Exemple #1
0
def rateOnTrakt(rating, media_type, media):
	Debug('[rating] Sending rating (%s) to trakt' % rating)
	if media_type == 'movie':
		params = {'title': media['title'], 'year': media['year'], 'rating': rating}

		if media['imdbnumber'].startswith('tt'):
			params['imdb_id'] = media['imdbnumber']

		elif media['imdbnumber'].isdigit():
			params['tmdb_id'] = media['imdbnumber']

		data = globals.traktapi.rateMovie(params)

	else:
		params = {'title': media['label'], 'year': media['year'], 'season': media['episode']['season'], 'episode': media['episode']['episode'], 'rating': rating}

		if media['imdbnumber'].isdigit():
			params['tvdb_id'] = media['imdbnumber']

		elif media['imdbnumber'].startswith('tt'):
			params['imdb_id'] = media['imdbnumber']

		data = globals.traktapi.rateEpisode(params)

	if data != None:
		notification(__language__(1201).encode('utf-8', 'ignore'), __language__(1167).encode('utf-8', 'ignore')) # Rating submitted successfully
Exemple #2
0
	def scrobbleNotification(self, info):
		if not self.curVideoInfo:
			return
		
		if utilities.getSettingAsBool("scrobble_notification"):
			s = utilities.getFormattedItemName(self.curVideo['type'], info)
			utilities.notification(utilities.getString(1049), s)
Exemple #3
0
def rateOnTrakt(rating, media_type, media):
	Debug("[Rating] Sending rating (%s) to trakt.tv" % rating)
	if utilities.isMovie(media_type):
		params = {}
		params['title'] = media['title']
		params['year'] = media['year']
		params['rating'] = rating
		params['tmdb_id'] = media['tmdb_id']
		params['imdb_id'] = media['imdb_id']

		data = globals.traktapi.rateMovie(params)

	elif utilities.isEpisode(media_type):
		params = {}
		params['title'] = media['show']['title']
		params['year'] = media['show']['year']
		params['season'] = media['episode']['season']
		params['episode'] = media['episode']['number']
		params['rating'] = rating
		params['tvdb_id'] = media['show']['tvdb_id']
		params['imdb_id'] = media['show']['imdb_id']

		data = globals.traktapi.rateEpisode(params)

	else:
		return

	if data != None:
		notification(utilities.getString(1201), utilities.getString(1167)) # Rating submitted successfully
Exemple #4
0
    def testAccount(self, force=False):

        if self.__username == "":
            notification('trakt', getString(
                1106))  # please enter your Username and Password in settings
            setSetting('account_valid', False)
            return False
        elif self.__password == "":
            notification(
                "trakt",
                getString(1107))  # please enter your Password in settings
            setSetting('account_valid', False)
            return False

        if not getSettingAsBool('account_valid') or force:
            Debug("[traktAPI] Testing account '%s'." % self.__username)

            url = "%s/account/test/%s" % (self.__baseURL, self.__apikey)
            Debug("[traktAPI] testAccount(url: %s)" % url)

            args = json.dumps({
                'username': self.__username,
                'password': self.__password
            })
            response = None

            try:
                # get data from trakt.tv
                response = self.__getData(url, args)
            except traktError, e:
                if isinstance(e, traktAuthProblem):
                    Debug(
                        "[traktAPI] testAccount(): Account '%s' failed authentication. (%s)"
                        % (self.__username, e.value))
                elif isinstance(e, traktServerBusy):
                    Debug("[traktAPI] testAccount(): Server Busy (%s)" %
                          e.value)
                elif isinstance(e, traktNetworkError):
                    Debug("[traktAPI] testAccount(): Network error: %s" %
                          e.value)
                elif isinstance(e, traktUnknownError):
                    Debug("[traktAPI] testAccount(): Other problem (%s)" %
                          e.value)
                else:
                    pass

            if response:
                data = None
                try:
                    data = json.loads(response)
                except ValueError:
                    pass

                if 'status' in data:
                    if data['status'] == 'success':
                        setSetting('account_valid', True)
                        Debug(
                            "[traktAPI] testAccount(): Account '%s' is valid."
                            % self.__username)
                        return True
Exemple #5
0
	def rateOnTrakt(self, rating):
		if self.media_type == 'movie':
			params = {'title': self.media['title'], 'year': self.media['year'], 'rating': rating}

			if self.media['imdbnumber'].startswith('tt'):
				params['imdb_id'] = self.media['imdbnumber']

			elif self.media['imdbnumber'].isdigit():
				params['tmdb_id']

			data = traktJsonRequest('POST', '/rate/movie/%%API_KEY%%', params, passVersions=True)

		else:
			params = {'title': self.media['label'], 'year': self.media['year'], 'season': self.media['episode']['season'], 'episode': self.media['episode']['episode'], 'rating': rating}

			if self.media['imdbnumber'].isdigit():
				params['tvdb_id'] = self.media['imdbnumber']

			elif self.media['imdbnumber'].startswith('tt'):
				params['imdb_id'] = self.media['imdbnumber']

			data = traktJsonRequest('POST', '/rate/episode/%%API_KEY%%', params, passVersions=True)

		if data != None:
			notification(__language__(1201).encode('utf-8', 'ignore'), __language__(1167).encode('utf-8', 'ignore')) # Rating submitted successfully
Exemple #6
0
    def Run(self):
        if not self.show_progress and __setting__("sync_on_update") == "true" and self.notify:
            notification("%s %s" % (__getstring__(1400), __getstring__(1402)), __getstring__(1420))  # Sync started

        self.GetFromXBMC()

        if not self.Canceled() and add_movies_to_trakt:
            self.GetFromTraktCollection()
            self.AddToTrakt()

        if trakt_movie_playcount or xbmc_movie_playcount:
            if not self.Canceled():
                self.GetFromTraktSeen()

        if not self.Canceled() and trakt_movie_playcount:
            self.UpdatePlaysTrakt()

        if not self.Canceled() and xbmc_movie_playcount:
            self.UpdatePlaysXBMC()

        if not self.Canceled() and clean_trakt_movies:
            if not add_movies_to_trakt:
                self.GetFromTraktCollection()
            if not self.Canceled():
                self.RemoveFromTrakt()

        if not self.Canceled() and self.show_progress:
            progress.update(100, line1=__getstring__(1431), line2=" ", line3=" ")
            progress.close()

        if not self.show_progress and __setting__("sync_on_update") == "true" and self.notify:
            notification("%s %s" % (__getstring__(1400), __getstring__(1402)), __getstring__(1421))  # Sync complete

        Debug("[Movies Sync] Complete")
    def __scrobbleNotification(self, info):
        if not self.curVideoInfo:
            return

        if utilities.getSettingAsBool("scrobble_notification"):
            s = utilities.getFormattedItemName(self.curVideo["type"], info[self.curVideo["type"]])
            utilities.notification(utilities.getString(32015), s)
Exemple #8
0
    def scrobbleNotification(self, info):
        if not self.curVideoInfo:
            return

        if utilities.getSettingAsBool("scrobble_notification"):
            s = utilities.getFormattedItemName(self.curVideo['type'], info)
            utilities.notification(utilities.getString(1049), 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' % (utilities.getString(32045), utilities.getString(32050)), utilities.getString(32061))  # Sync started
        if self.sync.show_progress and not self.sync.run_silent:
            progress.create("%s %s" % (utilities.getString(32045), utilities.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

        # we need a correct runtime for episodes until we have that this is commented out
        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)

        # we need a correct runtime for episodes until we have that this is commented out
        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' % (utilities.getString(32045), utilities.getString(32050)), utilities.getString(32062))  # Sync complete

        if self.sync.show_progress and not self.sync.run_silent:
            self.sync.UpdateProgress(100, line1=" ", line2=utilities.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.")
Exemple #10
0
    def __syncMovies(self):
        if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
            notification(
                '%s %s' %
                (utilities.getString(32045), utilities.getString(32046)),
                utilities.getString(32061))  #Sync started
        if self.show_progress and not self.run_silent:
            progress.create(
                "%s %s" %
                (utilities.getString(32045), utilities.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 self.show_progress and not self.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 self.show_progress and not self.run_silent:
                progress.close()
            return

        self.__addMoviesToTraktCollection(kodiMovies, traktMovies)

        self.__deleteMoviesFromTraktCollection(traktMovies, kodiMovies)

        self.__addMoviesToTraktWatched(kodiMovies, traktMovies)

        self.__addMoviesToKodiWatched(traktMovies, kodiMovies)

        if self.show_progress and not self.run_silent:
            self.__updateProgress(100,
                                  line1=utilities.getString(32066),
                                  line2=" ",
                                  line3=" ")
            progress.close()

        if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
            notification(
                '%s %s' %
                (utilities.getString(32045), utilities.getString(32046)),
                utilities.getString(32062))  #Sync complete

        logger.debug(
            "[Movies Sync] Movies on trakt.tv (%d), movies in Kodi (%d)." %
            (self.__countMovies(traktMovies), len(kodiMovies)))
        logger.debug("[Movies Sync] Complete.")
Exemple #11
0
    def Run(self):
        if not self.show_progress and __setting__(
                'sync_on_update') == 'true' and self.notify:
            notification('%s %s' % (__getstring__(1400), __getstring__(1406)),
                         __getstring__(1420))  #Sync started

        self.GetFromXBMC()

        # sanity check, test for non-empty xbmc movie list
        if self.xbmc_shows:

            if not self.Canceled() and add_episodes_to_trakt:
                self.GetCollectionFromTrakt()
                if not self.Canceled():
                    self.AddToTrakt()

            if trakt_episode_playcount or xbmc_episode_playcount:
                if not self.Canceled():
                    self.GetWatchedFromTrakt()

            if not self.Canceled() and trakt_episode_playcount:
                self.UpdatePlaysTrakt()

            if xbmc_episode_playcount:
                if not self.Canceled():
                    self.UpdatePlaysXBMC()

            if clean_trakt_episodes:
                if not self.Canceled() and not add_episodes_to_trakt:
                    self.GetCollectionFromTrakt()
                if not self.Canceled():
                    self.RemoveFromTrakt()

        else:
            Debug(
                "[Episodes Sync] XBMC Show list is empty, aborting Episodes Sync."
            )

        if not self.show_progress and __setting__(
                'sync_on_update') == 'true' and self.notify:
            notification('%s %s' % (__getstring__(1400), __getstring__(1406)),
                         __getstring__(1421))  #Sync complete

        if not self.Canceled() and self.show_progress:
            progress.update(100,
                            line1=__getstring__(1442),
                            line2=' ',
                            line3=' ')
            progress.close()

        Debug('[Episodes Sync] Complete')
Exemple #12
0
	def __syncEpisodes(self):
		if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
			notification('%s %s' % (utilities.getString(1400), utilities.getString(1406)), utilities.getString(1420)) #Sync started
		if self.show_progress and not self.run_silent:
			progress.create("%s %s" % (utilities.getString(1400), utilities.getString(1406)), line1=" ", line2=" ", line3=" ")

		kodiShows = self.__kodiLoadShows()
		if not isinstance(kodiShows, list) and not kodiShows:
			Debug("[Episodes Sync] Kodi show list is empty, aborting tv show Sync.")
			if self.show_progress and not self.run_silent:
				progress.close()
			return

		traktShows = self.__traktLoadShows()
		if not isinstance(traktShows['shows'], list):
			Debug("[Episodes Sync] Error getting trakt.tv show list, aborting tv show sync.")
			if self.show_progress and not self.run_silent:
				progress.close()
			return

		if utilities.getSettingAsBool('clean_trakt_episodes') and not self.__isCanceled():
			traktShowsRemove = self.__compareShows(traktShows, kodiShows)
			self.__traktRemoveEpisodes(traktShowsRemove)
		
		if utilities.getSettingAsBool('trakt_episode_playcount') and not self.__isCanceled():
			traktShowsUpdate = self.__compareShows(kodiShows, traktShows, watched=True)
			self.__traktUpdateEpisodes(traktShowsUpdate)

		if utilities.getSettingAsBool('kodi_episode_playcount') and not self.__isCanceled():
			kodiShowsUpadate = self.__compareShows(traktShows, kodiShows, watched=True, restrict=True)
			self.__kodiUpdateEpisodes(kodiShowsUpadate)

		if utilities.getSettingAsBool('add_episodes_to_trakt') and not self.__isCanceled():
			traktShowsAdd = self.__compareShows(kodiShows, traktShows)
			self.__traktAddEpisodes(traktShowsAdd)

		if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
			notification('%s %s' % (utilities.getString(1400), utilities.getString(1406)), utilities.getString(1421)) #Sync complete

		if not self.__isCanceled() and self.show_progress and not self.run_silent:
			self.__updateProgress(100, line1=" ", line2=utilities.getString(1442), line3=" ")
			progress.close()

		Debug("[Episodes Sync] Shows on trakt.tv (%d), shows in Kodi (%d)." % (len(traktShows['shows']), len(kodiShows['shows'])))

		Debug("[Episodes Sync] Episodes on trakt.tv (%d), episodes in Kodi (%d)." % (self.__countEpisodes(traktShows), self.__countEpisodes(kodiShows)))
		Debug("[Episodes Sync] Complete.")
Exemple #13
0
	def testAccount(self, force=False):
		
		if self.__username == "":
			notification('trakt', getString(1106)) # please enter your Username and Password in settings
			setSetting('account_valid', False)
			return False
		elif self.__password == "":
			notification("trakt", getString(1107)) # please enter your Password in settings
			setSetting('account_valid', False)
			return False

		if not getSettingAsBool('account_valid') or force:
			Debug("[traktAPI] Testing account '%s'." % self.__username)

			url = "%s/account/test/%s" % (self.__baseURL, self.__apikey)
			Debug("[traktAPI] testAccount(url: %s)" % url)
			
			args = json.dumps({'username': self.__username, 'password': self.__password})
			response = None
			
			try:
				# get data from trakt.tv
				response = self.__getData(url, args)
			except traktError, e:
				if isinstance(e, traktAuthProblem):
					Debug("[traktAPI] testAccount(): Account '%s' failed authentication. (%s)" % (self.__username, e.value))
				elif isinstance(e, traktServerBusy):
					Debug("[traktAPI] testAccount(): Server Busy (%s)" % e.value)
				elif isinstance(e, traktNetworkError):
					Debug("[traktAPI] testAccount(): Network error: %s" % e.value)
				elif isinstance(e, traktUnknownError):
					Debug("[traktAPI] testAccount(): Other problem (%s)" % e.value)
				else:
					pass
			
			if response:
				data = None
				try:
					data = json.loads(response)
				except ValueError:
					pass

				if 'status' in data:
					if data['status'] == 'success':
						setSetting('account_valid', True)
						Debug("[traktAPI] testAccount(): Account '%s' is valid." % self.__username)
						return True
Exemple #14
0
	def syncEpisodes(self):
		if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
			notification('%s %s' % (utilities.getString(1400), utilities.getString(1406)), utilities.getString(1420)) #Sync started
		if self.show_progress and not self.run_silent:
			progress.create("%s %s" % (utilities.getString(1400), utilities.getString(1406)), line1=" ", line2=" ", line3=" ")

		xbmcShows = self.xbmcLoadShows()
		if not isinstance(xbmcShows, list) and not xbmcShows:
			Debug("[Episodes Sync] XBMC show list is empty, aborting tv show Sync.")
			if self.show_progress and not self.run_silent:
				progress.close()
			return

		traktShows = self.traktLoadShows()
		if not isinstance(traktShows, list):
			Debug("[Episodes Sync] Error getting trakt.tv show list, aborting tv show sync.")
			if self.show_progress and not self.run_silent:
				progress.close()
			return

		if utilities.getSettingAsBool('add_episodes_to_trakt') and not self.isCanceled():
			traktShowsAdd = self.compareShows(xbmcShows, traktShows)
			self.traktAddEpisodes(traktShowsAdd)
		
		if utilities.getSettingAsBool('trakt_episode_playcount') and not self.isCanceled():
			traktShowsUpdate = self.compareShows(xbmcShows, traktShows, watched=True)
			self.traktUpdateEpisodes(traktShowsUpdate)

		if utilities.getSettingAsBool('xbmc_episode_playcount') and not self.isCanceled():
			xbmcShowsUpadate = self.compareShows(traktShows, xbmcShows, watched=True, restrict=True)
			self.xbmcUpdateEpisodes(xbmcShowsUpadate)

		if utilities.getSettingAsBool('clean_trakt_episodes') and not self.isCanceled():
			traktShowsRemove = self.compareShows(traktShows, xbmcShows)
			self.traktRemoveEpisodes(traktShowsRemove)

		if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
			notification('%s %s' % (utilities.getString(1400), utilities.getString(1406)), utilities.getString(1421)) #Sync complete

		if not self.isCanceled() and self.show_progress and not self.run_silent:
			self.updateProgress(100, line1=" ", line2=utilities.getString(1442), line3=" ")
			progress.close()

		Debug("[Episodes Sync] Shows on trakt.tv (%d), shows in XBMC (%d)." % (len(utilities.findAllInList(traktShows, 'in_collection', True)), len(xbmcShows)))
		Debug("[Episodes Sync] Episodes on trakt.tv (%d), episodes in XBMC (%d)." % (self.countEpisodes(traktShows), self.countEpisodes(xbmcShows)))
		Debug("[Episodes Sync] Complete.")
Exemple #15
0
	def syncMovies(self):
		if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
			notification('%s %s' % (utilities.getString(1400), utilities.getString(1402)), utilities.getString(1420)) #Sync started
		if self.show_progress and not self.run_silent:
			progress.create("%s %s" % (utilities.getString(1400), utilities.getString(1402)), line1=" ", line2=" ", line3=" ")

		xbmcMovies = self.xbmcLoadMovies()
		if not isinstance(xbmcMovies, list) and not xbmcMovies:
			Debug("[Movies Sync] XBMC movie list is empty, aborting movie Sync.")
			if self.show_progress and not self.run_silent:
				progress.close()
			return

		traktMovies = self.traktLoadMovies()
		if not isinstance(traktMovies, list):
			Debug("[Movies Sync] Error getting trakt.tv movie list, aborting movie Sync.")
			if self.show_progress and not self.run_silent:
				progress.close()
			return

		if utilities.getSettingAsBool('add_movies_to_trakt') and not self.isCanceled():
			traktMoviesToAdd = self.compareMovies(xbmcMovies, traktMovies)
			self.traktAddMovies(traktMoviesToAdd)
		
		if utilities.getSettingAsBool('trakt_movie_playcount') and not self.isCanceled():
			traktMoviesToUpdate = self.compareMovies(xbmcMovies, traktMovies, watched=True)
			self.traktUpdateMovies(traktMoviesToUpdate)

		if utilities.getSettingAsBool('xbmc_movie_playcount') and not self.isCanceled():
			xbmcMoviesToUpdate = self.compareMovies(traktMovies, xbmcMovies, watched=True, restrict=True)
			self.xbmcUpdateMovies(xbmcMoviesToUpdate)

		if utilities.getSettingAsBool('clean_trakt_movies') and not self.isCanceled():
			traktMoviesToRemove = self.compareMovies(traktMovies, xbmcMovies)
			self.traktRemoveMovies(traktMoviesToRemove)

		if not self.isCanceled() and self.show_progress and not self.run_silent:
			self.updateProgress(100, line1=utilities.getString(1431), line2=" ", line3=" ")
			progress.close()

		if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
			notification('%s %s' % (utilities.getString(1400), utilities.getString(1402)), utilities.getString(1421)) #Sync complete
		
		Debug("[Movies Sync] Movies on trakt.tv (%d), movies in XBMC (%d)." % (len(traktMovies), self.countMovies(xbmcMovies)))
		Debug("[Movies Sync] Complete.")
Exemple #16
0
	def __syncMovies(self):
		if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
			notification('%s %s' % (utilities.getString(1400), utilities.getString(1402)), utilities.getString(1420)) #Sync started
		if self.show_progress and not self.run_silent:
			progress.create("%s %s" % (utilities.getString(1400), utilities.getString(1402)), line1=" ", line2=" ", line3=" ")

		kodiMovies = self.__kodiLoadMovies()
		if not isinstance(kodiMovies, list) and not kodiMovies:
			Debug("[Movies Sync] Kodi movie list is empty, aborting movie Sync.")
			if self.show_progress and not self.run_silent:
				progress.close()
			return

		traktMovies = self.__traktLoadMovies()
		if not isinstance(traktMovies, list):
			Debug("[Movies Sync] Error getting trakt.tv movie list, aborting movie Sync.")
			if self.show_progress and not self.run_silent:
				progress.close()
			return

		if utilities.getSettingAsBool('clean_trakt_movies') and not self.__isCanceled():
			Debug("[Movies Sync] Starting to remove.")
			traktMoviesToRemove = self.__compareMovies(traktMovies, kodiMovies)
			Debug("[Movies Sync] Compared movies, found %s to remove." % traktMoviesToRemove)
			self.__traktRemoveMovies(traktMoviesToRemove)

		if utilities.getSettingAsBool('kodi_movie_playcount') and not self.__isCanceled():
			kodiMoviesToUpdate = self.__compareMovies(traktMovies, kodiMovies, watched=True, restrict=True)
			self.__kodiUpdateMovies(kodiMoviesToUpdate)

		if utilities.getSettingAsBool('add_movies_to_trakt') and not self.__isCanceled():
			traktMoviesToAdd = self.__compareMovies(kodiMovies, traktMovies)
			Debug("[Movies Sync] Compared movies, found %s to add." % traktMoviesToAdd)
			self.__traktAddMovies(traktMoviesToAdd)

		if not self.__isCanceled() and self.show_progress and not self.run_silent:
			self.__updateProgress(100, line1=utilities.getString(1431), line2=" ", line3=" ")
			progress.close()

		if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
			notification('%s %s' % (utilities.getString(1400), utilities.getString(1402)), utilities.getString(1421)) #Sync complete
		
		Debug("[Movies Sync] Movies on trakt.tv (%d), movies in Kodi (%d)." % (self.__countMovies(traktMovies), len(kodiMovies)))
		Debug("[Movies Sync] Complete.")
Exemple #17
0
    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' % (utilities.getString(32045), utilities.getString(32046)), utilities.getString(32061))  # Sync started
        if sync.show_progress and not sync.run_silent:
            progress.create("%s %s" % (utilities.getString(32045), utilities.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=utilities.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' % (utilities.getString(32045), utilities.getString(32046)), utilities.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.")
Exemple #18
0
    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 rate(rating, media):
    import kp, kinopoisk
    cookie=utils.get_string_setting('cookie')
    if cookie=='': cookie=None
    if not cookie:
        login=utils.get_string_setting('login')
        password=utils.get_string_setting('password')
        kpLogin=kp.Login(login,password,cookie)
        cookie=kpLogin.get_cookie()
        utils.set_string_setting('cookie', cookie)
    k=kinopoisk.KinoPoiskRuAgent()
    kpId,title,year=None,None,None
    if 'kinopoiskId' not in media:
        if 'titleAlt' in media: titles=(media['title'], media['titleAlt'])
        else: titles=(media['title'],)
        for i in titles:
            movies=k.search([],{'name':i,'year':media['year']},'English')
            if len(movies)>0:
                if movies[0][4]>90:
                    ret=0
                else:
                    items=[]
                    for i in movies: items.append('%s (%s)'%(i[1],str(i[2])))
                    ret=xbmcgui.Dialog().select('Movies:',items)
                if ret>-1:
                    kpId=movies[ret][0]
                    title=movies[ret][1].encode('utf-8')
                    year=str(movies[ret][2])
                    break
    else:
        kpId=str(media['kinopoiskId'])
        title=media['title'].encode('utf-8')
        year=str(media['year'])
    if kpId and kpId!='None':
        r_class=kp.Rate(str(rating),str(kpId), cookie)
        r=r_class.rateit()
        if r:
            utils.notification('Rated %s OK!' % (str(kpId)),'%s to %s (%s)!' %(str(rating), title, year))
            folderid=utils.get_string_setting('folderid')
            if folderid!="" and folderid>-1 and isinstance(int(folderid),int):
                r_class.moveit(int(folderid))
            return 1
Exemple #20
0
	def Run(self):
		if not self.show_progress and __setting__('sync_on_update') == 'true' and self.notify:
			notification('%s %s' % (__getstring__(1400), __getstring__(1406)), __getstring__(1420)) #Sync started

		self.GetFromXBMC()

		# sanity check, test for non-empty xbmc movie list
		if self.xbmc_shows:

			if not self.Canceled() and add_episodes_to_trakt:
				self.GetCollectionFromTrakt()
				if not self.Canceled():
					self.AddToTrakt()

			if trakt_episode_playcount or xbmc_episode_playcount:
				if not self.Canceled():
					self.GetWatchedFromTrakt()

			if not self.Canceled() and trakt_episode_playcount:
				self.UpdatePlaysTrakt()

			if xbmc_episode_playcount:
				if not self.Canceled():
					self.UpdatePlaysXBMC()

			if clean_trakt_episodes:
				if not self.Canceled() and not add_episodes_to_trakt:
					self.GetCollectionFromTrakt()
				if not self.Canceled():
					self.RemoveFromTrakt()

		else:
			Debug("[Episodes Sync] XBMC Show list is empty, aborting Episodes Sync.")

		if not self.show_progress and __setting__('sync_on_update') == 'true' and self.notify:
			notification('%s %s' % (__getstring__(1400), __getstring__(1406)), __getstring__(1421)) #Sync complete

		if not self.Canceled() and self.show_progress:
			progress.update(100, line1=__getstring__(1442), line2=' ', line3=' ')
			progress.close()

		Debug('[Episodes Sync] Complete')
Exemple #21
0
    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))
Exemple #22
0
def __rateOnTrakt(rating, media_type, media, unrate=False):
    logger.debug("Sending rating (%s) to Trakt.tv" % rating)

    params = media
    if utils.isMovie(media_type):
        key = 'movies'
        params['rating'] = rating
    elif utils.isShow(media_type):
        key = 'shows'
        params['rating'] = rating
    elif utils.isSeason(media_type):
        key = 'shows'
        params['seasons'] = [{'rating': rating, 'number': media['season']}]
    elif utils.isEpisode(media_type):
        key = 'episodes'
        params['rating'] = rating
    else:
        return
    root = {key: [params]}

    if not unrate:
        data = globals.traktapi.addRating(root)
    else:
        data = globals.traktapi.removeRating(root)

    if data:
        s = utils.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:
                utils.notification(utils.getString(32040), s)
            else:
                utils.notification(utils.getString(32042), s)
        else:
            utils.notification(utils.getString(32044), s)
Exemple #23
0
    def showContextMenu(self):
        show = self.tvshows[self.getControl(TVSHOW_LIST).getSelectedPosition()]
        li = self.getControl(TVSHOW_LIST).getSelectedItem()
        options = []
        actions = []
        if self.type != 'watchlist':
            if 'watchlist' in show:
                if show['watchlist']:
                    options.append(__language__(137).encode( "utf-8", "ignore" ))
                    actions.append('unwatchlist')
                else:
                    options.append(__language__(136).encode( "utf-8", "ignore" ))
                    actions.append('watchlist')
            else:
                options.append(__language__(136).encode( "utf-8", "ignore" ))
                actions.append('watchlist')
        else:
            options.append(__language__(137).encode( "utf-8", "ignore" ))
            actions.append('unwatchlist')
        options.append(__language__(138).encode( "utf-8", "ignore" ))
        actions.append('rate')

        select = xbmcgui.Dialog().select(show['title'], options)
        if select != -1:
            Debug("Select: " + actions[select])
        if select == -1:
            Debug ("menu quit by user")
            return
        elif actions[select] == 'play':
            xbmcgui.Dialog().ok(__language__(200).encode( "utf-8", "ignore" ), __language__(152).encode( "utf-8", "ignore" ))
        elif actions[select] == 'unwatchlist':
            if utilities.removeTVShowsFromWatchlist([show]) == None:
                utilities.notification(__language__(200).encode( "utf-8", "ignore" ), __language__(132).encode( "utf-8", "ignore" )) # Failed to remove from watch-list
            else:
                utilities.notification(__language__(200).encode( "utf-8", "ignore" ), __language__(133).encode( "utf-8", "ignore" )) # Successfully removed from watch-list
                li.setProperty('Watchlist','false')
                show['watchlist'] = False
        elif actions[select] == 'watchlist':
            if utilities.addTVShowsToWatchlist([show]) == None:
                utilities.notification(__language__(200).encode( "utf-8", "ignore" ), __language__(130).encode( "utf-8", "ignore" )) # Failed to added to watch-list
            else:
                utilities.notification(__language__(200).encode( "utf-8", "ignore" ), __language__(131).encode( "utf-8", "ignore" )) # Successfully added to watch-list
                li.setProperty('Watchlist','true')
                show['watchlist'] = True
        elif actions[select] == 'rate':
            rateShow = RateShowDialog("rate.xml", __settings__.getAddonInfo('path'), "Default")
            rateShow.initDialog(show['tvdb_id'], show['title'], show['year'], utilities.getShowRatingFromTrakt(show['tvdb_id'], show['title'], show['year']))
            rateShow.doModal()
            del rateShow
Exemple #24
0
    def showContextMenu(self):
        movie = self.movies[self.getControl(MOVIE_LIST).getSelectedPosition()]
        li = self.getControl(MOVIE_LIST).getSelectedItem()
        options = []
        actions = []
        if movie['idMovie'] != -1:
            options.append("Play")
            actions.append('play')
        if self.type != 'watchlist':
            if 'watchlist' in movie:
                if movie['watchlist']:
                    options.append(__language__(137).encode( "utf-8", "ignore" ))
                    actions.append('unwatchlist')
                else:
                    options.append(__language__(136).encode( "utf-8", "ignore" ))
                    actions.append('watchlist')
        else:
            options.append(__language__(137).encode( "utf-8", "ignore" ))
            actions.append('unwatchlist')
        options.append(__language__(138).encode( "utf-8", "ignore" ))
        actions.append('rate')

        select = xbmcgui.Dialog().select(movie['title']+" - "+str(movie['year']), options)
        if select != -1:
            Debug("Select: " + actions[select])
        if select == -1:
            Debug ("menu quit by user")
            return
        elif actions[select] == 'play':
            utilities.playMovieById(movie['idMovie'])
        elif actions[select] == 'unwatchlist':
            if utilities.removeMoviesFromWatchlist([movie]) == None:
                utilities.notification(__language__(200).encode( "utf-8", "ignore" ), __language__(132).encode( "utf-8", "ignore" )) # Failed to remove from watch-list
            else:
                utilities.notification(__language__(200).encode( "utf-8", "ignore" ), __language__(133).encode( "utf-8", "ignore" )) # Successfully removed from watch-list
                li.setProperty('Watchlist','false')
                movie['watchlist'] = False
        elif actions[select] == 'watchlist':
            if utilities.addMoviesToWatchlist([movie]) == None:
                utilities.notification(__language__(200).encode( "utf-8", "ignore" ), __language__(130).encode( "utf-8", "ignore" )) # Failed to added to watch-list
            else:
                utilities.notification(__language__(200).encode( "utf-8", "ignore" ), __language__(131).encode( "utf-8", "ignore" )) # Successfully added to watch-list
                li.setProperty('Watchlist','true')
                movie['watchlist'] = True
        elif actions[select] == 'rate':
            rating.rate_movie(imdbid=movie['imdb_id'], title=movie['title'], year=movie['year'])
Exemple #25
0
def __rateOnTrakt(rating, media_type, media, unrate=False):
    utils.Debug("[Rating] Sending rating (%s) to trakt.tv" % rating)

    params = {}

    if utils.isMovie(media_type):
        params = media
        params['rating'] = rating
        root = {}
        listing = [params]
        root['movies'] = listing

    elif utils.isShow(media_type):
        params['rating'] = rating
        params['title'] = media['title']
        params['year'] = media['year']
        params['ids'] = {}
        params['ids']['tmdb'] = media['ids']['tmdb']
        params['ids']['imdb'] = media['ids']['imdb']
        params['ids']['tvdb'] = media['ids']['tvdb']

        root = {}
        listing = [params]
        root['shows'] = listing

    elif utils.isEpisode(media_type):
        params = media
        params['rating'] = rating
        root = {}
        listing = [params]
        root['episodes'] = listing

    else:
        return

    if not unrate:
        data = globals.traktapi.addRating(root)
    else:
        data = globals.traktapi.removeRating(root)

    if data:
        utils.Debug("data rate: %s" % data)
        s = utils.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:
                utils.notification(utils.getString(1350), s)
            else:
                utils.notification(utils.getString(1352), s)
        else:
            utils.notification(utils.getString(1354), s)
Exemple #26
0
	def getToken(self):
		if not self.__username and not self.__password:
			notification('Trakt', getString(32021)) #Username and password error
		elif not self.__password:
			notification('Trakt', getString(32022)) #Password error
		else:
			# Attempt authentication (retrieve new token)
			with Trakt.configuration.http(retry=True):
				try:
					auth = Trakt['auth'].login(getSetting('username'), getSetting('password'))
					if auth:
						self.__token = auth
					else:
						logger.debug("Authentication Failure")
						notification('Trakt', getString(32025))
				except Exception as ex:
					message = createError(ex)
					logger.fatal(message)
					logger.debug("Cannot connect to server")
					notification('Trakt', getString(32023))
Exemple #27
0
def __rateOnTrakt(rating, media_type, media, unrate=False):
	logger.debug("Sending rating (%s) to Trakt.tv" % rating)

	params = {}
	

	if utils.isMovie(media_type):
		params = media
		params['rating'] = rating
		root = {}
		listing = [params]
		root['movies'] = listing

	elif utils.isShow(media_type):
		params['rating'] = rating
		params['title'] = media['title']
		params['year'] = media['year']
		params['ids'] = {}
		params['ids']['tmdb'] = media['ids']['tmdb']
		params['ids']['imdb'] = media['ids']['imdb']
		params['ids']['tvdb'] = media['ids']['tvdb']

		root = {}
		listing = [params]
		root['shows'] = listing

	elif utils.isEpisode(media_type):
		params = media
		params['rating'] = rating
		root = {}
		listing = [params]
		root['episodes'] = listing

	else:
		return

	if not unrate:
		data = globals.traktapi.addRating(root)
	else:
		data = globals.traktapi.removeRating(root)

	if data:
		s = utils.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:
				utils.notification(utils.getString(32040), s)
			else:
				utils.notification(utils.getString(32042), s)
		else:
			utils.notification(utils.getString(32044), s)
Exemple #28
0
 def getToken(self):
     if not self.__username and not self.__password:
         notification('trakt',
                      getString(32021))  #Username and password error
     elif not self.__password:
         notification('trakt', getString(32022))  #Password error
     else:
         # Attempt authentication (retrieve new token)
         with Trakt.configuration.http(retry=True):
             try:
                 auth = Trakt['auth'].login(getSetting('username'),
                                            getSetting('password'))
                 if auth:
                     self.__token = auth
                 else:
                     logger.debug("Authentication Failure")
                     notification('trakt', getString(32025))
             except Exception as ex:
                 message = createError(ex)
                 logger.fatal(message)
                 logger.debug("Cannot connect to server")
                 notification('trakt', getString(32023))
def rateOnTrakt(rating, media_type, media, unrate=False):
    utils.Debug("[Rating] Sending rating (%s) to trakt.tv" % rating)

    params = {}
    params["rating"] = rating

    if utils.isMovie(media_type):
        params["title"] = media["title"]
        params["year"] = media["year"]
        params["tmdb_id"] = media["tmdb_id"]
        params["imdb_id"] = media["imdb_id"]

        data = globals.traktapi.rateMovie(params)

    elif utils.isShow(media_type):
        params["title"] = media["title"]
        params["year"] = media["year"]
        params["tvdb_id"] = media["tvdb_id"]
        params["imdb_id"] = media["imdb_id"]

        data = globals.traktapi.rateShow(params)

    elif utils.isEpisode(media_type):
        params["title"] = media["show"]["title"]
        params["year"] = media["show"]["year"]
        params["season"] = media["episode"]["season"]
        params["episode"] = media["episode"]["number"]
        params["tvdb_id"] = media["show"]["tvdb_id"]
        params["imdb_id"] = media["show"]["imdb_id"]

        data = globals.traktapi.rateEpisode(params)

    else:
        return

    if data:
        s = utils.getFormattedItemName(media_type, media)
        if "status" in data and data["status"] == "success":
            if not unrate:
                utils.notification(utils.getString(1350), s)
            else:
                utils.notification(utils.getString(1352), s)
        elif "status" in data and data["status"] == "failure":
            utils.notification(utils.getString(1354), s)
        else:
            # status not in data, different problem, do nothing for now
            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()
Exemple #31
0
def __rateOnTrakt(rating, media_type, media, unrate=False):
    logger.debug("Sending rating (%s) to Trakt.tv" % rating)

    params = media
    if utils.isMovie(media_type):
        key = 'movies'
        params['rating'] = rating
        if 'movieid' in media:
            utils.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": media['movieid'], "userrating": rating}})
    elif utils.isShow(media_type):
        key = 'shows'
        params['rating'] = rating
        if 'tvshowid' in media:
            utils.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetTVShowDetails", "params": {"tvshowid": media['tvshowid'], "userrating": rating}})
    elif utils.isSeason(media_type):
        key = 'shows'
        params['seasons'] = [{'rating': rating, 'number': media['season']}]
    elif utils.isEpisode(media_type):
        key = 'episodes'
        params['rating'] = rating
        if 'episodeid' in media:
            utils.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 = utils.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:
                utils.notification(utils.getString(32040), s)
            else:
                utils.notification(utils.getString(32042), s)
        else:
            utils.notification(utils.getString(32044), s)
Exemple #32
0
def autostart():
    """Run when xbmc stars up, runs tv or movie sync and cleans based on user settings"""
    if utilities.checkSettings(True):
        notification_thread = ns.NotificationService()
        notification_thread.start()

        autosync_movies = __settings__.getSetting("autosync_movies")
        autosync_tv = __settings__.getSetting("autosync_tv")
        autosync_cleanmoviecollection = __settings__.getSetting("autosync_cleanmovies")
        autosync_cleantvshowcollection = __settings__.getSetting("autosync_cleantv")

        try:
            if autosync_movies == "true":
                utilities.notification(_(200), _(110))  # start sync movies

                su.sync_movies(daemon=True)

                if autosync_cleanmoviecollection == "true":
                    su.clean_movies(daemon=True)

            if xbmc.abortRequested:
                raise SystemExit()

            if autosync_tv == "true":
                utilities.notification(_(200), _(111))  # start tvshow collection update

                su.sync_tv(daemon=True)

                if autosync_cleantvshowcollection:
                    su.clean_tv(daemon=True)

            if xbmc.abortRequested:
                raise SystemExit()

            if autosync_tv == "true" or autosync_movies == "true":
                utilities.notification(_(200), _(112))  # update / sync done
        except SystemExit:
            notification_thread.abort_requested = True
            Debug("[Service] Auto sync processes aborted due to shutdown request")

        notification_thread.join()
Exemple #33
0
	def testAccount(self, force=False, daemon=True):
		
		if self.__username == "":
			notification("trakt", __language__(1106).encode("utf-8", "ignore")) # please enter your Username and Password in settings
			return False
		elif self.__password == "":
			notification("trakt", __language__(1107).encode("utf-8", "ignore")) # please enter your Password in settings
			return False

		if not self.validUser or force:
			url = "%s/account/test/%s" % (self.__baseURL, self.__apikey)
			Debug("[traktAPI] testAccount(url: %s)" % url)
			response = self.traktRequest("POST", url)
			if response:
				if response.has_key("status"):
					if response["status"] == "success":
						self.validUser = True
						return True
		else:
			return True

		notification("trakt", __language__(1110).encode("utf-8", "ignore")) # please enter your Password in settings
		return False
Exemple #34
0
def __rateOnTrakt(rating, media_type, media, unrate=False):
    logger.debug("Sending rating (%s) to Trakt.tv" % rating)

    params = media
    if utils.isMovie(media_type):
        key = 'movies'
        params['rating'] = rating
    elif utils.isShow(media_type):
        key = 'shows'
        params['rating'] = rating
    elif utils.isSeason(media_type):
        key = 'shows'
        params['seasons'] = [{'rating': rating, 'number': media['season']}]
    elif utils.isEpisode(media_type):
        key = 'episodes'
        params['rating'] = rating
    else:
        return
    root = {key: [params]}

    if not unrate:
        data = globals.traktapi.addRating(root)
    else:
        data = globals.traktapi.removeRating(root)

    if data:
        s = utils.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:
                utils.notification(utils.getString(32040), s)
            else:
                utils.notification(utils.getString(32042), s)
        else:
            utils.notification(utils.getString(32044), s)
Exemple #35
0
    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:
                        utilities.notification(utilities.getString(32113), s)
                    else:
                        utilities.notification(utilities.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:
                utilities.notification(utilities.getString(32113), s)
            else:
                utilities.notification(utilities.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:
                    utilities.notification(
                        utilities.getString(32113),
                        utilities.getString(32115) %
                        (result['added']['episodes'], s))
                else:
                    utilities.notification(utilities.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:
                        utilities.notification(
                            utilities.getString(32113),
                            utilities.getString(32115) %
                            (result['added']['episodes'], s))
                    else:
                        utilities.notification(utilities.getString(32114), s)
Exemple #36
0
    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:
                    utilities.notification(utilities.getString(32165), s)
                else:
                    utilities.notification(utilities.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:
                utilities.notification(utilities.getString(32165), s)
            else:
                utilities.notification(utilities.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:
                utilities.notification(utilities.getString(32165), s)
            else:
                utilities.notification(utilities.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:
                utilities.notification(utilities.getString(32165), s)
            else:
                utilities.notification(utilities.getString(32166), s)
    def __getData(self, url, args):
        data = None
        try:
            Debug("[myshowsAPI] __getData(): urllib2.Request(%s)" % url)

            if args == None:
                req = Request(url)
            else:
                req = Request(url, args)

            Debug("[myshowsAPI] __getData(): urllib2.urlopen()")
            t1 = time.time()
            response = urlopen(req, timeout=self.__timeout)
            t2 = time.time()

            Debug("[myshowsAPI] __getData(): response.read()")
            data = response.read()

            Debug("[myshowsAPI] __getData(): Response Code: %i" % response.getcode())
            Debug("[myshowsAPI] __getData(): Response Time: %0.2f ms" % ((t2 - t1) * 1000))
            Debug("[myshowsAPI] __getData(): Response Headers: %s" % str(response.info().dict))

        except IOError, e:
            if hasattr(e, "code"): # error 401 or 503, possibly others
                Debug("[myshowsAPI] __getData(): Error Code: %s" % str(e.code))
                
                error = {}

                # read the error document, strip newlines, this will make an html page 1 line
                error_data = e.read().replace("\n", "").replace("\r", "")

                # try to parse the data as json
                try:
                    error = json.loads(error_data)
                except ValueError:
                    Debug("[myshowsAPI] __getData(): Error data is not JSON format - %s" % error_data)
                    # manually add status, and the page data returned.
                    error["status"] = "failure"
                    error["error"] = error_data

                # add error code, and string type to error dictionary
                error["code"] = e.code
                error["type"] = "protocol"

                if e.code == 401: # authentication problem
                    # {"status":"failure","error":"failed authentication"}
                    Debug("[myshowsAPI] __getData(): Authentication Failure (%s)" % error_data)
                    # reset internal valid user
                    self.validUser = False

                elif e.code == 503: # server busy problem
                    # {"status":"failure","error":"server is over capacity"}
                    Debug("[myshowsAPI] __getData(): Server Busy (%s)" % error_data)

                else:
                    Debug("[myshowsAPI] __getData(): Other problem (%s)" % error_data)

                return json.dumps(error)
            elif hasattr(e, "reason"): # usually a read timeout, or unable to reach host
                Debug("[myshowsAPI] __getData(): Network error: %s" % str(e.reason))
                if isinstance(e.reason, socket.timeout):
                    notification("myshows", __language__(1108).encode( "utf-8", "ignore" ) + " (timeout)") # can't connect to myshows
                return '{"status":"failure","error":"%s","type":"network"}' % e.reason
            else:
                return '{"status":"failure","error":"%s"}' % e.message
Exemple #38
0
    def traktRequest(self,
                     method,
                     url,
                     args=None,
                     returnStatus=False,
                     returnOnFailure=False,
                     silent=True,
                     passVersions=False,
                     hideResponse=False):
        raw = None
        data = None
        jdata = {}
        retries = getSettingAsInt('retries')

        if args is None:
            args = {}

        if not (method == 'POST' or method == 'GET'):
            Debug("[traktAPI] traktRequest(): Unknown method '%s'." % method)
            return None

        if method == 'POST':
            # debug log before username and sha1hash are injected
            Debug("[traktAPI] traktRequest(): Request data: '%s'." %
                  str(json.dumps(args)))

            # inject username/pass into json data
            args['username'] = self.__username
            args['password'] = self.__password

            # check if plugin version needs to be passed
            if passVersions:
                args['plugin_version'] = __addonversion__
                args['media_center_version'] = xbmc.getInfoLabel(
                    'system.buildversion')
                args['media_center_date'] = xbmc.getInfoLabel(
                    'system.builddate')

            # convert to json data
            jdata = json.dumps(args)

        Debug(
            "[traktAPI] traktRequest(): Starting retry loop, maximum %i retries."
            % retries)

        # start retry loop
        for i in range(retries):
            Debug("[traktAPI] traktRequest(): (%i) Request URL '%s'" %
                  (i, url))

            # check if we are closing
            if xbmc.abortRequested:
                Debug("[traktAPI] traktRequest(): (%i) xbmc.abortRequested" %
                      i)
                break

            try:
                # get data from trakt.tv
                raw = self.__getData(url, jdata)
            except traktError, e:
                if isinstance(e, traktServerBusy):
                    Debug("[traktAPI] traktRequest(): (%i) Server Busy (%s)" %
                          (i, e.value))
                    xbmc.sleep(5000)
                elif isinstance(e, traktAuthProblem):
                    Debug(
                        "[traktAPI] traktRequest(): (%i) Authentication Failure (%s)"
                        % (i, e.value))
                    setSetting('account_valid', False)
                    notification('trakt', getString(1110))
                    return
                elif isinstance(e, traktNetworkError):
                    Debug("[traktAPI] traktRequest(): (%i) Network error: %s" %
                          (i, e.value))
                    if e.timeout:
                        notification('trakt',
                                     getString(1108) +
                                     " (timeout)")  # can't connect to trakt
                    xbmc.sleep(5000)
                elif isinstance(e, traktUnknownError):
                    Debug(
                        "[traktAPI] traktRequest(): (%i) Other problem (%s)" %
                        (i, e.value))
                else:
                    pass

                xbmc.sleep(1000)
                continue

            # check if we are closing
            if xbmc.abortRequested:
                Debug("[traktAPI] traktRequest(): (%i) xbmc.abortRequested" %
                      i)
                break

            # check that returned data is not empty
            if not raw:
                Debug("[traktAPI] traktRequest(): (%i) JSON Response empty" %
                      i)
                xbmc.sleep(1000)
                continue

            try:
                # get json formatted data
                data = json.loads(raw)
                if hideResponse:
                    Debug(
                        "[traktAPI] traktRequest(): (%i) JSON response recieved, response not logged"
                        % i)
                else:
                    Debug(
                        "[traktAPI] traktRequest(): (%i) JSON response: '%s'" %
                        (i, str(data)))
            except ValueError:
                # malformed json response
                Debug(
                    "[traktAPI] traktRequest(): (%i) Bad JSON response: '%s'" %
                    (i, raw))
                if not silent:
                    notification('trakt',
                                 getString(1109) +
                                 ": Bad response from trakt")  # Error

            # check for the status variable in JSON data
            if data and 'status' in data:
                if data['status'] == 'success':
                    break
                elif returnOnFailure and data['status'] == 'failure':
                    Debug(
                        "[traktAPI] traktRequest(): Return on error set, breaking retry."
                    )
                    break
                elif 'error' in data and data['status'] == 'failure':
                    Debug(
                        "[traktAPI] traktRequest(): (%i) JSON Error '%s' -> '%s'"
                        % (i, data['status'], data['error']))
                    xbmc.sleep(1000)
                    continue
                else:
                    pass

            # check to see if we have data, an empty array is still valid data, so check for None only
            if not data is None:
                Debug(
                    "[traktAPI] traktRequest(): Have JSON data, breaking retry."
                )
                break

            xbmc.sleep(500)
Exemple #39
0
        # handle scenario where all retries fail
        if data is None:
            Debug(
                "[traktAPI] traktRequest(): JSON Request failed, data is still empty after retries."
            )
            return None

        if 'status' in data:
            if data['status'] == 'failure':
                Debug("[traktAPI] traktRequest(): Error: %s" %
                      str(data['error']))
                if returnStatus or returnOnFailure:
                    return data
                if not silent:
                    notification('trakt',
                                 getString(1109) + ": " +
                                 str(data['error']))  # Error
                return None
            elif data['status'] == 'success':
                Debug(
                    "[traktAPI] traktRequest(): JSON request was successful.")

        return data

    # helper for onSettingsChanged
    def updateSettings(self):

        _username = getSetting('username')
        _password = sha1(getSetting('password')).hexdigest()

        if not ((self.__username == _username) and
Exemple #40
0
def rateOnTrakt(rating, media_type, media, unrate=False):
	utils.Debug("[Rating] Sending rating (%s) to trakt.tv" % rating)

	params = {}
	params['rating'] = rating

	if utils.isMovie(media_type):
		params['title'] = media['title']
		params['year'] = media['year']
		params['tmdb_id'] = media['tmdb_id']
		params['imdb_id'] = media['imdb_id']

		data = globals.traktapi.rateMovie(params)

	elif utils.isShow(media_type):
		params['title'] = media['title']
		params['year'] = media['year']
		params['tvdb_id'] = media['tvdb_id']
		params['imdb_id'] = media['imdb_id']

		data = globals.traktapi.rateShow(params)
	
	elif utils.isEpisode(media_type):
		params['title'] = media['show']['title']
		params['year'] = media['show']['year']
		params['season'] = media['episode']['season']
		params['episode'] = media['episode']['number']
		params['tvdb_id'] = media['show']['tvdb_id']
		params['imdb_id'] = media['show']['imdb_id']

		data = globals.traktapi.rateEpisode(params)

	else:
		return

	if data:
		s = utils.getFormattedItemName(media_type, media)
		if 'status' in data and data['status'] == "success":

			if tagging.isTaggingEnabled() and tagging.isRatingsEnabled():
				if utils.isMovie(media_type) or utils.isShow(media_type):

					id = media['xbmc_id']
					f = utils.getMovieDetailsFromXbmc if utils.isMovie(media_type) else utils.getShowDetailsFromXBMC
					result = f(id, ['tag'])
					
					if result:
						tags = result['tag']

						new_rating = rating
						if new_rating == "love":
							new_rating = 10
						elif new_rating == "hate":
							new_rating = 1

						new_rating_tag = tagging.ratingToTag(new_rating)
						if unrate:
							new_rating_tag = ""

						update = False
						if tagging.hasTraktRatingTag(tags):
							old_rating_tag = tagging.getTraktRatingTag(tags)
							if not old_rating_tag == new_rating_tag:
								tags.remove(old_rating_tag)
								update = True

						if not unrate and new_rating >= tagging.getMinRating():
							tags.append(new_rating_tag)
							update = True

						if update:
							tagging.xbmcSetTags(id, media_type, s, tags)

					else:
						utils.Debug("No data was returned from XBMC, aborting tag udpate.")

			if not unrate:
				utils.notification(utils.getString(1350), s)
			else:
				utils.notification(utils.getString(1352), s)
		elif 'status' in data and data['status'] == "failure":
			utils.notification(utils.getString(1354), s)
		else:
			# status not in data, different problem, do nothing for now
			pass
def get_pin():
    AUTH_BUTTON = 200
    LATER_BUTTON = 201
    NEVER_BUTTON = 202
    ACTION_PREVIOUS_MENU = 10
    ACTION_BACK = 92
    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)
            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('TraktPinAuthDialog.xml', __addon__.getAddonInfo('path'))
    dialog.doModal()
    if dialog.auth:
        notification(getString(32157), getString(32152), 3000)
    del dialog
Exemple #42
0
    def traktRequest(self,
                     method,
                     url,
                     args=None,
                     returnStatus=False,
                     returnOnFailure=False,
                     silent=True,
                     hideResponse=False):
        data = None

        retries = getSettingAsInt('retries')

        if args is None:
            args = {}

        if not (method == 'POST' or method == 'GET' or method == 'PUT'
                or method == 'DELETE'):
            Debug("[traktAPI] traktRequest(): Unknown method '%s'." % method)
            return None

        # debug log before username and token are injected
        Debug("[traktAPI] traktRequest(): Request data: '%s'." %
              str(json.dumps(args)))

        # convert to json data
        jdata = json.dumps(args)

        Debug(
            "[traktAPI] traktRequest(): Starting retry loop, maximum %i retries."
            % retries)

        # start retry loop
        for i in range(retries):
            Debug("[traktAPI] traktRequest(): (%i) Request URL '%s'" %
                  (i, url))

            # check if we are closing
            if xbmc.abortRequested:
                Debug("[traktAPI] traktRequest(): (%i) xbmc.abortRequested" %
                      i)
                break

            try:
                # get data from trakt.tv
                data = None
                try:
                    Debug("[traktAPI] __getData(): urllib2.Request(%s)" % url)

                    headers = {
                        'trakt-user-login': self.__username,
                        'trakt-user-token': self.__token,
                        'Content-type': 'application/json',
                        'trakt-api-key': self.__apikey,
                        'trakt-api-version': '2'
                    }
                    if jdata is None:
                        req = Request(url, headers)
                    else:
                        req = Request(url, jdata, headers)

                    req.get_method = lambda: method
                    Debug("[traktAPI] __getData(): urllib2.urlopen()")
                    t1 = time.time()
                    response = urlopen(req, timeout=self.__timeout)
                    t2 = time.time()

                    Debug("[traktAPI] __getData(): response.read()")
                    data = response.read()

                    Debug("[traktAPI] __getData(): Response Code: %i" %
                          response.getcode())
                    Debug("[traktAPI] __getData(): Response Time: %0.2f ms" %
                          ((t2 - t1) * 1000))
                    Debug("[traktAPI] __getData(): Response Headers: %s" %
                          str(response.info().dict))

                except BadStatusLine as e:
                    raise traktUnknownError(
                        "BadStatusLine: '%s' from URL: '%s'" % (e.line, url))
                except IOError as e:
                    if hasattr(e, 'code'):  # error 401 or 503, possibly others
                        # read the error document, strip newlines, this will make an html page 1 line
                        error_data = e.read().replace("\n",
                                                      "").replace("\r", "")

                        if e.code == 401:  # authentication problem
                            raise traktAuthProblem(error_data)
                        elif e.code == 503:  # server busy problem
                            raise traktServerBusy(error_data)
                        else:
                            try:
                                _data = json.loads(error_data)
                                if 'status' in _data:
                                    data = error_data
                            except ValueError:
                                raise traktUnknownError(error_data, e.code)

                    elif hasattr(
                            e, 'reason'
                    ):  # usually a read timeout, or unable to reach host
                        raise traktNetworkError(
                            str(e.reason), isinstance(e.reason,
                                                      socket.timeout))

                    else:
                        raise traktUnknownError(e.message)

                raw = data

            except traktError as e:
                if isinstance(e, traktServerBusy):
                    Debug("[traktAPI] traktRequest(): (%i) Server Busy (%s)" %
                          (i, e.value))
                    xbmc.sleep(5000)
                elif isinstance(e, traktAuthProblem):
                    Debug(
                        "[traktAPI] traktRequest(): (%i) Authentication Failure (%s)"
                        % (i, e.value))
                    notification('trakt', getString(1110))
                    return
                elif isinstance(e, traktNetworkError):
                    Debug("[traktAPI] traktRequest(): (%i) Network error: %s" %
                          (i, e.value))
                    if e.timeout:
                        notification('trakt',
                                     getString(1108) +
                                     " (timeout)")  # can't connect to trakt
                    xbmc.sleep(5000)
                elif isinstance(e, traktUnknownError):
                    Debug(
                        "[traktAPI] traktRequest(): (%i) Other problem (%s)" %
                        (i, e.value))
                else:
                    pass

                xbmc.sleep(1000)
                continue

            # check if we are closing
            if xbmc.abortRequested:
                Debug("[traktAPI] traktRequest(): (%i) xbmc.abortRequested" %
                      i)
                break

            # check that returned data is not empty
            if not raw:
                Debug("[traktAPI] traktRequest(): (%i) JSON Response empty" %
                      i)
                xbmc.sleep(1000)
                continue

            try:
                # get json formatted data
                data = json.loads(raw)
                if hideResponse:
                    Debug(
                        "[traktAPI] traktRequest(): (%i) JSON response recieved, response not logged"
                        % i)
                else:
                    Debug(
                        "[traktAPI] traktRequest(): (%i) JSON response: '%s'" %
                        (i, str(data)))
            except ValueError:
                # malformed json response
                Debug(
                    "[traktAPI] traktRequest(): (%i) Bad JSON response: '%s'" %
                    (i, raw))
                if not silent:
                    notification('trakt',
                                 getString(1109) +
                                 ": Bad response from trakt")  # Error

            # check for the status variable in JSON data
            if data and 'status' in data:
                if data['status'] == 'success':
                    break
                elif returnOnFailure and data['status'] == 'failure':
                    Debug(
                        "[traktAPI] traktRequest(): Return on error set, breaking retry."
                    )
                    break
                elif 'error' in data and data['status'] == 'failure':
                    Debug(
                        "[traktAPI] traktRequest(): (%i) JSON Error '%s' -> '%s'"
                        % (i, data['status'], data['error']))
                    xbmc.sleep(1000)
                    continue
                else:
                    pass

            # check to see if we have data, an empty array is still valid data, so check for None only
            if not data is None:
                Debug(
                    "[traktAPI] traktRequest(): Have JSON data, breaking retry."
                )
                break

            xbmc.sleep(500)

        # handle scenario where all retries fail
        if data is None:
            Debug(
                "[traktAPI] traktRequest(): JSON Request failed, data is still empty after retries."
            )
            return None

        if 'status' in data:
            if data['status'] == 'failure':
                Debug("[traktAPI] traktRequest(): Error: %s" %
                      str(data['error']))
                if returnStatus or returnOnFailure:
                    return data
                if not silent:
                    notification('trakt',
                                 getString(1109) + ": " +
                                 str(data['error']))  # Error
                return None
            elif data['status'] == 'success':
                Debug(
                    "[traktAPI] traktRequest(): JSON request was successful.")
        return data
Exemple #43
0
    def __syncEpisodes(self):
        if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
            notification(
                '%s %s' %
                (utilities.getString(32045), utilities.getString(32050)),
                utilities.getString(32061))  #Sync started
        if self.show_progress and not self.run_silent:
            progress.create(
                "%s %s" %
                (utilities.getString(32045), utilities.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.show_progress and not self.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.show_progress and not self.run_silent:
                progress.close()
            return

        traktShowsCollected, traktShowsWatched = self.__traktLoadShows()
        if not traktShowsCollected:
            logger.debug(
                "[Episodes Sync] Error getting trakt.tv collected show list, aborting tv show sync."
            )
            if self.show_progress and not self.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.show_progress and not self.run_silent:
                progress.close()
            return

        self.__addEpisodesToTraktCollection(kodiShowsCollected,
                                            traktShowsCollected)

        self.__deleteEpisodesFromTraktCollection(traktShowsCollected,
                                                 kodiShowsCollected)

        self.__addEpisodesToTraktWatched(kodiShowsWatched, traktShowsWatched)

        self.__addEpisodesToKodiWatched(traktShowsWatched, kodiShowsWatched,
                                        kodiShowsCollected)

        if not self.show_progress and self.sync_on_update and self.notify and self.notify_during_playback:
            notification(
                '%s %s' %
                (utilities.getString(32045), utilities.getString(32050)),
                utilities.getString(32062))  #Sync complete

        if self.show_progress and not self.run_silent:
            self.__updateProgress(100,
                                  line1=" ",
                                  line2=utilities.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.")
Exemple #44
0
				break

			xbmc.sleep(500)
		
		# handle scenario where all retries fail
		if data is None:
			Debug("[traktAPI] traktRequest(): JSON Request failed, data is still empty after retries.")
			return None
		
		if 'status' in data:
			if data['status'] == 'failure':
				Debug("[traktAPI] traktRequest(): Error: %s" % str(data['error']))
				if returnStatus or returnOnFailure:
					return data
				if not silent:
					notification('trakt', getString(1109) + ": " + str(data['error'])) # Error
				return None
			elif data['status'] == 'success':
				Debug("[traktAPI] traktRequest(): JSON request was successful.")

		return data

	# helper for onSettingsChanged
	def updateSettings(self):
	
		_username = getSetting('username')
		_password = sha1(getSetting('password')).hexdigest()
		
		if not ((self.__username == _username) and (self.__password == _password)):
			self.__username = _username
			self.__password = _password
Exemple #45
0
    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' %
                (utilities.getString(32045), utilities.getString(32046)),
                utilities.getString(32061))  # Sync started
        if sync.show_progress and not sync.run_silent:
            progress.create(
                "%s %s" %
                (utilities.getString(32045), utilities.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=utilities.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' %
                (utilities.getString(32045), utilities.getString(32046)),
                utilities.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.")
Exemple #46
0
def rateMedia(media_type, summary_info, unrate=False, rating=None):
	"""Launches the rating dialog"""
	if not utils.isValidMediaType(media_type):
		return
	
	if utils.isEpisode(media_type):
		if 'rating' in summary_info['episode']:
			summary_info['rating'] = summary_info['episode']['rating']
		if 'rating_advanced' in summary_info['episode']:
			summary_info['rating_advanced'] = summary_info['episode']['rating_advanced']

	s = utils.getFormattedItemName(media_type, summary_info)

	if not globals.traktapi.settings:
		globals.traktapi.getAccountSettings()
	rating_type = globals.traktapi.settings['viewing']['ratings']['mode']

	if unrate:
		rating = None

		if rating_type == "simple":
			if not summary_info['rating'] == "false":
				rating = "unrate"
		else:
			if summary_info['rating_advanced'] > 0:
				rating = 0

		if not rating is None:
			utils.Debug("[Rating] '%s' is being unrated." % s)
			rateOnTrakt(rating, media_type, summary_info, unrate=True)
		else:
			utils.Debug("[Rating] '%s' has not been rated, so not unrating." % s)

		return

	rerate = utils.getSettingAsBool('rate_rerate')
	if not rating is None:
		if summary_info['rating_advanced'] == 0:
			utils.Debug("[Rating] Rating for '%s' is being set to '%d' manually." % (s, rating))
			rateOnTrakt(rating, media_type, summary_info)
		else:
			if rerate:
				if not summary_info['rating_advanced'] == rating:
					utils.Debug("[Rating] Rating for '%s' is being set to '%d' manually." % (s, rating))
					rateOnTrakt(rating, media_type, summary_info)
				else:
					utils.notification(utils.getString(1353), s)
					utils.Debug("[Rating] '%s' already has a rating of '%d'." % (s, rating))
			else:
				utils.notification(utils.getString(1351), s)
				utils.Debug("[Rating] '%s' is already rated." % s)
		return

	if summary_info['rating'] or summary_info['rating_advanced']:
		if not rerate:
			utils.Debug("[Rating] '%s' has already been rated." % s)
			utils.notification(utils.getString(1351), s)
			return
		else:
			utils.Debug("[Rating] '%s' is being re-rated." % s)
	
	xbmc.executebuiltin('Dialog.Close(all, true)')

	gui = RatingDialog(
		"RatingDialog.xml",
		__addon__.getAddonInfo('path'),
		media_type=media_type,
		media=summary_info,
		rating_type=rating_type,
		rerate=rerate
	)

	gui.doModal()
	if gui.rating:
		rating = gui.rating
		if rerate:
			rating = gui.rating
			
			if rating_type == "simple":
				if not summary_info['rating'] == "false" and rating == summary_info['rating']:
					rating = "unrate"
			else:
				if summary_info['rating_advanced'] > 0 and rating == summary_info['rating_advanced']:
					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:
		utils.Debug("[Rating] Rating dialog was closed with no rating.")

	del gui
    def myshowsRequest(self, method, url, args=None, returnStatus=False, silent=True, passVersions=False, hideResponse=False):
        raw = None
        data = None
        jdata = {}
        retries = get_int_setting("retries")

        if args is None:
            args = {}

        if not (method == 'POST' or method == 'GET'):
            Debug("[myshowsAPI] myshowsRequest(): Unknown method '%s'" % method)
            return None
        
        if method == 'POST':
            # debug log before username and sha1hash are injected
            Debug("[myshowsAPI] myshowsRequest(): Request data: '%s'" % str(json.dumps(args)))
            
            # inject username/pass into json data
            args["username"] = self.__username
            args["password"] = self.__password
            
            # check if plugin version needs to be passed
            if passVersions:
                args['plugin_version'] = __addonversion__
                args['media_center_version'] = xbmc.getInfoLabel("system.buildversion")
                args['media_center_date'] = xbmc.getInfoLabel("system.builddate")
            
            # convert to json data
            jdata = json.dumps(args)

        Debug("[myshowsAPI] myshowsRequest(): Starting retry loop, maximum %i retries." % retries)
        
        # start retry loop
        for i in range(retries):    
            Debug("[myshowsAPI] myshowsRequest(): (%i) Request URL '%s'" % (i, url))
            
            # get data from myshows.tv
            raw = self.__getData(url, jdata)
            
            # check if we are closing
            if xbmc.abortRequested:
                Debug("[myshowsAPI] myshowsRequest(): (%i) xbmc.abortRequested" % i)
                break

            # check that returned data is not empty
            if not raw:
                Debug("[myshowsAPI] myshowsRequest(): (%i) JSON Response empty" % i)
                xbmc.sleep(1000)
                continue

            try:
                # get json formatted data    
                data = json.loads(raw)
                if hideResponse:
                    Debug("[myshowsAPI] myshowsRequest(): (%i) JSON response recieved, response not logged" % i)
                else:
                    Debug("[myshowsAPI] myshowsRequest(): (%i) JSON response: '%s'" % (i, str(data)))
            except ValueError:
                # malformed json response
                Debug("[myshowsAPI] myshowsRequest(): (%i) Bad JSON response: '%s'", (i, raw))
                if not silent:
                    notification("myshows", __language__(1109).encode( "utf-8", "ignore" ) + ": Bad response from myshows") # Error
                
            # check for the status variable in JSON data
            if 'status' in data:
                if data['status'] == 'success':
                    break
                else:
                    Debug("[myshowsAPI] myshowsRequest(): (%i) JSON Error '%s' -> '%s'" % (i, data['status'], data['error']))
                    if data.has_key("type"):
                        if data["type"] == "protocol":
                            # protocol error, so a 4xx or 5xx
                            if data["code"] == 401:
                                # auth error, no point retrying
                                self.validUser = False
                                return None
                            else:
                                pass
                        elif data["type"] == "network":
                            # network communication error, sleep for a
                            # bit longer before continuing
                            xbmc.sleep(5000)
                            continue
                    else:
                        #should never get here
                        pass
                    
                    xbmc.sleep(1000)
                    continue
            
            # check to see if we have data
            if data:
                Debug("[myshowsAPI] myshowsRequest(): Have JSON data, breaking retry.")
                break

            xbmc.sleep(500)
        
        # handle scenario where all retries fail
        if not data:
            Debug("[myshowsAPI] myshowsRequest(): JSON Request failed, data is still empty after retries.")
            return None
        
        if 'status' in data:
            if data['status'] == 'failure':
                Debug("[myshowsAPI] myshowsRequest(): Error: %s" % str(data['error']))
                if returnStatus:
                    return data
                if not silent:
                    notification("myshows", __language__(1109).encode( "utf-8", "ignore" ) + ": " + str(data['error'])) # Error
                return None
            elif data['status'] == 'success':
                Debug("[myshowsAPI] myshowsRequest(): JSON request was successful.")

        return data
Exemple #48
0
def rateMedia(media_type, itemsToRate, unrate=False, rating=None):
    """Launches the rating dialog"""
    for summary_info in itemsToRate:
        if not utils.isValidMediaType(media_type):
            logger.debug("Not a valid media type")
            return
        elif 'user' not in summary_info:
            logger.debug("No user data")
            return

        s = utils.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 = utils.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:
                        utils.notification(utils.getString(32043), s)
                        logger.debug("'%s' already has a rating of '%d'." %
                                     (s, rating))
                else:
                    utils.notification(utils.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)
                utils.notification(utils.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
Exemple #49
0
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')
        data['library'] = "all"
        if 'library' in args and args['library'] in ['episodes', 'movies']:
            data['library'] = args['library']

    elif args['action'] == 'loadsettings':
        data = {'action': 'loadsettings', 'force': True}
        utils.notification(utils.getString(1201), utils.getString(1111))

    elif args['action'] == 'settings':
        data = {'action': 'settings'}

    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)
Exemple #50
0
	def doMarkWatched(self, data):

		media_type = data['media_type']
		simulate = utilities.getSettingAsBool('simulate_sync')
		markedNotification = utilities.getSettingAsBool('show_marked_notification')
		
		if utilities.isMovie(media_type):
			summaryInfo = globals.traktapi.getMovieSummary(data['id'])
			if summaryInfo:
				if not summaryInfo['watched']:
					s = utilities.getFormattedItemName(media_type, summaryInfo)
					utilities.Debug("doMarkWatched(): '%s' is not watched on trakt, marking it as watched." % s)
					movie = {}
					movie['imdb_id'] = data['id']
					movie['title'] = summaryInfo['title']
					movie['year'] = summaryInfo['year']
					movie['plays'] = 1
					movie['last_played'] = int(time())
					params = {'movies': [movie]}
					utilities.Debug("doMarkWatched(): %s" % str(params))
					
					if not simulate:
						result = globals.traktapi.updateSeenMovie(params)
						if result:
							if markedNotification:
								utilities.notification(utilities.getString(1550), s)
						else:
							utilities.notification(utilities.getString(1551), s)
					else:
						if markedNotification:
							utilities.notification(utilities.getString(1550), s)
					
		elif utilities.isEpisode(media_type):
			summaryInfo = globals.traktapi.getEpisodeSummary(data['id'], data['season'], data['episode'])
			if summaryInfo:
				if not summaryInfo['episode']['watched']:
					s = utilities.getFormattedItemName(media_type, summaryInfo)
					utilities.Debug("doMarkWathced(): '%s' is not watched on trakt, marking it as watched." % s)
					params = {}
					params['imdb_id'] = summaryInfo['show']['imdb_id']
					params['tvdb_id'] = summaryInfo['show']['tvdb_id']
					params['title'] = summaryInfo['show']['title']
					params['year'] = summaryInfo['show']['year']
					params['episodes'] = [{'season': data['season'], 'episode': data['episode']}]
					utilities.Debug("doMarkWatched(): %s" % str(params))
					
					if not simulate:
						result = globals.traktapi.updateSeenEpisode(params)
						if result:
							if markedNotification:
								utilities.notification(utilities.getString(1550), s)
						else:
							utilities.notification(utilities.getString(1551), s)
					else:
						if markedNotification:
							utilities.notification(utilities.getString(1550), s)

		elif utilities.isSeason(media_type):
			showInfo = globals.traktapi.getShowSummary(data['id'])
			if not showInfo:
				return
			summaryInfo = globals.traktapi.getSeasonInfo(data['id'], data['season'])
			if summaryInfo:
				showInfo['season'] = data['season']
				s = utilities.getFormattedItemName(media_type, showInfo)
				params = {}
				params['imdb_id'] = showInfo['imdb_id']
				params['tvdb_id'] = showInfo['tvdb_id']
				params['title'] = showInfo['title']
				params['year'] = showInfo['year']
				params['episodes'] = []
				for ep in summaryInfo:
					if ep['episode'] in data['episodes']:
						if not ep['watched']:
							params['episodes'].append({'season': ep['season'], 'episode': ep['episode']})

				utilities.Debug("doMarkWatched(): '%s - Season %d' has %d episode(s) that are going to be marked as watched." % (showInfo['title'], data['season'], len(params['episodes'])))
				
				if len(params['episodes']) > 0:
					utilities.Debug("doMarkWatched(): %s" % str(params))
					if not simulate:
						result = globals.traktapi.updateSeenEpisode(params)
						if result:
							if markedNotification:
								utilities.notification(utilities.getString(1550), utilities.getString(1552) % (len(params['episodes']), s))
						else:
							utilities.notification(utilities.getString(1551), utilities.getString(1552) % (len(params['episodes']), s))
					else:
						if markedNotification:
							utilities.notification(utilities.getString(1550), utilities.getString(1552) % (len(params['episodes']), s))

		elif utilities.isShow(media_type):
			summaryInfo = globals.traktapi.getShowSummary(data['id'], extended=True)
			if summaryInfo:
				s = utilities.getFormattedItemName(media_type, summaryInfo)
				params = {}
				params['imdb_id'] = summaryInfo['imdb_id']
				params['tvdb_id'] = summaryInfo['tvdb_id']
				params['title'] = summaryInfo['title']
				params['year'] = summaryInfo['year']
				params['episodes'] = []
				for season in summaryInfo['seasons']:
					for ep in season['episodes']:
						if str(season['season']) in data['seasons']:
							if ep['episode'] in data['seasons'][str(season['season'])]:
								if not ep['watched']:
									params['episodes'].append({'season': ep['season'], 'episode': ep['episode']})
				utilities.Debug("doMarkWatched(): '%s' has %d episode(s) that are going to be marked as watched." % (summaryInfo['title'], len(params['episodes'])))

				if len(params['episodes']) > 0:
					utilities.Debug("doMarkWatched(): %s" % str(params))
					if not simulate:
						result = globals.traktapi.updateSeenEpisode(params)
						if result:
							if markedNotification:
								utilities.notification(utilities.getString(1550), utilities.getString(1552) % (len(params['episodes']), s))
						else:
							utilities.notification(utilities.getString(1551), utilities.getString(1552) % (len(params['episodes']), s))
					else:
						if markedNotification:
							utilities.notification(utilities.getString(1550), utilities.getString(1552) % (len(params['episodes']), s))
Exemple #51
0
	def traktRequest(self, method, url, args=None, returnStatus=False, returnOnFailure=False, silent=True, passVersions=False, hideResponse=False):
		raw = None
		data = None
		jdata = {}
		retries = getSettingAsInt('retries')

		if args is None:
			args = {}

		if not (method == 'POST' or method == 'GET'):
			Debug("[traktAPI] traktRequest(): Unknown method '%s'." % method)
			return None
		
		if method == 'POST':
			# debug log before username and sha1hash are injected
			Debug("[traktAPI] traktRequest(): Request data: '%s'." % str(json.dumps(args)))
			
			# inject username/pass into json data
			args['username'] = self.__username
			args['password'] = self.__password
			
			# check if plugin version needs to be passed
			if passVersions:
				args['plugin_version'] = __addonversion__
				args['media_center_version'] = xbmc.getInfoLabel('system.buildversion')
				args['media_center_date'] = xbmc.getInfoLabel('system.builddate')
			
			# convert to json data
			jdata = json.dumps(args)

		Debug("[traktAPI] traktRequest(): Starting retry loop, maximum %i retries." % retries)
		
		# start retry loop
		for i in range(retries):	
			Debug("[traktAPI] traktRequest(): (%i) Request URL '%s'" % (i, url))

			# check if we are closing
			if xbmc.abortRequested:
				Debug("[traktAPI] traktRequest(): (%i) xbmc.abortRequested" % i)
				break

			try:
				# get data from trakt.tv
				raw = self.__getData(url, jdata)
			except traktError, e:
				if isinstance(e, traktServerBusy):
					Debug("[traktAPI] traktRequest(): (%i) Server Busy (%s)" % (i, e.value))
				elif isinstance(e, traktAuthProblem):
					Debug("[traktAPI] traktRequest(): (%i) Authentication Failure (%s)" % (i, e.value))
					setSetting('account_valid', False)
					notification('trakt', getString(1110))
					return
				elif isinstance(e, traktNetworkError):
					Debug("[traktAPI] traktRequest(): (%i) Network error: %s" % (i, e.value))
					if e.timeout:
						notification('trakt', getString(1108) + " (timeout)") # can't connect to trakt
					xbmc.sleep(5000)
				elif isinstance(e, traktUnknownError):
					Debug("[traktAPI] traktRequest(): (%i) Other problem (%s)" % (i, e.value))
				else:
					pass

				xbmc.sleep(1000)
				continue

			# check if we are closing
			if xbmc.abortRequested:
				Debug("[traktAPI] traktRequest(): (%i) xbmc.abortRequested" % i)
				break

			# check that returned data is not empty
			if not raw:
				Debug("[traktAPI] traktRequest(): (%i) JSON Response empty" % i)
				xbmc.sleep(1000)
				continue

			try:
				# get json formatted data	
				data = json.loads(raw)
				if hideResponse:
					Debug("[traktAPI] traktRequest(): (%i) JSON response recieved, response not logged" % i)
				else:
					Debug("[traktAPI] traktRequest(): (%i) JSON response: '%s'" % (i, str(data)))
			except ValueError:
				# malformed json response
				Debug("[traktAPI] traktRequest(): (%i) Bad JSON response: '%s'", (i, raw))
				if not silent:
					notification('trakt', getString(1109) + ": Bad response from trakt") # Error
				
			# check for the status variable in JSON data
			if 'status' in data:
				if data['status'] == 'success':
					break
				elif returnOnFailure and data['status'] == 'failure':
					Debug("[traktAPI] traktRequest(): Return on error set, breaking retry.")
					break
				else:
					Debug("[traktAPI] traktRequest(): (%i) JSON Error '%s' -> '%s'" % (i, data['status'], data['error']))
					xbmc.sleep(1000)
					continue

			# check to see if we have data, an empty array is still valid data, so check for None only
			if not data is None:
				Debug("[traktAPI] traktRequest(): Have JSON data, breaking retry.")
				break

			xbmc.sleep(500)
Exemple #52
0
    def doMarkWatched(self, data):

        media_type = data['media_type']
        simulate = utilities.getSettingAsBool('simulate_sync')
        markedNotification = utilities.getSettingAsBool(
            'show_marked_notification')

        if utilities.isMovie(media_type):
            summaryInfo = globals.traktapi.getMovieSummary(data['id'])
            if summaryInfo:
                if not summaryInfo['watched']:
                    s = utilities.getFormattedItemName(media_type, summaryInfo)
                    utilities.Debug(
                        "doMarkWatched(): '%s' is not watched on trakt, marking it as watched."
                        % s)
                    movie = {}
                    movie['imdb_id'] = data['id']
                    movie['title'] = summaryInfo['title']
                    movie['year'] = summaryInfo['year']
                    movie['plays'] = 1
                    movie['last_played'] = int(time())
                    params = {'movies': [movie]}
                    utilities.Debug("doMarkWatched(): %s" % str(params))

                    if not simulate:
                        result = globals.traktapi.updateSeenMovie(params)
                        if result:
                            if markedNotification:
                                utilities.notification(
                                    utilities.getString(1550), s)
                        else:
                            utilities.notification(utilities.getString(1551),
                                                   s)
                    else:
                        if markedNotification:
                            utilities.notification(utilities.getString(1550),
                                                   s)

        elif utilities.isEpisode(media_type):
            summaryInfo = globals.traktapi.getEpisodeSummary(
                data['id'], data['season'], data['episode'])
            if summaryInfo:
                if not summaryInfo['episode']['watched']:
                    s = utilities.getFormattedItemName(media_type, summaryInfo)
                    utilities.Debug(
                        "doMarkWathced(): '%s' is not watched on trakt, marking it as watched."
                        % s)
                    params = {}
                    params['imdb_id'] = summaryInfo['show']['imdb_id']
                    params['tvdb_id'] = summaryInfo['show']['tvdb_id']
                    params['title'] = summaryInfo['show']['title']
                    params['year'] = summaryInfo['show']['year']
                    params['episodes'] = [{
                        'season': data['season'],
                        'episode': data['episode']
                    }]
                    utilities.Debug("doMarkWatched(): %s" % str(params))

                    if not simulate:
                        result = globals.traktapi.updateSeenEpisode(params)
                        if result:
                            if markedNotification:
                                utilities.notification(
                                    utilities.getString(1550), s)
                        else:
                            utilities.notification(utilities.getString(1551),
                                                   s)
                    else:
                        if markedNotification:
                            utilities.notification(utilities.getString(1550),
                                                   s)

        elif utilities.isSeason(media_type):
            showInfo = globals.traktapi.getShowSummary(data['id'])
            if not showInfo:
                return
            summaryInfo = globals.traktapi.getSeasonInfo(
                data['id'], data['season'])
            if summaryInfo:
                showInfo['season'] = data['season']
                s = utilities.getFormattedItemName(media_type, showInfo)
                params = {}
                params['imdb_id'] = showInfo['imdb_id']
                params['tvdb_id'] = showInfo['tvdb_id']
                params['title'] = showInfo['title']
                params['year'] = showInfo['year']
                params['episodes'] = []
                for ep in summaryInfo:
                    if ep['episode'] in data['episodes']:
                        if not ep['watched']:
                            params['episodes'].append({
                                'season': ep['season'],
                                'episode': ep['episode']
                            })

                utilities.Debug(
                    "doMarkWatched(): '%s - Season %d' has %d episode(s) that are going to be marked as watched."
                    % (showInfo['title'], data['season'],
                       len(params['episodes'])))

                if len(params['episodes']) > 0:
                    utilities.Debug("doMarkWatched(): %s" % str(params))
                    if not simulate:
                        result = globals.traktapi.updateSeenEpisode(params)
                        if result:
                            if markedNotification:
                                utilities.notification(
                                    utilities.getString(1550),
                                    utilities.getString(1552) %
                                    (len(params['episodes']), s))
                        else:
                            utilities.notification(
                                utilities.getString(1551),
                                utilities.getString(1552) %
                                (len(params['episodes']), s))
                    else:
                        if markedNotification:
                            utilities.notification(
                                utilities.getString(1550),
                                utilities.getString(1552) %
                                (len(params['episodes']), s))

        elif utilities.isShow(media_type):
            summaryInfo = globals.traktapi.getShowSummary(data['id'],
                                                          extended=True)
            if summaryInfo:
                s = utilities.getFormattedItemName(media_type, summaryInfo)
                params = {}
                params['imdb_id'] = summaryInfo['imdb_id']
                params['tvdb_id'] = summaryInfo['tvdb_id']
                params['title'] = summaryInfo['title']
                params['year'] = summaryInfo['year']
                params['episodes'] = []
                for season in summaryInfo['seasons']:
                    for ep in season['episodes']:
                        if str(season['season']) in data['seasons']:
                            if ep['episode'] in data['seasons'][str(
                                    season['season'])]:
                                if not ep['watched']:
                                    params['episodes'].append({
                                        'season':
                                        ep['season'],
                                        'episode':
                                        ep['episode']
                                    })
                utilities.Debug(
                    "doMarkWatched(): '%s' has %d episode(s) that are going to be marked as watched."
                    % (summaryInfo['title'], len(params['episodes'])))

                if len(params['episodes']) > 0:
                    utilities.Debug("doMarkWatched(): %s" % str(params))
                    if not simulate:
                        result = globals.traktapi.updateSeenEpisode(params)
                        if result:
                            if markedNotification:
                                utilities.notification(
                                    utilities.getString(1550),
                                    utilities.getString(1552) %
                                    (len(params['episodes']), s))
                        else:
                            utilities.notification(
                                utilities.getString(1551),
                                utilities.getString(1552) %
                                (len(params['episodes']), s))
                    else:
                        if markedNotification:
                            utilities.notification(
                                utilities.getString(1550),
                                utilities.getString(1552) %
                                (len(params['episodes']), s))