1515from getpass import getpass
1616from threading import Event , Thread
1717from urllib .parse import quote
18+ from requests .status_codes import _codes as codes
1819
1920import requests
20- from plexapi .exceptions import BadRequest , NotFound
21+ from plexapi .exceptions import BadRequest , NotFound , Unauthorized
2122
2223try :
2324 from tqdm import tqdm
@@ -391,12 +392,12 @@ def downloadSessionImages(server, filename=None, height=150, width=150,
391392 prettyname = media ._prettyfilename ()
392393 filename = f'session_transcode_{ media .usernames [0 ]} _{ prettyname } _{ int (time .time ())} '
393394 url = server .transcodeImage (url , height , width , opacity , saturation )
394- filepath = download (url , filename = filename )
395+ filepath = download (url , server . _token , filename = filename )
395396 info ['username' ] = {'filepath' : filepath , 'url' : url }
396397 return info
397398
398399
399- def download (url , token , filename = None , savepath = None , session = None , chunksize = 4024 ,
400+ def download (url , token , filename = None , savepath = None , session = None , chunksize = 4024 , # noqa: C901
400401 unpack = False , mocked = False , showstatus = False ):
401402 """ Helper to download a thumb, videofile or other media item. Returns the local
402403 path to the downloaded file.
@@ -419,6 +420,17 @@ def download(url, token, filename=None, savepath=None, session=None, chunksize=4
419420 session = session or requests .Session ()
420421 headers = {'X-Plex-Token' : token }
421422 response = session .get (url , headers = headers , stream = True )
423+ if response .status_code not in (200 , 201 , 204 ):
424+ codename = codes .get (response .status_code )[0 ]
425+ errtext = response .text .replace ('\n ' , ' ' )
426+ message = f'({ response .status_code } ) { codename } ; { response .url } { errtext } '
427+ if response .status_code == 401 :
428+ raise Unauthorized (message )
429+ elif response .status_code == 404 :
430+ raise NotFound (message )
431+ else :
432+ raise BadRequest (message )
433+
422434 # make sure the savepath directory exists
423435 savepath = savepath or os .getcwd ()
424436 os .makedirs (savepath , exist_ok = True )
0 commit comments