def test_utils_download(plex, episode): url = episode.getStreamURL() locations = episode.locations[0] session = episode._server._session assert utils.download(url, plex._token, filename=locations, mocked=True) assert utils.download(url, plex._token, filename=locations, session=session, mocked=True) assert utils.download(episode.thumbUrl, plex._token, filename=episode.title, mocked=True)
def test_server_transcodeImage(tmpdir, plex, show): width, height = 500, 500 imgurl = plex.transcodeImage(show.banner, height, width) gray = imgurl = plex.transcodeImage(show.banner, height, width, saturation=0) resized_img = download(imgurl, plex._token, savepath=str(tmpdir), filename="resize_image") original_img = download( show._server.url(show.banner), plex._token, savepath=str(tmpdir), filename="original_img", ) grayscale_img = download(gray, plex._token, savepath=str(tmpdir), filename="grayscale_img") with Image.open(resized_img) as image: assert width, height == image.size with Image.open(original_img) as image: assert width, height != image.size assert _detect_color_image(grayscale_img, thumb_size=150) == "grayscale"
def test_server_transcodeImage(tmpdir, plex, movie): width, height = 500, 500 original_url = plex.url(movie.thumb) resize_url = plex.transcodeImage(movie.thumb, height, width) grayscale_url = plex.transcodeImage(movie.thumb, height, width, saturation=0) original_img = download( original_url, plex._token, savepath=str(tmpdir), filename="original_img", ) resized_img = download(resize_url, plex._token, savepath=str(tmpdir), filename="resize_image") grayscale_img = download(grayscale_url, plex._token, savepath=str(tmpdir), filename="grayscale_img") with Image.open(resized_img) as image: assert width, height == image.size with Image.open(original_img) as image: assert width, height != image.size assert _detect_color_image(grayscale_img, thumb_size=150) == "grayscale"
def __download_item(self, item, converted=False): path_dir = self._data_dir + '/' + self._server.machineIdentifier filename = 'item_' + str(item.ratingKey) filename_tmp = filename + '.tmp' path = path_dir + '/' + filename path_tmp = path_dir + '/' + filename_tmp self.emit('item-downloading', item, True) if not os.path.exists(path_dir): os.makedirs(path_dir) if not os.path.exists(path): if os.path.exists(path_tmp): os.remove(path_tmp) locations = [i for i in item.iterParts() if i] if (converted == False): download_url = self._server.url('%s?download=1' % locations[0].key) else: download_url = item.getStreamURL() utils.download(download_url, self._server._token, filename=filename_tmp, savepath=path_dir, session=self._server._session) os.rename(path_tmp, path) self.emit('item-downloading', item, False)
def test_utils_download(a_episode): # this files is really getting downloaded.. without_session = utils.download(a_episode.getStreamURL(), filename=a_episode.location, mocked=True) assert without_session with_session = utils.download(a_episode.getStreamURL(), filename=a_episode.location, session=a_episode.server.session, mocked=True) assert with_session img = utils.download(a_episode.thumbUrl, filename=a_episode.title, mocked=True) assert img
def test_server_transcodeImage(tmpdir, plex, show): width, height = 500, 500 imgurl = plex.transcodeImage(show.banner, height, width) gray = imgurl = plex.transcodeImage(show.banner, height, width, saturation=0) resized_img = download(imgurl, plex._token, savepath=str(tmpdir), filename='resize_image') original_img = download(show._server.url(show.banner), plex._token, savepath=str(tmpdir), filename='original_img') grayscale_img = download(gray, plex._token, savepath=str(tmpdir), filename='grayscale_img') with Image.open(resized_img) as image: assert width, height == image.size with Image.open(original_img) as image: assert width, height != image.size assert _detect_color_image(grayscale_img, thumb_size=150) == 'grayscale'
def test_utils_download(a_episode): without_session = utils.download(a_episode.getStreamURL(), filename=a_episode.locations[0], mocked=True) assert without_session with_session = utils.download(a_episode.getStreamURL(), filename=a_episode.locations[0], session=a_episode._server._session, mocked=True) assert with_session img = utils.download(a_episode.thumbUrl, filename=a_episode.title, mocked=True) assert img
def download(self, savepath=None, keep_original_name=False, **kwargs): """ Download video files to specified directory. Parameters: savepath (str): Defaults to current working dir. keep_original_name (bool): True to keep the original file name otherwise a friendlier is generated. **kwargs: Additional options passed into :func:`~plexapi.base.PlexObject.getStreamURL`. """ filepaths = [] locations = [i for i in self.iterParts() if i] for location in locations: name = location.file if not keep_original_name: title = self.title.replace(' ', '.') name = '%s.%s' % (title, location.container) if kwargs is not None: url = self.getStreamURL(**kwargs) else: self._server.url('%s?download=1' % location.key) filepath = utils.download(url, self._server._token, filename=name, savepath=savepath, session=self._server._session) if filepath: filepaths.append(filepath) return filepaths
def download(self, savepath=None, keep_original_name=False, **kwargs): """ Downloads this items media to the specified location. Returns a list of filepaths that have been saved to disk. Parameters: savepath (str): Title of the track to return. keep_original_name (bool): Set True to keep the original filename as stored in the Plex server. False will create a new filename with the format "<Artist> - <Album> <Track>". kwargs (dict): If specified, a :func:`~plexapi.audio.Track.getStreamURL()` will be returned and the additional arguments passed in will be sent to that function. If kwargs is not specified, the media items will be downloaded and saved to disk. """ filepaths = [] locations = [i for i in self.iterParts() if i] for location in locations: filename = location.file if keep_original_name is False: filename = '%s.%s' % (self._prettyfilename(), location.container) # So this seems to be a alot slower but allows transcode. if kwargs: download_url = self.getStreamURL(**kwargs) else: download_url = self._server.url('%s?download=1' % location.key) filepath = utils.download(download_url, self._server._token, filename=filename, savepath=savepath, session=self._server._session) if filepath: filepaths.append(filepath) return filepaths
def download(self, savepath=None, keep_orginal_name=False, **kwargs): """ Downloads this items media to the specified location. Returns a list of filepaths that have been saved to disk. Parameters: savepath (str): Title of the track to return. keep_orginal_name (bool): Set True to keep the original filename as stored in the Plex server. False will create a new filename with the format "<Artist> - <Album> <Track>". kwargs (dict): If specified, a :func:`~plexapi.audio.Track.getStreamURL()` will be returned and the additional arguments passed in will be sent to that function. If kwargs is not specified, the media items will be downloaded and saved to disk. """ filepaths = [] locations = [i for i in self.iterParts() if i] for location in locations: filename = location.file if keep_orginal_name is False: filename = '%s.%s' % (self._prettyfilename(), location.container) # So this seems to be a alot slower but allows transcode. if kwargs: download_url = self.getStreamURL(**kwargs) else: download_url = self._server.url('%s?download=1' % location.key) filepath = utils.download(download_url, self._server._token, filename=filename, savepath=savepath, session=self._server._session) if filepath: filepaths.append(filepath) return filepaths
def download_theme(media, force=False): """Download a theme using PMS. And add it to shows cache. force (bool): Download even if the theme exists. Return: The filepath of the theme. """ if media.TYPE == 'show': name = media.title rk = media.ratingKey theme = media.theme else: name = media.grandparentTitle rk = media.grandparentRatingKey theme = media.grandparentTheme if theme is None: theme = media.show().theme name = '%s__%s' % (name.replace('*', ''), rk) f_name = '%s.mp3' % name f_path = os.path.join(THEMES, f_name) if not os.path.exists(f_path) or force and theme: LOG.debug('Downloading %s', f_path) dlt = download(PMS.url(theme), savepath=THEMES, filename=f_name) if dlt: SHOWS[rk] = f_path return f_path else: LOG.debug('Skipping %s as it already exists', f_name) return f_path
def download(self, savepath=None, keep_orginal_name=False, **kwargs): """ Download video files to specified directory. Parameters: savepath (str): Defaults to current working dir. keep_orginal_name (bool): True to keep the original file name otherwise a friendlier is generated. **kwargs: Additional options passed into :func:`~plexapi.base.PlexObject.getStreamURL()`. """ filepaths = [] locations = [i for i in self.iterParts() if i] for location in locations: name = location.file if not keep_orginal_name: title = self.title.replace(' ', '.') name = '%s.%s' % (title, location.container) if kwargs is not None: url = self.getStreamURL(**kwargs) else: self._server.url('%s?download=1' % location.key) filepath = utils.download(url, self._server._token, filename=name, savepath=savepath, session=self._server._session) if filepath: filepaths.append(filepath) return filepaths
def download(self, savepath=None, keep_original_name=False, showstatus=False): """ Download photo files to specified directory. Parameters: savepath (str): Defaults to current working dir. keep_original_name (bool): True to keep the original file name otherwise a friendlier is generated. showstatus(bool): Display a progressbar. """ filepaths = [] locations = [i for i in self.iterParts() if i] for location in locations: name = location.file if not keep_original_name: title = self.title.replace(' ', '.') name = '%s.%s' % (title, location.container) url = self._server.url('%s?download=1' % location.key) filepath = utils.download(url, self._server._token, filename=name, showstatus=showstatus, savepath=savepath, session=self._server._session) if filepath: filepaths.append(filepath) return filepaths
def downloadLogs(self, savepath=None, unpack=False): url = self.url('/diagnostics/logs') filepath = utils.download(url, None, savepath, self._session, unpack=unpack) return filepath
def downloadLogs(self, savepath=None, unpack=False): """ Download server logs. Parameters: savepath (str): Defaults to current working dir. unpack (bool): Unpack the zip file. """ url = self.url('/diagnostics/logs') filepath = utils.download(url, self._token, None, savepath, self._session, unpack=unpack) return filepath
def test_server_transcodeImage(tmpdir, pms, a_show): # Ideally we should also test the black white but this has to do for now. from PIL import Image width, height = 500, 500 img_url_resize = pms.transcodeImage(a_show.banner, height, width) gray = img_url_resize = pms.transcodeImage(a_show.banner, height, width, saturation=0) resized_image = download(img_url_resize, savepath=str(tmpdir), filename='resize_image') org_image = download(a_show.server.url(a_show.banner), savepath=str(tmpdir), filename='org_image') gray_image = download(gray, savepath=str(tmpdir), filename='gray_image') with Image.open(resized_image) as im: assert width, height == im.size with Image.open(org_image) as im: assert width, height != im.size assert _detect_color_image(gray_image, thumb_size=150) == 'grayscale'
def download_media(media): savepath = get_file_save_path(media) os.makedirs(savepath, mode=0o777, exist_ok=True) logger.info("Downloading {} to {}".format(get_media_title(media), savepath)) # modified from plexapi.base.playable location = [i for i in media.iterParts() if i and i.optimizedForStreaming][0] filename = '%s.%s' % (media._prettyfilename(), location.container) download_url = media._server.url('%s?download=1' % location.key) return plexutils.download(download_url, media._server._token, filename=filename, savepath=savepath, session=media._server._session)
def __init__(self, surface, client, x, y): if client.parentThumb: # Album thumb = client.parentThumb elif client.grandparentThumb: # Artist thumb = client.grandparentThumb else: self.thumbImg = None return w = screen_h - y url = plex.transcodeImage(thumb, height=w, width=w) filePath = download(url, token, filename='thumb.jpg') picture = pygame.image.load(filePath) self.thumbImg = pygame.transform.scale(picture, (w, w)) self.surface = surface self.pos = (x, y)
def download(self, savepath=None, keep_original_name=False, **kwargs): """ Downloads the media item to the specified location. Returns a list of filepaths that have been saved to disk. Parameters: savepath (str): Defaults to current working dir. keep_original_name (bool): True to keep the original filename otherwise a friendlier filename is generated. See filenames below. **kwargs (dict): Additional options passed into :func:`~plexapi.audio.Track.getStreamURL` to download a transcoded stream, otherwise the media item will be downloaded as-is and saved to disk. **Filenames** * Movie: ``<title> (<year>)`` * Episode: ``<show title> - s00e00 - <episode title>`` * Track: ``<artist title> - <album title> - 00 - <track title>`` * Photo: ``<photoalbum title> - <photo/clip title>`` or ``<photo/clip title>`` """ filepaths = [] parts = [i for i in self.iterParts() if i] for part in parts: if not keep_original_name: filename = utils.cleanFilename( '%s.%s' % (self._prettyfilename(), part.container)) else: filename = part.file if kwargs: # So this seems to be a a lot slower but allows transcode. download_url = self.getStreamURL(**kwargs) else: download_url = self._server.url('%s?download=1' % part.key) filepath = utils.download(download_url, self._server._token, filename=filename, savepath=savepath, session=self._server._session) if filepath: filepaths.append(filepath) return filepaths
def download(self, savepath=None, keep_orginal_name=False, **kwargs): downloaded = [] locs = [i for i in self.iterParts() if i] for loc in locs: if keep_orginal_name is False: name = '%s.%s' % (self.title.replace(' ', '.'), loc.container) else: name = loc.file # So this seems to be a alot slower but allows transcode. if kwargs: download_url = self.getStreamURL(**kwargs) else: download_url = self.server.url('%s?download=1' % loc.key) dl = utils.download(download_url, filename=name, savepath=savepath, session=self.server.session) if dl: downloaded.append(dl) return downloaded
def test_server_transcodeImage(tmpdir, plex, movie): width, height = 500, 100 background = "000000" original_url = movie.thumbUrl resize_jpeg_url = plex.transcodeImage(original_url, height, width) no_minSize_png_url = plex.transcodeImage(original_url, height, width, minSize=False, imageFormat="png") grayscale_url = plex.transcodeImage(original_url, height, width, saturation=0) opacity_background_url = plex.transcodeImage(original_url, height, width, opacity=0, background=background, blur=100) online_no_upscale_url = plex.transcodeImage( "https://raw.githubusercontent.com/pkkid/python-plexapi/master/tests/data/cute_cat.jpg", 1000, 1000, upscale=False) original_img = download( original_url, plex._token, savepath=str(tmpdir), filename="original_img", ) resized_jpeg_img = download( resize_jpeg_url, plex._token, savepath=str(tmpdir), filename="resized_jpeg_img" ) no_minSize_png_img = download( no_minSize_png_url, plex._token, savepath=str(tmpdir), filename="no_minSize_png_img" ) grayscale_img = download( grayscale_url, plex._token, savepath=str(tmpdir), filename="grayscale_img" ) opacity_background_img = download( opacity_background_url, plex._token, savepath=str(tmpdir), filename="opacity_background_img" ) online_no_upscale_img = download( online_no_upscale_url, plex._token, savepath=str(tmpdir), filename="online_no_upscale_img" ) with Image.open(original_img) as image: assert image.size[0] != width assert image.size[1] != height with Image.open(resized_jpeg_img) as image: assert image.size[0] == width assert image.size[1] != height assert image.format == "JPEG" with Image.open(no_minSize_png_img) as image: assert image.size[0] != width assert image.size[1] == height assert image.format == "PNG" assert _detect_color_image(grayscale_img, thumb_size=150) == "grayscale" assert _detect_dominant_hexcolor(opacity_background_img) == background with Image.open(online_no_upscale_img) as image1: with Image.open(utils.STUB_IMAGE_PATH) as image2: assert image1.size == image2.size
def download_theme_plex(media, force=False): """Download a theme using PMS. And add it to shows cache. force (bool): Download even if the theme exists. Return: The filepath of the theme. """ if media.TYPE == 'show': name = media.title rk = media.ratingKey theme = media.theme else: name = media.grandparentTitle rk = media.grandparentRatingKey theme = media.grandparentTheme if theme is None: theme = media.show().theme name = '%s__%s' % (re.sub('[\'\"\\\/;,-]+', '', name), rk ) # make a proper cleaning in misc. f_name = '%s.mp3' % name f_path = os.path.join(THEMES, f_name) if not os.path.exists(f_path) or force and theme: LOG.debug('Downloading %s', f_path) dlt = download(PMS.url(theme, includeToken=True), savepath=THEMES, filename=f_name) if dlt: SHOWS[rk] = f_path return f_path else: LOG.debug('Skipping %s as it already exists', f_name) return f_path
from plexapi import CONFIG from tqdm import tqdm parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-u', '--username', help='Your Plex username', default=CONFIG.get('auth.myplex_username')) parser.add_argument('-p', '--password', help='Your Plex password', default=CONFIG.get('auth.myplex_password')) parser.add_argument('--url', default=None, help='Download from URL (only paste after !)') opts = parser.parse_args() # Search item to download account = utils.getMyPlexAccount(opts) items = search_for_item(opts.url) for item in items: for part in item.iterParts(): # We do this manually since we dont want to add a progress to Episode etc filename = '%s.%s' % (item._prettyfilename(), part.container) url = item._server.url('%s?download=1' % part.key) filepath = utils.download(url, token=account.authenticationToken, filename=filename, savepath=os.getcwd(), session=item._server._session, showstatus=True) #print(' %s' % filepath)
# Command line parser from plexapi import CONFIG from tqdm import tqdm parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-u', '--username', help='Your Plex username', default=CONFIG.get('auth.myplex_username')) parser.add_argument('-p', '--password', help='Your Plex password', default=CONFIG.get('auth.myplex_password')) parser.add_argument('--url', default=None, help='Download from URL (only paste after !)') opts = parser.parse_args() # Search item to download account = utils.getMyPlexAccount(opts) items = search_for_item(opts.url) for item in items: for part in item.iterParts(): # We do this manually since we dont want to add a progress to Episode etc filename = '%s.%s' % (item._prettyfilename(), part.container) url = item._server.url('%s?download=1' % part.key) filepath = utils.download(url, filename=filename, savepath=os.getcwd(), session=item._server._session, showstatus=True) #print(' %s' % filepath)
import os from plexapi.server import PlexServer from plexapi import utils baseurl = 'https://plx.w00t.cloud' token = 'H6gqeSNE3yGthe72x1w7' plex = PlexServer(baseurl, token) playlists = [pl for pl in plex.playlists()] playlist = utils.choose('Choose Playlist', playlists, lambda pl: '%s' % pl.title) print(len(playlist.items())) for photo in playlist.items(): photomediapart = photo.media[0].parts[0] print('Download File: %s' % photomediapart.file) url = plex.url('%s?download=1' % photomediapart.key) utils.download(url, token, os.path.basename(photomediapart.file))
# Connect to the server and fetch the item servers = [r for r in account.resources() if r.clientIdentifier == clientid] if len(servers) != 1: raise SystemExit('Unknown or ambiguous client id: %s' % clientid) server = servers[0].connect() return server.fetchItem(key) if __name__ == '__main__': # Command line parser from plexapi import CONFIG from tqdm import tqdm parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-u', '--username', help='Your Plex username', default=CONFIG.get('auth.myplex_username')) parser.add_argument('-p', '--password', help='Your Plex password', default=CONFIG.get('auth.myplex_password')) parser.add_argument('--url', default=None, help='Download from URL (only paste after !)') opts = parser.parse_args() # Search item to download account = utils.getMyPlexAccount(opts) items = search_for_item(opts.url) for item in items: for part in item.iterParts(): # We do this manually since we dont want to add a progress to Episode etc filename = '%s.%s' % (item._prettyfilename(), part.container) url = item._server.url('%s?download=1' % part.key) filepath = utils.download(url, token=account.authenticationToken, filename=filename, savepath=os.getcwd(), session=item._server._session, showstatus=True) #print(' %s' % filepath)
print('Ok, I got the server instance, let`s download what you`re missing') def get_tvshow_path(name, season, episode): return os.path.join(tvshows_path, name, 'S%02dE%02d.mp4' % (season, episode)) if opts.with_movies or opts.with_shows: def get_movie_path(name, year): return os.path.join(movies_path, '%s (%d).mp4' % (name, year)) media_stub_path = os.path.join(path, 'media', 'video_stub.mp4') if not os.path.isfile(media_stub_path): download( 'http://www.mytvtestpatterns.com/mytvtestpatterns/Default/GetFile?p=PhilipsCircleMP4', '', filename='video_stub.mp4', savepath=os.path.join(path, 'media'), showstatus=True) sections = [] if opts.with_movies: movies_path = os.path.join(path, 'media', 'Movies') makedirs(movies_path, exist_ok=True) required_movies = { 'Elephants Dream': 2006, 'Sita Sings the Blues': 2008, 'Big Buck Bunny': 2008, 'Sintel': 2010, }
# Bulk Download of photos from PLEX playlist import os from plexapi.server import PlexServer from plexapi import utils baseurl = 'http://localhost:32400' token = 'PLACE TOKEN HERE' plex = PlexServer(baseurl, token) playlists = [pl for pl in plex.playlists() if pl.isPhoto] playlist = utils.choose('Choose Playlist', playlists, lambda pl: '%s' % pl.title) for photo in playlist.items(): photomediapart = photo.media[0].parts[0] if photo.year == 2018 or photo.year == 2019: print('Downlod File: %s' % photomediapart.file) url = plex.url('%s?download=1' % photomediapart.key) utils.download(url, token, os.path.basename(photomediapart.file), '%s' % photo.year) else: print('Skip File: %s | %s' % (photomediapart.file, photo.year))