def clean_movies(daemon=False):
    """Cleans trakt.tv movie database.

    Checks if trakt contains any movies that the xbmc database doesn't and if any
    are found unlibraries them on trakt.
    """
    if not daemon:
        progress = xbmcgui.DialogProgress()
        progress.create(_(200), _(171))

    trakt_movies = utilities.traktMovieListByImdbID(utilities.getMoviesFromTrakt())
    xbmc_movies = utilities.xbmcMovieListByImdbID(utilities.getMoviesFromXBMC())

    clean_list = []
    index = 0
    length = len(trakt_movies)

    for imdbid in trakt_movies:
        if not daemon:
            index += 1
            progress.update(int(float(index)/length*100), _(171))

        if imdbid not in xbmc_movies:
            clean_list.append({'imdb_id': imdbid, 'title': trakt_movies[imdbid]['title'], 'year': trakt_movies[imdbid]['year']})

    if len(clean_list) > 0:
        utilities.traktJsonRequest('POST', '/movie/unlibrary/%%API_KEY%%', {'movies': clean_list})

    if not daemon:
        progress.close()
Beispiel #2
0
	def rateOnTrakt(self, rating):
		if self.media_type == 'movie':
			params = {'title': self.media['title'], 'year': self.media['year'], 'rating': rating}

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

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

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

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

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

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

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

		if data != None:
			notification(__language__(1201).encode('utf-8', 'ignore'), __language__(1167).encode('utf-8', 'ignore')) # Rating submitted successfully
def _send_episodes_to_trakt(collected, watched):
    """Send collected and watched statuses to trakt"""
    conn = utilities.getTraktConnection()
    for to_send in collected:
        utilities.traktJsonRequest('POST', '/show/episode/library/%%API_KEY%%', to_send, conn=conn)
    for to_send in watched:
        utilities.traktJsonRequest('POST', '/show/episode/seen/%%API_KEY%%', to_send, conn=conn)
Beispiel #4
0
    def AddToTrakt(self):
        Debug(
            '[Movies Sync] Checking for XBMC movies that are not on trakt.tv')
        if self.show_progress:
            progress.update(30,
                            line1=__getstring__(1425),
                            line2=' ',
                            line3=' ')

        add_to_trakt = []
        trakt_imdb_ids = [
            x['imdb_id'] for x in self.trakt_movies_collection
            if 'imdb_id' in x
        ]
        trakt_tmdb_ids = [
            x['tmdb_id'] for x in self.trakt_movies_collection
            if 'tmdb_id' in x
        ]
        trakt_titles = [
            x['title'] for x in self.trakt_movies_collection if 'title' in x
        ]

        for xbmc_movie in self.xbmc_movies:
            #Compare IMDB IDs
            if xbmc_movie['imdbnumber'].startswith('tt'):
                if xbmc_movie['imdbnumber'] not in trakt_imdb_ids:
                    Debug('[Movies Sync][AddToTrakt] %s' % xbmc_movie)
                    add_to_trakt.append(xbmc_movie)

            #Compare TMDB IDs
            elif xbmc_movie['imdbnumber'].isdigit():
                if xbmc_movie['imdbnumber'] not in trakt_tmdb_ids:
                    Debug('[Movies Sync][AddToTrakt] %s' % xbmc_movie)
                    add_to_trakt.append(xbmc_movie)

            #Compare titles if unknown ID type
            else:
                if xbmc_movie['title'] not in trakt_titles:
                    Debug('[Movies Sync][AddToTrakt] %s' % xbmc_movie)
                    add_to_trakt.append(xbmc_movie)

        if add_to_trakt:
            Debug(
                '[Movies Sync] %i movie(s) will be added to trakt.tv collection'
                % len(add_to_trakt))
            if self.Canceled():
                return

            if self.show_progress:
                progress.update(45,
                                line2='%i %s' %
                                (len(add_to_trakt), __getstring__(1426)))

            traktJsonRequest(
                'POST', '/movie/library/%%API_KEY%%',
                {'movies': [xbmc_to_trakt_movie(x) for x in add_to_trakt]})

        else:
            Debug('[Movies Sync] trakt.tv movie collection is up to date')
Beispiel #5
0
def rateMedia(media_id, media_type):
	"""Launches the rating dialog"""
	if media_id == None:
		Debug('[Rating] Missing media_id')
		return

	if media_type == 'movie':
		xbmc_media = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovieDetails', 'params': {'movieid': media_id, 'properties': ['title', 'imdbnumber', 'year']}})['moviedetails']
		if xbmc_media == None:
			Debug('[Rating] Failed to retrieve movie data from XBMC')
			return

		trakt_summary = traktJsonRequest('POST', '/movie/summary.json/%%API_KEY%%/' + xbmc_media['imdbnumber'])
		if trakt_summary == None:
			Debug('[Rating] Failed to retrieve movie data from trakt')
			return

		if trakt_summary['rating'] or trakt_summary['rating_advanced']:
			Debug('[Rating] Movie has been rated')
			return

	else:
		episode = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetEpisodeDetails', 'params': {'episodeid': media_id, 'properties': ['uniqueid', 'tvshowid', 'episode', 'season']}})['episodedetails']
		if episode == None:
			Debug('[Rating] Failed to retrieve episode data from XBMC')
			return

		xbmc_media = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetTVShowDetails', 'params': {'tvshowid': episode['tvshowid'], 'properties': ['imdbnumber']}})['tvshowdetails']
		if xbmc_media == None:
			Debug('[Rating] Failed to retrieve tvshow data from XBMC')
			return

		xbmc_media['episode'] = episode

		trakt_summary = traktJsonRequest('POST', '/show/episode/summary.json/%%API_KEY%%/'+str(xbmc_media['imdbnumber'])+'/'+str(xbmc_media['episode']['season'])+'/'+str(xbmc_media['episode']['episode']))
		if trakt_summary == None:
			Debug('[Rating] Failed to retrieve show/episode data from trakt')
			return

		xbmc_media['year'] = trakt_summary['show']['year']

		if trakt_summary['episode']['rating'] or trakt_summary['episode']['rating_advanced']:
			Debug('[Rating] Episode has been rated')
			return

	rating_type = utilities.traktSettings['viewing']['ratings']['mode']
	xbmc.executebuiltin('Dialog.Close(all, true)')

	gui = RatingDialog(
		"RatingDialog.xml",
		__settings__.getAddonInfo('path'),
		media_type=media_type,
		media=xbmc_media,
		rating_type=rating_type
	)

	gui.doModal()
	del gui
Beispiel #6
0
    def RemoveFromTrakt(self):
        Debug('[Movies Sync] Cleaning trakt movie collection')
        if self.show_progress:
            progress.update(95,
                            line1=__getstring__(1443),
                            line2=' ',
                            line3=' ')

        remove_from_trakt = []
        xbmc_imdb_ids = [
            x['imdbnumber'] for x in self.xbmc_movies
            if x['imdbnumber'].startswith('tt')
        ]
        xbmc_tmdb_ids = [
            x['imdbnumber'] for x in self.xbmc_movies
            if x['imdbnumber'].isdigit()
        ]
        xbmc_titles = [x['title'] for x in self.xbmc_movies]

        for trakt_movie in self.trakt_movies_collection:
            remove = True
            if 'imdb_id' in trakt_movie and trakt_movie[
                    'imdb_id'] in xbmc_imdb_ids:
                remove = False
            if 'tmdb_id' in trakt_movie and trakt_movie[
                    'tmdb_id'] in xbmc_tmdb_ids:
                remove = False
            if trakt_movie['title'] in xbmc_titles:
                remove = False

            if remove:
                Debug(
                    '[Movies Sync] %s (%i) will be removed from trakt collection'
                    % (trakt_movie['title'].encode('utf-8'),
                       trakt_movie['year']))
                remove_from_trakt.append(trakt_movie)

        if remove_from_trakt:
            Debug(
                '[Movies Sync] %i movie(s) will be removed from trakt.tv collection'
                % len(remove_from_trakt))

            if self.Canceled():
                return

            if self.show_progress:
                progress.update(95,
                                line2='%i %s' %
                                (len(remove_from_trakt), __getstring__(1444)))
            traktJsonRequest('POST', '/movie/unlibrary/%%API_KEY%%',
                             {'movies': remove_from_trakt})

        else:
            Debug('[Movies Sync] trakt.tv movie collection is clean')
def _clean_show_diff(tvdbid, trakt_shows, xbmc_shows):
    """ Remove show episodes not on xbmc from the trakt library """
    to_send = {'tvdb_id': tvdbid, 'title': trakt_shows[tvdbid]['title'], 'year': trakt_shows[tvdbid]['year'], 'episodes': {}}
    xbmc_show = xbmc_shows[tvdbid]['data']
    trakt_show = trakt_shows[tvdbid]['data']

    for season_num in trakt_show:
        for episode_num in trakt_show[season_num]:
            if trakt_show[season_num][episode_num][0] == True and (season_num not in xbmc_show or episode_num not in xbmc_show[season_num]):
                to_send['episodes'].append({'season': season_num, 'episode': episode_num})

    utilities.traktJsonRequest('POST', '/show/episode/unlibrary', to_send)
Beispiel #8
0
    def UpdatePlaysTrakt(self):
        Debug("[Movies Sync] Checking if trakt.tv playcount is up to date")
        if self.show_progress:
            progress.update(60, line1=__getstring__(1427), line2=" ", line3=" ")

        update_playcount = []
        trakt_playcounts = {}
        xbmc_movies_seen = [x for x in self.xbmc_movies if x["playcount"]]

        for trakt_movie in self.trakt_movies_seen:
            if "tmdb_id" in trakt_movie:
                trakt_playcounts[trakt_movie["tmdb_id"]] = trakt_movie["plays"]

            if "imdb_id" in trakt_movie:
                trakt_playcounts[trakt_movie["imdb_id"]] = trakt_movie["plays"]

            trakt_playcounts[trakt_movie["title"]] = trakt_movie["plays"]

        for xbmc_movie in xbmc_movies_seen:
            if xbmc_movie["imdbnumber"] in trakt_playcounts:
                if trakt_playcounts[xbmc_movie["imdbnumber"]] < xbmc_movie["playcount"]:
                    Debug("[Movies Sync][UpdatePlaysTrakt] %s" % xbmc_movie)
                    update_playcount.append(xbmc_movie)
                else:
                    pass

            elif xbmc_movie["title"] in trakt_playcounts:
                if trakt_playcounts[xbmc_movie["title"]] < xbmc_movie["playcount"]:
                    Debug("[Movies Sync][UpdatePlaysTrakt][Update] %s" % xbmc_movie)
                    update_playcount.append(xbmc_movie)
                else:
                    pass

            else:
                Debug("[Movies Sync][UpdatePlaysTrakt][Update] %s" % xbmc_movie)
                update_playcount.append(xbmc_movie)

        if update_playcount:
            Debug("[Movies Sync] %i movie(s) playcount will be updated on trakt.tv" % len(update_playcount))
            if self.Canceled():
                return

            if self.show_progress:
                progress.update(75, line2="%i %s" % (len(update_playcount), __getstring__(1428)))

                # Send request to update playcounts on trakt.tv
            params = {"movies": [xbmc_to_trakt_movie(x, playcount=True) for x in update_playcount]}
            traktJsonRequest("POST", "/movie/seen/%%API_KEY%%", params)

        else:
            Debug("[Movies Sync] trakt.tv movie playcount is up to date")
def sync_movies(daemon=False):
    """Sync playcounts and collection status between trakt and xbmc.

    Scans XBMC and trakt and updates the play count of each movie in both the xbmc
    and trakt libraries based on which is higher. If the movie exists in xbmc
    but is not collected in trakt it is set as collected too.
    """
    if not daemon:
        progress = xbmcgui.DialogProgress()
        progress.create(_(200), _(172))

    # Generate list of movies keyed with their imdb id
    trakt_movies = utilities.traktMovieListByImdbID(utilities.getMoviesFromTrakt())
    xbmc_movies = utilities.xbmcMovieListByImdbID(utilities.getMoviesFromXBMC())

    xbmc_playcount_update = []
    trakt_playcount_update = []
    trakt_collection_update = []

    for imdbid in xbmc_movies:
        if imdbid not in trakt_movies:
            trakt_collection_update.append({'imdb_id': imdbid, 'title': xbmc_movies[imdbid]['title'], 'year': xbmc_movies[imdbid]['year']})

            if xbmc_movies[imdbid]['playcount'] > 0:
                trakt_playcount_update.append({'imdb_id': imdbid, 'title': xbmc_movies[imdbid]['title'], 'year': xbmc_movies[imdbid]['year'], 'plays': xbmc_movies[imdbid]['playcount'], 'last_played': xbmc_movies[imdbid]['lastplayed']})

            continue

        if xbmc_movies[imdbid]['playcount'] > trakt_movies[imdbid]['plays']:
            trakt_playcount_update.append({'imdb_id': imdbid, 'title': xbmc_movies[imdbid]['title'], 'year': xbmc_movies[imdbid]['year'], 'plays': xbmc_movies[imdbid]['playcount'], 'last_played': xbmc_movies[imdbid]['lastplayed']})
        elif xbmc_movies[imdbid]['playcount'] < trakt_movies[imdbid]['plays']:
            xbmc_playcount_update.append((xbmc_movies[imdbid]['movieid'], trakt_movies[imdbid]['plays'], imdbid))

    if not daemon:
        progress.update(0, _(173))

    if len(trakt_collection_update) > 0:
        utilities.traktJsonRequest('POST', '/movie/library/%%API_KEY%%', {'movies': trakt_collection_update})

    if len(trakt_playcount_update) > 0:
        utilities.setMoviesSeenOnTrakt(trakt_playcount_update)

    if len(xbmc_playcount_update) > 0:
        if not daemon:
            _update_xbmc_movie_playcounts(xbmc_playcount_update, progress, daemon)
        else:
            _update_xbmc_movie_playcounts(xbmc_playcount_update, None, True)

    if not daemon:
        progress.close()
Beispiel #10
0
 def GetFromTraktSeen(self):
     Debug("[Movie Sync] Getting seen movies from trakt.tv")
     if self.show_progress:
         progress.update(15, line1=__getstring__(1424), line2=" ", line3=" ")
     self.trakt_movies_seen = traktJsonRequest(
         "POST", "/user/library/movies/watched.json/%%API_KEY%%/%%USERNAME%%/min"
     )
Beispiel #11
0
 def GetFromTraktCollection(self):
     Debug("[Movie Sync] Getting movie collection from trakt.tv")
     if self.show_progress:
         progress.update(10, line1=__getstring__(1423), line2=" ", line3=" ")
     self.trakt_movies_collection = traktJsonRequest(
         "POST", "/user/library/movies/collection.json/%%API_KEY%%/%%USERNAME%%/min"
     )
Beispiel #12
0
 def GetFromTraktSeen(self):
     Debug('[Movies Sync] Getting seen movies from trakt.tv')
     if self.show_progress:
         progress.update(15,
                         line1=__getstring__(1424),
                         line2=' ',
                         line3=' ')
     self.trakt_movies_seen = traktJsonRequest(
         'POST',
         '/user/library/movies/watched.json/%%API_KEY%%/%%USERNAME%%/min')
Beispiel #13
0
    def AddToTrakt(self):
        Debug("[Movies Sync] Checking for XBMC movies that are not on trakt.tv")
        if self.show_progress:
            progress.update(30, line1=__getstring__(1425), line2=" ", line3=" ")

        add_to_trakt = []
        trakt_imdb_ids = [x["imdb_id"] for x in self.trakt_movies_collection if "imdb_id" in x]
        trakt_tmdb_ids = [x["tmdb_id"] for x in self.trakt_movies_collection if "tmdb_id" in x]
        trakt_titles = [x["title"] for x in self.trakt_movies_collection if "title" in x]

        for xbmc_movie in self.xbmc_movies:
            # Compare IMDB IDs
            if xbmc_movie["imdbnumber"].startswith("tt"):
                if xbmc_movie["imdbnumber"] not in trakt_imdb_ids:
                    Debug("[Movies Sync][AddToTrakt] %s" % xbmc_movie)
                    add_to_trakt.append(xbmc_movie)

                    # Compare TMDB IDs
            elif xbmc_movie["imdbnumber"].isdigit():
                if xbmc_movie["imdbnumber"] not in trakt_tmdb_ids:
                    Debug("[Movies Sync][AddToTrakt] %s" % xbmc_movie)
                    add_to_trakt.append(xbmc_movie)

                    # Compare titles if unknown ID type
            else:
                if xbmc_movie["title"] not in trakt_titles:
                    Debug("[Movies Sync][AddToTrakt] %s" % xbmc_movie)
                    add_to_trakt.append(xbmc_movie)

        if add_to_trakt:
            Debug("[Movies Sync] %i movie(s) will be added to trakt.tv collection" % len(add_to_trakt))
            if self.Canceled():
                return

            if self.show_progress:
                progress.update(45, line2="%i %s" % (len(add_to_trakt), __getstring__(1426)))

            traktJsonRequest(
                "POST", "/movie/library/%%API_KEY%%", {"movies": [xbmc_to_trakt_movie(x) for x in add_to_trakt]}
            )

        else:
            Debug("[Movies Sync] trakt.tv movie collection is up to date")
Beispiel #14
0
 def GetFromTraktCollection(self):
     Debug('[Movies Sync] Getting movie collection from trakt.tv')
     if self.show_progress:
         progress.update(10,
                         line1=__getstring__(1423),
                         line2=' ',
                         line3=' ')
     self.trakt_movies_collection = traktJsonRequest(
         'POST',
         '/user/library/movies/collection.json/%%API_KEY%%/%%USERNAME%%/min'
     )
Beispiel #15
0
    def GetWatchedFromTrakt(self):
        Debug('[Episodes Sync] Getting watched episodes from trakt.tv')
        if self.show_progress:
            progress.update(50,
                            line1=__getstring__(1438),
                            line2=' ',
                            line3=' ')

        self.trakt_shows['watched'] = traktJsonRequest(
            'POST',
            '/user/library/shows/watched.json/%%API_KEY%%/%%USERNAME%%/min')
Beispiel #16
0
    def GetCollectionFromTrakt(self):
        Debug('[Episodes Sync] Getting episode collection from trakt.tv')
        if self.show_progress:
            progress.update(15,
                            line1=__getstring__(1434),
                            line2=' ',
                            line3=' ')

        self.trakt_shows['collection'] = traktJsonRequest(
            'POST',
            '/user/library/shows/collection.json/%%API_KEY%%/%%USERNAME%%/min')
Beispiel #17
0
    def RemoveFromTrakt(self):
        Debug("[Movies Sync] Cleaning trakt movie collection")
        if self.show_progress:
            progress.update(95, line1=__getstring__(1443), line2=" ", line3=" ")

        remove_from_trakt = []
        xbmc_imdb_ids = [x["imdbnumber"] for x in self.xbmc_movies if x["imdbnumber"].startswith("tt")]
        xbmc_tmdb_ids = [x["imdbnumber"] for x in self.xbmc_movies if x["imdbnumber"].isdigit()]
        xbmc_titles = [x["title"] for x in self.xbmc_movies]

        for trakt_movie in self.trakt_movies_collection:
            remove = True
            if "imdb_id" in trakt_movie and trakt_movie["imdb_id"] in xbmc_imdb_ids:
                remove = False
            if "tmdb_id" in trakt_movie and trakt_movie["tmdb_id"] in xbmc_tmdb_ids:
                remove = False
            if trakt_movie["title"] in xbmc_titles:
                remove = False

            if remove:
                Debug(
                    "[Movies Sync] %s (%i) will be removed from trakt collection"
                    % (trakt_movie["title"].encode("utf-8"), trakt_movie["year"])
                )
                remove_from_trakt.append(trakt_movie)

        if remove_from_trakt:
            Debug("[Movies Sync] %i movie(s) will be removed from trakt.tv collection" % len(remove_from_trakt))

            if self.Canceled():
                return

            if self.show_progress:
                progress.update(95, line2="%i %s" % (len(remove_from_trakt), __getstring__(1444)))
            traktJsonRequest("POST", "/movie/unlibrary/%%API_KEY%%", {"movies": remove_from_trakt})

        else:
            Debug("[Movies Sync] trakt.tv movie collection is clean")
Beispiel #18
0
    def AddToTrakt(self):
        Debug(
            '[Episodes Sync] Checking for episodes missing from trakt.tv collection'
        )
        if self.show_progress:
            progress.update(30,
                            line1=__getstring__(1435),
                            line2=' ',
                            line3=' ')

        add_to_trakt = []
        trakt_imdb_index = {}
        trakt_tvdb_index = {}
        trakt_title_index = {}

        for i in range(len(self.trakt_shows['collection'])):
            if 'imdb_id' in self.trakt_shows['collection'][i]:
                trakt_imdb_index[self.trakt_shows['collection'][i]
                                 ['imdb_id']] = i

            if 'tvdb_id' in self.trakt_shows['collection'][i]:
                trakt_tvdb_index[self.trakt_shows['collection'][i]
                                 ['tvdb_id']] = i

            trakt_title_index[self.trakt_shows['collection'][i]['title']] = i

        for xbmc_show in self.xbmc_shows:
            missing = []

            #IMDB ID
            if xbmc_show['imdbnumber'].startswith('tt'):
                if xbmc_show['imdbnumber'] not in trakt_imdb_index.keys():
                    missing = xbmc_show['episodes']

                else:
                    trakt_show = self.trakt_shows['collection'][
                        trakt_imdb_index[xbmc_show['imdbnumber']]]
                    missing = compare_show(xbmc_show, trakt_show)

            #TVDB ID
            elif xbmc_show['imdbnumber'].isdigit():
                if xbmc_show['imdbnumber'] not in trakt_tvdb_index.keys():
                    missing = xbmc_show['episodes']

                else:
                    trakt_show = self.trakt_shows['collection'][
                        trakt_tvdb_index[xbmc_show['imdbnumber']]]
                    missing = compare_show(xbmc_show, trakt_show)

            #Title
            else:
                if xbmc_show['title'] not in trakt_title_index.keys():
                    missing = xbmc_show['episodes']

                else:
                    trakt_show = self.trakt_shows['collection'][
                        trakt_title_index[xbmc_show['title']]]
                    missing = compare_show(xbmc_show, trakt_show)

            if missing:
                show = {
                    'title':
                    xbmc_show['title'],
                    'episodes': [{
                        'episode': x['episode'],
                        'season': x['season'],
                        'episode_tvdb_id': x['uniqueid']['unknown']
                    } for x in missing]
                }
                Debug('[Episodes Sync][AddToTrakt] %s' % show)

                if xbmc_show['imdbnumber'].isdigit():
                    show['tvdb_id'] = xbmc_show['imdbnumber']
                else:
                    show['imdb_id'] = xbmc_show['imdbnumber']

                add_to_trakt.append(show)

        if add_to_trakt:
            Debug(
                '[Episodes Sync] %i shows(s) have episodes added to trakt.tv collection'
                % len(add_to_trakt))
            if self.show_progress:
                progress.update(35,
                                line1=__getstring__(1435),
                                line2='%i %s' %
                                (len(add_to_trakt), __getstring__(1436)))

            for show in add_to_trakt:
                if self.Canceled():
                    return
                if self.show_progress:
                    progress.update(
                        45,
                        line1=__getstring__(1435),
                        line2=show['title'].encode('utf-8', 'ignore'),
                        line3='%i %s' %
                        (len(show['episodes']), __getstring__(1437)))

                traktJsonRequest('POST', '/show/episode/library/%%API_KEY%%',
                                 show)

        else:
            Debug('[Episodes Sync] trakt.tv episode collection is up to date')
Beispiel #19
0
    def UpdatePlaysTrakt(self):
        Debug('[Movies Sync] Checking if trakt.tv playcount is up to date')
        if self.show_progress:
            progress.update(60,
                            line1=__getstring__(1427),
                            line2=' ',
                            line3=' ')

        update_playcount = []
        trakt_playcounts = {}
        xbmc_movies_seen = [x for x in self.xbmc_movies if x['playcount']]

        for trakt_movie in self.trakt_movies_seen:
            if 'tmdb_id' in trakt_movie:
                trakt_playcounts[trakt_movie['tmdb_id']] = trakt_movie['plays']

            if 'imdb_id' in trakt_movie:
                trakt_playcounts[trakt_movie['imdb_id']] = trakt_movie['plays']

            trakt_playcounts[trakt_movie['title']] = trakt_movie['plays']

        for xbmc_movie in xbmc_movies_seen:
            if xbmc_movie['imdbnumber'] in trakt_playcounts:
                if trakt_playcounts[
                        xbmc_movie['imdbnumber']] < xbmc_movie['playcount']:
                    Debug('[Movies Sync][UpdatePlaysTrakt] %s' % xbmc_movie)
                    update_playcount.append(xbmc_movie)
                else:
                    pass

            elif xbmc_movie['title'] in trakt_playcounts:
                if trakt_playcounts[
                        xbmc_movie['title']] < xbmc_movie['playcount']:
                    Debug('[Movies Sync][UpdatePlaysTrakt][Update] %s' %
                          xbmc_movie)
                    update_playcount.append(xbmc_movie)
                else:
                    pass

            else:
                Debug('[Movies Sync][UpdatePlaysTrakt][Update] %s' %
                      xbmc_movie)
                update_playcount.append(xbmc_movie)

        if update_playcount:
            Debug(
                '[Movies Sync] %i movie(s) playcount will be updated on trakt.tv'
                % len(update_playcount))
            if self.Canceled():
                return

            if self.show_progress:
                progress.update(75,
                                line2='%i %s' %
                                (len(update_playcount), __getstring__(1428)))

            # Send request to update playcounts on trakt.tv
            params = {
                'movies': [
                    xbmc_to_trakt_movie(x, playcount=True)
                    for x in update_playcount
                ]
            }
            traktJsonRequest('POST', '/movie/seen/%%API_KEY%%', params)

        else:
            Debug('[Movies Sync] trakt.tv movie playcount is up to date')
Beispiel #20
0
    def UpdatePlaysTrakt(self):
        Debug('[Episodes Sync] Checking watched episodes on trakt.tv')
        if self.show_progress:
            progress.update(60,
                            line1=__getstring__(1438),
                            line2=' ',
                            line3=' ')

        update_playcount = []
        trakt_imdb_index = {}
        trakt_tvdb_index = {}
        trakt_title_index = {}

        for i in range(len(self.trakt_shows['watched'])):
            if 'imdb_id' in self.trakt_shows['watched'][i]:
                trakt_imdb_index[self.trakt_shows['watched'][i]['imdb_id']] = i

            if 'tvdb_id' in self.trakt_shows['watched'][i]:
                trakt_tvdb_index[self.trakt_shows['watched'][i]['tvdb_id']] = i

            trakt_title_index[self.trakt_shows['watched'][i]['title']] = i

        xbmc_shows_watched = []
        for show in self.xbmc_shows:
            watched_episodes = [x for x in show['episodes'] if x['playcount']]
            if watched_episodes:
                xbmc_shows_watched.append(show)

        for xbmc_show in xbmc_shows_watched:
            missing = []
            trakt_show = {}

            #IMDB ID
            if xbmc_show['imdbnumber'].startswith('tt') and xbmc_show[
                    'imdbnumber'] in trakt_imdb_index.keys():
                trakt_show = self.trakt_shows['watched'][trakt_imdb_index[
                    xbmc_show['imdbnumber']]]

            #TVDB ID
            elif xbmc_show['imdbnumber'].isdigit(
            ) and xbmc_show['imdbnumber'] in trakt_tvdb_index.keys():
                trakt_show = self.trakt_shows['watched'][trakt_tvdb_index[
                    xbmc_show['imdbnumber']]]

            #Title
            else:
                if xbmc_show['title'] in trakt_title_index.keys():
                    trakt_show = self.trakt_shows['watched'][trakt_title_index[
                        xbmc_show['title']]]

            if trakt_show:
                missing = compare_show_watched_trakt(xbmc_show, trakt_show)
            else:
                missing = [x for x in xbmc_show['episodes'] if x['playcount']]

            if missing:
                show = {
                    'title':
                    xbmc_show['title'],
                    'episodes': [{
                        'episode': x['episode'],
                        'season': x['season'],
                        'episode_tvdb_id': x['uniqueid']['unknown']
                    } for x in missing]
                }
                Debug('[Episodes Sync][UpdatePlaysTrakt] %s' % show)

                if xbmc_show['imdbnumber'].isdigit():
                    show['tvdb_id'] = xbmc_show['imdbnumber']
                else:
                    show['imdb_id'] = xbmc_show['imdbnumber']

                update_playcount.append(show)

        if update_playcount:
            Debug(
                '[Episodes Sync] %i shows(s) shows are missing playcounts on trakt.tv'
                % len(update_playcount))
            if self.show_progress:
                progress.update(65,
                                line1=__getstring__(1438),
                                line2='%i %s' %
                                (len(update_playcount), __getstring__(1439)))

            for show in update_playcount:
                if self.Canceled():
                    return
                if self.show_progress:
                    progress.update(
                        70,
                        line1=__getstring__(1438),
                        line2=show['title'].encode('utf-8', 'ignore'),
                        line3='%i %s' %
                        (len(show['episodes']), __getstring__(1440)))

                traktJsonRequest('POST', '/show/episode/seen/%%API_KEY%%',
                                 show)

        else:
            Debug('[Episodes Sync] trakt.tv episode playcounts are up to date')
Beispiel #21
0
	def UpdatePlaysTrakt(self):
		Debug('[Episodes Sync] Checking watched episodes on trakt.tv')
		if self.show_progress:
			progress.update(60, line1=__getstring__(1438), line2=' ', line3=' ')

		update_playcount = []
		trakt_imdb_index = {}
		trakt_tvdb_index = {}
		trakt_title_index = {}

		for i in range(len(self.trakt_shows['watched'])):
			if 'imdb_id' in self.trakt_shows['watched'][i]:
				trakt_imdb_index[self.trakt_shows['watched'][i]['imdb_id']] = i

			if 'tvdb_id' in self.trakt_shows['watched'][i]:
				trakt_tvdb_index[self.trakt_shows['watched'][i]['tvdb_id']] = i

			trakt_title_index[self.trakt_shows['watched'][i]['title']] = i

		xbmc_shows_watched = []
		for show in self.xbmc_shows:
			watched_episodes = [x for x in show['episodes'] if x['playcount']]
			if watched_episodes:
				xbmc_shows_watched.append(show)

		for xbmc_show in xbmc_shows_watched:
			missing = []
			trakt_show = {}

			#IMDB ID
			if xbmc_show['imdbnumber'].startswith('tt') and xbmc_show['imdbnumber'] in trakt_imdb_index.keys():
				trakt_show = self.trakt_shows['watched'][trakt_imdb_index[xbmc_show['imdbnumber']]]

			#TVDB ID
			elif xbmc_show['imdbnumber'].isdigit() and xbmc_show['imdbnumber'] in trakt_tvdb_index.keys():
				trakt_show = self.trakt_shows['watched'][trakt_tvdb_index[xbmc_show['imdbnumber']]]

			#Title
			else:
				if xbmc_show['title'] in trakt_title_index.keys():
					trakt_show = self.trakt_shows['watched'][trakt_title_index[xbmc_show['title']]]

			if trakt_show:
				missing = compare_show_watched_trakt(xbmc_show, trakt_show)
			else:
				missing = [x for x in xbmc_show['episodes'] if x['playcount']]

			if missing:
				show = {'title': xbmc_show['title'], 'episodes': [{'episode': x['episode'], 'season': x['season'], 'episode_tvdb_id': x['uniqueid']['unknown']} for x in missing]}
				Debug('[Episodes Sync][UpdatePlaysTrakt] %s' % show)

				if xbmc_show['imdbnumber'].isdigit():
					show['tvdb_id'] = xbmc_show['imdbnumber']
				else:
					show['imdb_id'] = xbmc_show['imdbnumber']

				update_playcount.append(show)

		if update_playcount:
			Debug('[Episodes Sync] %i shows(s) shows are missing playcounts on trakt.tv' % len(update_playcount))
			if self.show_progress:
				progress.update(65, line1=__getstring__(1438), line2='%i %s' % (len(update_playcount), __getstring__(1439)))

			for show in update_playcount:
				if self.Canceled():
					return
				if self.show_progress:
					progress.update(70, line1=__getstring__(1438), line2=show['title'].encode('utf-8', 'ignore'), line3='%i %s' % (len(show['episodes']), __getstring__(1440)))

				traktJsonRequest('POST', '/show/episode/seen/%%API_KEY%%', show)

		else:
			Debug('[Episodes Sync] trakt.tv episode playcounts are up to date')
Beispiel #22
0
	def GetWatchedFromTrakt(self):
		Debug('[Episodes Sync] Getting watched episodes from trakt.tv')
		if self.show_progress:
			progress.update(50, line1=__getstring__(1438), line2=' ', line3=' ')

		self.trakt_shows['watched'] = traktJsonRequest('POST', '/user/library/shows/watched.json/%%API_KEY%%/%%USERNAME%%/min')
Beispiel #23
0
    def RemoveFromTrakt(self):
        Debug('[Movies Sync] Cleaning trakt tvshow collection')
        if self.show_progress:
            progress.update(90,
                            line1=__getstring__(1445),
                            line2=' ',
                            line3=' ')

        def convert_seasons(show):
            episodes = []
            if 'seasons' in show and show['seasons']:
                for season in show['seasons']:
                    for episode in season['episodes']:
                        episodes.append({
                            'season': season['season'],
                            'episode': episode
                        })
            return episodes

        remove_from_trakt = []
        indices = {'imdb_id': {}, 'tvdb_id': {}, 'title': {}}

        for i in range(len(self.xbmc_shows)):
            if self.xbmc_shows[i]['imdbnumber'].startswith('tt'):
                indices['imdb_id'][self.xbmc_shows[i]['imdbnumber']] = i

            if self.xbmc_shows[i]['imdbnumber'].isdigit():
                indices['tvdb_id'][self.xbmc_shows[i]['imdbnumber']] = i

            indices['title'][self.xbmc_shows[i]['title']] = i

        for trakt_show in self.trakt_shows['collection']:
            matched = False
            remove = []

            if 'tvdb_id' in trakt_show:
                if trakt_show['tvdb_id'] in indices['tvdb_id']:
                    matched = 'tvdb_id'

            if not matched and 'imdb_id' in trakt_show:
                if trakt_show['imdb_id'] in indices['imdb_id']:
                    matched = 'imdb_id'

            if not matched:
                if trakt_show['title'] in indices['title']:
                    matched = 'title'

            if matched:
                xbmc_show = self.xbmc_shows[indices[matched][
                    trakt_show[matched]]]
                trakt_episodes = convert_seasons(trakt_show)
                xbmc_episodes = [{
                    'season': x['season'],
                    'episode': x['episode']
                } for x in xbmc_show['episodes']]

                for episode in trakt_episodes:
                    if episode not in xbmc_episodes:
                        remove.append(episode)

            else:
                remove = convert_seasons(trakt_show)

            if remove:
                show = {
                    'title': trakt_show['title'],
                    'year': trakt_show['year'],
                    'episodes': remove
                }
                if matched:
                    show[matched] = trakt_show[matched]
                remove_from_trakt.append(show)

        if remove_from_trakt:
            Debug(
                '[Episodes Sync] %ishow(s) will have episodes removed from trakt.tv collection'
                % len(remove_from_trakt))
            if self.show_progress:
                progress.update(90,
                                line1=__getstring__(1445),
                                line2='%i %s' %
                                (len(remove_from_trakt), __getstring__(1446)))

            for show in remove_from_trakt:
                if self.Canceled():
                    return

                if self.show_progress:
                    progress.update(
                        95,
                        line1=__getstring__(1445),
                        line2=show['title'].encode('utf-8', 'ignore'),
                        line3='%i %s' %
                        (len(show['episodes']), __getstring__(1447)))

                traktJsonRequest('POST', '/show/episode/unlibrary/%%API_KEY%%',
                                 show)

        else:
            Debug('[Episodes Sync] trakt.tv episode collection is clean')
def _clean_show(tvdbid, trakt_shows):
    """ Remove an entire show from the trakt library """
    to_send = {'tvdb_id': tvdbid, 'title': trakt_shows[tvdbid]['title'], 'year': trakt_shows[tvdbid]['year']}
    utilities.traktJsonRequest('POST', '/show/unlibrary/%%API_KEY%%', to_send)
Beispiel #25
0
	def GetCollectionFromTrakt(self):
		Debug('[Episodes Sync] Getting episode collection from trakt.tv')
		if self.show_progress:
			progress.update(15, line1=__getstring__(1434), line2=' ', line3=' ')

		self.trakt_shows['collection'] = traktJsonRequest('POST', '/user/library/shows/collection.json/%%API_KEY%%/%%USERNAME%%/min')
Beispiel #26
0
	def RemoveFromTrakt(self):
		Debug('[Movies Sync] Cleaning trakt tvshow collection')
		if self.show_progress:
			progress.update(90, line1=__getstring__(1445), line2=' ', line3=' ')

		def convert_seasons(show):
			episodes = []
			if 'seasons' in show and show['seasons']:
				for season in show['seasons']:
					for episode in season['episodes']:
						episodes.append({'season': season['season'], 'episode': episode})
			return episodes

		remove_from_trakt = []
		indices = {'imdb_id': {}, 'tvdb_id': {}, 'title': {}}

		for i in range(len(self.xbmc_shows)):
			if self.xbmc_shows[i]['imdbnumber'].startswith('tt'):
				indices['imdb_id'][self.xbmc_shows[i]['imdbnumber']] = i

			if self.xbmc_shows[i]['imdbnumber'].isdigit():
				indices['tvdb_id'][self.xbmc_shows[i]['imdbnumber']] = i

			indices['title'][self.xbmc_shows[i]['title']] = i

		for trakt_show in self.trakt_shows['collection']:
			matched = False
			remove = []

			if 'tvdb_id' in trakt_show:
				if trakt_show['tvdb_id'] in indices['tvdb_id']:
					matched = 'tvdb_id'

			if not matched and 'imdb_id' in trakt_show:
				if trakt_show['imdb_id'] in indices['imdb_id']:
					matched = 'imdb_id'

			if not matched:
				if trakt_show['title'] in indices['title']:
					matched = 'title'

			if matched:
				xbmc_show = self.xbmc_shows[indices[matched][trakt_show[matched]]]
				trakt_episodes = convert_seasons(trakt_show)
				xbmc_episodes = [{'season': x['season'], 'episode': x['episode']} for x in xbmc_show['episodes']]

				for episode in trakt_episodes:
					if episode not in xbmc_episodes:
						remove.append(episode)

			else:
				remove = convert_seasons(trakt_show)

			if remove:
				show = {'title': trakt_show['title'], 'year': trakt_show['year'], 'episodes': remove}
				if matched:
					show[matched] = trakt_show[matched]
				remove_from_trakt.append(show)

		if remove_from_trakt:
			Debug('[Episodes Sync] %ishow(s) will have episodes removed from trakt.tv collection' % len(remove_from_trakt))
			if self.show_progress:
				progress.update(90, line1=__getstring__(1445), line2='%i %s' % (len(remove_from_trakt), __getstring__(1446)))

			for show in remove_from_trakt:
				if self.Canceled():
					return

				if self.show_progress:
					progress.update(95, line1=__getstring__(1445), line2=show['title'].encode('utf-8', 'ignore'), line3='%i %s' % (len(show['episodes']), __getstring__(1447)))

				traktJsonRequest('POST', '/show/episode/unlibrary/%%API_KEY%%', show)

		else:
			Debug('[Episodes Sync] trakt.tv episode collection is clean')
Beispiel #27
0
	def AddToTrakt(self):
		Debug('[Episodes Sync] Checking for episodes missing from trakt.tv collection')
		if self.show_progress:
			progress.update(30, line1=__getstring__(1435), line2=' ', line3=' ')

		add_to_trakt = []
		trakt_imdb_index = {}
		trakt_tvdb_index = {}
		trakt_title_index = {}

		for i in range(len(self.trakt_shows['collection'])):
			if 'imdb_id' in self.trakt_shows['collection'][i]:
				trakt_imdb_index[self.trakt_shows['collection'][i]['imdb_id']] = i

			if 'tvdb_id' in self.trakt_shows['collection'][i]:
				trakt_tvdb_index[self.trakt_shows['collection'][i]['tvdb_id']] = i

			trakt_title_index[self.trakt_shows['collection'][i]['title']] = i

		for xbmc_show in self.xbmc_shows:
			missing = []

			#IMDB ID
			if xbmc_show['imdbnumber'].startswith('tt'):
				if xbmc_show['imdbnumber'] not in trakt_imdb_index.keys():
					missing = xbmc_show['episodes']

				else:
					trakt_show = self.trakt_shows['collection'][trakt_imdb_index[xbmc_show['imdbnumber']]]
					missing = compare_show(xbmc_show, trakt_show)

			#TVDB ID
			elif xbmc_show['imdbnumber'].isdigit():
				if xbmc_show['imdbnumber'] not in trakt_tvdb_index.keys():
					missing = xbmc_show['episodes']

				else:
					trakt_show = self.trakt_shows['collection'][trakt_tvdb_index[xbmc_show['imdbnumber']]]
					missing = compare_show(xbmc_show, trakt_show)

			#Title
			else:
				if xbmc_show['title'] not in trakt_title_index.keys():
					missing = xbmc_show['episodes']

				else:
					trakt_show = self.trakt_shows['collection'][trakt_title_index[xbmc_show['title']]]
					missing = compare_show(xbmc_show, trakt_show)

			if missing:
				show = {'title': xbmc_show['title'], 'episodes': [{'episode': x['episode'], 'season': x['season'], 'episode_tvdb_id': x['uniqueid']['unknown']} for x in missing]}
				Debug('[Episodes Sync][AddToTrakt] %s' % show)

				if xbmc_show['imdbnumber'].isdigit():
					show['tvdb_id'] = xbmc_show['imdbnumber']
				else:
					show['imdb_id'] = xbmc_show['imdbnumber']

				add_to_trakt.append(show)

		if add_to_trakt:
			Debug('[Episodes Sync] %i shows(s) have episodes added to trakt.tv collection' % len(add_to_trakt))
			if self.show_progress:
				progress.update(35, line1=__getstring__(1435), line2='%i %s' % (len(add_to_trakt), __getstring__(1436)))

			for show in add_to_trakt:
				if self.Canceled():
					return
				if self.show_progress:
					progress.update(45, line1=__getstring__(1435), line2=show['title'].encode('utf-8', 'ignore'), line3='%i %s' % (len(show['episodes']), __getstring__(1437)))

				traktJsonRequest('POST', '/show/episode/library/%%API_KEY%%', show)

		else:
			Debug('[Episodes Sync] trakt.tv episode collection is up to date')
Beispiel #28
0
def rateMedia(media_id, media_type):
	"""Launches the rating dialog"""
	if media_id == None:
		Debug('[Rating] Missing media_id')
		return

	if media_type == 'movie':
		resp = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovieDetails', 'params': {'movieid': media_id, 'properties': ['title', 'imdbnumber', 'year']}})
		if not resp:
			Debug("[Rating] Problem getting movie data from XBMC")
			return
		
		if not resp.has_key("moviedetails"):
			Debug("[Rating] Error with movie results from XBMC, %s" % resp)
			return
			
		xbmc_media = resp["moviedetails"]
		if xbmc_media == None:
			Debug('[Rating] Failed to retrieve movie data from XBMC')
			return

		jsonString = "/movie/summary.json/%%API_KEY%%/" + xbmc_media['imdbnumber']
		trakt_summary = traktJsonRequest('POST', jsonString)
		if trakt_summary == None:
			Debug('[Rating] Failed to retrieve movie data from trakt')
			return

		if trakt_summary['rating'] or trakt_summary['rating_advanced']:
			Debug('[Rating] Movie has been rated')
			return

	else:
		resp = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetEpisodeDetails', 'params': {'episodeid': media_id, 'properties': ['uniqueid', 'tvshowid', 'episode', 'season']}})
		if not resp:
			Debug("[Rating] Problem getting episode data from XBMC")
			return
		
		if not resp.has_key("episodedetails"):
			Debug("[Rating] Error with episode results from XBMC, %s" % resp)
			return
			
		episode = resp["episodedetails"]
		if episode == None:
			Debug('[Rating] Failed to retrieve episode data from XBMC')
			return

		resp = xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetTVShowDetails', 'params': {'tvshowid': episode['tvshowid'], 'properties': ['imdbnumber']}})
		if not resp:
			Debug("[Rating] Problem getting tvshow data from XBMC")
			return
		
		if not resp.has_key("tvshowdetails"):
			Debug("[Rating] Error with tvshow results from XBMC, %s" % resp)
			return

		xbmc_media = resp["tvshowdetails"]
		if xbmc_media == None:
			Debug('[Rating] Failed to retrieve tvshow data from XBMC')
			return

		xbmc_media["episode"] = episode

		jsonString = "/show/episode/summary.json/%%API_KEY%%/" + str(xbmc_media['imdbnumber']) + "/" + str(xbmc_media['episode']['season']) + "/" + str(xbmc_media['episode']['episode'])
		trakt_summary = traktJsonRequest('POST', jsonString)
		if trakt_summary == None:
			Debug('[Rating] Failed to retrieve show/episode data from trakt')
			return

		xbmc_media['year'] = trakt_summary['show']['year']

		if trakt_summary['episode']['rating'] or trakt_summary['episode']['rating_advanced']:
			Debug('[Rating] Episode has been rated')
			return

	rating_type = utilities.traktSettings['viewing']['ratings']['mode']
	xbmc.executebuiltin('Dialog.Close(all, true)')

	gui = RatingDialog(
		"RatingDialog.xml",
		__settings__.getAddonInfo('path'),
		media_type=media_type,
		media=xbmc_media,
		rating_type=rating_type
	)

	gui.doModal()
	del gui