Esempio n. 1
0
    def doManualRating(self, data):
        action = data['action']
        media_type = data['media_type']
        summaryInfo = None

        if not utilities.isValidMediaType(media_type):
            logger.debug("doManualRating(): Invalid media type '%s' passed for manual %s." % (media_type, action))
            return

        if not data['action'] in ['rate', 'unrate']:
            logger.debug("doManualRating(): Unknown action passed.")
            return

        logger.debug("Getting data for manual %s of %s: video_id: |%s| dbid: |%s|" % (action, media_type, data.get('video_id'), data.get('dbid')))

        id_type = utilities.parseIdToTraktIds(str(data['video_id']), media_type)[1]

        if not id_type:
            logger.debug("doManualRating(): Unrecognized id_type: |%s|-|%s|." % (media_type, data['video_id']))
            return
            
        ids = globals.traktapi.getIdLookup(data['video_id'], id_type)
        
        if not ids:
            logger.debug("doManualRating(): No Results for: |%s|-|%s|." % (media_type, data['video_id']))
            return
            
        trakt_id = dict(ids[0].keys)['trakt']
        if utilities.isEpisode(media_type):
            summaryInfo = globals.traktapi.getEpisodeSummary(trakt_id, data['season'], data['episode'])
            userInfo = globals.traktapi.getEpisodeRatingForUser(trakt_id, data['season'], data['episode'], 'trakt')
        elif utilities.isSeason(media_type):
            summaryInfo = globals.traktapi.getShowSummary(trakt_id)
            userInfo = globals.traktapi.getSeasonRatingForUser(trakt_id, data['season'], 'trakt')
        elif utilities.isShow(media_type):
            summaryInfo = globals.traktapi.getShowSummary(trakt_id)
            userInfo = globals.traktapi.getShowRatingForUser(trakt_id, 'trakt')
        elif utilities.isMovie(media_type):
            summaryInfo = globals.traktapi.getMovieSummary(trakt_id)
            userInfo = globals.traktapi.getMovieRatingForUser(trakt_id, 'trakt')

        if summaryInfo is not None:
            summaryInfo = summaryInfo.to_dict()
            summaryInfo['user'] = {'ratings': userInfo}
            if utilities.isEpisode(media_type):
                summaryInfo['season'] = data['season']
                summaryInfo['number'] = data['episode']
            elif utilities.isSeason(media_type):
                summaryInfo['season'] = data['season']

            if action == 'rate':
                if not 'rating' in data:
                    rateMedia(media_type, [summaryInfo])
                else:
                    rateMedia(media_type, [summaryInfo], rating=data['rating'])
        else:
            logger.debug("doManualRating(): Summary info was empty, possible problem retrieving data from Trakt.tv")
Esempio n. 2
0
    def doManualRating(self, data):
        action = data['action']
        media_type = data['media_type']
        summaryInfo = None

        if not utilities.isValidMediaType(media_type):
            logger.debug("doManualRating(): Invalid media type '%s' passed for manual %s." % (media_type, action))
            return

        if not data['action'] in ['rate', 'unrate']:
            logger.debug("doManualRating(): Unknown action passed.")
            return

        logger.debug("Getting data for manual %s of %s: video_id: |%s| dbid: |%s|" % (action, media_type, data.get('video_id'), data.get('dbid')))

        id_type = utilities.parseIdToTraktIds(str(data['video_id']), media_type)[1]

        if not id_type:
            logger.debug("doManualRating(): Unrecognized id_type: |%s|-|%s|." % (media_type, data['video_id']))
            return
            
        ids = globals.traktapi.getIdLookup(data['video_id'], id_type)
        
        if not ids:
            logger.debug("doManualRating(): No Results for: |%s|-|%s|." % (media_type, data['video_id']))
            return
            
        trakt_id = dict(ids[0].keys)['trakt']
        if utilities.isEpisode(media_type):
            summaryInfo = globals.traktapi.getEpisodeSummary(trakt_id, data['season'], data['episode'])
            userInfo = globals.traktapi.getEpisodeRatingForUser(trakt_id, data['season'], data['episode'], 'trakt')
        elif utilities.isSeason(media_type):
            summaryInfo = globals.traktapi.getShowSummary(trakt_id)
            userInfo = globals.traktapi.getSeasonRatingForUser(trakt_id, data['season'], 'trakt')
        elif utilities.isShow(media_type):
            summaryInfo = globals.traktapi.getShowSummary(trakt_id)
            userInfo = globals.traktapi.getShowRatingForUser(trakt_id, 'trakt')
        elif utilities.isMovie(media_type):
            summaryInfo = globals.traktapi.getMovieSummary(trakt_id)
            userInfo = globals.traktapi.getMovieRatingForUser(trakt_id, 'trakt')

        if summaryInfo is not None:
            summaryInfo = summaryInfo.to_dict()
            summaryInfo['user'] = {'ratings': userInfo}
            if utilities.isEpisode(media_type):
                summaryInfo['season'] = data['season']
                summaryInfo['number'] = data['episode']
            elif utilities.isSeason(media_type):
                summaryInfo['season'] = data['season']

            if action == 'rate':
                if not 'rating' in data:
                    rateMedia(media_type, [summaryInfo])
                else:
                    rateMedia(media_type, [summaryInfo], rating=data['rating'])
        else:
            logger.debug("doManualRating(): Summary info was empty, possible problem retrieving data from Trakt.tv")
Esempio n. 3
0
    def onInit(self):
        lang = utils.getString
        mange_string = lang(32133) if utils.isMovie(self.media_type) else lang(32134)
        rate_string = lang(32137)
        if utils.isShow(self.media_type):
            rate_string = lang(32138)
        elif utils.isSeason(self.media_type):
            rate_string = lang(32149)
        elif utils.isEpisode(self.media_type):
            rate_string = lang(32139)

        actions = [mange_string, lang(32135), lang(32136), rate_string, lang(32140), lang(32141), lang(32142), lang(32143)]
        keys = ["itemlists", "removefromlist", "addtolist", "rate", "togglewatched", "managelists", "updatetags",
                "sync"]

        l = self.getControl(ACTION_LIST)
        for i in range(len(actions)):
            if keys[i] in self.buttons:
                l.addItem(self.newListItem(actions[i], id=keys[i]))

        h = ((len(self.buttons)) * 46) - 6
        l.setHeight(h)

        d = self.getControl(DIALOG_IMAGE)
        d.setHeight(h + 40)

        self.setFocus(l)
Esempio n. 4
0
def rateOnTrakt(rating, media_type, media):
	Debug("[Rating] Sending rating (%s) to trakt.tv" % rating)
	if utilities.isMovie(media_type):
		params = {}
		params['title'] = media['title']
		params['year'] = media['year']
		params['rating'] = rating
		params['tmdb_id'] = media['tmdb_id']
		params['imdb_id'] = media['imdb_id']

		data = globals.traktapi.rateMovie(params)

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

		data = globals.traktapi.rateEpisode(params)

	else:
		return

	if data != None:
		notification(utilities.getString(1201), utilities.getString(1167)) # Rating submitted successfully
Esempio n. 5
0
    def __scrobble(self, status):
        if not self.curVideoInfo:
            return

        logger.debug("scrobble()")
        scrobbleMovieOption = utilities.getSettingAsBool('scrobble_movie')
        scrobbleEpisodeOption = utilities.getSettingAsBool('scrobble_episode')

        watchedPercent = self.__calculateWatchedPercent()

        if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
            response = self.traktapi.scrobbleMovie(self.curVideoInfo, watchedPercent, status)
            if not response is None:
                self.__scrobbleNotification(response)
                logger.debug("Scrobble response: %s" % str(response))
                return response

        elif utilities.isEpisode(self.curVideo['type']) and scrobbleEpisodeOption:
            if self.isMultiPartEpisode:
                logger.debug("Multi-part episode, scrobbling part %d of %d." % (self.curMPEpisode + 1, self.curVideo['multi_episode_count']))
                adjustedDuration = int(self.videoDuration / self.curVideo['multi_episode_count'])
                watchedPercent = ((self.watchedTime - (adjustedDuration * self.curMPEpisode)) / adjustedDuration) * 100

            response = self.traktapi.scrobbleEpisode(self.traktShowSummary, self.curVideoInfo, watchedPercent, status)

            if not response is None:
                self.__scrobbleNotification(response)
                logger.debug("Scrobble response: %s" % str(response))
                return response
Esempio n. 6
0
 def __preFetchUserRatings(self, result):
     if result:
         if utilities.isMovie(
                 self.curVideo['type']) and kodiUtilities.getSettingAsBool(
                     'rate_movie'):
             # pre-get summary information, for faster rating dialog.
             logger.debug(
                 "Movie rating is enabled, pre-fetching summary information."
             )
             self.curVideoInfo = result['movie']
             self.curVideoInfo['user'] = {
                 'ratings':
                 self.traktapi.getMovieRatingForUser(
                     result['movie']['ids']['trakt'], 'trakt')
             }
         elif utilities.isEpisode(
                 self.curVideo['type']) and kodiUtilities.getSettingAsBool(
                     'rate_episode'):
             # pre-get summary information, for faster rating dialog.
             logger.debug(
                 "Episode rating is enabled, pre-fetching summary information."
             )
             self.curVideoInfo = result['episode']
             self.curVideoInfo['user'] = {
                 'ratings':
                 self.traktapi.getEpisodeRatingForUser(
                     result['show']['ids']['trakt'],
                     self.curVideoInfo['season'],
                     self.curVideoInfo['number'], 'trakt')
             }
         logger.debug('Pre-Fetch result: %s; Info: %s' %
                      (result, self.curVideoInfo))
Esempio n. 7
0
def __rateOnTrakt(rating, media_type, media, unrate=False):
    logger.debug("Sending rating (%s) to Trakt.tv" % rating)

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

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

    if data:
        s = utils.getFormattedItemName(media_type, media)
        if 'not_found' in data and not data['not_found']['movies'] and not data['not_found']['episodes'] and not data['not_found']['shows']:

            if not unrate:
                utils.notification(utils.getString(32040), s)
            else:
                utils.notification(utils.getString(32042), s)
        else:
            utils.notification(utils.getString(32044), s)
Esempio n. 8
0
def rateMedia(media_type, summary_info):
	"""Launches the rating dialog"""
	if utilities.isMovie(media_type):
		if summary_info['rating'] or summary_info['rating_advanced']:
			Debug("[Rating] Movie has already been rated.")
			return

	elif utilities.isEpisode(media_type):
		if summary_info['episode']['rating'] or summary_info['episode']['rating_advanced']:
			Debug("[Rating] Episode has already been rated.")
			return

	else:
		return

	if not globals.traktapi.settings:
		globals.traktapi.getAccountSettings()
	rating_type = globals.traktapi.settings['viewing']['ratings']['mode']
	xbmc.executebuiltin('Dialog.Close(all, true)')

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

	gui.doModal()
	if gui.rating:
		rateOnTrakt(gui.rating, gui.media_type, gui.media)
	del gui
Esempio n. 9
0
    def onInit(self):
        mange_string = getString(32133) if isMovie(
            self.media_type) else getString(32134)
        rate_string = getString(32137)
        if isShow(self.media_type):
            rate_string = getString(32138)
        elif isSeason(self.media_type):
            rate_string = getString(32149)
        elif isEpisode(self.media_type):
            rate_string = getString(32139)

        actions = [
            mange_string,
            getString(32135),
            getString(32136), rate_string,
            getString(32140),
            getString(32141),
            getString(32142),
            getString(32143)
        ]
        keys = [
            "itemlists", "removefromlist", "addtowatchlist", "rate",
            "togglewatched", "managelists", "updatetags", "sync"
        ]

        l = self.getControl(ACTION_LIST)
        for i in range(len(actions)):
            if keys[i] in self.buttons:
                l.addItem(self.newListItem(actions[i], id=keys[i]))

        self.setFocus(l)
Esempio n. 10
0
    def __scrobble(self, status):
        if not self.curVideoInfo:
            return

        logger.debug("scrobble()")
        scrobbleMovieOption = utilities.getSettingAsBool("scrobble_movie")
        scrobbleEpisodeOption = utilities.getSettingAsBool("scrobble_episode")

        watchedPercent = self.__calculateWatchedPercent()

        if utilities.isMovie(self.curVideo["type"]) and scrobbleMovieOption:
            response = self.traktapi.scrobbleMovie(self.curVideoInfo, watchedPercent, status)
            if not response is None:
                self.__scrobbleNotification(response)
                logger.debug("Scrobble response: %s" % str(response))
                return response

        elif utilities.isEpisode(self.curVideo["type"]) and scrobbleEpisodeOption:
            if self.isMultiPartEpisode:
                logger.debug(
                    "Multi-part episode, scrobbling part %d of %d."
                    % (self.curMPEpisode + 1, self.curVideo["multi_episode_count"])
                )
                adjustedDuration = int(self.videoDuration / self.curVideo["multi_episode_count"])
                watchedPercent = ((self.watchedTime - (adjustedDuration * self.curMPEpisode)) / adjustedDuration) * 100

            response = self.traktapi.scrobbleEpisode(self.traktShowSummary, self.curVideoInfo, watchedPercent, status)

            if response is not None:
                self.__scrobbleNotification(response)
                logger.debug("Scrobble response: %s" % str(response))
                return response
	def onInit(self):
		lang = utils.getString
		mange_string = lang(2000) if utils.isMovie(self.media_type) else lang(2001)
		rate_string = lang(2030)
		if utils.isShow(self.media_type):
			rate_string = lang(2031)
		elif utils.isEpisode(self.media_type):
			rate_string = lang(2032)

		actions = [mange_string, lang(2010), lang(2020), rate_string, lang(2040), lang(2050), lang(2060), lang(2070)]
		keys = ["itemlists", "removefromlist", "addtolist", "rate", "togglewatched", "managelists", "updatetags", "sync"]

		l = self.getControl(ACTION_LIST)
		for i in range(len(actions)):
			if keys[i] in self.buttons:
				l.addItem(self.newListItem(actions[i], id=keys[i]))

		h = ((len(self.buttons)) * 46) - 6
		l.setHeight(h)

		d = self.getControl(DIALOG_IMAGE)
		d.setHeight(h + 40)

		offset = (316 - h) / 2

		d.setPosition(0, offset - 20)
		l.setPosition(20, offset)

		self.setFocus(l)
Esempio n. 12
0
    def __scrobble(self, status):
        if not self.curVideoInfo:
            return

        logger.debug("scrobble()")
        scrobbleMovieOption = kodiUtilities.getSettingAsBool('scrobble_movie')
        scrobbleEpisodeOption = kodiUtilities.getSettingAsBool('scrobble_episode')

        watchedPercent = self.__calculateWatchedPercent()

        if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
            response = self.traktapi.scrobbleMovie(self.curVideoInfo, watchedPercent, status)
            if response is not None:
                self.__scrobbleNotification(response)
                logger.debug("Scrobble response: %s" % str(response))
                return response
            else:
                logger.debug("Failed to scrobble movie: %s | %s | %s" % (self.curVideoInfo, watchedPercent, status))

        elif utilities.isEpisode(self.curVideo['type']) and scrobbleEpisodeOption:
            if self.isMultiPartEpisode:
                logger.debug("Multi-part episode, scrobbling part %d of %d." % (self.curMPEpisode + 1, self.curVideo['multi_episode_count']))
                adjustedDuration = int(self.videoDuration / self.curVideo['multi_episode_count'])
                watchedPercent = ((self.watchedTime - (adjustedDuration * self.curMPEpisode)) / adjustedDuration) * 100

            logger.debug("scrobble sending show object: %s" % str(self.traktShowSummary))
            logger.debug("scrobble sending episode object: %s" % str(self.curVideoInfo))
            response = self.traktapi.scrobbleEpisode(self.traktShowSummary, self.curVideoInfo, watchedPercent, status)
            
            if (kodiUtilities.getSettingAsBool('scrobble_secondary_title')):
                logger.debug('[traktPlayer] Setting is enabled to try secondary show title, if necessary.')
                # If there is an empty response, the reason might be that the title we have isn't the actual show title,
                # but rather an alternative title. To handle this case, call the Trakt search function.
                if response is None:
                    logger.debug("Searching for show title: %s" % self.traktShowSummary['title'])
                    # This text query API is basically the same as searching on the website. Works with alternative 
                    # titles, unlike the scrobble function.
                    newResp = self.traktapi.getTextQuery(self.traktShowSummary['title'], "show", None)
                    if not newResp:
                        logger.debug("Empty Response from getTextQuery, giving up")
                    else:
                        logger.debug("Got Response from getTextQuery: %s" % str(newResp))
                        # We got something back. Have to assume the first show found is the right one; if there's more than
                        # one, there's no way to know which to use. Pull the primary title from the response (and the year,
                        # just because it's there).
                        showObj = {'title': newResp[0].title, 'year': newResp[0].year}
                        logger.debug("scrobble sending getTextQuery first show object: %s" % str(showObj))
                        # Now we can attempt the scrobble again, using the primary title this time.
                        response = self.traktapi.scrobbleEpisode(showObj, self.curVideoInfo, watchedPercent, status)
                    
            if response is not None:
                self.__scrobbleNotification(response)
                logger.debug("Scrobble response: %s" % str(response))
                return response
            else:
                logger.debug("Failed to scrobble episode: %s | %s | %s | %s" % (self.traktShowSummary,
                                                                                self.curVideoInfo, watchedPercent,
                                                                                status))
Esempio n. 13
0
    def doManualRating(self, data):
        action = data['action']
        media_type = data['media_type']
        summaryInfo = None

        if not utilities.isValidMediaType(media_type):
            logger.debug("doManualRating(): Invalid media type '%s' passed for manual %s." % (media_type, action))
            return

        if not data['action'] in ['rate', 'unrate']:
            logger.debug("doManualRating(): Unknown action passed.")
            return

        logger.debug("Getting data for manual %s of %s: imdb: |%s| dbid: |%s|" % (action, media_type, data.get('remoteid'), data.get('dbid')))

        if utilities.isEpisode(media_type):
            summaryInfo = globals.traktapi.getEpisodeSummary(data['imdbnumber'], data['season'], data['episode'])
            userInfo = globals.traktapi.getEpisodeRatingForUser(data['imdbnumber'], data['season'], data['episode'], 'imdb')
        elif utilities.isSeason(media_type):
            summaryInfo = globals.traktapi.getShowSummary(data['imdbnumber'])
            userInfo = globals.traktapi.getSeasonRatingForUser(data['imdbnumber'], data['season'], 'imdb')
        elif utilities.isShow(media_type):
            summaryInfo = globals.traktapi.getShowSummary(data['imdbnumber'])
            userInfo = globals.traktapi.getShowRatingForUser(data['imdbnumber'], 'imdb')
        elif utilities.isMovie(media_type):
            summaryInfo = globals.traktapi.getMovieSummary(data['imdbnumber'])
            userInfo = globals.traktapi.getMovieRatingForUser(data['imdbnumber'])

        if summaryInfo is not None:
            summaryInfo = summaryInfo.to_dict()
            summaryInfo['user'] = {'ratings': userInfo}
            if utilities.isEpisode(media_type):
                summaryInfo['season'] = data['season']
                summaryInfo['number'] = data['episode']
            elif utilities.isSeason(media_type):
                summaryInfo['season'] = data['season']

            if action == 'rate':
                if not 'rating' in data:
                    rateMedia(media_type, [summaryInfo])
                else:
                    rateMedia(media_type, [summaryInfo], rating=data['rating'])
        else:
            logger.debug("doManualRating(): Summary info was empty, possible problem retrieving data from Trakt.tv")
Esempio n. 14
0
	def watching(self):
		if not self.isPlaying:
			return

		if not self.curVideoInfo:
			return

		Debug("[Scrobbler] watching()")
		scrobbleMovieOption = utilities.getSettingAsBool('scrobble_movie')
		scrobbleEpisodeOption = utilities.getSettingAsBool('scrobble_episode')

		self.update(True)

		duration = self.videoDuration / 60
		watchedPercent = (self.watchedTime / self.videoDuration) * 100

		if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
			response = self.traktapi.watchingMovie(self.curVideoInfo, duration, watchedPercent)
			if response != None:
				if self.curVideoInfo['imdbnumber'] is None:
					if 'status' in response and response['status'] == "success":
						if 'movie' in response and 'imdb_id' in response['movie']:
							self.curVideoInfo['imdbnumber'] = response['movie']['imdb_id']
							if 'id' in self.curVideo and utilities.getSettingAsBool('update_imdb_id'):
								req = {"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetMovieDetails", "params": {"movieid" : self.curVideoInfo['movieid'], "imdbnumber": self.curVideoInfo['imdbnumber']}}
								utilities.xbmcJsonRequest(req)
							# get summary data now if we are rating this movie
							if utilities.getSettingAsBool('rate_movie') and self.traktSummaryInfo is None:
								Debug("[Scrobbler] Movie rating is enabled, pre-fetching summary information.")
								self.traktSummaryInfo = self.traktapi.getMovieSummary(self.curVideoInfo['imdbnumber'])

				Debug("[Scrobbler] Watch response: %s" % str(response))
				
		elif utilities.isEpisode(self.curVideo['type']) and scrobbleEpisodeOption:
			if self.isMultiPartEpisode:
				Debug("[Scrobbler] Multi-part episode, watching part %d of %d." % (self.curMPEpisode + 1, self.curVideo['multi_episode_count']))
				# recalculate watchedPercent and duration for multi-part
				adjustedDuration = int(self.videoDuration / self.curVideo['multi_episode_count'])
				duration = adjustedDuration / 60
				watchedPercent = ((self.watchedTime - (adjustedDuration * self.curMPEpisode)) / adjustedDuration) * 100
			
			response = self.traktapi.watchingEpisode(self.curVideoInfo, duration, watchedPercent)
			if response != None:
				if self.curVideoInfo['tvdb_id'] is None:
					if 'status' in response and response['status'] == "success":
						if 'show' in response and 'tvdb_id' in response['show']:
							self.curVideoInfo['tvdb_id'] = response['show']['tvdb_id']
							if 'id' in self.curVideo and utilities.getSettingAsBool('update_tvdb_id'):
								req = {"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetTVShowDetails", "params": {"tvshowid" : self.curVideoInfo['tvshowid'], "imdbnumber": self.curVideoInfo['tvdb_id']}}
								utilities.xbmcJsonRequest(req)
							# get summary data now if we are rating this episode
							if utilities.getSettingAsBool('rate_episode') and self.traktSummaryInfo is None:
								Debug("[Scrobbler] Episode rating is enabled, pre-fetching summary information.")
								self.traktSummaryInfo = self.traktapi.getEpisodeSummary(self.curVideoInfo['tvdb_id'], self.curVideoInfo['season'], self.curVideoInfo['episode'])

				Debug("[Scrobbler] Watch response: %s" % str(response))
Esempio n. 15
0
	def watching(self):
		if not self.isPlaying:
			return

		if not self.curVideoInfo:
			return

		Debug("[Scrobbler] watching()")
		scrobbleMovieOption = utilities.getSettingAsBool('scrobble_movie')
		scrobbleEpisodeOption = utilities.getSettingAsBool('scrobble_episode')

		self.update(True)

		duration = self.videoDuration / 60
		watchedPercent = (self.watchedTime / self.videoDuration) * 100

		if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
			response = self.traktapi.watchingMovie(self.curVideoInfo, duration, watchedPercent)
			if response != None:
				if self.curVideoInfo['imdbnumber'] is None:
					if 'status' in response and response['status'] == "success":
						if 'movie' in response and 'imdb_id' in response['movie']:
							self.curVideoInfo['imdbnumber'] = response['movie']['imdb_id']
							if 'id' in self.curVideo and utilities.getSettingAsBool('update_imdb_id'):
								req = {"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetMovieDetails", "params": {"movieid" : self.curVideoInfo['movieid'], "imdbnumber": self.curVideoInfo['imdbnumber']}}
								utilities.xbmcJsonRequest(req)
							# get summary data now if we are rating this movie
							if utilities.getSettingAsBool('rate_movie') and self.traktSummaryInfo is None:
								Debug("[Scrobbler] Movie rating is enabled, pre-fetching summary information.")
								self.traktSummaryInfo = self.traktapi.getMovieSummary(self.curVideoInfo['imdbnumber'])

				Debug("[Scrobbler] Watch response: %s" % str(response))
				
		elif utilities.isEpisode(self.curVideo['type']) and scrobbleEpisodeOption:
			if self.isMultiPartEpisode:
				Debug("[Scrobbler] Multi-part episode, watching part %d of %d." % (self.curMPEpisode + 1, self.curVideo['multi_episode_count']))
				# recalculate watchedPercent and duration for multi-part
				adjustedDuration = int(self.videoDuration / self.curVideo['multi_episode_count'])
				duration = adjustedDuration / 60
				watchedPercent = ((self.watchedTime - (adjustedDuration * self.curMPEpisode)) / adjustedDuration) * 100
			
			response = self.traktapi.watchingEpisode(self.curVideoInfo, duration, watchedPercent)
			if response != None:
				if self.curVideoInfo['tvdb_id'] is None:
					if 'status' in response and response['status'] == "success":
						if 'show' in response and 'tvdb_id' in response['show']:
							self.curVideoInfo['tvdb_id'] = response['show']['tvdb_id']
							if 'id' in self.curVideo and utilities.getSettingAsBool('update_tvdb_id'):
								req = {"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetTVShowDetails", "params": {"tvshowid" : self.curVideoInfo['tvshowid'], "imdbnumber": self.curVideoInfo['tvdb_id']}}
								utilities.xbmcJsonRequest(req)
							# get summary data now if we are rating this episode
							if utilities.getSettingAsBool('rate_episode') and self.traktSummaryInfo is None:
								Debug("[Scrobbler] Episode rating is enabled, pre-fetching summary information.")
								self.traktSummaryInfo = self.traktapi.getEpisodeSummary(self.curVideoInfo['tvdb_id'], self.curVideoInfo['season'], self.curVideoInfo['episode'])

				Debug("[Scrobbler] Watch response: %s" % str(response))
Esempio n. 16
0
    def doManualRating(self, data):

        action = data['action']
        media_type = data['media_type']
        summaryInfo = None

        if not utilities.isValidMediaType(media_type):
            utilities.Debug(
                "doManualRating(): Invalid media type '%s' passed for manual %s."
                % (media_type, action))
            return

        if not data['action'] in ['rate', 'unrate']:
            utilities.Debug("doManualRating(): Unknown action passed.")
            return

        if 'dbid' in data:
            utilities.Debug(
                "Getting data for manual %s of library '%s' with ID of '%s'" %
                (action, media_type, data['dbid']))
        elif 'remoteitd' in data:
            if 'season' in data:
                utilities.Debug(
                    "Getting data for manual %s of non-library '%s' S%02dE%02d, with ID of '%s'."
                    % (action, media_type, data['season'], data['episode'],
                       data['remoteid']))
            else:
                utilities.Debug(
                    "Getting data for manual %s of non-library '%s' with ID of '%s'"
                    % (action, media_type, data['remoteid']))

        if utilities.isEpisode(media_type):
            summaryInfo = globals.traktapi.getEpisodeSummary(
                data['tvdb_id'], data['season'], data['episode'])
        elif utilities.isShow(media_type):
            summaryInfo = globals.traktapi.getShowSummary(data['imdbnumber'])
        elif utilities.isMovie(media_type):
            summaryInfo = globals.traktapi.getMovieSummary(data['imdbnumber'])

        if not summaryInfo is None:
            if utilities.isMovie(media_type) or utilities.isShow(media_type):
                summaryInfo['xbmc_id'] = data['dbid']

            if action == 'rate':
                if not 'rating' in data:
                    rateMedia(media_type, summaryInfo)
                else:
                    rateMedia(media_type, summaryInfo, rating=data['rating'])
            elif action == 'unrate':
                rateMedia(media_type, summaryInfo, unrate=True)
        else:
            utilities.Debug(
                "doManualRating(): Summary info was empty, possible problem retrieving data from trakt.tv"
            )
Esempio n. 17
0
def __rateOnTrakt(rating, media_type, media, unrate=False):
    utils.Debug("[Rating] Sending rating (%s) to trakt.tv" % rating)

    params = {}

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

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

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

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

    else:
        return

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

    if data:
        utils.Debug("data rate: %s" % data)
        s = utils.getFormattedItemName(media_type, media)
        if 'not_found' in data and not data['not_found']['movies'] and not data[
                'not_found']['episodes'] and not data['not_found']['shows']:

            if not unrate:
                utils.notification(utils.getString(1350), s)
            else:
                utils.notification(utils.getString(1352), s)
        else:
            utils.notification(utils.getString(1354), s)
Esempio n. 18
0
    def scrobble(self):
        if not self.curVideoInfo:
            return

        Debug("[Scrobbler] scrobble()")
        scrobbleMovieOption = utilities.getSettingAsBool('scrobble_movie')
        scrobbleEpisodeOption = utilities.getSettingAsBool('scrobble_episode')

        duration = self.videoDuration / 60
        watchedPercent = (self.watchedTime / self.videoDuration) * 100

        if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
            response = self.traktapi.scrobbleMovie(self.curVideoInfo, duration,
                                                   watchedPercent)
            if not response is None and 'status' in response:
                if response['status'] == "success":
                    self.watchlistTagCheck()
                    Debug("[Scrobbler] Scrobble response: %s" % str(response))
                elif response['status'] == "failure":
                    if response['error'].startswith("scrobbled") and response[
                            'error'].endswith("already"):
                        Debug(
                            "[Scrobbler] Movie was just recently scrobbled, attempting to cancel watching instead."
                        )
                        self.stoppedWatching()

        elif utilities.isEpisode(
                self.curVideo['type']) and scrobbleEpisodeOption:
            if self.isMultiPartEpisode:
                Debug(
                    "[Scrobbler] Multi-part episode, scrobbling part %d of %d."
                    % (self.curMPEpisode + 1,
                       self.curVideo['multi_episode_count']))
                adjustedDuration = int(self.videoDuration /
                                       self.curVideo['multi_episode_count'])
                duration = adjustedDuration / 60
                watchedPercent = ((self.watchedTime -
                                   (adjustedDuration * self.curMPEpisode)) /
                                  adjustedDuration) * 100

            response = self.traktapi.scrobbleEpisode(self.curVideoInfo,
                                                     duration, watchedPercent)
            if not response is None and 'status' in response:
                if response['status'] == "success":
                    Debug("[Scrobbler] Scrobble response: %s" % str(response))
                elif response['status'] == "failure":
                    if response['error'].startswith("scrobbled") and response[
                            'error'].endswith("already"):
                        Debug(
                            "[Scrobbler] Episode was just recently scrobbled, attempting to cancel watching instead."
                        )
                        self.stoppedWatching()
Esempio n. 19
0
	def stoppedWatching(self):
		Debug("[Scrobbler] stoppedWatching()")
		scrobbleMovieOption = utilities.getSettingAsBool("scrobble_movie")
		scrobbleEpisodeOption = utilities.getSettingAsBool("scrobble_episode")

		if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
			response = self.traktapi.cancelWatchingMovie()
			if response != None:
				Debug("[Scrobbler] Cancel watch response: %s" % str(response))
		elif utilities.isEpisode(self.curVideo['type']) and scrobbleEpisodeOption:
			response = self.traktapi.cancelWatchingEpisode()
			if response != None:
				Debug("[Scrobbler] Cancel watch response: %s" % str(response))
Esempio n. 20
0
	def stoppedWatching(self):
		Debug("[Scrobbler] stoppedWatching()")
		scrobbleMovieOption = utilities.getSettingAsBool("scrobble_movie")
		scrobbleEpisodeOption = utilities.getSettingAsBool("scrobble_episode")

		if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
			response = self.traktapi.cancelWatchingMovie()
			if response != None:
				Debug("[Scrobbler] Cancel watch response: %s" % str(response))
		elif utilities.isEpisode(self.curVideo['type']) and scrobbleEpisodeOption:
			response = self.traktapi.cancelWatchingEpisode()
			if response != None:
				Debug("[Scrobbler] Cancel watch response: %s" % str(response))
Esempio n. 21
0
    def scrobble(self, status):
        if not self.curVideoInfo:
            return

        Debug("[Scrobbler] scrobble()")
        scrobbleMovieOption = utilities.getSettingAsBool('scrobble_movie')
        scrobbleEpisodeOption = utilities.getSettingAsBool('scrobble_episode')

        duration = self.videoDuration / 60
        watchedPercent = (self.watchedTime / self.videoDuration) * 100

        if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
            response = self.traktapi.scrobbleMovie(self.curVideoInfo,
                                                   watchedPercent, status)
            if not response is None and 'status' in response:
                if response['status'] == "success":
                    self.watchlistTagCheck()
                    response['title'] = response['movie']['title']
                    response['year'] = response['movie']['year']
                    self.scrobbleNotification(response)
                    Debug("[Scrobbler] Scrobble response: %s" % str(response))
                elif response['status'] == "failure":
                    Debug(
                        "[Scrobbler] Movie '%s' was not found on trakt.tv, possible malformed XBMC metadata."
                        % self.curVideoInfo['title'])

        elif utilities.isEpisode(
                self.curVideo['type']) and scrobbleEpisodeOption:
            if self.isMultiPartEpisode:
                Debug(
                    "[Scrobbler] Multi-part episode, scrobbling part %d of %d."
                    % (self.curMPEpisode + 1,
                       self.curVideo['multi_episode_count']))
                adjustedDuration = int(self.videoDuration /
                                       self.curVideo['multi_episode_count'])
                duration = adjustedDuration / 60
                watchedPercent = ((self.watchedTime -
                                   (adjustedDuration * self.curMPEpisode)) /
                                  adjustedDuration) * 100

            response = self.traktapi.scrobbleEpisode(self.curVideoInfo,
                                                     watchedPercent, status)
            if not response is None and 'status' in response:
                if response['status'] == "success":
                    response['episode']['season'] = response['season']
                    self.scrobbleNotification(response)
                    Debug("[Scrobbler] Scrobble response: %s" % str(response))
                elif response['status'] == "failure":
                    Debug(
                        "[Scrobbler] Show '%s' was not found on trakt.tv, possible malformed XBMC metadata."
                        % self.curVideoInfo['showtitle'])
Esempio n. 22
0
def __rateOnTrakt(rating, media_type, media, unrate=False):
	logger.debug("Sending rating (%s) to Trakt.tv" % rating)

	params = {}
	

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

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

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

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

	else:
		return

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

	if data:
		s = utils.getFormattedItemName(media_type, media)
		if 'not_found' in data and not data['not_found']['movies'] and not data['not_found']['episodes'] and not data['not_found']['shows']:

			if not unrate:
				utils.notification(utils.getString(32040), s)
			else:
				utils.notification(utils.getString(32042), s)
		else:
			utils.notification(utils.getString(32044), s)
Esempio n. 23
0
    def doAddToWatchlist(self, data):
        media_type = data['media_type']

        if utilities.isMovie(media_type):
            summaryInfo = globals.traktapi.getMovieSummary(data['id']).to_dict()
            if summaryInfo:
                s = utilities.getFormattedItemName(media_type, summaryInfo)
                logger.debug("doAddToWatchlist(): '%s' trying to add to users watchlist." % s)
                params = {'movies': [summaryInfo]}
                logger.debug("doAddToWatchlist(): %s" % str(params))

                result = globals.traktapi.addToWatchlist(params)
                if result:
                    utilities.notification(utilities.getString(32165), s)
                else:
                    utilities.notification(utilities.getString(32166), s)
        elif utilities.isEpisode(media_type):
            summaryInfo = {'shows': [{'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0],
                                      'seasons': [{'number': data['season'], 'episodes': [{'number':data['number']}]}]}]}
            logger.debug("doAddToWatchlist(): %s" % str(summaryInfo))
            s = utilities.getFormattedItemName(media_type, data)

            result = globals.traktapi.addToWatchlist(summaryInfo)
            if result:
                utilities.notification(utilities.getString(32165), s)
            else:
                utilities.notification(utilities.getString(32166), s)
        elif utilities.isSeason(media_type):
            summaryInfo = {'shows': [{'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0],
                                      'seasons': [{'number': data['season']}]}]}
            s = utilities.getFormattedItemName(media_type, data)

            logger.debug("doAddToWatchlist(): '%s - Season %d' trying to add to users watchlist."
                         % (data['id'], data['season']))

            result = globals.traktapi.addToWatchlist(summaryInfo)
            if result:
                utilities.notification(utilities.getString(32165), s)
            else:
                utilities.notification(utilities.getString(32166), s)
        elif utilities.isShow(media_type):
            summaryInfo = {'shows': [{'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0]}]}
            s = utilities.getFormattedItemName(media_type, data)
            logger.debug("doAddToWatchlist(): %s" % str(summaryInfo))

            result = globals.traktapi.addToWatchlist(summaryInfo)
            if result:
                utilities.notification(utilities.getString(32165), s)
            else:
                utilities.notification(utilities.getString(32166), s)
Esempio n. 24
0
    def scrobble(self):
        if not self.curVideoInfo:
            return

        Debug("[Scrobbler] scrobble()")
        scrobbleMovieOption = utilities.getSettingAsBool("scrobble_movie")
        scrobbleEpisodeOption = utilities.getSettingAsBool("scrobble_episode")

        duration = self.videoDuration / 60
        watchedPercent = (self.watchedTime / self.videoDuration) * 100

        if utilities.isMovie(self.curVideo["type"]) and scrobbleMovieOption:
            response = self.traktapi.scrobbleMovie(self.curVideoInfo, duration, watchedPercent)
            if not response is None and "status" in response:
                if response["status"] == "success":
                    self.watchlistTagCheck()
                    Debug("[Scrobbler] Scrobble response: %s" % str(response))
                elif response["status"] == "failure":
                    if response["error"].startswith("scrobbled") and response["error"].endswith("already"):
                        Debug("[Scrobbler] Movie was just recently scrobbled, attempting to cancel watching instead.")
                        self.stoppedWatching()
                    elif response["error"] == "movie not found":
                        Debug(
                            "[Scrobbler] Movie '%s' was not found on trakt.tv, possible malformed XBMC metadata."
                            % self.curVideoInfo["title"]
                        )

        elif utilities.isEpisode(self.curVideo["type"]) and scrobbleEpisodeOption:
            if self.isMultiPartEpisode:
                Debug(
                    "[Scrobbler] Multi-part episode, scrobbling part %d of %d."
                    % (self.curMPEpisode + 1, self.curVideo["multi_episode_count"])
                )
                adjustedDuration = int(self.videoDuration / self.curVideo["multi_episode_count"])
                duration = adjustedDuration / 60
                watchedPercent = ((self.watchedTime - (adjustedDuration * self.curMPEpisode)) / adjustedDuration) * 100

            response = self.traktapi.scrobbleEpisode(self.curVideoInfo, duration, watchedPercent)
            if not response is None and "status" in response:
                if response["status"] == "success":
                    Debug("[Scrobbler] Scrobble response: %s" % str(response))
                elif response["status"] == "failure":
                    if response["error"].startswith("scrobbled") and response["error"].endswith("already"):
                        Debug("[Scrobbler] Episode was just recently scrobbled, attempting to cancel watching instead.")
                        self.stoppedWatching()
                    elif response["error"] == "show not found":
                        Debug(
                            "[Scrobbler] Show '%s' was not found on trakt.tv, possible malformed XBMC metadata."
                            % self.curVideoInfo["showtitle"]
                        )
Esempio n. 25
0
    def doMarkWatched(self, data):

        media_type = data['media_type']

        if utilities.isMovie(media_type):
            summaryInfo = globals.traktapi.getMovieSummary(data['id']).to_dict()
            if summaryInfo:
                if not summaryInfo['watched']:
                    s = utilities.getFormattedItemName(media_type, summaryInfo)
                    logger.debug("doMarkWatched(): '%s' is not watched on Trakt, marking it as watched." % s)
                    params = {'movies': [summaryInfo]}
                    logger.debug("doMarkWatched(): %s" % str(params))

                    result = globals.traktapi.addToHistory(params)
                    if result:
                        kodiUtilities.notification(kodiUtilities.getString(32113), s)
                    else:
                        kodiUtilities.notification(kodiUtilities.getString(32114), s)
        elif utilities.isEpisode(media_type):
            summaryInfo = {'shows': [{'ids':utilities.parseIdToTraktIds(data['id'],media_type)[0], 'seasons': [{'number': data['season'], 'episodes': [{'number':data['number']}]}]}]}
            logger.debug("doMarkWatched(): %s" % str(summaryInfo))
            s = utilities.getFormattedItemName(media_type, data)

            result = globals.traktapi.addToHistory(summaryInfo)
            if result:
                kodiUtilities.notification(kodiUtilities.getString(32113), s)
            else:
                kodiUtilities.notification(kodiUtilities.getString(32114), s)
        elif utilities.isSeason(media_type):
            summaryInfo = {'shows': [{'ids':utilities.parseIdToTraktIds(data['id'],media_type)[0], 'seasons': [{'number': data['season'], 'episodes': []}]}]}
            s = utilities.getFormattedItemName(media_type, data)
            for ep in data['episodes']:
                summaryInfo['shows'][0]['seasons'][0]['episodes'].append({'number': ep})

            logger.debug("doMarkWatched(): '%s - Season %d' has %d episode(s) that are going to be marked as watched." % (data['id'], data['season'], len(summaryInfo['shows'][0]['seasons'][0]['episodes'])))

            self.addEpisodesToHistory(summaryInfo, s)

        elif utilities.isShow(media_type):
            summaryInfo = {'shows': [{'ids':utilities.parseIdToTraktIds(data['id'],media_type)[0], 'seasons': []}]}
            if summaryInfo:
                s = utilities.getFormattedItemName(media_type, data)
                logger.debug('data: %s' % data)
                for season in data['seasons']:
                    episodeJson = []
                    for episode in data['seasons'][season]:
                        episodeJson.append({'number': episode})
                    summaryInfo['shows'][0]['seasons'].append({'number': season, 'episodes': episodeJson})

                self.addEpisodesToHistory(summaryInfo, s)
Esempio n. 26
0
 def __preFetchUserRatings(self, result):
     if result:
         if utilities.isMovie(self.curVideo['type']) and utilities.getSettingAsBool('rate_movie'):
             # pre-get summary information, for faster rating dialog.
             logger.debug("Movie rating is enabled, pre-fetching summary information.")
             self.curVideoInfo = result['movie']
             self.curVideoInfo['user'] = {'ratings': self.traktapi.getMovieRatingForUser(result['movie']['ids']['trakt'], 'trakt')}
         elif utilities.isEpisode(self.curVideo['type']) and utilities.getSettingAsBool('rate_episode'):
             # pre-get summary information, for faster rating dialog.
             logger.debug("Episode rating is enabled, pre-fetching summary information.")
             self.curVideoInfo = result['episode']
             self.curVideoInfo['user'] = {'ratings': self.traktapi.getEpisodeRatingForUser(result['show']['ids']['trakt'],
                                                                                           self.curVideoInfo['season'], self.curVideoInfo['number'], 'trakt')}
         logger.debug('Pre-Fetch result: %s; Info: %s' % (result, self.curVideoInfo))
Esempio n. 27
0
    def doAddToWatchlist(self, data):
        media_type = data['media_type']

        if utilities.isMovie(media_type):
            summaryInfo = globals.traktapi.getMovieSummary(data['id']).to_dict()
            if summaryInfo:
                s = utilities.getFormattedItemName(media_type, summaryInfo)
                logger.debug("doAddToWatchlist(): '%s' trying to add to users watchlist." % s)
                params = {'movies': [summaryInfo]}
                logger.debug("doAddToWatchlist(): %s" % str(params))

                result = globals.traktapi.addToWatchlist(params)
                if result:
                    kodiUtilities.notification(kodiUtilities.getString(32165), s)
                else:
                    kodiUtilities.notification(kodiUtilities.getString(32166), s)
        elif utilities.isEpisode(media_type):
            summaryInfo = {'shows': [{'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0],
                                      'seasons': [{'number': data['season'], 'episodes': [{'number':data['number']}]}]}]}
            logger.debug("doAddToWatchlist(): %s" % str(summaryInfo))
            s = utilities.getFormattedItemName(media_type, data)

            result = globals.traktapi.addToWatchlist(summaryInfo)
            if result:
                kodiUtilities.notification(kodiUtilities.getString(32165), s)
            else:
                kodiUtilities.notification(kodiUtilities.getString(32166), s)
        elif utilities.isSeason(media_type):
            summaryInfo = {'shows': [{'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0],
                                      'seasons': [{'number': data['season']}]}]}
            s = utilities.getFormattedItemName(media_type, data)

            logger.debug("doAddToWatchlist(): '%s - Season %d' trying to add to users watchlist."
                         % (data['id'], data['season']))

            result = globals.traktapi.addToWatchlist(summaryInfo)
            if result:
                kodiUtilities.notification(kodiUtilities.getString(32165), s)
            else:
                kodiUtilities.notification(kodiUtilities.getString(32166), s)
        elif utilities.isShow(media_type):
            summaryInfo = {'shows': [{'ids': utilities.parseIdToTraktIds(data['id'], media_type)[0]}]}
            s = utilities.getFormattedItemName(media_type, data)
            logger.debug("doAddToWatchlist(): %s" % str(summaryInfo))

            result = globals.traktapi.addToWatchlist(summaryInfo)
            if result:
                kodiUtilities.notification(kodiUtilities.getString(32165), s)
            else:
                kodiUtilities.notification(kodiUtilities.getString(32166), s)
Esempio n. 28
0
	def watching(self):
		if not self.isPlaying:
			return

		if not self.curVideoInfo:
			return

		Debug("[Scrobbler] watching()")
		scrobbleMovieOption = utilities.getSettingAsBool('scrobble_movie')
		scrobbleEpisodeOption = utilities.getSettingAsBool('scrobble_episode')

		self.update(True)

		duration = self.videoDuration / 60
		watchedPercent = (self.watchedTime / self.videoDuration) * 100

		if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
			response = self.traktapi.watchingMovie(self.curVideoInfo, duration, watchedPercent)
			if response != None:
				if self.curVideoInfo['imdbnumber'] is None:
					if 'status' in response and response['status'] == "success":
						if 'movie' in response and 'imdb_id' in response['movie']:
							self.curVideoInfo['imdbnumber'] = response['movie']['imdb_id']
							# get summary data now if we are rating this movie
							if utilities.getSettingAsBool('rate_movie') and self.traktSummaryInfo is None:
								self.traktSummaryInfo = self.traktapi.getMovieSummary(self.curVideoInfo['imdbnumber'])

				Debug("[Scrobbler] Watch response: %s" % str(response))
				
		elif utilities.isEpisode(self.curVideo['type']) and scrobbleEpisodeOption:
			if self.isMultiPartEpisode:
				Debug("[Scrobbler] Multi-part episode, watching part %d of %d." % (self.curMPEpisode + 1, self.curVideo['multi_episode_count']))
				# recalculate watchedPercent and duration for multi-part
				adjustedDuration = int(self.videoDuration / self.curVideo['multi_episode_count'])
				duration = adjustedDuration / 60
				watchedPercent = ((self.watchedTime - (adjustedDuration * self.curMPEpisode)) / adjustedDuration) * 100
			
			response = self.traktapi.watchingEpisode(self.curVideoInfo, duration, watchedPercent)
			if response != None:
				if self.curVideoInfo['tvdb_id'] is None:
					if 'status' in response and response['status'] == "success":
						if 'show' in response and 'tvdb_id' in response['show']:
							self.curVideoInfo['tvdb_id'] = response['show']['tvdb_id']
							# get summary data now if we are rating this episode
							if utilities.getSettingAsBool('rate_episode') and self.traktSummaryInfo is None:
								self.traktSummaryInfo = self.traktapi.getEpisodeSummary(self.curVideoInfo['tvdb_id'], self.curVideoInfo['season'], self.curVideoInfo['episode'])

				Debug("[Scrobbler] Watch response: %s" % str(response))
Esempio n. 29
0
def rateOnTrakt(rating, media_type, media, unrate=False):
    utils.Debug("[Rating] Sending rating (%s) to trakt.tv" % rating)

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

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

        data = globals.traktapi.rateMovie(params)

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

        data = globals.traktapi.rateShow(params)

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

        data = globals.traktapi.rateEpisode(params)

    else:
        return

    if data:
        s = utils.getFormattedItemName(media_type, media)
        if "status" in data and data["status"] == "success":
            if not unrate:
                utils.notification(utils.getString(1350), s)
            else:
                utils.notification(utils.getString(1352), s)
        elif "status" in data and data["status"] == "failure":
            utils.notification(utils.getString(1354), s)
        else:
            # status not in data, different problem, do nothing for now
            pass
Esempio n. 30
0
	def onFocus(self, controlID):
		if controlID in self.focus_labels:
			s = utils.getString(self.focus_labels[controlID])
			if self.rerate:
				if self.media['rating'] == self.buttons[controlID] or self.media['rating_advanced'] == self.buttons[controlID]:
					if utils.isMovie(self.media_type):
						s = utils.getString(1325)
					elif utils.isShow(self.media_type):
						s = utils.getString(1326)
					elif utils.isEpisode(self.media_type):
						s = utils.getString(1327)
					else:
						pass
			
			self.getControl(10013).setLabel(s)
		else:
			self.getControl(10013).setLabel('')
Esempio n. 31
0
	def onFocus(self, controlID):
		if controlID in self.focus_labels:
			s = utils.getString(self.focus_labels[controlID])

			if self.rerate:
				if self.media['user']['ratings'] and self.media['user']['ratings']['rating'] == self.buttons[controlID]:
					if utils.isMovie(self.media_type):
						s = utils.getString(32037)
					elif utils.isShow(self.media_type):
						s = utils.getString(32038)
					elif utils.isEpisode(self.media_type):
						s = utils.getString(32039)
					else:
						pass

			self.getControl(10013).setLabel(s)
		else:
			self.getControl(10013).setLabel('')
Esempio n. 32
0
	def onFocus(self, controlID):
		if controlID in self.focus_labels:
			s = utils.getString(self.focus_labels[controlID])

			if self.rerate:
				if self.media['user']['ratings'] and self.media['user']['ratings']['rating'] == self.buttons[controlID]:
					if utils.isMovie(self.media_type):
						s = utils.getString(32037)
					elif utils.isShow(self.media_type):
						s = utils.getString(32038)
					elif utils.isEpisode(self.media_type):
						s = utils.getString(32039)
					else:
						pass

			self.getControl(10013).setLabel(s)
		else:
			self.getControl(10013).setLabel('')
Esempio n. 33
0
    def __preFetchUserRatings(self, result):
        if result:
            if utilities.isMovie(
                    self.curVideo['type']) and utilities.getSettingAsBool(
                        'rate_movie'):
                # pre-get sumamry information, for faster rating dialog.
                logger.debug(
                    "Movie rating is enabled, pre-fetching summary information."
                )
                if result['movie']['ids']['imdb']:
                    self.curVideoInfo['user'] = {
                        'ratings':
                        self.traktapi.getMovieRatingForUser(
                            result['movie']['ids']['imdb'])
                    }
                    self.curVideoInfo['ids'] = result['movie']['ids']
                else:
                    logger.debug(
                        "'%s (%d)' has no valid id, can't get rating." %
                        (self.curVideoInfo['title'],
                         self.curVideoInfo['year']))
            elif utilities.isEpisode(
                    self.curVideo['type']) and utilities.getSettingAsBool(
                        'rate_episode'):
                # pre-get sumamry information, for faster rating dialog.
                logger.debug(
                    "Episode rating is enabled, pre-fetching summary information."
                )

                if result['show']['ids']['tvdb']:
                    self.curVideoInfo['user'] = {
                        'ratings':
                        self.traktapi.getEpisodeRatingForUser(
                            result['show']['ids']['tvdb'],
                            self.curVideoInfo['season'],
                            self.curVideoInfo['number'])
                    }
                    self.curVideoInfo['ids'] = result['episode']['ids']
                else:
                    logger.debug(
                        "'%s - S%02dE%02d' has no valid id, can't get rating."
                        % (self.curVideoInfo['showtitle'],
                           self.curVideoInfo['season'],
                           self.curVideoInfo['episode']))
Esempio n. 34
0
    def __preFetchUserRatings(self, result):
        if result:
            if utilities.isMovie(self.curVideo['type']) and utilities.getSettingAsBool('rate_movie'):
                # pre-get sumamry information, for faster rating dialog.
                logger.debug("Movie rating is enabled, pre-fetching summary information.")
                if result['movie']['ids']['imdb']:
                    self.curVideoInfo['user'] = {'ratings': self.traktapi.getMovieRatingForUser(result['movie']['ids']['imdb'])}
                    self.curVideoInfo['ids'] = result['movie']['ids']
                else:
                    logger.debug("'%s (%d)' has no valid id, can't get rating." % (self.curVideoInfo['title'], self.curVideoInfo['year']))
            elif utilities.isEpisode(self.curVideo['type']) and utilities.getSettingAsBool('rate_episode'):
                # pre-get sumamry information, for faster rating dialog.
                logger.debug("Episode rating is enabled, pre-fetching summary information.")

                if result['show']['ids']['tvdb']:
                    self.curVideoInfo['user'] = {'ratings': self.traktapi.getEpisodeRatingForUser(result['show']['ids']['tvdb'], self.curVideoInfo['season'], self.curVideoInfo['number'])}
                    self.curVideoInfo['ids'] = result['episode']['ids']
                else:
                    logger.debug("'%s - S%02dE%02d' has no valid id, can't get rating." % (self.curVideoInfo['showtitle'], self.curVideoInfo['season'], self.curVideoInfo['episode']))
Esempio n. 35
0
	def doManualRating(self, data):

		action = data['action']
		media_type = data['media_type']
		summaryInfo = None

		if not utilities.isValidMediaType(media_type):
			utilities.Debug("doManualRating(): Invalid media type '%s' passed for manual %s." % (media_type, action))
			return

		if not data['action'] in ['rate', 'unrate']:
			utilities.Debug("doManualRating(): Unknown action passed.")
			return
			
		if 'dbid' in data:
			utilities.Debug("Getting data for manual %s of library '%s' with ID of '%s'" % (action, media_type, data['dbid']))
		elif 'remoteitd' in data:
			if 'season' in data:
				utilities.Debug("Getting data for manual %s of non-library '%s' S%02dE%02d, with ID of '%s'." % (action, media_type, data['season'], data['episode'], data['remoteid']))
			else:
				utilities.Debug("Getting data for manual %s of non-library '%s' with ID of '%s'" % (action, media_type, data['remoteid']))

		if utilities.isEpisode(media_type):
			summaryInfo = globals.traktapi.getEpisodeSummary(data['tvdb_id'], data['season'], data['episode'])
		elif utilities.isShow(media_type):
			summaryInfo = globals.traktapi.getShowSummary(data['imdbnumber'])
		elif utilities.isMovie(media_type):
			summaryInfo = globals.traktapi.getMovieSummary(data['imdbnumber'])
		
		if not summaryInfo is None:
			if utilities.isMovie(media_type) or utilities.isShow(media_type):
				summaryInfo['xbmc_id'] = data['dbid']

			if action == 'rate':
				if not 'rating' in data:
					rateMedia(media_type, summaryInfo)
				else:
					rateMedia(media_type, summaryInfo, rating=data['rating'])
			elif action == 'unrate':
				rateMedia(media_type, summaryInfo, unrate=True)
		else:
			utilities.Debug("doManualRating(): Summary info was empty, possible problem retrieving data from trakt.tv")
Esempio n. 36
0
    def onInit(self):
        mange_string = getString(32133) if isMovie(self.media_type) else getString(32134)
        rate_string = getString(32137)
        if isShow(self.media_type):
            rate_string = getString(32138)
        elif isSeason(self.media_type):
            rate_string = getString(32149)
        elif isEpisode(self.media_type):
            rate_string = getString(32139)

        actions = [mange_string, getString(32135), getString(32136), rate_string, getString(32140), getString(32141), getString(32142), getString(32143)]
        keys = ["itemlists", "removefromlist", "addtowatchlist", "rate", "togglewatched", "managelists", "updatetags",
                "sync"]

        l = self.getControl(ACTION_LIST)
        for i in range(len(actions)):
            if keys[i] in self.buttons:
                l.addItem(self.newListItem(actions[i], id=keys[i]))

        self.setFocus(l)
Esempio n. 37
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)
Esempio n. 38
0
    def onInit(self):
        lang = utils.getString
        mange_string = lang(2000) if utils.isMovie(
            self.media_type) else lang(2001)
        rate_string = lang(2030)
        if utils.isShow(self.media_type):
            rate_string = lang(2031)
        elif utils.isEpisode(self.media_type):
            rate_string = lang(2032)

        actions = [
            mange_string,
            lang(2010),
            lang(2020), rate_string,
            lang(2040),
            lang(2050),
            lang(2060),
            lang(2070)
        ]
        keys = [
            "itemlists", "removefromlist", "addtolist", "rate",
            "togglewatched", "managelists", "updatetags", "sync"
        ]

        l = self.getControl(ACTION_LIST)
        for i in range(len(actions)):
            if keys[i] in self.buttons:
                l.addItem(self.newListItem(actions[i], id=keys[i]))

        h = ((len(self.buttons)) * 46) - 6
        l.setHeight(h)

        d = self.getControl(DIALOG_IMAGE)
        d.setHeight(h + 40)

        offset = (316 - h) / 2

        d.setPosition(0, offset - 20)
        l.setPosition(20, offset)

        self.setFocus(l)
Esempio n. 39
0
def __rateOnTrakt(rating, media_type, media, unrate=False):
    logger.debug("Sending rating (%s) to Trakt.tv" % rating)

    params = media
    if utilities.isMovie(media_type):
        key = 'movies'
        params['rating'] = rating
        if 'movieid' in media:
            kodiUtilities.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": media['movieid'], "userrating": rating}})
    elif utilities.isShow(media_type):
        key = 'shows'
        params['rating'] = rating
        if 'tvshowid' in media:
            kodiUtilities.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetTVShowDetails", "params": {"tvshowid": media['tvshowid'], "userrating": rating}})
    elif utilities.isSeason(media_type):
        key = 'shows'
        params['seasons'] = [{'rating': rating, 'number': media['season']}]
    elif utilities.isEpisode(media_type):
        key = 'episodes'
        params['rating'] = rating
        if 'episodeid' in media:
            kodiUtilities.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid": media['episodeid'], "userrating": rating}})
    else:
        return
    root = {key: [params]}

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

    if data:
        s = utilities.getFormattedItemName(media_type, media)
        if 'not_found' in data and not data['not_found']['movies'] and not data['not_found']['episodes'] and not data['not_found']['shows']:

            if not unrate:
                kodiUtilities.notification(kodiUtilities.getString(32040), s)
            else:
                kodiUtilities.notification(kodiUtilities.getString(32042), s)
        else:
            kodiUtilities.notification(kodiUtilities.getString(32044), s)
Esempio n. 40
0
 def __preFetchUserRatings(self, result):
     if result:
         if utilities.isMovie(self.curVideo["type"]) and utilities.getSettingAsBool("rate_movie"):
             # pre-get summary information, for faster rating dialog.
             logger.debug("Movie rating is enabled, pre-fetching summary information.")
             self.curVideoInfo = result["movie"]
             self.curVideoInfo["user"] = {
                 "ratings": self.traktapi.getMovieRatingForUser(result["movie"]["ids"]["trakt"], "trakt")
             }
         elif utilities.isEpisode(self.curVideo["type"]) and utilities.getSettingAsBool("rate_episode"):
             # pre-get summary information, for faster rating dialog.
             logger.debug("Episode rating is enabled, pre-fetching summary information.")
             self.curVideoInfo = result["episode"]
             self.curVideoInfo["user"] = {
                 "ratings": self.traktapi.getEpisodeRatingForUser(
                     result["show"]["ids"]["trakt"],
                     self.curVideoInfo["season"],
                     self.curVideoInfo["number"],
                     "trakt",
                 )
             }
         logger.debug("Pre-Fetch result: %s; Info: %s" % (result, self.curVideoInfo))
    def onInit(self):
        lang = utils.getString
        mange_string = lang(32133) if utils.isMovie(
            self.media_type) else lang(32134)
        rate_string = lang(32137)
        if utils.isShow(self.media_type):
            rate_string = lang(32138)
        elif utils.isSeason(self.media_type):
            rate_string = lang(32149)
        elif utils.isEpisode(self.media_type):
            rate_string = lang(32139)

        actions = [
            mange_string,
            lang(32135),
            lang(32136), rate_string,
            lang(32140),
            lang(32141),
            lang(32142),
            lang(32143)
        ]
        keys = [
            "itemlists", "removefromlist", "addtolist", "rate",
            "togglewatched", "managelists", "updatetags", "sync"
        ]

        l = self.getControl(ACTION_LIST)
        for i in range(len(actions)):
            if keys[i] in self.buttons:
                l.addItem(self.newListItem(actions[i], id=keys[i]))

        h = ((len(self.buttons)) * 46) - 6
        l.setHeight(h)

        d = self.getControl(DIALOG_IMAGE)
        d.setHeight(h + 40)

        self.setFocus(l)
Esempio n. 42
0
	def scrobble(self):
		if not self.curVideoInfo:
			return

		Debug("[Scrobbler] scrobble()")
		scrobbleMovieOption = utilities.getSettingAsBool('scrobble_movie')
		scrobbleEpisodeOption = utilities.getSettingAsBool('scrobble_episode')

		duration = self.videoDuration / 60
		watchedPercent = (self.watchedTime / self.videoDuration) * 100

		if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
			response = self.traktapi.scrobbleMovie(self.curVideoInfo, duration, watchedPercent)
			if not response is None and 'status' in response:
				if response['status'] == "success":
					self.watchlistTagCheck()
					Debug("[Scrobbler] Scrobble response: %s" % str(response))
				elif response['status'] == "failure":
					if response['error'].startswith("scrobbled") and response['error'].endswith("already"):
						Debug("[Scrobbler] Movie was just recently scrobbled, attempting to cancel watching instead.")
						self.stoppedWatching()

		elif utilities.isEpisode(self.curVideo['type']) and scrobbleEpisodeOption:
			if self.isMultiPartEpisode:
				Debug("[Scrobbler] Multi-part episode, scrobbling part %d of %d." % (self.curMPEpisode + 1, self.curVideo['multi_episode_count']))
				adjustedDuration = int(self.videoDuration / self.curVideo['multi_episode_count'])
				duration = adjustedDuration / 60
				watchedPercent = ((self.watchedTime - (adjustedDuration * self.curMPEpisode)) / adjustedDuration) * 100
			
			response = self.traktapi.scrobbleEpisode(self.curVideoInfo, duration, watchedPercent)
			if not response is None and 'status' in response:
				if response['status'] == "success":
					Debug("[Scrobbler] Scrobble response: %s" % str(response))
				elif response['status'] == "failure":
					if response['error'].startswith("scrobbled") and response['error'].endswith("already"):
						Debug("[Scrobbler] Episode was just recently scrobbled, attempting to cancel watching instead.")
						self.stoppedWatching()
Esempio n. 43
0
def __rateOnTrakt(rating, media_type, media, unrate=False):
    logger.debug("Sending rating (%s) to Trakt.tv" % rating)

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

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

    if data:
        s = utils.getFormattedItemName(media_type, media)
        if 'not_found' in data and not data['not_found']['movies'] and not data[
                'not_found']['episodes'] and not data['not_found']['shows']:

            if not unrate:
                utils.notification(utils.getString(32040), s)
            else:
                utils.notification(utils.getString(32042), s)
        else:
            utils.notification(utils.getString(32044), s)
Esempio n. 44
0
    def playbackStarted(self, data):
        logger.debug("playbackStarted(data: %s)" % data)
        if not data:
            return
        self.curVideo = data
        self.curVideoInfo = None
        self.videosToRate = []

        if not utilities.getSettingAsBool('scrobble_fallback') and 'id' not in self.curVideo and 'video_ids' not in self.curVideo:
            logger.debug('Aborting scrobble to avoid fallback: %s' % (self.curVideo))
            return
             
        if 'type' in self.curVideo:
            logger.debug("Watching: %s" % self.curVideo['type'])
            if not xbmc.Player().isPlayingVideo():
                logger.debug("Suddenly stopped watching item")
                return
            xbmc.sleep(1000)  # Wait for possible silent seek (caused by resuming)
            try:
                self.watchedTime = xbmc.Player().getTime()
                self.videoDuration = xbmc.Player().getTotalTime()
            except Exception as e:
                logger.debug("Suddenly stopped watching item: %s" % e.message)
                self.curVideo = None
                return

            if self.videoDuration == 0:
                if utilities.isMovie(self.curVideo['type']):
                    self.videoDuration = 90
                elif utilities.isEpisode(self.curVideo['type']):
                    self.videoDuration = 30
                else:
                    self.videoDuration = 1

            self.playlistLength = len(xbmc.PlayList(xbmc.PLAYLIST_VIDEO))
            self.playlistIndex = xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition()
            if self.playlistLength == 0:
                logger.debug("Warning: Cant find playlist length, assuming that this item is by itself")
                self.playlistLength = 1

            self.isMultiPartEpisode = False
            if utilities.isMovie(self.curVideo['type']):
                if 'id' in self.curVideo:
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject('movie', utilities.getMovieDetailsFromKodi(self.curVideo['id'], ['imdbnumber', 'title', 'year', 'file', 'lastplayed', 'playcount']))
                elif 'video_ids' in self.curVideo:
                    self.curVideoInfo = {'ids': self.curVideo['video_ids']}
                elif 'title' in self.curVideo and 'year' in self.curVideo:
                    self.curVideoInfo = {'title': self.curVideo['title'], 'year': self.curVideo['year']}

            elif utilities.isEpisode(self.curVideo['type']):
                if 'id' in self.curVideo:
                    episodeDetailsKodi = utilities.getEpisodeDetailsFromKodi(self.curVideo['id'], ['showtitle', 'season', 'episode', 'tvshowid', 'uniqueid', 'file', 'playcount'])
                    tvdb = episodeDetailsKodi['imdbnumber']
                    title, year = utilities.regex_year(episodeDetailsKodi['showtitle'])
                    if not year:
                        self.traktShowSummary = {'title': episodeDetailsKodi['showtitle'], 'year': episodeDetailsKodi['year']}
                    else:
                        self.traktShowSummary = {'title': title, 'year': year}
                    if tvdb:
                        self.traktShowSummary['ids'] = {'tvdb': tvdb}
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject('episode', episodeDetailsKodi)
                    if not self.curVideoInfo:  # getEpisodeDetailsFromKodi was empty
                        logger.debug("Episode details from Kodi was empty, ID (%d) seems invalid, aborting further scrobbling of this episode." % self.curVideo['id'])
                        self.curVideo = None
                        self.isPlaying = False
                        self.watchedTime = 0
                        return
                elif 'video_ids' in self.curVideo and 'season' in self.curVideo and 'episode' in self.curVideo:
                    self.curVideoInfo = {'season': self.curVideo['season'], 'number': self.curVideo['episode']}
                    self.traktShowSummary = {'ids': self.curVideo['video_ids']}
                elif 'title' in self.curVideo and 'season' in self.curVideo and 'episode' in self.curVideo:
                    self.curVideoInfo = {'title': self.curVideo['title'], 'season': self.curVideo['season'],
                                         'number': self.curVideo['episode']}

                    title, year = utilities.regex_year(self.curVideo['showtitle'])
                    if not year:
                        self.traktShowSummary = {'title': self.curVideo['showtitle']}
                    else:
                        self.traktShowSummary = {'title': title, 'year': year}

                    if 'year' in self.curVideo:
                        self.traktShowSummary['year'] = self.curVideo['year']

                if 'multi_episode_count' in self.curVideo and self.curVideo['multi_episode_count'] > 1:
                    self.isMultiPartEpisode = True

            self.isPlaying = True
            self.isPaused = False

            result = {}
            if utilities.getSettingAsBool('scrobble_movie') or utilities.getSettingAsBool('scrobble_episode'):
                result = self.__scrobble('start')
            elif utilities.getSettingAsBool('rate_movie') and utilities.isMovie(self.curVideo['type']) and 'ids' in self.curVideoInfo:
                best_id = utilities.best_id(self.curVideoInfo['ids'])
                result = {'movie': self.traktapi.getMovieSummary(best_id).to_dict()}
                if 'id' in self.curVideo: result['movie']['movieid'] = self.curVideo['id']
            elif utilities.getSettingAsBool('rate_episode') and utilities.isEpisode(self.curVideo['type']) and 'ids' in self.traktShowSummary:
                best_id = utilities.best_id(self.traktShowSummary['ids'])
                result = {'show': self.traktapi.getShowSummary(best_id).to_dict(),
                          'episode': self.traktapi.getEpisodeSummary(best_id, self.curVideoInfo['season'],
                                                                     self.curVideoInfo['number']).to_dict()}
                result['episode']['season'] = self.curVideoInfo['season']
                if 'id' in self.curVideo: result['episode']['episodeid'] = self.curVideo['id']

            self.__preFetchUserRatings(result)
Esempio n. 45
0
def test_isEpisode():
    assert utilities.isEpisode('episode')
Esempio n. 46
0
    def doMarkWatched(self, data):

        media_type = data['media_type']

        if utilities.isMovie(media_type):
            summaryInfo = globals.traktapi.getMovieSummary(
                data['id']).to_dict()
            if summaryInfo:
                if not summaryInfo['watched']:
                    s = utilities.getFormattedItemName(media_type, summaryInfo)
                    logger.debug(
                        "doMarkWatched(): '%s' is not watched on Trakt, marking it as watched."
                        % s)
                    params = {'movies': [summaryInfo]}
                    logger.debug("doMarkWatched(): %s" % str(params))

                    result = globals.traktapi.addToHistory(params)
                    if result:
                        utilities.notification(utilities.getString(32113), s)
                    else:
                        utilities.notification(utilities.getString(32114), s)
        elif utilities.isEpisode(media_type):
            summaryInfo = {
                'shows': [{
                    'ids':
                    utilities.parseIdToTraktIds(data['id'], media_type)[0],
                    'seasons': [{
                        'number': data['season'],
                        'episodes': [{
                            'number': data['number']
                        }]
                    }]
                }]
            }
            logger.debug("doMarkWatched(): %s" % str(summaryInfo))
            s = utilities.getFormattedItemName(media_type, data)

            result = globals.traktapi.addToHistory(summaryInfo)
            if result:
                utilities.notification(utilities.getString(32113), s)
            else:
                utilities.notification(utilities.getString(32114), s)
        elif utilities.isSeason(media_type):
            summaryInfo = {
                'shows': [{
                    'ids':
                    utilities.parseIdToTraktIds(data['id'], media_type)[0],
                    'seasons': [{
                        'number': data['season'],
                        'episodes': []
                    }]
                }]
            }
            s = utilities.getFormattedItemName(media_type, data)
            for ep in data['episodes']:
                summaryInfo['shows'][0]['seasons'][0]['episodes'].append(
                    {'number': ep})

            logger.debug(
                "doMarkWatched(): '%s - Season %d' has %d episode(s) that are going to be marked as watched."
                % (data['id'], data['season'],
                   len(summaryInfo['shows'][0]['seasons'][0]['episodes'])))

            if len(summaryInfo['shows'][0]['seasons'][0]['episodes']) > 0:
                logger.debug("doMarkWatched(): %s" % str(summaryInfo))

                result = globals.traktapi.addToHistory(summaryInfo)
                if result:
                    utilities.notification(
                        utilities.getString(32113),
                        utilities.getString(32115) %
                        (result['added']['episodes'], s))
                else:
                    utilities.notification(utilities.getString(32114), s)
        elif utilities.isShow(media_type):
            summaryInfo = {
                'shows': [{
                    'ids':
                    utilities.parseIdToTraktIds(data['id'], media_type)[0],
                    'seasons': []
                }]
            }
            if summaryInfo:
                s = utilities.getFormattedItemName(media_type, data)
                logger.debug('data: %s' % data)
                for season in data['seasons']:
                    episodeJson = []
                    for episode in data['seasons'][season]:
                        episodeJson.append({'number': episode})
                    summaryInfo['shows'][0]['seasons'].append({
                        'number':
                        season,
                        'episodes':
                        episodeJson
                    })

                if len(summaryInfo['shows'][0]['seasons'][0]['episodes']) > 0:
                    logger.debug("doMarkWatched(): %s" % str(summaryInfo))

                    result = globals.traktapi.addToHistory(summaryInfo)
                    if result:
                        utilities.notification(
                            utilities.getString(32113),
                            utilities.getString(32115) %
                            (result['added']['episodes'], s))
                    else:
                        utilities.notification(utilities.getString(32114), s)
Esempio n. 47
0
def Main():

	args = getArguments()
	data = {}

	if args['action'] == 'sync':
		data = {'action': 'manualSync'}

	elif args['action'] in ['rate', 'unrate']:
		data = {}
		data['action'] = args['action']
		media_type = None
		if 'media_type' in args and 'dbid' in args:
			media_type = args['media_type']
			try:
				data['dbid'] = int(args['dbid'])
			except ValueError:
				utils.Debug("Manual %s triggered for library item, but DBID is invalid." % args['action'])
				return
		elif 'media_type' in args and 'remoteid' in args:
			media_type = args['media_type']
			data['remoteid'] = args['remoteid']
			if 'season' in args:
				if not 'episode' in args:
					utils.Debug("Manual %s triggered for non-library episode, but missing episode number." % args['action'])
					return
				try:
					data['season'] = int(args['season'])
					data['episode'] = int(args['episode'])
				except ValueError:
					utilities.Debug("Error parsing season or episode for manual %s" % args['action'])
					return
		else:
			media_type = getMediaType()
			if not utils.isValidMediaType(media_type):
				utils.Debug("Error, not in video library.")
				return
			data['dbid'] = int(xbmc.getInfoLabel('ListItem.DBID'))

		if media_type is None:
			utils.Debug("Manual %s triggered on an unsupported content container." % args['action'])
		elif utils.isValidMediaType(media_type):
			data['media_type'] = media_type
			if 'dbid' in data:
				utils.Debug("Manual %s of library '%s' with an ID of '%s'." % (args['action'], media_type, data['dbid']))
				if utils.isMovie(media_type):
					result = utils.getMovieDetailsFromXbmc(data['dbid'], ['imdbnumber', 'title', 'year'])
					if not result:
						utils.Debug("No data was returned from XBMC, aborting manual %s." % args['action'])
						return
					data['imdbnumber'] = result['imdbnumber']

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

				elif utils.isEpisode(media_type):
					result = utils.getEpisodeDetailsFromXbmc(data['dbid'], ['showtitle', 'season', 'episode', 'tvshowid'])
					if not result:
						utils.Debug("No data was returned from XBMC, aborting manual %s." % args['action'])
						return
					data['tvdb_id'] = result['tvdb_id']
					data['season'] = result['season']
					data['episode'] = result['episode']

			else:
				if 'season' in data:
					utils.Debug("Manual %s of non-library '%s' S%02dE%02d, with an ID of '%s'." % (args['action'], media_type, data['season'], data['episode'], data['remoteid']))
					data['tvdb_id'] = data['remoteid']
				else:
					utils.Debug("Manual %s of non-library '%s' with an ID of '%s'." % (args['action'], media_type, data['remoteid']))
					data['imdbnumber'] = data['remoteid']

			if args['action'] == 'rate' and 'rating' in args:
				if args['rating'] in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']:
					data['rating'] = int(args['rating'])

			data = {'action': 'manualRating', 'ratingData': data}

		else:
			utils.Debug("Manual %s of '%s' is unsupported." % (args['action'], media_type))

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

			elif utils.isEpisode(media_type):
				dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
				result = utils.getEpisodeDetailsFromXbmc(dbid, ['showtitle', 'season', 'episode', 'tvshowid', 'playcount'])
				if result:
					if result['playcount'] == 0:
						data['id'] = result['tvdb_id']
						data['season'] = result['season']
						data['episode'] = result['episode']
					else:
						utils.Debug("Episode already marked as watched in XBMC.")
				else:
					utils.Debug("Error getting episode details from XBMC.")
					return

			elif utils.isSeason(media_type):
				showID = None
				showTitle = xbmc.getInfoLabel('ListItem.TVShowTitle')
				result = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber', 'year']}, 'id': 0})
				if result and 'tvshows' in result:
					for show in result['tvshows']:
						if show['title'] == showTitle:
							showID = show['tvshowid']
							data['id'] = show['imdbnumber']
							break
				else:
					utils.Debug("Error getting TV shows from XBMC.")
					return

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

				result = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': showID, 'season': season, 'properties': ['season', 'episode', 'playcount']}, 'id': 0})
				if result and 'episodes' in result:
					episodes = []
					for episode in result['episodes']:
						if episode['playcount'] == 0:
							episodes.append(episode['episode'])
					
					if len(episodes) == 0:
						utils.Debug("'%s - Season %d' is already marked as watched." % (showTitle, season))
						return

					data['season'] = season
					data['episodes'] = episodes
				else:
					utils.Debug("Error getting episodes from '%s' for Season %d" % (showTitle, season))
					return

			elif utils.isShow(media_type):
				dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
				result = utils.getShowDetailsFromXBMC(dbid, ['year', 'imdbnumber'])
				if not result:
					utils.Debug("Error getting show details from XBMC.")
					return
				showTitle = result['label']
				data['id'] = result['imdbnumber']
				result = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': dbid, 'properties': ['season', 'episode', 'playcount']}, 'id': 0})
				if result and 'episodes' in result:
					i = 0
					s = {}
					for e in result['episodes']:
						season = str(e['season'])
						if not season in s:
							s[season] = []
						if e['playcount'] == 0:
							s[season].append(e['episode'])
							i = i + 1

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

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

			if len(data) > 1:
				utils.Debug("Marking '%s' with the following data '%s' as watched on trakt.tv" % (media_type, str(data)))
				data['action'] = 'markWatched'

		# execute toggle watched action
		xbmc.executebuiltin("Action(ToggleWatched)")

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

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

	elif args['action'] == 'timertest':
		utils.Debug("Timing JSON requests.")
		import time
		t = time.time()
		data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShowDetails', 'params':{'tvshowid': 254, 'properties': ['tag']}, 'id': 1})
		#data = utils.getShowDetailsFromXBMC(254, ['tag', 'imdbnumber'])
		e = time.time() - t
		utils.Debug("VideoLibrary.GetTVShowDetails with tags: %0.3f seconds." % e)
		
		t = time.time()
		data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovieDetails', 'params':{'movieid': 634, 'properties': ['tag']}, 'id': 1})
		#data = utils.getMovieDetailsFromXbmc(634, ['tag', 'imdbnumber', 'title', 'year'])
		e = time.time() - t
		utils.Debug("VideoLibrary.GetMovieDetails with tags: %0.3f seconds." % e)

		t = time.time()
		data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['tag', 'title', 'imdbnumber', 'year']}, 'id': 0})
		e = time.time() - t
		utils.Debug("VideoLibrary.GetTVShows with tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['tvshows']), e / len(data['tvshows'])))
		
		t = time.time()
		data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['tag', 'title', 'imdbnumber', 'year']}})
		e = time.time() - t
		utils.Debug("VideoLibrary.GetMovies with tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['movies']), e / len(data['movies'])))
		
		t = time.time()
		data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber', 'year']}, 'id': 0})
		e = time.time() - t
		utils.Debug("VideoLibrary.GetTVShows without tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['tvshows']), e / len(data['tvshows'])))
		
		t = time.time()
		data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'id': 0, 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['title', 'imdbnumber', 'year']}})
		e = time.time() - t
		utils.Debug("VideoLibrary.GetMovies without tags: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data['movies']), e / len(data['movies'])))
		
		t = time.time()
		data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShowDetails', 'params':{'tvshowid': 254, 'properties': ['imdbnumber']}, 'id': 1})
		#data = utils.getShowDetailsFromXBMC(254, ['imdbnumber'])
		e = time.time() - t
		utils.Debug("VideoLibrary.GetTVShowDetails without tags: %0.3f seconds." % e)
		
		t = time.time()
		data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovieDetails', 'params':{'movieid': 634, 'properties': ['imdbnumber', 'title', 'year']}, 'id': 1})
		#data = utils.getMovieDetailsFromXbmc(634, ['imdbnumber', 'title', 'year'])
		e = time.time() - t
		utils.Debug("VideoLibrary.GetMovieDetails without tags: %0.3f seconds." % e)
		
		t = time.time()
		data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title', 'imdbnumber', 'year']}, 'id': 0})
		data = data['tvshows']
		for item in data:
			item_data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShowDetails', 'params':{'tvshowid': item['tvshowid'], 'properties': ['tag']}, 'id': 1})
			item['tag'] = item_data['tvshowdetails']['tag']
		e = time.time() - t
		utils.Debug("VideoLibrary.GetTVShows with tags from loop: %0.3f seconds, %d items at %0.5f seconds per item" % (e, len(data), e / len(data)))
		
		t = time.time()
		data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovies', 'params': {'properties': ['title', 'imdbnumber', 'year']}, 'id': 0})
		data = data['movies']
		for item in data:
			item_data = utils.xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovieDetails', 'params':{'movieid': item['movieid'], 'properties': ['tag']}, 'id': 1})
			item['tag'] = item_data['moviedetails']['tag']
		e = time.time() - t
		utils.Debug("VideoLibrary.GetMovies with tags from: %0.3f seconds, %d items at %0.5f seconds per item." % (e, len(data), e / len(data)))

	elif args['action'] in ['itemlists', 'addtolist', 'removefromlist']:
		data = {}
		data['action'] = args['action']
		media_type = None
		dbid = None
		if 'media_type' in args and 'dbid' in args:
			media_type = args['media_type']
			try:
				dbid = int(args['dbid'])
			except ValueError:
				utils.Debug("'%s' triggered for library item, but DBID is invalid." % args['action'])
				return
		else:
			media_type = getMediaType()
			if not media_type in ['movie', 'show']:
				utils.Debug("Error, not in video library.")
				return
			try:
				dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
			except ValueError:
				utils.Debug("'%s' triggered for library item, but there is a problem with ListItem.DBID." % args['action'])
				return
		
		if not media_type in ['movie', 'show']:
			utils.Debug("'%s' is not a valid media type for '%s'." % (media_type, args['action']))
			return

		if args['action'] in ['addtolist', 'removefromlist']:
			if 'list' in args:
				data['list'] = args['list']
			else:
				utils.Debug("'%s' requires a list parameter." % data['action'])

		data['type'] = media_type

		if utils.isMovie(media_type):
			result = utils.getMovieDetailsFromXbmc(dbid, ['imdbnumber', 'title', 'year', 'tag'])
			if not result:
				utils.Debug("Error getting movie details from XBMC.")
				return
			data['tag'] = result['tag']
			data['movieid'] = result['movieid']
			data['title'] = result['title']
			data['year'] = result['year']
			if result['imdbnumber'].startswith("tt"):
				data['imdb_id'] = result['imdbnumber']
			elif result['imdbnumber'].isdigit():
				data['tmdb_id'] = result['imdbnumber']
		
		elif utils.isShow(media_type):
			result = utils.getShowDetailsFromXBMC(dbid, ['imdbnumber', 'title', 'tag'])
			if not result:
				utils.Debug("Error getting show details from XBMC.")
				return
			data['tag'] = result['tag']
			data['tvshowid'] = result['tvshowid']
			data['title'] = result['title']
			if result['imdbnumber'].startswith("tt"):
				data['imdb_id'] = result['imdbnumber']
			elif result['imdbnumber'].isdigit():
				data['tvdb_id'] = result['imdbnumber']

	q = queue.SqliteQueue()
	if 'action' in data:
		utils.Debug("Queuing for dispatch: %s" % data)
		q.append(data)
Esempio n. 48
0
	def doMarkWatched(self, data):

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

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

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

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

				if len(params['episodes']) > 0:
					utilities.Debug("doMarkWatched(): %s" % str(params))
					if not simulate:
						result = globals.traktapi.updateSeenEpisode(params)
						if result:
							if markedNotification:
								utilities.notification(utilities.getString(1550), utilities.getString(1552) % (len(params['episodes']), s))
						else:
							utilities.notification(utilities.getString(1551), utilities.getString(1552) % (len(params['episodes']), s))
					else:
						if markedNotification:
							utilities.notification(utilities.getString(1550), utilities.getString(1552) % (len(params['episodes']), s))
Esempio n. 49
0
    def __scrobble(self, status):
        if not self.curVideoInfo:
            return

        logger.debug("scrobble()")
        scrobbleMovieOption = kodiUtilities.getSettingAsBool('scrobble_movie')
        scrobbleEpisodeOption = kodiUtilities.getSettingAsBool(
            'scrobble_episode')

        watchedPercent = self.__calculateWatchedPercent()

        if utilities.isMovie(self.curVideo['type']) and scrobbleMovieOption:
            response = self.traktapi.scrobbleMovie(self.curVideoInfo,
                                                   watchedPercent, status)
            if response is not None:
                self.__scrobbleNotification(response)
                logger.debug("Scrobble response: %s" % str(response))
                return response
            else:
                logger.debug("Failed to scrobble movie: %s | %s | %s" %
                             (self.curVideoInfo, watchedPercent, status))

        elif utilities.isEpisode(
                self.curVideo['type']) and scrobbleEpisodeOption:
            if self.isMultiPartEpisode:
                logger.debug("Multi-part episode, scrobbling part %d of %d." %
                             (self.curMPEpisode + 1,
                              self.curVideo['multi_episode_count']))
                adjustedDuration = int(self.videoDuration /
                                       self.curVideo['multi_episode_count'])
                watchedPercent = ((self.watchedTime -
                                   (adjustedDuration * self.curMPEpisode)) /
                                  adjustedDuration) * 100

            logger.debug("scrobble sending show object: %s" %
                         str(self.traktShowSummary))
            logger.debug("scrobble sending episode object: %s" %
                         str(self.curVideoInfo))
            response = self.traktapi.scrobbleEpisode(self.traktShowSummary,
                                                     self.curVideoInfo,
                                                     watchedPercent, status)

            if (kodiUtilities.getSettingAsBool('scrobble_secondary_title')):
                logger.debug(
                    '[traktPlayer] Setting is enabled to try secondary show title, if necessary.'
                )
                # If there is an empty response, the reason might be that the title we have isn't the actual show title,
                # but rather an alternative title. To handle this case, call the Trakt search function.
                if response is None:
                    logger.debug("Searching for show title: %s" %
                                 self.traktShowSummary['title'])
                    # This text query API is basically the same as searching on the website. Works with alternative
                    # titles, unlike the scrobble function.
                    newResp = self.traktapi.getTextQuery(
                        self.traktShowSummary['title'], "show", None)
                    if not newResp:
                        logger.debug(
                            "Empty Response from getTextQuery, giving up")
                    else:
                        logger.debug("Got Response from getTextQuery: %s" %
                                     str(newResp))
                        # We got something back. Have to assume the first show found is the right one; if there's more than
                        # one, there's no way to know which to use. Pull the primary title from the response (and the year,
                        # just because it's there).
                        showObj = {
                            'title': newResp[0].title,
                            'year': newResp[0].year
                        }
                        logger.debug(
                            "scrobble sending getTextQuery first show object: %s"
                            % str(showObj))
                        # Now we can attempt the scrobble again, using the primary title this time.
                        response = self.traktapi.scrobbleEpisode(
                            showObj, self.curVideoInfo, watchedPercent, status)

            if response is not None:
                self.__scrobbleNotification(response)
                logger.debug("Scrobble response: %s" % str(response))
                return response
            else:
                logger.debug("Failed to scrobble episode: %s | %s | %s | %s" %
                             (self.traktShowSummary, self.curVideoInfo,
                              watchedPercent, status))
Esempio n. 50
0
    def playbackStarted(self, data):
        logger.debug("playbackStarted(data: %s)" % data)
        if not data:
            return
        self.curVideo = data
        self.curVideoInfo = None
        self.videosToRate = []

        if not utilities.getSettingAsBool('scrobble_fallback') and 'id' not in self.curVideo and 'video_ids' not in self.curVideo:
            logger.debug('Aborting scrobble to avoid fallback: %s' % (self.curVideo))
            return
             
        if 'type' in self.curVideo:
            logger.debug("Watching: %s" % self.curVideo['type'])
            if not xbmc.Player().isPlayingVideo():
                logger.debug("Suddenly stopped watching item")
                return
            xbmc.sleep(1000)  # Wait for possible silent seek (caused by resuming)
            try:
                self.watchedTime = xbmc.Player().getTime()
                self.videoDuration = xbmc.Player().getTotalTime()
            except Exception as e:
                logger.debug("Suddenly stopped watching item: %s" % e.message)
                self.curVideo = None
                return

            if self.videoDuration == 0:
                if utilities.isMovie(self.curVideo['type']):
                    self.videoDuration = 90
                elif utilities.isEpisode(self.curVideo['type']):
                    self.videoDuration = 30
                else:
                    self.videoDuration = 1

            self.playlistLength = len(xbmc.PlayList(xbmc.PLAYLIST_VIDEO))
            self.playlistIndex = xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition()
            if self.playlistLength == 0:
                logger.debug("Warning: Cant find playlist length, assuming that this item is by itself")
                self.playlistLength = 1

            self.isMultiPartEpisode = False
            if utilities.isMovie(self.curVideo['type']):
                if 'id' in self.curVideo:
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject('movie', utilities.getMovieDetailsFromKodi(self.curVideo['id'], ['imdbnumber', 'title', 'year', 'file', 'lastplayed', 'playcount']))
                elif 'video_ids' in self.curVideo:
                    self.curVideoInfo = {'ids': self.curVideo['video_ids'], 'title': self.curVideo['title'], 'year': self.curVideo['year']}
                elif 'title' in self.curVideo and 'year' in self.curVideo:
                    self.curVideoInfo = {'title': self.curVideo['title'], 'year': self.curVideo['year']}

            elif utilities.isEpisode(self.curVideo['type']):
                if 'id' in self.curVideo:
                    episodeDetailsKodi = utilities.getEpisodeDetailsFromKodi(self.curVideo['id'], ['showtitle', 'season', 'episode', 'tvshowid', 'uniqueid', 'file', 'playcount'])
                    tvdb = episodeDetailsKodi['imdbnumber']
                    title, year = utilities.regex_year(episodeDetailsKodi['showtitle'])
                    if not year:
                        self.traktShowSummary = {'title': episodeDetailsKodi['showtitle'], 'year': episodeDetailsKodi['year']}
                    else:
                        self.traktShowSummary = {'title': title, 'year': year}
                    if tvdb:
                        self.traktShowSummary['ids'] = {'tvdb': tvdb}
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject('episode', episodeDetailsKodi)
                    if not self.curVideoInfo:  # getEpisodeDetailsFromKodi was empty
                        logger.debug("Episode details from Kodi was empty, ID (%d) seems invalid, aborting further scrobbling of this episode." % self.curVideo['id'])
                        self.curVideo = None
                        self.isPlaying = False
                        self.watchedTime = 0
                        return
                elif 'video_ids' in self.curVideo and 'season' in self.curVideo and 'episode' in self.curVideo:
                    self.curVideoInfo = {'title': self.curVideo['title'], 'season': self.curVideo['season'], 'number': self.curVideo['episode']}
                    self.traktShowSummary = {'ids': self.curVideo['video_ids']}
                elif 'title' in self.curVideo and 'season' in self.curVideo and 'episode' in self.curVideo:
                    self.curVideoInfo = {'title': self.curVideo['title'], 'season': self.curVideo['season'],
                                         'number': self.curVideo['episode']}

                    title, year = utilities.regex_year(self.curVideo['showtitle'])
                    if not year:
                        self.traktShowSummary = {'title': self.curVideo['showtitle']}
                    else:
                        self.traktShowSummary = {'title': title, 'year': year}

                    if 'year' in self.curVideo:
                        self.traktShowSummary['year'] = self.curVideo['year']

                if 'multi_episode_count' in self.curVideo and self.curVideo['multi_episode_count'] > 1:
                    self.isMultiPartEpisode = True

            self.isPlaying = True
            self.isPaused = False

            result = {}
            if utilities.getSettingAsBool('scrobble_movie') or utilities.getSettingAsBool('scrobble_episode'):
                result = self.__scrobble('start')
            elif utilities.getSettingAsBool('rate_movie') and utilities.isMovie(self.curVideo['type']) and 'ids' in self.curVideoInfo:
                result = {'movie': self.traktapi.getMovieSummary(utilities.best_id(self.curVideoInfo['ids'])).to_dict()}
            elif utilities.getSettingAsBool('rate_episode') and utilities.isEpisode(self.curVideo['type']) and 'ids' in self.traktShowSummary:
                best_id = utilities.best_id(self.traktShowSummary['ids'])
                result = {'show': self.traktapi.getShowSummary(best_id).to_dict(),
                          'episode': self.traktapi.getEpisodeSummary(best_id, self.curVideoInfo['season'], self.curVideoInfo['number']).to_dict()}

            self.__preFetchUserRatings(result)
Esempio n. 51
0
def rateMedia(media_type, summary_info, unrate=False, rating=None):
	"""Launches the rating dialog"""
	if not utils.isValidMediaType(media_type):
		return
	
	if utils.isEpisode(media_type):
		if 'rating' in summary_info['episode']:
			summary_info['rating'] = summary_info['episode']['rating']
		if 'rating_advanced' in summary_info['episode']:
			summary_info['rating_advanced'] = summary_info['episode']['rating_advanced']

	s = utils.getFormattedItemName(media_type, summary_info)

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

	if unrate:
		rating = None

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

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

		return

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

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

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

	gui.doModal()
	if gui.rating:
		rating = gui.rating
		if rerate:
			rating = gui.rating
			
			if rating_type == "simple":
				if not summary_info['rating'] == "false" and rating == summary_info['rating']:
					rating = "unrate"
			else:
				if summary_info['rating_advanced'] > 0 and rating == summary_info['rating_advanced']:
					rating = 0

		if rating == 0 or rating == "unrate":
			rateOnTrakt(rating, gui.media_type, gui.media, unrate=True)
		else:
			rateOnTrakt(rating, gui.media_type, gui.media)
	else:
		utils.Debug("[Rating] Rating dialog was closed with no rating.")

	del gui
Esempio n. 52
0
def Main():
    args = __getArguments()
    data = {}

    if args['action'] == 'auth_info':
        data['action'] = 'auth_info'

    if args['action'] == 'contextmenu':
        buttons = []
        media_type = kodiUtilities.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 = kodiUtilities.getMediaType()
            if not utilities.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 utilities.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 utilities.isMovie(media_type):
                    result = kodiUtilities.getMovieDetailsFromKodi(
                        data['dbid'], ['imdbnumber', 'title', 'year'])
                    if not result:
                        logger.debug(
                            "No data was returned from Kodi, aborting manual %s."
                            % args['action'])
                        return

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

                elif utilities.isSeason(media_type):
                    result = kodiUtilities.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 utilities.isEpisode(media_type):
                    result = kodiUtilities.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 utilities.isShow(media_type) or utilities.isSeason(
                        media_type) or utilities.isEpisode(media_type):
                    result = kodiUtilities.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 = kodiUtilities.getMediaType()
        if media_type in ['movie', 'show', 'season', 'episode']:
            data = {'media_type': media_type}
            if utilities.isMovie(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = kodiUtilities.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 utilities.isEpisode(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = kodiUtilities.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 utilities.isSeason(media_type):
                showID = None
                showTitle = xbmc.getInfoLabel('ListItem.TVShowTitle')
                result = kodiUtilities.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 = kodiUtilities.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 utilities.isShow(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = kodiUtilities.getShowDetailsFromKodi(
                    dbid, ['year', 'imdbnumber'])
                if not result:
                    logger.debug("Error getting show details from Kodi.")
                    return
                showTitle = result['label']
                data['id'] = result['imdbnumber']
                result = kodiUtilities.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 = kodiUtilities.getMediaType()
        if media_type in ['movie', 'show', 'season', 'episode']:
            data = {'media_type': media_type}
            if utilities.isMovie(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = kodiUtilities.getMovieDetailsFromKodi(
                    dbid, ['imdbnumber', 'title', 'year', 'playcount'])
                if result:
                    data['id'] = result['imdbnumber']

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

            elif utilities.isEpisode(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = kodiUtilities.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 utilities.isSeason(media_type):
                showID = None
                showTitle = xbmc.getInfoLabel('ListItem.TVShowTitle')
                result = kodiUtilities.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 = kodiUtilities.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 utilities.isShow(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = kodiUtilities.getShowDetailsFromKodi(
                    dbid, ['year', 'imdbnumber'])
                if not result:
                    logger.debug("Error getting show details from Kodi.")
                    return
                showTitle = result['label']
                data['id'] = result['imdbnumber']
                result = kodiUtilities.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)
Esempio n. 53
0
def Main():

    args = getArguments()
    data = {}

    if args['action'] == 'sync':
        data = {'action': 'manualSync'}

    elif args['action'] in ['rate', 'unrate']:
        data = {}
        data['action'] = args['action']
        media_type = None
        if 'media_type' in args and 'dbid' in args:
            media_type = args['media_type']
            try:
                data['dbid'] = int(args['dbid'])
            except ValueError:
                utils.Debug(
                    "Manual %s triggered for library item, but DBID is invalid."
                    % args['action'])
                return
        elif 'media_type' in args and 'remoteid' in args:
            media_type = args['media_type']
            data['remoteid'] = args['remoteid']
            if 'season' in args:
                if not 'episode' in args:
                    utils.Debug(
                        "Manual %s triggered for non-library episode, but missing episode number."
                        % args['action'])
                    return
                try:
                    data['season'] = int(args['season'])
                    data['episode'] = int(args['episode'])
                except ValueError:
                    utilities.Debug(
                        "Error parsing season or episode for manual %s" %
                        args['action'])
                    return
        else:
            media_type = getMediaType()
            if not utils.isValidMediaType(media_type):
                utils.Debug("Error, not in video library.")
                return
            data['dbid'] = int(xbmc.getInfoLabel('ListItem.DBID'))

        if media_type is None:
            utils.Debug(
                "Manual %s triggered on an unsupported content container." %
                args['action'])
        elif utils.isValidMediaType(media_type):
            data['media_type'] = media_type
            if 'dbid' in data:
                utils.Debug("Manual %s of library '%s' with an ID of '%s'." %
                            (args['action'], media_type, data['dbid']))
                if utils.isMovie(media_type):
                    result = utils.getMovieDetailsFromXbmc(
                        data['dbid'], ['imdbnumber', 'title', 'year'])
                    if not result:
                        utils.Debug(
                            "No data was returned from XBMC, aborting manual %s."
                            % args['action'])
                        return
                    data['imdbnumber'] = result['imdbnumber']

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

                elif utils.isEpisode(media_type):
                    result = utils.getEpisodeDetailsFromXbmc(
                        data['dbid'],
                        ['showtitle', 'season', 'episode', 'tvshowid'])
                    if not result:
                        utils.Debug(
                            "No data was returned from XBMC, aborting manual %s."
                            % args['action'])
                        return
                    data['tvdb_id'] = result['tvdb_id']
                    data['season'] = result['season']
                    data['episode'] = result['episode']

            else:
                if 'season' in data:
                    utils.Debug(
                        "Manual %s of non-library '%s' S%02dE%02d, with an ID of '%s'."
                        % (args['action'], media_type, data['season'],
                           data['episode'], data['remoteid']))
                    data['tvdb_id'] = data['remoteid']
                else:
                    utils.Debug(
                        "Manual %s of non-library '%s' with an ID of '%s'." %
                        (args['action'], media_type, data['remoteid']))
                    data['imdbnumber'] = data['remoteid']

            if args['action'] == 'rate' and 'rating' in args:
                if args['rating'] in [
                        '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'
                ]:
                    data['rating'] = int(args['rating'])

            data = {'action': 'manualRating', 'ratingData': data}

        else:
            utils.Debug("Manual %s of '%s' is unsupported." %
                        (args['action'], media_type))

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

            elif utils.isEpisode(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = utils.getEpisodeDetailsFromXbmc(
                    dbid, [
                        'showtitle', 'season', 'episode', 'tvshowid',
                        'playcount'
                    ])
                if result:
                    if result['playcount'] == 0:
                        data['id'] = result['tvdb_id']
                        data['season'] = result['season']
                        data['episode'] = result['episode']
                    else:
                        utils.Debug(
                            "Episode already marked as watched in XBMC.")
                else:
                    utils.Debug("Error getting episode details from XBMC.")
                    return

            elif utils.isSeason(media_type):
                showID = None
                showTitle = xbmc.getInfoLabel('ListItem.TVShowTitle')
                result = utils.xbmcJsonRequest({
                    'jsonrpc': '2.0',
                    'method': 'VideoLibrary.GetTVShows',
                    'params': {
                        'properties': ['title', 'imdbnumber', 'year']
                    },
                    'id': 0
                })
                if result and 'tvshows' in result:
                    for show in result['tvshows']:
                        if show['title'] == showTitle:
                            showID = show['tvshowid']
                            data['id'] = show['imdbnumber']
                            break
                else:
                    utils.Debug("Error getting TV shows from XBMC.")
                    return

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

                result = utils.xbmcJsonRequest({
                    'jsonrpc': '2.0',
                    'method': 'VideoLibrary.GetEpisodes',
                    'params': {
                        'tvshowid': showID,
                        'season': season,
                        'properties': ['season', 'episode', 'playcount']
                    },
                    'id': 0
                })
                if result and 'episodes' in result:
                    episodes = []
                    for episode in result['episodes']:
                        if episode['playcount'] == 0:
                            episodes.append(episode['episode'])

                    if len(episodes) == 0:
                        utils.Debug(
                            "'%s - Season %d' is already marked as watched." %
                            (showTitle, season))
                        return

                    data['season'] = season
                    data['episodes'] = episodes
                else:
                    utils.Debug(
                        "Error getting episodes from '%s' for Season %d" %
                        (showTitle, season))
                    return

            elif utils.isShow(media_type):
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
                result = utils.getShowDetailsFromXBMC(dbid,
                                                      ['year', 'imdbnumber'])
                if not result:
                    utils.Debug("Error getting show details from XBMC.")
                    return
                showTitle = result['label']
                data['id'] = result['imdbnumber']
                result = utils.xbmcJsonRequest({
                    'jsonrpc': '2.0',
                    'method': 'VideoLibrary.GetEpisodes',
                    'params': {
                        'tvshowid': dbid,
                        'properties': ['season', 'episode', 'playcount']
                    },
                    'id': 0
                })
                if result and 'episodes' in result:
                    i = 0
                    s = {}
                    for e in result['episodes']:
                        season = str(e['season'])
                        if not season in s:
                            s[season] = []
                        if e['playcount'] == 0:
                            s[season].append(e['episode'])
                            i = i + 1

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

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

            if len(data) > 1:
                utils.Debug(
                    "Marking '%s' with the following data '%s' as watched on trakt.tv"
                    % (media_type, str(data)))
                data['action'] = 'markWatched'

        # execute toggle watched action
        xbmc.executebuiltin("Action(ToggleWatched)")

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

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

    elif args['action'] == 'timertest':
        utils.Debug("Timing JSON requests.")
        import time
        t = time.time()
        data = utils.xbmcJsonRequest({
            'jsonrpc': '2.0',
            'method': 'VideoLibrary.GetTVShowDetails',
            'params': {
                'tvshowid': 254,
                'properties': ['tag']
            },
            'id': 1
        })
        #data = utils.getShowDetailsFromXBMC(254, ['tag', 'imdbnumber'])
        e = time.time() - t
        utils.Debug("VideoLibrary.GetTVShowDetails with tags: %0.3f seconds." %
                    e)

        t = time.time()
        data = utils.xbmcJsonRequest({
            'jsonrpc': '2.0',
            'method': 'VideoLibrary.GetMovieDetails',
            'params': {
                'movieid': 634,
                'properties': ['tag']
            },
            'id': 1
        })
        #data = utils.getMovieDetailsFromXbmc(634, ['tag', 'imdbnumber', 'title', 'year'])
        e = time.time() - t
        utils.Debug("VideoLibrary.GetMovieDetails with tags: %0.3f seconds." %
                    e)

        t = time.time()
        data = utils.xbmcJsonRequest({
            'jsonrpc': '2.0',
            'method': 'VideoLibrary.GetTVShows',
            'params': {
                'properties': ['tag', 'title', 'imdbnumber', 'year']
            },
            'id': 0
        })
        e = time.time() - t
        utils.Debug(
            "VideoLibrary.GetTVShows with tags: %0.3f seconds, %d items at %0.5f seconds per item"
            % (e, len(data['tvshows']), e / len(data['tvshows'])))

        t = time.time()
        data = utils.xbmcJsonRequest({
            'jsonrpc': '2.0',
            'id': 0,
            'method': 'VideoLibrary.GetMovies',
            'params': {
                'properties': ['tag', 'title', 'imdbnumber', 'year']
            }
        })
        e = time.time() - t
        utils.Debug(
            "VideoLibrary.GetMovies with tags: %0.3f seconds, %d items at %0.5f seconds per item"
            % (e, len(data['movies']), e / len(data['movies'])))

        t = time.time()
        data = utils.xbmcJsonRequest({
            'jsonrpc': '2.0',
            'method': 'VideoLibrary.GetTVShows',
            'params': {
                'properties': ['title', 'imdbnumber', 'year']
            },
            'id': 0
        })
        e = time.time() - t
        utils.Debug(
            "VideoLibrary.GetTVShows without tags: %0.3f seconds, %d items at %0.5f seconds per item"
            % (e, len(data['tvshows']), e / len(data['tvshows'])))

        t = time.time()
        data = utils.xbmcJsonRequest({
            'jsonrpc': '2.0',
            'id': 0,
            'method': 'VideoLibrary.GetMovies',
            'params': {
                'properties': ['title', 'imdbnumber', 'year']
            }
        })
        e = time.time() - t
        utils.Debug(
            "VideoLibrary.GetMovies without tags: %0.3f seconds, %d items at %0.5f seconds per item"
            % (e, len(data['movies']), e / len(data['movies'])))

        t = time.time()
        data = utils.xbmcJsonRequest({
            'jsonrpc': '2.0',
            'method': 'VideoLibrary.GetTVShowDetails',
            'params': {
                'tvshowid': 254,
                'properties': ['imdbnumber']
            },
            'id': 1
        })
        #data = utils.getShowDetailsFromXBMC(254, ['imdbnumber'])
        e = time.time() - t
        utils.Debug(
            "VideoLibrary.GetTVShowDetails without tags: %0.3f seconds." % e)

        t = time.time()
        data = utils.xbmcJsonRequest({
            'jsonrpc': '2.0',
            'method': 'VideoLibrary.GetMovieDetails',
            'params': {
                'movieid': 634,
                'properties': ['imdbnumber', 'title', 'year']
            },
            'id': 1
        })
        #data = utils.getMovieDetailsFromXbmc(634, ['imdbnumber', 'title', 'year'])
        e = time.time() - t
        utils.Debug(
            "VideoLibrary.GetMovieDetails without tags: %0.3f seconds." % e)

        t = time.time()
        data = utils.xbmcJsonRequest({
            'jsonrpc': '2.0',
            'method': 'VideoLibrary.GetTVShows',
            'params': {
                'properties': ['title', 'imdbnumber', 'year']
            },
            'id': 0
        })
        data = data['tvshows']
        for item in data:
            item_data = utils.xbmcJsonRequest({
                'jsonrpc': '2.0',
                'method': 'VideoLibrary.GetTVShowDetails',
                'params': {
                    'tvshowid': item['tvshowid'],
                    'properties': ['tag']
                },
                'id': 1
            })
            item['tag'] = item_data['tvshowdetails']['tag']
        e = time.time() - t
        utils.Debug(
            "VideoLibrary.GetTVShows with tags from loop: %0.3f seconds, %d items at %0.5f seconds per item"
            % (e, len(data), e / len(data)))

        t = time.time()
        data = utils.xbmcJsonRequest({
            'jsonrpc': '2.0',
            'method': 'VideoLibrary.GetMovies',
            'params': {
                'properties': ['title', 'imdbnumber', 'year']
            },
            'id': 0
        })
        data = data['movies']
        for item in data:
            item_data = utils.xbmcJsonRequest({
                'jsonrpc': '2.0',
                'method': 'VideoLibrary.GetMovieDetails',
                'params': {
                    'movieid': item['movieid'],
                    'properties': ['tag']
                },
                'id': 1
            })
            item['tag'] = item_data['moviedetails']['tag']
        e = time.time() - t
        utils.Debug(
            "VideoLibrary.GetMovies with tags from: %0.3f seconds, %d items at %0.5f seconds per item."
            % (e, len(data), e / len(data)))

    elif args['action'] in ['itemlists', 'addtolist', 'removefromlist']:
        data = {}
        data['action'] = args['action']
        media_type = None
        dbid = None
        if 'media_type' in args and 'dbid' in args:
            media_type = args['media_type']
            try:
                dbid = int(args['dbid'])
            except ValueError:
                utils.Debug(
                    "'%s' triggered for library item, but DBID is invalid." %
                    args['action'])
                return
        else:
            media_type = getMediaType()
            if not media_type in ['movie', 'show']:
                utils.Debug("Error, not in video library.")
                return
            try:
                dbid = int(xbmc.getInfoLabel('ListItem.DBID'))
            except ValueError:
                utils.Debug(
                    "'%s' triggered for library item, but there is a problem with ListItem.DBID."
                    % args['action'])
                return

        if not media_type in ['movie', 'show']:
            utils.Debug("'%s' is not a valid media type for '%s'." %
                        (media_type, args['action']))
            return

        if args['action'] in ['addtolist', 'removefromlist']:
            if 'list' in args:
                data['list'] = args['list']
            else:
                utils.Debug("'%s' requires a list parameter." % data['action'])

        data['type'] = media_type

        if utils.isMovie(media_type):
            result = utils.getMovieDetailsFromXbmc(
                dbid, ['imdbnumber', 'title', 'year', 'tag'])
            if not result:
                utils.Debug("Error getting movie details from XBMC.")
                return
            data['tag'] = result['tag']
            data['movieid'] = result['movieid']
            data['title'] = result['title']
            data['year'] = result['year']
            if result['imdbnumber'].startswith("tt"):
                data['imdb_id'] = result['imdbnumber']
            elif result['imdbnumber'].isdigit():
                data['tmdb_id'] = result['imdbnumber']

        elif utils.isShow(media_type):
            result = utils.getShowDetailsFromXBMC(
                dbid, ['imdbnumber', 'title', 'tag'])
            if not result:
                utils.Debug("Error getting show details from XBMC.")
                return
            data['tag'] = result['tag']
            data['tvshowid'] = result['tvshowid']
            data['title'] = result['title']
            if result['imdbnumber'].startswith("tt"):
                data['imdb_id'] = result['imdbnumber']
            elif result['imdbnumber'].isdigit():
                data['tvdb_id'] = result['imdbnumber']

    q = queue.SqliteQueue()
    if 'action' in data:
        utils.Debug("Queuing for dispatch: %s" % data)
        q.append(data)
Esempio n. 54
0
    def playbackStarted(self, data):
        logger.debug("playbackStarted(data: %s)" % data)
        if not data:
            return
        self.curVideo = data
        self.curVideoInfo = None
        self.videosToRate = []

        if (
            not utilities.getSettingAsBool("scrobble_fallback")
            and "id" not in self.curVideo
            and "video_ids" not in self.curVideo
        ):
            logger.debug("Aborting scrobble to avoid fallback: %s" % (self.curVideo))
            return

        if "type" in self.curVideo:
            logger.debug("Watching: %s" % self.curVideo["type"])
            if not xbmc.Player().isPlayingVideo():
                logger.debug("Suddenly stopped watching item")
                return
            xbmc.sleep(1000)  # Wait for possible silent seek (caused by resuming)
            try:
                self.watchedTime = xbmc.Player().getTime()
                self.videoDuration = xbmc.Player().getTotalTime()
            except Exception as e:
                logger.debug("Suddenly stopped watching item: %s" % e.message)
                self.curVideo = None
                return

            if self.videoDuration == 0:
                if utilities.isMovie(self.curVideo["type"]):
                    self.videoDuration = 90
                elif utilities.isEpisode(self.curVideo["type"]):
                    self.videoDuration = 30
                else:
                    self.videoDuration = 1

            self.playlistLength = len(xbmc.PlayList(xbmc.PLAYLIST_VIDEO))
            self.playlistIndex = xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition()
            if self.playlistLength == 0:
                logger.debug("Warning: Cant find playlist length, assuming that this item is by itself")
                self.playlistLength = 1

            self.isMultiPartEpisode = False
            if utilities.isMovie(self.curVideo["type"]):
                if "id" in self.curVideo:
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject(
                        "movie",
                        utilities.getMovieDetailsFromKodi(
                            self.curVideo["id"], ["imdbnumber", "title", "year", "file", "lastplayed", "playcount"]
                        ),
                    )
                elif "video_ids" in self.curVideo:
                    self.curVideoInfo = {"ids": self.curVideo["video_ids"]}
                elif "title" in self.curVideo and "year" in self.curVideo:
                    self.curVideoInfo = {"title": self.curVideo["title"], "year": self.curVideo["year"]}

            elif utilities.isEpisode(self.curVideo["type"]):
                if "id" in self.curVideo:
                    episodeDetailsKodi = utilities.getEpisodeDetailsFromKodi(
                        self.curVideo["id"],
                        ["showtitle", "season", "episode", "tvshowid", "uniqueid", "file", "playcount"],
                    )
                    tvdb = episodeDetailsKodi["imdbnumber"]
                    title, year = utilities.regex_year(episodeDetailsKodi["showtitle"])
                    if not year:
                        self.traktShowSummary = {
                            "title": episodeDetailsKodi["showtitle"],
                            "year": episodeDetailsKodi["year"],
                        }
                    else:
                        self.traktShowSummary = {"title": title, "year": year}
                    if tvdb:
                        self.traktShowSummary["ids"] = {"tvdb": tvdb}
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject("episode", episodeDetailsKodi)
                    if not self.curVideoInfo:  # getEpisodeDetailsFromKodi was empty
                        logger.debug(
                            "Episode details from Kodi was empty, ID (%d) seems invalid, aborting further scrobbling of this episode."
                            % self.curVideo["id"]
                        )
                        self.curVideo = None
                        self.isPlaying = False
                        self.watchedTime = 0
                        return
                elif "video_ids" in self.curVideo and "season" in self.curVideo and "episode" in self.curVideo:
                    self.curVideoInfo = {"season": self.curVideo["season"], "number": self.curVideo["episode"]}
                    self.traktShowSummary = {"ids": self.curVideo["video_ids"]}
                elif "title" in self.curVideo and "season" in self.curVideo and "episode" in self.curVideo:
                    self.curVideoInfo = {
                        "title": self.curVideo["title"],
                        "season": self.curVideo["season"],
                        "number": self.curVideo["episode"],
                    }

                    title, year = utilities.regex_year(self.curVideo["showtitle"])
                    if not year:
                        self.traktShowSummary = {"title": self.curVideo["showtitle"]}
                    else:
                        self.traktShowSummary = {"title": title, "year": year}

                    if "year" in self.curVideo:
                        self.traktShowSummary["year"] = self.curVideo["year"]

                if "multi_episode_count" in self.curVideo and self.curVideo["multi_episode_count"] > 1:
                    self.isMultiPartEpisode = True

            self.isPlaying = True
            self.isPaused = False

            result = {}
            if utilities.getSettingAsBool("scrobble_movie") or utilities.getSettingAsBool("scrobble_episode"):
                result = self.__scrobble("start")
            elif (
                utilities.getSettingAsBool("rate_movie")
                and utilities.isMovie(self.curVideo["type"])
                and "ids" in self.curVideoInfo
            ):
                result = {"movie": self.traktapi.getMovieSummary(utilities.best_id(self.curVideoInfo["ids"])).to_dict()}
            elif (
                utilities.getSettingAsBool("rate_episode")
                and utilities.isEpisode(self.curVideo["type"])
                and "ids" in self.traktShowSummary
            ):
                best_id = utilities.best_id(self.traktShowSummary["ids"])
                result = {
                    "show": self.traktapi.getShowSummary(best_id).to_dict(),
                    "episode": self.traktapi.getEpisodeSummary(
                        best_id, self.curVideoInfo["season"], self.curVideoInfo["number"]
                    ).to_dict(),
                }
                result["episode"]["season"] = self.curVideoInfo["season"]

            self.__preFetchUserRatings(result)
Esempio n. 55
0
    def playbackStarted(self, data):
        Debug("[Scrobbler] playbackStarted(data: %s)" % data)
        if not data:
            return
        self.curVideo = data
        self.curVideoInfo = None
        # {"jsonrpc":"2.0","method":"Player.OnPlay","params":{"data":{"item":{"type":"movie"},"player":{"playerid":1,"speed":1},"title":"Shooter","year":2007},"sender":"xbmc"}}
        # {"jsonrpc":"2.0","method":"Player.OnPlay","params":{"data":{"episode":3,"item":{"type":"episode"},"player":{"playerid":1,"speed":1},"season":4,"showtitle":"24","title":"9:00 A.M. - 10:00 A.M."},"sender":"xbmc"}}
        if 'type' in self.curVideo:
            Debug("[Scrobbler] Watching: %s" % self.curVideo['type'])
            if not xbmc.Player().isPlayingVideo():
                Debug("[Scrobbler] Suddenly stopped watching item")
                return
            xbmc.sleep(
                1000)  # Wait for possible silent seek (caused by resuming)
            try:
                self.watchedTime = xbmc.Player().getTime()
                self.videoDuration = xbmc.Player().getTotalTime()
            except Exception, e:
                Debug("[Scrobbler] Suddenly stopped watching item: %s" %
                      e.message)
                self.curVideo = None
                return

            if self.videoDuration == 0:
                if utilities.isMovie(self.curVideo['type']):
                    self.videoDuration = 90
                elif utilities.isEpisode(self.curVideo['type']):
                    self.videoDuration = 30
                else:
                    self.videoDuration = 1

            self.playlistLength = len(xbmc.PlayList(xbmc.PLAYLIST_VIDEO))
            self.playlistIndex = xbmc.PlayList(
                xbmc.PLAYLIST_VIDEO).getposition()
            if (self.playlistLength == 0):
                Debug(
                    "[Scrobbler] Warning: Cant find playlist length, assuming that this item is by itself"
                )
                self.playlistLength = 1

            self.traktSummaryInfo = None
            self.isMultiPartEpisode = False
            if utilities.isMovie(self.curVideo['type']):
                if 'id' in self.curVideo:
                    self.curVideoInfo = utilities.getMovieDetailsFromXbmc(
                        self.curVideo['id'], ['imdbnumber', 'title', 'year'])
                    if utilities.getSettingAsBool('rate_movie'):
                        # pre-get sumamry information, for faster rating dialog.
                        Debug(
                            "[Scrobbler] Movie rating is enabled, pre-fetching summary information."
                        )
                        imdb_id = self.curVideoInfo['imdbnumber']
                        if imdb_id.startswith("tt") or imdb_id.isdigit():
                            self.traktSummaryInfo = self.traktapi.getMovieSummary(
                                self.curVideoInfo['imdbnumber'])
                            self.traktSummaryInfo['xbmc_id'] = self.curVideo[
                                'id']
                        else:
                            self.curVideoInfo['imdbnumber'] = None
                            Debug(
                                "[Scrobbler] Can not get summary information for '%s (%d)' as is has no valid id, will retry during a watching call."
                                % (self.curVideoInfo['title'],
                                   self.curVideoInfo['year']))
                elif 'title' in self.curVideo and 'year' in self.curVideo:
                    self.curVideoInfo = {}
                    self.curVideoInfo['imdbnumber'] = None
                    self.curVideoInfo['title'] = self.curVideo['title']
                    self.curVideoInfo['year'] = self.curVideo['year']

            elif utilities.isEpisode(self.curVideo['type']):
                if 'id' in self.curVideo:
                    self.curVideoInfo = utilities.getEpisodeDetailsFromXbmc(
                        self.curVideo['id'], [
                            'showtitle', 'season', 'episode', 'tvshowid',
                            'uniqueid'
                        ])
                    if not self.curVideoInfo:  # getEpisodeDetailsFromXbmc was empty
                        Debug(
                            "[Scrobbler] Episode details from XBMC was empty, ID (%d) seems invalid, aborting further scrobbling of this episode."
                            % self.curVideo['id'])
                        self.curVideo = None
                        self.isPlaying = False
                        self.watchedTime = 0
                        return
                    if utilities.getSettingAsBool('rate_episode'):
                        # pre-get sumamry information, for faster rating dialog.
                        Debug(
                            "[Scrobbler] Episode rating is enabled, pre-fetching summary information."
                        )
                        tvdb_id = self.curVideoInfo['tvdb_id']
                        if tvdb_id.isdigit() or tvdb_id.startswith("tt"):
                            self.traktSummaryInfo = self.traktapi.getEpisodeSummary(
                                tvdb_id, self.curVideoInfo['season'],
                                self.curVideoInfo['episode'])
                        else:
                            self.curVideoInfo['tvdb_id'] = None
                            Debug(
                                "[Scrobbler] Can not get summary information for '%s - S%02dE%02d' as it has no valid id, will retry during a watching call."
                                % (self.curVideoInfo['showtitle'],
                                   self.curVideoInfo['season'],
                                   self.curVideoInfo['episode']))
                elif 'showtitle' in self.curVideo and 'season' in self.curVideo and 'episode' in self.curVideo:
                    self.curVideoInfo = {}
                    self.curVideoInfo['tvdb_id'] = None
                    self.curVideoInfo['year'] = None
                    if 'year' in self.curVideo:
                        self.curVideoInfo['year'] = self.curVideo['year']
                    self.curVideoInfo['showtitle'] = self.curVideo['showtitle']
                    self.curVideoInfo['season'] = self.curVideo['season']
                    self.curVideoInfo['episode'] = self.curVideo['episode']

                if 'multi_episode_count' in self.curVideo:
                    self.isMultiPartEpisode = True
                    self.markedAsWatched = []
                    episode_count = self.curVideo['multi_episode_count']
                    for i in range(episode_count):
                        self.markedAsWatched.append(False)

            self.isPlaying = True
            self.isPaused = False
            self.scrobble('start')
Esempio n. 56
0
def rateOnTrakt(rating, media_type, media, unrate=False):
	utils.Debug("[Rating] Sending rating (%s) to trakt.tv" % rating)

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

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

		data = globals.traktapi.rateMovie(params)

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

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

		data = globals.traktapi.rateEpisode(params)

	else:
		return

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

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

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

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

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

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

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

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

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

			if not unrate:
				utils.notification(utils.getString(1350), s)
			else:
				utils.notification(utils.getString(1352), s)
		elif 'status' in data and data['status'] == "failure":
			utils.notification(utils.getString(1354), s)
		else:
			# status not in data, different problem, do nothing for now
			pass
Esempio n. 57
0
    def playbackStarted(self, data):
        Debug("[Scrobbler] playbackStarted(data: %s)" % data)
        if not data:
            return
        self.curVideo = data
        self.curVideoInfo = None

        if 'type' in self.curVideo:
            Debug("[Scrobbler] Watching: %s" % self.curVideo['type'])
            if not xbmc.Player().isPlayingVideo():
                Debug("[Scrobbler] Suddenly stopped watching item")
                return
            xbmc.sleep(
                1000)  # Wait for possible silent seek (caused by resuming)
            try:
                self.watchedTime = xbmc.Player().getTime()
                self.videoDuration = xbmc.Player().getTotalTime()
            except Exception as e:
                Debug("[Scrobbler] Suddenly stopped watching item: %s" %
                      e.message)
                self.curVideo = None
                return

            if self.videoDuration == 0:
                if utilities.isMovie(self.curVideo['type']):
                    self.videoDuration = 90
                elif utilities.isEpisode(self.curVideo['type']):
                    self.videoDuration = 30
                else:
                    self.videoDuration = 1

            self.playlistLength = len(xbmc.PlayList(xbmc.PLAYLIST_VIDEO))
            self.playlistIndex = xbmc.PlayList(
                xbmc.PLAYLIST_VIDEO).getposition()
            if (self.playlistLength == 0):
                Debug(
                    "[Scrobbler] Warning: Cant find playlist length, assuming that this item is by itself"
                )
                self.playlistLength = 1

            self.traktSummaryInfo = None
            self.isMultiPartEpisode = False
            if utilities.isMovie(self.curVideo['type']):
                if 'id' in self.curVideo:
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject(
                        'movie',
                        utilities.getMovieDetailsFromKodi(
                            self.curVideo['id'], [
                                'imdbnumber', 'title', 'year', 'file',
                                'lastplayed', 'playcount'
                            ]))
                    Debug("Trakt ticket: %s" % self.curVideo)
                    if utilities.getSettingAsBool('rate_movie'):
                        # pre-get sumamry information, for faster rating dialog.
                        Debug(
                            "[Scrobbler] Movie rating is enabled, pre-fetching summary information."
                        )
                        if self.curVideoInfo['ids']['imdb']:
                            self.traktSummaryInfo = self.traktapi.getMovieSummary(
                                self.curVideoInfo['ids']['imdb'])
                        elif self.curVideoInfo['ids']['tmdb']:
                            self.traktSummaryInfo = self.traktapi.getMovieSummary(
                                self.curVideoInfo['ids']['tmdb'])
                        else:
                            self.curVideoInfo['ids']['imdb'] = None
                            Debug(
                                "[Scrobbler] Can not get summary information for '%s (%d)' as is has no valid id, will retry during a watching call."
                                % (self.curVideoInfo['title'],
                                   self.curVideoInfo['year']))
                elif 'title' in self.curVideo and 'year' in self.curVideo:
                    self.curVideoInfo = {'ids': {}}
                    self.curVideoInfo['ids']['imdb'] = None
                    self.curVideoInfo['title'] = self.curVideo['title']
                    self.curVideoInfo['year'] = self.curVideo['year']

            elif utilities.isEpisode(self.curVideo['type']):
                if 'id' in self.curVideo:
                    episodeDetailsKodi = utilities.getEpisodeDetailsFromKodi(
                        self.curVideo['id'], [
                            'showtitle', 'season', 'episode', 'tvshowid',
                            'uniqueid', 'file', 'playcount'
                        ])
                    tvdb = episodeDetailsKodi['imdbnumber']
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject(
                        'episode', episodeDetailsKodi)
                    if not self.curVideoInfo:  # getEpisodeDetailsFromKodi was empty
                        Debug(
                            "[Scrobbler] Episode details from Kodi was empty, ID (%d) seems invalid, aborting further scrobbling of this episode."
                            % self.curVideo['id'])
                        self.curVideo = None
                        self.isPlaying = False
                        self.watchedTime = 0
                        return
                    if utilities.getSettingAsBool('rate_episode'):
                        # pre-get sumamry information, for faster rating dialog.
                        Debug(
                            "[Scrobbler] Episode rating is enabled, pre-fetching summary information."
                        )

                        if tvdb:
                            lookupShow = self.traktapi.getIdLookup(
                                'tvdb', tvdb)
                            self.traktShowSummary = self.traktapi.getShowSummary(
                                lookupShow['ids']['slug'])
                            self.traktSummaryInfo = self.traktapi.getEpisodeSummary(
                                lookupShow['ids'], self.curVideoInfo['season'],
                                self.curVideoInfo['number'])
                        else:
                            Debug(
                                "[Scrobbler] Can not get summary information for '%s - S%02dE%02d' as it has no valid id, will retry during a watching call."
                                % (self.curVideoInfo['showtitle'],
                                   self.curVideoInfo['season'],
                                   self.curVideoInfo['episode']))
                    else:
                        self.traktShowSummary = {
                            'title': episodeDetailsKodi['showtitle']
                        }
                        self.traktShowSummary['ids'] = {'tvdb': tvdb}
                elif 'title' in self.curVideo and 'season' in self.curVideo and 'episode' in self.curVideo:
                    self.curVideoInfo = {'tvdb_id': None}
                    self.curVideoInfo['title'] = self.curVideo['title']
                    self.curVideoInfo['season'] = self.curVideo['season']
                    self.curVideoInfo['number'] = self.curVideo['episode']

                    self.traktShowSummary = {
                        'title': self.curVideo['showtitle']
                    }
                    if 'year' in self.curVideo:
                        self.traktShowSummary['year'] = self.curVideo['year']

                if 'multi_episode_count' in self.curVideo:
                    self.isMultiPartEpisode = True
                    self.markedAsWatched = []
                    episode_count = self.curVideo['multi_episode_count']
                    for i in range(episode_count):
                        self.markedAsWatched.append(False)

            self.isPlaying = True
            self.isPaused = False
            self.__scrobble('start')
Esempio n. 58
0
    def doMarkWatched(self, data):

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

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

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

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

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

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

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

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

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

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