def GetFromXBMC(self): Debug('[Episodes Sync] Getting episodes from XBMC') if self.show_progress: progress.update(5, line1=__getstring__(1432), line2=' ', line3=' ') shows = xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber']}, 'id': 0}) # sanity check, test for empty result if not shows: Debug("[Episodes Sync] xbmc json request was empty.") return # test to see if tvshows key exists in xbmc json request if 'tvshows' in shows: shows = shows['tvshows'] Debug("[Episodes Sync] XBMC JSON Result: '%s'" % str(shows)) else: Debug("[Episodes Sync] Key 'tvshows' not found") return if self.show_progress: progress.update(10, line1=__getstring__(1433), line2=' ', line3=' ') for show in shows: if self.Canceled(): return show['episodes'] = [] episodes = xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': show['tvshowid'], 'properties': ['season', 'episode', 'playcount', 'uniqueid']}, 'id': 0}) if 'episodes' in episodes: episodes = episodes['episodes'] show['episodes'] = [x for x in episodes if type(x) == type(dict())] self.xbmc_shows = [x for x in shows if x['episodes']]
def xbmcUpdateEpisodes(self, shows): if len(shows) == 0: self.updateProgress(82, line1=utilities.getString(1441), line2=utilities.getString(1493)) Debug("[Episodes Sync] XBMC episode playcounts are up to date.") return Debug("[Episodes Sync] %i show(s) shows are missing playcounts on XBMC" % len(shows)) for s in ["%s" % self.getShowAsString(s, short=True) for s in shows]: Debug("[Episodes Sync] Episodes updated: %s" % s) self.updateProgress(64, line1=utilities.getString(1441), line2="%i %s" % (len(shows), utilities.getString(1439)), line3=" ") episodes = [] for show in shows: for season in show['seasons']: for episode in show['seasons'][season]: episodes.append({'episodeid': show['seasons'][season][episode]['id'], 'playcount': 1}) #split episode list into chunks of 50 chunked_episodes = utilities.chunks([{"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": episodes[i], "id": i} for i in range(len(episodes))], 50) i = 0 x = float(len(chunked_episodes)) for chunk in chunked_episodes: if self.isCanceled(): return if self.simulate: Debug("[Episodes Sync] %s" % str(chunk)) else: utilities.xbmcJsonRequest(chunk) i = i + 1 y = ((i / x) * 18) + 64 self.updateProgress(int(y), line2=utilities.getString(1494)) self.updateProgress(82, line2=utilities.getString(1495) % len(episodes))
def xbmcUpdateMovies(self, movies): if len(movies) == 0: self.updateProgress(80, line2=utilities.getString(1471)) Debug("[Movies Sync] XBMC movie playcount is up to date.") return titles = ", ".join(["%s (%s)" % (m['title'], m['imdb_id']) for m in movies]) Debug("[Movies Sync] %i movie(s) playcount will be updated in XBMC" % len(movies)) Debug("[Movies Sync] Movies updated: %s" % titles) self.updateProgress(60, line2="%i %s" % (len(movies), utilities.getString(1430))) #split movie list into chunks of 50 chunked_movies = utilities.chunks([{"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": movies[i]['movieid'], "playcount": movies[i]['plays']}, "id": i} for i in range(len(movies))], 50) i = 0 x = float(len(chunked_movies)) for chunk in chunked_movies: if self.isCanceled(): return if self.simulate: Debug("[Movies Sync] %s" % str(chunk)) else: utilities.xbmcJsonRequest(chunk) i = i + 1 y = ((i / x) * 20) + 60 self.updateProgress(int(y), line2=utilities.getString(1472)) self.updateProgress(80, line2=utilities.getString(1473) % len(movies))
def rateMedia(media_id, media_type): """Launches the rating dialog""" if media_id == None: Debug('[Rating] Missing media_id') return if media_type == 'movie': xbmc_media = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovieDetails', 'params': {'movieid': media_id, 'properties': ['title', 'imdbnumber', 'year']}})['moviedetails'] if xbmc_media == None: Debug('[Rating] Failed to retrieve movie data from XBMC') return trakt_summary = traktJsonRequest('POST', '/movie/summary.json/%%API_KEY%%/' + xbmc_media['imdbnumber']) if trakt_summary == None: Debug('[Rating] Failed to retrieve movie data from trakt') return if trakt_summary['rating'] or trakt_summary['rating_advanced']: Debug('[Rating] Movie has been rated') return else: episode = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetEpisodeDetails', 'params': {'episodeid': media_id, 'properties': ['uniqueid', 'tvshowid', 'episode', 'season']}})['episodedetails'] if episode == None: Debug('[Rating] Failed to retrieve episode data from XBMC') return xbmc_media = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetTVShowDetails', 'params': {'tvshowid': episode['tvshowid'], 'properties': ['imdbnumber']}})['tvshowdetails'] if xbmc_media == None: Debug('[Rating] Failed to retrieve tvshow data from XBMC') return xbmc_media['episode'] = episode trakt_summary = traktJsonRequest('POST', '/show/episode/summary.json/%%API_KEY%%/'+str(xbmc_media['imdbnumber'])+'/'+str(xbmc_media['episode']['season'])+'/'+str(xbmc_media['episode']['episode'])) if trakt_summary == None: Debug('[Rating] Failed to retrieve show/episode data from trakt') return xbmc_media['year'] = trakt_summary['show']['year'] if trakt_summary['episode']['rating'] or trakt_summary['episode']['rating_advanced']: Debug('[Rating] Episode has been rated') return rating_type = utilities.traktSettings['viewing']['ratings']['mode'] xbmc.executebuiltin('Dialog.Close(all, true)') gui = RatingDialog( "RatingDialog.xml", __settings__.getAddonInfo('path'), media_type=media_type, media=xbmc_media, rating_type=rating_type ) gui.doModal() del gui
def GetFromXBMC(self): Debug('[Episodes Sync] Getting episodes from XBMC') if self.show_progress: progress.update(5, line1=__getstring__(1432), line2=' ', line3=' ') shows = xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': { 'properties': ['title', 'imdbnumber'] }, 'id': 0 }) # sanity check, test for empty result if not shows: Debug("[Episodes Sync] xbmc json request was empty.") return # test to see if tvshows key exists in xbmc json request if 'tvshows' in shows: shows = shows['tvshows'] Debug("[Episodes Sync] XBMC JSON Result: '%s'" % str(shows)) else: Debug("[Episodes Sync] Key 'tvshows' not found") return if self.show_progress: progress.update(10, line1=__getstring__(1433), line2=' ', line3=' ') for show in shows: if self.Canceled(): return show['episodes'] = [] episodes = xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': { 'tvshowid': show['tvshowid'], 'properties': ['season', 'episode', 'playcount', 'uniqueid'] }, 'id': 0 }) if 'episodes' in episodes: episodes = episodes['episodes'] show['episodes'] = [ x for x in episodes if type(x) == type(dict()) ] self.xbmc_shows = [x for x in shows if x['episodes']]
def watching(self): if not self.isPlaying: return if not self.curVideoInfo: return Debug("[Scrobbler] watching()") scrobbleMovieOption = utilities.getSettingAsBool('scrobble_movie') scrobbleEpisodeOption = utilities.getSettingAsBool('scrobble_episode') self.update(True) duration = self.videoDuration / 60 watchedPercent = (self.watchedTime / self.videoDuration) * 100 if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption: response = self.traktapi.watchingMovie(self.curVideoInfo, duration, watchedPercent) if response != None: if self.curVideoInfo['imdbnumber'] is None: if 'status' in response and response['status'] == "success": if 'movie' in response and 'imdb_id' in response['movie']: self.curVideoInfo['imdbnumber'] = response['movie']['imdb_id'] if 'id' in self.curVideo and utilities.getSettingAsBool('update_imdb_id'): req = {"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetMovieDetails", "params": {"movieid" : self.curVideoInfo['movieid'], "imdbnumber": self.curVideoInfo['imdbnumber']}} utilities.xbmcJsonRequest(req) # get summary data now if we are rating this movie if utilities.getSettingAsBool('rate_movie') and self.traktSummaryInfo is None: Debug("[Scrobbler] Movie rating is enabled, pre-fetching summary information.") self.traktSummaryInfo = self.traktapi.getMovieSummary(self.curVideoInfo['imdbnumber']) Debug("[Scrobbler] Watch response: %s" % str(response)) elif utilities.isEpisode(self.curVideo['type']) and scrobbleEpisodeOption: if self.isMultiPartEpisode: Debug("[Scrobbler] Multi-part episode, watching part %d of %d." % (self.curMPEpisode + 1, self.curVideo['multi_episode_count'])) # recalculate watchedPercent and duration for multi-part adjustedDuration = int(self.videoDuration / self.curVideo['multi_episode_count']) duration = adjustedDuration / 60 watchedPercent = ((self.watchedTime - (adjustedDuration * self.curMPEpisode)) / adjustedDuration) * 100 response = self.traktapi.watchingEpisode(self.curVideoInfo, duration, watchedPercent) if response != None: if self.curVideoInfo['tvdb_id'] is None: if 'status' in response and response['status'] == "success": if 'show' in response and 'tvdb_id' in response['show']: self.curVideoInfo['tvdb_id'] = response['show']['tvdb_id'] if 'id' in self.curVideo and utilities.getSettingAsBool('update_tvdb_id'): req = {"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetTVShowDetails", "params": {"tvshowid" : self.curVideoInfo['tvshowid'], "imdbnumber": self.curVideoInfo['tvdb_id']}} utilities.xbmcJsonRequest(req) # get summary data now if we are rating this episode if utilities.getSettingAsBool('rate_episode') and self.traktSummaryInfo is None: Debug("[Scrobbler] Episode rating is enabled, pre-fetching summary information.") self.traktSummaryInfo = self.traktapi.getEpisodeSummary(self.curVideoInfo['tvdb_id'], self.curVideoInfo['season'], self.curVideoInfo['episode']) Debug("[Scrobbler] Watch response: %s" % str(response))
def UpdatePlaysXBMC(self): Debug("[Movies Sync] Checking if XBMC playcount is up to date") if self.show_progress: progress.update(85, line1=__getstring__(1429), line2=" ", line3=" ") update_playcount = [] trakt_playcounts = {} for trakt_movie in self.trakt_movies_seen: if "tmdb_id" in trakt_movie: trakt_playcounts[trakt_movie["tmdb_id"]] = trakt_movie["plays"] if "imdb_id" in trakt_movie: trakt_playcounts[trakt_movie["imdb_id"]] = trakt_movie["plays"] trakt_playcounts[trakt_movie["title"]] = trakt_movie["plays"] for xbmc_movie in self.xbmc_movies: if xbmc_movie["imdbnumber"] in trakt_playcounts: if trakt_playcounts[xbmc_movie["imdbnumber"]] > xbmc_movie["playcount"]: xbmc_movie["playcount"] = trakt_playcounts[xbmc_movie["imdbnumber"]] update_playcount.append(xbmc_movie) elif xbmc_movie["title"] in trakt_playcounts: if trakt_playcounts[xbmc_movie["title"]] > xbmc_movie["playcount"]: xbmc_movie["playcount"] = trakt_playcounts[xbmc_movie["title"]] update_playcount.append(xbmc_movie) if update_playcount: Debug("[Movies Sync] %i movie(s) playcount will be updated on XBMC" % len(update_playcount)) if self.show_progress: progress.update(90, line2="%i %s" % (len(update_playcount), __getstring__(1430))) # split movie list into chunks of 50 chunked_movies = chunks( [ { "jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": { "movieid": update_playcount[i]["movieid"], "playcount": update_playcount[i]["playcount"], }, "id": i, } for i in range(len(update_playcount)) ], 50, ) for chunk in chunked_movies: if self.Canceled(): return xbmcJsonRequest(chunk) else: Debug("[Movies Sync] XBMC movie playcount is up to date")
def watching(self): if not self.isPlaying: return if not self.curVideoInfo: return Debug("[Scrobbler] watching()") self.update(True) duration = self.videoDuration / 60 watchedPercent = (self.watchedTime / self.videoDuration) * 100 if self.isMultiPartEpisode: Debug("[Scrobbler] Multi-part episode, watching part %d of %d." % ( self.curMPEpisode + 1, self.curVideo['multi_episode_count'])) # recalculate watchedPercent and duration for multi-part adjustedDuration = int(self.videoDuration / self.curVideo['multi_episode_count']) duration = adjustedDuration / 60 watchedPercent = ((self.watchedTime - (adjustedDuration * self.curMPEpisode)) / adjustedDuration) * 100 response = 'yep' if response != None: if self.curVideoInfo['tvdb_id'] is None: if 'status' in response and response['status'] == "success": if 'show' in response and 'tvdb_id' in response['show']: self.curVideoInfo['tvdb_id'] = response['show']['tvdb_id'] if 'id' in self.curVideo and utilities.getSettingAsBool('update_tvdb_id'): req = {"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetTVShowDetails", "params": {"tvshowid": self.curVideoInfo['tvshowid'], "imdbnumber": self.curVideoInfo['tvdb_id']}} utilities.xbmcJsonRequest(req) # get summary data now if we are rating this episode if utilities.getSettingAsBool('rate_episode') and self.traktSummaryInfo is None: self.traktSummaryInfo = self.traktapi.getEpisodeSummary(self.curVideoInfo['tvdb_id'], self.curVideoInfo['season'], self.curVideoInfo['episode']) Debug("[Scrobbler] Watch response: %s" % str(response)) match = utilities.getEpisodeDetailsFromXbmc(self.curMPEpisode, ['showtitle', 'season', 'episode', 'tvshowid', 'uniqueid']) else: match = utilities.getEpisodeDetailsFromXbmc(self.curVideo['id'], ['showtitle', 'season', 'episode', 'tvshowid', 'uniqueid']) elif 'showtitle' in self.curVideoData and 'season' in self.curVideoData and 'episode' in self.curVideoData: match = {} match['tvdb_id'] = None match['year'] = None match['showtitle'] = self.curVideoData['showtitle'] match['season'] = self.curVideoData['season'] match['episode'] = self.curVideoData['episode'] match['uniqueid'] = None if match == None: return
def xbmcLoadMovies(self): Debug("[Movies Sync] Getting movie data from XBMC") data = utilities.xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['title', 'imdbnumber', 'year', 'playcount', 'lastplayed']}}) if not data: Debug("[Movies Sync] XBMC JSON request was empty.") return if not 'movies' in data: Debug('[Movies Sync] Key "movies" not found') return movies = data['movies'] Debug("[Movies Sync] XBMC JSON Result: '%s'" % str(movies)) # reformat movie array for movie in movies: movie['last_played'] = utilities.sqlDateToUnixDate(movie['lastplayed']) movie['plays'] = movie.pop('playcount') movie['in_collection'] = True movie['imdb_id'] = "" movie['tmdb_id'] = "" id = movie['imdbnumber'] if id.startswith("tt"): movie['imdb_id'] = id if id.isdigit(): movie['tmdb_id'] = id del(movie['imdbnumber']) del(movie['lastplayed']) del(movie['label']) return movies
def GetFromXBMC(self): Debug('[Movies Sync] Getting movies from XBMC') if self.show_progress: progress.update(5, line1=__getstring__(1422), line2=' ', line3=' ') result = xbmcJsonRequest({ 'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': { 'properties': ['title', 'imdbnumber', 'year', 'playcount'] } }) # sanity check, test for empty result if not result: Debug("[Movies Sync] xbmc json request was empty.") return if 'movies' in result: self.xbmc_movies = result['movies'] Debug("[Movies Sync] XBMC JSON Result: '%s'" % str(self.xbmc_movies)) else: Debug('[Movies Sync] Key "movies" not found')
def xbmcLoadShowList(self): Debug("[Episodes Sync] Getting show data from XBMC") data = utilities.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber', 'year']}, 'id': 0}) if not data: Debug("[Episodes Sync] xbmc json request was empty.") return None if not 'tvshows' in data: Debug('[Episodes Sync] Key "tvshows" not found') return None shows = data['tvshows'] Debug("[Episodes Sync] XBMC JSON Result: '%s'" % str(shows)) # reformat show array for show in shows: show['in_collection'] = True show['tvdb_id'] = "" show['imdb_id'] = "" id = show['imdbnumber'] if id.startswith("tt"): show['imdb_id'] = id if id.isdigit(): show['tvdb_id'] = id del(show['imdbnumber']) del(show['label']) return shows
def xbmcLoadShows(self): tvshows = self.xbmcLoadShowList() if tvshows is None: return None Debug("[Episodes Sync] Getting episode data from XBMC") for show in tvshows: show['seasons'] = {} show['watched'] = {} data = utilities.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': show['tvshowid'], 'properties': ['season', 'episode', 'playcount', 'uniqueid']}, 'id': 0}) if not data: Debug("[Episodes Sync] There was a problem getting episode data for '%s', aborting sync." % show['title']) return None if not 'episodes' in data: Debug("[Episodes Sync] '%s' has no episodes in XBMC." % show['title']) continue episodes = data['episodes'] for e in episodes: _season = e['season'] _episode = e['episode'] if not _season in show['seasons']: show['seasons'][_season] = {} show['watched'][_season] = [] if not _episode in show['seasons'][_season]: show['seasons'][_season][_episode] = {'id': e['episodeid'], 'episode_tvdb_id': e['uniqueid']['unknown']} if e['playcount'] > 0: if not _episode in show['watched'][_season]: show['watched'][_season].append(_episode) return tvshows
def UpdatePlaysXBMC(self): Debug('[Movies Sync] Checking if XBMC playcount is up to date') if self.show_progress: progress.update(85, line1=__getstring__(1429), line2=' ', line3=' ') update_playcount = [] trakt_playcounts = {} for trakt_movie in self.trakt_movies_seen: if 'tmdb_id' in trakt_movie: trakt_playcounts[trakt_movie['tmdb_id']] = trakt_movie['plays'] if 'imdb_id' in trakt_movie: trakt_playcounts[trakt_movie['imdb_id']] = trakt_movie['plays'] trakt_playcounts[trakt_movie['title']] = trakt_movie['plays'] for xbmc_movie in self.xbmc_movies: if xbmc_movie['imdbnumber'] in trakt_playcounts: if trakt_playcounts[xbmc_movie['imdbnumber']] > xbmc_movie['playcount']: xbmc_movie['playcount'] = trakt_playcounts[xbmc_movie['imdbnumber']] update_playcount.append(xbmc_movie) elif xbmc_movie['title'] in trakt_playcounts: if trakt_playcounts[xbmc_movie['title']] > xbmc_movie['playcount']: xbmc_movie['playcount'] = trakt_playcounts[xbmc_movie['title']] update_playcount.append(xbmc_movie) if update_playcount: Debug('[Movies Sync] %i movie(s) playcount will be updated on XBMC' % len(update_playcount)) if self.show_progress: progress.update(90, line2='%i %s' % (len(update_playcount), __getstring__(1430))) #split movie list into chunks of 50 chunked_movies = chunks([{"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": update_playcount[i]['movieid'], "playcount": update_playcount[i]['playcount']}, "id": i} for i in range(len(update_playcount))], 50) for chunk in chunked_movies: if self.Canceled(): return xbmcJsonRequest(chunk) else: Debug('[Movies Sync] XBMC movie playcount is up to date')
def GetFromXBMC(self): Debug('[Episodes Sync] Getting episodes from XBMC') if self.show_progress: progress.update(5, line1=__getstring__(1432), line2=' ', line3=' ') shows = xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber']}, 'id': 0})['tvshows'] if self.show_progress: progress.update(10, line1=__getstring__(1433), line2=' ', line3=' ') for show in shows: if self.Canceled(): return show['episodes'] = [] episodes = xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': show['tvshowid'], 'properties': ['season', 'episode', 'playcount', 'uniqueid']}, 'id': 0}) if 'episodes' in episodes: episodes = episodes['episodes'] show['episodes'] = [x for x in episodes if type(x) == type(dict())] self.xbmc_shows = [x for x in shows if x['episodes']]
def xbmcLoadMovies(self): self.updateProgress(1, line2=utilities.getString(1460)) Debug("[Movies Sync] Getting movie data from XBMC") data = utilities.xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['title', 'imdbnumber', 'year', 'playcount', 'lastplayed', 'file']}}) if not data: Debug("[Movies Sync] XBMC JSON request was empty.") return if not 'movies' in data: Debug('[Movies Sync] Key "movies" not found') return movies = data['movies'] Debug("[Movies Sync] XBMC JSON Result: '%s'" % str(movies)) i = 0 x = float(len(movies)) xbmc_movies = [] # reformat movie array for movie in movies: if self.checkExclusion(movie['file']): continue if movie['lastplayed']: movie['last_played'] = utilities.sqlDateToUnixDate(movie['lastplayed']) movie['plays'] = movie.pop('playcount') movie['in_collection'] = True movie['imdb_id'] = "" movie['tmdb_id'] = "" id = movie['imdbnumber'] if id.startswith("tt"): movie['imdb_id'] = id if id.isdigit(): movie['tmdb_id'] = id del(movie['imdbnumber']) del(movie['lastplayed']) del(movie['label']) del(movie['file']) xbmc_movies.append(movie) i = i + 1 y = ((i / x) * 4) + 1 self.updateProgress(int(y)) self.updateProgress(5, line2=utilities.getString(1461)) return xbmc_movies
def GetFromXBMC(self): Debug('[Movies Sync] Getting movies from XBMC') if self.show_progress: progress.update(5, line1=__getstring__(1422), line2=' ', line3=' ') result = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['title', 'imdbnumber', 'year', 'playcount']}}) # sanity check, test for empty result if not result: Debug("[Movies Sync] xbmc json request was empty.") return if 'movies' in result: self.xbmc_movies = result['movies'] Debug("[Movies Sync] XBMC JSON Result: '%s'" % str(self.xbmc_movies)) else: Debug('[Movies Sync] Key "movies" not found')
def GetFromXBMC(self): Debug("[Movies Sync] Getting movies from XBMC") if self.show_progress: progress.update(5, line1=__getstring__(1422), line2=" ", line3=" ") result = xbmcJsonRequest( { "jsonrpc": "2.0", "id": 0, "method": "VideoLibrary.GetMovies", "params": {"properties": ["title", "imdbnumber", "year", "playcount"]}, } ) if "movies" in result: self.xbmc_movies = result["movies"] else: Debug('[Movie Sync] Key "movies" not found')
def xbmcLoadShows(self): self.updateProgress(1, line1=utilities.getString(1480), line2=utilities.getString(1481)) tvshows = self.xbmcLoadShowList() if tvshows is None: return None self.updateProgress(2, line2=utilities.getString(1482)) i = 0 x = float(len(tvshows)) Debug("[Episodes Sync] Getting episode data from XBMC") for show in tvshows: show['seasons'] = {} show['watched'] = {} data = utilities.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': show['tvshowid'], 'properties': ['season', 'episode', 'playcount', 'uniqueid', 'file']}, 'id': 0}) if not data: Debug("[Episodes Sync] There was a problem getting episode data for '%s', aborting sync." % show['title']) return None if not 'episodes' in data: Debug("[Episodes Sync] '%s' has no episodes in XBMC." % show['title']) continue episodes = data['episodes'] for e in episodes: if self.checkExclusion(e['file']): continue _season = e['season'] _episode = e['episode'] if not _season in show['seasons']: show['seasons'][_season] = {} show['watched'][_season] = [] if not _episode in show['seasons'][_season]: show['seasons'][_season][_episode] = {'id': e['episodeid'], 'episode_tvdb_id': e['uniqueid']['unknown']} if e['playcount'] > 0: if not _episode in show['watched'][_season]: show['watched'][_season].append(_episode) i = i + 1 y = ((i / x) * 8) + 2 self.updateProgress(int(y), line2=utilities.getString(1483)) self.updateProgress(10, line2=utilities.getString(1484)) return tvshows
def Main(): args = getArguments() data = {} if args['action'] == 'sync': data = {'action': 'manualSync'} elif args['action'] in ['rate', 'unrate']: data = {} data['action'] = args['action'] media_type = None if 'media_type' in args and 'dbid' in args: media_type = args['media_type'] try: data['dbid'] = int(args['dbid']) except ValueError: utils.Debug( "Manual %s triggered for library item, but DBID is invalid." % args['action']) return elif 'media_type' in args and 'remoteid' in args: media_type = args['media_type'] data['remoteid'] = args['remoteid'] if 'season' in args: if not 'episode' in args: utils.Debug( "Manual %s triggered for non-library episode, but missing episode number." % args['action']) return try: data['season'] = int(args['season']) data['episode'] = int(args['episode']) except ValueError: utilities.Debug( "Error parsing season or episode for manual %s" % args['action']) return else: media_type = getMediaType() if not utils.isValidMediaType(media_type): utils.Debug("Error, not in video library.") return data['dbid'] = int(xbmc.getInfoLabel('ListItem.DBID')) if media_type is None: utils.Debug( "Manual %s triggered on an unsupported content container." % args['action']) elif utils.isValidMediaType(media_type): data['media_type'] = media_type if 'dbid' in data: utils.Debug("Manual %s of library '%s' with an ID of '%s'." % (args['action'], media_type, data['dbid'])) if utils.isMovie(media_type): result = utils.getMovieDetailsFromXbmc( data['dbid'], ['imdbnumber', 'title', 'year']) if not result: utils.Debug( "No data was returned from XBMC, aborting manual %s." % args['action']) return data['imdbnumber'] = result['imdbnumber'] elif utils.isShow(media_type): result = utils.getShowDetailsFromXBMC( data['dbid'], ['imdbnumber', 'tag']) if not result: utils.Debug( "No data was returned from XBMC, aborting manual %s." % args['action']) return data['imdbnumber'] = result['imdbnumber'] data['tag'] = result['tag'] elif utils.isEpisode(media_type): result = utils.getEpisodeDetailsFromXbmc( data['dbid'], ['showtitle', 'season', 'episode', 'tvshowid']) if not result: utils.Debug( "No data was returned from XBMC, aborting manual %s." % args['action']) return data['tvdb_id'] = result['tvdb_id'] data['season'] = result['season'] data['episode'] = result['episode'] else: if 'season' in data: utils.Debug( "Manual %s of non-library '%s' S%02dE%02d, with an ID of '%s'." % (args['action'], media_type, data['season'], data['episode'], data['remoteid'])) data['tvdb_id'] = data['remoteid'] else: utils.Debug( "Manual %s of non-library '%s' with an ID of '%s'." % (args['action'], media_type, data['remoteid'])) data['imdbnumber'] = data['remoteid'] if args['action'] == 'rate' and 'rating' in args: if args['rating'] in [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10' ]: data['rating'] = int(args['rating']) data = {'action': 'manualRating', 'ratingData': data} else: utils.Debug("Manual %s of '%s' is unsupported." % (args['action'], media_type)) elif args['action'] == 'togglewatched': media_type = getMediaType() if media_type in ['movie', 'show', 'season', 'episode']: data = {} data['media_type'] = media_type if utils.isMovie(media_type): dbid = int(xbmc.getInfoLabel('ListItem.DBID')) result = utils.getMovieDetailsFromXbmc( dbid, ['imdbnumber', 'title', 'year', 'playcount']) if result: if result['playcount'] == 0: data['id'] = result['imdbnumber'] else: utils.Debug("Movie alread marked as watched in XBMC.") else: utils.Debug("Error getting movie details from XBMC.") return elif utils.isEpisode(media_type): dbid = int(xbmc.getInfoLabel('ListItem.DBID')) result = utils.getEpisodeDetailsFromXbmc( dbid, [ 'showtitle', 'season', 'episode', 'tvshowid', 'playcount' ]) if result: if result['playcount'] == 0: data['id'] = result['tvdb_id'] data['season'] = result['season'] data['episode'] = result['episode'] else: utils.Debug( "Episode already marked as watched in XBMC.") else: utils.Debug("Error getting episode details from XBMC.") return elif utils.isSeason(media_type): showID = None showTitle = xbmc.getInfoLabel('ListItem.TVShowTitle') result = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': { 'properties': ['title', 'imdbnumber', 'year'] }, 'id': 0 }) if result and 'tvshows' in result: for show in result['tvshows']: if show['title'] == showTitle: showID = show['tvshowid'] data['id'] = show['imdbnumber'] break else: utils.Debug("Error getting TV shows from XBMC.") return season = xbmc.getInfoLabel('ListItem.Season') if season == "": season = 0 else: season = int(season) result = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': { 'tvshowid': showID, 'season': season, 'properties': ['season', 'episode', 'playcount'] }, 'id': 0 }) if result and 'episodes' in result: episodes = [] for episode in result['episodes']: if episode['playcount'] == 0: episodes.append(episode['episode']) if len(episodes) == 0: utils.Debug( "'%s - Season %d' is already marked as watched." % (showTitle, season)) return data['season'] = season data['episodes'] = episodes else: utils.Debug( "Error getting episodes from '%s' for Season %d" % (showTitle, season)) return elif utils.isShow(media_type): dbid = int(xbmc.getInfoLabel('ListItem.DBID')) result = utils.getShowDetailsFromXBMC(dbid, ['year', 'imdbnumber']) if not result: utils.Debug("Error getting show details from XBMC.") return showTitle = result['label'] data['id'] = result['imdbnumber'] result = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': { 'tvshowid': dbid, 'properties': ['season', 'episode', 'playcount'] }, 'id': 0 }) if result and 'episodes' in result: i = 0 s = {} for e in result['episodes']: season = str(e['season']) if not season in s: s[season] = [] if e['playcount'] == 0: s[season].append(e['episode']) i = i + 1 if i == 0: utils.Debug("'%s' is already marked as watched." % showTitle) return data['seasons'] = dict( (k, v) for k, v in s.iteritems() if v) else: utils.Debug( "Error getting episode details for '%s' from XBMC." % showTitle) return if len(data) > 1: utils.Debug( "Marking '%s' with the following data '%s' as watched on trakt.tv" % (media_type, str(data))) data['action'] = 'markWatched' # execute toggle watched action xbmc.executebuiltin("Action(ToggleWatched)") elif args['action'] == 'updatetags': data = {'action': 'updatetags'} elif args['action'] == 'managelists': data = {'action': 'managelists'} elif args['action'] == 'timertest': utils.Debug("Timing JSON requests.") import time t = time.time() data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShowDetails', 'params': { 'tvshowid': 254, 'properties': ['tag'] }, 'id': 1 }) #data = utils.getShowDetailsFromXBMC(254, ['tag', 'imdbnumber']) e = time.time() - t utils.Debug("VideoLibrary.GetTVShowDetails with tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovieDetails', 'params': { 'movieid': 634, 'properties': ['tag'] }, 'id': 1 }) #data = utils.getMovieDetailsFromXbmc(634, ['tag', 'imdbnumber', 'title', 'year']) e = time.time() - t utils.Debug("VideoLibrary.GetMovieDetails with tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': { 'properties': ['tag', 'title', 'imdbnumber', 'year'] }, 'id': 0 }) e = time.time() - t utils.Debug( "VideoLibrary.GetTVShows with tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['tvshows']), e / len(data['tvshows']))) t = time.time() data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': { 'properties': ['tag', 'title', 'imdbnumber', 'year'] } }) e = time.time() - t utils.Debug( "VideoLibrary.GetMovies with tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['movies']), e / len(data['movies']))) t = time.time() data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': { 'properties': ['title', 'imdbnumber', 'year'] }, 'id': 0 }) e = time.time() - t utils.Debug( "VideoLibrary.GetTVShows without tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['tvshows']), e / len(data['tvshows']))) t = time.time() data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': { 'properties': ['title', 'imdbnumber', 'year'] } }) e = time.time() - t utils.Debug( "VideoLibrary.GetMovies without tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['movies']), e / len(data['movies']))) t = time.time() data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShowDetails', 'params': { 'tvshowid': 254, 'properties': ['imdbnumber'] }, 'id': 1 }) #data = utils.getShowDetailsFromXBMC(254, ['imdbnumber']) e = time.time() - t utils.Debug( "VideoLibrary.GetTVShowDetails without tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovieDetails', 'params': { 'movieid': 634, 'properties': ['imdbnumber', 'title', 'year'] }, 'id': 1 }) #data = utils.getMovieDetailsFromXbmc(634, ['imdbnumber', 'title', 'year']) e = time.time() - t utils.Debug( "VideoLibrary.GetMovieDetails without tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': { 'properties': ['title', 'imdbnumber', 'year'] }, 'id': 0 }) data = data['tvshows'] for item in data: item_data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShowDetails', 'params': { 'tvshowid': item['tvshowid'], 'properties': ['tag'] }, 'id': 1 }) item['tag'] = item_data['tvshowdetails']['tag'] e = time.time() - t utils.Debug( "VideoLibrary.GetTVShows with tags from loop: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data), e / len(data))) t = time.time() data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovies', 'params': { 'properties': ['title', 'imdbnumber', 'year'] }, 'id': 0 }) data = data['movies'] for item in data: item_data = utils.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovieDetails', 'params': { 'movieid': item['movieid'], 'properties': ['tag'] }, 'id': 1 }) item['tag'] = item_data['moviedetails']['tag'] e = time.time() - t utils.Debug( "VideoLibrary.GetMovies with tags from: %0.3f seconds, %d items at %0.5f seconds per item." % (e, len(data), e / len(data))) elif args['action'] in ['itemlists', 'addtolist', 'removefromlist']: data = {} data['action'] = args['action'] media_type = None dbid = None if 'media_type' in args and 'dbid' in args: media_type = args['media_type'] try: dbid = int(args['dbid']) except ValueError: utils.Debug( "'%s' triggered for library item, but DBID is invalid." % args['action']) return else: media_type = getMediaType() if not media_type in ['movie', 'show']: utils.Debug("Error, not in video library.") return try: dbid = int(xbmc.getInfoLabel('ListItem.DBID')) except ValueError: utils.Debug( "'%s' triggered for library item, but there is a problem with ListItem.DBID." % args['action']) return if not media_type in ['movie', 'show']: utils.Debug("'%s' is not a valid media type for '%s'." % (media_type, args['action'])) return if args['action'] in ['addtolist', 'removefromlist']: if 'list' in args: data['list'] = args['list'] else: utils.Debug("'%s' requires a list parameter." % data['action']) data['type'] = media_type if utils.isMovie(media_type): result = utils.getMovieDetailsFromXbmc( dbid, ['imdbnumber', 'title', 'year', 'tag']) if not result: utils.Debug("Error getting movie details from XBMC.") return data['tag'] = result['tag'] data['movieid'] = result['movieid'] data['title'] = result['title'] data['year'] = result['year'] if result['imdbnumber'].startswith("tt"): data['imdb_id'] = result['imdbnumber'] elif result['imdbnumber'].isdigit(): data['tmdb_id'] = result['imdbnumber'] elif utils.isShow(media_type): result = utils.getShowDetailsFromXBMC( dbid, ['imdbnumber', 'title', 'tag']) if not result: utils.Debug("Error getting show details from XBMC.") return data['tag'] = result['tag'] data['tvshowid'] = result['tvshowid'] data['title'] = result['title'] if result['imdbnumber'].startswith("tt"): data['imdb_id'] = result['imdbnumber'] elif result['imdbnumber'].isdigit(): data['tvdb_id'] = result['imdbnumber'] q = queue.SqliteQueue() if 'action' in data: utils.Debug("Queuing for dispatch: %s" % data) q.append(data)
def UpdatePlaysXBMC(self): Debug('[Episodes Sync] Checking watched episodes on XBMC') if self.show_progress: progress.update(80, line1=__getstring__(1441), line2=' ', line3=' ') update_playcount = [] trakt_imdb_index = {} trakt_tvdb_index = {} trakt_title_index = {} for i in range(len(self.trakt_shows['watched'])): if 'imdb_id' in self.trakt_shows['watched'][i]: trakt_imdb_index[self.trakt_shows['watched'][i]['imdb_id']] = i if 'tvdb_id' in self.trakt_shows['watched'][i]: trakt_tvdb_index[self.trakt_shows['watched'][i]['tvdb_id']] = i trakt_title_index[self.trakt_shows['watched'][i]['title']] = i for xbmc_show in self.xbmc_shows: missing = [] trakt_show = None #IMDB ID if xbmc_show['imdbnumber'].startswith('tt') and xbmc_show[ 'imdbnumber'] in trakt_imdb_index.keys(): trakt_show = self.trakt_shows['watched'][trakt_imdb_index[ xbmc_show['imdbnumber']]] #TVDB ID elif xbmc_show['imdbnumber'].isdigit( ) and xbmc_show['imdbnumber'] in trakt_tvdb_index.keys(): trakt_show = self.trakt_shows['watched'][trakt_tvdb_index[ xbmc_show['imdbnumber']]] #Title else: if xbmc_show['title'] in trakt_title_index.keys(): trakt_show = self.trakt_shows['watched'][trakt_title_index[ xbmc_show['title']]] if trakt_show: missing = compare_show_watched_xbmc(xbmc_show, trakt_show) else: Debug('[Episodes Sync] Failed to find %s on trakt.tv' % xbmc_show['title']) if missing: show = { 'title': xbmc_show['title'], 'episodes': [{ 'episodeid': x['episodeid'], 'playcount': 1 } for x in missing] } update_playcount.append(show) if update_playcount: Debug( '[Episodes Sync] %i shows(s) shows are missing playcounts on XBMC' % len(update_playcount)) if self.show_progress: progress.update(85, line1=__getstring__(1441), line2='%i %s' % (len(update_playcount), __getstring__(1439))) for show in update_playcount: if self.show_progress: progress.update( 85, line1=__getstring__(1441), line2=show['title'].encode('utf-8', 'ignore'), line3='%i %s' % (len(show['episodes']), __getstring__(1440))) #split episode list into chunks of 50 chunked_episodes = chunks([{ "jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": show['episodes'][i], "id": i } for i in range(len(show['episodes']))], 50) for chunk in chunked_episodes: if self.Canceled(): return xbmcJsonRequest(chunk) else: Debug('[Episodes Sync] XBMC episode playcounts are up to date')
def rateMedia(media_id, media_type): """Launches the rating dialog""" if media_id == None: Debug('[Rating] Missing media_id') return if media_type == 'movie': resp = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovieDetails', 'params': {'movieid': media_id, 'properties': ['title', 'imdbnumber', 'year']}}) if not resp: Debug("[Rating] Problem getting movie data from XBMC") return if not resp.has_key("moviedetails"): Debug("[Rating] Error with movie results from XBMC, %s" % resp) return xbmc_media = resp["moviedetails"] if xbmc_media == None: Debug('[Rating] Failed to retrieve movie data from XBMC') return trakt_summary = globals.traktapi.getMovieSummary(xbmc_media['imdbnumber']) if trakt_summary == None: Debug('[Rating] Failed to retrieve movie data from trakt') return if trakt_summary['rating'] or trakt_summary['rating_advanced']: Debug('[Rating] Movie has been rated') return else: resp = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetEpisodeDetails', 'params': {'episodeid': media_id, 'properties': ['uniqueid', 'tvshowid', 'episode', 'season']}}) if not resp: Debug("[Rating] Problem getting episode data from XBMC") return if not resp.has_key("episodedetails"): Debug("[Rating] Error with episode results from XBMC, %s" % resp) return episode = resp["episodedetails"] if episode == None: Debug('[Rating] Failed to retrieve episode data from XBMC') return resp = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetTVShowDetails', 'params': {'tvshowid': episode['tvshowid'], 'properties': ['imdbnumber']}}) if not resp: Debug("[Rating] Problem getting tvshow data from XBMC") return if not resp.has_key("tvshowdetails"): Debug("[Rating] Error with tvshow results from XBMC, %s" % resp) return xbmc_media = resp["tvshowdetails"] if xbmc_media == None: Debug('[Rating] Failed to retrieve tvshow data from XBMC') return xbmc_media["episode"] = episode trakt_summary = globals.traktapi.getShowSummary(xbmc_media['imdbnumber'], xbmc_media['episode']['season'], xbmc_media['episode']['episode']) if trakt_summary == None: Debug('[Rating] Failed to retrieve show/episode data from trakt') return xbmc_media['year'] = trakt_summary['show']['year'] if trakt_summary['episode']['rating'] or trakt_summary['episode']['rating_advanced']: Debug('[Rating] Episode has been rated') return if not globals.traktapi.settings: globals.traktapi.getAccountSettings() rating_type = globals.traktapi.settings['viewing']['ratings']['mode'] xbmc.executebuiltin('Dialog.Close(all, true)') gui = RatingDialog( "RatingDialog.xml", __settings__.getAddonInfo('path'), media_type=media_type, media=xbmc_media, rating_type=rating_type ) gui.doModal() if gui.rating: rateOnTrakt(gui.rating, gui.media_type, gui.media) del gui
def onPlayBackStarted(self): xbmc.sleep(1000) self.type = None self.id = None # only do anything if we're playing a video if self.isPlayingVideo(): # get item data from json rpc result = utilities.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'Player.GetItem', 'params': { 'playerid': 1 }, 'id': 1 }) utilities.Debug("[traktPlayer] onPlayBackStarted() - %s" % result) # check for exclusion _filename = None try: _filename = self.getPlayingFile() except: utilities.Debug( "[traktPlayer] onPlayBackStarted() - Exception trying to get playing filename, player stopped suddently." ) return if utilities.checkScrobblingExclusion(_filename): utilities.Debug( "[traktPlayer] onPlayBackStarted() - '%s' is in exclusion settings, ignoring." % _filename) return self.type = result['item']['type'] data = {'action': 'started'} # check type of item if self.type == 'unknown': # do a deeper check to see if we have enough data to perform scrobbles utilities.Debug( "[traktPlayer] onPlayBackStarted() - Started playing a non-library file, checking available data." ) season = xbmc.getInfoLabel('VideoPlayer.Season') episode = xbmc.getInfoLabel('VideoPlayer.Episode') showtitle = xbmc.getInfoLabel('VideoPlayer.TVShowTitle') year = xbmc.getInfoLabel('VideoPlayer.Year') if season and episode and showtitle: # we have season, episode and show title, can scrobble this as an episode self.type = 'episode' data['type'] = 'episode' data['season'] = int(season) data['episode'] = int(episode) data['showtitle'] = showtitle data['title'] = xbmc.getInfoLabel('VideoPlayer.Title') if year.isdigit(): data['year'] = year utilities.Debug( "[traktPlayer] onPlayBackStarted() - Playing a non-library 'episode' - %s - S%02dE%02d - %s." % (data['showtitle'], data['season'], data['episode'], data['title'])) elif year and not season and not showtitle: # we have a year and no season/showtitle info, enough for a movie self.type = 'movie' data['type'] = 'movie' data['year'] = int(year) data['title'] = xbmc.getInfoLabel('VideoPlayer.Title') utilities.Debug( "[traktPlayer] onPlayBackStarted() - Playing a non-library 'movie' - %s (%d)." % (data['title'], data['year'])) else: utilities.Debug( "[traktPlayer] onPlayBackStarted() - Non-library file, not enough data for scrobbling, skipping." ) return elif self.type == 'episode' or self.type == 'movie': # get library id self.id = result['item']['id'] data['id'] = self.id data['type'] = self.type if self.type == 'episode': utilities.Debug( "[traktPlayer] onPlayBackStarted() - Doing multi-part episode check." ) result = utilities.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodeDetails', 'params': { 'episodeid': self.id, 'properties': ['tvshowid', 'season', 'episode'] }, 'id': 1 }) if result: utilities.Debug( "[traktPlayer] onPlayBackStarted() - %s" % result) tvshowid = int(result['episodedetails']['tvshowid']) season = int(result['episodedetails']['season']) episode = int(result['episodedetails']['episode']) episode_index = episode - 1 result = utilities.xbmcJsonRequest({ 'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': { 'tvshowid': tvshowid, 'season': season, 'properties': ['episode', 'file'], 'sort': { 'method': 'episode' } }, 'id': 1 }) if result: utilities.Debug( "[traktPlayer] onPlayBackStarted() - %s" % result) # make sure episodes array exists in results if 'episodes' in result: multi = [] for i in range(episode_index, result['limits']['total']): if result['episodes'][i]['file'] == result[ 'episodes'][episode_index]['file']: multi.append( result['episodes'][i]['episodeid']) else: break if len(multi) > 1: data['multi_episode_data'] = multi data['multi_episode_count'] = len(multi) utilities.Debug( "[traktPlayer] onPlayBackStarted() - This episode is part of a multi-part episode." ) else: utilities.Debug( "[traktPlayer] onPlayBackStarted() - This is a single episode." ) else: utilities.Debug( "[traktPlayer] onPlayBackStarted() - Video type '%s' unrecognized, skipping." % self.type) return pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) plSize = len(pl) if plSize > 1: pos = pl.getposition() if not self.plIndex is None: utilities.Debug( "[traktPlayer] onPlayBackStarted() - User manually skipped to next (or previous) video, forcing playback ended event." ) self.onPlayBackEnded() self.plIndex = pos utilities.Debug( "[traktPlayer] onPlayBackStarted() - Playlist contains %d item(s), and is currently on item %d" % (plSize, (pos + 1))) self._playing = True # send dispatch self.action(data)
def Main(): args = getArguments() data = {} if args['action'] == 'sync': data = {'action': 'manualSync'} elif args['action'] in ['rate', 'unrate']: data = {} data['action'] = args['action'] media_type = None if 'media_type' in args and 'dbid' in args: media_type = args['media_type'] try: data['dbid'] = int(args['dbid']) except ValueError: utils.Debug("Manual %s triggered for library item, but DBID is invalid." % args['action']) return elif 'media_type' in args and 'remoteid' in args: media_type = args['media_type'] data['remoteid'] = args['remoteid'] if 'season' in args: if not 'episode' in args: utils.Debug("Manual %s triggered for non-library episode, but missing episode number." % args['action']) return try: data['season'] = int(args['season']) data['episode'] = int(args['episode']) except ValueError: utilities.Debug("Error parsing season or episode for manual %s" % args['action']) return else: media_type = getMediaType() if not utils.isValidMediaType(media_type): utils.Debug("Error, not in video library.") return data['dbid'] = int(xbmc.getInfoLabel('ListItem.DBID')) if media_type is None: utils.Debug("Manual %s triggered on an unsupported content container." % args['action']) elif utils.isValidMediaType(media_type): data['media_type'] = media_type if 'dbid' in data: utils.Debug("Manual %s of library '%s' with an ID of '%s'." % (args['action'], media_type, data['dbid'])) if utils.isMovie(media_type): result = utils.getMovieDetailsFromXbmc(data['dbid'], ['imdbnumber', 'title', 'year']) if not result: utils.Debug("No data was returned from XBMC, aborting manual %s." % args['action']) return data['imdbnumber'] = result['imdbnumber'] elif utils.isShow(media_type): result = utils.getShowDetailsFromXBMC(data['dbid'], ['imdbnumber', 'tag']) if not result: utils.Debug("No data was returned from XBMC, aborting manual %s." % args['action']) return data['imdbnumber'] = result['imdbnumber'] data['tag'] = result['tag'] elif utils.isEpisode(media_type): result = utils.getEpisodeDetailsFromXbmc(data['dbid'], ['showtitle', 'season', 'episode', 'tvshowid']) if not result: utils.Debug("No data was returned from XBMC, aborting manual %s." % args['action']) return data['tvdb_id'] = result['tvdb_id'] data['season'] = result['season'] data['episode'] = result['episode'] else: if 'season' in data: utils.Debug("Manual %s of non-library '%s' S%02dE%02d, with an ID of '%s'." % (args['action'], media_type, data['season'], data['episode'], data['remoteid'])) data['tvdb_id'] = data['remoteid'] else: utils.Debug("Manual %s of non-library '%s' with an ID of '%s'." % (args['action'], media_type, data['remoteid'])) data['imdbnumber'] = data['remoteid'] if args['action'] == 'rate' and 'rating' in args: if args['rating'] in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']: data['rating'] = int(args['rating']) data = {'action': 'manualRating', 'ratingData': data} else: utils.Debug("Manual %s of '%s' is unsupported." % (args['action'], media_type)) elif args['action'] == 'togglewatched': media_type = getMediaType() if media_type in ['movie', 'show', 'season', 'episode']: data = {} data['media_type'] = media_type if utils.isMovie(media_type): dbid = int(xbmc.getInfoLabel('ListItem.DBID')) result = utils.getMovieDetailsFromXbmc(dbid, ['imdbnumber', 'title', 'year', 'playcount']) if result: if result['playcount'] == 0: data['id'] = result['imdbnumber'] else: utils.Debug("Movie alread marked as watched in XBMC.") else: utils.Debug("Error getting movie details from XBMC.") return elif utils.isEpisode(media_type): dbid = int(xbmc.getInfoLabel('ListItem.DBID')) result = utils.getEpisodeDetailsFromXbmc(dbid, ['showtitle', 'season', 'episode', 'tvshowid', 'playcount']) if result: if result['playcount'] == 0: data['id'] = result['tvdb_id'] data['season'] = result['season'] data['episode'] = result['episode'] else: utils.Debug("Episode already marked as watched in XBMC.") else: utils.Debug("Error getting episode details from XBMC.") return elif utils.isSeason(media_type): showID = None showTitle = xbmc.getInfoLabel('ListItem.TVShowTitle') result = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber', 'year']}, 'id': 0}) if result and 'tvshows' in result: for show in result['tvshows']: if show['title'] == showTitle: showID = show['tvshowid'] data['id'] = show['imdbnumber'] break else: utils.Debug("Error getting TV shows from XBMC.") return season = xbmc.getInfoLabel('ListItem.Season') if season == "": season = 0 else: season = int(season) result = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': showID, 'season': season, 'properties': ['season', 'episode', 'playcount']}, 'id': 0}) if result and 'episodes' in result: episodes = [] for episode in result['episodes']: if episode['playcount'] == 0: episodes.append(episode['episode']) if len(episodes) == 0: utils.Debug("'%s - Season %d' is already marked as watched." % (showTitle, season)) return data['season'] = season data['episodes'] = episodes else: utils.Debug("Error getting episodes from '%s' for Season %d" % (showTitle, season)) return elif utils.isShow(media_type): dbid = int(xbmc.getInfoLabel('ListItem.DBID')) result = utils.getShowDetailsFromXBMC(dbid, ['year', 'imdbnumber']) if not result: utils.Debug("Error getting show details from XBMC.") return showTitle = result['label'] data['id'] = result['imdbnumber'] result = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': dbid, 'properties': ['season', 'episode', 'playcount']}, 'id': 0}) if result and 'episodes' in result: i = 0 s = {} for e in result['episodes']: season = str(e['season']) if not season in s: s[season] = [] if e['playcount'] == 0: s[season].append(e['episode']) i = i + 1 if i == 0: utils.Debug("'%s' is already marked as watched." % showTitle) return data['seasons'] = dict((k, v) for k, v in s.iteritems() if v) else: utils.Debug("Error getting episode details for '%s' from XBMC." % showTitle) return if len(data) > 1: utils.Debug("Marking '%s' with the following data '%s' as watched on trakt.tv" % (media_type, str(data))) data['action'] = 'markWatched' # execute toggle watched action xbmc.executebuiltin("Action(ToggleWatched)") elif args['action'] == 'updatetags': data = {'action': 'updatetags'} elif args['action'] == 'managelists': data = {'action': 'managelists'} elif args['action'] == 'timertest': utils.Debug("Timing JSON requests.") import time t = time.time() data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShowDetails', 'params':{'tvshowid': 254, 'properties': ['tag']}, 'id': 1}) #data = utils.getShowDetailsFromXBMC(254, ['tag', 'imdbnumber']) e = time.time() - t utils.Debug("VideoLibrary.GetTVShowDetails with tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovieDetails', 'params':{'movieid': 634, 'properties': ['tag']}, 'id': 1}) #data = utils.getMovieDetailsFromXbmc(634, ['tag', 'imdbnumber', 'title', 'year']) e = time.time() - t utils.Debug("VideoLibrary.GetMovieDetails with tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['tag', 'title', 'imdbnumber', 'year']}, 'id': 0}) e = time.time() - t utils.Debug("VideoLibrary.GetTVShows with tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['tvshows']), e / len(data['tvshows']))) t = time.time() data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['tag', 'title', 'imdbnumber', 'year']}}) e = time.time() - t utils.Debug("VideoLibrary.GetMovies with tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['movies']), e / len(data['movies']))) t = time.time() data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber', 'year']}, 'id': 0}) e = time.time() - t utils.Debug("VideoLibrary.GetTVShows without tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['tvshows']), e / len(data['tvshows']))) t = time.time() data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['title', 'imdbnumber', 'year']}}) e = time.time() - t utils.Debug("VideoLibrary.GetMovies without tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['movies']), e / len(data['movies']))) t = time.time() data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShowDetails', 'params':{'tvshowid': 254, 'properties': ['imdbnumber']}, 'id': 1}) #data = utils.getShowDetailsFromXBMC(254, ['imdbnumber']) e = time.time() - t utils.Debug("VideoLibrary.GetTVShowDetails without tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovieDetails', 'params':{'movieid': 634, 'properties': ['imdbnumber', 'title', 'year']}, 'id': 1}) #data = utils.getMovieDetailsFromXbmc(634, ['imdbnumber', 'title', 'year']) e = time.time() - t utils.Debug("VideoLibrary.GetMovieDetails without tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber', 'year']}, 'id': 0}) data = data['tvshows'] for item in data: item_data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShowDetails', 'params':{'tvshowid': item['tvshowid'], 'properties': ['tag']}, 'id': 1}) item['tag'] = item_data['tvshowdetails']['tag'] e = time.time() - t utils.Debug("VideoLibrary.GetTVShows with tags from loop: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data), e / len(data))) t = time.time() data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['title', 'imdbnumber', 'year']}, 'id': 0}) data = data['movies'] for item in data: item_data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovieDetails', 'params':{'movieid': item['movieid'], 'properties': ['tag']}, 'id': 1}) item['tag'] = item_data['moviedetails']['tag'] e = time.time() - t utils.Debug("VideoLibrary.GetMovies with tags from: %0.3f seconds, %d items at %0.5f seconds per item." % (e, len(data), e / len(data))) elif args['action'] in ['itemlists', 'addtolist', 'removefromlist']: data = {} data['action'] = args['action'] media_type = None dbid = None if 'media_type' in args and 'dbid' in args: media_type = args['media_type'] try: dbid = int(args['dbid']) except ValueError: utils.Debug("'%s' triggered for library item, but DBID is invalid." % args['action']) return else: media_type = getMediaType() if not media_type in ['movie', 'show']: utils.Debug("Error, not in video library.") return try: dbid = int(xbmc.getInfoLabel('ListItem.DBID')) except ValueError: utils.Debug("'%s' triggered for library item, but there is a problem with ListItem.DBID." % args['action']) return if not media_type in ['movie', 'show']: utils.Debug("'%s' is not a valid media type for '%s'." % (media_type, args['action'])) return if args['action'] in ['addtolist', 'removefromlist']: if 'list' in args: data['list'] = args['list'] else: utils.Debug("'%s' requires a list parameter." % data['action']) data['type'] = media_type if utils.isMovie(media_type): result = utils.getMovieDetailsFromXbmc(dbid, ['imdbnumber', 'title', 'year', 'tag']) if not result: utils.Debug("Error getting movie details from XBMC.") return data['tag'] = result['tag'] data['movieid'] = result['movieid'] data['title'] = result['title'] data['year'] = result['year'] if result['imdbnumber'].startswith("tt"): data['imdb_id'] = result['imdbnumber'] elif result['imdbnumber'].isdigit(): data['tmdb_id'] = result['imdbnumber'] elif utils.isShow(media_type): result = utils.getShowDetailsFromXBMC(dbid, ['imdbnumber', 'title', 'tag']) if not result: utils.Debug("Error getting show details from XBMC.") return data['tag'] = result['tag'] data['tvshowid'] = result['tvshowid'] data['title'] = result['title'] if result['imdbnumber'].startswith("tt"): data['imdb_id'] = result['imdbnumber'] elif result['imdbnumber'].isdigit(): data['tvdb_id'] = result['imdbnumber'] q = queue.SqliteQueue() if 'action' in data: utils.Debug("Queuing for dispatch: %s" % data) q.append(data)
def UpdatePlaysXBMC(self): Debug('[Movies Sync] Checking if XBMC playcount is up to date') if self.show_progress: progress.update(85, line1=__getstring__(1429), line2=' ', line3=' ') update_playcount = [] trakt_playcounts = {} for trakt_movie in self.trakt_movies_seen: if 'tmdb_id' in trakt_movie: trakt_playcounts[trakt_movie['tmdb_id']] = trakt_movie['plays'] if 'imdb_id' in trakt_movie: trakt_playcounts[trakt_movie['imdb_id']] = trakt_movie['plays'] trakt_playcounts[trakt_movie['title']] = trakt_movie['plays'] for xbmc_movie in self.xbmc_movies: if xbmc_movie['imdbnumber'] in trakt_playcounts: if trakt_playcounts[ xbmc_movie['imdbnumber']] > xbmc_movie['playcount']: xbmc_movie['playcount'] = trakt_playcounts[ xbmc_movie['imdbnumber']] update_playcount.append(xbmc_movie) elif xbmc_movie['title'] in trakt_playcounts: if trakt_playcounts[ xbmc_movie['title']] > xbmc_movie['playcount']: xbmc_movie['playcount'] = trakt_playcounts[ xbmc_movie['title']] update_playcount.append(xbmc_movie) if update_playcount: Debug( '[Movies Sync] %i movie(s) playcount will be updated on XBMC' % len(update_playcount)) if self.show_progress: progress.update(90, line2='%i %s' % (len(update_playcount), __getstring__(1430))) #split movie list into chunks of 50 chunked_movies = chunks([{ "jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": { "movieid": update_playcount[i]['movieid'], "playcount": update_playcount[i]['playcount'] }, "id": i } for i in range(len(update_playcount))], 50) for chunk in chunked_movies: if self.Canceled(): return xbmcJsonRequest(chunk) else: Debug('[Movies Sync] XBMC movie playcount is up to date')
def onPlayBackStarted(self): xbmc.sleep(1000) self.type = None self.id = None # only do anything if we're playing a video if self.isPlayingVideo(): # get item data from json rpc result = utilities.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'Player.GetItem', 'params': {'playerid': 1}, 'id': 1}) utilities.Debug("[traktPlayer] onPlayBackStarted() - %s" % result) # check for exclusion _filename = None try: _filename = self.getPlayingFile() except: utilities.Debug("[traktPlayer] onPlayBackStarted() - Exception trying to get playing filename, player stopped suddently.") return if utilities.checkScrobblingExclusion(_filename): utilities.Debug("[traktPlayer] onPlayBackStarted() - '%s' is in exclusion settings, ignoring." % _filename) return self.type = result['item']['type'] data = {'action': 'started'} # check type of item if self.type == 'unknown': # do a deeper check to see if we have enough data to perform scrobbles utilities.Debug("[traktPlayer] onPlayBackStarted() - Started playing a non-library file, checking available data.") season = xbmc.getInfoLabel('VideoPlayer.Season') episode = xbmc.getInfoLabel('VideoPlayer.Episode') showtitle = xbmc.getInfoLabel('VideoPlayer.TVShowTitle') year = xbmc.getInfoLabel('VideoPlayer.Year') if season and episode and showtitle: # we have season, episode and show title, can scrobble this as an episode self.type = 'episode' data['type'] = 'episode' data['season'] = int(season) data['episode'] = int(episode) data['showtitle'] = showtitle data['title'] = xbmc.getInfoLabel('VideoPlayer.Title') if year.isdigit(): data['year'] = year utilities.Debug("[traktPlayer] onPlayBackStarted() - Playing a non-library 'episode' - %s - S%02dE%02d - %s." % (data['showtitle'], data['season'], data['episode'], data['title'])) elif year and not season and not showtitle: # we have a year and no season/showtitle info, enough for a movie self.type = 'movie' data['type'] = 'movie' data['year'] = int(year) data['title'] = xbmc.getInfoLabel('VideoPlayer.Title') utilities.Debug("[traktPlayer] onPlayBackStarted() - Playing a non-library 'movie' - %s (%d)." % (data['title'], data['year'])) else: utilities.Debug("[traktPlayer] onPlayBackStarted() - Non-library file, not enough data for scrobbling, skipping.") return elif self.type == 'episode' or self.type == 'movie': # get library id self.id = result['item']['id'] data['id'] = self.id data['type'] = self.type if self.type == 'episode': utilities.Debug("[traktPlayer] onPlayBackStarted() - Doing multi-part episode check.") result = utilities.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodeDetails', 'params': {'episodeid': self.id, 'properties': ['tvshowid', 'season', 'episode']}, 'id': 1}) if result: utilities.Debug("[traktPlayer] onPlayBackStarted() - %s" % result) tvshowid = int(result['episodedetails']['tvshowid']) season = int(result['episodedetails']['season']) episode = int(result['episodedetails']['episode']) episode_index = episode - 1 result = utilities.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': tvshowid, 'season': season, 'properties': ['episode', 'file'], 'sort': {'method': 'episode'}}, 'id': 1}) if result: utilities.Debug("[traktPlayer] onPlayBackStarted() - %s" % result) # make sure episodes array exists in results if 'episodes' in result: multi = [] for i in range(episode_index, result['limits']['total']): if result['episodes'][i]['file'] == result['episodes'][episode_index]['file']: multi.append(result['episodes'][i]['episodeid']) else: break if len(multi) > 1: data['multi_episode_data'] = multi data['multi_episode_count'] = len(multi) utilities.Debug("[traktPlayer] onPlayBackStarted() - This episode is part of a multi-part episode.") else: utilities.Debug("[traktPlayer] onPlayBackStarted() - This is a single episode.") else: utilities.Debug("[traktPlayer] onPlayBackStarted() - Video type '%s' unrecognized, skipping." % self.type) return pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) plSize = len(pl) if plSize > 1: pos = pl.getposition() if not self.plIndex is None: utilities.Debug("[traktPlayer] onPlayBackStarted() - User manually skipped to next (or previous) video, forcing playback ended event.") self.onPlayBackEnded() self.plIndex = pos utilities.Debug("[traktPlayer] onPlayBackStarted() - Playlist contains %d item(s), and is currently on item %d" % (plSize, (pos + 1))) self._playing = True # send dispatch self.action(data)
def Main(): args = getArguments() data = {} if args["action"] == "contextmenu": buttons = [] media_type = getMediaType() if utils.getSettingAsBool("tagging_enable"): if utils.isMovie(media_type): buttons.append("itemlists") dbid = int(xbmc.getInfoLabel("ListItem.DBID")) result = utils.getMovieDetailsFromXbmc(dbid, ["tag"]) if tagging.hasTraktWatchlistTag(result["tag"]): buttons.append("removefromlist") else: buttons.append("addtolist") elif utils.isShow(media_type): buttons.append("itemlists") dbid = int(xbmc.getInfoLabel("ListItem.DBID")) result = utils.getShowDetailsFromXBMC(dbid, ["tag"]) if tagging.hasTraktWatchlistTag(result["tag"]): buttons.append("removefromlist") else: buttons.append("addtolist") if media_type in ["movie", "show", "episode"]: buttons.append("rate") if media_type in ["movie", "show", "season", "episode"]: buttons.append("togglewatched") if utils.getSettingAsBool("tagging_enable"): buttons.append("managelists") buttons.append("updatetags") buttons.append("sync") contextMenu = traktContextMenu(media_type=media_type, buttons=buttons) contextMenu.doModal() _action = contextMenu.action del contextMenu if _action is None: return utils.Debug("'%s' selected from trakt.tv action menu" % _action) args["action"] = _action if _action in ["addtolist", "removefromlist"]: args["list"] = "watchlist" if args["action"] == "sync": data = {"action": "manualSync"} data["silent"] = False if "silent" in args: data["silent"] = args["silent"].lower() == "true" elif args["action"] == "loadsettings": data = {"action": "loadsettings", "force": True} utils.notification(utils.getString(1201), utils.getString(1111)) elif args["action"] in ["rate", "unrate"]: data = {} data["action"] = args["action"] media_type = None if "media_type" in args and "dbid" in args: media_type = args["media_type"] try: data["dbid"] = int(args["dbid"]) except ValueError: utils.Debug("Manual %s triggered for library item, but DBID is invalid." % args["action"]) return elif "media_type" in args and "remoteid" in args: media_type = args["media_type"] data["remoteid"] = args["remoteid"] if "season" in args: if not "episode" in args: utils.Debug( "Manual %s triggered for non-library episode, but missing episode number." % args["action"] ) return try: data["season"] = int(args["season"]) data["episode"] = int(args["episode"]) except ValueError: utilities.Debug("Error parsing season or episode for manual %s" % args["action"]) return else: media_type = getMediaType() if not utils.isValidMediaType(media_type): utils.Debug("Error, not in video library.") return data["dbid"] = int(xbmc.getInfoLabel("ListItem.DBID")) if media_type is None: utils.Debug("Manual %s triggered on an unsupported content container." % args["action"]) elif utils.isValidMediaType(media_type): data["media_type"] = media_type if "dbid" in data: utils.Debug( "Manual %s of library '%s' with an ID of '%s'." % (args["action"], media_type, data["dbid"]) ) if utils.isMovie(media_type): result = utils.getMovieDetailsFromXbmc(data["dbid"], ["imdbnumber", "title", "year"]) if not result: utils.Debug("No data was returned from XBMC, aborting manual %s." % args["action"]) return data["imdbnumber"] = result["imdbnumber"] elif utils.isShow(media_type): result = utils.getShowDetailsFromXBMC(data["dbid"], ["imdbnumber", "tag"]) if not result: utils.Debug("No data was returned from XBMC, aborting manual %s." % args["action"]) return data["imdbnumber"] = result["imdbnumber"] data["tag"] = result["tag"] elif utils.isEpisode(media_type): result = utils.getEpisodeDetailsFromXbmc( data["dbid"], ["showtitle", "season", "episode", "tvshowid"] ) if not result: utils.Debug("No data was returned from XBMC, aborting manual %s." % args["action"]) return data["tvdb_id"] = result["tvdb_id"] data["season"] = result["season"] data["episode"] = result["episode"] else: if "season" in data: utils.Debug( "Manual %s of non-library '%s' S%02dE%02d, with an ID of '%s'." % (args["action"], media_type, data["season"], data["episode"], data["remoteid"]) ) data["tvdb_id"] = data["remoteid"] else: utils.Debug( "Manual %s of non-library '%s' with an ID of '%s'." % (args["action"], media_type, data["remoteid"]) ) data["imdbnumber"] = data["remoteid"] if args["action"] == "rate" and "rating" in args: if args["rating"] in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]: data["rating"] = int(args["rating"]) data = {"action": "manualRating", "ratingData": data} else: utils.Debug("Manual %s of '%s' is unsupported." % (args["action"], media_type)) elif args["action"] == "togglewatched": media_type = getMediaType() if media_type in ["movie", "show", "season", "episode"]: data = {} data["media_type"] = media_type if utils.isMovie(media_type): dbid = int(xbmc.getInfoLabel("ListItem.DBID")) result = utils.getMovieDetailsFromXbmc(dbid, ["imdbnumber", "title", "year", "playcount"]) if result: if result["playcount"] == 0: data["id"] = result["imdbnumber"] else: utils.Debug("Movie alread marked as watched in XBMC.") else: utils.Debug("Error getting movie details from XBMC.") return elif utils.isEpisode(media_type): dbid = int(xbmc.getInfoLabel("ListItem.DBID")) result = utils.getEpisodeDetailsFromXbmc( dbid, ["showtitle", "season", "episode", "tvshowid", "playcount"] ) if result: if result["playcount"] == 0: data["id"] = result["tvdb_id"] data["season"] = result["season"] data["episode"] = result["episode"] else: utils.Debug("Episode already marked as watched in XBMC.") else: utils.Debug("Error getting episode details from XBMC.") return elif utils.isSeason(media_type): showID = None showTitle = xbmc.getInfoLabel("ListItem.TVShowTitle") result = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties": ["title", "imdbnumber", "year"]}, "id": 0, } ) if result and "tvshows" in result: for show in result["tvshows"]: if show["title"] == showTitle: showID = show["tvshowid"] data["id"] = show["imdbnumber"] break else: utils.Debug("Error getting TV shows from XBMC.") return season = xbmc.getInfoLabel("ListItem.Season") if season == "": season = 0 else: season = int(season) result = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": { "tvshowid": showID, "season": season, "properties": ["season", "episode", "playcount"], }, "id": 0, } ) if result and "episodes" in result: episodes = [] for episode in result["episodes"]: if episode["playcount"] == 0: episodes.append(episode["episode"]) if len(episodes) == 0: utils.Debug("'%s - Season %d' is already marked as watched." % (showTitle, season)) return data["season"] = season data["episodes"] = episodes else: utils.Debug("Error getting episodes from '%s' for Season %d" % (showTitle, season)) return elif utils.isShow(media_type): dbid = int(xbmc.getInfoLabel("ListItem.DBID")) result = utils.getShowDetailsFromXBMC(dbid, ["year", "imdbnumber"]) if not result: utils.Debug("Error getting show details from XBMC.") return showTitle = result["label"] data["id"] = result["imdbnumber"] result = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"tvshowid": dbid, "properties": ["season", "episode", "playcount"]}, "id": 0, } ) if result and "episodes" in result: i = 0 s = {} for e in result["episodes"]: season = str(e["season"]) if not season in s: s[season] = [] if e["playcount"] == 0: s[season].append(e["episode"]) i = i + 1 if i == 0: utils.Debug("'%s' is already marked as watched." % showTitle) return data["seasons"] = dict((k, v) for k, v in s.iteritems() if v) else: utils.Debug("Error getting episode details for '%s' from XBMC." % showTitle) return if len(data) > 1: utils.Debug( "Marking '%s' with the following data '%s' as watched on trakt.tv" % (media_type, str(data)) ) data["action"] = "markWatched" # execute toggle watched action xbmc.executebuiltin("Action(ToggleWatched)") elif args["action"] == "updatetags": data = {"action": "updatetags"} elif args["action"] == "managelists": data = {"action": "managelists"} elif args["action"] == "timertest": utils.Debug("Timing JSON requests.") import time t = time.time() data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetTVShowDetails", "params": {"tvshowid": 254, "properties": ["tag"]}, "id": 1, } ) # data = utils.getShowDetailsFromXBMC(254, ['tag', 'imdbnumber']) e = time.time() - t utils.Debug("VideoLibrary.GetTVShowDetails with tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"movieid": 634, "properties": ["tag"]}, "id": 1, } ) # data = utils.getMovieDetailsFromXbmc(634, ['tag', 'imdbnumber', 'title', 'year']) e = time.time() - t utils.Debug("VideoLibrary.GetMovieDetails with tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties": ["tag", "title", "imdbnumber", "year"]}, "id": 0, } ) e = time.time() - t utils.Debug( "VideoLibrary.GetTVShows with tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data["tvshows"]), e / len(data["tvshows"])) ) t = time.time() data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "id": 0, "method": "VideoLibrary.GetMovies", "params": {"properties": ["tag", "title", "imdbnumber", "year"]}, } ) e = time.time() - t utils.Debug( "VideoLibrary.GetMovies with tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data["movies"]), e / len(data["movies"])) ) t = time.time() data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties": ["title", "imdbnumber", "year"]}, "id": 0, } ) e = time.time() - t utils.Debug( "VideoLibrary.GetTVShows without tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data["tvshows"]), e / len(data["tvshows"])) ) t = time.time() data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "id": 0, "method": "VideoLibrary.GetMovies", "params": {"properties": ["title", "imdbnumber", "year"]}, } ) e = time.time() - t utils.Debug( "VideoLibrary.GetMovies without tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data["movies"]), e / len(data["movies"])) ) t = time.time() data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetTVShowDetails", "params": {"tvshowid": 254, "properties": ["imdbnumber"]}, "id": 1, } ) # data = utils.getShowDetailsFromXBMC(254, ['imdbnumber']) e = time.time() - t utils.Debug("VideoLibrary.GetTVShowDetails without tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"movieid": 634, "properties": ["imdbnumber", "title", "year"]}, "id": 1, } ) # data = utils.getMovieDetailsFromXbmc(634, ['imdbnumber', 'title', 'year']) e = time.time() - t utils.Debug("VideoLibrary.GetMovieDetails without tags: %0.3f seconds." % e) t = time.time() data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties": ["title", "imdbnumber", "year"]}, "id": 0, } ) data = data["tvshows"] for item in data: item_data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetTVShowDetails", "params": {"tvshowid": item["tvshowid"], "properties": ["tag"]}, "id": 1, } ) item["tag"] = item_data["tvshowdetails"]["tag"] e = time.time() - t utils.Debug( "VideoLibrary.GetTVShows with tags from loop: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data), e / len(data)) ) t = time.time() data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"properties": ["title", "imdbnumber", "year"]}, "id": 0, } ) data = data["movies"] for item in data: item_data = utils.xbmcJsonRequest( { "jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"movieid": item["movieid"], "properties": ["tag"]}, "id": 1, } ) item["tag"] = item_data["moviedetails"]["tag"] e = time.time() - t utils.Debug( "VideoLibrary.GetMovies with tags from: %0.3f seconds, %d items at %0.5f seconds per item." % (e, len(data), e / len(data)) ) elif args["action"] in ["itemlists", "addtolist", "removefromlist"]: data = {} data["action"] = args["action"] media_type = None dbid = None if "media_type" in args and "dbid" in args: media_type = args["media_type"] try: dbid = int(args["dbid"]) except ValueError: utils.Debug("'%s' triggered for library item, but DBID is invalid." % args["action"]) return else: media_type = getMediaType() if not media_type in ["movie", "show"]: utils.Debug("Error, not in video library.") return try: dbid = int(xbmc.getInfoLabel("ListItem.DBID")) except ValueError: utils.Debug( "'%s' triggered for library item, but there is a problem with ListItem.DBID." % args["action"] ) return if not media_type in ["movie", "show"]: utils.Debug("'%s' is not a valid media type for '%s'." % (media_type, args["action"])) return if args["action"] in ["addtolist", "removefromlist"]: if "list" in args: data["list"] = args["list"] else: utils.Debug("'%s' requires a list parameter." % data["action"]) data["type"] = media_type if utils.isMovie(media_type): result = utils.getMovieDetailsFromXbmc(dbid, ["imdbnumber", "title", "year", "tag"]) if not result: utils.Debug("Error getting movie details from XBMC.") return data["tag"] = result["tag"] data["movieid"] = result["movieid"] data["title"] = result["title"] data["year"] = result["year"] if result["imdbnumber"].startswith("tt"): data["imdb_id"] = result["imdbnumber"] elif result["imdbnumber"].isdigit(): data["tmdb_id"] = result["imdbnumber"] elif utils.isShow(media_type): result = utils.getShowDetailsFromXBMC(dbid, ["imdbnumber", "title", "tag"]) if not result: utils.Debug("Error getting show details from XBMC.") return data["tag"] = result["tag"] data["tvshowid"] = result["tvshowid"] data["title"] = result["title"] if result["imdbnumber"].startswith("tt"): data["imdb_id"] = result["imdbnumber"] elif result["imdbnumber"].isdigit(): data["tvdb_id"] = result["imdbnumber"] q = queue.SqliteQueue() if "action" in data: utils.Debug("Queuing for dispatch: %s" % data) q.append(data)
def UpdatePlaysXBMC(self): Debug('[Episodes Sync] Checking watched episodes on XBMC') if self.show_progress: progress.update(80, line1=__getstring__(1441), line2=' ', line3=' ') update_playcount = [] trakt_imdb_index = {} trakt_tvdb_index = {} trakt_title_index = {} for i in range(len(self.trakt_shows['watched'])): if 'imdb_id' in self.trakt_shows['watched'][i]: trakt_imdb_index[self.trakt_shows['watched'][i]['imdb_id']] = i if 'tvdb_id' in self.trakt_shows['watched'][i]: trakt_tvdb_index[self.trakt_shows['watched'][i]['tvdb_id']] = i trakt_title_index[self.trakt_shows['watched'][i]['title']] = i for xbmc_show in self.xbmc_shows: missing = [] trakt_show = None #IMDB ID if xbmc_show['imdbnumber'].startswith('tt') and xbmc_show['imdbnumber'] in trakt_imdb_index.keys(): trakt_show = self.trakt_shows['watched'][trakt_imdb_index[xbmc_show['imdbnumber']]] #TVDB ID elif xbmc_show['imdbnumber'].isdigit() and xbmc_show['imdbnumber'] in trakt_tvdb_index.keys(): trakt_show = self.trakt_shows['watched'][trakt_tvdb_index[xbmc_show['imdbnumber']]] #Title else: if xbmc_show['title'] in trakt_title_index.keys(): trakt_show = self.trakt_shows['watched'][trakt_title_index[xbmc_show['title']]] if trakt_show: missing = compare_show_watched_xbmc(xbmc_show, trakt_show) else: Debug('[Episodes Sync] Failed to find %s on trakt.tv' % xbmc_show['title']) if missing: show = {'title': xbmc_show['title'], 'episodes': [{'episodeid': x['episodeid'], 'playcount': 1} for x in missing]} update_playcount.append(show) if update_playcount: Debug('[Episodes Sync] %i shows(s) shows are missing playcounts on XBMC' % len(update_playcount)) if self.show_progress: progress.update(85, line1=__getstring__(1441), line2='%i %s' % (len(update_playcount), __getstring__(1439))) for show in update_playcount: if self.show_progress: progress.update(85, line1=__getstring__(1441), line2=show['title'].encode('utf-8', 'ignore'), line3='%i %s' % (len(show['episodes']), __getstring__(1440))) #split episode list into chunks of 50 chunked_episodes = chunks([{"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": show['episodes'][i], "id": i} for i in range(len(show['episodes']))], 50) for chunk in chunked_episodes: if self.Canceled(): return xbmcJsonRequest(chunk) else: Debug('[Episodes Sync] XBMC episode playcounts are up to date')
def onPlayBackStarted(self): #xbmc.sleep(2000) self.type = None self.id = None # only do anything if we're playing a video if self.isPlayingVideo(): # get item data from json rpc result = xbmcJsonRequest({"jsonrpc": "2.0", "method": "Player.GetItem", "params": {"playerid": 1}, "id": 1}) Debug("[myshowsPlayer] onPlayBackStarted() - %s" % result) # check for exclusion _filename = self.getPlayingFile() if checkScrobblingExclusion(_filename): Debug("[myshowsPlayer] onPlayBackStarted() - '%s' is in exclusion settings, ignoring." % _filename) return try: if result['item']['label']=='': result['item']['label']=_filename.replace('\\','/').split('/')[-1] except: pass self.type = result["item"]["type"] data = {"action": "started"} # check type of item if self.type == "unknown": # do a deeper check to see if we have enough data to perform scrobbles Debug("[myshowsPlayer] onPlayBackStarted() - Started playing a non-library file, checking available data.") season = xbmc.getInfoLabel("VideoPlayer.Season") episode = xbmc.getInfoLabel("VideoPlayer.Episode") showtitle = xbmc.getInfoLabel("VideoPlayer.TVShowTitle") year = xbmc.getInfoLabel("VideoPlayer.Year") if season and episode and showtitle: # we have season, episode and show title, can scrobble this as an episode self.type = "episode" data["type"] = "episode" data["season"] = int(season) data["episode"] = int(episode) data["showtitle"] = showtitle data["title"] = xbmc.getInfoLabel("VideoPlayer.Title") Debug("[myshowsPlayer] onPlayBackStarted() - Playing a non-library 'episode' - %s - S%02dE%02d - %s." % (data["title"], data["season"], data["episode"])) elif year and not season and not showtitle: # we have a year and no season/showtitle info, enough for a movie self.type = "movie" data["type"] = "movie" data["year"] = int(year) data["title"] = xbmc.getInfoLabel("VideoPlayer.Title") data["titleAlt"]= xbmc.getInfoLabel("VideoPlayer.OriginalTitle") Debug("[myshowsPlayer] onPlayBackStarted() - Playing a non-library 'movie' - %s (%d)." % (data["title"], data["year"])) else: Debug("[myshowsPlayer] onPlayBackStarted() - Non-library file, not enough data for scrobbling, try use lable.") try:data["label"]=result["item"]["label"] except: return urls=['(.+)s(\d+)e(\d+)','(.+)s(\d+)\.e(\d+)', '(.+) [\[|\(](\d+)[x|-](\d+)[\]|\)]', '(.+) (\d+)[x|-](\d+)', '(.+)(\d{4})\.(\d{2,4})\.(\d{2,4})','(.+)(\d{4}) (\d{2}) (\d{2})'] for file in urls: match=re.compile(file, re.I | re.IGNORECASE).findall(data["label"]) if match: self.type = "episode" data["type"] = "episode" break if self.type!="episode": file=data["label"] file=file.replace('.',' ').replace('_',' ').replace('[',' ').replace(']',' ').replace('(',' ').replace(')',' ').strip() match=re.compile('(.+) (\d{4})( |$)', re.I | re.IGNORECASE).findall(file) if match: data["title"], data["year"] = match[0][0],match[0][1] self.type = "movie" data["type"] = "movie" data["year"]=int(data["year"]) data["title"]=data["title"].strip() if self.type == "unknown": Debug("[myshowsPlayer] onPlayBackStarted() - Non-library unknown file, stopped scrobble.") elif self.type == "episode" or self.type == "movie": # get library id self.id = result["item"]["id"] data["id"] = self.id data["type"] = self.type if self.type == "movie": data["year"] = xbmc.getInfoLabel("VideoPlayer.Year") data["title"] = xbmc.getInfoLabel("VideoPlayer.Title") data["titleAlt"]= xbmc.getInfoLabel("VideoPlayer.OriginalTitle") if len(data["title"])<1: result = xbmcJsonRequest({"jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"movieid": self.id, "properties": ["title", "year","originaltitle"]}, "id": 1}) if result: Debug("[myshowsPlayer] onPlayBackStarted() TitleLen0 Event - %s" % result) data["title"] = result["moviedetails"]["title"] data["year"] = int(result["moviedetails"]["year"]) data["titleAlt"] = result["moviedetails"]["originaltitle"] if self.type == "episode": Debug("[myshowsPlayer] onPlayBackStarted() - Doing multi-part episode check.") result = xbmcJsonRequest({"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodeDetails", "params": {"episodeid": self.id, "properties": ["tvshowid", "season","episode"]}, "id": 1}) if result: Debug("[myshowsPlayer] onPlayBackStarted() - %s" % result) tvshowid = int(result["episodedetails"]["tvshowid"]) season = int(result["episodedetails"]["season"]) episode = int(result["episodedetails"]["episode"]) episode_index = episode - 1 result = xbmcJsonRequest({"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"tvshowid": tvshowid, "season": season, "properties": ["episode", "file"], "sort": {"method": "episode"}}, "id": 1}) if result: Debug("[myshowsPlayer] onPlayBackStarted() - %s" % result) # make sure episodes array exists in results if result.has_key("episodes"): multi = [] for i in range(episode_index, result["limits"]["total"]): if result["episodes"][i]["file"] == result["episodes"][episode_index]["file"]: multi.append(result["episodes"][i]["episodeid"]) else: break if len(multi) > 1: data["multi_episode_data"] = multi data["multi_episode_count"] = len(multi) Debug("[myshowsPlayer] onPlayBackStarted() - This episode is part of a multi-part episode.") else: Debug("[myshowsPlayer] onPlayBackStarted() - Video type '%s' unrecognized, skipping." % self.type) return self._playing = True # send dispatch Debug("[myshowsPlayer] onPlayBackStarted() - Data '%s'." % data) self.action(data)
def onPlayBackStarted(self): xbmc.sleep(1000) self.type = None self.id = None # only do anything if we're playing a video if self.isPlayingVideo(): # get item data from json rpc result = xbmcJsonRequest({"jsonrpc": "2.0", "method": "Player.GetItem", "params": {"playerid": 1}, "id": 1}) Debug("[traktPlayer] onPlayBackStarted() - %s" % result) # check for exclusion _filename = self.getPlayingFile() if checkScrobblingExclusion(_filename): Debug("[traktPlayer] onPlayBackStarted() - '%s' is in exclusion settings, ignoring." % _filename) return self.type = result["item"]["type"] data = {"action": "started"} # check type of item if self.type == "unknown": # do a deeper check to see if we have enough data to perform scrobbles Debug("[traktPlayer] onPlayBackStarted() - Started playing a non-library file, checking available data.") season = xbmc.getInfoLabel("VideoPlayer.Season") episode = xbmc.getInfoLabel("VideoPlayer.Episode") showtitle = xbmc.getInfoLabel("VideoPlayer.TVShowTitle") year = xbmc.getInfoLabel("VideoPlayer.Year") if season and episode and showtitle: # we have season, episode and show title, can scrobble this as an episode self.type = "episode" data["type"] = "episode" data["season"] = int(season) data["episode"] = int(episode) data["showtitle"] = showtitle data["title"] = xbmc.getInfoLabel("VideoPlayer.Title") Debug("[traktPlayer] onPlayBackStarted() - Playing a non-library 'episode' - %s - S%02dE%02d - %s." % (data["title"], data["season"], data["episode"])) elif year and not season and not showtitle: # we have a year and no season/showtitle info, enough for a movie self.type = "movie" data["type"] = "movie" data["year"] = int(year) data["title"] = xbmc.getInfoLabel("VideoPlayer.Title") Debug("[traktPlayer] onPlayBackStarted() - Playing a non-library 'movie' - %s (%d)." % (data["title"], data["year"])) else: Debug("[traktPlayer] onPlayBackStarted() - Non-library file, not enough data for scrobbling, skipping.") return elif self.type == "episode" or self.type == "movie": # get library id self.id = result["item"]["id"] data["id"] = self.id data["type"] = self.type if self.type == "episode": Debug("[traktPlayer] onPlayBackStarted() - Doing multi-part episode check.") result = xbmcJsonRequest({"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodeDetails", "params": {"episodeid": self.id, "properties": ["tvshowid", "season","episode"]}, "id": 1}) if result: Debug("[traktPlayer] onPlayBackStarted() - %s" % result) tvshowid = int(result["episodedetails"]["tvshowid"]) season = int(result["episodedetails"]["season"]) episode = int(result["episodedetails"]["episode"]) episode_index = episode - 1 result = xbmcJsonRequest({"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"tvshowid": tvshowid, "season": season, "properties": ["episode", "file"], "sort": {"method": "episode"}}, "id": 1}) if result: Debug("[traktPlayer] onPlayBackStarted() - %s" % result) # make sure episodes array exists in results if result.has_key("episodes"): multi = [] for i in range(episode_index, result["limits"]["total"]): if result["episodes"][i]["file"] == result["episodes"][episode_index]["file"]: multi.append(result["episodes"][i]["episodeid"]) else: break if len(multi) > 1: data["multi_episode_data"] = multi data["multi_episode_count"] = len(multi) Debug("[traktPlayer] onPlayBackStarted() - This episode is part of a multi-part episode.") else: Debug("[traktPlayer] onPlayBackStarted() - Video type '%s' unrecognized, skipping." % self.type) return self._playing = True # send dispatch self.action(data)