-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCurrentStreams.ps1
285 lines (262 loc) · 9.49 KB
/
CurrentStreams.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
Clear-Host
# Enter the path to the config file for Tautulli and Discord
[string]$strPathToConfig = "$PSScriptRoot\config.json"
# Log file path
[string]$strStreamLogPath = "$PSScriptRoot\StreamLog.txt"
# Script name MUST match what is in config.json under "ScriptSettings"
[string]$strScriptName = 'CurrentStreams'
<############################################################
Do NOT edit lines below unless you know what you are doing!
############################################################>
# Define the functions to be used
function Get-TMDBInfo {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$strAPIKey,
[Parameter(Mandatory)]
[ValidateSet('tv', 'movie')]
[string]$strMediaType,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$strTMDB_ID
)
[object]$objResults = Invoke-RestMethod -Method Get -Uri "https://api.themoviedb.org/3/$($strMediaType)/$($strTMDB_ID)?api_key=$($strAPIKey)&language=en-US"
return $objResults
}
function Get-SanitizedString {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$strInputString
)
# Credit to FS.Corrupt for the initial version of this function. https://github.com/FSCorrupt
[regex]$regAppendedYear = ' \(([0-9]{4})\)' # This will match any titles with the year appended. I ran into issues with 'Yellowstone (2018)'
[hashtable]$htbReplaceValues = @{
'ß' = 'ss'
'à' = 'a'
'á' = 'a'
'â' = 'a'
'ã' = 'a'
'ä' = 'a'
'å' = 'a'
'æ' = 'ae'
'ç' = 'c'
'è' = 'e'
'é' = 'e'
'ê' = 'e'
'ë' = 'e'
'ì' = 'i'
'í' = 'i'
'î' = 'i'
'ï' = 'i'
'ð' = 'd'
'ñ' = 'n'
'ò' = 'o'
'ó' = 'o'
'ô' = 'o'
'õ' = 'o'
'ö' = 'o'
'ø' = 'o'
'ù' = 'u'
'ú' = 'u'
'û' = 'u'
'ü' = 'u'
'ý' = 'y'
'þ' = 'p'
'ÿ' = 'y'
'“' = '"'
'”' = '"'
'·' = '-'
':' = ''
$regAppendedYear = ''
}
foreach($key in $htbReplaceValues.Keys){
$strInputString = $strInputString -Replace($key, $htbReplaceValues.$key)
}
return $strInputString
}
function Push-ObjectToDiscord {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$strDiscordWebhook,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object]$objPayload
)
try {
$null = Invoke-RestMethod -Method Post -Uri $strDiscordWebhook -Body $objPayload -ContentType 'Application/Json'
Start-Sleep -Seconds 1
}
catch {
Write-Host "Unable to send to Discord. $($_)" -ForegroundColor Red
Write-Host $objPayload
}
}
# Parse the config file and assign variables
[object]$objConfig = Get-Content -Path $strPathToConfig -Raw | ConvertFrom-Json
[string]$strDiscordWebhook = $objConfig.ScriptSettings.$strScriptName.Webhook
[string]$strTautulliURL = $objConfig.Tautulli.URL
[string]$strTautulliAPIKey = $objConfig.Tautulli.APIKey
[string]$strTMDB_APIKey = $objConfig.TMDB.APIKey
# Get PMS Identifier
[object]$objPlexServerIdentifier = Invoke-RestMethod -Method Get -Uri "$strTautulliURL/api/v2?apikey=$strTautulliAPIKey&cmd=get_server_info"
[string]$strPlexServerIdentifier = ($objPlexServerIdentifier.response.data | Select-Object -ExpandProperty pms_identifier)
# Attempt to get Plex activity from Tautulli
try {
[object]$objCurrentActivity = Invoke-RestMethod -Method Get -Uri "$strTautulliURL/api/v2?apikey=$strTautulliAPIKey&cmd=get_activity"
[array]$arrCurrentStreams = $objCurrentActivity.response.data.sessions
}
catch {
[object]$objPayload = @{
username = "Current Streams"
content = "**Could not get current streams from Tautulli.**`nError message:`n$($_)"
} | ConvertTo-Json -Depth 4
Push-ObjectToDiscord -strDiscordWebhook $strDiscordWebhook -objPayload $objPayload
exit
}
# Loop through each stream
[System.Collections.ArrayList]$arrCurrentStreamsEmbed = @()
foreach ($stream in $arrCurrentStreams) {
[string]$strSanitizedTitle = Get-SanitizedString -strInputString $stream.title
# TV
if ($stream.media_type -eq 'episode') {
[string]$strTMDB_ID = ($stream.guids | Where-Object {$_ -match 'tmdb'}).Split('/')[2]
[object]$objTMDBResults = Get-TMDBInfo -strAPIKey $strTMDB_APIKey -strMediaType 'tv' -strTMDB_ID $strTMDB_ID
[hashtable]$htbEmbedParameters = @{
color = '40635'
title = $strSanitizedTitle
url = "https://www.themoviedb.org/tv/$strTMDB_ID"
author = @{
name = 'Open on Plex'
url = "https://app.plex.tv/desktop/#!/server/$strPlexServerIdentifier/details?key=%2Flibrary%2Fmetadata%2F$($stream.grandparent_rating_key)"
icon_url = 'https://i.imgur.com/FNoiYXP.png'
}
description = Get-SanitizedString -strInputString $stream.summary
thumbnail = @{url = "https://image.tmdb.org/t/p/w500$($objTMDBResults.poster_path)"}
fields = @{
name = 'User'
value = $stream.friendly_name
inline = $false
},@{
name = 'Season'
value = $stream.parent_media_index
inline = $true
},@{
name = 'Episode'
value = $stream.media_index
inline = $true
}
footer = @{
text = "$($stream.state) - $($stream.progress_percent)%"
}
timestamp = ((Get-Date).AddHours(5)).ToString("yyyy-MM-ddTHH:mm:ss.Mss")
}
}
# MUSIC
elseif($stream.media_type -eq 'track') {
[hashtable]$htbEmbedParameters = @{
color = '3066993'
title = $strSanitizedTitle
author = @{
name = 'Open on Plex'
url = "https://app.plex.tv/desktop/#!/server/$strPlexServerIdentifier/details?key=%2Flibrary%2Fmetadata%2F$($stream.rating_key)"
icon_url = 'https://i.imgur.com/FNoiYXP.png'
}
description = Get-SanitizedString -strInputString $stream.summary
fields = @{
name = 'User'
value = $stream.friendly_name
inline = $false
},@{
name = 'Album'
value = $stream.parent_title
inline = $true
},@{
name = 'Track'
value = $stream.media_index
inline = $true
}
footer = @{
text = "$($stream.state) - $($stream.progress_percent)%"
}
timestamp = ((Get-Date).AddHours(5)).ToString("yyyy-MM-ddTHH:mm:ss.Mss")
}
}
# MOVIE
else {
[string]$strTMDB_ID = ($stream.guids[1]).Split('/')[2]
[object]$objTMDBResults = Get-TMDBInfo -strAPIKey $strTMDB_APIKey -strMediaType movie -strTMDB_ID $strTMDB_ID
[hashtable]$htbEmbedParameters = @{
color = '13400320'
title = $strSanitizedTitle
url = "https://www.themoviedb.org/movie/$strTMDB_ID"
author = @{
name = "Open on Plex"
url = "https://app.plex.tv/desktop/#!/server/$strPlexServerIdentifier/details?key=%2Flibrary%2Fmetadata%2F$($stream.rating_key)"
icon_url = 'https://i.imgur.com/FNoiYXP.png'
}
description = Get-SanitizedString -strInputString $stream.summary
thumbnail = @{url = "https://image.tmdb.org/t/p/w500$($objTMDBResults.poster_path)"}
fields = @{
name = 'User'
value = $stream.friendly_name
inline = $false
},@{
name = 'Resolution'
value = $stream.stream_video_full_resolution
inline = $true
},@{
name = 'Direct Play/Transcode'
value = $stream.transcode_decision
inline = $true
}
footer = @{
text = "$($stream.state) - $($stream.progress_percent)%"
}
timestamp = ((Get-Date).AddHours(5)).ToString("yyyy-MM-ddTHH:mm:ss.Mss")
}
}
# Add line results to final object
$null = $arrCurrentStreamsEmbed.Add($htbEmbedParameters)
}
[object]$objPayload = @{
username = "Current Streams"
content = "**Current Streams on Plex:**"
embeds = $arrCurrentStreamsEmbed
} | ConvertTo-Json -Depth 4
if (!(Test-Path $strStreamLogPath)) { # Log file doesn't exist. Create it and update Discord
# Create the log file
$arrCurrentStreams.Count | Out-File -FilePath $strStreamLogPath -Force
# Send to Discord
Push-ObjectToDiscord -strDiscordWebhook $strDiscordWebhook -objPayload $objPayload
}
else { # Log file exists.
[int]$lastStreamCount = Get-Content $strStreamLogPath | Out-String
if ($lastStreamCount -eq 0 -and $arrCurrentStreams.Count -eq 0) { # Log file and current stream count are both 0. Do not update.
Write-Host 'Nothing to update.'
}
else {
# Update the log file
$arrCurrentStreams.Count | Out-File -FilePath $strStreamLogPath -Force
if ($arrCurrentStreamsEmbed.Count -gt 0) {
Push-ObjectToDiscord -strDiscordWebhook $strDiscordWebhook -objPayload $objPayload
}
else {
[object]$objNoStreamsPayload = @{
embeds = @(
@{
color = '15158332'
title = "Nothing is currently streaming"
timestamp = ((Get-Date).AddHours(5)).ToString("yyyy-MM-ddTHH:mm:ss.Mss")
}
)
} | ConvertTo-Json -Depth 4
Push-ObjectToDiscord -strDiscordWebhook $strDiscordWebhook -objPayload $objNoStreamsPayload
}
}
}