Skip to content

Commit e7e5dfb

Browse files
committed
Implement rate limiter in plex module
1 parent 0ad0eec commit e7e5dfb

File tree

1 file changed

+21
-21
lines changed

1 file changed

+21
-21
lines changed

content/services/plex.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from ui.ui_print import *
66

77
name = 'Plex'
8-
session = requests.Session()
8+
session = custom_session(get_rate_limit=1.0, post_rate_limit=1.0) # 1 second between requests = 60 requests/minute
99
users = []
1010
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
1111
current_library = []
@@ -28,7 +28,7 @@ def logerror(response):
2828
else:
2929
ui_print("plex error: (401 unauthorized): token for user '"+name+"' does not seem to work. check your plex user settings.")
3030

31-
def get(url, timeout=60):
31+
def get(session: requests.Session, url: str, timeout=60):
3232
try:
3333
response = session.get(url, headers=headers, timeout=timeout)
3434
logerror(response)
@@ -38,7 +38,7 @@ def get(url, timeout=60):
3838
ui_print("plex error: (json exception): " + str(e), debug=ui_settings.debug)
3939
return None
4040

41-
def post(url, data):
41+
def post(session: requests.Session, url: str, data):
4242
try:
4343
response = session.post(url, data=data, headers=headers)
4444
logerror(response)
@@ -69,7 +69,7 @@ def __init__(self) -> None:
6969
while added < total:
7070
total = 0
7171
url = 'https://metadata.provider.plex.tv/library/sections/watchlist/all?X-Plex-Container-Size=200&X-Plex-Container-Start=' + str(added) + '&X-Plex-Token=' + user[1]
72-
response = get(url)
72+
response = get(session, url)
7373
if hasattr(response, 'MediaContainer'):
7474
total = response.MediaContainer.totalSize
7575
added += response.MediaContainer.size
@@ -134,7 +134,7 @@ def update(self):
134134
try:
135135
for user in users:
136136
url = 'https://metadata.provider.plex.tv/library/sections/watchlist/all?X-Plex-Token=' + user[1]
137-
response = get(url)
137+
response = get(session, url)
138138
if hasattr(response, 'MediaContainer'):
139139
if hasattr(response.MediaContainer, 'Metadata'):
140140
for entry in response.MediaContainer.Metadata:
@@ -180,7 +180,7 @@ def __init__(self, other):
180180
viewCount = 0
181181
while len(self.Episodes) < self.leafCount:
182182
url = 'https://metadata.provider.plex.tv/library/metadata/' + self.ratingKey + '/children?includeUserState=1&X-Plex-Container-Size=200&X-Plex-Container-Start=' + str(len(self.Episodes)) + '&X-Plex-Token=' + token
183-
response = get(url)
183+
response = get(session, url)
184184
if not response == None:
185185
if hasattr(response, 'MediaContainer'):
186186
self.duration = 0
@@ -226,13 +226,13 @@ def __init__(self, ratingKey):
226226
success = False
227227
while not success:
228228
url = 'https://metadata.provider.plex.tv/library/metadata/' + ratingKey + '?includeUserState=1&X-Plex-Token=' + token
229-
response = get(url)
229+
response = get(session, url)
230230
if not response == None:
231231
self.__dict__.update(response.MediaContainer.Metadata[0].__dict__)
232232
self.EID = setEID(self)
233233
self.Seasons = []
234234
url = 'https://metadata.provider.plex.tv/library/metadata/' + ratingKey + '/children?includeUserState=1&X-Plex-Container-Size=200&X-Plex-Container-Start=0&X-Plex-Token=' + token
235-
response = get(url)
235+
response = get(session, url)
236236
if not response == None:
237237
if hasattr(response, 'MediaContainer'):
238238
if hasattr(response.MediaContainer, 'Metadata'):
@@ -286,7 +286,7 @@ def __init__(self, ratingKey):
286286
elif ratingKey.startswith('plex://'):
287287
ratingKey = ratingKey.split('/')[-1]
288288
url = 'https://metadata.provider.plex.tv/library/metadata/' + ratingKey + '?includeUserState=1&X-Plex-Token=' + token
289-
response = get(url)
289+
response = get(session, url)
290290
self.__dict__.update(response.MediaContainer.Metadata[0].__dict__)
291291
self.EID = setEID(self)
292292
if not hasattr(self,"watchlistedAt"):
@@ -346,7 +346,7 @@ def setup(cls, new=False):
346346
working = False
347347
while not working:
348348
try:
349-
response = get(library.url + '/library/sections/?X-Plex-Token=' + users[0][1])
349+
response = get(session, library.url + '/library/sections/?X-Plex-Token=' + users[0][1])
350350
working = True
351351
if len(response.MediaContainer.Directory) == 0:
352352
print("It looks like this server does not have any libraries set-up! Please open the plex webui, setup at least one library and point it to your mounted debrid service drive.")
@@ -480,7 +480,7 @@ def call(paths):
480480
while refreshing:
481481
refreshing = False
482482
url = library.url + '/library/sections/?X-Plex-Token=' + users[0][1]
483-
response = get(url)
483+
response = get(session, url)
484484
for section_ in response.MediaContainer.Directory:
485485
if section_.refreshing:
486486
refreshing = True
@@ -501,7 +501,7 @@ def __new__(cls, element):
501501
names = []
502502
element_type = ("show" if element.type in ["show","season","episode"] else "movie")
503503
url = library.url + '/library/sections/?X-Plex-Token=' + users[0][1]
504-
response = get(url)
504+
response = get(session, url)
505505
paths = []
506506
for section_ in response.MediaContainer.Directory:
507507
if section_.key in library.refresh.sections and element_type == section_.type:
@@ -547,7 +547,7 @@ def setup(cls, new=False):
547547
working = False
548548
while not working:
549549
try:
550-
response = get(library.url + '/library/sections/?X-Plex-Token=' + users[0][1])
550+
response = get(session, library.url + '/library/sections/?X-Plex-Token=' + users[0][1])
551551
working = True
552552
if len(response.MediaContainer.Directory) == 0:
553553
print("It looks like this server does not have any libraries set-up! Please open the plex webui, setup at least one library and point it to your mounted debrid service drive.")
@@ -595,7 +595,7 @@ def call(element):
595595
url = library.url + '/library/sections/' + str(library_item.librarySectionID) + '/all?type=' + type_string + '&id=' + library_item.ratingKey + '&label.locked=1' + tags_string + '&X-Plex-Token=' + users[0][1]
596596
response = session.put(url,headers=headers)
597597
url = library.url + '/library/metadata/' + library_item.ratingKey + '?X-Plex-Token=' + users[0][1]
598-
response = get(url)
598+
response = get(session, url)
599599
library_item.__dict__.update(response.MediaContainer.Metadata[0].__dict__)
600600
except Exception as e:
601601
ui_print("[plex] error: couldnt add labels! Turn on debug printing for more info.")
@@ -729,7 +729,7 @@ def add(self):
729729
return
730730
ui_print('[plex] ignoring item: ' + self.query() + " for user: '" + ignoreuser + "'")
731731
url = 'https://metadata.provider.plex.tv/actions/scrobble?identifier=tv.plex.provider.metadata&key=' + self.ratingKey + '&X-Plex-Token=' + user[1]
732-
get(url)
732+
get(session, url)
733733
if not self in classes.ignore.ignored:
734734
classes.ignore.ignored += [self]
735735
except Exception as e:
@@ -748,7 +748,7 @@ def remove(self):
748748
return
749749
ui_print('[plex] un-ignoring item: ' + self.query() + " for user: '" + ignoreuser + "'")
750750
url = 'https://metadata.provider.plex.tv/actions/unscrobble?identifier=tv.plex.provider.metadata&key=' + self.ratingKey + '&X-Plex-Token=' + user[1]
751-
get(url)
751+
get(session, url)
752752
if self in classes.ignore.ignored:
753753
classes.ignore.ignored.remove(self)
754754
except Exception as e:
@@ -785,7 +785,7 @@ def __new__(self,silent=False):
785785
if library.check == [['']]:
786786
library.check = []
787787
try:
788-
response = get(library.url + '/library/sections/?X-Plex-Token=' + users[0][1])
788+
response = get(session, library.url + '/library/sections/?X-Plex-Token=' + users[0][1])
789789
for Directory in response.MediaContainer.Directory:
790790
if ([Directory.key] in library.check or library.check == []) and Directory.type in ["movie","show"]:
791791
types = ['1'] if Directory.type == "movie" else ['2', '3', '4']
@@ -804,7 +804,7 @@ def __new__(self,silent=False):
804804
section_title = ''
805805
for type in types:
806806
url = library.url + '/library/sections/' + section + '/all?type=' + type + '&X-Plex-Token=' + users[0][1]
807-
response = get(url)
807+
response = get(session, url)
808808
if hasattr(response, 'MediaContainer'):
809809
if hasattr(response.MediaContainer, 'Metadata'):
810810
for element in response.MediaContainer.Metadata:
@@ -860,7 +860,7 @@ def __new__(self,silent=False):
860860
if not item in current_library:
861861
updated = True
862862
url = library.url + '/library/metadata/' + item.ratingKey + '?X-Plex-Token=' + users[0][1]
863-
response = get(url)
863+
response = get(session, url)
864864
item.__dict__.update(response.MediaContainer.Metadata[0].__dict__)
865865
else:
866866
match = next((x for x in current_library if item == x), None)
@@ -888,7 +888,7 @@ def __new__(self,silent=False):
888888
def search(query, library=[]):
889889
query = query.replace(' ', '%20')
890890
url = 'https://metadata.provider.plex.tv/library/search?query=' + query + '&limit=20&searchTypes=movies%2Ctv&includeMetadata=1&X-Plex-Token=' + users[0][1]
891-
response = get(url)
891+
response = get(session, url)
892892
try:
893893
return response.MediaContainer.SearchResult
894894
except:
@@ -934,7 +934,7 @@ def match(self):
934934
service,query = EID.split('://')
935935
query = '-'.join([service,query])
936936
url = current_module.library.url + '/library/metadata/' + some_local_media.ratingKey + '/matches?manual=1&title=' + query + '&agent=' + agent + '&language=en-US&X-Plex-Token=' + users[0][1]
937-
response = get(url)
937+
response = get(session, url)
938938
try:
939939
match = response.MediaContainer.SearchResult[0]
940940
if match.type == 'show':

0 commit comments

Comments
 (0)