script.cinematic/addon.py

208 lines
7.7 KiB
Python

import xbmc
import xbmcgui
import xbmcaddon
import xbmcvfs
import json
import random
import sys
import urllib
ADDON = xbmcaddon.Addon()
CWD = ADDON.getAddonInfo('path').decode('utf-8')
#CWD = ADDON.getAddonInfo('path') # for kodi 19
def list_programs(cinematic_path):
dirs, files = xbmcvfs.listdir(cinematic_path)
programs = {}
for filename in files:
if filename.endswith('.json'):
filehandle = xbmcvfs.File(cinematic_path + filename)
program_json = filehandle.read()
filehandle.close()
program_data = json.loads(program_json)
programs[program_data['name']] = filename
return programs
def show_dialog(programs):
entries = programs.keys()
dialog = xbmcgui.Dialog()
ret = dialog.select('Cinematic: Select a program', entries)
del dialog
return programs[entries[ret]]
def files_from_dir(count, location):
dirs, files = xbmcvfs.listdir(location)
files = random.sample(files, count)
for i in range(len(files)):
files[i] = location + files[i]
return files
def get_tmdbid(apikey, imdbid):
print("getting tmdbid for imdbid %s" % imdbid)
baseurl = 'https://api.themoviedb.org/3/'
url = baseurl + 'find/%s?api_key=%s&external_source=imdb_id'
url = url % (imdbid, apikey)
json_url = urllib.urlopen(url)
data = json.loads(json_url.read())
print(data)
try:
tmdbid = data['movie_results'][0]['id']
print("tmdbid is %d" % tmdbid)
except:
tmdbid = 0
print("tmdbid could not be found")
return tmdbid
def get_recommendations(apikey, movieid, language, choice):
print("getting %s for %d" % (choice, movieid))
baseurl = 'https://api.themoviedb.org/3/'
url = baseurl + 'movie/%d/%s?api_key=%s&language=%s'
url = url % (movieid, choice, apikey, language)
json_url = urllib.urlopen(url)
data = json.loads(json_url.read())
results = []
for result in data['results']:
results.append({'title': result['title'], 'movieid': result['id']})
return results
def get_movie_trailers(apikey, movieid, language):
print("getting trailers for %d" % movieid)
baseurl = 'https://api.themoviedb.org/3/'
url = baseurl + 'movie/%d?api_key=%s&language=%s&append_to_response=videos'
url = url % (movieid, apikey, language)
json_url = urllib.urlopen(url)
data = json.loads(json_url.read())
results = []
for result in data['videos']['results']:
if result['site'] == 'YouTube':
location = 'plugin://plugin.video.youtube/play/?video_id=%s' % result['key']
else:
next
results.append({'title': result['name'], 'type': result['type'], 'location': location})
return results
def get_trailers(apikey, recommendations, language, cliptype, count):
results = []
for recommendation in recommendations[:10]:
all_trailers = get_movie_trailers(apikey, recommendation['movieid'], language)
trailers = []
for trailer in all_trailers:
if trailer['type'] == cliptype:
trailers.append(trailer)
if len(trailers) > 0:
random.shuffle(trailers)
trailer = trailers[0]
results.append(trailer)
if len(results) == count:
break
return results
def conduct_program(program_file, feature):
filehandle = xbmcvfs.File(program_file)
program_json = filehandle.read()
filehandle.close()
program_data = json.loads(program_json)
program = []
for item in program_data['items']:
settings = item['settings']
if settings['source'] == 'file':
entry = {'type': 'video', 'data': settings['location']}
program.append(entry)
elif settings['source'] == 'dir':
for location in files_from_dir(settings['count'], settings['location']):
entry = {'type': 'video', 'data': location}
program.append(entry)
elif settings['source'] == 'tmdbtrailer':
apikey = settings['apikey']
tmdbid = int(feature['tmdbid'])
imdbid = feature['imdbid']
language = settings['language']
choice = settings['choice']
trailertype = settings['type']
count = settings['count']
if not tmdbid:
tmdbid = get_tmdbid(apikey, imdbid)
if tmdbid:
movies = get_recommendations(apikey, tmdbid, language, choice)
random.shuffle(movies)
trailers = get_trailers(apikey, movies, language, trailertype, count)
else:
print("TODO: this feature has no tmdb id, find someting else to play")
trailers = []
for trailer in trailers:
entry = {'type': 'video', 'data': trailer['location']}
program.append(entry)
elif settings['source'] == 'rating':
rating = -1
for s in feature['mpaa'].split():
if s.isdigit():
rating = int(s)
break
if rating > -1:
dirs, files = xbmcvfs.listdir(settings['location'])
for f in files:
if f.startswith(str(rating)+'.'):
location = settings['location'] + f
break
entry = {'type': 'video', 'data': location}
program.append(entry)
elif settings['source'] == 'feature':
entry = {'type': 'video', 'data': feature['file']}
program.append(entry)
return program
def get_feature(movieid):
query = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"movieid": %s, "properties": ["file", "mpaa", "uniqueid"]}, "id": "1"}' % movieid
json_response = xbmc.executeJSONRPC(query)
response = json.loads(json_response)
if not 'tmdb' in response['result']['moviedetails']['uniqueid']:
response['result']['moviedetails']['uniqueid']['tmdb'] = 0
if not 'imdb' in response['result']['moviedetails']['uniqueid']:
response['result']['moviedetails']['uniqueid']['tmdb'] = ''
feature = {
'label': response['result']['moviedetails']['label'],
'file': response['result']['moviedetails']['file'],
'mpaa': response['result']['moviedetails']['mpaa'],
'tmdbid': response['result']['moviedetails']['uniqueid']['tmdb'],
'imdbid': response['result']['moviedetails']['uniqueid']['imdb']
}
return feature
if __name__ == '__main__':
if (sys.argv[1] == 'experience'):
movieid = xbmc.getInfoLabel('ListItem.DBID').decode('utf-8')
else:
for arg in sys.argv[1:]:
(name, value) = arg.split('=')
if name == 'dbid':
movieid = int(value)
cinematic_path = ADDON.getSettingString('cinematic_path')
feature = get_feature(movieid)
print(feature)
programs = list_programs(cinematic_path)
program_file = cinematic_path + show_dialog(programs)
program = conduct_program(program_file, feature)
print('=== playlist')
for entry in program:
print(" * [%s] -- %s" % (entry['type'], entry['data']))
if xbmc.getCondVisibility('Window.IsVisible(MovieInformation)'):
xbmc.executebuiltin('Dialog.Close(MovieInformation)')
print('=== playing')
playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
playlist.clear()
for entry in program:
print(" * [%s] -- %s" % (entry['type'], entry['data']))
if entry['type'] == 'video':
playlist.add(entry['data'])
else:
print(" unable to handle %s yet" % entry['type'])
xbmc.Player().play(playlist)
xbmc.sleep(500)
while xbmc.getCondVisibility('Player.HasMedia'):
xbmc.sleep(100)
print('=== done playing')