Advertisement
jalarab

plex_list_to_collection_v3

Dec 27th, 2017
1,620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.38 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import requests
  5. from math import ceil
  6. from plexapi.server import PlexServer
  7. from lxml.html import parse
  8. from plexapi.utils import NA
  9.  
  10. ### Plex server details ###
  11. PLEX_URL = 'http://127.0.0.1:32400'
  12. PLEX_TOKEN = 'XXXXXXX'
  13.  
  14. ### Existing movie library details ###
  15. MOVIE_LIBRARY_NAME = 'Movies'
  16. LIST_ID = 'ls027955354'
  17.  
  18. IMDB_LIST_URL = 'http://www.imdb.com/list/{}/?view=compact&sort=listorian:asc&defaults=1&' \
  19.                 'lists={}&mode=detail&page='.format(LIST_ID, LIST_ID)
  20. IMDB_COLLECTION_NAME = 'Independent_Spirit_Best_Film'
  21.  
  22. def add_collection(library_key, rating_key):
  23.     headers = {"X-Plex-Token": PLEX_TOKEN}
  24.     params = {"type": 1,
  25.               "id": rating_key,
  26.               "collection[0].tag.tag": IMDB_COLLECTION_NAME,
  27.               "collection.locked": 1
  28.               }
  29.  
  30.     url = "{base_url}/library/sections/{library}/all".format(base_url=PLEX_URL, library=library_key)
  31.     r = requests.put(url, headers=headers, params=params)
  32.  
  33. def run_imdb_list():
  34.     try:
  35.         plex = PlexServer(PLEX_URL, PLEX_TOKEN)
  36.     except:
  37.         print("No Plex server found at: {base_url}".format(base_url=PLEX_URL))
  38.         print("Exiting script.")
  39.         return [], 0
  40.  
  41.     # Get the IMDB  list
  42.     print("Retrieving the IMDB list...")
  43.     i = 1
  44.     remaining_pages = 0
  45.     url = IMDB_LIST_URL + str(i)
  46.     tree = parse(url)
  47.     total_tiles = int(tree.xpath("//div[@class='desc lister-total-num-results']/text()")[0].strip().split(' ')[0].replace(",", ""))
  48.     list_picture_titles = tree.xpath("//div[@class='lister-item-content']//h3[@class='lister-item-header']//a/text()")
  49.     list_picture_years = tree.xpath("//div[@class='lister-item-content']//h3[@class='lister-item-header']//span[@class='lister-item-year text-muted unbold']/text()")
  50.     list_picture_ids = [a.split('/')[2] for a in
  51.                         tree.xpath("//div[@class='lister-item-content']//h3[@class='lister-item-header']//a//@href")]
  52.     if (total_tiles > 100):
  53.         total_tiles = total_tiles - 100
  54.         remaining_pages = int(ceil(total_tiles / 100.0))
  55.         i = i + 1
  56.  
  57.     while(remaining_pages > 0):
  58.         url = IMDB_LIST_URL + str(i)
  59.         tree = parse(url)
  60.         list_picture_titles = list_picture_titles + tree.xpath(
  61.             "//div[@class='lister-item-content']//h3[@class='lister-item-header']//a/text()")
  62.         list_picture_years = list_picture_years + tree.xpath(
  63.             "//div[@class='lister-item-content']//h3[@class='lister-item-header']//span[@class='lister-item-year text-muted unbold']/text()")
  64.         list_picture_ids = list_picture_ids + [a.split('/')[2] for a in
  65.                             tree.xpath(
  66.                                 "//div[@class='lister-item-content']//h3[@class='lister-item-header']//a//@href")]
  67.  
  68.         remaining_pages = remaining_pages - 1
  69.         i = i + 1
  70.  
  71.     # Get list of movies from the Plex server
  72.     print("Retrieving a list of movies from the '{library}' library in Plex...".format(library=MOVIE_LIBRARY_NAME))
  73.     try:
  74.         movie_library = plex.library.section(MOVIE_LIBRARY_NAME)
  75.         movie_library_key = movie_library.key
  76.         all_movies = movie_library.all()
  77.     except:
  78.         print("The '{library}' library does not exist in Plex.".format(library=MOVIE_LIBRARY_NAME))
  79.         print("Exiting script.")
  80.         return
  81.  
  82.     # Create a dictionary of {imdb_id: movie}
  83.     imdb_map = {}
  84.     for m in all_movies:
  85.         if m.guid != NA and 'imdb://' in m.guid:
  86.             imdb_id = m.guid.split('imdb://')[1].split('?')[0]
  87.             if imdb_id in list_picture_ids:
  88.                 imdb_map[imdb_id] = m
  89.  
  90.  
  91.     print("Setting the collection for the '{}' library...".format(MOVIE_LIBRARY_NAME))
  92.     in_library_idx = []
  93.     for i, imdb_id in enumerate(list_picture_ids):
  94.         movie = imdb_map.pop(imdb_id, None)
  95.         if movie:
  96.             add_collection(movie_library_key, movie.ratingKey)
  97.             in_library_idx.append(i)
  98.  
  99.     # Get list of missing movies
  100.     missing_imdb_list = [(idx, imdb) for idx, imdb in enumerate(zip(list_picture_ids, list_picture_titles, list_picture_years))
  101.                         if idx not in in_library_idx]
  102.  
  103.     return missing_imdb_list, len(list_picture_ids)
  104.  
  105. if __name__ == "__main__":
  106.     print("===================================================================")
  107.     import time
  108.     print time.strftime("%d/%m/%Y")
  109.     print("===================================================================\n")
  110.  
  111.     missing_imdb_list, list_count = run_imdb_list()
  112.  
  113.     print("\n===================================================================\n")
  114.     print("Number of IMDB movies in the library: {count}".format(count=list_count - len(missing_imdb_list)))
  115.     print("Number of missing IMDB movies: {count}".format(count=len(missing_imdb_list)))
  116.     print("\nList of missing movies:\n")
  117.  
  118.     for idx, (imdb_id, title, year) in missing_imdb_list:
  119.         print("{idx}\t{imdb_id}\t{title} {year}".format(idx=idx + 1, imdb_id=imdb_id, title=title.encode('utf-8'),
  120.                                                         year=year.encode('utf-8')))
  121.  
  122.     print("\n===================================================================")
  123.     print("                               Done!                               ")
  124.     print("===================================================================\n")
  125. f = open('taschen_decadas.txt','w')
  126. f.write("===================================================================\n")
  127. f.write(time.strftime("%d/%m/%Y") + '\n')
  128. f.write("===================================================================\n")
  129. f.write("\nNumber of IMDB movies in the library: {count}".format(count=list_count - len(missing_imdb_list)))
  130. f.write("\nNumber of missing IMDB movies: {count}\n".format(count=len(missing_imdb_list)))
  131. f.write("\nList of missing movies:")
  132.    
  133. for idx, (imdb_id, title, year) in missing_imdb_list:
  134.     f.write("\n{idx}\t{imdb_id}\t{title} {year}".format(idx=idx + 1, imdb_id=imdb_id, title=title.encode('utf-8'),
  135.                                                         year=year.encode('utf-8')))
  136.                                                        
  137. f.write("\n===================================================================")
  138. f.write("\n                               Done!                               ")
  139. f.write("\n===================================================================")                                                   
  140.    
  141.    # raw_input("Press Enter to finish...")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement