def login(self): # Request new device code with Trakt.configuration.http(timeout=90): code = Trakt['oauth/device'].code() if not code: logger.debug('Error can not reach trakt') notification(getString(32024), getString(32023)) else: # Construct device authentication poller poller = Trakt['oauth/device'].poll(**code)\ .on('aborted', self.on_aborted)\ .on('authenticated', self.on_authenticated)\ .on('expired', self.on_expired)\ .on('poll', self.on_poll) # Start polling for authentication token poller.start(daemon=False) logger.debug('Enter the code "%s" at %s to authenticate your account' % ( code.get('user_code'), code.get('verification_url') )) self.authDialog = deviceAuthDialog.DeviceAuthDialog('script-trakt-DeviceAuthDialog.xml', __addon__.getAddonInfo('path'), code=code.get('user_code'), url=code.get('verification_url')) self.authDialog.doModal() del self.authDialog
def __init__(self, sync, progress): self.sync = sync if not self.sync.show_progress and sync.sync_on_update and sync.notify and self.sync.notify_during_playback: notification('%s %s' % (kodiUtilities.getString(32045), kodiUtilities.getString(32046)), kodiUtilities.getString(32061)) # Sync started if sync.show_progress and not sync.run_silent: progress.create("%s %s" % (kodiUtilities.getString(32045), kodiUtilities.getString(32046)), line1=" ", line2=" ", line3=" ") kodiMovies = self.__kodiLoadMovies() if not isinstance(kodiMovies, list) and not kodiMovies: logger.debug( "[Movies Sync] Kodi movie list is empty, aborting movie Sync.") if sync.show_progress and not sync.run_silent: progress.close() return try: traktMovies = self.__traktLoadMovies() except Exception: logger.debug( "[Movies Sync] Error getting Trakt.tv movie list, aborting movie Sync." ) if sync.show_progress and not sync.run_silent: progress.close() return traktMoviesProgress = self.__traktLoadMoviesPlaybackProgress(25, 36) self.__addMoviesToTraktCollection(kodiMovies, traktMovies, 37, 47) self.__deleteMoviesFromTraktCollection(traktMovies, kodiMovies, 48, 58) self.__addMoviesToTraktWatched(kodiMovies, traktMovies, 59, 69) self.__addMoviesToKodiWatched(traktMovies, kodiMovies, 70, 80) self.__addMovieProgressToKodi(traktMoviesProgress, kodiMovies, 81, 91) self.__syncMovieRatings(traktMovies, kodiMovies, 92, 99) if sync.show_progress and not sync.run_silent: self.sync.UpdateProgress(100, line1=kodiUtilities.getString(32066), line2=" ", line3=" ") progress.close() if not sync.show_progress and sync.sync_on_update and sync.notify and sync.notify_during_playback: notification('%s %s' % (kodiUtilities.getString(32045), kodiUtilities.getString(32046)), kodiUtilities.getString(32062)) # Sync complete logger.debug( "[Movies Sync] Movies on Trakt.tv (%d), movies in Kodi (%d)." % (len(traktMovies), len(kodiMovies))) logger.debug("[Movies Sync] Complete.")
def __scrobbleNotification(self, info): if not self.curVideoInfo: return if kodiUtilities.getSettingAsBool("scrobble_notification"): s = utilities.getFormattedItemName(self.curVideo['type'], info[self.curVideo['type']]) kodiUtilities.notification(kodiUtilities.getString(32015), s)
def login(self): # Request new device code with Trakt.configuration.http(timeout=90): code = Trakt['oauth/device'].code() if not code: logger.debug('Error can not reach trakt') notification(getString(32024), getString(32023)) else: # Construct device authentication poller poller = Trakt['oauth/device'].poll(**code)\ .on('aborted', self.on_aborted)\ .on('authenticated', self.on_authenticated)\ .on('expired', self.on_expired)\ .on('poll', self.on_poll) # Start polling for authentication token poller.start(daemon=False) logger.debug( 'Enter the code "%s" at %s to authenticate your account' % (code.get('user_code'), code.get('verification_url'))) self.authDialog = deviceAuthDialog.DeviceAuthDialog( 'script-trakt-DeviceAuthDialog.xml', __addon__.getAddonInfo('path'), code=code.get('user_code'), url=code.get('verification_url')) self.authDialog.doModal() del self.authDialog
def addEpisodesToHistory(self, summaryInfo, s): if len(summaryInfo['shows'][0]['seasons'][0]['episodes']) > 0: logger.debug("doMarkWatched(): %s" % str(summaryInfo)) result = globals.traktapi.addToHistory(summaryInfo) if result: kodiUtilities.notification(kodiUtilities.getString(32113), kodiUtilities.getString(32115) % (result['added']['episodes'], s)) else: kodiUtilities.notification(kodiUtilities.getString(32114), s)
def __init__(self, sync, progress): self.sync = sync if not self.sync.show_progress and self.sync.sync_on_update and self.sync.notify and self.sync.notify_during_playback: notification('%s %s' % (kodiUtilities.getString(32045), kodiUtilities.getString(32050)), kodiUtilities.getString(32061)) # Sync started if self.sync.show_progress and not self.sync.run_silent: progress.create("%s %s" % (kodiUtilities.getString(32045), kodiUtilities.getString(32050)), line1=" ", line2=" ", line3=" ") kodiShowsCollected, kodiShowsWatched = self.__kodiLoadShows() if not isinstance(kodiShowsCollected, list) and not kodiShowsCollected: logger.debug("[Episodes Sync] Kodi collected show list is empty, aborting tv show Sync.") if self.sync.show_progress and not self.sync.run_silent: progress.close() return if not isinstance(kodiShowsWatched, list) and not kodiShowsWatched: logger.debug("[Episodes Sync] Kodi watched show list is empty, aborting tv show Sync.") if self.sync.show_progress and not self.sync.run_silent: progress.close() return traktShowsCollected, traktShowsWatched, traktShowsRated, traktEpisodesRated = self.__traktLoadShows() if not traktShowsCollected: logger.debug("[Episodes Sync] Error getting Trakt.tv collected show list, aborting tv show sync.") if self.sync.show_progress and not self.sync.run_silent: progress.close() return if not traktShowsWatched: logger.debug("[Episodes Sync] Error getting Trakt.tv watched show list, aborting tv show sync.") if self.sync.show_progress and not self.sync.run_silent: progress.close() return traktShowsProgress = self.__traktLoadShowsPlaybackProgress(25, 36) self.__addEpisodesToTraktCollection(kodiShowsCollected, traktShowsCollected, 37, 47) self.__deleteEpisodesFromTraktCollection(traktShowsCollected, kodiShowsCollected, 48, 58) self.__addEpisodesToTraktWatched(kodiShowsWatched, traktShowsWatched, 59, 69) self.__addEpisodesToKodiWatched(traktShowsWatched, kodiShowsWatched, kodiShowsCollected, 70, 80) self.__addEpisodeProgressToKodi(traktShowsProgress, kodiShowsCollected, 81, 91) self.__syncShowsRatings(traktShowsRated, kodiShowsCollected, 92, 95) self.__syncEpisodeRatings(traktEpisodesRated, kodiShowsCollected, 96, 99) if not self.sync.show_progress and self.sync.sync_on_update and self.sync.notify and self.sync.notify_during_playback: notification('%s %s' % (kodiUtilities.getString(32045), kodiUtilities.getString(32050)), kodiUtilities.getString(32062)) # Sync complete if self.sync.show_progress and not self.sync.run_silent: self.sync.UpdateProgress(100, line1=" ", line2=kodiUtilities.getString(32075), line3=" ") progress.close() logger.debug("[Episodes Sync] Shows on Trakt.tv (%d), shows in Kodi (%d)." % (len(traktShowsCollected['shows']), len(kodiShowsCollected['shows']))) logger.debug("[Episodes Sync] Episodes on Trakt.tv (%d), episodes in Kodi (%d)." % (self.__countEpisodes(traktShowsCollected), self.__countEpisodes(kodiShowsCollected))) logger.debug("[Episodes Sync] Complete.")
def on_authenticated(self, token): """Triggered when device authentication has been completed :param token: Authentication token details :type token: dict """ self.authorization = token setSetting('authorization', dumps(self.authorization)) logger.debug('Authentication complete: %r' % token) self.authDialog.close() notification(getString(32157), getString(32152), 3000) self.updateUser()
def addEpisodesToHistory(self, summaryInfo, s): if len(summaryInfo['shows'][0]['seasons'][0]['episodes']) > 0: logger.debug("doMarkWatched(): %s" % str(summaryInfo)) result = globals.traktapi.addToHistory(summaryInfo) if result: kodiUtilities.notification( kodiUtilities.getString(32113), kodiUtilities.getString(32115) % (result['added']['episodes'], s)) else: kodiUtilities.notification(kodiUtilities.getString(32114), s)
def onClick(self, control): logger.debug('onClick: %s' % (control)) if control == LATER_BUTTON: notification(getString(32157), getString(32150), 5000) setSetting('last_reminder', str(int(time.time()))) if control == NEVER_BUTTON: notification(getString(32157), getString(32151), 5000) setSetting('last_reminder', '-1') if control in [LATER_BUTTON, NEVER_BUTTON]: self.close()
def __init__(self, sync, progress): self.sync = sync if not self.sync.show_progress and sync.sync_on_update and sync.notify and self.sync.notify_during_playback: notification('%s %s' % (kodiUtilities.getString(32045), kodiUtilities.getString(32046)), kodiUtilities.getString(32061)) # Sync started if sync.show_progress and not sync.run_silent: progress.create("%s %s" % (kodiUtilities.getString(32045), kodiUtilities.getString(32046)), line1=" ", line2=" ", line3=" ") kodiMovies = self.__kodiLoadMovies() if not isinstance(kodiMovies, list) and not kodiMovies: logger.debug("[Movies Sync] Kodi movie list is empty, aborting movie Sync.") if sync.show_progress and not sync.run_silent: progress.close() return try: traktMovies = self.__traktLoadMovies() except Exception: logger.debug("[Movies Sync] Error getting Trakt.tv movie list, aborting movie Sync.") if sync.show_progress and not sync.run_silent: progress.close() return traktMoviesProgress = self.__traktLoadMoviesPlaybackProgress(25, 36) self.__addMoviesToTraktCollection(kodiMovies, traktMovies, 37, 47) self.__deleteMoviesFromTraktCollection(traktMovies, kodiMovies, 48, 58) self.__addMoviesToTraktWatched(kodiMovies, traktMovies, 59, 69) self.__addMoviesToKodiWatched(traktMovies, kodiMovies, 70, 80) self.__addMovieProgressToKodi(traktMoviesProgress, kodiMovies, 81, 91) self.__syncMovieRatings(traktMovies, kodiMovies, 92, 99) if sync.show_progress and not sync.run_silent: self.sync.UpdateProgress(100, line1=kodiUtilities.getString(32066), line2=" ", line3=" ") progress.close() if not sync.show_progress and sync.sync_on_update and sync.notify and sync.notify_during_playback: notification('%s %s' % (kodiUtilities.getString(32045), kodiUtilities.getString(32046)), kodiUtilities.getString(32062)) # Sync complete logger.debug("[Movies Sync] Movies on Trakt.tv (%d), movies in Kodi (%d)." % (len(traktMovies), len(kodiMovies))) logger.debug("[Movies Sync] Complete.")
def authenticate(self, pin=None): # Attempt authentication (retrieve new token) with Trakt.configuration.http(retry=True): try: # Exchange `code` for `access_token` logger.debug("Exchanging pin for access token") self.authorization = Trakt['oauth'].token_exchange(pin, 'urn:ietf:wg:oauth:2.0:oob') if not self.authorization: logger.debug("Authentication Failure") return False else: setSetting('authorization', dumps(self.authorization)) return True except Exception as ex: message = createError(ex) logger.fatal(message) logger.debug("Cannot connect to server") notification('Trakt', getString(32023))
def doMarkWatched(self, data): media_type = data['media_type'] if utilities.isMovie(media_type): summaryInfo = globals.traktapi.getMovieSummary(data['id']).to_dict() if summaryInfo: if not summaryInfo['watched']: s = utilities.getFormattedItemName(media_type, summaryInfo) logger.debug("doMarkWatched(): '%s' is not watched on Trakt, marking it as watched." % s) params = {'movies': [summaryInfo]} logger.debug("doMarkWatched(): %s" % str(params)) result = globals.traktapi.addToHistory(params) if result: kodiUtilities.notification(kodiUtilities.getString(32113), s) else: kodiUtilities.notification(kodiUtilities.getString(32114), s) elif utilities.isEpisode(media_type): summaryInfo = {'shows': [{'ids':utilities.parseIdToTraktIds(data['id'],media_type)[0], 'seasons': [{'number': data['season'], 'episodes': [{'number':data['number']}]}]}]} logger.debug("doMarkWatched(): %s" % str(summaryInfo)) s = utilities.getFormattedItemName(media_type, data) result = globals.traktapi.addToHistory(summaryInfo) if result: kodiUtilities.notification(kodiUtilities.getString(32113), s) else: kodiUtilities.notification(kodiUtilities.getString(32114), s) elif utilities.isSeason(media_type): summaryInfo = {'shows': [{'ids':utilities.parseIdToTraktIds(data['id'],media_type)[0], 'seasons': [{'number': data['season'], 'episodes': []}]}]} s = utilities.getFormattedItemName(media_type, data) for ep in data['episodes']: summaryInfo['shows'][0]['seasons'][0]['episodes'].append({'number': ep}) logger.debug("doMarkWatched(): '%s - Season %d' has %d episode(s) that are going to be marked as watched." % (data['id'], data['season'], len(summaryInfo['shows'][0]['seasons'][0]['episodes']))) self.addEpisodesToHistory(summaryInfo, s) elif utilities.isShow(media_type): summaryInfo = {'shows': [{'ids':utilities.parseIdToTraktIds(data['id'],media_type)[0], 'seasons': []}]} if summaryInfo: s = utilities.getFormattedItemName(media_type, data) logger.debug('data: %s' % data) for season in data['seasons']: episodeJson = [] for episode in data['seasons'][season]: episodeJson.append({'number': episode}) summaryInfo['shows'][0]['seasons'].append({'number': season, 'episodes': episodeJson}) self.addEpisodesToHistory(summaryInfo, s)
def onClick(self, control): #print 'onClick: %s' % (control) logger.debug('onClick: %s' % (control)) if control == AUTH_BUTTON: if not self.__get_token(): logger.debug("Authentification error") notification(getString(32157), getString(32147), 5000) return self.auth = True if control == LATER_BUTTON: notification(getString(32157), getString(32150), 5000) setSetting('last_reminder', str(int(time.time()))) if control == NEVER_BUTTON: notification(getString(32157), getString(32151), 5000) setSetting('last_reminder', '-1') if control in [AUTH_BUTTON, LATER_BUTTON, NEVER_BUTTON]: self.close()
def __rateOnTrakt(rating, media_type, media, unrate=False): logger.debug("Sending rating (%s) to Trakt.tv" % rating) params = media if utilities.isMovie(media_type): key = 'movies' params['rating'] = rating if 'movieid' in media: kodiUtilities.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": media['movieid'], "userrating": rating}}) elif utilities.isShow(media_type): key = 'shows' params['rating'] = rating if 'tvshowid' in media: kodiUtilities.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetTVShowDetails", "params": {"tvshowid": media['tvshowid'], "userrating": rating}}) elif utilities.isSeason(media_type): key = 'shows' params['seasons'] = [{'rating': rating, 'number': media['season']}] elif utilities.isEpisode(media_type): key = 'episodes' params['rating'] = rating if 'episodeid' in media: kodiUtilities.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid": media['episodeid'], "userrating": rating}}) else: return root = {key: [params]} if not unrate: data = globals.traktapi.addRating(root) else: data = globals.traktapi.removeRating(root) if data: s = utilities.getFormattedItemName(media_type, media) if 'not_found' in data and not data['not_found']['movies'] and not data['not_found']['episodes'] and not data['not_found']['shows']: if not unrate: kodiUtilities.notification(kodiUtilities.getString(32040), s) else: kodiUtilities.notification(kodiUtilities.getString(32042), s) else: kodiUtilities.notification(kodiUtilities.getString(32044), s)
def rateMedia(media_type, itemsToRate, unrate=False, rating=None): """Launches the rating dialog""" for summary_info in itemsToRate: if not utilities.isValidMediaType(media_type): logger.debug("Not a valid media type") return elif 'user' not in summary_info: logger.debug("No user data") return s = utilities.getFormattedItemName(media_type, summary_info) logger.debug("Summary Info %s" % summary_info) if unrate: rating = None if summary_info['user']['ratings']['rating'] > 0: rating = 0 if not rating is None: logger.debug("'%s' is being unrated." % s) __rateOnTrakt(rating, media_type, summary_info, unrate=True) else: logger.debug("'%s' has not been rated, so not unrating." % s) return rerate = kodiUtilities.getSettingAsBool('rate_rerate') if rating is not None: if summary_info['user']['ratings']['rating'] == 0: logger.debug("Rating for '%s' is being set to '%d' manually." % (s, rating)) __rateOnTrakt(rating, media_type, summary_info) else: if rerate: if not summary_info['user']['ratings']['rating'] == rating: logger.debug( "Rating for '%s' is being set to '%d' manually." % (s, rating)) __rateOnTrakt(rating, media_type, summary_info) else: kodiUtilities.notification( kodiUtilities.getString(32043), s) logger.debug("'%s' already has a rating of '%d'." % (s, rating)) else: kodiUtilities.notification(kodiUtilities.getString(32041), s) logger.debug("'%s' is already rated." % s) return if summary_info['user']['ratings'] and summary_info['user']['ratings'][ 'rating']: if not rerate: logger.debug("'%s' has already been rated." % s) kodiUtilities.notification(kodiUtilities.getString(32041), s) return else: logger.debug("'%s' is being re-rated." % s) xbmc.executebuiltin('Dialog.Close(all, true)') gui = RatingDialog("script-trakt-RatingDialog.xml", __addon__.getAddonInfo('path'), media_type=media_type, media=summary_info, rerate=rerate) gui.doModal() if gui.rating: rating = gui.rating if rerate: rating = gui.rating if summary_info['user']['ratings'] and summary_info['user'][ 'ratings']['rating'] > 0 and rating == summary_info[ 'user']['ratings']['rating']: rating = 0 if rating == 0 or rating == "unrate": __rateOnTrakt(rating, gui.media_type, gui.media, unrate=True) else: __rateOnTrakt(rating, gui.media_type, gui.media) else: logger.debug("Rating dialog was closed with no rating.") del gui #Reset rating and unrate for multi part episodes unrate = False rating = None
def doAddToWatchlist(self, data): media_type = data['media_type'] if utilities.isMovie(media_type): summaryInfo = globals.traktapi.getMovieSummary(data['id']).to_dict() if summaryInfo: s = utilities.getFormattedItemName(media_type, summaryInfo) logger.debug("doAddToWatchlist(): '%s' trying to add to users watchlist." % s) params = {'movies': [summaryInfo]} logger.debug("doAddToWatchlist(): %s" % str(params)) result = globals.traktapi.addToWatchlist(params) if result: kodiUtilities.notification(kodiUtilities.getString(32165), s) else: kodiUtilities.notification(kodiUtilities.getString(32166), s) elif utilities.isEpisode(media_type): summaryInfo = {'shows': [{'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0], 'seasons': [{'number': data['season'], 'episodes': [{'number':data['number']}]}]}]} logger.debug("doAddToWatchlist(): %s" % str(summaryInfo)) s = utilities.getFormattedItemName(media_type, data) result = globals.traktapi.addToWatchlist(summaryInfo) if result: kodiUtilities.notification(kodiUtilities.getString(32165), s) else: kodiUtilities.notification(kodiUtilities.getString(32166), s) elif utilities.isSeason(media_type): summaryInfo = {'shows': [{'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0], 'seasons': [{'number': data['season']}]}]} s = utilities.getFormattedItemName(media_type, data) logger.debug("doAddToWatchlist(): '%s - Season %d' trying to add to users watchlist." % (data['id'], data['season'])) result = globals.traktapi.addToWatchlist(summaryInfo) if result: kodiUtilities.notification(kodiUtilities.getString(32165), s) else: kodiUtilities.notification(kodiUtilities.getString(32166), s) elif utilities.isShow(media_type): summaryInfo = {'shows': [{'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0]}]} s = utilities.getFormattedItemName(media_type, data) logger.debug("doAddToWatchlist(): %s" % str(summaryInfo)) result = globals.traktapi.addToWatchlist(summaryInfo) if result: kodiUtilities.notification(kodiUtilities.getString(32165), s) else: kodiUtilities.notification(kodiUtilities.getString(32166), s)
def doMarkWatched(self, data): media_type = data['media_type'] if utilities.isMovie(media_type): summaryInfo = globals.traktapi.getMovieSummary( data['id']).to_dict() if summaryInfo: if not summaryInfo['watched']: s = utilities.getFormattedItemName(media_type, summaryInfo) logger.debug( "doMarkWatched(): '%s' is not watched on Trakt, marking it as watched." % s) params = {'movies': [summaryInfo]} logger.debug("doMarkWatched(): %s" % str(params)) result = globals.traktapi.addToHistory(params) if result: kodiUtilities.notification( kodiUtilities.getString(32113), s) else: kodiUtilities.notification( kodiUtilities.getString(32114), s) elif utilities.isEpisode(media_type): summaryInfo = { 'shows': [{ 'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0], 'seasons': [{ 'number': data['season'], 'episodes': [{ 'number': data['number'] }] }] }] } logger.debug("doMarkWatched(): %s" % str(summaryInfo)) s = utilities.getFormattedItemName(media_type, data) result = globals.traktapi.addToHistory(summaryInfo) if result: kodiUtilities.notification(kodiUtilities.getString(32113), s) else: kodiUtilities.notification(kodiUtilities.getString(32114), s) elif utilities.isSeason(media_type): summaryInfo = { 'shows': [{ 'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0], 'seasons': [{ 'number': data['season'], 'episodes': [] }] }] } s = utilities.getFormattedItemName(media_type, data) for ep in data['episodes']: summaryInfo['shows'][0]['seasons'][0]['episodes'].append( {'number': ep}) logger.debug( "doMarkWatched(): '%s - Season %d' has %d episode(s) that are going to be marked as watched." % (data['id'], data['season'], len(summaryInfo['shows'][0]['seasons'][0]['episodes']))) if len(summaryInfo['shows'][0]['seasons'][0]['episodes']) > 0: logger.debug("doMarkWatched(): %s" % str(summaryInfo)) result = globals.traktapi.addToHistory(summaryInfo) if result: kodiUtilities.notification( kodiUtilities.getString(32113), kodiUtilities.getString(32115) % (result['added']['episodes'], s)) else: kodiUtilities.notification(kodiUtilities.getString(32114), s) elif utilities.isShow(media_type): summaryInfo = { 'shows': [{ 'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0], 'seasons': [] }] } if summaryInfo: s = utilities.getFormattedItemName(media_type, data) logger.debug('data: %s' % data) for season in data['seasons']: episodeJson = [] for episode in data['seasons'][season]: episodeJson.append({'number': episode}) summaryInfo['shows'][0]['seasons'].append({ 'number': season, 'episodes': episodeJson }) if len(summaryInfo['shows'][0]['seasons'][0]['episodes']) > 0: logger.debug("doMarkWatched(): %s" % str(summaryInfo)) result = globals.traktapi.addToHistory(summaryInfo) if result: kodiUtilities.notification( kodiUtilities.getString(32113), kodiUtilities.getString(32115) % (result['added']['episodes'], s)) else: kodiUtilities.notification( kodiUtilities.getString(32114), s)
def rateMedia(media_type, itemsToRate, unrate=False, rating=None): """Launches the rating dialog""" for summary_info in itemsToRate: if not utilities.isValidMediaType(media_type): logger.debug("Not a valid media type") return elif 'user' not in summary_info: logger.debug("No user data") return s = utilities.getFormattedItemName(media_type, summary_info) logger.debug("Summary Info %s" % summary_info) if unrate: rating = None if summary_info['user']['ratings']['rating'] > 0: rating = 0 if not rating is None: logger.debug("'%s' is being unrated." % s) __rateOnTrakt(rating, media_type, summary_info, unrate=True) else: logger.debug("'%s' has not been rated, so not unrating." % s) return rerate = kodiUtilities.getSettingAsBool('rate_rerate') if rating is not None: if summary_info['user']['ratings']['rating'] == 0: logger.debug("Rating for '%s' is being set to '%d' manually." % (s, rating)) __rateOnTrakt(rating, media_type, summary_info) else: if rerate: if not summary_info['user']['ratings']['rating'] == rating: logger.debug("Rating for '%s' is being set to '%d' manually." % (s, rating)) __rateOnTrakt(rating, media_type, summary_info) else: kodiUtilities.notification(kodiUtilities.getString(32043), s) logger.debug("'%s' already has a rating of '%d'." % (s, rating)) else: kodiUtilities.notification(kodiUtilities.getString(32041), s) logger.debug("'%s' is already rated." % s) return if summary_info['user']['ratings'] and summary_info['user']['ratings']['rating']: if not rerate: logger.debug("'%s' has already been rated." % s) kodiUtilities.notification(kodiUtilities.getString(32041), s) return else: logger.debug("'%s' is being re-rated." % s) xbmc.executebuiltin('Dialog.Close(all, true)') gui = RatingDialog( "script-trakt-RatingDialog.xml", __addon__.getAddonInfo('path'), media_type=media_type, media=summary_info, rerate=rerate ) gui.doModal() if gui.rating: rating = gui.rating if rerate: rating = gui.rating if summary_info['user']['ratings'] and summary_info['user']['ratings']['rating'] > 0 and rating == summary_info['user']['ratings']['rating']: rating = 0 if rating == 0 or rating == "unrate": __rateOnTrakt(rating, gui.media_type, gui.media, unrate=True) else: __rateOnTrakt(rating, gui.media_type, gui.media) else: logger.debug("Rating dialog was closed with no rating.") del gui #Reset rating and unrate for multi part episodes unrate=False rating=None
def get_pin(): AUTH_BUTTON = 200 LATER_BUTTON = 201 NEVER_BUTTON = 202 ACTION_PREVIOUS_MENU = 10 ACTION_BACK = 92 INSTRUCTION_LABEL = 203 CENTER_Y = 6 CENTER_X = 2 logger = logging.getLogger(__name__) class PinAuthDialog(xbmcgui.WindowXMLDialog): auth = False def onInit(self): self.pin_edit_control = self.__add_editcontrol(30, 240, 40, 450) self.setFocus(self.pin_edit_control) auth = self.getControl(AUTH_BUTTON) never = self.getControl(NEVER_BUTTON) instuction = self.getControl(INSTRUCTION_LABEL) instuction.setLabel( "1) " + getString(32159).format("[COLOR red]http://trakt.tv/pin/999[/COLOR]") + "\n2) " + getString(32160) + "\n3) " + getString(32161) + "\n\n" + getString(32162)) self.pin_edit_control.controlUp(never) self.pin_edit_control.controlLeft(never) self.pin_edit_control.controlDown(auth) self.pin_edit_control.controlRight(auth) auth.controlUp(self.pin_edit_control) auth.controlLeft(self.pin_edit_control) never.controlDown(self.pin_edit_control) never.controlRight(self.pin_edit_control) def onAction(self, action): #print 'Action: %s' % (action.getId()) if action == ACTION_PREVIOUS_MENU or action == ACTION_BACK: self.close() def onControl(self, control): #print 'onControl: %s' % (control) pass def onFocus(self, control): #print 'onFocus: %s' % (control) pass def onClick(self, control): #print 'onClick: %s' % (control) logger.debug('onClick: %s' % (control)) if control == AUTH_BUTTON: if not self.__get_token(): logger.debug("Authentification error") notification(getString(32157), getString(32147), 5000) return self.auth = True if control == LATER_BUTTON: notification(getString(32157), getString(32150), 5000) setSetting('last_reminder', str(int(time.time()))) if control == NEVER_BUTTON: notification(getString(32157), getString(32151), 5000) setSetting('last_reminder', '-1') if control in [AUTH_BUTTON, LATER_BUTTON, NEVER_BUTTON]: self.close() def __get_token(self): pin = self.pin_edit_control.getText().strip() if pin: try: if traktapi.traktAPI().authenticate(pin): return True except: return False return False # have to add edit controls programatically because getControl() (hard) crashes XBMC on them def __add_editcontrol(self, x, y, height, width): media_path = os.path.join(__addon__.getAddonInfo('path'), 'resources', 'skins', 'Default', 'media') temp = xbmcgui.ControlEdit(0, 0, 0, 0, '', font='font12', textColor='0xFFFFFFFF', focusTexture=os.path.join(media_path, 'button-focus2.png'), noFocusTexture=os.path.join(media_path, 'button-nofocus.png'), _alignment=CENTER_Y | CENTER_X) temp.setPosition(x, y) temp.setHeight(height) temp.setWidth(width) self.addControl(temp) return temp dialog = PinAuthDialog('script-trakt-PinAuthDialog.xml', __addon__.getAddonInfo('path')) dialog.doModal() if dialog.auth: notification(getString(32157), getString(32152), 3000) del dialog
def doAddToWatchlist(self, data): media_type = data['media_type'] if utilities.isMovie(media_type): summaryInfo = globals.traktapi.getMovieSummary( data['id']).to_dict() if summaryInfo: s = utilities.getFormattedItemName(media_type, summaryInfo) logger.debug( "doAddToWatchlist(): '%s' trying to add to users watchlist." % s) params = {'movies': [summaryInfo]} logger.debug("doAddToWatchlist(): %s" % str(params)) result = globals.traktapi.addToWatchlist(params) if result: kodiUtilities.notification(kodiUtilities.getString(32165), s) else: kodiUtilities.notification(kodiUtilities.getString(32166), s) elif utilities.isEpisode(media_type): summaryInfo = { 'shows': [{ 'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0], 'seasons': [{ 'number': data['season'], 'episodes': [{ 'number': data['number'] }] }] }] } logger.debug("doAddToWatchlist(): %s" % str(summaryInfo)) s = utilities.getFormattedItemName(media_type, data) result = globals.traktapi.addToWatchlist(summaryInfo) if result: kodiUtilities.notification(kodiUtilities.getString(32165), s) else: kodiUtilities.notification(kodiUtilities.getString(32166), s) elif utilities.isSeason(media_type): summaryInfo = { 'shows': [{ 'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0], 'seasons': [{ 'number': data['season'] }] }] } s = utilities.getFormattedItemName(media_type, data) logger.debug( "doAddToWatchlist(): '%s - Season %d' trying to add to users watchlist." % (data['id'], data['season'])) result = globals.traktapi.addToWatchlist(summaryInfo) if result: kodiUtilities.notification(kodiUtilities.getString(32165), s) else: kodiUtilities.notification(kodiUtilities.getString(32166), s) elif utilities.isShow(media_type): summaryInfo = { 'shows': [{ 'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0] }] } s = utilities.getFormattedItemName(media_type, data) logger.debug("doAddToWatchlist(): %s" % str(summaryInfo)) result = globals.traktapi.addToWatchlist(summaryInfo) if result: kodiUtilities.notification(kodiUtilities.getString(32165), s) else: kodiUtilities.notification(kodiUtilities.getString(32166), s)
def __rateOnTrakt(rating, media_type, media, unrate=False): logger.debug("Sending rating (%s) to Trakt.tv" % rating) params = media if utilities.isMovie(media_type): key = 'movies' params['rating'] = rating if 'movieid' in media: kodiUtilities.kodiJsonRequest({ "jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetMovieDetails", "params": { "movieid": media['movieid'], "userrating": rating } }) elif utilities.isShow(media_type): key = 'shows' params['rating'] = rating if 'tvshowid' in media: kodiUtilities.kodiJsonRequest({ "jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetTVShowDetails", "params": { "tvshowid": media['tvshowid'], "userrating": rating } }) elif utilities.isSeason(media_type): key = 'shows' params['seasons'] = [{'rating': rating, 'number': media['season']}] elif utilities.isEpisode(media_type): key = 'episodes' params['rating'] = rating if 'episodeid' in media: kodiUtilities.kodiJsonRequest({ "jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetEpisodeDetails", "params": { "episodeid": media['episodeid'], "userrating": rating } }) else: return root = {key: [params]} if not unrate: data = globals.traktapi.addRating(root) else: data = globals.traktapi.removeRating(root) if data: s = utilities.getFormattedItemName(media_type, media) if 'not_found' in data and not data['not_found']['movies'] and not data[ 'not_found']['episodes'] and not data['not_found']['shows']: if not unrate: kodiUtilities.notification(kodiUtilities.getString(32040), s) else: kodiUtilities.notification(kodiUtilities.getString(32042), s) else: kodiUtilities.notification(kodiUtilities.getString(32044), s)