macaon

search-tmdb

May 4th, 2018
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.22 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. lang = 'en'
  5. region = 'US'
  6. localechanged = False
  7. api_key = '[enter your themoviedb api key here (and remove the brackets!)]'
  8. ws = '  '
  9.  
  10. try:
  11.  while True:
  12.   try:
  13.    import urllib.request
  14.    from urllib.request import urlopen
  15.    import urllib.parse
  16.    from collections import OrderedDict
  17.   except ImportError:
  18.    from urllib2 import urlopen
  19.  
  20.   import json
  21.   import sys
  22.   import os
  23.   import codecs
  24.   import languagecodes
  25.  
  26.   lang_list = [x[0] for x in languagecodes.languages]
  27.   country_list = [x[0] for x in languagecodes.countries]
  28.  
  29.   def query_yes_no(question, default="yes"):
  30.    valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
  31.    if default is None:
  32.     prompt = " [y/n] "
  33.    elif default == "yes":
  34.     prompt = " [Y/n] "
  35.    elif default == "no":
  36.     prompt = " [y/N] "
  37.    else:
  38.     raise ValueError("invalid default answer: '%s'" % default)
  39.  
  40.    while True:
  41.     sys.stdout.write(question + prompt)
  42.     choice = input().lower()
  43.     if default is not None and choice == '':
  44.      return valid[default]
  45.     elif choice in valid:
  46.      return valid[choice]
  47.     else:
  48.      sys.stdout.write("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
  49.  
  50.   def get_jsonparsed_data(url):
  51.    response = urlopen(url)
  52.    data = response.read().decode("utf-8")
  53.    return json.loads(data)
  54.   crash = False
  55.   print('Current locale: ' + lang + '-' + region + '. Type \'change-locale\' to change.')
  56.   print()
  57.   search_title = input("Movie title: ")
  58.   if search_title == 'change-locale':
  59.    while localechanged == False:
  60.     newlang = input('\nEnter new language code (ISO-639-1) (type list to show available codes): ').lower()
  61.     if newlang == 'list':
  62.      print()
  63.      for code, language, in languagecodes.languages:
  64.       print(code, language)
  65.     elif newlang not in lang_list:
  66.      print("Unknown language code")
  67.     else:
  68.      lang = newlang
  69.      x = 0
  70.      for x in range(0, len(languagecodes.languages)):
  71.       if newlang in languagecodes.languages[x]:
  72.        print('\nLanguage set to: ' + str(languagecodes.languages[x])[8:][:-2])
  73.        newregion = input('\nEnter new country code (ISO-3166-1) (type list to show available codes): ').upper()
  74.        if newregion == 'list':
  75.         print()
  76.         for code, country, in languagecodes.countries:
  77.          print(code, country)
  78.        elif newregion not in country_list:
  79.         print("Unknown country code")
  80.        else:
  81.         region = newregion
  82.         x = 0
  83.         for x in range(0, len(languagecodes.countries)):
  84.          if newregion in languagecodes.countries[x]:
  85.           print('\nCountry set to: ' + str(languagecodes.countries[x])[8:][:-2])
  86.           localechanged = True
  87.           break
  88.  
  89.   search_title = urllib.parse.quote(search_title)
  90.  
  91.   try:
  92.    search_result = get_jsonparsed_data("https://api.themoviedb.org/3/search/movie?api_key=" + api_key + "&language=" + lang + "-" + region + "&query=" + str(search_title))
  93.   except:
  94.    print("\nNo title entered!")
  95.    crash = True
  96.    
  97.   try:
  98.    query = query_yes_no('\nIs ' + search_result['results'][0]['title'] + ' (' + search_result['results'][0]['release_date'][:-6] + ') the title you\'re looking for?')
  99.    if query == False:
  100.     print()
  101.     x = 1
  102.     for x in range(1, len(search_result['results'])):
  103.      search_details = get_jsonparsed_data("https://api.themoviedb.org/3/movie/" + str(search_result['results'][x]['id']) + "?api_key=" + api_key + "&language=" + lang + "-" + region + "&region=" + region + "&append_to_response=credits")
  104.      print(str(x) + ": " + search_result['results'][x]['title'] + ' (' + search_result['results'][x]['release_date'][:-6] + ')')
  105.     selected_title = int(input("\nSelect correct title ([ENTER] to cancel): "))
  106.    
  107.    else:
  108.     selected_title = 0
  109.    
  110.    info_default = get_jsonparsed_data("https://api.themoviedb.org/3/movie/" + str(search_result['results'][selected_title]['id']) + "?api_key=" + api_key + "&language=" + lang + "-" + region + "&region=" + region + "&append_to_response=credits,release_dates")
  111.    info_english = get_jsonparsed_data("https://api.themoviedb.org/3/movie/" + str(search_result['results'][selected_title]['id']) + "?api_key=" + api_key)
  112.  
  113.    print('\nSelected title: ' + info_default['title'] + ' (' + info_default['release_date'][:-6] + ') - TMDB ID: ' + str(search_result['results'][selected_title]['id']) + '\n')
  114.  
  115.    filepath = input("Drag and drop your video file here (or type a path+filename without extension) and press [ENTER]: ").replace("\"", "")[:-4]
  116.    print()
  117.    path = filepath.rsplit('\\', 1)
  118.  
  119.    with open(filepath + '.xml', 'w', encoding='utf-8') as f:
  120.     f.write('<media type="Movie">\n' + ws + '<title>')
  121.  
  122.     f.write(info_default['title'])
  123.     print('Added title: ' + info_default['title'])
  124.  
  125.     f.write('</title>\n' + ws + '<description>')
  126.  
  127.     f.write(info_default['overview'])
  128.     f.write('</description>\n' + ws + '<cast>\n')
  129.     print('Added overview')
  130.  
  131.     x = 0
  132.     for x in range(0, len(info_default['credits']['cast'])):
  133.      actor = info_default['credits']['cast'][x]['name']
  134.      f.write(ws*2 + '<name>' + actor + '</name>\n')
  135.      print('Added actor: ' + actor)
  136.      x += 1
  137.  
  138.     f.write(ws + '</cast>\n' + ws + '<rating>')
  139.  
  140.     x = 0
  141.     for x in range(0, len(info_default['release_dates']['results'])):
  142.      if region in info_default['release_dates']['results'][x]['iso_3166_1']:
  143.       cert = info_default['release_dates']['results'][x]['release_dates'][0]['certification']
  144.       f.write(cert)
  145.       print('Added certification: ' + cert)
  146.     x += 1
  147.  
  148.     f.write('</rating>\n' + ws + '<userStarRating>')
  149.  
  150.     rating = str(info_default['vote_average'])
  151.     f.write(rating)
  152.     print('Added rating: ' + rating)
  153.  
  154.     f.write('</userStarRating>\n' + ws + '<published>')
  155.  
  156.     x = 0
  157.     for x in range(0, len(info_default['release_dates']['results'])):
  158.      if region in info_default['release_dates']['results'][x]['iso_3166_1']:
  159.       reldate = info_default['release_dates']['results'][x]['release_dates'][0]['release_date'][:10]
  160.       f.write(reldate)
  161.       print('Added release date: ' + reldate)
  162.     x += 1
  163.  
  164.     f.write('</published>\n' + ws + '<genres>\n')
  165.  
  166.     x = 0
  167.     for x in range(0, len(info_english['genres'])):
  168.      genre = info_english['genres'][x]['name']
  169.      f.write(ws*2 + '<genre>' + genre + '</genre>\n')
  170.      print('Added genre: ' + genre)
  171.  
  172.     f.write(ws + '</genres>\n' + ws + '<directors>\n')
  173.  
  174.     x = 0
  175.     for x in range(0, len(info_default['credits']['crew'])):
  176.      if 'Director' in info_default['credits']['crew'][x]['job']:
  177.       director = info_default['credits']['crew'][x]['name']
  178.       f.write(ws*2 + '<name>' + str(director) + '</name>\n')
  179.       print('Added director: ' + director)
  180.  
  181.     f.write(ws + '</directors>\n' + ws + '<writers>\n')
  182.  
  183.     x = 0
  184.     duplicate_check = []
  185.     for x in range(0, len(info_default['credits']['crew'])):
  186.      if ('Writer' in info_default['credits']['crew'][x]['job']) or ('Story' in info_default['credits']['crew'][x]['job']) or ('Screenplay' in info_default['credits']['crew'][x]['job']) or ('Author' in info_default['credits']['crew'][x]['job']) or ('Novel' in info_default['credits']['crew'][x]['job']):
  187.       writer = info_default['credits']['crew'][x]['name']
  188.       if not writer in duplicate_check:
  189.        duplicate_check.append(writer)
  190.        f.write(ws*2 + '<name>' + writer + '</name>\n')
  191.        print('Added writer: ' + writer)
  192.       else:
  193.        print('Discarded duplicate entry: ' + writer)
  194.  
  195.     f.write(ws + '</writers>\n</media>')
  196.    f.close
  197.    with open(path[0] + '\.' + str(info_default['id']), 'w') as f:
  198.     f.close
  199.  
  200.    print('Downloading poster...')
  201.    urllib.request.urlretrieve("http://image.tmdb.org/t/p/original" + info_default['poster_path'], filepath + ".jpg")
  202.    print('Downloading backdrop...')
  203.    urllib.request.urlretrieve("http://image.tmdb.org/t/p/original" + info_default['backdrop_path'], filepath + "-fanart.jpg")
  204.    print('Done!')
  205.   except:
  206.    if localechanged == True:
  207.     print()
  208.     localechanged = False
  209.    elif crash == True:
  210.     print()
  211.     crash = False
  212.    else:
  213.     try:
  214.      selected_title
  215.     except:
  216.      print('\nNo title selected!\n')
  217.     else:
  218.      print('\nNo match!\n')
  219. except KeyboardInterrupt:
  220.  print('Interrupted!')
Advertisement
Add Comment
Please, Sign In to add comment