def load_playcount(self):
     jsonfilepath = utils.os_join(self.path, self.jsonfilename)
     if os.path.exists(jsonfilepath):
         with open(jsonfilepath, "r") as f:
             playcount = json.load(f)
         kodi.rpc("VideoLibrary.Set%sDetails" % self.mediatype.capitalize(), playcount=playcount,
                  **{self.mediatype + "id": self.kodiid})
         os.remove(jsonfilepath)
 def mark_watched(self, mediaitem, started_watching_at):
     finished_watching_at = dt.datetime.now()
     watch_duration = finished_watching_at - started_watching_at
     if 0 in (mediaitem.runtime.seconds, watch_duration.seconds):
         return
     if watch_duration.seconds / mediaitem.runtime.seconds >= 0.9:
         kodi.rpc("VideoLibrary.SetEpisodeDetails", episodeid=mediaitem.kodiid,
                  playcount=mediaitem.playcount + 1, lastplayed=finished_watching_at.strftime("%d-%m-%Y %H:%M:%S"))
         kodi.log("%s: Marked as watched" % mediaitem.name)
     else:
         kodi.log("%s: Skipped, only partially watched (%s vs. %s)" %
                  (mediaitem.name, mediaitem.runtime.seconds, watch_duration.seconds))
def run_schedule():
    timeout = minutes_to_next_rounded_update_time()
    kodi.log("Starting update scheduler, next update at %s" %
             (dt.datetime.now() + dt.timedelta(seconds=timeout)).strftime("%H:%M"))
    while True:
        abort = xbmc.Monitor().waitForAbort(timeout)
        if abort:
            kodi.log("Closing background service")
            break
        timeout = {
            "15 min": 900,
            "30 min": 1800,
            "1 hour": 3600,
            "2 hours": 7200
        }[kodi.settings["schedule frequency"]]

        scheduler_enabled = kodi.settings["enable schedule"]
        player_active = kodi.rpc("Player.GetActivePlayers")
        koala_active = xbmcgui.Window(10000).getProperty("%s running" % const.addonname) == "true"
        if player_active or koala_active or not scheduler_enabled:
            continue

        kodi.log("Starting scheduled update next update at %s" %
                 (dt.datetime.now() + dt.timedelta(seconds=timeout)).strftime("%H:%M"))
        xbmc.executebuiltin("RunScript(%s, mode=library, action=schedule)" % const.addonid)
    def get_koala_stored_eps(self):
        # get any stored koala episodes
        episodes = kodi.rpc("VideoLibrary.GetEpisodes", properties=["season", "episode", "playcount"],
                            filter={"field": "path", "operator": "startswith", "value": self.path})
        koala_stored_episodes = set()
        for epdict in episodes.get('episodes', []):
            episode = EpisodeLibEntry(self, epdict["season"], epdict["episode"],
                                      kodiid=epdict["episodeid"], playcount=epdict["playcount"])
            koala_stored_episodes.add(episode)

        return koala_stored_episodes
 def get_lib_entry(self):
     moviesdict = kodi.rpc("VideoLibrary.GetMovies",
                           properties=["file", 'playcount'],
                           multifilter={"and":
                                        [("filename", "is", self.htmfilename),
                                         ("path", "startswith", self.path)]})
     try:
         movie_dict = moviesdict['movies'][0]
     except (KeyError, IndexError):
         return None
     return MovieLibEntry(self.title, movie_dict["movieid"], movie_dict["playcount"])
    def get_stored_episodes(self):
        koala_stored_episodes = self.get_koala_stored_eps()
        if koala_stored_episodes:
            any_ep_kodiid = next(iter(koala_stored_episodes)).kodiid
        else:
            # no stored koala episode, get any stored episode
            episodes = kodi.rpc("VideoLibrary.GetEpisodes", limits={"start": 0, "end": 1},
                                filter={"field": "filename", "operator": "startswith", "value": "%s S" % utils.stringtofile(self.title)},
                                ).get('episodes', [])
            if not episodes:
                # no stored episodes detectable
                return set(), set()
            any_ep_kodiid = episodes[0]['episodeid']
        any_episode = kodi.rpc("VideoLibrary.GetEpisodeDetails", episodeid=any_ep_kodiid, properties=["showtitle"])
        scraped_title = any_episode['episodedetails']['showtitle']

        all_stored_episodes_dict = kodi.rpc("VideoLibrary.GetEpisodes",
                                            properties=["season", "episode"],
                                            filter={"field": "tvshow", "operator": "is", "value": scraped_title})
        all_stored_episodes_set = set(BaseEpisode(show=self, seasonnr=epdict['season'], episodenr=epdict['episode'])
                                      for epdict in all_stored_episodes_dict.get('episodes', []))
        return koala_stored_episodes, all_stored_episodes_set
 def get_episodes(self, playingfile):
     startkodiid = playingfile['id']
     tvshowid = playingfile["tvshowid"]
     tvshow_dict = kodi.rpc("VideoLibrary.GetEpisodes", tvshowid=tvshowid, properties=[
                            "playcount", "season", "episode", "file", "runtime"])
     stored_episodes = {}
     for episode in tvshow_dict['episodes']:
         epcode = 'S%02dE%02d' % (episode['season'], episode['episode'])
         kodiid = episode['episodeid']
         playcount = episode['playcount']
         runtime = dt.timedelta(seconds=episode['runtime'])
         with open(episode['file'], 'r') as txt:
             urlid = re.match(r".*www.netflix.com/watch/(\d+).*", txt.read()).group(1)
         stored_episodes[urlid] = MediaItem(epcode, kodiid, playcount, runtime)
         if kodiid == startkodiid:
             starturlid = urlid
     return starturlid, stored_episodes
def is_libpath_added():
    sources = kodi.rpc("Files.GetSources", media="video")
    for source in sources.get('sources', []):
        if source['file'].startswith(utils.uni_join(const.libpath, const.provider)):
            return True
    return False
 def remove_from_lib(self):
     kodi.rpc("VideoLibrary.Remove%s" % self.mediatype.capitalize(),
              **{self.mediatype + "id": self.kodiid})
 def get_playing_file(self):
     active_player = kodi.rpc("Player.GetActivePlayers")[0]['playerid']
     playingfile = kodi.rpc("Player.GetItem", playerid=active_player,
                            properties=["season", "episode", "tvshowid", "file", "playcount", "runtime"])
     return playingfile["item"]