def get_in_progress_tvshows(dummy_arg, page_no, letter):
    def _process(item):
        tmdb_id = item['media_id']
        meta = metadata.tvshow_meta('tmdb_id', tmdb_id, meta_user_info)
        watched_status = get_watched_status_tvshow(watched_info, tmdb_id,
                                                   meta.get('total_aired_eps'))
        if watched_status[0] == 0: append(item)

    check_trakt_refresh()
    duplicates = set()
    data = []
    append = data.append
    watched_indicators = settings.watched_indicators()
    paginate = settings.paginate()
    limit = settings.page_limit()
    meta_user_info = metadata.retrieve_user_info()
    watched_info = get_watched_info_tv(watched_indicators)
    prelim_data = [{
        'media_id': i[0],
        'title': i[3]
    } for i in watched_info
                   if not (i[0] in duplicates or duplicates.add(i[0]))]
    threads = list(make_thread_list(_process, prelim_data, Thread))
    [i.join() for i in threads]
    original_list = sort_for_article(data, 'title', settings.ignore_articles())
    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
Exemple #2
0
def build_add_to_remove_from_list(meta='', media_type='', orig_mode='', from_search=''):
    try: from urlparse import parse_qsl
    except ImportError: from urllib.parse import parse_qsl
    import json
    from modules.settings import trakt_list_subscriptions, watched_indicators
    from modules.nav_utils import build_url
    params = dict(parse_qsl(sys.argv[2].replace('?','')))
    media_type = params.get('media_type', '')
    orig_mode = params.get('orig_mode', '')
    from_search = params.get('from_search', '')
    meta = json.loads(params.get('meta', None))
    main_listing = [('Add to...', 'add'), ('Remove from...', 'remove')]
    mlc = selection_dialog([i[0] for i in main_listing], [i[1] for i in main_listing], 'Choose Add to or Remove from...')
    if mlc == None: return
    string = "Choose Selection to Add Item To" if mlc == 'add' else "Choose Selection to Remove Item From"
    heading = 'Add to ' if mlc == 'add' else 'Remove from '
    listing = [(heading + 'Trakt List', 'trakt'), (heading + 'Fen Favourites', 'favourites')]
    if not trakt_list_subscriptions(): listing.append((heading + 'Fen Subscriptions', 'subscriptions'))
    if media_type == 'tvshow' and watched_indicators() == 0: listing.append((heading + 'Fen Next Episode', 'unwatched_next_episode'))
    if mlc == 'remove': listing.append((heading + 'Cache (Re-cache %s Info)' % ('Movie' if media_type == 'movie' else 'TV Show'), 'refresh'))
    choice = selection_dialog([i[0] for i in listing], [i[1] for i in listing], string)
    if choice == None: return
    elif choice == 'trakt': url = {'mode': ('trakt.trakt_add_to_list' if mlc == 'add' else 'trakt.trakt_remove_from_list'), 'tmdb_id': meta["tmdb_id"], 'imdb_id': meta["imdb_id"], 'tvdb_id': meta["tvdb_id"], 'db_type': media_type}
    elif choice == 'favourites': url = {'mode': ('add_to_favourites' if mlc == 'add' else 'remove_from_favourites'), 'db_type': media_type, 'tmdb_id': meta["tmdb_id"], 'title': meta['title']}
    elif choice == 'subscriptions': url = {'mode': 'subscriptions_add_remove', 'action': mlc, 'db_type': media_type, 'tmdb_id': meta["tmdb_id"], 'orig_mode': orig_mode}
    elif choice == 'unwatched_next_episode': url = {'mode': 'add_next_episode_unwatched', 'action': mlc, 'title': meta["title"], 'tmdb_id': meta["tmdb_id"], 'imdb_id': meta["imdb_id"]}
    elif choice == 'refresh': url = {'mode': 'refresh_cached_data', 'db_type': media_type, 'id_type': 'tmdb_id', 'media_id': meta['tmdb_id']}
    xbmc.executebuiltin('XBMC.RunPlugin(%s)' % build_url(url))
def mark_as_watched_unwatched_movie(params):
    action = params.get('action')
    db_type = 'movie'
    tmdb_id = params.get('tmdb_id')
    title = params.get('title')
    year = params.get('year')
    refresh = params.get('refresh', 'true')
    from_playback = params.get('from_playback', 'false')
    watched_indicators = settings.watched_indicators()
    if watched_indicators == 1:
        if from_playback == 'true' and trakt_official_status(db_type) == False:
            skip_trakt_mark = True
        else:
            skip_trakt_mark = False
        if skip_trakt_mark: kodi_utils.sleep(3000)
        elif not trakt_watched_unwatched(action, 'movies', tmdb_id):
            return kodi_utils.notification(32574)
        clear_trakt_collection_watchlist_data('watchlist', db_type)
        data_base = TRAKT_DB
        data_base = TRAKT_DB
    else:
        data_base = WATCHED_DB
    mark_as_watched_unwatched(db_type,
                              tmdb_id,
                              action,
                              title=title,
                              data_base=data_base)
    erase_bookmark(db_type, tmdb_id)
    if settings.sync_kodi_library_watchstatus():
        from modules.kodi_library import mark_as_watched_unwatched_kodi_library
        mark_as_watched_unwatched_kodi_library(db_type, action, title, year)
    refresh_container(refresh)
def erase_bookmark(db_type, tmdb_id, season='', episode='', refresh='false'):
    try:
        watched_indicators = settings.watched_indicators()
        if watched_indicators == 1:
            bookmarks = get_bookmarks(db_type, watched_indicators)
            if db_type == 'episode':
                season, episode = int(season), int(episode)
            try:
                resume_point, curr_time = detect_bookmark(
                    bookmarks, tmdb_id, season, episode)
            except:
                return
            trakt_progress('clear_progress', db_type, tmdb_id, 0, season,
                           episode)
            database_file = TRAKT_DB
        else:
            database_file = WATCHED_DB
        dbcon = database.connect(database_file)
        dbcur = dbcon.cursor()
        dbcur.execute(
            "DELETE FROM progress where db_type=? and media_id=? and season = ? and episode = ?",
            (db_type, tmdb_id, season, episode))
        dbcon.commit()
        refresh_container(refresh)
    except:
        pass
def set_bookmark(db_type,
                 tmdb_id,
                 curr_time,
                 total_time,
                 season='',
                 episode=''):
    try:
        erase_bookmark(db_type, tmdb_id, season, episode)
        adjusted_current_time = float(curr_time) - 5
        resume_point = round(adjusted_current_time / float(total_time) * 100,
                             1)
        watched_indicators = settings.watched_indicators()
        if watched_indicators == 1:
            trakt_progress('set_progress', db_type, tmdb_id, resume_point,
                           season, episode)
            database_file = TRAKT_DB
        else:
            database_file = WATCHED_DB
        dbcon = database.connect(database_file)
        dbcur = dbcon.cursor()
        dbcur.execute("INSERT INTO progress VALUES (?, ?, ?, ?, ?, ?)",
                      (db_type, tmdb_id, season, episode, str(resume_point),
                       str(curr_time)))
        dbcon.commit()
        if settings.sync_kodi_library_watchstatus():
            from modules.kodi_library import set_bookmark_kodi_library
            set_bookmark_kodi_library(db_type, tmdb_id, curr_time, total_time,
                                      season, episode)
    except:
        pass
Exemple #6
0
 def get_info(self):
     self.meta_user_info = metadata.retrieve_user_info()
     self.watched_indicators = settings.watched_indicators()
     self.watched_info = get_watched_info_tv(self.watched_indicators)
     self.all_episodes = settings.default_all_episodes()
     self.include_year_in_title = settings.include_year_in_title('tvshow')
     self.open_extras = settings.extras_open_action('tvshow')
Exemple #7
0
 def get_info(self):
     self.meta_user_info = metadata.retrieve_user_info()
     self.watched_indicators = settings.watched_indicators()
     self.watched_info = get_watched_info_movie(self.watched_indicators)
     self.bookmarks = get_bookmarks('movie', self.watched_indicators)
     self.include_year_in_title = settings.include_year_in_title('movie')
     self.open_extras = settings.extras_open_action('movie')
Exemple #8
0
def get_unwatched_next_episodes():
    try:
        if settings.watched_indicators() in (1, 2):
            from apis.trakt_api import trakt_fetch_collection_watchlist, get_trakt_tvshow_id
            data = trakt_fetch_collection_watchlist('watchlist', 'tvshow')
            return [{
                "tmdb_id": get_trakt_tvshow_id(i['media_ids']),
                "season": 1,
                "episode": 0,
                "unwatched": True
            } for i in data]
        else:
            settings.check_database(WATCHED_DB)
            dbcon = database.connect(WATCHED_DB)
            dbcur = dbcon.cursor()
            dbcur.execute('''SELECT media_id FROM unwatched_next_episode''')
            unwatched = dbcur.fetchall()
            return [{
                "tmdb_id": i[0],
                "season": 1,
                "episode": 0,
                "unwatched": True
            } for i in unwatched]
    except:
        return []
Exemple #9
0
def get_tvshow_info():
    meta_user_info = metadata.retrieve_user_info()
    watched_indicators = settings.watched_indicators()
    watched_info = get_watched_info_tv(watched_indicators)
    all_episodes = settings.default_all_episodes()
    include_year_in_title = settings.include_year_in_title('tvshow')
    open_extras = settings.extras_open_action('tvshow')
    return meta_user_info, watched_indicators, watched_info, all_episodes, include_year_in_title, open_extras
Exemple #10
0
def get_episode_info():
	meta_user_info = metadata.retrieve_user_info()
	watched_indicators = settings.watched_indicators()
	watched_info = indicators.get_watched_info_tv(watched_indicators)
	show_unaired = settings.show_unaired()
	thumb_fanart = settings.thumb_fanart()
	is_widget = kodi_utils.external_browse()
	current_date = get_datetime()
	adjust_hours = settings.date_offset()
	bookmarks = indicators.get_bookmarks('episode', watched_indicators)
	return meta_user_info, watched_indicators, watched_info, show_unaired, thumb_fanart, is_widget, current_date, adjust_hours, bookmarks
Exemple #11
0
 def worker(self):
     threads = []
     self.watched_indicators = settings.watched_indicators()
     self.all_trailers = settings.all_trailers()
     self.watched_info, self.use_trakt = get_watched_info_movie()
     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_movie_content()
def mark_as_watched_unwatched_tvshow(params):
    action = params.get('action')
    tmdb_id = params.get('tmdb_id')
    try:
        tvdb_id = int(params.get('tvdb_id', '0'))
    except:
        tvdb_id = 0
    watched_indicators = settings.watched_indicators()
    kodi_utils.progressDialogBG.create(ls(32577), '')
    if watched_indicators == 1:
        if not trakt_watched_unwatched(action, 'shows', tmdb_id, tvdb_id):
            return kodi_utils.notification(32574)
        clear_trakt_collection_watchlist_data('watchlist', 'tvshow')
        data_base = TRAKT_DB
    else:
        data_base = WATCHED_DB
    title = params.get('title', '')
    year = params.get('year', '')
    meta_user_info = metadata.retrieve_user_info()
    adjust_hours = settings.date_offset()
    current_date = get_datetime()
    insert_list = []
    insert_append = insert_list.append
    meta = metadata.tvshow_meta('tmdb_id', tmdb_id, meta_user_info)
    season_data = meta['season_data']
    season_data = [i for i in season_data if i['season_number'] > 0]
    total = len(season_data)
    last_played = get_last_played_value(data_base)
    for count, item in enumerate(season_data, 1):
        season_number = item['season_number']
        ep_data = metadata.season_episodes_meta(season_number, meta,
                                                meta_user_info)
        for ep in ep_data:
            season_number = ep['season']
            ep_number = ep['episode']
            display = 'S%.2dE%.2d' % (int(season_number), int(ep_number))
            kodi_utils.progressDialogBG.update(
                int(float(count) / float(total) * 100), ls(32577),
                '%s' % display)
            episode_date, premiered = adjust_premiered_date(
                ep['premiered'], adjust_hours)
            if not episode_date or current_date < episode_date: continue
            insert_append(
                make_batch_insert(action, 'episode', tmdb_id, season_number,
                                  ep_number, last_played, title))
    batch_mark_as_watched_unwatched(insert_list, action, data_base)
    batch_erase_bookmark(insert_list, action, watched_indicators)
    kodi_utils.progressDialogBG.close()
    if settings.sync_kodi_library_watchstatus():
        batch_mark_kodi_library(action, insert_list, title, year)
    refresh_container()
Exemple #13
0
def mark_episode_as_watched_unwatched(params=None):
    from modules.next_episode import add_next_episode_unwatched
    params = dict(parse_qsl(sys.argv[2].replace('?',
                                                ''))) if not params else params
    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')
    season = int(params.get('season'))
    episode = int(params.get('episode'))
    title = params.get('title')
    year = params.get('year')
    refresh = params.get('refresh', 'true')
    from_playback = params.get('from_playback', 'false')
    watched_indicators = settings.watched_indicators()
    if season == 0:
        from modules.nav_utils import notification
        notification(
            'Specials cannot be marked as %s' %
            ('Watched' if action == 'mark_as_watched' else 'Unwatched'),
            time=5000)
        return
    if watched_indicators in (1, 2):
        import time
        from apis.trakt_api import trakt_watched_unwatched, trakt_official_status
        if from_playback == 'true' and trakt_official_status(
                'episode') == False:
            skip_trakt_mark = True
        else:
            skip_trakt_mark = False
        if not skip_trakt_mark:
            trakt_watched_unwatched(action, 'episode', imdb_id, tvdb_id,
                                    season, episode)
        if skip_trakt_mark: time.sleep(3)
        clear_trakt_watched_data('tvshow')
        clear_trakt_collection_watchlist_data('watchlist', 'tvshow')
    if watched_indicators in (0, 1):
        mark_as_watched_unwatched('episode', media_id, action, season, episode,
                                  title)
    erase_bookmark('episode', media_id, season, episode)
    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 mark_as_watched_unwatched_kodi_library
        mark_as_watched_unwatched_kodi_library('episode', action, title, year,
                                               season, episode)
    refresh_container(refresh)
def get_in_progress_episodes():
    watched_indicators = settings.watched_indicators()
    if watched_indicators == 1: database_file = TRAKT_DB
    else: database_file = WATCHED_DB
    dbcon = database.connect(database_file)
    dbcur = dbcon.cursor()
    dbcur.execute(
        '''SELECT media_id, season, episode, resume_point FROM progress WHERE db_type=? ORDER BY rowid DESC''',
        ('episode', ))
    data = dbcur.fetchall()
    episode_list = reversed([{
        'tmdb_id': i[0],
        'season': int(i[1]),
        'episode': int(i[2]),
        'resume_point': float(i[3])
    } for i in data])
    return episode_list
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
Exemple #16
0
def build_next_episode():
	nextep_settings = nextep_content_settings()
	include_unwatched = nextep_settings['include_unwatched']
	indicators = watched_indicators()
	watched_info = get_watched_info_tv(indicators)
	data = get_next_episodes(watched_info)
	if indicators == 1:
		list_type = 'next_episode_trakt'
		try: hidden_data = trakt_get_hidden_items('progress_watched')
		except: hidden_data = []
		data = [i for i in data if not i['tmdb_id'] in hidden_data]
	else: list_type = 'next_episode_fen'
	if include_unwatched:
		try: unwatched = [{'tmdb_id': get_trakt_tvshow_id(i['media_ids']), 'season': 1, 'episode': 0, 'unwatched': True} \
						for i in trakt_fetch_collection_watchlist('watchlist', 'tvshow')]
		except: unwatched = []
		data += unwatched
	build_single_episode(list_type, data)
Exemple #17
0
def get_watched_info_tv():
    info = []
    use_trakt = False
    try:
        if settings.watched_indicators() in (1, 2):
            from apis.trakt_api import trakt_indicators_tv
            use_trakt = True
            info = trakt_indicators_tv()
        else:
            use_trakt = False
            settings.check_database(WATCHED_DB)
            dbcon = database.connect(WATCHED_DB)
            dbcur = dbcon.cursor()
            dbcur.execute(
                "SELECT media_id, season, episode, title FROM watched_status WHERE db_type = ?",
                ('episode', ))
            info = dbcur.fetchall()
            dbcon.close()
    except:
        pass
    return info, use_trakt
def get_in_progress_movies(dummy_arg, page_no, letter):
    check_trakt_refresh()
    watched_indicators = settings.watched_indicators()
    paginate = settings.paginate()
    limit = settings.page_limit()
    if watched_indicators == 1: database_file = TRAKT_DB
    else: database_file = WATCHED_DB
    dbcon = database.connect(database_file)
    dbcur = dbcon.cursor()
    dbcur.execute(
        '''SELECT media_id FROM progress WHERE db_type=? ORDER BY rowid DESC''',
        ('movie', ))
    rows = dbcur.fetchall()
    data = reversed([i[0] for i in rows if not i[0] == ''])
    original_list = [{'media_id': i} 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
def get_watched_items(db_type, page_no, letter):
    paginate = settings.paginate()
    limit = settings.page_limit()
    watched_indicators = settings.watched_indicators()
    if db_type == 'tvshow':
        from threading import Thread
        from modules.utils import make_thread_list

        def _process(item):
            tmdb_id = item['media_id']
            meta = metadata.tvshow_meta('tmdb_id', tmdb_id, meta_user_info)
            watched_status = get_watched_status_tvshow(
                watched_info, tmdb_id, meta.get('total_aired_eps'))
            if watched_status[0] == 1: append(item)

        meta_user_info = metadata.retrieve_user_info()
        watched_info = get_watched_info_tv(watched_indicators)
        duplicates = set()
        data = []
        append = data.append
        prelim_data = [{
            'media_id': i[0],
            'title': i[3]
        } for i in watched_info
                       if not (i[0] in duplicates or duplicates.add(i[0]))]
        threads = list(make_thread_list(_process, prelim_data, Thread))
        [i.join() for i in threads]
        original_list = sort_for_article(data, 'title',
                                         settings.ignore_articles())
    else:
        watched_info = get_watched_info_movie(watched_indicators)
        data = [{'media_id': i[0], 'title': i[1]} for i in watched_info]
        original_list = sort_for_article(data, 'title',
                                         settings.ignore_articles())
    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
Exemple #20
0
def process_eps(item, nextep_settings, nextep_display_settings, watched_info,
                use_trakt, meta_user_info):
    try:
        meta = tvshow_meta('tmdb_id', item['tmdb_id'], meta_user_info)
        include_unaired = nextep_settings['include_unaired']
        season = item['season']
        episode = item['episode']
        unwatched = item.get('unwatched', False)
        seasons_data = all_episodes_meta(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'] == season
        ][0]
        season = season if episode < curr_season_data[
            'episode_count'] else season + 1
        episode = episode + 1 if episode < curr_season_data[
            'episode_count'] else 1
        if settings.watched_indicators() in (1, 2):
            resformat = "%Y-%m-%dT%H:%M:%S.%fZ"
            curr_last_played = item.get('last_played',
                                        '2000-01-01T00:00:00.000Z')
        else:
            resformat = "%Y-%m-%d %H:%M:%S"
            curr_last_played = item.get('last_played', '2000-01-01 00:00:00')
        datetime_object = jsondate_to_datetime(curr_last_played, resformat)
        result.append(
            build_episode(
                {
                    "season": season,
                    "episode": episode,
                    "meta": meta,
                    "curr_last_played_parsed": datetime_object,
                    "action": "next_episode",
                    "unwatched": unwatched,
                    "nextep_display_settings": nextep_display_settings,
                    'include_unaired': include_unaired
                }, watched_info, use_trakt, meta_user_info))
    except:
        pass
Exemple #21
0
def mark_movie_as_watched_unwatched(params=None):
    params = dict(parse_qsl(sys.argv[2].replace('?',
                                                ''))) if not params else params
    action = params.get('action')
    db_type = 'movie'
    media_id = params.get('media_id')
    title = params.get('title')
    year = params.get('year')
    refresh = params.get('refresh', 'true')
    watched_indicators = settings.watched_indicators()
    if watched_indicators in (1, 2):
        from apis.trakt_api import trakt_watched_unwatched
        trakt_watched_unwatched(action, 'movies', media_id)
        clear_trakt_watched_data(db_type)
        clear_trakt_collection_watchlist_data('watchlist', 'movie')
    if watched_indicators in (0, 1):
        mark_as_watched_unwatched(db_type, media_id, action, title=title)
    erase_bookmark(db_type, media_id)
    if settings.sync_kodi_library_watchstatus():
        from modules.kodi_library import mark_as_watched_unwatched_kodi_library
        mark_as_watched_unwatched_kodi_library(db_type, action, title, year)
    refresh_container()
def mark_as_watched_unwatched_episode(params):
    action = params.get('action')
    db_type = 'episode'
    tmdb_id = params.get('tmdb_id')
    try:
        tvdb_id = int(params.get('tvdb_id', '0'))
    except:
        tvdb_id = 0
    season = int(params.get('season'))
    episode = int(params.get('episode'))
    title = params.get('title')
    year = params.get('year')
    refresh = params.get('refresh', 'true')
    from_playback = params.get('from_playback', 'false')
    watched_indicators = settings.watched_indicators()
    if season == 0:
        kodi_utils.notification(32490)
        return
    if watched_indicators == 1:
        if from_playback == 'true' and trakt_official_status(db_type) == False:
            skip_trakt_mark = True
        else:
            skip_trakt_mark = False
        if skip_trakt_mark: kodi_utils.sleep(3000)
        elif not trakt_watched_unwatched(action, db_type, tmdb_id, tvdb_id,
                                         season, episode):
            return kodi_utils.notification(32574)
        clear_trakt_collection_watchlist_data('watchlist', 'tvshow')
        data_base = TRAKT_DB
    else:
        data_base = WATCHED_DB
    mark_as_watched_unwatched(db_type, tmdb_id, action, season, episode, title,
                              data_base)
    erase_bookmark(db_type, tmdb_id, season, episode)
    if settings.sync_kodi_library_watchstatus():
        from modules.kodi_library import mark_as_watched_unwatched_kodi_library
        mark_as_watched_unwatched_kodi_library(db_type, action, title, year,
                                               season, episode)
    refresh_container(refresh)
Exemple #23
0
def build_season_list(params):
    def _process():
        running_ep_count = total_aired_eps

        def _unaired_status():
            if episode_count == 0: return True
            season_date_start = adjust_premiered_date(air_date, 0)[0]
            if not season_date_start or current_date < season_date_start:
                return True
            return False

        for item in season_data:
            try:
                listitem = make_listitem()
                set_property = listitem.setProperty
                cm = []
                cm_append = cm.append
                item_get = item.get
                overview = item_get('overview')
                name = item_get('name')
                poster_path = item_get('poster_path')
                air_date = item_get('air_date')
                season_number = item_get('season_number')
                episode_count = item_get('episode_count')
                season_poster = 'https://image.tmdb.org/t/p/%s%s' % (
                    image_resolution,
                    poster_path) if poster_path is not None else show_poster
                if season_number == 0: unaired = False
                else:
                    unaired = _unaired_status()
                    if unaired:
                        if not show_unaired: return
                        episode_count = 0
                    else:
                        running_ep_count -= episode_count
                        if running_ep_count < 0:
                            episode_count = running_ep_count + episode_count
                try:
                    year = air_date.split('-')[0]
                except:
                    year = show_year
                plot = overview if overview != '' else show_plot
                title = name if use_season_title and name != '' else '%s %s' % (
                    season_str, string(season_number))
                if unaired: title = unaired_label % title
                playcount, overlay, watched, unwatched = get_watched_status_season(
                    watched_info, string(tmdb_id), season_number,
                    episode_count)
                url_params = build_url({
                    'mode': 'build_episode_list',
                    'tmdb_id': tmdb_id,
                    'season': season_number
                })
                extras_params = build_url({
                    'mode': 'extras_menu_choice',
                    'tmdb_id': tmdb_id,
                    'db_type': 'tvshow',
                    'is_widget': is_widget
                })
                options_params = build_url({
                    'mode': 'options_menu_choice',
                    'content': 'season',
                    'tmdb_id': tmdb_id
                })
                cm_append((extras_str, run_plugin % extras_params))
                cm_append((options_str, run_plugin % options_params))
                if not playcount:
                    watched_params = build_url({
                        'mode': 'mark_as_watched_unwatched_season',
                        'action': 'mark_as_watched',
                        'title': show_title,
                        'year': show_year,
                        'tmdb_id': tmdb_id,
                        'tvdb_id': tvdb_id,
                        'season': season_number
                    })
                    cm_append((watched_str % watched_title,
                               run_plugin % watched_params))
                if watched:
                    unwatched_params = build_url({
                        'mode': 'mark_as_watched_unwatched_season',
                        'action': 'mark_as_unwatched',
                        'title': show_title,
                        'year': show_year,
                        'tmdb_id': tmdb_id,
                        'tvdb_id': tvdb_id,
                        'season': season_number
                    })
                    cm_append((unwatched_str % watched_title,
                               run_plugin % unwatched_params))
                listitem.setLabel(title)
                listitem.setContentLookup(False)
                listitem.addContextMenuItems(cm)
                listitem.setArt({
                    'poster': season_poster,
                    'icon': season_poster,
                    'thumb': season_poster,
                    'fanart': fanart,
                    'banner': banner,
                    'clearart': clearart,
                    'clearlogo': clearlogo,
                    'landscape': landscape,
                    'tvshow.clearart': clearart,
                    'tvshow.clearlogo': clearlogo,
                    'tvshow.landscape': landscape,
                    'tvshow.banner': banner
                })
                listitem.setCast(cast)
                listitem.setUniqueIDs({
                    'imdb': imdb_id,
                    'tmdb': string(tmdb_id),
                    'tvdb': string(tvdb_id)
                })
                listitem.setInfo(
                    'video', {
                        'mediatype': 'season',
                        'trailer': trailer,
                        'title': title,
                        'size': '0',
                        'duration': episode_run_time,
                        'plot': plot,
                        'rating': rating,
                        'premiered': premiered,
                        'studio': studio,
                        'year': year,
                        'genre': genre,
                        'mpaa': mpaa,
                        'tvshowtitle': show_title,
                        'imdbnumber': imdb_id,
                        'votes': votes,
                        'season': season_number,
                        'playcount': playcount,
                        'overlay': overlay
                    })
                set_property('watchedepisodes', string(watched))
                set_property('unwatchedepisodes', string(unwatched))
                set_property('totalepisodes', string(episode_count))
                if is_widget:
                    set_property('fen_widget', 'true')
                    set_property('fen_playcount', string(playcount))
                    set_property('fen_extras_menu_params', extras_params)
                    set_property('fen_options_menu_params', options_params)
                else:
                    set_property('fen_widget', 'false')
                yield (url_params, listitem, True)
            except:
                pass

    __handle__ = int(argv[1])
    meta_user_info = metadata.retrieve_user_info()
    watched_indicators = settings.watched_indicators()
    watched_info = get_watched_info_tv(watched_indicators)
    show_unaired = settings.show_unaired()
    is_widget = kodi_utils.external_browse()
    current_date = get_datetime()
    image_resolution = meta_user_info['image_resolution']['poster']
    poster_main, poster_backup, fanart_main, fanart_backup = settings.get_art_provider(
    )
    meta = metadata.tvshow_meta('tmdb_id', params['tmdb_id'], meta_user_info)
    meta_get = meta.get
    season_data = meta_get('season_data')
    if not season_data: return
    tmdb_id, tvdb_id, imdb_id = meta_get('tmdb_id'), meta_get(
        'tvdb_id'), meta_get('imdb_id')
    show_title, show_year, show_plot, banner = meta_get('title'), meta_get(
        'year'), meta_get('plot'), meta_get('banner')
    show_poster = meta_get(poster_main) or meta_get(
        poster_backup) or poster_empty
    fanart = meta_get(fanart_main) or meta_get(fanart_backup) or fanart_empty
    clearlogo, clearart, landscape = meta_get('clearlogo'), meta_get(
        'clearart'), meta_get('landscape')
    cast, mpaa, votes = meta_get('cast'), meta_get('mpaa'), meta_get('votes')
    trailer, genre, studio = string(
        meta_get('trailer')), meta_get('genre'), meta_get('studio')
    episode_run_time, rating, premiered = meta_get(
        'episode_run_time'), meta_get('rating'), meta_get('premiered')
    total_seasons = meta_get('total_seasons')
    total_aired_eps = meta_get('total_aired_eps')
    if not settings.show_specials():
        season_data = [i for i in season_data if not i['season_number'] == 0]
    season_data.sort(key=lambda k: k['season_number'])
    use_season_title = settings.use_season_title()
    watched_title = 'Trakt' if watched_indicators == 1 else 'Fen'
    kodi_utils.add_items(__handle__, list(_process()))
    kodi_utils.set_content(__handle__, 'seasons')
    kodi_utils.end_directory(__handle__)
    kodi_utils.set_view_mode('view.seasons', 'seasons')
Exemple #24
0
def next_episode_context_choice():
    from modules.utils import selection_dialog
    from modules.nav_utils import toggle_setting, build_url
    params = dict(parse_qsl(sys.argv[2].replace('?', '')))
    content_settings = settings.nextep_content_settings()
    display_settings = settings.nextep_display_settings()
    airdate_replacement = [('%d-%m-%Y', 'Day-Month-Year'),
                           ('%Y-%m-%d', 'Year-Month-Day'),
                           ('%m-%d-%Y', 'Month-Day-Year')]
    sort_type_status = ('Recently Watched', 'Airdate',
                        'Title')[content_settings['sort_type']]
    sort_order_status = ('Descending',
                         'Ascending')[content_settings['sort_order']]
    toggle_sort_order_SETTING = ('nextep.sort_order',
                                 ('0' if sort_order_status == 'Ascending' else
                                  '1'))
    cache_to_disk_status = str(content_settings['cache_to_disk'])
    toggle_cache_to_disk_SETTING = ('nextep.cache_to_disk',
                                    ('true' if cache_to_disk_status == 'False'
                                     else 'false'))
    unaired_status = str(content_settings['include_unaired'])
    toggle_unaired_SETTING = ('nextep.include_unaired',
                              ('true'
                               if unaired_status == 'False' else 'false'))
    unwatched_status = str(content_settings['include_unwatched'])
    toggle_unwatched_SETTING = ('nextep.include_unwatched',
                                ('true'
                                 if unwatched_status == 'False' else 'false'))
    airdate_status = str(display_settings['include_airdate'])
    toggle_airdate_SETTING = ('nextep.include_airdate',
                              ('true'
                               if airdate_status == 'False' else 'false'))
    airdate_format = settings.nextep_airdate_format()
    airdate_format_status = [
        airdate_format.replace(i[0], i[1]) for i in airdate_replacement
        if i[0] == airdate_format
    ][0]
    airdate_highlight = display_settings['airdate_colour'].capitalize()
    unaired_highlight = display_settings['unaired_colour'].capitalize()
    unwatched_highlight = display_settings['unwatched_colour'].capitalize()
    choices = [
        ('MANAGE IN PROGRESS SHOWS', 'manage_in_progress'),
        ('SORT TYPE: [I]Currently [B]%s[/B][/I]' % sort_type_status,
         'Sort Type'),
        ('SORT ORDER: [I]Currently [B]%s[/B][/I]' % sort_order_status,
         'toggle_cache_to_disk'),
        ('CACHE TO DISK: [I]Currently [B]%s[/B][/I]' % cache_to_disk_status,
         'toggle_cache_to_disk'),
        ('INCLUDE UNAIRED EPISODES: [I]Currently [B]%s[/B][/I]' %
         unaired_status, 'toggle_unaired'),
        ('INCLUDE WATCHLIST/UNWATCHED TV: [I]Currently [B]%s[/B][/I]' %
         unwatched_status, 'toggle_unwatched'),
        ('INCLUDE AIRDATE: [I]Currently [B]%s[/B][/I]' % airdate_status,
         'toggle_airdate'),
        ('AIRDATE FORMAT: [I]Currently [B]%s[/B][/I]' % airdate_format_status,
         'Airdate Format'),
        ('AIRDATE HIGHLIGHT: [I]Currently [B]%s[/B][/I]' % airdate_highlight,
         'Airdate'),
        ('UNAIRED HIGHLIGHT: [I]Currently [B]%s[/B][/I]' % unaired_highlight,
         'Unaired'),
        ('UNWATCHED HIGHLIGHT: [I]Currently [B]%s[/B][/I]' %
         unwatched_highlight, 'Unwatched')
    ]
    if settings.watched_indicators() == 0:
        choices.append(('MANAGE UNWATCHED TV SHOWS', 'manage_unwatched'))
    if settings.watched_indicators() in (1, 2):
        choices.append(('CLEAR TRAKT CACHE', 'clear_cache'))
    string = 'Next Episode Manager'
    dialog_list = [i[0] for i in choices]
    function_list = [i[1] for i in choices]
    choice = selection_dialog(dialog_list, function_list, string)
    if not choice: return
    if choice in ('toggle_sort_order', 'toggle_cache_to_disk',
                  'toggle_unaired', 'toggle_unwatched', 'toggle_airdate'):
        setting = eval(choice + '_SETTING')
        toggle_setting(setting[0], setting[1])
    elif choice == 'clear_cache':
        from modules.nav_utils import clear_cache
        clear_cache('trakt')
    else:
        if choice in ('manage_in_progress', 'manage_unwatched'):
            xbmc.executebuiltin('Container.Update(%s)' %
                                build_url({
                                    'mode': 'build_next_episode_manager',
                                    'action': choice
                                }))
            return
        elif choice in ('Airdate', 'Unaired', 'Unwatched'):
            function = next_episode_color_choice
        else:
            function = next_episode_options_choice
        function(choice)
    xbmc.executebuiltin("Container.Refresh")
    xbmc.executebuiltin('RunPlugin(%s)' %
                        build_url({'mode': 'next_episode_context_choice'}))
Exemple #25
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
Exemple #26
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')
Exemple #27
0
def build_episode(item, watched_info, use_trakt, meta_user_info):
    from modules.utils import make_day
    def check_for_unaired():
        if item.get('ignore_unaired', False): return False
        try:
            d = first_aired.split('-')
            episode_date = date(int(d[0]), int(d[1]), int(d[2]))
        except: episode_date = None
        current_adjusted_date = settings.adjusted_datetime()
        unaired = False
        if not episode_date or current_adjusted_date < episode_date:
            unaired = True
        return unaired
    def build_display():
        if nextep_info:
            display_first_aired = make_day(first_aired)
            airdate = '[[COLOR %s]%s[/COLOR]] ' % (nextep_info['airdate_colour'], display_first_aired) if nextep_info['include_airdate'] else ''
            highlight_color = nextep_info['unwatched_colour'] if item.get('unwatched', False) else nextep_info['unaired_colour'] if unaired else ''
            italics_open, italics_close = ('[I]', '[/I]') if highlight_color else ('', '')
            if highlight_color: episode_info = '%s[COLOR %s]%dx%.2d - %s[/COLOR]%s' % (italics_open, highlight_color, info['season'], info['episode'], info['title'], italics_close)
            else: episode_info = '%s%dx%.2d - %s%s' % (italics_open, info['season'], info['episode'], info['title'], italics_close)
            display = '%s%s: %s' % (airdate, title, episode_info)
        elif trakt_calendar:
            display_first_aired = make_day(first_aired)
            display = '[%s] %s: %dx%.2d - %s' % (display_first_aired, title.upper(), info['season'], info['episode'], info['title'])
            if unaired:
                UNAIRED_EPISODE_COLOUR = settings.unaired_episode_colour()
                if not UNAIRED_EPISODE_COLOUR or UNAIRED_EPISODE_COLOUR == '': UNAIRED_EPISODE_COLOUR = 'red'
                displays = display.split(']')
                display = '[COLOR %s]' % UNAIRED_EPISODE_COLOUR + displays[0] + '][/COLOR]' + displays[1]
        else:
            UNAIRED_EPISODE_COLOUR = settings.unaired_episode_colour()
            if not UNAIRED_EPISODE_COLOUR or UNAIRED_EPISODE_COLOUR == '': UNAIRED_EPISODE_COLOUR = 'red'
            color_tags = ('[COLOR %s]' % UNAIRED_EPISODE_COLOUR, '[/COLOR]') if unaired else ('', '')
            display = '%s: %s%dx%.2d - %s%s' % (title.upper(), color_tags[0], info['season'], info['episode'], info['title'], color_tags[1])
        return display
    try:
        cm = []
        nextep_info = item.get('nextep_display_settings', None)
        trakt_calendar = item.get('trakt_calendar', False)
        watched_indicators = settings.watched_indicators()
        action = item.get('action', '')
        meta = item['meta']
        tmdb_id = meta['tmdb_id']
        tvdb_id = meta['tvdb_id']
        imdb_id = meta["imdb_id"]
        title = meta['title']
        year = meta['year']
        episodes_data = tikimeta.season_episodes_meta(tmdb_id, tvdb_id, item['season'], meta['tvdb_summary']['airedSeasons'], meta['season_data'], meta_user_info)
        info = [i for i in episodes_data if i['episode'] == item['episode']][0]
        first_aired = info['premiered']
        season = info['season']
        episode = info['episode']
        unaired = check_for_unaired()
        if unaired and not item.get('include_unaired', False): return
        thumb = info['thumb'] if 'episodes' in info['thumb'] else meta['fanart']
        playcount, overlay = get_watched_status(watched_info, use_trakt, 'episode', tmdb_id, season, episode)
        resumetime = get_resumetime('episode', tmdb_id, season, episode)
        info.update({'trailer': str(meta.get('trailer')), 'tvshowtitle': title,
                    'genre': meta.get('genre'), 'duration': meta.get('duration'), 'mpaa': meta.get('mpaa'),
                    'studio': meta.get('studio'), 'playcount': playcount, 'overlay': overlay})
        query = title + ' S%.2dE%.2d' % (season, episode)
        display = build_display()
        rootname = '{0} ({1})'.format(title, year)
        meta.update({'vid_type': 'episode', 'rootname': rootname, 'season': season,
                    'episode': episode, 'premiered': first_aired, 'ep_name': info['title'],
                    'plot': info['plot']})
        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)
        browse_url = build_url({'mode': 'build_season_list', 'meta': meta_json})
        playback_menu_params = {'mode': 'playback_menu', 'suggestion': query, 'play_params': json.dumps(url_params)}
        (wstate, waction) = ('Watched', 'mark_as_watched') if playcount == 0 else ('Unwatched', 'mark_as_unwatched')
        watched_title = 'Trakt' if watched_indicators in (1, 2) else "Fen"
        watched_params = {"mode": "mark_episode_as_watched_unwatched", "action": waction, "media_id": tmdb_id, "imdb_id": imdb_id, "tvdb_id": tvdb_id, "season": season, "episode": episode,  "title": title, "year": year}
        if action == 'next_episode': nextep_manage_params = {"mode": "next_episode_context_choice"}
        if not unaired: cm.append(("[B]Mark %s %s[/B]" % (wstate, watched_title),'RunPlugin(%s)' % build_url(watched_params)))
        cm.append(("[B]Options[/B]",'RunPlugin(%s)' % build_url(playback_menu_params)))
        if action == 'next_episode':
            cm.append(("[B]Next Episode Manager[/B]",'RunPlugin(%s)'% build_url(nextep_manage_params)))
            if nextep_info['cache_to_disk']: cm.append(("[B]Refresh...[/B]",'Container.Refresh()'))
        cm.append(("[B]Browse...[/B]",'Container.Update(%s)' % browse_url))
        cm.append(("[B]Extended Info[/B]", 'RunScript(script.extendedinfo,info=extendedtvinfo,id=%s)' % tmdb_id))
        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"})))
        listitem = xbmcgui.ListItem()
        listitem.setLabel(display)
        listitem.setProperty("resumetime", resumetime)
        listitem.setArt({'poster': meta['poster'], 'fanart': meta['fanart'], 'thumb':thumb, 'banner': meta['banner'], 'clearart': meta['clearart'], 'clearlogo': meta['clearlogo'], 'landscape': meta['landscape']})
        listitem.addContextMenuItems(cm)
        listitem.setCast(meta['cast'])
        listitem.setUniqueIDs({'imdb': str(imdb_id), 'tmdb': str(tmdb_id), 'tvdb': str(tvdb_id)})
        info['title'] = display
        listitem.setInfo('video', remove_unwanted_info_keys(info))
        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))
        return {'listitem': (url, listitem, False), 'curr_last_played_parsed': item.get('curr_last_played_parsed', ''), 'label': display, 'order': item.get('order', ''), 'name': query, 'first_aired': first_aired}
    except: pass
Exemple #28
0
def options_menu(params, meta=None):
    def _builder():
        for item in listing:
            line1 = item[0]
            line2 = item[1]
            if line2 == '': line2 = line1
            yield {'line1': line1, 'line2': line2}

    content = params.get('content', None)
    if not content: content = kodi_utils.container_content()[:-1]
    season = params.get('season', None)
    episode = params.get('episode', None)
    if not meta:
        function = metadata.movie_meta if content == 'movie' else metadata.tvshow_meta
        meta_user_info = metadata.retrieve_user_info()
        meta = function('tmdb_id', params['tmdb_id'], meta_user_info)
    watched_indicators = settings.watched_indicators()
    on_str, off_str, currently_str, open_str, settings_str = ls(32090), ls(
        32027), ls(32598), ls(32641), ls(32247)
    autoplay_status, autoplay_toggle, quality_setting = (on_str, 'false', 'autoplay_quality_%s' % content) if settings.auto_play(content) \
                else (off_str, 'true', 'results_quality_%s' % content)
    quality_filter_setting = 'autoplay_quality_%s' % content if autoplay_status == on_str else 'results_quality_%s' % content
    autoplay_next_status, autoplay_next_toggle = (
        on_str, 'false') if settings.autoplay_next_episode() else (off_str,
                                                                   'true')
    results_xml_style_status = get_setting('results.xml_style', 'Default')
    results_filter_ignore_status, results_filter_ignore_toggle = (
        on_str, 'false') if settings.ignore_results_filter() else (off_str,
                                                                   'true')
    results_sorting_status = get_setting('results.sort_order_display').replace(
        '$ADDON[plugin.video.fen 32582]', ls(32582))
    current_results_highlights_action = get_setting('highlight.type')
    results_highlights_status = ls(
        32240) if current_results_highlights_action == '0' else ls(
            32583) if current_results_highlights_action == '1' else ls(32241)
    current_subs_action = get_setting('subtitles.subs_action')
    current_subs_action_status = 'Auto' if current_subs_action == '0' else ls(
        32193) if current_subs_action == '1' else off_str
    active_internal_scrapers = [
        i.replace('_', '') for i in settings.active_internal_scrapers()
    ]
    current_scrapers_status = ', '.join([
        i for i in active_internal_scrapers
    ]) if len(active_internal_scrapers) > 0 else 'N/A'
    current_quality_status = ', '.join(
        settings.quality_filter(quality_setting))
    uncached_torrents_status, uncached_torrents_toggle = (
        on_str, 'false') if settings.display_uncached_torrents() else (off_str,
                                                                       'true')
    listing = []
    base_str1 = '%s%s'
    base_str2 = '%s: [B]%s[/B]' % (currently_str, '%s')
    if content in ('movie', 'episode'):
        multi_line = 'true'
        listing += [(ls(32014), '', 'clear_and_rescrape')]
        listing += [(ls(32006), '', 'rescrape_with_disabled')]
        listing += [(ls(32135), '', 'scrape_with_custom_values')]
        listing += [(base_str1 % (ls(32175), ' (%s)' % content),
                     base_str2 % autoplay_status, 'toggle_autoplay')]
        if autoplay_status == on_str and content == 'episode':
            listing += [
                (base_str1 % (ls(32178), ''), base_str2 % autoplay_next_status,
                 'toggle_autoplay_next')
            ]
        listing += [(base_str1 % (ls(32105), ' (%s)' % content),
                     base_str2 % current_quality_status, 'set_quality')]
        listing += [(base_str1 % ('', '%s %s' % (ls(32055), ls(32533))),
                     base_str2 % current_scrapers_status, 'enable_scrapers')]
        if autoplay_status == off_str:
            listing += [(base_str1 % ('', ls(32140)),
                         base_str2 % results_xml_style_status,
                         'set_results_xml_display')]
            listing += [
                (base_str1 % ('', ls(32151)),
                 base_str2 % results_sorting_status, 'set_results_sorting')
            ]
            listing += [(base_str1 % ('', ls(32138)),
                         base_str2 % results_highlights_status,
                         'set_results_highlights')]
        listing += [(base_str1 % ('', ls(32686)),
                     base_str2 % results_filter_ignore_status,
                     'set_results_filter_ignore')]
        listing += [(base_str1 % ('', ls(32183)),
                     base_str2 % current_subs_action_status, 'set_subs_action')
                    ]
        if 'external' in active_internal_scrapers:
            listing += [(base_str1 % ('', ls(32160)),
                         base_str2 % uncached_torrents_status,
                         'toggle_torrents_display_uncached')]
    else:
        multi_line = 'false'
    listing += [(ls(32046), '', 'extras_lists_choice')]
    if content in ('movie', 'tvshow') and meta:
        listing += [
            (ls(32604) %
             (ls(32028) if meta['mediatype'] == 'movie' else ls(32029)), '',
             'clear_media_cache')
        ]
    if watched_indicators == 1:
        listing += [(ls(32497) % ls(32037), '', 'clear_trakt_cache')]
    if content in ('movie', 'episode'):
        listing += [(ls(32637), '', 'clear_scrapers_cache')]
    listing += [('%s %s' % (ls(32118), ls(32513)), '',
                 'open_external_scrapers_manager')]
    listing += [('%s %s %s' % (open_str, ls(32522), settings_str), '',
                 'open_scraper_settings')]
    listing += [('%s %s %s' % (open_str, ls(32036), settings_str), '',
                 'open_fen_settings')]
    listing += [(ls(32640), '', 'save_and_exit')]
    list_items = list(_builder())
    heading = ls(32646).replace('[B]', '').replace('[/B]', '')
    kwargs = {
        'items': json.dumps(list_items),
        'heading': heading,
        'enumerate': 'false',
        'multi_choice': 'false',
        'multi_line': multi_line
    }
    choice = kodi_utils.select_dialog([i[2] for i in listing], **kwargs)
    if choice in (None, 'save_and_exit'): return
    elif choice == 'clear_and_rescrape':
        return clear_and_rescrape(content, meta, season, episode)
    elif choice == 'rescrape_with_disabled':
        return rescrape_with_disabled(content, meta, season, episode)
    elif choice == 'scrape_with_custom_values':
        return scrape_with_custom_values(content, meta, season, episode)
    elif choice == 'toggle_autoplay':
        set_setting('auto_play_%s' % content, autoplay_toggle)
    elif choice == 'toggle_autoplay_next':
        set_setting('autoplay_next_episode', autoplay_next_toggle)
    elif choice == 'enable_scrapers':
        enable_scrapers_choice()
    elif choice == 'set_results_xml_display':
        results_layout_choice()
    elif choice == 'set_results_sorting':
        results_sorting_choice()
    elif choice == 'set_results_filter_ignore':
        set_setting('ignore_results_filter', results_filter_ignore_toggle)
    elif choice == 'set_results_highlights':
        results_highlights_choice()
    elif choice == 'set_quality':
        set_quality_choice(quality_filter_setting)
    elif choice == 'set_subs_action':
        set_subtitle_choice()
    elif choice == 'extras_lists_choice':
        extras_lists_choice()
    elif choice == 'clear_media_cache':
        return refresh_cached_data(meta['mediatype'], 'tmdb_id',
                                   meta['tmdb_id'], meta['tvdb_id'],
                                   settings.get_language())
    elif choice == 'toggle_torrents_display_uncached':
        set_setting('torrent.display.uncached', uncached_torrents_toggle)
    elif choice == 'clear_trakt_cache':
        return clear_cache('trakt')
    elif choice == 'clear_scrapers_cache':
        return clear_scrapers_cache()
    elif choice == 'open_external_scrapers_manager':
        return external_scrapers_manager()
    elif choice == 'open_scraper_settings':
        return kodi_utils.execute_builtin(
            'Addon.OpenSettings(script.module.fenomscrapers)')
    elif choice == 'open_fen_settings':
        return open_settings('0.0')
    if choice == 'clear_trakt_cache' and content in ('movie', 'tvshow',
                                                     'season', 'episode'):
        kodi_utils.execute_builtin('Container.Refresh')
    kodi_utils.show_busy_dialog()
    kodi_utils.sleep(200)
    kodi_utils.hide_busy_dialog()
    options_menu(params, meta=meta)
Exemple #29
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
Exemple #30
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()