def build_in_progress_episode():
    from modules.indicators_bookmarks import get_watched_info_tv

    def process_eps(item):
        listitem = build_episode(
            {
                "season": int(item[1]),
                "episode": int(item[2]),
                "meta": tvshow_meta('tmdb_id', item[0], meta_user_info)
            }, watched_info, use_trakt, meta_user_info)['listitem']
        xbmcplugin.addDirectoryItem(__handle__,
                                    listitem[0],
                                    listitem[1],
                                    isFolder=listitem[2])

    check_meta_database()
    settings.check_database(WATCHED_DB)
    watched_info, use_trakt = get_watched_info_tv()
    meta_user_info = retrieve_user_info()
    window.clearProperty('fen_fanart_error')
    threads = []
    dbcon = database.connect(WATCHED_DB)
    dbcur = dbcon.cursor()
    dbcur.execute(
        '''SELECT media_id, season, episode FROM progress WHERE db_type=? ORDER BY rowid DESC''',
        ('episode', ))
    rows = dbcur.fetchall()
    for item in rows:
        threads.append(Thread(target=process_eps, args=(item, )))
    [i.start() for i in threads]
    [i.join() for i in threads]
    xbmcplugin.setContent(__handle__, 'episodes')
    xbmcplugin.endOfDirectory(__handle__)
    setView('view.episode_lists', 'episodes')
Beispiel #2
0
def similar_recommendations_choice():
    try:
        from urlparse import parse_qsl
    except ImportError:
        from urllib.parse import parse_qsl
    import json
    from modules.utils import selection_dialog
    import tikimeta
    params = dict(parse_qsl(sys.argv[2].replace('?', '')))
    db_type = params.get('db_type')
    try:
        meta_user_info = json.loads(params.get('meta_user_info'))
    except:
        meta_user_info = tikimeta.retrieve_user_info()
    meta_type = 'movie' if db_type == 'movies' else 'tvshow'
    dl = ['Similar', 'Recommended']
    fl = ['tmdb_%s_similar' % db_type, 'tmdb_%s_recommendations' % db_type]
    string = 'Please Choose Movie Search Option:' if db_type == 'movies' else 'Please Choose TV Show Search Option:'
    mode = 'build_%s_list' % meta_type
    choice = selection_dialog(dl, fl, string)
    if not choice: return
    try:
        sim_recom_params = {
            'mode': mode,
            'action': choice,
            'sim_recom_tmdb': params.get('sim_recom_tmdb'),
            'sim_recom_name': params.get('sim_recom_name'),
            'from_search': params.get('from_search')
        }
        xbmc.executebuiltin('XBMC.Container.Update(%s)' %
                            build_url(sim_recom_params))
    except:
        return
Beispiel #3
0
 def worker(self):
     threads = []
     self.watched_info, self.use_trakt = get_watched_info_tv()
     self.meta_user_info = tikimeta.retrieve_user_info()
     window.clearProperty('fen_fanart_error')
     for item_position, item in enumerate(self.list): threads.append(Thread(target=self.set_info, args=(item_position, item)))
     [i.start() for i in threads]
     [i.join() for i in threads]
     self.build_tvshow_content()
 def __init__(self,
              db_type=None,
              tmdb_id=None,
              action=None,
              orig_mode=None):
     tikimeta.check_meta_database()
     self.db_type = db_type
     self.tmdb_id = tmdb_id  #str
     self.action = action
     self.orig_mode = orig_mode
     self.meta_user_info = tikimeta.retrieve_user_info()
     if self.db_type:
         self.path = settings.movies_directory(
         ) if self.db_type == 'movie' else settings.tv_show_directory()
     self.add_release_date = settings.add_release_date()
     window.setProperty('fen_fanart_error', 'true')
def in_progress_tvshow(db_type, page_no, letter):
    from modules.utils import title_key
    from modules.nav_utils import paginate_list
    paginate = settings.paginate()
    limit = settings.page_limit()
    check_meta_database()
    if settings.watched_indicators() in (1, 2):
        from apis.trakt_api import trakt_indicators_tv
        items = trakt_indicators_tv()
        data = [(i[0], i[3]) for i in items if i[1] > len(i[2])]
    else:
        from modules.indicators_bookmarks import get_watched_status_tvshow, get_watched_info_tv

        def _process(item):
            meta = tvshow_meta('tmdb_id', item[0], meta_user_info)
            watched_status = get_watched_status_tvshow(
                watched_info, use_trakt, meta['tmdb_id'],
                meta.get('total_episodes'))
            if not watched_status[0] == 1: data.append(item)

        data = []
        threads = []
        settings.check_database(WATCHED_DB)
        dbcon = database.connect(WATCHED_DB)
        dbcur = dbcon.cursor()
        dbcur.execute(
            '''SELECT media_id, title, last_played FROM watched_status WHERE db_type=? ORDER BY rowid DESC''',
            ('episode', ))
        rows1 = dbcur.fetchall()
        in_progress_result = list(set([i for i in rows1]))
        watched_info, use_trakt = get_watched_info_tv()
        meta_user_info = retrieve_user_info()
        window.setProperty('fen_fanart_error', 'true')
        for item in in_progress_result:
            threads.append(Thread(target=_process, args=(item, )))
        [i.start() for i in threads]
        [i.join() for i in threads]
    data = sorted(data, key=lambda k: title_key(k[1]))
    original_list = [{'media_id': i[0]} for i in data]
    if paginate:
        final_list, total_pages = paginate_list(original_list, page_no, letter,
                                                limit)
    else:
        final_list, total_pages = original_list, 1
    return final_list, total_pages
Beispiel #6
0
def nextep_playback_info(tmdb_id,
                         current_season,
                         current_episode,
                         from_library=None):
    def build_next_episode_play():
        ep_data = [
            i['episodes_data'] for i in seasons_data
            if i['season_number'] == season
        ][0]
        ep_data = [i for i in ep_data if i['airedEpisodeNumber'] == episode][0]
        airdate = ep_data['firstAired']
        d = airdate.split('-')
        episode_date = date(int(d[0]), int(d[1]), int(d[2]))
        if current_adjusted_date < episode_date: return {'pass': True}
        query = meta['title'] + ' S%.2dE%.2d' % (int(season), int(episode))
        display_name = '%s - %dx%.2d' % (meta['title'], int(season),
                                         int(episode))
        meta.update({
            'vid_type': 'episode',
            'rootname': display_name,
            "season": season,
            'ep_name': ep_data['episodeName'],
            "episode": episode,
            'premiered': airdate,
            'plot': ep_data['overview']
        })
        meta_json = json.dumps(meta)
        url_params = {
            'mode': 'play_media',
            'background': 'true',
            'vid_type': 'episode',
            'tmdb_id': meta['tmdb_id'],
            'query': query,
            'tvshowtitle': meta['rootname'],
            'season': season,
            'episode': episode,
            'meta': meta_json,
            'ep_name': ep_data['episodeName']
        }
        if from_library:
            url_params.update({'library': 'True', 'plot': ep_data['overview']})
        return build_url(url_params)

    check_meta_database()
    meta_user_info = retrieve_user_info()
    meta = tvshow_meta('tmdb_id', tmdb_id, meta_user_info)
    nextep_info = {'pass': True}
    try:
        current_adjusted_date = settings.adjusted_datetime()
        seasons_data = all_episodes_meta(tmdb_id, meta['tvdb_id'],
                                         meta['tvdb_summary']['airedSeasons'],
                                         meta['season_data'], meta_user_info)
        curr_season_data = [
            i for i in seasons_data if i['season_number'] == current_season
        ][0]
        season = current_season if current_episode < curr_season_data[
            'episode_count'] else current_season + 1
        episode = current_episode + 1 if current_episode < curr_season_data[
            'episode_count'] else 1
        nextep_info = {
            'season': season,
            'episode': episode,
            'url': build_next_episode_play()
        }
    except:
        pass
    return nextep_info
Beispiel #7
0
def build_next_episode():
    from modules.indicators_bookmarks import get_watched_info_tv
    check_meta_database()
    clear_all_trakt_cache_data(confirm=False)
    sync_watched_trakt_to_fen()
    try:
        threads = []
        seen = set()
        ep_list = []
        nextep_settings = settings.nextep_content_settings()
        nextep_display_settings = settings.nextep_display_settings()
        watched_info, use_trakt = get_watched_info_tv()
        meta_user_info = retrieve_user_info()
        cache_to_disk = nextep_settings['cache_to_disk']
        nextep_display_settings['cache_to_disk'] = cache_to_disk
        window.setProperty('fen_fanart_error', 'true')
        if nextep_settings['include_unwatched']:
            for i in get_unwatched_next_episodes():
                ep_list.append(i)
        if settings.watched_indicators() in (1, 2):
            from apis.trakt_api import trakt_get_next_episodes
            ep_list += trakt_get_next_episodes()
        else:
            settings.check_database(WATCHED_DB)
            dbcon = database.connect(WATCHED_DB)
            dbcur = dbcon.cursor()
            dbcur.execute(
                '''SELECT media_id, season, episode, last_played FROM watched_status WHERE db_type=?''',
                ('episode', ))
            rows = dbcur.fetchall()
            rows = sorted(rows, key=lambda x: (x[0], x[1], x[2]), reverse=True)
            [
                ep_list.append({
                    "tmdb_id": a,
                    "season": int(b),
                    "episode": int(c),
                    "last_played": d
                }) for a, b, c, d in rows if not (a in seen or seen.add(a))
            ]
            ep_list = [
                x for x in ep_list
                if x['tmdb_id'] not in check_for_next_episode_excludes()
            ]
        ep_list = [i for i in ep_list if not i['tmdb_id'] == None]
        for item in ep_list:
            threads.append(
                Thread(target=process_eps,
                       args=(item, nextep_settings, nextep_display_settings,
                             watched_info, use_trakt, meta_user_info)))
        [i.start() for i in threads]
        [i.join() for i in threads]
        r = [i for i in result if i is not None]
        r = sort_next_eps(r, nextep_settings)
        item_list = [i['listitem'] for i in r]
        for i in item_list:
            xbmcplugin.addDirectoryItem(__handle__, i[0], i[1], i[2])
        xbmcplugin.setContent(__handle__, 'episodes')
        xbmcplugin.endOfDirectory(__handle__, cacheToDisc=cache_to_disk)
        setView('view.episode_lists', 'episodes')
    except:
        from modules.nav_utils import notification
        notification('Error getting Next Episode Info', time=3500)
        pass
Beispiel #8
0
def build_next_episode_manager():
    from modules.nav_utils import add_dir
    from modules.indicators_bookmarks import get_watched_status_tvshow, get_watched_info_tv

    def _process(tmdb_id, action):
        try:
            meta = tvshow_meta('tmdb_id', tmdb_id, meta_user_info)
            title = meta['title']
            if action == 'manage_unwatched':
                action, display = 'remove', '[COLOR=%s][UNWATCHED][/COLOR] %s' % (
                    NEXT_EP_UNWATCHED, title)
                url_params = {
                    'mode': 'add_next_episode_unwatched',
                    'action': 'remove',
                    'tmdb_id': tmdb_id,
                    'title': title
                }
            elif action == 'trakt_and_fen':
                action, display = 'unhide' if tmdb_id in exclude_list else 'hide', '[COLOR=red][EXCLUDED][/COLOR] %s' % title if tmdb_id in exclude_list else '[COLOR=green][INCLUDED][/COLOR] %s' % title
                url_params = {
                    "mode": "hide_unhide_trakt_items",
                    "action": action,
                    "media_type": "shows",
                    "media_id": meta['imdb_id'],
                    "section": "progress_watched"
                }
            else:
                action, display = 'remove' if tmdb_id in exclude_list else 'add', '[COLOR=red][EXCLUDED][/COLOR] %s' % title if tmdb_id in exclude_list else '[COLOR=green][INCLUDED][/COLOR] %s' % title
                url_params = {
                    'mode': 'add_to_remove_from_next_episode_excludes',
                    'action': action,
                    'title': title,
                    'media_id': tmdb_id
                }
            sorted_list.append({
                'tmdb_id': tmdb_id,
                'display': display,
                'url_params': url_params,
                'meta': json.dumps(meta)
            })
        except:
            pass

    check_meta_database()
    clear_all_trakt_cache_data(confirm=False)
    sync_watched_trakt_to_fen()
    params = dict(parse_qsl(sys.argv[2].replace('?', '')))
    NEXT_EP_UNWATCHED = __addon__.getSetting('nextep.unwatched_colour')
    if not NEXT_EP_UNWATCHED or NEXT_EP_UNWATCHED == '':
        NEXT_EP_UNWATCHED = 'red'
    threads = []
    sorted_list = []
    action = params['action']
    if action == 'manage_unwatched':
        tmdb_list = [i['tmdb_id'] for i in get_unwatched_next_episodes()]
        heading = 'Select Show to remove from Fen Next Episode:'
    elif settings.watched_indicators() in (1, 2):
        from apis.trakt_api import trakt_get_next_episodes
        tmdb_list, exclude_list = trakt_get_next_episodes(include_hidden=True)
        heading = 'Select Show to Hide/Unhide from Trakt Progress:'
        action = 'trakt_and_fen'
    else:
        settings.check_database(WATCHED_DB)
        dbcon = database.connect(WATCHED_DB)
        dbcur = dbcon.cursor()
        dbcur.execute(
            '''SELECT media_id FROM watched_status WHERE db_type=? GROUP BY media_id''',
            ('episode', ))
        rows = dbcur.fetchall()
        tmdb_list = [row[0] for row in rows]
        exclude_list = check_for_next_episode_excludes()
        heading = 'Select Show to Include/Exclude in Fen Next Episode:'
    add_dir({'mode': 'nill'},
            '[I][COLOR=grey][B]INFO:[/B][/COLOR] [COLOR=grey2]%s[/COLOR][/I]' %
            heading,
            iconImage='settings.png')
    if not tmdb_list:
        from modules.nav_utils import notification
        return notification('No Shows Present', time=5000)
    meta_user_info = retrieve_user_info()
    window.setProperty('fen_fanart_error', 'true')
    for tmdb_id in tmdb_list:
        threads.append(Thread(target=_process, args=(tmdb_id, action)))
    [i.start() for i in threads]
    [i.join() for i in threads]
    sorted_items = sorted(sorted_list, key=lambda k: k['display'])
    watched_info, use_trakt = get_watched_info_tv()
    for i in sorted_items:
        try:
            cm = []
            meta = json.loads(i['meta'])
            playcount, overlay, total_watched, total_unwatched = get_watched_status_tvshow(
                watched_info, use_trakt, meta['tmdb_id'],
                meta.get('total_episodes'))
            meta.update({
                'playcount': playcount,
                'overlay': overlay,
                'total_watched': str(total_watched),
                'total_unwatched': str(total_unwatched)
            })
            url = build_url(i['url_params'])
            browse_url = build_url({
                'mode': 'build_season_list',
                'meta': i['meta']
            })
            cm.append(
                ("[B]Browse...[/B]", 'XBMC.Container.Update(%s)' % browse_url))
            listitem = xbmcgui.ListItem(i['display'])
            listitem.setProperty('watchedepisodes', str(total_watched))
            listitem.setProperty('unwatchedepisodes', str(total_unwatched))
            listitem.setProperty('totalepisodes', str(meta['total_episodes']))
            listitem.setProperty('totalseasons', str(meta['total_seasons']))
            listitem.addContextMenuItems(cm)
            listitem.setArt({
                'poster': meta['poster'],
                'fanart': meta['fanart'],
                'banner': meta['banner'],
                'clearart': meta['clearart'],
                'clearlogo': meta['clearlogo'],
                'landscape': meta['landscape']
            })
            listitem.setCast(meta['cast'])
            listitem.setInfo('video', remove_unwanted_info_keys(meta))
            xbmcplugin.addDirectoryItem(__handle__,
                                        url,
                                        listitem,
                                        isFolder=True)
        except:
            pass
    xbmcplugin.setContent(__handle__, 'tvshows')
    xbmcplugin.endOfDirectory(__handle__, cacheToDisc=False)
    setView('view.main', 'tvshows')
Beispiel #9
0
def set_bookmark_kodi_library(db_type,
                              tmdb_id,
                              curr_time,
                              season='',
                              episode=''):
    from tikimeta import movie_meta, tvshow_meta, retrieve_user_info
    meta_user_info = retrieve_user_info()
    window.setProperty('fen_fanart_error', 'true')
    try:
        info = movie_meta(
            'tmdb_id', tmdb_id,
            meta_user_info) if db_type == 'movie' else tvshow_meta(
                'tmdb_id', tmdb_id, meta_user_info)
        title = info['title']
        year = info['year']
        years = (str(year), str(int(year) + 1), str(int(year) - 1))
        if db_type == 'movie':
            r = xbmc.executeJSONRPC(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties": ["title"]}, "id": 1}'
                % years)
        else:
            r = xbmc.executeJSONRPC(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties": ["title"]}, "id": 1}'
                % years)
        r = to_utf8(r)
        r = json.loads(
            r)['result']['movies'] if db_type == 'movie' else json.loads(
                r)['result']['tvshows']
        if db_type == 'movie':
            r = [
                i for i in r
                if clean_file_name(title).lower() in clean_file_name(
                    to_utf8(i['title'])).lower()
            ]
        else:
            r = [
                i for i in r if clean_file_name(title).lower() in (
                    clean_file_name(to_utf8(i['title'])).lower(
                    ) if not ' (' in to_utf8(i['title']) else clean_file_name(
                        to_utf8(i['title'])).lower().split(' (')[0])
            ]
        if db_type == 'episode':
            r = xbmc.executeJSONRPC(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "season", "operator": "is", "value": "%s"}, {"field": "episode", "operator": "is", "value": "%s"}]}, "properties": ["file"], "tvshowid": %s }, "id": 1}'
                % (str(season), str(episode), str(r['tvshowid'])))
            r = to_utf8(r)
            r = json.loads(r)['result']['episodes'][0]
        (method, id_name,
         library_id) = ('SetMovieDetails', 'movieid',
                        r['movieid']) if db_type == 'movie' else (
                            'SetEpisodeDetails', 'episodeid', r['episodeid'])
        query = {
            "jsonrpc": "2.0",
            "id": "setResumePoint",
            "method": "VideoLibrary." + method,
            "params": {
                id_name: library_id,
                "resume": {
                    "position": curr_time,
                }
            }
        }
        xbmc.executeJSONRPC(json.dumps(query))
    except:
        pass
Beispiel #10
0
def build_kodi_library_recently_added(db_type):
    import xbmcplugin
    from modules.nav_utils import setView
    limit = int(__addon__.getSetting('recent_added_limit'))
    recent_added = []
    results = []
    if db_type in ('movie', 'movies'):
        from indexers.movies import Movies
        db_type = 'movies'
        view_type = 'view.movies'
        try:
            JSON_req = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetRecentlyAddedMovies", \
            "params": {"properties": ["title", "imdbnumber"]},"id": "1"}'

            r = xbmc.executeJSONRPC(JSON_req)
            r = to_utf8(json.loads(r)['result'][db_type])[:limit]
            results = [i.get('imdbnumber') for i in r]
            Movies(results, 'imdb_id').worker()
        except:
            pass
    else:
        from indexers.tvshows import build_episode
        from modules.indicators_bookmarks import get_watched_info_tv
        from tikimeta import tvshow_meta, retrieve_user_info
        from threading import Thread

        def process_eps(item):
            results.append(
                build_episode(
                    {
                        "season":
                        int(item['season']),
                        "episode":
                        int(item['episode']),
                        'order':
                        item['order'],
                        "meta":
                        tvshow_meta('tvdb_id', item['media_id'],
                                    meta_user_info)
                    }, watched_info, use_trakt, meta_user_info))

        try:
            db_type = 'episodes'
            view_type = 'view.episodes'
            ALL_JSON_req = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTvShows", \
            "params": {"properties": ["imdbnumber","uniqueid"]}, "id": "1"}'

            r = xbmc.executeJSONRPC(ALL_JSON_req)
            r = to_utf8(json.loads(r)['result']['tvshows'])
            tvshow_list = [{
                'tvshow_id':
                i["tvshowid"],
                'media_id':
                i['uniqueid']['tvdb'] if 'uniqueid' in i
                and 'tvdb' in i['uniqueid'] else i['imdbnumber']
                if not i['imdbnumber'].startswith("tt") else None
            } for i in r]
            tvshow_list = [i for i in tvshow_list if i['media_id'] != None]
            JSON_req = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetRecentlyAddedEpisodes", \
            "params": {"properties": ["tvshowid", "season", "episode"]}, "id": "1"}'

            r = xbmc.executeJSONRPC(JSON_req)
            r = to_utf8(json.loads(r)['result'][db_type])[:limit]
            episodes_list = [{
                'tvshow_id': i['tvshowid'],
                'season': i['season'],
                'episode': i['episode'],
                'order': r.index(i)
            } for i in r]
            watched_info, use_trakt = get_watched_info_tv()
            meta_user_info = retrieve_user_info()
            window.setProperty('fen_fanart_error', 'true')
            for i in episodes_list:
                for t in tvshow_list:
                    if i['tvshow_id'] == t['tvshow_id']:
                        recent_added.append({
                            'media_id': t['media_id'],
                            'season': i['season'],
                            'episode': i['episode'],
                            'order': episodes_list.index(i)
                        })
            threads = []
            for item in recent_added:
                threads.append(Thread(target=process_eps, args=(item, )))
            [i.start() for i in threads]
            [i.join() for i in threads]
            r = [i for i in results if i is not None]
            r = sorted(r, key=lambda k: k['order'])
            listitems = [i['listitem'] for i in r]
            xbmcplugin.addDirectoryItems(__handle__, listitems, len(listitems))
        except:
            pass
    xbmcplugin.setContent(__handle__, db_type)
    xbmcplugin.endOfDirectory(__handle__)
    setView(view_type)
Beispiel #11
0
def mark_tv_show_as_watched_unwatched():
    from modules.next_episode import add_next_episode_unwatched
    params = dict(parse_qsl(sys.argv[2].replace('?', '')))
    action = 'mark_as_watched' if params.get(
        'action') == 'mark_as_watched' else 'mark_as_unwatched'
    media_id = params.get('media_id')
    tvdb_id = int(params.get('tvdb_id', '0'))
    imdb_id = params.get('imdb_id')
    watched_indicators = settings.watched_indicators()
    if watched_indicators in (1, 2):
        from apis.trakt_api import trakt_watched_unwatched
        trakt_watched_unwatched(action, 'shows', imdb_id, tvdb_id)
        clear_trakt_watched_data('tvshow')
        clear_trakt_collection_watchlist_data('watchlist', 'tvshow')
    if watched_indicators in (0, 1):
        import tikimeta
        bg_dialog = xbmcgui.DialogProgressBG()
        bg_dialog.create('Please Wait', '')
        title = params.get('title', '')
        year = params.get('year', '')
        try:
            meta_user_info = json.loads(params.get('meta_user_info', ))
        except:
            meta_user_info = tikimeta.retrieve_user_info()
        se_list = []
        count = 1
        meta = tikimeta.tvshow_meta('tmdb_id', media_id, meta_user_info)
        season_data = tikimeta.all_episodes_meta(
            media_id, tvdb_id, meta['tvdb_summary']['airedSeasons'],
            meta['season_data'], meta_user_info)
        total = sum([
            i['episode_count'] for i in season_data if i['season_number'] > 0
        ])
        for item in season_data:
            season_number = item['season_number']
            if season_number <= 0: continue
            ep_data = tikimeta.season_episodes_meta(
                media_id, tvdb_id, season_number,
                meta['tvdb_summary']['airedSeasons'], meta['season_data'],
                meta_user_info)
            for ep in ep_data:
                season_number = ep['season']
                ep_number = ep['episode']
                season_ep = '%.2d<>%.2d' % (int(season_number), int(ep_number))
                display = 'Updating - S%.2dE%.2d' % (int(season_number),
                                                     int(ep_number))
                bg_dialog.update(int(float(count) / float(total) * 100),
                                 'Please Wait', '%s' % display)
                count += 1
                try:
                    first_aired = ep['premiered']
                    d = first_aired.split('-')
                    episode_date = date(int(d[0]), int(d[1]), int(d[2]))
                except:
                    episode_date = date(2100, 10, 24)
                if not settings.adjusted_datetime() > episode_date: continue
                mark_as_watched_unwatched('episode', media_id, action,
                                          season_number, ep_number, title)
                se_list.append(season_ep)
        bg_dialog.close()
    if action == 'mark_as_watched':
        add_next_episode_unwatched('remove', media_id, silent=True)
    if settings.sync_kodi_library_watchstatus():
        from modules.kodi_library import get_library_video, batch_mark_episodes_as_watched_unwatched_kodi_library
        in_library = get_library_video('tvshow', title, year)
        if not in_library:
            refresh_container()
            return
        if not in_library: return
        from modules.nav_utils import notification
        notification('Browse back to Kodi Home Screen!!', time=7000)
        xbmc.sleep(8500)
        ep_dict = {
            'action': action,
            'tvshowid': in_library['tvshowid'],
            'season_ep_list': se_list
        }
        if batch_mark_episodes_as_watched_unwatched_kodi_library(
                in_library, ep_dict):
            notification('Kodi Library Sync Complete', time=5000)
    refresh_container()
Beispiel #12
0
def get_watched_items(db_type, page_no, letter):
    from modules.nav_utils import paginate_list
    from modules.utils import title_key, to_utf8
    watched_indicators = settings.watched_indicators()
    paginate = settings.paginate()
    limit = settings.page_limit()
    if db_type == 'tvshow':
        if watched_indicators in (1, 2):
            from apis.trakt_api import trakt_indicators_tv
            data = trakt_indicators_tv()
            data = sorted(data, key=lambda tup: title_key(tup[3]))
            original_list = [{
                'media_id': i[0],
                'title': i[3]
            } for i in data if i[1] == len(i[2])]
        else:
            import tikimeta
            meta_user_info = tikimeta.retrieve_user_info()
            settings.check_database(WATCHED_DB)
            dbcon = database.connect(WATCHED_DB)
            dbcur = dbcon.cursor()
            dbcur.execute(
                "SELECT media_id, title FROM watched_status WHERE db_type = ?",
                ('episode', ))
            rows = dbcur.fetchall()
            dbcon.close()
            watched_list = list(set(to_utf8([(i[0], i[1]) for i in rows])))
            watched_info, use_trakt = get_watched_info_tv()
            data = []
            for item in watched_list:
                meta = tikimeta.tvshow_meta('tmdb_id', item[0], meta_user_info)
                watched = get_watched_status_tvshow(watched_info, use_trakt,
                                                    item[0],
                                                    meta.get('total_episodes'))
                if watched[0] == 1: data.append(item)
                else: pass
            data = sorted(data, key=lambda tup: title_key(tup[1]))
            original_list = [{'media_id': i[0], 'title': i[1]} for i in data]
    else:
        if watched_indicators in (1, 2):
            from apis.trakt_api import trakt_indicators_movies
            data = trakt_indicators_movies()
            data = sorted(data, key=lambda tup: title_key(tup[1]))
            original_list = [{'media_id': i[0], 'title': i[1]} for i in data]

        else:
            settings.check_database(WATCHED_DB)
            dbcon = database.connect(WATCHED_DB)
            dbcur = dbcon.cursor()
            dbcur.execute(
                "SELECT media_id, title FROM watched_status WHERE db_type = ?",
                (db_type, ))
            rows = dbcur.fetchall()
            dbcon.close()
            data = to_utf8([(i[0], i[1]) for i in rows])
            data = sorted(data, key=lambda tup: title_key(tup[1]))
            original_list = [{'media_id': i[0], 'title': i[1]} for i in data]
    if paginate:
        final_list, total_pages = paginate_list(original_list, page_no, letter,
                                                limit)
    else:
        final_list, total_pages = original_list, 1
    return final_list, total_pages
Beispiel #13
0
def build_episode_list():
    def _build(item):
        try:
            cm = []
            season = item['season']
            episode = item['episode']
            ep_name = item['title']
            premiered = item['premiered']
            playcount, overlay = get_watched_status(watched_info, use_trakt, 'episode', tmdb_id, season, episode)
            resumetime = get_resumetime('episode', tmdb_id, season, episode)
            query = title + ' S%.2dE%.2d' % (int(season), int(episode))
            display_name = '%s - %dx%.2d' % (title, season, episode)
            thumb = item['thumb'] if 'episodes' in item['thumb'] else fanart
            meta.update({'vid_type': 'episode', 'rootname': display_name, 'season': season,
                        'episode': episode, 'premiered': premiered, 'ep_name': ep_name,
                        'plot': item['plot']})
            item.update({'trailer': trailer, 'tvshowtitle': title,
                        'genre': genre, 'duration': duration, 'mpaa': mpaa,
                        'studio': studio, 'playcount': playcount, 'overlay': overlay})
            meta_json = json.dumps(meta)
            url_params = {'mode': 'play_media', 'vid_type': 'episode', 'tmdb_id': tmdb_id,
                        'query': query, 'tvshowtitle': meta['rootname'], 'season': season,
                        'episode': episode, 'meta': meta_json}
            url = build_url(url_params)
            try:
                d = premiered.split('-')
                episode_date = date(int(d[0]), int(d[1]), int(d[2]))
            except: episode_date = date(2000,1,1) if season == 0 else None
            unaired = False
            display = ep_name
            if not episode_date or current_adjusted_date < episode_date:
                unaired = True
                display = '[I][COLOR %s]%s[/COLOR][/I]' % (UNAIRED_EPISODE_COLOUR, ep_name)
                item['title'] = display
            item['sortseason'] = season
            item['sortepisode'] = episode
            (state, action) = ('Watched', 'mark_as_watched') if playcount == 0 else ('Unwatched', 'mark_as_unwatched')
            playback_menu_params = {'mode': 'playback_menu', 'suggestion': query, 'play_params': json.dumps(url_params)}
            if not unaired:
                watched_unwatched_params = {"mode": "mark_episode_as_watched_unwatched", "action": action, "media_id": tmdb_id, "imdb_id": imdb_id, "tvdb_id": tvdb_id, "season": season, "episode": episode,  "title": title, "year": year}
                cm.append(("[B]Mark %s %s[/B]" % (state, watched_title),'RunPlugin(%s)' % build_url(watched_unwatched_params)))
            cm.append(("[B]Options[/B]",'RunPlugin(%s)' % build_url(playback_menu_params)))
            if not unaired and resumetime != '0': cm.append(("[B]Clear Progress[/B]", 'RunPlugin(%s)' % build_url({"mode": "watched_unwatched_erase_bookmark", "db_type": "episode", "media_id": tmdb_id, "season": season, "episode": episode, "refresh": "true"})))
            cm.append(("[B]Extended Info[/B]", 'RunScript(script.extendedinfo,info=extendedtvinfo,id=%s)' % tmdb_id))
            listitem = xbmcgui.ListItem()
            listitem.setLabel(display)
            listitem.setProperty("resumetime", resumetime)
            listitem.addContextMenuItems(cm)
            listitem.setArt({'poster': show_poster, 'fanart': fanart, 'thumb': thumb, 'banner': banner, 'clearart': clearart, 'clearlogo': clearlogo, 'landscape': landscape})
            listitem.setCast(cast)
            listitem.setUniqueIDs({'imdb': str(imdb_id), 'tmdb': str(tmdb_id), 'tvdb': str(tvdb_id)})
            listitem.setInfo('video', remove_unwanted_info_keys(item))
            if is_widget:
                try:
                    listitem.setProperties({'fen_widget': 'true', 'fen_playcount': str(playcount), 'fen_playback_menu_params': json.dumps(playback_menu_params)})
                except:
                    listitem.setProperty("fen_widget", 'true')
                    listitem.setProperty("fen_playcount", str(playcount))
                    listitem.setProperty("fen_playback_menu_params", json.dumps(playback_menu_params))
            if use_threading: item_list.append((url, listitem, False))
            else: xbmcplugin.addDirectoryItem(__handle__, url, listitem, isFolder=False)
        except: pass
    UNAIRED_EPISODE_COLOUR = settings.unaired_episode_colour()
    if not UNAIRED_EPISODE_COLOUR or UNAIRED_EPISODE_COLOUR == '': UNAIRED_EPISODE_COLOUR = 'red'
    params = dict(parse_qsl(sys.argv[2].replace('?','')))
    meta_user_info = tikimeta.retrieve_user_info()
    all_episodes = True if params.get('season') == 'all' else False
    if all_episodes:
        if 'meta' in params:
            meta = json.loads(params.get('meta'))
        else:
            window.clearProperty('fen_fanart_error')
            meta = tikimeta.tvshow_meta('tmdb_id', params.get('tmdb_id'), meta_user_info)
    else:
        try:
            meta = json.loads(window.getProperty('fen_media_meta'))
        except:
            window.clearProperty('fen_fanart_error')
            meta = tikimeta.tvshow_meta('tmdb_id', params.get('tmdb_id'), meta_user_info)
    tmdb_id = meta['tmdb_id']
    tvdb_id = meta['tvdb_id']
    imdb_id = meta['imdb_id']
    title = meta['title']
    year = meta['year']
    rootname = meta['rootname']
    show_poster = meta['poster']
    fanart = meta['fanart']
    banner = meta['banner']
    clearlogo = meta['clearlogo']
    clearart = meta['clearart']
    landscape = meta['landscape']
    cast = meta['cast']
    mpaa = meta['mpaa']
    duration = meta.get('duration')
    trailer = str(meta['trailer'])
    genre = meta.get('genre')
    studio = meta.get('studio')
    watched_indicators = settings.watched_indicators()
    current_adjusted_date = settings.adjusted_datetime()
    watched_title = 'Trakt' if watched_indicators in (1, 2) else "Fen"
    episodes_data = tikimeta.season_episodes_meta(tmdb_id, tvdb_id, params.get('season'), meta['tvdb_summary']['airedSeasons'], meta['season_data'], meta_user_info, all_episodes)
    if all_episodes:
        if not settings.show_specials(): episodes_data = [i for i in episodes_data if not i['season'] == 0]
    episodes_data = sorted(episodes_data, key=lambda i: i['episode'])
    watched_info, use_trakt = get_watched_info_tv()
    use_threading = settings.thread_main_menus()
    if use_threading:
        item_list = []
        threads = []
        for item in episodes_data: threads.append(Thread(target=_build, args=(item,)))
        [i.start() for i in threads]
        [i.join() for i in threads]
        xbmcplugin.addDirectoryItems(__handle__, item_list)
    else:
        for item in episodes_data: _build(item)
    xbmcplugin.setContent(__handle__, 'episodes')
    xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_EPISODE)
    xbmcplugin.endOfDirectory(__handle__)
    setView('view.episodes', 'episodes')
Beispiel #14
0
def build_season_list():
    def _build(item, item_position=None):
        try:
            cm = []
            overview = item['overview']
            name = item['name']
            poster_path = item['poster_path']
            season_number = item['season_number']
            episode_count = item['episode_count']
            plot = overview if overview != '' else show_plot
            title = name if use_season_title and name != '' else 'Season %s' % str(season_number)
            season_poster = poster_path if poster_path is not None else show_poster
            playcount, overlay, watched, unwatched = get_watched_status_season(watched_info, use_trakt, tmdb_id, season_number, episode_count)
            watched_params = {"mode": "mark_season_as_watched_unwatched", "action": 'mark_as_watched', "title": show_title, "year": show_year, "media_id": tmdb_id, "imdb_id": imdb_id, "tvdb_id": tvdb_id, "season": season_number, "meta_user_info": meta_user_info}
            unwatched_params = {"mode": "mark_season_as_watched_unwatched", "action": 'mark_as_unwatched', "title": show_title, "year": show_year, "media_id": tmdb_id, "imdb_id": imdb_id, "tvdb_id": tvdb_id, "season": season_number, "meta_user_info": meta_user_info}
            playback_menu_params = {'mode': 'playback_menu'}
            cm.append(("[B]Mark Watched %s[/B]" % watched_title,'XBMC.RunPlugin(%s)' % build_url(watched_params)))
            cm.append(("[B]Mark Unwatched %s[/B]" % watched_title,'XBMC.RunPlugin(%s)' % build_url(unwatched_params)))
            cm.append(("[B]Options[/B]",'XBMC.RunPlugin(%s)' % build_url(playback_menu_params)))
            cm.append(("[B]Extended Info[/B]", 'RunScript(script.extendedinfo,info=extendedtvinfo,id=%s)' % tmdb_id))
            url_params = {'mode': 'build_episode_list', 'tmdb_id': tmdb_id, 'season': season_number}
            url = build_url(url_params)
            listitem = xbmcgui.ListItem()
            listitem.setLabel(title)
            try:
                listitem.setProperties({'watchedepisodes': str(watched), 'unwatchedepisodes': str(unwatched), 'totalepisodes': str(episode_count)})
            except:
                listitem.setProperty('watchedepisodes', str(watched))
                listitem.setProperty('unwatchedepisodes', str(unwatched))
                listitem.setProperty('totalepisodes', str(episode_count))
            listitem.addContextMenuItems(cm)
            listitem.setArt({'poster': season_poster, 'fanart': fanart, 'banner': banner, 'clearart': clearart, 'clearlogo': clearlogo, 'landscape': landscape})
            listitem.setCast(cast)
            listitem.setUniqueIDs({'imdb': str(imdb_id), 'tmdb': str(tmdb_id), 'tvdb': str(tvdb_id)})
            listitem.setInfo(
                'video', {'mediatype': 'tvshow', 'trailer': trailer,
                    'title': show_title, 'size': '0', 'duration': episode_run_time, 'plot': plot,
                    'rating': rating, 'premiered': premiered, 'studio': studio,
                    'year': show_year,'genre': genre, 'mpaa': mpaa,
                    'tvshowtitle': show_title, 'imdbnumber': imdb_id,'votes': votes,
                    'episode': str(episode_count),'playcount': playcount, 'overlay': overlay})
            if use_threading: item_list.append({'list_item': (url, listitem, True), 'item_position': item_position})
            else: xbmcplugin.addDirectoryItem(__handle__, url, listitem, isFolder=True)
        except: pass
    params = dict(parse_qsl(sys.argv[2].replace('?','')))
    meta_user_info = tikimeta.retrieve_user_info()
    if 'meta' in params:
        meta = json.loads(params.get('meta'))
    else:
        window.clearProperty('fen_fanart_error')
        meta = tikimeta.tvshow_meta('tmdb_id', params.get('tmdb_id'), meta_user_info)
    season_data = tikimeta.all_episodes_meta(meta['tmdb_id'], meta['tvdb_id'], meta['tvdb_summary']['airedSeasons'], meta['season_data'], meta_user_info)
    if not season_data: return
    meta_user_info = json.dumps(meta_user_info)
    tmdb_id = meta['tmdb_id']
    tvdb_id = meta['tvdb_id']
    imdb_id = meta['imdb_id']
    show_title = meta['title']
    show_year = meta['year']
    show_poster = meta['poster']
    show_plot = meta['plot']
    fanart = meta['fanart']
    banner = meta['banner']
    clearlogo = meta['clearlogo']
    clearart = meta['clearart']
    landscape = meta['landscape']
    cast = meta['cast']
    mpaa = meta['mpaa']
    trailer = str(meta['trailer'])
    episode_run_time = meta.get('episode_run_time')
    rating = meta.get('rating')
    premiered = meta.get('premiered')
    studio = meta.get('studio')
    genre = meta.get('genre')
    votes = meta.get('votes')
    if not settings.show_specials(): season_data = [i for i in season_data if not i['season_number'] == 0]
    season_data = sorted(season_data, key=lambda i: i['season_number'])
    use_season_title = settings.use_season_title()
    watched_indicators = settings.watched_indicators()
    watched_title = 'Trakt' if watched_indicators in (1, 2) else "Fen"
    use_threading = settings.thread_main_menus()
    watched_info, use_trakt = get_watched_info_tv()
    if use_threading:
        item_list = []
        threads = []
        for item_position, item in enumerate(season_data): threads.append(Thread(target=_build, args=(item, item_position)))
        [i.start() for i in threads]
        [i.join() for i in threads]
        item_list.sort(key=lambda k: k['item_position'])
        xbmcplugin.addDirectoryItems(__handle__, [i['list_item'] for i in item_list])
    else:
        for item in season_data: _build(item)
    xbmcplugin.setContent(__handle__, 'seasons')
    xbmcplugin.endOfDirectory(__handle__)
    setView('view.seasons', 'seasons')
    window.setProperty('fen_media_meta', json.dumps(meta))