-
Notifications
You must be signed in to change notification settings - Fork 26
/
watchlist.py
243 lines (174 loc) · 9.02 KB
/
watchlist.py
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
import traceback
import requests
import json
import datetime
from typing import List
from shared.discord import discordError, discordUpdate
from shared.shared import plex, plexHeaders, tokensFilename
from shared.overseerr import requestItem, getUserForPlexToken
import xml.etree.ElementTree as ET
host = plex['host']
metadataHost = plex['metadataHost']
serverHost = plex['serverHost']
serverMachineId = plex['serverMachineId']
class SeasonMetadata:
def __init__(self, json) -> None:
self.viewedLeafCount = json['viewedLeafCount']
self.leafCount = json['leafCount']
self.index = json['index']
def getSeasonsMetadata(ratingKey, headers) -> List[SeasonMetadata]:
# excludeAllLeaves=1?
seasonsMetadataRequest = requests.get(f"{metadataHost}library/metadata/{ratingKey}/children?excludeAllLeaves=1&includeUserState=1", headers=headers)
seasonsMetadata = seasonsMetadataRequest.json()['MediaContainer']['Metadata']
return list(map(SeasonMetadata, seasonsMetadata))
def getServerSeasonsMetadata(ratingKey, headers, owner) -> List[SeasonMetadata]:
headers = getServerHeaders(headers, owner)
serverMetadataInfoRequest = requests.get(f"{serverHost}/library/all?type=2&guid=plex%3A%2F%2Fshow%2F{ratingKey}", headers=headers)
serverMetadataInfo = serverMetadataInfoRequest.json()['MediaContainer']
if 'Metadata' in serverMetadataInfo:
serverMetadata = serverMetadataInfo['Metadata']
showServerMetadata = next(iter(serverMetadata), None)
if showServerMetadata:
serverRatingKey = showServerMetadata['ratingKey']
serverSeasonsMetadataRequest = requests.get(f"{serverHost}/library/metadata/{serverRatingKey}/children", headers=headers)
serverSeasonsMetadata = serverSeasonsMetadataRequest.json()['MediaContainer']['Metadata']
return list(map(SeasonMetadata, serverSeasonsMetadata))
return
def getCombinedSeasonsMetadata(ratingKey, headers, owner) -> List[SeasonMetadata]:
seasonsMetadata = getSeasonsMetadata(ratingKey, headers)
serverSeasonsMetadata = getServerSeasonsMetadata(ratingKey, headers, owner)
if not serverSeasonsMetadata: return seasonsMetadata
combinedSeasonsMetadata = []
for seasonMetadata in seasonsMetadata:
serverSeasonMetadata = next(iter(serverSeasonMetadata for serverSeasonMetadata in serverSeasonsMetadata if serverSeasonMetadata.index == seasonMetadata.index), None)
combinedSeasonMetadata = combineSeasonMetadata(seasonMetadata, serverSeasonMetadata)
combinedSeasonsMetadata.append(combinedSeasonMetadata)
return combinedSeasonsMetadata
def combineSeasonMetadata(seasonMetadata: SeasonMetadata, serverSeasonMetadata: SeasonMetadata) -> SeasonMetadata:
if serverSeasonMetadata and serverSeasonMetadata.viewedLeafCount > seasonMetadata.viewedLeafCount:
seasonMetadata.viewedLeafCount = serverSeasonMetadata.viewedLeafCount
return seasonMetadata
def getServerHeaders(headers, owner):
if owner: return headers
usersRequest = requests.get(f"{host}api/users", headers=headers)
users = ET.fromstring(usersRequest.content)
servers = (server.attrib for user in users for server in user)
serverId = next(server['id'] for server in servers if server['machineIdentifier'] == serverMachineId)
serverRequest = requests.get(f"{host}api/servers/{serverMachineId}/shared_servers/{serverId}", headers=headers)
serverToken = ET.fromstring(serverRequest.content)[0].attrib['accessToken']
return {
**headers,
'X-Plex-Token': serverToken
}
def buildRecentItem(item):
return f"{item['ratingKey']}:{item['watchlistedAt']}"
def getCurrentSeason(ratingKey, headers, token):
season = [1]
seasonsMetadata = getCombinedSeasonsMetadata(ratingKey, headers, token.get('owner', False))
# Consider logic for choosing the season
for seasonMetadata in reversed(seasonsMetadata):
totalCount = seasonMetadata.leafCount
remainingCount = totalCount - seasonMetadata.viewedLeafCount
if remainingCount <= 0 and totalCount != 0 and seasonMetadata != seasonsMetadata[-1]:
season = [seasonMetadata.index + 1]
break
elif remainingCount < totalCount:
season = [seasonMetadata.index]
break
return season
def getWatchlistedAt(ratingKey, headers):
request = requests.get(f"{metadataHost}library/metadata/{ratingKey}/userState", headers=headers)
if request.status_code != 200: return
watchlistedAt = request.json()['MediaContainer']['UserState']['watchlistedAt']
return watchlistedAt
def run():
print()
print(datetime.datetime.now())
print('Running Watchlist')
with open(tokensFilename, 'r') as tokensFile:
tokens = json.load(tokensFile)
for userId, token in tokens.items():
try:
headers = {
**plexHeaders,
'X-Plex-Token': token['token']
}
def requestWatchlist(tryAgain=True):
try:
return requests.get(
f"{metadataHost}library/sections/watchlist/all?includeFields=ratingKey%2CwatchlistedAt&sort=watchlistedAt%3Adesc",
headers={
**headers,
'If-None-Match': token['etag'],
})
except:
if tryAgain:
return requestWatchlist(tryAgain=False)
else:
raise
watchlistRequest = requestWatchlist()
if watchlistRequest.status_code == 401:
print(f"UserId {userId} no longer authenticated")
discordError(f"UserId {userId} no longer authenticated")
continue
if watchlistRequest.status_code == 304:
print(f"No changes for userId {userId}")
continue
if watchlistRequest.status_code != 200:
print(watchlistRequest)
print(watchlistRequest.url)
continue
etag = watchlistRequest.headers['etag']
now = datetime.datetime.now()
recentlyProcessedItems = token.get('recentlyProcessedItems', [])
watchlist = watchlistRequest.json()['MediaContainer']
if not 'Metadata' in watchlist:
continue
watchlistItems = watchlist['Metadata']
recentWatchlist = []
newRecentlyProcessedItems = []
for item in watchlistItems:
try:
watchlistedAt = datetime.datetime.fromtimestamp(item['watchlistedAt'])
discordUpdate('Watchlist has resumed functioning')
except:
ratingKey = item['ratingKey']
watchlistedAtTimestamp = getWatchlistedAt(ratingKey, headers)
if not watchlistedAtTimestamp:
print(f"No watchlisted timestamp for RatingKey {ratingKey} and UserId {userId}")
discordError(f"No watchlisted timestamp for RatingKey {ratingKey} and UserId {userId}")
continue
watchlistedAt = datetime.datetime.fromtimestamp(watchlistedAtTimestamp)
item['watchlistedAt'] = watchlistedAtTimestamp
if now - watchlistedAt < datetime.timedelta(hours=1):
recentItem = buildRecentItem(item)
newRecentlyProcessedItems.append(recentItem)
if not recentItem in recentlyProcessedItems:
recentWatchlist.append(item)
else:
break
with open(tokensFilename, 'r+') as tokensFile:
tokens = json.load(tokensFile)
token = tokens[userId]
token['etag'] = etag
token['recentlyProcessedItems'] = newRecentlyProcessedItems
tokensFile.seek(0)
json.dump(tokens, tokensFile)
tokensFile.truncate()
user = getUserForPlexToken(token['token'])
userId = user['id']
username = user['displayName']
print(f"Requesting new items for userId {userId} - {username}")
if not recentWatchlist:
print("No new items were found")
for item in recentWatchlist:
ratingKey = item['ratingKey']
watchlistedAt = item['watchlistedAt']
requestItem(user, ratingKey, watchlistedAt, headers, getSeason=lambda: getCurrentSeason(ratingKey, headers, token))
except:
e = traceback.format_exc()
print(f"Error processing requests for userId {userId}")
print(e)
discordError(f"Error processing requests for userId {userId}", e)
if __name__ == "__main__":
run()