コード例 #1
0
ファイル: sync.py プロジェクト: Leinad4Mind/script.trakt
	def __addMoviesToKodiWatched(self, traktMovies, kodiMovies):

		if utilities.getSettingAsBool('kodi_movie_playcount') and not self.__isCanceled():
			updateKodiTraktMovies = copy.deepcopy(traktMovies)
			updateKodiKodiMovies = copy.deepcopy(kodiMovies)

			kodiMoviesToUpdate = self.__compareMovies(updateKodiTraktMovies, updateKodiKodiMovies, watched=True, restrict=True)

			if len(kodiMoviesToUpdate) == 0:
				self.__updateProgress(84, line2=utilities.getString(32088))
				logger.debug("[Movies Sync] Kodi movie playcount is up to date.")
				return

			titles = ", ".join(["%s" % (m['title']) for m in kodiMoviesToUpdate])
			logger.debug("[Movies Sync] %i movie(s) playcount will be updated in Kodi" % len(kodiMoviesToUpdate))
			logger.debug("[Movies Sync] Movies to add: %s" % titles)

			self.__updateProgress(73, line2=utilities.getString(32065) % len(kodiMoviesToUpdate))

			#split movie list into chunks of 50
			chunksize = 50
			chunked_movies = utilities.chunks([{"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": kodiMoviesToUpdate[i]['movieid'], "playcount": kodiMoviesToUpdate[i]['plays'], "lastplayed": utilities.convertUtcToDateTime(kodiMoviesToUpdate[i]['last_watched_at'])}, "id": i} for i in range(len(kodiMoviesToUpdate))], chunksize)
			i = 0
			x = float(len(kodiMoviesToUpdate))
			for chunk in chunked_movies:
				if self.__isCanceled():
					return
				i += 1
				y = ((i / x) * 11) + 73
				self.__updateProgress(int(y), line2=utilities.getString(32089) % ((i)*chunksize if (i)*chunksize < x else x, x))

				utilities.kodiJsonRequest(chunk)

			self.__updateProgress(84, line2=utilities.getString(32090) % len(kodiMoviesToUpdate))
コード例 #2
0
ファイル: sync.py プロジェクト: Leinad4Mind/script.trakt
	def __addMovieProgressToKodi(self, traktMovies, kodiMovies):

		if utilities.getSettingAsBool('trakt_movie_playback') and traktMovies and not self.__isCanceled():
			updateKodiTraktMovies = copy.deepcopy(traktMovies)
			updateKodiKodiMovies = copy.deepcopy(kodiMovies)

			kodiMoviesToUpdate = self.__compareMovies(updateKodiTraktMovies['movies'], updateKodiKodiMovies, restrict=True, playback=True)
			if len(kodiMoviesToUpdate) == 0:
				self.__updateProgress(99, line2=utilities.getString(32125))
				logger.debug("[Movies Sync] Kodi movie playbacks are up to date.")
				return

			logger.debug("[Movies Sync] %i movie(s) playbacks will be updated in Kodi" % len(kodiMoviesToUpdate))

			self.__updateProgress(85, line2=utilities.getString(32126) % len(kodiMoviesToUpdate))
			#need to calculate the progress in int from progress in percent from Trakt
			#split movie list into chunks of 50
			chunksize = 50
			chunked_movies = utilities.chunks([{"jsonrpc": "2.0", "id": i, "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": kodiMoviesToUpdate[i]['movieid'], "resume": {"position": kodiMoviesToUpdate[i]['runtime']/100.0*kodiMoviesToUpdate[i]['progress']}}} for i in range(len(kodiMoviesToUpdate))], chunksize)
			i = 0
			x = float(len(kodiMoviesToUpdate))
			for chunk in chunked_movies:
				if self.__isCanceled():
					return
				i += 1
				y = ((i / x) * 14) + 85
				self.__updateProgress(int(y), line2=utilities.getString(32127) % ((i)*chunksize if (i)*chunksize < x else x, x))
				utilities.kodiJsonRequest(chunk)

			self.__updateProgress(99, line2=utilities.getString(32128) % len(kodiMoviesToUpdate))
コード例 #3
0
ファイル: sync.py プロジェクト: mikellgonzalez/script.trakt
    def __addMoviesToKodiWatched(self, traktMovies, kodiMovies):

        if utilities.getSettingAsBool(
                'kodi_movie_playcount') and not self.__isCanceled():
            updateKodiTraktMovies = copy.deepcopy(traktMovies)
            updateKodiKodiMovies = copy.deepcopy(kodiMovies)

            kodiMoviesToUpdate = self.__compareMovies(updateKodiTraktMovies,
                                                      updateKodiKodiMovies,
                                                      watched=True,
                                                      restrict=True)

            if len(kodiMoviesToUpdate) == 0:
                self.__updateProgress(99, line2=utilities.getString(32088))
                logger.debug(
                    "[Movies Sync] Kodi movie playcount is up to date.")
                return

            titles = ", ".join(
                ["%s" % (m['title']) for m in kodiMoviesToUpdate])
            logger.debug(
                "[Movies Sync] %i movie(s) playcount will be updated in Kodi" %
                len(kodiMoviesToUpdate))
            logger.debug("[Movies Sync] Movies to add: %s" % titles)

            self.__updateProgress(83,
                                  line2=utilities.getString(32065) %
                                  len(kodiMoviesToUpdate))

            #split movie list into chunks of 50
            chunksize = 50
            chunked_movies = utilities.chunks([{
                "jsonrpc": "2.0",
                "method": "VideoLibrary.SetMovieDetails",
                "params": {
                    "movieid": kodiMoviesToUpdate[i]['movieid'],
                    "playcount": kodiMoviesToUpdate[i]['plays']
                },
                "id": i
            } for i in range(len(kodiMoviesToUpdate))], chunksize)
            i = 0
            x = float(len(kodiMoviesToUpdate))
            for chunk in chunked_movies:
                if self.__isCanceled():
                    return
                i += 1
                y = ((i / x) * 16) + 83
                self.__updateProgress(int(y),
                                      line2=utilities.getString(32089) %
                                      ((i) * chunksize if
                                       (i) * chunksize < x else x, x))

                utilities.kodiJsonRequest(chunk)

            self.__updateProgress(99,
                                  line2=utilities.getString(32090) %
                                  len(kodiMoviesToUpdate))
コード例 #4
0
    def __kodiLoadShows(self):
        self.sync.UpdateProgress(1, line1=utilities.getString(32094), line2=utilities.getString(32095))

        logger.debug("[Episodes Sync] Getting show data from Kodi")
        data = utilities.kodiJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber', 'year', 'userrating']}, 'id': 0})
        if data['limits']['total'] == 0:
            logger.debug("[Episodes Sync] Kodi json request was empty.")
            return None, None

        tvshows = utilities.kodiRpcToTraktMediaObjects(data)
        logger.debug("[Episode Sync] Getting shows from kodi finished %s" % tvshows)

        if tvshows is None:
            return None, None
        self.sync.UpdateProgress(2, line2=utilities.getString(32096))
        resultCollected = {'shows': []}
        resultWatched = {'shows': []}
        i = 0
        x = float(len(tvshows))
        logger.debug("[Episodes Sync] Getting episode data from Kodi")
        for show_col1 in tvshows:
            i += 1
            y = ((i / x) * 8) + 2
            self.sync.UpdateProgress(int(y), line2=utilities.getString(32097) % (i, x))

            show = {'title': show_col1['title'], 'ids': {}, 'year': show_col1['year'], 'rating': show_col1['rating'],
                    'tvshowid': show_col1['tvshowid'], 'seasons': []}

            if 'ids' in show_col1 and 'tvdb' in show_col1['ids']:
                show['ids'] = {'tvdb': show_col1['ids']['tvdb']}

            data = utilities.kodiJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': show_col1['tvshowid'], 'properties': ['season', 'episode', 'playcount', 'uniqueid', 'lastplayed', 'file', 'dateadded', 'runtime', 'userrating']}, 'id': 0})
            if not data:
                logger.debug("[Episodes Sync] There was a problem getting episode data for '%s', aborting sync." % show['title'])
                return None, None
            elif 'episodes' not in data:
                logger.debug("[Episodes Sync] '%s' has no episodes in Kodi." % show['title'])
                continue

            if 'tvshowid' in show_col1:
                del(show_col1['tvshowid'])

            showWatched = copy.deepcopy(show)
            data2 = copy.deepcopy(data)
            show['seasons'] = utilities.kodiRpcToTraktMediaObjects(data)

            showWatched['seasons'] = utilities.kodiRpcToTraktMediaObjects(data2, 'watched')

            resultCollected['shows'].append(show)
            resultWatched['shows'].append(showWatched)

        self.sync.UpdateProgress(10, line2=utilities.getString(32098))
        return resultCollected, resultWatched
コード例 #5
0
    def __syncEpisodeRatings(self, traktShows, kodiShows, fromPercent, toPercent):
        if utilities.getSettingAsBool('trakt_sync_ratings') and traktShows and not self.sync.IsCanceled():
            updateKodiTraktShows = copy.deepcopy(traktShows)
            updateKodiKodiShows = copy.deepcopy(kodiShows)

            traktShowsToUpdate = self.__compareEpisodes(updateKodiKodiShows, updateKodiTraktShows, rating=True)
            if len(traktShowsToUpdate['shows']) == 0:
                self.sync.UpdateProgress(toPercent, line1='', line2=utilities.getString(32181))
                logger.debug("[Episodes Sync] Trakt episode ratings are up to date.")
            else:
                logger.debug("[Episodes Sync] %i show(s) will have episode ratings added on Trakt" % len(traktShowsToUpdate['shows']))

                self.sync.UpdateProgress(fromPercent, line1='', line2=utilities.getString(32182) % len(traktShowsToUpdate['shows']))
                self.sync.traktapi.addRating(traktShowsToUpdate)


            kodiShowsUpdate = self.__compareEpisodes(updateKodiTraktShows, updateKodiKodiShows, restrict=True, rating=True)
            if len(kodiShowsUpdate['shows']) == 0:
                self.sync.UpdateProgress(toPercent, line1='', line2=utilities.getString(32173))
                logger.debug("[Episodes Sync] Kodi episode ratings are up to date.")
            else:
                logger.debug("[Episodes Sync] %i show(s) will have episode ratings added in Kodi" % len(kodiShowsUpdate['shows']))
                for s in ["%s" % self.__getShowAsString(s, short=True) for s in kodiShowsUpdate['shows']]:
                    logger.debug("[Episodes Sync] Episodes updated: %s" % s)

                episodes = []
                for show in kodiShowsUpdate['shows']:
                    for season in show['seasons']:
                        for episode in season['episodes']:
                            episodes.append({'episodeid': episode['ids']['episodeid'], 'rating': episode['rating']})

                # split episode list into chunks of 50
                chunksize = 50
                chunked_episodes = utilities.chunks([{"jsonrpc": "2.0", "id": i, "method": "VideoLibrary.SetEpisodeDetails",
                                        "params": {"episodeid": episodes[i]['episodeid'],
                                                   "userrating": episodes[i]['rating']}} for i in range(len(episodes))],
                                        chunksize)
                i = 0
                x = float(len(episodes))
                for chunk in chunked_episodes:
                    if self.sync.IsCanceled():
                        return
                    i += 1
                    y = ((i / x) * (toPercent-fromPercent)) + fromPercent
                    self.sync.UpdateProgress(int(y), line1='', line2=utilities.getString(32174) % ((i) * chunksize if (i) * chunksize < x else x, x))

                    utilities.kodiJsonRequest(chunk)

                self.sync.UpdateProgress(toPercent, line2=utilities.getString(32175) % len(episodes))
コード例 #6
0
ファイル: sync.py プロジェクト: shedrock/script.trakt
	def __kodiLoadShowList(self):
		Debug("[Episodes Sync] Getting show data from Kodi")
		data = utilities.kodiJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber', 'year']}, 'id': 0})
		if not data:
			Debug("[Episodes Sync] Kodi json request was empty.")
			return None
		
		if not 'tvshows' in data:
			Debug('[Episodes Sync] Key "tvshows" not found')
			return None

		shows = data['tvshows']
		Debug("[Episodes Sync] Kodi JSON Result: '%s'" % str(shows))

		# reformat show array
		for show in shows:
			show['ids'] = {}
			show['ids']['tvdb'] = ""
			show['ids']['imdb'] = ""
			id = show['imdbnumber']
			if id.startswith("tt"):
				show['ids']['imdb'] = id
			if id.isdigit():
				show['ids']['tvdb'] = id
			del(show['imdbnumber'])
			del(show['label'])
		Debug("[Episode Sync] Shows finished %s" % shows)
		return shows
コード例 #7
0
ファイル: sync.py プロジェクト: shedrock/script.trakt
	def __kodiUpdateEpisodes(self, shows):
		if len(shows['shows']) == 0:
			self.__updateProgress(82, line1=utilities.getString(1441), line2=utilities.getString(1493))
			Debug("[Episodes Sync] Kodi episode playcounts are up to date.")
			return

		Debug("[Episodes Sync] %i show(s) shows are missing playcounts on Kodi" % len(shows['shows']))
		for s in ["%s" % self.__getShowAsString(s, short=True) for s in shows['shows']]:
			Debug("[Episodes Sync] Episodes updated: %s" % s)

		self.__updateProgress(64, line1=utilities.getString(1441), line2="%i %s" % (len(shows['shows']), utilities.getString(1439)), line3=" ")

		episodes = []
		for show in shows['shows']:
			for season in show['seasons']:
				for episode in season['episodes']:
					episodes.append({'episodeid': episode['ids']['episodeid'], 'playcount': 1})

		#split episode list into chunks of 50
		chunked_episodes = utilities.chunks([{"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": episodes[i], "id": i} for i in range(len(episodes))], 50)
		i = 0
		x = float(len(chunked_episodes))
		for chunk in chunked_episodes:
			if self.__isCanceled():
				return

			Debug("[Episodes Sync] chunk %s" % str(chunk))
			result = utilities.kodiJsonRequest(chunk)
			Debug("[Episodes Sync] result %s" % str(result))

			i += 1
			y = ((i / x) * 18) + 64
			self.__updateProgress(int(y), line2=utilities.getString(1494))

		self.__updateProgress(82, line2=utilities.getString(1495) % len(episodes))
コード例 #8
0
ファイル: syncMovies.py プロジェクト: nb2a/script.trakt
    def __syncMovieRatings(self, traktMovies, kodiMovies, fromPercent, toPercent):

        if utilities.getSettingAsBool('trakt_sync_ratings') and traktMovies and not self.sync.IsCanceled():
            updateKodiTraktMovies = copy.deepcopy(traktMovies)
            updateKodiKodiMovies = copy.deepcopy(kodiMovies)

            traktMoviesToUpdate = self.__compareMovies(updateKodiKodiMovies, updateKodiTraktMovies, rating=True)
            if len(traktMoviesToUpdate) == 0:
                self.sync.UpdateProgress(toPercent, line1='', line2=utilities.getString(32179))
                logger.debug("[Movies Sync] Trakt movie ratings are up to date.")
            else:
                logger.debug("[Movies Sync] %i movie(s) ratings will be updated on Trakt" % len(traktMoviesToUpdate))

                self.sync.UpdateProgress(fromPercent, line1='', line2=utilities.getString(32180) % len(traktMoviesToUpdate))

                moviesRatings = {'movies': []}
                for movie in traktMoviesToUpdate:
                    moviesRatings['movies'].append(movie)

                self.sync.traktapi.addRating(moviesRatings)


            kodiMoviesToUpdate = self.__compareMovies(updateKodiTraktMovies, updateKodiKodiMovies, restrict=True, rating=True)
            if len(kodiMoviesToUpdate) == 0:
                self.sync.UpdateProgress(toPercent, line1='', line2=utilities.getString(32169))
                logger.debug("[Movies Sync] Kodi movie ratings are up to date.")
            else:
                logger.debug("[Movies Sync] %i movie(s) ratings will be updated in Kodi" % len(kodiMoviesToUpdate))

                self.sync.UpdateProgress(fromPercent, line1='', line2=utilities.getString(32170) % len(kodiMoviesToUpdate))
                # split movie list into chunks of 50
                chunksize = 50
                chunked_movies = utilities.chunks([{"jsonrpc": "2.0", "id": i, "method": "VideoLibrary.SetMovieDetails",
                                                    "params": {"movieid": kodiMoviesToUpdate[i]['movieid'],
                                                               "userrating": kodiMoviesToUpdate[i]['rating']}} for i in range(len(kodiMoviesToUpdate))],
                                                  chunksize)
                i = 0
                x = float(len(kodiMoviesToUpdate))
                for chunk in chunked_movies:
                    if self.sync.IsCanceled():
                        return
                    i += 1
                    y = ((i / x) * (toPercent-fromPercent)) + fromPercent
                    self.sync.UpdateProgress(int(y), line2=utilities.getString(32171) % ((i) * chunksize if (i) * chunksize < x else x, x))
                    utilities.kodiJsonRequest(chunk)

                self.sync.UpdateProgress(toPercent, line2=utilities.getString(32172) % len(kodiMoviesToUpdate))
コード例 #9
0
    def __syncShowsRatings(self, traktShows, kodiShows, fromPercent, toPercent):
        if utilities.getSettingAsBool('trakt_sync_ratings') and traktShows and not self.sync.IsCanceled():
            updateKodiTraktShows = copy.deepcopy(traktShows)
            updateKodiKodiShows = copy.deepcopy(kodiShows)

            traktShowsToUpdate = self.__compareShows(updateKodiKodiShows, updateKodiTraktShows, rating=True)
            if len(traktShowsToUpdate['shows']) == 0:
                self.sync.UpdateProgress(toPercent, line1='', line2=utilities.getString(32181))
                logger.debug("[Episodes Sync] Trakt show ratings are up to date.")
            else:
                logger.debug("[Episodes Sync] %i show(s) will have show ratings added on Trakt" % len(traktShowsToUpdate['shows']))

                self.sync.UpdateProgress(fromPercent, line1='', line2=utilities.getString(32182) % len(traktShowsToUpdate['shows']))

                self.sync.traktapi.addRating(traktShowsToUpdate)

            # needs to be restricted, because we can't add a rating to an episode which is not in our Kodi collection
            kodiShowsUpdate = self.__compareShows(updateKodiTraktShows, updateKodiKodiShows, rating=True, restrict = True)

            if len(kodiShowsUpdate['shows']) == 0:
                self.sync.UpdateProgress(toPercent, line1='', line2=utilities.getString(32176))
                logger.debug("[Episodes Sync] Kodi show ratings are up to date.")
            else:
                logger.debug("[Episodes Sync] %i show(s) will have show ratings added in Kodi" % len(kodiShowsUpdate['shows']))

                shows = []
                for show in kodiShowsUpdate['shows']:
                    shows.append({'tvshowid': show['tvshowid'], 'rating': show['rating']})

                # split episode list into chunks of 50
                chunksize = 50
                chunked_episodes = utilities.chunks([{"jsonrpc": "2.0", "id": i, "method": "VideoLibrary.SetTVShowDetails",
                                        "params": {"tvshowid": shows[i]['tvshowid'],
                                                   "userrating": shows[i]['rating']}} for i in range(len(shows))],
                                        chunksize)
                i = 0
                x = float(len(shows))
                for chunk in chunked_episodes:
                    if self.sync.IsCanceled():
                        return
                    i += 1
                    y = ((i / x) * (toPercent-fromPercent)) + fromPercent
                    self.sync.UpdateProgress(int(y), line1='', line2=utilities.getString(32177) % ((i) * chunksize if (i) * chunksize < x else x, x))

                    utilities.kodiJsonRequest(chunk)

                self.sync.UpdateProgress(toPercent, line2=utilities.getString(32178) % len(shows))
コード例 #10
0
ファイル: sync.py プロジェクト: vishal8492/script.trakt
    def __kodiUpdateMovies(self, movies):
        if len(movies) == 0:
            self.__updateProgress(82, line2=utilities.getString(1471))
            Debug("[Movies Sync] Kodi movie playcount is up to date.")
            return

        Debug("[Movies Sync] %i movie(s) playcount will be updated in Kodi" %
              len(movies))

        self.__updateProgress(66,
                              line2=utilities.getString(1430) % len(movies))

        #split movie list into chunks of 50
        chunksize = 50
        chunked_movies = utilities.chunks([{
            "jsonrpc": "2.0",
            "method": "VideoLibrary.SetMovieDetails",
            "params": {
                "movieid": movies[i]['movieid'],
                "playcount": movies[i]['plays']
            },
            "id": i
        } for i in range(len(movies))], chunksize)
        i = 0
        x = float(len(chunked_movies))
        for chunk in chunked_movies:
            if self.__isCanceled():
                return
            utilities.kodiJsonRequest(chunk)

            i += 1
            y = ((i / x) * 16) + 66

            self.__updateProgress(int(y),
                                  line2=utilities.getString(1472) %
                                  ((i + 1) * chunksize if
                                   (i + 1) * chunksize < x else x, x))

        self.__updateProgress(82,
                              line2=utilities.getString(1473) % len(movies))
コード例 #11
0
ファイル: sync.py プロジェクト: shedrock/script.trakt
	def __kodiLoadMovies(self):
		self.__updateProgress(1, line2=utilities.getString(1460))

		Debug("[Movies Sync] Getting movie data from Kodi")
		data = utilities.kodiJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['title', 'imdbnumber', 'year', 'playcount', 'lastplayed', 'file']}})
		if not data:
			Debug("[Movies Sync] Kodi JSON request was empty.")
			return
		
		if not 'movies' in data:
			Debug('[Movies Sync] Key "movies" not found')
			return

		movies = data['movies']
		Debug("[Movies Sync] Kodi JSON Result: '%s'" % str(movies))

		i = 0
		x = float(len(movies))
		
		xbmc_movies = []

		# reformat movie array
		for movie in movies:
			if self.__checkExclusion(movie['file']):
				continue
			if movie['lastplayed']:
				movie['last_played'] = utilities.sqlDateToUnixDate(movie['lastplayed'])
			movie['plays'] = movie.pop('playcount')
			movie['collected'] = 1 #this is in our kodi so it should be collected
			movie['watched'] = 1 if movie['plays'] > 0 else 0
			movie['ids'] = {}
			id = movie['imdbnumber']
			if id.startswith("tt"):
				movie['ids']['imdb'] = ""
				movie['ids']['imdb'] = id
			if id.isdigit():
				movie['ids']['tmdb'] = ""
				movie['ids']['tmdb'] = id
			del(movie['imdbnumber'])
			del(movie['lastplayed'])
			del(movie['label'])
			del(movie['file'])

			xbmc_movies.append(movie)

			i += 1
			y = ((i / x) * 4) + 1
			self.__updateProgress(int(y))
			
		self.__updateProgress(5, line2=utilities.getString(1461))

		return xbmc_movies
コード例 #12
0
ファイル: sync.py プロジェクト: Leinad4Mind/script.trakt
	def __kodiLoadMovies(self):
		self.__updateProgress(1, line2=utilities.getString(32079))

		logger.debug("[Movies Sync] Getting movie data from Kodi")
		data = utilities.kodiJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['title', 'imdbnumber', 'year', 'playcount', 'lastplayed', 'file', 'dateadded', 'runtime']}})
		if data['limits']['total'] == 0:
			logger.debug("[Movies Sync] Kodi JSON request was empty.")
			return

		kodi_movies = utilities.kodiRpcToTraktMediaObjects(data)

		self.__updateProgress(10, line2=utilities.getString(32080))

		return kodi_movies
コード例 #13
0
ファイル: sync.py プロジェクト: Leinad4Mind/script.trakt
	def __addEpisodeProgressToKodi(self, traktShows, kodiShows):
		if utilities.getSettingAsBool('trakt_episode_playback') and traktShows and not self.__isCanceled():
			updateKodiTraktShows = copy.deepcopy(traktShows)
			updateKodiKodiShows = copy.deepcopy(kodiShows)
			kodiShowsUpadate = self.__compareShows(updateKodiTraktShows, updateKodiKodiShows, restrict=True, playback=True)

			if len(kodiShowsUpadate['shows']) == 0:
				self.__updateProgress(98, line1=utilities.getString(1441), line2=utilities.getString(32129))
				logger.debug("[Episodes Sync] Kodi episode playbacks are up to date.")
				return

			logger.debug("[Episodes Sync] %i show(s) shows are missing playbacks on Kodi" % len(kodiShowsUpadate['shows']))
			for s in ["%s" % self.__getShowAsString(s, short=True) for s in kodiShowsUpadate['shows']]:
				logger.debug("[Episodes Sync] Episodes updated: %s" % s)

			episodes = []
			for show in kodiShowsUpadate['shows']:
				for season in show['seasons']:
					for episode in season['episodes']:
						episodes.append({'episodeid': episode['ids']['episodeid'], 'progress': episode['progress'], 'runtime': episode['runtime']})

			#need to calculate the progress in int from progress in percent from Trakt
			#split episode list into chunks of 50
			chunksize = 50
			chunked_episodes = utilities.chunks([{"jsonrpc": "2.0", "id": i, "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid":episodes[i]['episodeid'], "resume": {"position": episodes[i]['runtime']/100.0*episodes[i]['progress']}}} for i in range(len(episodes))], chunksize)
			i = 0
			x = float(len(episodes))
			for chunk in chunked_episodes:
				if self.__isCanceled():
					return
				i += 1
				y = ((i / x) * 16) + 82
				self.__updateProgress(int(y), line2=utilities.getString(32130) % ((i)*chunksize if (i)*chunksize < x else x, x))

				utilities.kodiJsonRequest(chunk)

			self.__updateProgress(98, line2=utilities.getString(32131) % len(episodes))
コード例 #14
0
ファイル: sync.py プロジェクト: shedrock/script.trakt
	def __kodiLoadShows(self):
		self.__updateProgress(1, line1=utilities.getString(1480), line2=utilities.getString(1481))

		tvshows = self.__kodiLoadShowList()
		if tvshows is None:
			return None
		self.__updateProgress(2, line2=utilities.getString(1482))
		result = {'shows': []}
		i = 0
		x = float(len(tvshows))
		Debug("[Episodes Sync] Getting episode data from Kodi")
		for show_col1 in tvshows:

			show = {'title': show_col1['title'], 'ids': {'tvdb': show_col1['ids']['tvdb']}, 'year': show_col1['year'], 'seasons': []}

			data = utilities.kodiJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': show_col1['tvshowid'], 'properties': ['season', 'episode', 'playcount', 'uniqueid', 'file']}, 'id': 0})
			if not data:
				Debug("[Episodes Sync] There was a problem getting episode data for '%s', aborting sync." % show['title'])
				return None
			if not 'episodes' in data:
				Debug("[Episodes Sync] '%s' has no episodes in Kodi." % show['title'])
				continue

			a_episodes = {}
			seasons = []
			for episode in data['episodes']:
				watched = 0;
				if episode['playcount'] > 0:
					watched = 1
				while not episode['season'] in a_episodes :
					s_no = episode['season']
					a_episodes[s_no] = []
				s_no = episode['season']
				a_episodes[s_no].append({ 'number': episode['episode'], 'ids': { 'tvdb': episode['uniqueid']['unknown'], 'episodeid' : episode['episodeid']}, 'watched': watched })
				
			for episode in a_episodes:
				seasons.append({'number': episode, 'episodes': a_episodes[episode]})
			show['seasons'] = seasons

			if 'tvshowid' in show_col1:
				del(show_col1['tvshowid'])
			result['shows'].append(show)

			i += 1
			y = ((i / x) * 8) + 2
			self.__updateProgress(int(y), line2=utilities.getString(1483))

		self.__updateProgress(10, line2=utilities.getString(1484))
		return result
コード例 #15
0
    def __kodiLoadShowList(self):
        Debug("[Episodes Sync] Getting show data from Kodi")
        data = utilities.kodiJsonRequest({
            'jsonrpc': '2.0',
            'method': 'VideoLibrary.GetTVShows',
            'params': {
                'properties': ['title', 'imdbnumber', 'year']
            },
            'id': 0
        })
        if not data:
            Debug("[Episodes Sync] Kodi json request was empty.")
            return None

        shows = utilities.kodiRpcToTraktMediaObjects(data)
        Debug("[Episode Sync] Shows finished %s" % shows)
        return shows
コード例 #16
0
ファイル: sync.py プロジェクト: Leinad4Mind/script.trakt
	def __addEpisodesToKodiWatched(self, traktShows, kodiShows, kodiShowsCollected):
		if utilities.getSettingAsBool('kodi_episode_playcount') and not self.__isCanceled():
			updateKodiTraktShows = copy.deepcopy(traktShows)
			updateKodiKodiShows = copy.deepcopy(kodiShows)

			kodiShowsUpadate = self.__compareShows(updateKodiTraktShows, updateKodiKodiShows, watched=True, restrict=True, collected=kodiShowsCollected)

			if len(kodiShowsUpadate['shows']) == 0:
				self.__updateProgress(98, line1=utilities.getString(32074), line2=utilities.getString(32107))
				logger.debug("[Episodes Sync] Kodi episode playcounts are up to date.")
				return

			logger.debug("[Episodes Sync] %i show(s) shows are missing playcounts on Kodi" % len(kodiShowsUpadate['shows']))
			for s in ["%s" % self.__getShowAsString(s, short=True) for s in kodiShowsUpadate['shows']]:
				logger.debug("[Episodes Sync] Episodes updated: %s" % s)

			#logger.debug("kodiShowsUpadate: %s" % kodiShowsUpadate)
			episodes = []
			for show in kodiShowsUpadate['shows']:
				for season in show['seasons']:
					for episode in season['episodes']:
						episodes.append({'episodeid': episode['ids']['episodeid'], 'playcount': episode['plays'], "lastplayed": utilities.convertUtcToDateTime(episode['last_watched_at'])})

			#split episode list into chunks of 50
			chunksize = 50
			chunked_episodes = utilities.chunks([{"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": episodes[i], "id": i} for i in range(len(episodes))], chunksize)
			i = 0
			x = float(len(episodes))
			for chunk in chunked_episodes:
				if self.__isCanceled():
					return
				i += 1
				y = ((i / x) * 16) + 82
				self.__updateProgress(int(y), line2=utilities.getString(32108) % ((i)*chunksize if (i)*chunksize < x else x, x))

				logger.debug("[Episodes Sync] chunk %s" % str(chunk))
				result = utilities.kodiJsonRequest(chunk)
				logger.debug("[Episodes Sync] result %s" % str(result))

			self.__updateProgress(98, line2=utilities.getString(32109) % len(episodes))
コード例 #17
0
ファイル: sync.py プロジェクト: vishal8492/script.trakt
    def __kodiLoadMovies(self):
        self.__updateProgress(1, line2=utilities.getString(1460))

        Debug("[Movies Sync] Getting movie data from Kodi")
        data = utilities.kodiJsonRequest({
            'jsonrpc': '2.0',
            'id': 0,
            'method': 'VideoLibrary.GetMovies',
            'params': {
                'properties': [
                    'title', 'imdbnumber', 'year', 'playcount', 'lastplayed',
                    'file', 'dateadded'
                ]
            }
        })
        if data['limits']['total'] == 0:
            Debug("[Movies Sync] Kodi JSON request was empty.")
            return

        kodi_movies = utilities.kodiRpcToTraktMediaObjects(data)

        self.__updateProgress(10, line2=utilities.getString(1461))

        return kodi_movies
コード例 #18
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)
コード例 #19
0
ファイル: sync.py プロジェクト: mikellgonzalez/script.trakt
    def __addEpisodesToKodiWatched(self, traktShows, kodiShows,
                                   kodiShowsCollected):
        if utilities.getSettingAsBool(
                'kodi_episode_playcount') and not self.__isCanceled():
            updateKodiTraktShows = copy.deepcopy(traktShows)
            updateKodiKodiShows = copy.deepcopy(kodiShows)

            kodiShowsUpadate = self.__compareShows(
                updateKodiTraktShows,
                updateKodiKodiShows,
                watched=True,
                restrict=True,
                collected=kodiShowsCollected)

            if len(kodiShowsUpadate['shows']) == 0:
                self.__updateProgress(98,
                                      line1=utilities.getString(32074),
                                      line2=utilities.getString(32107))
                logger.debug(
                    "[Episodes Sync] Kodi episode playcounts are up to date.")
                return

            logger.debug(
                "[Episodes Sync] %i show(s) shows are missing playcounts on Kodi"
                % len(kodiShowsUpadate['shows']))
            for s in [
                    "%s" % self.__getShowAsString(s, short=True)
                    for s in kodiShowsUpadate['shows']
            ]:
                logger.debug("[Episodes Sync] Episodes updated: %s" % s)

            #logger.debug("kodiShowsUpadate: %s" % kodiShowsUpadate)
            episodes = []
            for show in kodiShowsUpadate['shows']:
                for season in show['seasons']:
                    for episode in season['episodes']:
                        episodes.append({
                            'episodeid':
                            episode['ids']['episodeid'],
                            'playcount':
                            episode['plays']
                        })

            #split episode list into chunks of 50
            chunksize = 50
            chunked_episodes = utilities.chunks([{
                "jsonrpc": "2.0",
                "method": "VideoLibrary.SetEpisodeDetails",
                "params": episodes[i],
                "id": i
            } for i in range(len(episodes))], chunksize)
            i = 0
            x = float(len(episodes))
            for chunk in chunked_episodes:
                if self.__isCanceled():
                    return
                i += 1
                y = ((i / x) * 16) + 82
                self.__updateProgress(int(y),
                                      line2=utilities.getString(32108) %
                                      ((i) * chunksize if
                                       (i) * chunksize < x else x, x))

                logger.debug("[Episodes Sync] chunk %s" % str(chunk))
                result = utilities.kodiJsonRequest(chunk)
                logger.debug("[Episodes Sync] result %s" % str(result))

            self.__updateProgress(98,
                                  line2=utilities.getString(32109) %
                                  len(episodes))
コード例 #20
0
    def __addMovieProgressToKodi(self, traktMovies, kodiMovies, fromPercent,
                                 toPercent):

        if utilities.getSettingAsBool(
                'trakt_movie_playback'
        ) and traktMovies and not self.sync.IsCanceled():
            updateKodiTraktMovies = copy.deepcopy(traktMovies)
            updateKodiKodiMovies = copy.deepcopy(kodiMovies)

            kodiMoviesToUpdate = self.__compareMovies(
                updateKodiTraktMovies['movies'],
                updateKodiKodiMovies,
                restrict=True,
                playback=True)
            if len(kodiMoviesToUpdate) == 0:
                self.sync.UpdateProgress(toPercent,
                                         line1='',
                                         line2=utilities.getString(32125))
                logger.debug(
                    "[Movies Sync] Kodi movie playbacks are up to date.")
                return

            logger.debug(
                "[Movies Sync] %i movie(s) playbacks will be updated in Kodi" %
                len(kodiMoviesToUpdate))

            self.sync.UpdateProgress(fromPercent,
                                     line1='',
                                     line2=utilities.getString(32126) %
                                     len(kodiMoviesToUpdate))
            # need to calculate the progress in int from progress in percent from Trakt
            # split movie list into chunks of 50
            chunksize = 50
            chunked_movies = utilities.chunks([{
                "jsonrpc": "2.0",
                "id": i,
                "method": "VideoLibrary.SetMovieDetails",
                "params": {
                    "movieid": kodiMoviesToUpdate[i]['movieid'],
                    "resume": {
                        "position":
                        kodiMoviesToUpdate[i]['runtime'] / 100.0 *
                        kodiMoviesToUpdate[i]['progress']
                    }
                }
            } for i in range(len(kodiMoviesToUpdate))], chunksize)
            i = 0
            x = float(len(kodiMoviesToUpdate))
            for chunk in chunked_movies:
                if self.sync.IsCanceled():
                    return
                i += 1
                y = ((i / x) * (toPercent - fromPercent)) + fromPercent
                self.sync.UpdateProgress(int(y),
                                         line2=utilities.getString(32127) %
                                         ((i) * chunksize if
                                          (i) * chunksize < x else x, x))
                utilities.kodiJsonRequest(chunk)

            self.sync.UpdateProgress(toPercent,
                                     line2=utilities.getString(32128) %
                                     len(kodiMoviesToUpdate))
コード例 #21
0
    def __syncMovieRatings(self, traktMovies, kodiMovies, fromPercent,
                           toPercent):

        if utilities.getSettingAsBool(
                'trakt_sync_ratings'
        ) and traktMovies and not self.sync.IsCanceled():
            updateKodiTraktMovies = copy.deepcopy(traktMovies)
            updateKodiKodiMovies = copy.deepcopy(kodiMovies)

            traktMoviesToUpdate = self.__compareMovies(updateKodiKodiMovies,
                                                       updateKodiTraktMovies,
                                                       rating=True)
            if len(traktMoviesToUpdate) == 0:
                self.sync.UpdateProgress(toPercent,
                                         line1='',
                                         line2=utilities.getString(32179))
                logger.debug(
                    "[Movies Sync] Trakt movie ratings are up to date.")
            else:
                logger.debug(
                    "[Movies Sync] %i movie(s) ratings will be updated on Trakt"
                    % len(traktMoviesToUpdate))

                self.sync.UpdateProgress(fromPercent,
                                         line1='',
                                         line2=utilities.getString(32180) %
                                         len(traktMoviesToUpdate))

                moviesRatings = {'movies': []}
                for movie in traktMoviesToUpdate:
                    moviesRatings['movies'].append(movie)

                self.sync.traktapi.addRating(moviesRatings)

            kodiMoviesToUpdate = self.__compareMovies(updateKodiTraktMovies,
                                                      updateKodiKodiMovies,
                                                      restrict=True,
                                                      rating=True)
            if len(kodiMoviesToUpdate) == 0:
                self.sync.UpdateProgress(toPercent,
                                         line1='',
                                         line2=utilities.getString(32169))
                logger.debug(
                    "[Movies Sync] Kodi movie ratings are up to date.")
            else:
                logger.debug(
                    "[Movies Sync] %i movie(s) ratings will be updated in Kodi"
                    % len(kodiMoviesToUpdate))

                self.sync.UpdateProgress(fromPercent,
                                         line1='',
                                         line2=utilities.getString(32170) %
                                         len(kodiMoviesToUpdate))
                # split movie list into chunks of 50
                chunksize = 50
                chunked_movies = utilities.chunks([{
                    "jsonrpc": "2.0",
                    "id": i,
                    "method": "VideoLibrary.SetMovieDetails",
                    "params": {
                        "movieid": kodiMoviesToUpdate[i]['movieid'],
                        "userrating": kodiMoviesToUpdate[i]['rating']
                    }
                } for i in range(len(kodiMoviesToUpdate))], chunksize)
                i = 0
                x = float(len(kodiMoviesToUpdate))
                for chunk in chunked_movies:
                    if self.sync.IsCanceled():
                        return
                    i += 1
                    y = ((i / x) * (toPercent - fromPercent)) + fromPercent
                    self.sync.UpdateProgress(int(y),
                                             line2=utilities.getString(32171) %
                                             ((i) * chunksize if
                                              (i) * chunksize < x else x, x))
                    utilities.kodiJsonRequest(chunk)

                self.sync.UpdateProgress(toPercent,
                                         line2=utilities.getString(32172) %
                                         len(kodiMoviesToUpdate))
コード例 #22
0
ファイル: sync.py プロジェクト: vishal8492/script.trakt
    def __kodiLoadShows(self):
        self.__updateProgress(1,
                              line1=utilities.getString(1480),
                              line2=utilities.getString(1481))

        Debug("[Episodes Sync] Getting show data from Kodi")
        data = utilities.kodiJsonRequest({
            'jsonrpc': '2.0',
            'method': 'VideoLibrary.GetTVShows',
            'params': {
                'properties': ['title', 'imdbnumber', 'year']
            },
            'id': 0
        })
        if data['limits']['total'] == 0:
            Debug("[Episodes Sync] Kodi json request was empty.")
            return None

        tvshows = utilities.kodiRpcToTraktMediaObjects(data)
        Debug("[Episode Sync] Getting shows from kodi finished %s" % tvshows)

        if tvshows is None:
            return None
        self.__updateProgress(2, line2=utilities.getString(1482))
        result = {'shows': []}
        i = 0
        x = float(len(tvshows))
        Debug("[Episodes Sync] Getting episode data from Kodi")
        for show_col1 in tvshows:

            show = {
                'title': show_col1['title'],
                'ids': {},
                'year': show_col1['year'],
                'seasons': []
            }

            if 'ids' in show_col1 and 'tvdb' in show_col1['ids']:
                show['ids'] = {'tvdb': show_col1['ids']['tvdb']}

            data = utilities.kodiJsonRequest({
                'jsonrpc': '2.0',
                'method': 'VideoLibrary.GetEpisodes',
                'params': {
                    'tvshowid':
                    show_col1['tvshowid'],
                    'properties': [
                        'season', 'episode', 'playcount', 'uniqueid',
                        'lastplayed', 'file', 'dateadded'
                    ]
                },
                'id': 0
            })
            if not data:
                Debug(
                    "[Episodes Sync] There was a problem getting episode data for '%s', aborting sync."
                    % show['title'])
                return None
            elif 'episodes' not in data:
                Debug("[Episodes Sync] '%s' has no episodes in Kodi." %
                      show['title'])
                continue

            seasons = utilities.kodiRpcToTraktMediaObjects(data)

            show['seasons'] = seasons

            if 'tvshowid' in show_col1:
                del (show_col1['tvshowid'])
            result['shows'].append(show)

            i += 1
            y = ((i / x) * 8) + 2
            self.__updateProgress(int(y),
                                  line2=utilities.getString(1483) % (i + 1, x))

        self.__updateProgress(10, line2=utilities.getString(1484))
        return result
コード例 #23
0
    def onPlayBackStarted(self):
        xbmc.sleep(1000)
        self.type = None
        self.id = None

        # only do anything if we're playing a video
        if self.isPlayingVideo():
            # get item data from json rpc
            result = utilities.kodiJsonRequest({
                'jsonrpc': '2.0',
                'method': 'Player.GetItem',
                'params': {
                    'playerid': 1
                },
                'id': 1
            })
            utilities.Debug("[traktPlayer] onPlayBackStarted() - %s" % result)

            # check for exclusion
            _filename = None
            try:
                _filename = self.getPlayingFile()
            except:
                utilities.Debug(
                    "[traktPlayer] onPlayBackStarted() - Exception trying to get playing filename, player suddenly stopped."
                )
                return

            if utilities.checkScrobblingExclusion(_filename):
                utilities.Debug(
                    "[traktPlayer] onPlayBackStarted() - '%s' is in exclusion settings, ignoring."
                    % _filename)
                return

            self.type = result['item']['type']

            data = {'action': 'started'}

            # check type of item
            if self.type == 'unknown':
                # do a deeper check to see if we have enough data to perform scrobbles
                utilities.Debug(
                    "[traktPlayer] onPlayBackStarted() - Started playing a non-library file, checking available data."
                )

                season = xbmc.getInfoLabel('VideoPlayer.Season')
                episode = xbmc.getInfoLabel('VideoPlayer.Episode')
                showtitle = xbmc.getInfoLabel('VideoPlayer.TVShowTitle')
                year = xbmc.getInfoLabel('VideoPlayer.Year')

                utilities.Debug("[traktPlayer] info - showtitle:" + showtitle +
                                ", Year:" + year + ", Season:" + season +
                                ", Episode:" + episode)

                if season and episode and showtitle:
                    # we have season, episode and show title, can scrobble this as an episode
                    self.type = 'episode'
                    data['type'] = 'episode'
                    data['season'] = int(season)
                    data['episode'] = int(episode)
                    data['showtitle'] = showtitle
                    data['title'] = xbmc.getInfoLabel('VideoPlayer.Title')
                    if year.isdigit():
                        data['year'] = year
                    utilities.Debug(
                        "[traktPlayer] onPlayBackStarted() - Playing a non-library 'episode' - %s - S%02dE%02d - %s."
                        % (data['showtitle'], data['season'], data['episode'],
                           data['title']))
                elif year and not season and not showtitle:
                    # we have a year and no season/showtitle info, enough for a movie
                    self.type = 'movie'
                    data['type'] = 'movie'
                    data['year'] = int(year)
                    data['title'] = xbmc.getInfoLabel('VideoPlayer.Title')
                    utilities.Debug(
                        "[traktPlayer] onPlayBackStarted() - Playing a non-library 'movie' - %s (%d)."
                        % (data['title'], data['year']))
                elif showtitle:
                    title, season, episode = utilities.regex_tvshow(
                        False, showtitle)
                    data['type'] = 'episode'
                    data['season'] = int(season)
                    data['episode'] = int(episode)
                    data['showtitle'] = title
                    data['title'] = title
                    utilities.Debug(
                        "[traktPlayer] onPlayBackStarted() - Title:" + title +
                        ", showtitle:" + showtitle + ", season:" + season +
                        ", episode:" + episode)
                else:
                    utilities.Debug(
                        "[traktPlayer] onPlayBackStarted() - Non-library file, not enough data for scrobbling, skipping."
                    )
                    return

            elif self.type == 'episode' or self.type == 'movie':
                # get library id
                self.id = result['item']['id']
                data['id'] = self.id
                data['type'] = self.type

                if self.type == 'episode':
                    utilities.Debug(
                        "[traktPlayer] onPlayBackStarted() - Doing multi-part episode check."
                    )
                    result = utilities.kodiJsonRequest({
                        'jsonrpc': '2.0',
                        'method': 'VideoLibrary.GetEpisodeDetails',
                        'params': {
                            'episodeid': self.id,
                            'properties': ['tvshowid', 'season', 'episode']
                        },
                        'id': 1
                    })
                    if result:
                        utilities.Debug(
                            "[traktPlayer] onPlayBackStarted() - %s" % result)
                        tvshowid = int(result['episodedetails']['tvshowid'])
                        season = int(result['episodedetails']['season'])
                        episode = int(result['episodedetails']['episode'])
                        episode_index = episode - 1

                        result = utilities.kodiJsonRequest({
                            'jsonrpc': '2.0',
                            'method': 'VideoLibrary.GetEpisodes',
                            'params': {
                                'tvshowid': tvshowid,
                                'season': season,
                                'properties': ['episode', 'file'],
                                'sort': {
                                    'method': 'episode'
                                }
                            },
                            'id': 1
                        })
                        if result:
                            utilities.Debug(
                                "[traktPlayer] onPlayBackStarted() - %s" %
                                result)
                            # make sure episodes array exists in results
                            if 'episodes' in result:
                                multi = []
                                for i in range(episode_index,
                                               result['limits']['total']):
                                    if result['episodes'][i]['file'] == result[
                                            'episodes'][episode_index]['file']:
                                        multi.append(
                                            result['episodes'][i]['episodeid'])
                                    else:
                                        break
                                if len(multi) > 1:
                                    data['multi_episode_data'] = multi
                                    data['multi_episode_count'] = len(multi)
                                    utilities.Debug(
                                        "[traktPlayer] onPlayBackStarted() - This episode is part of a multi-part episode."
                                    )
                                else:
                                    utilities.Debug(
                                        "[traktPlayer] onPlayBackStarted() - This is a single episode."
                                    )

            else:
                utilities.Debug(
                    "[traktPlayer] onPlayBackStarted() - Video type '%s' unrecognized, skipping."
                    % self.type)
                return

            pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            plSize = len(pl)
            if plSize > 1:
                pos = pl.getposition()
                if not self.plIndex is None:
                    utilities.Debug(
                        "[traktPlayer] onPlayBackStarted() - User manually skipped to next (or previous) video, forcing playback ended event."
                    )
                    self.onPlayBackEnded()
                self.plIndex = pos
                utilities.Debug(
                    "[traktPlayer] onPlayBackStarted() - Playlist contains %d item(s), and is currently on item %d"
                    % (plSize, (pos + 1)))

            self._playing = True

            # send dispatch
            self.action(data)
コード例 #24
0
ファイル: service.py プロジェクト: neopack1/script.trakt
    def onPlayBackStarted(self):
        xbmc.sleep(1000)
        self.type = None
        self.id = None

        # take the user start scrobble offset into account
        scrobbleStartOffset = utilities.getSettingAsInt(
            'scrobble_start_offset') * 60
        if scrobbleStartOffset > 0:
            waitFor = 10
            waitedFor = 0
            # check each 10 seconds if we can abort or proceed
            while not xbmc.abortRequested and scrobbleStartOffset > waitedFor:
                waitedFor += waitFor
                time.sleep(waitFor)
                if not self.isPlayingVideo():
                    logger.debug(
                        '[traktPlayer] Playback stopped before reaching the scrobble offset'
                    )
                    return

        # only do anything if we're playing a video
        if self.isPlayingVideo():
            # get item data from json rpc
            result = utilities.kodiJsonRequest({
                'jsonrpc': '2.0',
                'method': 'Player.GetItem',
                'params': {
                    'playerid': 1
                },
                'id': 1
            })
            if result:
                logger.debug("[traktPlayer] onPlayBackStarted() - %s" % result)
                # check for exclusion
                _filename = None
                try:
                    _filename = self.getPlayingFile()
                except:
                    logger.debug(
                        "[traktPlayer] onPlayBackStarted() - Exception trying to get playing filename, player suddenly stopped."
                    )
                    return

                if utilities.checkExclusion(_filename):
                    logger.debug(
                        "[traktPlayer] onPlayBackStarted() - '%s' is in exclusion settings, ignoring."
                        % _filename)
                    return

                self.type = result['item']['type']

                data = {'action': 'started'}

                # check type of item
                if 'id' not in result['item']:
                    # do a deeper check to see if we have enough data to perform scrobbles
                    logger.debug(
                        "[traktPlayer] onPlayBackStarted() - Started playing a non-library file, checking available data."
                    )

                    season = xbmc.getInfoLabel('VideoPlayer.Season')
                    episode = xbmc.getInfoLabel('VideoPlayer.Episode')
                    showtitle = xbmc.getInfoLabel('VideoPlayer.TVShowTitle')
                    year = xbmc.getInfoLabel('VideoPlayer.Year')
                    video_ids = xbmcgui.Window(10000).getProperty(
                        'script.trakt.ids')
                    if video_ids:
                        data['video_ids'] = json.loads(video_ids)

                    logger.debug(
                        "[traktPlayer] info - ids: %s, showtitle: %s, Year: %s, Season: %s, Episode: %s"
                        % (video_ids, showtitle, year, season, episode))

                    if season and episode and (showtitle or video_ids):
                        # we have season, episode and either a show title or video_ids, can scrobble this as an episode
                        self.type = 'episode'
                        data['type'] = 'episode'
                        data['season'] = int(season)
                        data['episode'] = int(episode)
                        data['showtitle'] = showtitle
                        data['title'] = xbmc.getInfoLabel('VideoPlayer.Title')
                        if year.isdigit():
                            data['year'] = int(year)
                        logger.debug(
                            "[traktPlayer] onPlayBackStarted() - Playing a non-library 'episode' - %s - S%02dE%02d - %s."
                            % (data['showtitle'], data['season'],
                               data['episode'], data['title']))
                    elif (year or video_ids) and not season and not showtitle:
                        # we have a year or video_id and no season/showtitle info, enough for a movie
                        self.type = 'movie'
                        data['type'] = 'movie'
                        if year.isdigit():
                            data['year'] = int(year)
                        data['title'] = xbmc.getInfoLabel('VideoPlayer.Title')
                        logger.debug(
                            "[traktPlayer] onPlayBackStarted() - Playing a non-library 'movie' - %s (%s)."
                            % (data['title'], data.get('year', 'NaN')))
                    elif showtitle:
                        title, season, episode = utilities.regex_tvshow(
                            False, showtitle)
                        data['type'] = 'episode'
                        data['season'] = int(season)
                        data['episode'] = int(episode)
                        data['showtitle'] = title
                        data['title'] = title
                        logger.debug(
                            "[traktPlayer] onPlayBackStarted() - Title: %s, showtitle: %s, season: %d, episode: %d"
                            % (title, showtitle, season, episode))
                    else:
                        logger.debug(
                            "[traktPlayer] onPlayBackStarted() - Non-library file, not enough data for scrobbling, skipping."
                        )
                        return

                elif self.type == 'episode' or self.type == 'movie':
                    # get library id
                    self.id = result['item']['id']
                    data['id'] = self.id
                    data['type'] = self.type

                    if self.type == 'episode':
                        logger.debug(
                            "[traktPlayer] onPlayBackStarted() - Doing multi-part episode check."
                        )
                        result = utilities.kodiJsonRequest({
                            'jsonrpc': '2.0',
                            'method': 'VideoLibrary.GetEpisodeDetails',
                            'params': {
                                'episodeid':
                                self.id,
                                'properties':
                                ['tvshowid', 'season', 'episode', 'file']
                            },
                            'id': 1
                        })
                        if result:
                            logger.debug(
                                "[traktPlayer] onPlayBackStarted() - %s" %
                                result)
                            tvshowid = int(
                                result['episodedetails']['tvshowid'])
                            season = int(result['episodedetails']['season'])
                            currentfile = result['episodedetails']['file']

                            result = utilities.kodiJsonRequest({
                                'jsonrpc': '2.0',
                                'method': 'VideoLibrary.GetEpisodes',
                                'params': {
                                    'tvshowid': tvshowid,
                                    'season': season,
                                    'properties': ['episode', 'file'],
                                    'sort': {
                                        'method': 'episode'
                                    }
                                },
                                'id': 1
                            })
                            if result:
                                logger.debug(
                                    "[traktPlayer] onPlayBackStarted() - %s" %
                                    result)
                                # make sure episodes array exists in results
                                if 'episodes' in result:
                                    multi = []
                                    for i in range(result['limits']['start'],
                                                   result['limits']['total']):
                                        if currentfile == result['episodes'][
                                                i]['file']:
                                            multi.append(result['episodes'][i]
                                                         ['episodeid'])
                                    if len(multi) > 1:
                                        data['multi_episode_data'] = multi
                                        data['multi_episode_count'] = len(
                                            multi)
                                        logger.debug(
                                            "[traktPlayer] onPlayBackStarted() - This episode is part of a multi-part episode."
                                        )
                                    else:
                                        logger.debug(
                                            "[traktPlayer] onPlayBackStarted() - This is a single episode."
                                        )

                else:
                    logger.debug(
                        "[traktPlayer] onPlayBackStarted() - Video type '%s' unrecognized, skipping."
                        % self.type)
                    return

                pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
                plSize = len(pl)
                if plSize > 1:
                    pos = pl.getposition()
                    if not self.plIndex is None:
                        logger.debug(
                            "[traktPlayer] onPlayBackStarted() - User manually skipped to next (or previous) video, forcing playback ended event."
                        )
                        self.onPlayBackEnded()
                    self.plIndex = pos
                    logger.debug(
                        "[traktPlayer] onPlayBackStarted() - Playlist contains %d item(s), and is currently on item %d"
                        % (plSize, (pos + 1)))

                self._playing = True

                # send dispatch
                self.action(data)
コード例 #25
0
ファイル: script.py プロジェクト: mikesilvo164/script.trakt
def Main():

    args = __getArguments()
    data = {}

    if args['action'] == 'sync':
        data = {'action': 'manualSync', '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'] in ['rate', 'unrate']:
        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:
                    utils.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.getMovieDetailsFromKodi(
                        data['dbid'], ['imdbnumber', 'title', 'year'])
                    if not result:
                        utils.Debug(
                            "No data was returned from Kodi, aborting manual %s."
                            % args['action'])
                        return
                    data['imdbnumber'] = result['imdbnumber']

                elif utils.isShow(media_type):
                    result = utils.getShowDetailsFromKodi(
                        data['dbid'], ['imdbnumber', 'tag'])
                    if not result:
                        utils.Debug(
                            "No data was returned from Kodi, aborting manual %s."
                            % args['action'])
                        return
                    data['imdbnumber'] = result['imdbnumber']
                    data['tag'] = result['tag']

                elif utils.isEpisode(media_type):
                    result = utils.getEpisodeDetailsFromKodi(
                        data['dbid'],
                        ['showtitle', 'season', 'episode', 'imdbnumber'])
                    if not result:
                        utils.Debug(
                            "No data was returned from Kodi, aborting manual %s."
                            % args['action'])
                        return
                    data['imdbnumber'] = result['imdbnumber']
                    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['imdbnumber'] = 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 = {'media_type': media_type}
            if utils.isMovie(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = utils.getMovieDetailsFromKodi(
                    dbid, ['imdbnumber', 'title', 'year', 'playcount'])
                if result:
                    if result['playcount'] == 0:
                        data['id'] = result['imdbnumber']
                    else:
                        utils.Debug("Movie alread marked as watched in Kodi.")
                else:
                    utils.Debug("Error getting movie details from Kodi.")
                    return

            elif utils.isEpisode(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = utils.getEpisodeDetailsFromKodi(
                    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 Kodi.")
                else:
                    utils.Debug("Error getting episode details from Kodi.")
                    return

            elif utils.isSeason(media_type):
                showID = None
                showTitle = xbmc.getInfoLabel('ListItem.TVShowTitle')
                result = utils.kodiJsonRequest({
                    '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 Kodi.")
                    return

                season = xbmc.getInfoLabel('ListItem.Season')
                if season == "":
                    season = 0
                else:
                    season = int(season)

                result = utils.kodiJsonRequest({
                    '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.getShowDetailsFromKodi(dbid,
                                                      ['year', 'imdbnumber'])
                if not result:
                    utils.Debug("Error getting show details from Kodi.")
                    return
                showTitle = result['label']
                data['id'] = result['imdbnumber']
                result = utils.kodiJsonRequest({
                    '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 += 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 Kodi." %
                        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)")

    q = sqliteQueue.SqliteQueue()
    if 'action' in data:
        utils.Debug("Queuing for dispatch: %s" % data)
        q.append(data)
コード例 #26
0
ファイル: script.py プロジェクト: TonyPh12345/kodibrasilforum
def Main():
    args = __getArguments()
    data = {}

    if args["action"] == "pin_info":
        xbmc.executebuiltin("Dialog.Close(all, true)")

        pinInfo = xbmcgui.WindowXMLDialog("PinInfoWindow.xml", __addon__.getAddonInfo("path"))

        pinInfo.doModal()
        del pinInfo

    if args["action"] == "contextmenu":
        buttons = []
        media_type = __getMediaType()

        if media_type in ["movie", "show", "season", "episode"]:
            buttons.append("rate")

        if media_type in ["movie", "show", "season", "episode"]:
            buttons.append("togglewatched")

        buttons.append("sync")

        contextMenu = traktContextMenu(media_type=media_type, buttons=buttons)
        contextMenu.doModal()
        _action = contextMenu.action
        del contextMenu

        if _action is None:
            return

        logger.debug("'%s' selected from trakt.tv action menu" % _action)
        args["action"] = _action

    if args["action"] == "sync":
        data = {"action": "manualSync", "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"] in ["rate", "unrate"]:
        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:
                logger.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"]
            try:
                data["season"] = int(args["season"])
                data["episode"] = int(args["episode"])
            except ValueError:
                logger.debug("Error parsing season or episode for manual %s" % args["action"])
                return
            except KeyError:
                pass
        else:
            media_type = __getMediaType()
            if not utils.isValidMediaType(media_type):
                logger.debug("Error, not in video library.")
                return
            data["dbid"] = int(xbmc.getInfoLabel("ListItem.DBID"))

        if media_type is None:
            logger.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:
                logger.debug(
                    "Manual %s of library '%s' with an ID of '%s'." % (args["action"], media_type, data["dbid"])
                )
                if utils.isMovie(media_type):
                    result = utils.getMovieDetailsFromKodi(data["dbid"], ["imdbnumber", "title", "year"])
                    if not result:
                        logger.debug("No data was returned from Kodi, aborting manual %s." % args["action"])
                        return
                    data["imdbnumber"] = result["imdbnumber"]

                elif utils.isShow(media_type) or utils.isSeason(media_type):
                    result = utils.getShowDetailsFromKodi(data["dbid"], ["imdbnumber", "tag"])
                    if not result:
                        logger.debug("No data was returned from Kodi, aborting manual %s." % args["action"])
                        return
                    data["imdbnumber"] = result["imdbnumber"]
                    data["tag"] = result["tag"]

                elif utils.isEpisode(media_type):
                    result = utils.getEpisodeDetailsFromKodi(
                        data["dbid"], ["showtitle", "season", "episode", "tvshowid", "uniqueid", "file", "playcount"]
                    )
                    if not result:
                        logger.debug("No data was returned from Kodi, aborting manual %s." % args["action"])
                        return
                    data["imdbnumber"] = result["episodeid"]
                    data["season"] = result["season"]
                    data["episode"] = result["episode"]
            else:
                data["imdbnumber"] = data["remoteid"]
                if "season" in data and "episode" in data:
                    logger.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"])
                    )
                elif "season" in data:
                    logger.debug(
                        "Manual %s of non-library '%s' S%02d, with an ID of '%s'."
                        % (args["action"], media_type, data["season"], data["remoteid"])
                    )
                else:
                    logger.debug(
                        "Manual %s of non-library '%s' with an ID of '%s'."
                        % (args["action"], media_type, 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:
            logger.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 = {"media_type": media_type}
            if utils.isMovie(media_type):
                dbid = int(xbmc.getInfoLabel("ListItem.DBID"))
                result = utils.getMovieDetailsFromKodi(dbid, ["imdbnumber", "title", "year", "playcount"])
                if result:
                    if result["playcount"] == 0:
                        data["id"] = result["imdbnumber"]
                    else:
                        logger.debug("Movie alread marked as watched in Kodi.")
                else:
                    logger.debug("Error getting movie details from Kodi.")
                    return

            elif utils.isEpisode(media_type):
                dbid = int(xbmc.getInfoLabel("ListItem.DBID"))
                result = utils.getEpisodeDetailsFromKodi(
                    dbid, ["showtitle", "season", "episode", "tvshowid", "playcount"]
                )
                if result:
                    if result["playcount"] == 0:
                        data["id"] = result["imdbnumber"]
                        data["season"] = result["season"]
                        data["number"] = result["episode"]
                        data["title"] = result["showtitle"]
                    else:
                        logger.debug("Episode already marked as watched in Kodi.")
                else:
                    logger.debug("Error getting episode details from Kodi.")
                    return

            elif utils.isSeason(media_type):
                showID = None
                showTitle = xbmc.getInfoLabel("ListItem.TVShowTitle")
                result = utils.kodiJsonRequest(
                    {
                        "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"]
                            data["title"] = show["title"]
                            break
                else:
                    logger.debug("Error getting TV shows from Kodi.")
                    return

                season = xbmc.getInfoLabel("ListItem.Season")
                if season == "":
                    season = 0
                else:
                    season = int(season)

                result = utils.kodiJsonRequest(
                    {
                        "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:
                        logger.debug("'%s - Season %d' is already marked as watched." % (showTitle, season))
                        return

                    data["season"] = season
                    data["episodes"] = episodes
                else:
                    logger.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.getShowDetailsFromKodi(dbid, ["year", "imdbnumber"])
                if not result:
                    logger.debug("Error getting show details from Kodi.")
                    return
                showTitle = result["label"]
                data["id"] = result["imdbnumber"]
                result = utils.kodiJsonRequest(
                    {
                        "jsonrpc": "2.0",
                        "method": "VideoLibrary.GetEpisodes",
                        "params": {"tvshowid": dbid, "properties": ["season", "episode", "playcount", "showtitle"]},
                        "id": 0,
                    }
                )
                if result and "episodes" in result:
                    i = 0
                    s = {}
                    for e in result["episodes"]:
                        data["title"] = e["showtitle"]
                        season = str(e["season"])
                        if not season in s:
                            s[season] = []
                        if e["playcount"] == 0:
                            s[season].append(e["episode"])
                            i += 1

                    if i == 0:
                        logger.debug("'%s' is already marked as watched." % showTitle)
                        return

                    data["seasons"] = dict((k, v) for k, v in s.iteritems() if v)
                else:
                    logger.debug("Error getting episode details for '%s' from Kodi." % showTitle)
                    return

            if len(data) > 1:
                logger.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)")

    q = sqlitequeue.SqliteQueue()
    if "action" in data:
        logger.debug("Queuing for dispatch: %s" % data)
        q.append(data)
コード例 #27
0
ファイル: script.py プロジェクト: CatoV9/script.trakt
def Main():
    args = __getArguments()
    data = {}

    if args['action'] == 'pin_info':
        xbmc.executebuiltin('Dialog.Close(all, true)')
        gui_utils.get_pin()

    if args['action'] == 'contextmenu':
        buttons = []
        media_type = utils.getMediaType()

        if media_type in ['movie', 'show', 'season', 'episode']:
            buttons.append("rate")

        if media_type in ['movie', 'show', 'season', 'episode']:
            buttons.append("togglewatched")

        buttons.append("sync")

        contextMenu = traktContextMenu(media_type=media_type, buttons=buttons)
        contextMenu.doModal()
        _action = contextMenu.action
        del contextMenu

        if _action is None:
            return

        logger.debug("'%s' selected from trakt.tv action menu" % _action)
        args['action'] = _action

    if args['action'] == 'sync':
        data = {'action': 'manualSync', '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'] in ['rate', 'unrate']:
        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:
                logger.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']
            try:
                data['season'] = int(args['season'])
                data['episode'] = int(args['episode'])
            except ValueError:
                logger.debug("Error parsing season or episode for manual %s" % args['action'])
                return
            except KeyError:
                pass
        else:
            media_type = utils.getMediaType()
            if not utils.isValidMediaType(media_type):
                logger.debug("Error, not in video library.")
                return
            data['dbid'] = int(xbmc.getInfoLabel('ListItem.DBID'))

        if media_type is None:
            logger.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:
                logger.debug("Manual %s of library '%s' with an ID of '%s'." % (args['action'], media_type, data['dbid']))
                if utils.isMovie(media_type):
                    result = utils.getMovieDetailsFromKodi(data['dbid'], ['imdbnumber', 'title', 'year'])
                    if not result:
                        logger.debug("No data was returned from Kodi, aborting manual %s." % args['action'])
                        return

                elif utils.isShow(media_type):
                    tvshow_id = data['dbid']

                elif utils.isSeason(media_type):
                    result = utils.getSeasonDetailsFromKodi(data['dbid'], ['tvshowid', 'season'])
                    if not result:
                        logger.debug("No data was returned from Kodi, aborting manual %s." % args['action'])
                        return
                    tvshow_id = result['tvshowid']
                    data['season'] = result['season']

                elif utils.isEpisode(media_type):
                    result = utils.getEpisodeDetailsFromKodi(data['dbid'], ['season', 'episode', 'tvshowid'])
                    if not result:
                        logger.debug("No data was returned from Kodi, aborting manual %s." % args['action'])
                        return
                    tvshow_id = result['tvshowid']
                    data['season'] = result['season']
                    data['episode'] = result['episode']

                if utils.isShow(media_type) or utils.isSeason(media_type) or utils.isEpisode(media_type):
                    result = utils.getShowDetailsFromKodi(tvshow_id, ['imdbnumber'])
                    if not result:
                        logger.debug("No data was returned from Kodi, aborting manual %s." % args['action'])
                        return
                    
                data['video_id'] = result['imdbnumber']
            else:
                data['video_id'] = data['remoteid']
                if 'season' in data and 'episode' in data:
                    logger.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']))
                elif 'season' in data:
                    logger.debug("Manual %s of non-library '%s' S%02d, with an ID of '%s'." % (args['action'], media_type, data['season'], data['remoteid']))
                else:
                    logger.debug("Manual %s of non-library '%s' with an ID of '%s'." % (args['action'], media_type, 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:
            logger.debug("Manual %s of '%s' is unsupported." % (args['action'], media_type))

    elif args['action'] == 'togglewatched':
        media_type = utils.getMediaType()
        if media_type in ['movie', 'show', 'season', 'episode']:
            data = {'media_type': media_type}
            if utils.isMovie(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = utils.getMovieDetailsFromKodi(dbid, ['imdbnumber', 'title', 'year', 'playcount'])
                if result:
                    if result['playcount'] == 0:
                        data['id'] = result['imdbnumber']
                    else:
                        logger.debug("Movie alread marked as watched in Kodi.")
                else:
                    logger.debug("Error getting movie details from Kodi.")
                    return

            elif utils.isEpisode(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = utils.getEpisodeDetailsFromKodi(dbid, ['showtitle', 'season', 'episode', 'tvshowid', 'playcount'])
                if result:
                    if result['playcount'] == 0:
                        data['id'] = result['imdbnumber']
                        data['season'] = result['season']
                        data['number'] = result['episode']
                        data['title'] = result['showtitle']
                    else:
                        logger.debug("Episode already marked as watched in Kodi.")
                else:
                    logger.debug("Error getting episode details from Kodi.")
                    return

            elif utils.isSeason(media_type):
                showID = None
                showTitle = xbmc.getInfoLabel('ListItem.TVShowTitle')
                result = utils.kodiJsonRequest({'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']
                            data['title'] = show['title']
                            break
                else:
                    logger.debug("Error getting TV shows from Kodi.")
                    return

                season = xbmc.getInfoLabel('ListItem.Season')
                if season == "":
                    season = 0
                else:
                    season = int(season)

                result = utils.kodiJsonRequest({'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:
                        logger.debug("'%s - Season %d' is already marked as watched." % (showTitle, season))
                        return

                    data['season'] = season
                    data['episodes'] = episodes
                else:
                    logger.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.getShowDetailsFromKodi(dbid, ['year', 'imdbnumber'])
                if not result:
                    logger.debug("Error getting show details from Kodi.")
                    return
                showTitle = result['label']
                data['id'] = result['imdbnumber']
                result = utils.kodiJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': dbid, 'properties': ['season', 'episode', 'playcount', 'showtitle']}, 'id': 0})
                if result and 'episodes' in result:
                    i = 0
                    s = {}
                    for e in result['episodes']:
                        data['title'] = e['showtitle']
                        season = str(e['season'])
                        if not season in s:
                            s[season] = []
                        if e['playcount'] == 0:
                            s[season].append(e['episode'])
                            i += 1

                    if i == 0:
                        logger.debug("'%s' is already marked as watched." % showTitle)
                        return

                    data['seasons'] = dict((k, v) for k, v in s.iteritems() if v)
                else:
                    logger.debug("Error getting episode details for '%s' from Kodi." % showTitle)
                    return

            if len(data) > 1:
                logger.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)")

    q = sqlitequeue.SqliteQueue()
    if 'action' in data:
        logger.debug("Queuing for dispatch: %s" % data)
        q.append(data)
コード例 #28
0
def Main():
    args = __getArguments()
    data = {}

    if args['action'] == 'pin_info':
        xbmc.executebuiltin(
            'Dialog.Close(all, true)'
        )  #FIXME stupid hack we need to do as the AddonInfo dialog won't go away
        xbmc.executebuiltin('Dialog.Close(all, true)')
        gui_utils.get_pin()

    if args['action'] == 'contextmenu':
        buttons = []
        media_type = utils.getMediaType()

        if media_type in ['movie', 'show', 'season', 'episode']:
            buttons.append("rate")
            buttons.append("togglewatched")
            buttons.append("addtowatchlist")

        buttons.append("sync")

        contextMenu = traktContextMenu(media_type=media_type, buttons=buttons)
        contextMenu.doModal()
        _action = contextMenu.action
        del contextMenu

        if _action is None:
            return

        logger.debug("'%s' selected from trakt.tv action menu" % _action)
        args['action'] = _action

    if args['action'] == 'sync':
        data = {'action': 'manualSync', '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'] in ['rate', 'unrate']:
        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:
                logger.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']
            try:
                data['season'] = int(args['season'])
                data['episode'] = int(args['episode'])
            except ValueError:
                logger.debug("Error parsing season or episode for manual %s" %
                             args['action'])
                return
            except KeyError:
                pass
        else:
            media_type = utils.getMediaType()
            if not utils.isValidMediaType(media_type):
                logger.debug("Error, not in video library.")
                return
            data['dbid'] = int(xbmc.getInfoLabel('ListItem.DBID'))

        if media_type is None:
            logger.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:
                logger.debug("Manual %s of library '%s' with an ID of '%s'." %
                             (args['action'], media_type, data['dbid']))
                if utils.isMovie(media_type):
                    result = utils.getMovieDetailsFromKodi(
                        data['dbid'], ['imdbnumber', 'title', 'year'])
                    if not result:
                        logger.debug(
                            "No data was returned from Kodi, aborting manual %s."
                            % args['action'])
                        return

                elif utils.isShow(media_type):
                    tvshow_id = data['dbid']

                elif utils.isSeason(media_type):
                    result = utils.getSeasonDetailsFromKodi(
                        data['dbid'], ['tvshowid', 'season'])
                    if not result:
                        logger.debug(
                            "No data was returned from Kodi, aborting manual %s."
                            % args['action'])
                        return
                    tvshow_id = result['tvshowid']
                    data['season'] = result['season']

                elif utils.isEpisode(media_type):
                    result = utils.getEpisodeDetailsFromKodi(
                        data['dbid'], ['season', 'episode', 'tvshowid'])
                    if not result:
                        logger.debug(
                            "No data was returned from Kodi, aborting manual %s."
                            % args['action'])
                        return
                    tvshow_id = result['tvshowid']
                    data['season'] = result['season']
                    data['episode'] = result['episode']

                if utils.isShow(media_type) or utils.isSeason(
                        media_type) or utils.isEpisode(media_type):
                    result = utils.getShowDetailsFromKodi(
                        tvshow_id, ['imdbnumber'])
                    if not result:
                        logger.debug(
                            "No data was returned from Kodi, aborting manual %s."
                            % args['action'])
                        return

                data['video_id'] = result['imdbnumber']
            else:
                data['video_id'] = data['remoteid']
                if 'season' in data and 'episode' in data:
                    logger.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']))
                elif 'season' in data:
                    logger.debug(
                        "Manual %s of non-library '%s' S%02d, with an ID of '%s'."
                        % (args['action'], media_type, data['season'],
                           data['remoteid']))
                else:
                    logger.debug(
                        "Manual %s of non-library '%s' with an ID of '%s'." %
                        (args['action'], media_type, 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:
            logger.debug("Manual %s of '%s' is unsupported." %
                         (args['action'], media_type))

    elif args['action'] == 'togglewatched':
        media_type = utils.getMediaType()
        if media_type in ['movie', 'show', 'season', 'episode']:
            data = {'media_type': media_type}
            if utils.isMovie(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = utils.getMovieDetailsFromKodi(
                    dbid, ['imdbnumber', 'title', 'year', 'playcount'])
                if result:
                    if result['playcount'] == 0:
                        data['id'] = result['imdbnumber']
                    else:
                        logger.debug("Movie alread marked as watched in Kodi.")
                else:
                    logger.debug("Error getting movie details from Kodi.")
                    return

            elif utils.isEpisode(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = utils.getEpisodeDetailsFromKodi(
                    dbid, [
                        'showtitle', 'season', 'episode', 'tvshowid',
                        'playcount'
                    ])
                if result:
                    if result['playcount'] == 0:
                        data['id'] = result['imdbnumber']
                        data['season'] = result['season']
                        data['number'] = result['episode']
                        data['title'] = result['showtitle']
                    else:
                        logger.debug(
                            "Episode already marked as watched in Kodi.")
                else:
                    logger.debug("Error getting episode details from Kodi.")
                    return

            elif utils.isSeason(media_type):
                showID = None
                showTitle = xbmc.getInfoLabel('ListItem.TVShowTitle')
                result = utils.kodiJsonRequest({
                    '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']
                            data['title'] = show['title']
                            break
                else:
                    logger.debug("Error getting TV shows from Kodi.")
                    return

                season = xbmc.getInfoLabel('ListItem.Season')
                if season == "":
                    season = 0
                else:
                    season = int(season)

                result = utils.kodiJsonRequest({
                    '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:
                        logger.debug(
                            "'%s - Season %d' is already marked as watched." %
                            (showTitle, season))
                        return

                    data['season'] = season
                    data['episodes'] = episodes
                else:
                    logger.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.getShowDetailsFromKodi(dbid,
                                                      ['year', 'imdbnumber'])
                if not result:
                    logger.debug("Error getting show details from Kodi.")
                    return
                showTitle = result['label']
                data['id'] = result['imdbnumber']
                result = utils.kodiJsonRequest({
                    'jsonrpc': '2.0',
                    'method': 'VideoLibrary.GetEpisodes',
                    'params': {
                        'tvshowid':
                        dbid,
                        'properties':
                        ['season', 'episode', 'playcount', 'showtitle']
                    },
                    'id': 0
                })
                if result and 'episodes' in result:
                    i = 0
                    s = {}
                    for e in result['episodes']:
                        data['title'] = e['showtitle']
                        season = str(e['season'])
                        if not season in s:
                            s[season] = []
                        if e['playcount'] == 0:
                            s[season].append(e['episode'])
                            i += 1

                    if i == 0:
                        logger.debug("'%s' is already marked as watched." %
                                     showTitle)
                        return

                    data['seasons'] = dict(
                        (k, v) for k, v in s.iteritems() if v)
                else:
                    logger.debug(
                        "Error getting episode details for '%s' from Kodi." %
                        showTitle)
                    return

            if len(data) > 1:
                logger.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'] == 'addtowatchlist':
        media_type = utils.getMediaType()
        if media_type in ['movie', 'show', 'season', 'episode']:
            data = {'media_type': media_type}
            if utils.isMovie(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = utils.getMovieDetailsFromKodi(
                    dbid, ['imdbnumber', 'title', 'year', 'playcount'])
                if result:
                    data['id'] = result['imdbnumber']

                else:
                    logger.debug("Error getting movie details from Kodi.")
                    return

            elif utils.isEpisode(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = utils.getEpisodeDetailsFromKodi(
                    dbid, [
                        'showtitle', 'season', 'episode', 'tvshowid',
                        'playcount'
                    ])
                if result:
                    data['id'] = result['imdbnumber']
                    data['season'] = result['season']
                    data['number'] = result['episode']
                    data['title'] = result['showtitle']

                else:
                    logger.debug("Error getting episode details from Kodi.")
                    return

            elif utils.isSeason(media_type):
                showID = None
                showTitle = xbmc.getInfoLabel('ListItem.TVShowTitle')
                result = utils.kodiJsonRequest({
                    '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']
                            data['title'] = show['title']
                            break
                else:
                    logger.debug("Error getting TV shows from Kodi.")
                    return

                season = xbmc.getInfoLabel('ListItem.Season')
                if season == "":
                    season = 0
                else:
                    season = int(season)

                result = utils.kodiJsonRequest({
                    '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'])

                    data['season'] = season
                    data['episodes'] = episodes
                else:
                    logger.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.getShowDetailsFromKodi(dbid,
                                                      ['year', 'imdbnumber'])
                if not result:
                    logger.debug("Error getting show details from Kodi.")
                    return
                showTitle = result['label']
                data['id'] = result['imdbnumber']
                result = utils.kodiJsonRequest({
                    'jsonrpc': '2.0',
                    'method': 'VideoLibrary.GetEpisodes',
                    'params': {
                        'tvshowid':
                        dbid,
                        'properties':
                        ['season', 'episode', 'playcount', 'showtitle']
                    },
                    'id': 0
                })
                if result and 'episodes' in result:
                    s = {}
                    for e in result['episodes']:
                        data['title'] = e['showtitle']
                        season = str(e['season'])
                        if not season in s:
                            s[season] = []
                        if e['playcount'] == 0:
                            s[season].append(e['episode'])

                    data['seasons'] = dict(
                        (k, v) for k, v in s.iteritems() if v)
                else:
                    logger.debug(
                        "Error getting episode details for '%s' from Kodi." %
                        showTitle)
                    return

            if len(data) > 1:
                logger.debug(
                    "Adding '%s' with the following data '%s' to users watchlist on Trakt.tv"
                    % (media_type, str(data)))
                data['action'] = 'addtowatchlist'

    q = sqlitequeue.SqliteQueue()
    if 'action' in data:
        logger.debug("Queuing for dispatch: %s" % data)
        q.append(data)
コード例 #29
0
ファイル: service.py プロジェクト: beljim/tknorris-beta-repo
    def onPlayBackStarted(self):
        xbmc.sleep(1000)
        self.type = None
        self.id = None

        # only do anything if we're playing a video
        if self.isPlayingVideo():
            # get item data from json rpc
            result = utilities.kodiJsonRequest({'jsonrpc': '2.0', 'method': 'Player.GetItem', 'params': {'playerid': 1}, 'id': 1})
            logger.debug("[traktPlayer] onPlayBackStarted() - %s" % result)

            # check for exclusion
            _filename = None
            try:
                _filename = self.getPlayingFile()
            except:
                logger.debug("[traktPlayer] onPlayBackStarted() - Exception trying to get playing filename, player suddenly stopped.")
                return

            if utilities.checkExclusion(_filename):
                logger.debug("[traktPlayer] onPlayBackStarted() - '%s' is in exclusion settings, ignoring." % _filename)
                return

            self.type = result['item']['type']

            data = {'action': 'started'}

            # check type of item
            if 'id' not in result['item']:
                # do a deeper check to see if we have enough data to perform scrobbles
                logger.debug("[traktPlayer] onPlayBackStarted() - Started playing a non-library file, checking available data.")

                season = xbmc.getInfoLabel('VideoPlayer.Season')
                episode = xbmc.getInfoLabel('VideoPlayer.Episode')
                showtitle = xbmc.getInfoLabel('VideoPlayer.TVShowTitle')
                year = xbmc.getInfoLabel('VideoPlayer.Year')
                video_ids = xbmcgui.Window(10000).getProperty('script.trakt.ids')
                if video_ids:
                    data['video_ids'] = json.loads(video_ids)

                logger.debug("[traktPlayer] info - ids: %s, showtitle: %s, Year: %s, Season: %s, Episode: %s" % (video_ids, showtitle, year, season, episode))

                if season and episode and (showtitle or video_ids):
                    # we have season, episode and either a show title or video_ids, can scrobble this as an episode
                    self.type = 'episode'
                    data['type'] = 'episode'
                    data['season'] = int(season)
                    data['episode'] = int(episode)
                    data['showtitle'] = showtitle
                    data['title'] = xbmc.getInfoLabel('VideoPlayer.Title')
                    if year.isdigit():
                        data['year'] = int(year)
                    logger.debug("[traktPlayer] onPlayBackStarted() - Playing a non-library 'episode' - %s - S%02dE%02d - %s." % (data['showtitle'], data['season'], data['episode'], data['title']))
                elif (year or video_ids) and not season and not showtitle:
                    # we have a year or video_id and no season/showtitle info, enough for a movie
                    self.type = 'movie'
                    data['type'] = 'movie'
                    if year.isdigit():
                        data['year'] = int(year)
                    data['title'] = xbmc.getInfoLabel('VideoPlayer.Title')
                    logger.debug("[traktPlayer] onPlayBackStarted() - Playing a non-library 'movie' - %s (%s)." % (data['title'], data.get('year', 'NaN')))
                elif showtitle:
                    title, season, episode = utilities.regex_tvshow(False, showtitle)
                    data['type'] = 'episode'
                    data['season'] = int(season)
                    data['episode'] = int(episode)
                    data['showtitle'] = title
                    data['title'] = title
                    logger.debug("[traktPlayer] onPlayBackStarted() - Title: %s, showtitle: %s, season: %d, episode: %d" % (title, showtitle, season, episode))
                else:
                    logger.debug("[traktPlayer] onPlayBackStarted() - Non-library file, not enough data for scrobbling, skipping.")
                    return

            elif self.type == 'episode' or self.type == 'movie':
                # get library id
                self.id = result['item']['id']
                data['id'] = self.id
                data['type'] = self.type

                if self.type == 'episode':
                    logger.debug("[traktPlayer] onPlayBackStarted() - Doing multi-part episode check.")
                    result = utilities.kodiJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodeDetails', 'params': {'episodeid': self.id, 'properties': ['tvshowid', 'season', 'episode', 'file']}, 'id': 1})
                    if result:
                        logger.debug("[traktPlayer] onPlayBackStarted() - %s" % result)
                        tvshowid = int(result['episodedetails']['tvshowid'])
                        season = int(result['episodedetails']['season'])
                        currentfile = result['episodedetails']['file']

                        result = utilities.kodiJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': tvshowid, 'season': season, 'properties': ['episode', 'file'], 'sort': {'method': 'episode'}}, 'id': 1})
                        if result:
                            logger.debug("[traktPlayer] onPlayBackStarted() - %s" % result)
                            # make sure episodes array exists in results
                            if 'episodes' in result:
                                multi = []
                                for i in range(result['limits']['start'], result['limits']['total']):
                                    if currentfile == result['episodes'][i]['file']:
                                        multi.append(result['episodes'][i]['episodeid'])
                                if len(multi) > 1:
                                    data['multi_episode_data'] = multi
                                    data['multi_episode_count'] = len(multi)
                                    logger.debug("[traktPlayer] onPlayBackStarted() - This episode is part of a multi-part episode.")
                                else:
                                    logger.debug("[traktPlayer] onPlayBackStarted() - This is a single episode.")

            else:
                logger.debug("[traktPlayer] onPlayBackStarted() - Video type '%s' unrecognized, skipping." % self.type)
                return

            pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            plSize = len(pl)
            if plSize > 1:
                pos = pl.getposition()
                if not self.plIndex is None:
                    logger.debug("[traktPlayer] onPlayBackStarted() - User manually skipped to next (or previous) video, forcing playback ended event.")
                    self.onPlayBackEnded()
                self.plIndex = pos
                logger.debug("[traktPlayer] onPlayBackStarted() - Playlist contains %d item(s), and is currently on item %d" % (plSize, (pos + 1)))

            self._playing = True

            # send dispatch
            self.action(data)