示例#1
0
    def __scrobbleNotification(self, info):
        if not self.curVideoInfo:
            return

        if kodiUtilities.getSettingAsBool("scrobble_notification"):
            s = utilities.getFormattedItemName(self.curVideo['type'], info[self.curVideo['type']])
            kodiUtilities.notification(kodiUtilities.getString(32015), s)
示例#2
0
    def __init__(self, sync, progress):
        self.sync = sync
        if not self.sync.show_progress and sync.sync_on_update and sync.notify and self.sync.notify_during_playback:
            kodiUtilities.notification(
                '%s %s' % (kodiUtilities.getString(32045),
                           kodiUtilities.getString(32046)),
                kodiUtilities.getString(32061))  # Sync started
        if sync.show_progress and not sync.run_silent:
            progress.create(
                "%s %s" % (kodiUtilities.getString(32045),
                           kodiUtilities.getString(32046)), "")

        kodiMovies = self.__kodiLoadMovies()
        if not isinstance(kodiMovies, list) and not kodiMovies:
            logger.debug(
                "[Movies Sync] Kodi movie list is empty, aborting movie Sync.")
            if sync.show_progress and not sync.run_silent:
                progress.close()
            return
        try:
            traktMovies = self.__traktLoadMovies()
        except Exception:
            logger.debug(
                "[Movies Sync] Error getting Trakt.tv movie list, aborting movie Sync."
            )
            if sync.show_progress and not sync.run_silent:
                progress.close()
            return

        traktMoviesProgress = self.__traktLoadMoviesPlaybackProgress(25, 36)

        self.__addMoviesToTraktCollection(kodiMovies, traktMovies, 37, 47)

        self.__deleteMoviesFromTraktCollection(traktMovies, kodiMovies, 48, 58)

        self.__addMoviesToTraktWatched(kodiMovies, traktMovies, 59, 69)

        self.__addMoviesToKodiWatched(traktMovies, kodiMovies, 70, 80)

        self.__addMovieProgressToKodi(traktMoviesProgress, kodiMovies, 81, 91)

        self.__syncMovieRatings(traktMovies, kodiMovies, 92, 99)

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

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

        logger.debug(
            "[Movies Sync] Movies on Trakt.tv (%d), movies in Kodi (%d)." %
            (len(traktMovies), len(kodiMovies)))
        logger.debug("[Movies Sync] Complete.")
示例#3
0
 def __get_settings(self):
     """get users settings and launch actions"""
     logger.debug("reading settings")
     self.service = globals.Service(
         getSettingAsBool("betaactive"),
         getSettingAsBool("betafirst"),
         getSetting("betauser"),
         getSetting("betapass"),
         getSettingAsBool("betabulk"),
         getSettingAsBool("betamark"),
         getSettingAsBool("betaunmark"),
         getSettingAsBool("betafollow"),
         getSettingAsBool("betanotify"),
         getSettingAsBool("betaupdate"),
     )
     if self.service.active and self.service.user and self.service.password:
         globals.betaseriesapi = ServiceApi(self)
         globals.betaseriesapi._service_authenticate(
             self.service.user, self.service.password
         )
         self.Player = MyPlayer(
             action=globals.betaseriesapi._service_betaserie, service=self.service
         )
         if self.service.notify:
             notification(getString(32010), getString(30003))
示例#4
0
    def login(self):
        # Request new device code
        with Trakt.configuration.http(timeout=90):
            code = Trakt['oauth/device'].code()

            if not code:
                logger.debug('Error can not reach trakt')
                notification(getString(32024), getString(32023))
            else:
                # Construct device authentication poller
                poller = Trakt['oauth/device'].poll(**code)\
                    .on('aborted', self.on_aborted)\
                    .on('authenticated', self.on_authenticated)\
                    .on('expired', self.on_expired)\
                    .on('poll', self.on_poll)

                # Start polling for authentication token
                poller.start(daemon=False)

                logger.debug(
                    'Enter the code "%s" at %s to authenticate your account' %
                    (code.get('user_code'), code.get('verification_url')))

                self.authDialog = deviceAuthDialog.DeviceAuthDialog(
                    'script-trakt-DeviceAuthDialog.xml',
                    __addon__.getAddonInfo('path'),
                    code=code.get('user_code'),
                    url=code.get('verification_url'))
                self.authDialog.doModal()

                del self.authDialog
示例#5
0
    def __scrobbleNotification(self, info):
        if not self.curVideoInfo:
            return

        if kodiUtilities.getSettingAsBool("scrobble_notification"):
            s = utilities.getFormattedItemName(self.curVideo['type'], info[self.curVideo['type']])
            kodiUtilities.notification(kodiUtilities.getString(32015), s)
示例#6
0
    def login(self):
        # Request new device code
        with Trakt.configuration.http(timeout=90):
            code = Trakt['oauth/device'].code()

            if not code:
                logger.debug('Error can not reach trakt')
                notification(getString(32024), getString(32023))
            else:
                # Construct device authentication poller
                poller = Trakt['oauth/device'].poll(**code)\
                    .on('aborted', self.on_aborted)\
                    .on('authenticated', self.on_authenticated)\
                    .on('expired', self.on_expired)\
                    .on('poll', self.on_poll)

                # Start polling for authentication token
                poller.start(daemon=False)

                logger.debug('Enter the code "%s" at %s to authenticate your account' % (
                    code.get('user_code'),
                    code.get('verification_url')
                ))

                self.authDialog = deviceAuthDialog.DeviceAuthDialog('script-trakt-DeviceAuthDialog.xml', __addon__.getAddonInfo('path'),
                                                                    code=code.get('user_code'), url=code.get('verification_url'))
                self.authDialog.doModal()

                del self.authDialog
示例#7
0
    def __init__(self, sync, progress):
        self.sync = sync
        if not self.sync.show_progress and self.sync.sync_on_update and self.sync.notify and self.sync.notify_during_playback:
            kodiUtilities.notification('%s %s' % (kodiUtilities.getString(32045), kodiUtilities.getString(32050)), kodiUtilities.getString(32061))  # Sync started
        if self.sync.show_progress and not self.sync.run_silent:
            progress.create("%s %s" % (kodiUtilities.getString(32045), kodiUtilities.getString(32050)), line1=" ", line2=" ", line3=" ")

        kodiShowsCollected, kodiShowsWatched = self.__kodiLoadShows()
        if not isinstance(kodiShowsCollected, list) and not kodiShowsCollected:
            logger.debug("[Episodes Sync] Kodi collected show list is empty, aborting tv show Sync.")
            if self.sync.show_progress and not self.sync.run_silent:
                progress.close()
            return
        if not isinstance(kodiShowsWatched, list) and not kodiShowsWatched:
            logger.debug("[Episodes Sync] Kodi watched show list is empty, aborting tv show Sync.")
            if self.sync.show_progress and not self.sync.run_silent:
                progress.close()
            return

        traktShowsCollected, traktShowsWatched, traktShowsRated, traktEpisodesRated = self.__traktLoadShows()
        if not traktShowsCollected:
            logger.debug("[Episodes Sync] Error getting Trakt.tv collected show list, aborting tv show sync.")
            if self.sync.show_progress and not self.sync.run_silent:
                progress.close()
            return
        if not traktShowsWatched:
            logger.debug("[Episodes Sync] Error getting Trakt.tv watched show list, aborting tv show sync.")
            if self.sync.show_progress and not self.sync.run_silent:
                progress.close()
            return

        traktShowsProgress = self.__traktLoadShowsPlaybackProgress(25, 36)

        self.__addEpisodesToTraktCollection(kodiShowsCollected, traktShowsCollected, 37, 47)

        self.__deleteEpisodesFromTraktCollection(traktShowsCollected, kodiShowsCollected, 48, 58)

        self.__addEpisodesToTraktWatched(kodiShowsWatched, traktShowsWatched, 59, 69)

        self.__addEpisodesToKodiWatched(traktShowsWatched, kodiShowsWatched, kodiShowsCollected, 70, 80)

        self.__addEpisodeProgressToKodi(traktShowsProgress, kodiShowsCollected, 81, 91)

        self.__syncShowsRatings(traktShowsRated, kodiShowsCollected, 92, 95)
        self.__syncEpisodeRatings(traktEpisodesRated, kodiShowsCollected, 96, 99)

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

        if self.sync.show_progress and not self.sync.run_silent:
            self.sync.UpdateProgress(100, line1=" ", line2=kodiUtilities.getString(32075), line3=" ")
            progress.close()

        logger.debug("[Episodes Sync] Shows on Trakt.tv (%d), shows in Kodi (%d)." % (len(traktShowsCollected['shows']), len(kodiShowsCollected['shows'])))

        logger.debug("[Episodes Sync] Episodes on Trakt.tv (%d), episodes in Kodi (%d)." % (utilities.countEpisodes(traktShowsCollected), utilities.countEpisodes(kodiShowsCollected)))
        logger.debug("[Episodes Sync] Complete.")
示例#8
0
    def __init__(self, sync, progress):
        self.sync = sync
        if not self.sync.show_progress and self.sync.sync_on_update and self.sync.notify and self.sync.notify_during_playback:
            kodiUtilities.notification('%s %s' % (kodiUtilities.getString(32045), kodiUtilities.getString(32050)), kodiUtilities.getString(32061))  # Sync started
        if self.sync.show_progress and not self.sync.run_silent:
            progress.create("%s %s" % (kodiUtilities.getString(32045), kodiUtilities.getString(32050)), line1=" ", line2=" ", line3=" ")

        kodiShowsCollected, kodiShowsWatched = self.__kodiLoadShows()
        if not isinstance(kodiShowsCollected, list) and not kodiShowsCollected:
            logger.debug("[Episodes Sync] Kodi collected show list is empty, aborting tv show Sync.")
            if self.sync.show_progress and not self.sync.run_silent:
                progress.close()
            return
        if not isinstance(kodiShowsWatched, list) and not kodiShowsWatched:
            logger.debug("[Episodes Sync] Kodi watched show list is empty, aborting tv show Sync.")
            if self.sync.show_progress and not self.sync.run_silent:
                progress.close()
            return

        traktShowsCollected, traktShowsWatched, traktShowsRated, traktEpisodesRated = self.__traktLoadShows()
        if not traktShowsCollected:
            logger.debug("[Episodes Sync] Error getting Trakt.tv collected show list, aborting tv show sync.")
            if self.sync.show_progress and not self.sync.run_silent:
                progress.close()
            return
        if not traktShowsWatched:
            logger.debug("[Episodes Sync] Error getting Trakt.tv watched show list, aborting tv show sync.")
            if self.sync.show_progress and not self.sync.run_silent:
                progress.close()
            return

        traktShowsProgress = self.__traktLoadShowsPlaybackProgress(25, 36)

        self.__addEpisodesToTraktCollection(kodiShowsCollected, traktShowsCollected, 37, 47)

        self.__deleteEpisodesFromTraktCollection(traktShowsCollected, kodiShowsCollected, 48, 58)

        self.__addEpisodesToTraktWatched(kodiShowsWatched, traktShowsWatched, 59, 69)

        self.__addEpisodesToKodiWatched(traktShowsWatched, kodiShowsWatched, kodiShowsCollected, 70, 80)

        self.__addEpisodeProgressToKodi(traktShowsProgress, kodiShowsCollected, 81, 91)

        self.__syncShowsRatings(traktShowsRated, kodiShowsCollected, 92, 95)
        self.__syncEpisodeRatings(traktEpisodesRated, kodiShowsCollected, 96, 99)

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

        if self.sync.show_progress and not self.sync.run_silent:
            self.sync.UpdateProgress(100, line1=" ", line2=kodiUtilities.getString(32075), line3=" ")
            progress.close()

        logger.debug("[Episodes Sync] Shows on Trakt.tv (%d), shows in Kodi (%d)." % (len(traktShowsCollected['shows']), len(kodiShowsCollected['shows'])))

        logger.debug("[Episodes Sync] Episodes on Trakt.tv (%d), episodes in Kodi (%d)." % (self.__countEpisodes(traktShowsCollected), self.__countEpisodes(kodiShowsCollected)))
        logger.debug("[Episodes Sync] Complete.")
示例#9
0
    def addEpisodesToHistory(self, summaryInfo, s):
        if len(summaryInfo['shows'][0]['seasons'][0]['episodes']) > 0:
            logger.debug("doMarkWatched(): %s" % str(summaryInfo))

            result = globals.traktapi.addToHistory(summaryInfo)
            if result:
                kodiUtilities.notification(kodiUtilities.getString(32113), kodiUtilities.getString(32115) % (result['added']['episodes'], s))
            else:
                kodiUtilities.notification(kodiUtilities.getString(32114), s)
示例#10
0
    def addEpisodesToHistory(self, summaryInfo, s):
        if len(summaryInfo['shows'][0]['seasons'][0]['episodes']) > 0:
            logger.debug("doMarkWatched(): %s" % str(summaryInfo))

            result = globals.traktapi.addToHistory(summaryInfo)
            if result:
                kodiUtilities.notification(kodiUtilities.getString(
                    32113), kodiUtilities.getString(32115) % (result['added']['episodes'], s))
            else:
                kodiUtilities.notification(kodiUtilities.getString(32114), s)
示例#11
0
    def on_authenticated(self, token):
        """Triggered when device authentication has been completed

        :param token: Authentication token details
        :type token: dict
        """
        self.authorization = token
        setSetting('authorization', dumps(self.authorization))
        logger.debug('Authentication complete: %r' % token)
        self.authDialog.close()
        notification(getString(32157), getString(32152), 3000)
        self.updateUser()
示例#12
0
    def on_authenticated(self, token):
        """Triggered when device authentication has been completed

        :param token: Authentication token details
        :type token: dict
        """
        self.authorization = token
        setSetting('authorization', dumps(self.authorization))
        logger.debug('Authentication complete: %r' % token)
        self.authDialog.close()
        notification(getString(32157), getString(32152), 3000)
        self.updateUser()
示例#13
0
    def onClick(self, control):
        logger.debug('onClick: %s' % (control))

        if control == LATER_BUTTON:
            notification(getString(32157), getString(32150), 5000)
            setSetting('last_reminder', str(int(time.time())))

        if control == NEVER_BUTTON:
            notification(getString(32157), getString(32151), 5000)
            setSetting('last_reminder', '-1')

        if control in [LATER_BUTTON, NEVER_BUTTON]:
            self.close()
示例#14
0
    def onClick(self, control):
        logger.debug('onClick: %s' % (control))

        if control == LATER_BUTTON:
            notification(getString(32157), getString(32150), 5000)
            setSetting('last_reminder', str(int(time.time())))

        if control == NEVER_BUTTON:
            notification(getString(32157), getString(32151), 5000)
            setSetting('last_reminder', '-1')

        if control in [LATER_BUTTON, NEVER_BUTTON]:
            self.close()
示例#15
0
    def __init__(self, sync, progress):
        self.sync = sync
        if not self.sync.show_progress and sync.sync_on_update and sync.notify and self.sync.notify_during_playback:
            kodiUtilities.notification('%s %s' % (kodiUtilities.getString(32045), kodiUtilities.getString(32046)), kodiUtilities.getString(32061))  # Sync started
        if sync.show_progress and not sync.run_silent:
            progress.create("%s %s" % (kodiUtilities.getString(32045), kodiUtilities.getString(32046)), line1=" ", line2=" ", line3=" ")

        kodiMovies = self.__kodiLoadMovies()
        if not isinstance(kodiMovies, list) and not kodiMovies:
            logger.debug("[Movies Sync] Kodi movie list is empty, aborting movie Sync.")
            if sync.show_progress and not sync.run_silent:
                progress.close()
            return
        try:
            traktMovies = self.__traktLoadMovies()
        except Exception:
            logger.debug("[Movies Sync] Error getting Trakt.tv movie list, aborting movie Sync.")
            if sync.show_progress and not sync.run_silent:
                progress.close()
            return

        traktMoviesProgress = self.__traktLoadMoviesPlaybackProgress(25, 36)

        self.__addMoviesToTraktCollection(kodiMovies, traktMovies, 37, 47)

        self.__deleteMoviesFromTraktCollection(traktMovies, kodiMovies, 48, 58)

        self.__addMoviesToTraktWatched(kodiMovies, traktMovies, 59, 69)

        self.__addMoviesToKodiWatched(traktMovies, kodiMovies, 70, 80)

        self.__addMovieProgressToKodi(traktMoviesProgress, kodiMovies, 81, 91)

        self.__syncMovieRatings(traktMovies, kodiMovies, 92, 99)

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

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

        logger.debug("[Movies Sync] Movies on Trakt.tv (%d), movies in Kodi (%d)." % (len(traktMovies), len(kodiMovies)))
        logger.debug("[Movies Sync] Complete.")
示例#16
0
    def _service_authenticate(self, user=None, pw=None):
        """authenticate if necessary into betaseries.com

        Args:
            user ([str], optional): username. Defaults to None.
            pw ([str], optional): password. Defaults to None.
        """
        if user:
            self.user = user
        if pw:
            self.pw = pw
        # don't proceed if timeout timer has not expired
        if self.timerexpiretime > int(time.time()):
            return
        if self.__auth():
            logger.info("successfully authenticated")
        else:
            notification(getString(32010), getString(32003))
            logger.error("failed to connect for authentication")
示例#17
0
    def __auth(self):
        """low level Authenticate into betaseries.com

        Returns:
            True or None
        """
        # create a pass hash
        md5pass = hashlib.md5()
        md5pass.update(self.pw.encode("utf8"))
        url = self.apiurl + "/members/auth"
        urldata = {
            "v": self.apiver,
            "key": self.apikey,
            "login": self.user,
            "password": md5pass.hexdigest(),
        }
        try:
            # authentication request
            response = utilities.get_urldata(url, urldata, "POST")
            # authentication response
            data = json.loads(response)
            logger.info("successfully authenticated")
        except Exception:
            logger.error("failed to connect for authentication")
            return None

        # parse results
        if "token" in data:
            # get token
            self.token = str(data["token"])
            # reset failure count
            self.failurecount = 0
            # reset timer
            self.timercounter = 0
            self.timerexpiretime = 0
        if data["errors"]:
            self.__checkerrors(data["errors"][0], auth=True)
            return None
        else:
            logger.debug("token find:" + self.token)
            notification(getString(32010), getString(32008))
            return True
示例#18
0
    def __checkerrors(self, error, auth=False, infos=""):
        """treatment about error returned by betaseries API

        Args:
            error (dict): error returned by API
            auth (bool, optional): error occured during authentication process. Defaults to False.
            infos (str, optional): text to add to message. Defaults to "".
        Returns:
            True on real error
            False on non real error (informations returned by API with 0 code)
        """
        if auth is False and error["code"] == 0:
            return False
        if error["code"] < 2000:
            # API error
            notification(getString(32010), getString(32002))
            logger.warning(
                f"bad API usage : [{error['code']}] - {error['text']}")
            # disable the service, the monitor class will pick up the changes
            # setSetting("betaactive", "false")
        elif error["code"] > 4001:
            # login error
            notification(getString(32010), getString(32004))
            logger.warning("login or password incorrect")
            self.auth_fail = True
        elif error["code"] == 2001:
            # drop our session key
            self.token = ""
            logger.info("bad token")
            return True
        elif error["code"] == 2003:
            logger.info(f"already following show {infos}")
        # everything else
        elif auth is True:
            self.__service_fail(True)
            notification(getString(32010), getString(32001))
            logger.error("server error while authenticating")
            notification(getString(32010), getString(32009))
        else:
            notification(getString(32010), getString(32005, infos))
            logger.info(f"failed to follow show {infos}")
        return True
示例#19
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)
示例#20
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'
        # we need to remove this key or trakt will be confused
        del(params["seasons"])
        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)
示例#21
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)
示例#22
0
    def ScanBSMarkedEpisode(self):
        """Do self.action on recently added media in kodi based on lastdate treatment"""
        f = __addon__.getAddonInfo("path") + "/lastdate.tmp"
        try:
            with open(f, "r") as fic:
                lastdate = fic.read()
        except Exception:
            lastdate = "2001-01-01 00:00:00"
        newdate = lastdate
        new = False
        counter = 0
        # cree table de tous les episodes
        result_episodes = kodiUtilities.getEpisodesFromKodi()

        if "episodes" in result_episodes:
            logger.debug(
                "Start scanning BS for viewed episode and compare with Kodi database"
            )
            for media in result_episodes["episodes"]:
                # web_pdb.set_trace()
                ep_id = media["episodeid"]
                seen = False
                try:
                    tvshow = kodiUtilities.getEpisodeDetailsFromKodi(
                        ep_id, ["dateadded", "playcount"])
                    if tvshow["playcount"] > 0:
                        seen = True
                except Exception as e:
                    logger.error(
                        f"getEpisodeDetailsFromKodi error for {ep_id} : {e}")
                    # passe au suivant si erreur
                    continue

                if tvshow["dateadded"] > lastdate:
                    new = True
                    if tvshow["dateadded"] > newdate:
                        newdate = tvshow["dateadded"]
                # 0101 voir pour l'interet de not seen
                if new:  # or not seen:
                    # si pas vu, regarder sur BS si marque

                    episode = Media(ep_id, -1,
                                    self.Play).get_media_info("episode")
                    if episode:
                        if seen:
                            episode["playcount"] = 1
                        # follow ?    # downloaded ?
                        if not episode["followed"] or not episode["downloaded"]:
                            self.action(episode, self.service)
                        if episode["tvshow_playcount"] < 1 and episode["seen"]:
                            result = kodiUtilities.setEpisodeDetailsOnKodi(
                                ep_id, {"playcount": 1})
                            logger.info(
                                f"info :{episode['showtitle']},{episode['title']}"
                            )
                            if result == "OK":
                                # logger.info(result,)
                                logger.info(
                                    "episode marked watched or downloaded on BetaSeries.com",
                                )
                                counter += 1
                            else:
                                logger.error(
                                    "error: failed to mark watched or downloaded on Betaseries.com",
                                )
            if counter > 0:
                notification(getString(32010), getString(30021, str(counter)))
            else:
                logger.info("Scan finished, all episodes updated")
            with open(f, "w") as fic:
                fic.write(newdate)
示例#23
0
def rateMedia(media_type, itemsToRate, unrate=False, rating=None):
    """Launches the rating dialog"""
    for summary_info in itemsToRate:
        if not utilities.isValidMediaType(media_type):
            logger.debug("Not a valid media type")
            return
        elif 'user' not in summary_info:
            logger.debug("No user data")
            return

        s = utilities.getFormattedItemName(media_type, summary_info)

        logger.debug("Summary Info %s" % summary_info)

        if unrate:
            rating = None

            if summary_info['user']['ratings']['rating'] > 0:
                rating = 0

            if not rating is None:
                logger.debug("'%s' is being unrated." % s)
                __rateOnTrakt(rating, media_type, summary_info, unrate=True)
            else:
                logger.debug("'%s' has not been rated, so not unrating." % s)

            return

        rerate = kodiUtilities.getSettingAsBool('rate_rerate')
        if rating is not None:
            if summary_info['user']['ratings']['rating'] == 0:
                logger.debug("Rating for '%s' is being set to '%d' manually." % (s, rating))
                __rateOnTrakt(rating, media_type, summary_info)
            else:
                if rerate:
                    if not summary_info['user']['ratings']['rating'] == rating:
                        logger.debug("Rating for '%s' is being set to '%d' manually." % (s, rating))
                        __rateOnTrakt(rating, media_type, summary_info)
                    else:
                        kodiUtilities.notification(kodiUtilities.getString(32043), s)
                        logger.debug("'%s' already has a rating of '%d'." % (s, rating))
                else:
                    kodiUtilities.notification(kodiUtilities.getString(32041), s)
                    logger.debug("'%s' is already rated." % s)
            return

        if summary_info['user']['ratings'] and summary_info['user']['ratings']['rating']:
            if not rerate:
                logger.debug("'%s' has already been rated." % s)
                kodiUtilities.notification(kodiUtilities.getString(32041), s)
                return
            else:
                logger.debug("'%s' is being re-rated." % s)

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

        gui.doModal()
        if gui.rating:
            rating = gui.rating
            if rerate:
                rating = gui.rating

                if summary_info['user']['ratings'] and summary_info['user']['ratings']['rating'] > 0 and rating == summary_info['user']['ratings']['rating']:
                    rating = 0

            if rating == 0 or rating == "unrate":
                __rateOnTrakt(rating, gui.media_type, gui.media, unrate=True)
            else:
                __rateOnTrakt(rating, gui.media_type, gui.media)
        else:
            logger.debug("Rating dialog was closed with no rating.")

        del gui
        #Reset rating and unrate for multi part episodes
        unrate=False
        rating=None
示例#24
0
    def _service_mark(self, episode, service):
        # abort if betamark = false and playcount > 0 and play = false
        if not service.mark and episode["playcount"] > 0 and not episode[
                "playstatus"]:
            logger.info(f"abort marking, as play = {episode['playstatus']}")
            return
        # abort if betaunmark = false and playcount = 0 and play = false
        elif (not service.unMark and episode["playcount"] == 0
              and not episode["playstatus"]):
            logger.info(f"abort unmarking, as play = {episode['playstatus']}")
            return
        if utilities.isEpisode(episode["type"]):
            # follow show if BetaFollow = true
            # if service.follow and episode["playcount"] != -1:
            if service.follow and not episode["followed"]:
                url = self.apiurl + "/shows/show"
                urldata = {
                    "v": self.apiver,
                    "key": self.apikey,
                    "token": self.token,
                    "thetvdb_id": episode["int_id"],
                }
                try:
                    # marking request
                    response = utilities.get_urldata(url, urldata, "POST")
                    # marking response
                    data = json.loads(response)
                except Exception:
                    self.__service_fail(False)
                    logger.info(
                        f"failed to follow TV show {episode['showtitle']}")
                # parse results
                if data["errors"]:
                    if self.__checkerrors(data["errors"][0],
                                          infos=episode["showtitle"]):
                        return None

                if service.notify:
                    notification(getString(32010),
                                 getString(30013, episode["showtitle"]))
                logger.info(f"now following show {episode['showtitle']}")
        if utilities.isMovie(episode["type"]):
            # mark movie as watched
            url = self.apiurl + "/movies/movie"
            urldata = {
                "v": self.apiver,
                "key": self.apikey,
                "token": self.token,
                "id": episode["int_id"],
                "state": episode["playcount"],
            }
            method = "POST"
            if episode["playcount"] == 0:
                act = "not watched"
                actlang = 30017
            else:
                act = "watched"
                actlang = 30016
        elif utilities.isEpisode(episode["type"]):
            # mark episode as watched, unwatched or downloaded
            urldata = {
                "v": self.apiver,
                "key": self.apikey,
                "token": self.token,
                "thetvdb_id": episode["remote_id"],
            }
            if service.bulk:
                urldata.update({"bulk": 1})
            if episode["playcount"] == 0:
                url = self.apiurl + "/episodes/watched"
                method = "DELETE"
                act = "not watched"
                actlang = 30015
            elif episode["playcount"] == -1:
                url = self.apiurl + "/episodes/downloaded"
                method = "POST"
                act = "downloaded"
                actlang = 30101
            else:
                url = self.apiurl + "/episodes/watched"
                method = "POST"
                act = "watched"
                actlang = 30014
        try:
            # marking request
            response = utilities.get_urldata(url, urldata, method)
            # marking response
            data = json.loads(response)
        except Exception:
            self.__service_fail(False)
            logger.warning(f"failed to mark as {act}")
            return
        # parse results
        if data["errors"]:
            if self.__checkerrors(data["errors"][0],
                                  infos=episode["type"] + episode["title"]):
                return None

        if service.notify:
            notification(getString(32010), getString(actlang))
        logger.info(
            f"{episode['showtitle']} {episode['title']} marked as {act}")
        return None
示例#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)
示例#26
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)
示例#27
0
def rateMedia(media_type, itemsToRate, unrate=False, rating=None):
    """Launches the rating dialog"""
    for summary_info in itemsToRate:
        if not utilities.isValidMediaType(media_type):
            logger.debug("Not a valid media type")
            return
        elif 'user' not in summary_info:
            logger.debug("No user data")
            return

        s = utilities.getFormattedItemName(media_type, summary_info)

        logger.debug("Summary Info %s" % summary_info)

        if unrate:
            rating = None

            if summary_info['user']['ratings']['rating'] > 0:
                rating = 0

            if not rating is None:
                logger.debug("'%s' is being unrated." % s)
                __rateOnTrakt(rating, media_type, summary_info, unrate=True)
            else:
                logger.debug("'%s' has not been rated, so not unrating." % s)

            return

        rerate = kodiUtilities.getSettingAsBool('rate_rerate')
        if rating is not None:
            if summary_info['user']['ratings']['rating'] == 0:
                logger.debug("Rating for '%s' is being set to '%d' manually." %
                             (s, rating))
                __rateOnTrakt(rating, media_type, summary_info)
            else:
                if rerate:
                    if not summary_info['user']['ratings']['rating'] == rating:
                        logger.debug(
                            "Rating for '%s' is being set to '%d' manually." %
                            (s, rating))
                        __rateOnTrakt(rating, media_type, summary_info)
                    else:
                        kodiUtilities.notification(
                            kodiUtilities.getString(32043), s)
                        logger.debug("'%s' already has a rating of '%d'." %
                                     (s, rating))
                else:
                    kodiUtilities.notification(kodiUtilities.getString(32041),
                                               s)
                    logger.debug("'%s' is already rated." % s)
            return

        if summary_info['user']['ratings'] and summary_info['user']['ratings'][
                'rating']:
            if not rerate:
                logger.debug("'%s' has already been rated." % s)
                kodiUtilities.notification(kodiUtilities.getString(32041), s)
                return
            else:
                logger.debug("'%s' is being re-rated." % s)

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

        gui.doModal()
        if gui.rating:
            rating = gui.rating
            if rerate:
                rating = gui.rating

                if summary_info['user']['ratings'] and summary_info['user'][
                        'ratings']['rating'] > 0 and rating == summary_info[
                            'user']['ratings']['rating']:
                    rating = 0

            if rating == 0 or rating == "unrate":
                __rateOnTrakt(rating, gui.media_type, gui.media, unrate=True)
            else:
                __rateOnTrakt(rating, gui.media_type, gui.media)
        else:
            logger.debug("Rating dialog was closed with no rating.")

        del gui
        #Reset rating and unrate for multi part episodes
        unrate = False
        rating = None
示例#28
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)
示例#29
0
def test_notification():
    assert not xbmc_mock.executebuiltin.called
    kodiUtilities.notification('header', 'message')
    assert xbmc_mock.executebuiltin.called