Ejemplo n.º 1
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 []
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
	def _process_ids(item_position, item):
		item['media_id'] = trakt_api.get_trakt_movie_id(item['media_ids']) if item['media_type'] == 'movie' else trakt_api.get_trakt_tvshow_id(item['media_ids'])
		final_append((item_position, item))
Ejemplo n.º 4
0
	def _process(item_position, ep_data):
		try:
			cm = []
			listitem = make_listitem()
			set_property = listitem.setProperty
			cm_append = cm.append
			ep_data_get = ep_data.get
			if list_type_starts_with('trakt_'): tmdb_id = get_trakt_tvshow_id(ep_data_get('ids'))
			else: tmdb_id = ep_data_get('tmdb_id')
			if not tmdb_id: return
			meta = metadata.tvshow_meta('tmdb_id', tmdb_id, meta_user_info)
			meta_get = meta.get
			tmdb_id, tvdb_id, imdb_id = meta_get('tmdb_id'), meta_get('tvdb_id'), meta_get('imdb_id')
			title, year, rootname, banner = meta_get('title'), meta_get('year'), meta_get('rootname'), 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, duration = meta_get('cast'), meta_get('mpaa'), meta_get('duration')
			trailer, genre, studio = string(meta_get('trailer')), meta_get('genre'), meta_get('studio')
			tvshow_plot = meta_get('plot')
			orig_season = ep_data_get('season')
			orig_episode = ep_data_get('episode')
			if list_type_starts_with('next_episode'):
				season_data = meta_get('season_data')
				curr_season_data = [i for i in season_data if i['season_number'] == orig_season][0]
				orig_season = orig_season if orig_episode < curr_season_data['episode_count'] else orig_season + 1
				orig_episode = orig_episode + 1 if orig_episode < curr_season_data['episode_count'] else 1
			episodes_data = metadata.season_episodes_meta(orig_season, meta, meta_user_info)
			try: item = [i for i in episodes_data if i['episode'] == orig_episode][0]
			except: return
			item_get = item.get
			season = item_get('season')
			episode = item_get('episode')
			ep_name = item_get('title')
			orig_premiered = item_get('premiered')
			all_cast = cast + item_get('guest_stars', [])
			episode_date, premiered = adjust_premiered_date(orig_premiered, adjust_hours)
			if not episode_date or current_date < episode_date:
				if list_type_starts_with('next_episode'):
					if not include_unaired: return
					if not date_difference(current_date, episode_date, 7): return
				elif not show_unaired: return
				unaired = True
				set_property('fen_unaired', 'true')
			else:
				unaired = False
				set_property('fen_unaired', 'false')
			playcount, overlay = get_watched_status(watched_info, string(tmdb_id), season, episode)
			resumetime = get_resumetime(bookmarks, tmdb_id, season, episode)
			if display_title == 0: title_string = '%s: ' % title
			else: title_string = ''
			if display_title in (0,1): seas_ep = '%dx%.2d - ' % (season, episode)
			else: seas_ep = ''
			if list_type_starts_with('next_episode'):
				unwatched = ep_data_get('unwatched', False)
				if episode_date: display_premiered = make_day(current_date, episode_date, date_format)
				else: display_premiered == 'UNKNOWN'
				airdate = '[[COLOR magenta]%s[/COLOR]] ' % display_premiered if include_airdate else ''
				highlight_color = unwatched_color if unwatched else unaired_color if unaired else ''
				italics_open, italics_close = ('[I]', '[/I]') if highlight_color else ('', '')
				if highlight_color: episode_info = '%s[COLOR %s]%s %s[/COLOR]%s' % (italics_open, highlight_color, seas_ep, ep_name, italics_close)
				else: episode_info = '%s%s%s%s' % (italics_open, seas_ep, ep_name, italics_close)
				display = '%s%s%s' % (airdate, upper(title_string), episode_info)
			elif list_type == 'trakt_calendar':
				if episode_date: display_premiered = make_day(current_date, episode_date, date_format)
				else: display_premiered == 'UNKNOWN'
				display = '[%s]%s%s%s' % (display_premiered, upper(title_string), seas_ep, item_get('title'))
				if unaired:
					displays = display.split(']')
					display = '[COLOR red]' + displays[0] + '][/COLOR]' + displays[1]
			else:
				color_tags = ('[COLOR red]', '[/COLOR]') if unaired else ('', '')
				display = '%s%s%s%s%s' % (upper(title_string), color_tags[0], seas_ep, ep_name, color_tags[1])
			thumb = item_get('thumb', None) or fanart
			if thumb_fanart: background = thumb
			else: background = fanart
			item.update({'trailer': trailer, 'tvshowtitle': title, 'premiered': premiered, 'genre': genre, 'duration': duration,
						'mpaa': mpaa, 'studio': studio, 'playcount': playcount, 'overlay': overlay, 'title': display})
			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': 'episode', 'tmdb_id': tmdb_id, 'season': season, 'episode': episode})
			url_params = build_url({'mode': 'play_media', 'vid_type': 'episode', 'tmdb_id': tmdb_id, 'season': season, 'episode': episode})
			if show_all_episodes:
				if all_episodes == 1 and meta_get('total_seasons') > 1: browse_params = build_url({'mode': 'build_season_list', 'tmdb_id': tmdb_id})
				else: browse_params = build_url({'mode': 'build_episode_list', 'tmdb_id': tmdb_id, 'season': 'all'})
			else: browse_params = build_url({'mode': 'build_season_list', 'tmdb_id': tmdb_id})
			cm_append((extras_str, run_plugin % extras_params))
			cm_append((options_str, run_plugin % options_params))
			cm_append((browse_str, container_update % browse_params))
			clearprog_params, unwatched_params, watched_params = '', '', ''
			if not unaired:
				if resumetime != '0':
					clearprog_params = build_url({'mode': 'watched_unwatched_erase_bookmark', 'db_type': 'episode', 'tmdb_id': tmdb_id,
												'season': season, 'episode': episode, 'refresh': 'true'})
					cm_append((clearprog_str, run_plugin % clearprog_params))
					set_property('fen_in_progress', 'true')
				if playcount:
					unwatched_params = build_url({'mode': 'mark_as_watched_unwatched_episode', 'action': 'mark_as_unwatched', 'tmdb_id': tmdb_id,
												'tvdb_id': tvdb_id, 'season': season, 'episode': episode,  'title': title, 'year': year})
					cm_append((unwatched_str % watched_title, run_plugin % unwatched_params))
				else:
					watched_params = build_url({'mode': 'mark_as_watched_unwatched_episode', 'action': 'mark_as_watched', 'tmdb_id': tmdb_id,
												'tvdb_id': tvdb_id, 'season': season, 'episode': episode,  'title': title, 'year': year})
					cm_append((watched_str % watched_title, run_plugin % watched_params))
			if list_type == 'next_episode_trakt': cm_append((ls(32599), container_update % build_url({'mode': 'build_next_episode_manager'})))
			listitem.setLabel(display)
			listitem.setContentLookup(False)
			listitem.addContextMenuItems(cm)
			listitem.setArt({'poster': show_poster, 'fanart': background, 'thumb': thumb, 'icon':thumb, 'banner': banner, 'clearart': clearart, 'clearlogo': clearlogo,
							'landscape': thumb, 'tvshow.clearart': clearart, 'tvshow.clearlogo': clearlogo, 'tvshow.landscape': thumb, 'tvshow.banner': banner})
			listitem.setCast(all_cast)
			listitem.setUniqueIDs({'imdb': imdb_id, 'tmdb': string(tmdb_id), 'tvdb': string(tvdb_id)})
			listitem.setInfo('video', remove_meta_keys(item, dict_removals))
			set_property('resumetime', resumetime)
			set_property('fen_name', '%s - %.2dx%.2d' % (title, season, episode))
			if list_type_starts_with('next_episode'):
				last_played = ep_data_get('last_played', resinsert)
				set_property('fen_last_played', last_played)
				set_property('fen_first_aired', premiered)
			else: set_property('fen_sort_order', string(item_position))
			if is_widget:
				set_property('fen_widget', 'true')
				set_property('fen_playcount', string(playcount))
				set_property('fen_browse_params', browse_params)
				set_property('fen_options_menu_params', options_params)
				set_property('fen_extras_menu_params', extras_params)
				set_property('fen_unwatched_params', unwatched_params)
				set_property('fen_watched_params', watched_params)
				set_property('fen_clearprog_params', clearprog_params)
			else: set_property('fen_widget', 'false')
			append((url_params, listitem, False))
		except: pass
Ejemplo n.º 5
0
 def fetch_list(self):
     try:
         params_get = self.params.get
         self.is_widget = kodi_utils.external_browse()
         self.exit_list_params = params_get(
             'exit_list_params',
             None) or kodi_utils.get_infolabel('Container.FolderPath')
         self.handle = int(argv[1])
         content_type = 'tvshows'
         mode = params_get('mode')
         try:
             page_no = int(params_get('new_page', '1'))
         except ValueError:
             page_no = params_get('new_page')
         letter = params_get('new_letter', 'None')
         list_append = self.list.append
         if self.action in personal:
             if self.action == 'favourites_tvshows':
                 var_module, import_function = 'modules.favourites', 'retrieve_favourites'
             elif self.action == 'in_progress_tvshows':
                 var_module, import_function = 'modules.watched_status', 'get_in_progress_tvshows'
             else:
                 var_module, import_function = 'modules.watched_status', 'get_watched_items'
         else:
             var_module, import_function = 'apis.%s_api' % self.action.split(
                 '_')[0], self.action
         try:
             function = manual_function_import(var_module, import_function)
         except:
             pass
         if self.action in tmdb_main:
             data = function(page_no)
             for item in data['results']:
                 list_append(item['id'])
             self.new_page = {
                 'new_page':
                 string(
                     (data['page'] if 'tmdb' in self.action else page_no) +
                     1)
             }
         elif self.action in trakt_main:
             data = function(page_no)
             for item in data:
                 list_append(get_trakt_tvshow_id(item['show']['ids']))
             self.new_page = {
                 'new_page':
                 string(
                     (data['page'] if 'tmdb' in self.action else page_no) +
                     1)
             }
         elif self.action in trakt_personal:
             data, total_pages = function('shows', page_no, letter)
             self.list = [i['media_id'] for i in data]
             if total_pages > 2: self.total_pages = total_pages
             try:
                 if total_pages > page_no:
                     self.new_page = {
                         'new_page': string(page_no + 1),
                         'new_letter': letter
                     }
             except:
                 pass
         elif self.action in imdb_personal:
             self.id_type = 'imdb_id'
             list_id = params_get('list_id', None)
             data, next_page = function('tvshow', list_id, page_no)
             self.list = [i['imdb_id'] for i in data]
             if next_page:
                 self.new_page = {
                     'list_id': list_id,
                     'new_page': string(page_no + 1),
                     'new_letter': letter
                 }
         elif self.action in personal:
             data, total_pages = function('tvshow', page_no, letter)
             self.list = [i['media_id'] for i in data]
             if total_pages > 2: self.total_pages = total_pages
             if total_pages > page_no:
                 self.new_page = {
                     'new_page': string(page_no + 1),
                     'new_letter': letter
                 }
         elif self.action in similar:
             tmdb_id = self.params['tmdb_id']
             data = function(tmdb_id, page_no)
             self.list = [i['id'] for i in data['results']]
             if data['page'] < data['total_pages']:
                 self.new_page = {
                     'new_page': string(data['page'] + 1),
                     'tmdb_id': tmdb_id
                 }
         elif self.action in tmdb_special:
             key = tmdb_special_key_dict[self.action]
             function_var = params_get(key, None)
             if not function_var: return
             data = function(function_var, page_no)
             self.list = [i['id'] for i in data['results']]
             if data['page'] < data['total_pages']:
                 self.new_page = {
                     'new_page': string(data['page'] + 1),
                     key: function_var
                 }
         elif self.action == 'tmdb_tv_discover':
             from indexers.discover import set_history
             name = self.params['name']
             query = self.params['query']
             if page_no == 1: set_history('tvshow', name, query)
             data = function(query, page_no)
             for item in data['results']:
                 list_append(item['id'])
             if data['page'] < data['total_pages']:
                 self.new_page = {
                     'query': query,
                     'name': name,
                     'new_page': string(data['page'] + 1)
                 }
         elif self.action == 'trakt_tv_mosts':
             for item in function(self.params['period'],
                                  self.params['duration'], page_no):
                 list_append((get_trakt_tvshow_id(item['show']['ids'])))
             self.new_page = {
                 'period': self.params['period'],
                 'duration': self.params['duration'],
                 'new_page': string(page_no + 1)
             }
         elif self.action == 'trakt_tv_related':
             imdb_id = params_get('imdb_id')
             data, total_pages = function(imdb_id, page_no)
             for item in data:
                 list_append(get_trakt_tvshow_id(item['ids']))
             if total_pages > page_no:
                 self.new_page = {
                     'new_page': string(page_no + 1),
                     'imdb_id': imdb_id,
                     'imdb_id': params_get('imdb_id')
                 }
         elif self.action == 'tmdb_tv_genres':
             genre_id = self.params[
                 'genre_id'] if 'genre_id' in self.params else self.multiselect_genres(
                     params_get('genre_list'))
             if not genre_id: return
             data = function(genre_id, page_no)
             self.list = [i['id'] for i in data['results']]
             if data['page'] < data['total_pages']:
                 self.new_page = {
                     'new_page': string(data['page'] + 1),
                     'genre_id': genre_id
                 }
         elif self.action == 'trakt_tv_certifications':
             for item in function(self.params['certification'], page_no):
                 list_append((get_trakt_tvshow_id(item['show']['ids'])))
             self.new_page = {
                 'new_page': string(page_no + 1),
                 'certification': self.params['certification']
             }
         elif self.action == 'trakt_recommendations':
             for item in function('shows'):
                 list_append(get_trakt_tvshow_id(item['ids']))
         elif self.action == 'tmdb_tv_search':
             query = self.params['query']
             data = function(query, page_no)
             total_pages = data['total_pages']
             if total_pages > page_no:
                 self.new_page = {
                     'new_page': string(page_no + 1),
                     'query': query
                 }
             self.list = [i['id'] for i in data['results']]
         elif self.action == 'trakt_tv_search':
             query = self.params['query']
             data, total_pages = function(query, page_no, letter)
             for item in data:
                 list_append(get_trakt_tvshow_id(item['show']['ids']))
             if total_pages > page_no:
                 self.new_page = {
                     'new_page': string(page_no + 1),
                     'new_letter': letter,
                     'query': query
                 }
         if self.total_pages and not self.is_widget:
             url_params = {
                 'mode': 'build_navigate_to_page',
                 'db_type': 'TV Shows',
                 'current_page': page_no,
                 'total_pages': self.total_pages,
                 'transfer_mode': mode,
                 'transfer_action': self.action,
                 'query': params_get('search_name', ''),
                 'actor_id': params_get('actor_id', '')
             }
             self.add_dir(url_params, jumpto_str, item_jump, False)
         kodi_utils.add_items(self.handle, self.worker())
         if self.new_page:
             self.new_page.update({
                 'mode': mode,
                 'action': self.action,
                 'exit_list_params': self.exit_list_params
             })
             self.add_dir(self.new_page)
     except:
         pass
     kodi_utils.set_content(self.handle, content_type)
     kodi_utils.end_directory(self.handle)
     kodi_utils.set_view_mode('view.tvshows', content_type)
Ejemplo n.º 6
0
 def fetch_list(self):
     try:
         params = dict(parse_qsl(sys.argv[2].replace('?','')))
         worker = True
         mode = params.get('mode')
         cache_page = settings.cache_page()
         try: page_no = int(params.get('new_page', '1'))
         except ValueError: page_no = params.get('new_page')
         if cache_page:
             if self.action == 'tmdb_tv_discover':
                 self.cache_page_string = params['name']
             if not 'new_page' in params:
                 silent = True if is_widget else False
                 retrieved_page = cached_page(self.cache_page_string, silent=silent)
                 if retrieved_page: page_no = retrieved_page
         letter = params.get('new_letter', 'None')
         content_type = 'tvshows'
         var_module = 'tmdb_api' if 'tmdb' in self.action else 'trakt_api' if 'trakt' in self.action else 'imdb_api' if 'imdb' in self.action else None
         if var_module:
             try:
                 module = 'apis.%s' % (var_module)
                 function = getattr(importlib.import_module(module), self.action)
             except: pass
         if self.action in ('tmdb_tv_popular','tmdb_tv_top_rated', 'tmdb_tv_premieres','tmdb_tv_upcoming',
             'tmdb_tv_airing_today','tmdb_tv_on_the_air','trakt_tv_anticipated','trakt_tv_trending'):
             data = function(page_no)
             if 'tmdb' in self.action:
                 for item in data['results']: self.list.append(item['id'])
             else:
                 for item in data: self.list.append(get_trakt_tvshow_id(item['show']['ids']))
             self.new_page = {'mode': mode, 'action': self.action, 'new_page': str((data['page'] if 'tmdb' in self.action else page_no) + 1), 'foldername': self.action}
         elif self.action == 'tmdb_tv_discover':
             from modules.discover import set_history
             name = params['name']
             query = params['query']
             if page_no == 1: set_history('tvshow', name, query)
             data = function(query, page_no)
             for item in data['results']: self.list.append(item['id'])
             if data['page'] < data['total_pages']: self.new_page = {'mode': mode, 'action': self.action, 'query': query, 'name': name, 'new_page': str(data['page'] + 1), 'foldername': self.action}
         elif self.action in ('trakt_collection', 'trakt_watchlist', 'trakt_collection_widgets'):
             data, total_pages = function('shows', page_no, letter)
             self.list = [i['media_id'] for i in data]
             if total_pages > 2: self.total_pages = total_pages
             if total_pages > page_no: self.new_page = {'mode': mode, 'action': self.action, 'new_page': str(page_no + 1), 'new_letter': letter, 'foldername': self.action}
         elif self.action == ('trakt_tv_mosts'):
             for item in function(params['period'], params['duration'], page_no): self.list.append((get_trakt_tvshow_id(item['show']['ids'])))
             self.new_page = {'mode': mode, 'action': self.action, 'period': params['period'], 'duration': params['duration'], 'new_page': str(page_no + 1), 'foldername': self.action}
         elif self.action == 'tmdb_tv_genres':
             genre_id = params['genre_id'] if 'genre_id' in params else self.multiselect_genres(params.get('genre_list'))
             if not genre_id: return
             data = function(genre_id, page_no)
             self.list = [i['id'] for i in data['results']]
             if data['page'] < data['total_pages']: self.new_page = {'mode': mode, 'action': self.action, 'new_page': str(data['page'] + 1), 'genre_id': genre_id, 'foldername': genre_id}
         elif self.action == 'tmdb_tv_languages':
             language = params['language']
             if not language: return
             data = function(language, page_no)
             self.list = [i['id'] for i in data['results']]
             if data['page'] < data['total_pages']: self.new_page = {'mode': mode, 'action': self.action, 'new_page': str(data['page'] + 1), 'language': language, 'foldername': language}
         elif self.action == 'tmdb_tv_networks':
             data = function(params['network_id'], page_no)
             self.list = [i['id'] for i in data['results']]
             if data['page'] < data['total_pages']: self.new_page = {'mode': mode, 'action': self.action, 'new_page': str(data['page'] + 1), 'network_id': params['network_id'], 'foldername': params['network_id']}
         elif self.action == 'trakt_tv_certifications':
             for item in function(params['certification'], page_no): self.list.append((get_trakt_tvshow_id(item['show']['ids'])))
             self.new_page = {'mode': mode, 'action': self.action, 'new_page': str(page_no + 1), 'foldername': params['certification'], 'certification': params['certification']}
         elif self.action == 'tmdb_tv_year':
             data = function(params['year'], page_no)
             self.list = [i['id'] for i in data['results']]
             if data['page'] < data['total_pages']: self.new_page = {'mode': mode, 'action': self.action, 'new_page': str(page_no + 1), 'year': params['year'], 'foldername': params['year']}
         elif self.action in ('in_progress_tvshows', 'favourites_tvshows', 'subscriptions_tvshows', 'kodi_library_tvshows', 'watched_tvshows'):
             (var_module, import_function) = ('in_progress', 'in_progress_tvshow') if 'in_progress' in self.action else ('favourites', 'retrieve_favourites') if 'favourites' in self.action else ('subscriptions', 'retrieve_subscriptions') if 'subscriptions' in self.action else ('indicators_bookmarks', 'get_watched_items') if 'watched' in self.action else ('kodi_library', 'retrieve_kodi_library') if 'library' in self.action else ''
             try:
                 module = 'modules.%s' % (var_module)
                 function = getattr(importlib.import_module(module), import_function)
             except: pass
             if self.action == 'kodi_library_tvshows': self.id_type = 'tvdb_id'
             data, total_pages = function('tvshow', page_no, letter)
             self.list = [i['media_id'] for i in data]
             if total_pages > 2: self.total_pages = total_pages
             if total_pages > page_no: self.new_page = {'mode': mode, 'action': self.action, 'new_page': str(page_no + 1), 'new_letter': letter, 'foldername': self.action}
         elif self.action in ('tmdb_tv_similar', 'tmdb_tv_recommendations'):
             self.sim_recom_name = params['sim_recom_name']
             self.sim_recom_tmdb = params['sim_recom_tmdb']
             data = function(self.sim_recom_tmdb, page_no)
             self.list = [i['id'] for i in data['results']]
             if data['page'] < data['total_pages']: self.new_page = {'mode': mode, 'action': self.action, 'new_page': str(data['page'] + 1), 'sim_recom_name': self.sim_recom_name, 'sim_recom_tmdb': self.sim_recom_tmdb, 'foldername': self.action}
         elif self.action == 'trakt_recommendations':
             for item in function('shows'): self.list.append(get_trakt_tvshow_id(item['ids']))
         elif self.action == 'tmdb_popular_people':
             import os
             worker = False
             icon_directory = settings.get_theme()
             data = function(page_no)
             content_type = 'addons'
             fanart = __addon__.getAddonInfo('fanart')
             for item in data['results']:
                 cm = []
                 actor_poster = "http://image.tmdb.org/t/p/original%s" % item['profile_path'] if item['profile_path'] else os.path.join(icon_directory, 'genre_family.png')
                 url_params = {'mode': 'people_search.main', 'actor_id': item['id'], 'actor_name': item['name'], 'actor_image': actor_poster.replace('w185', 'h632')}
                 cm.append(("[B]Extended Info[/B]", 'RunScript(script.extendedinfo,info=extendedactorinfo,id=%s)' % item['id']))
                 url = build_url(url_params)
                 listitem = xbmcgui.ListItem(item['name'])
                 listitem.setArt({'icon': actor_poster, 'poster': actor_poster, 'thumb': actor_poster, 'fanart': fanart, 'banner': actor_poster})
                 listitem.addContextMenuItems(cm)
                 xbmcplugin.addDirectoryItem(__handle__, url, listitem, isFolder=True)
             if data['page'] < data['total_pages']: self.new_page = {'mode': mode, 'action': self.action, 'new_page': str(int(data['page']) + 1), 'foldername': self.action}
         elif self.action == 'tmdb_tv_search':
             try: from urllib import unquote
             except ImportError: from urllib.parse import unquote
             if params.get('query') == 'NA':
                 search_title = dialog.input("Search Fen", type=xbmcgui.INPUT_ALPHANUM)
                 search_name = unquote(search_title)
             else: search_name = unquote(params.get('query'))
             if not search_name: return
             params['search_name'] = search_name
             data = function(search_name, page_no)
             total_pages = data['total_pages']
             if total_pages > page_no: self.new_page = {'mode': mode, 'action': self.action, 'new_page': str(page_no + 1), 'query': search_name, 'foldername': search_name}
             self.list = [i['id'] for i in data['results']]
         if self.total_pages and not is_widget:
             url_params = {'mode': 'build_navigate_to_page', 'db_type': 'TV Shows', 'current_page': page_no, 'total_pages': self.total_pages, 'transfer_mode': mode, 'transfer_action': self.action, 'foldername': self.action, 'query': params.get('search_name', ''), 'actor_id': params.get('actor_id', '')}
             self.add_dir(url_params, 'Jump To...', 'Jump To a Certain Page/Letter...', 'item_jump.png')
         if cache_page: cached_page(self.cache_page_string, page_no=page_no)
         if worker: self.worker()
         if self.new_page: self.add_dir(self.new_page)
     except: pass
     xbmcplugin.setContent(__handle__, content_type)
     xbmcplugin.endOfDirectory(__handle__)
     if params.get('refreshed') == 'true': xbmc.sleep(1500)
     setView('view.tvshows', content_type)
Ejemplo n.º 7
0
def subscriptions_update_list():
    def _get_trakt_list_contents(db_type, item):
        append_list = trakt_movie_list_contents if db_type in (
            'movie', 'movies') else trakt_tvshow_list_contents
        try:
            if item['name'].lower() == 'none': return append_list
            if item['name'] in ('Collection', 'Watchlist'):
                from modules.trakt_cache import clear_trakt_collection_watchlist_data
                from apis.trakt_api import trakt_fetch_collection_watchlist
                clear_trakt_collection_watchlist_data(item['name'].lower(),
                                                      db_type)
                list_contents = trakt_fetch_collection_watchlist(
                    item['name'].lower(), db_type)
            else:
                from apis.trakt_api import get_trakt_list_contents
                from modules.trakt_cache import clear_trakt_list_contents_data
                trakt_dbtype = 'movie' if db_type in ('movie',
                                                      'movies') else 'show'
                clear_trakt_list_contents_data(user=item['user'],
                                               list_slug=item['slug'])
                list_contents = get_trakt_list_contents(
                    item['user'], item['slug'])
                list_contents = [{
                    'media_ids': i[trakt_dbtype]['ids'],
                    'title': i[trakt_dbtype]['title']
                } for i in list_contents if i['type'] == trakt_dbtype]
            append_list.extend(list_contents)
        except:
            return append_list

    close_all_dialog()
    dialog = xbmcgui.DialogProgressBG()
    dialog.create('Please Wait', 'Preparing for Subscription Update...')
    trakt_dbtype = ('movie', 'show')
    main_setting = ('trakt.subscriptions_movie', 'trakt.subscriptions_show')
    display_setting = ('trakt.subscriptions_movie_display',
                       'trakt.subscriptions_show_display')
    trakt_movie_list_contents = []
    trakt_tvshow_list_contents = []
    update_movies, update_tvshows, movies_added, tvshows_added, movies_removed, tvshows_removed = (
        False for _ in range(6))
    movie_subscriptions_object = Subscriptions('movie')
    tvshow_subscriptions_object = Subscriptions('tvshow')
    movie_subscriptions = movie_subscriptions_object.get_subscriptions()
    tvshow_subscriptions = tvshow_subscriptions_object.get_subscriptions()
    try:
        movie_list = json.loads(__addon__.getSetting(main_setting[0]))
    except:
        movie_list = []
    try:
        tvshow_list = json.loads(__addon__.getSetting(main_setting[1]))
    except:
        tvshow_list = []
    movie_list_name = __addon__.getSetting(display_setting[0])
    tvshow_list_name = __addon__.getSetting(display_setting[1])
    for i in [('movies', movie_list), ('shows', tvshow_list)]:
        _get_trakt_list_contents(i[0], i[1])
    trakt_movie_compare_contents = sorted([
        str(get_trakt_movie_id(i['media_ids']))
        for i in trakt_movie_list_contents
    ])
    subscriptions_movie_compare_contents = sorted(
        [str(i['media_id']) for i in movie_subscriptions])
    trakt_tvshow_compare_contents = sorted([
        str(get_trakt_tvshow_id(i['media_ids']))
        for i in trakt_tvshow_list_contents
    ])
    subscriptions_tvshow_compare_contents = sorted(
        [str(i['media_id']) for i in tvshow_subscriptions])
    if not trakt_movie_compare_contents == subscriptions_movie_compare_contents:
        if len(trakt_movie_compare_contents) > 0: update_movies = True
    if not trakt_tvshow_compare_contents == subscriptions_tvshow_compare_contents:
        if len(trakt_tvshow_compare_contents) > 0: update_tvshows = True
    if any([update_movies, update_tvshows]):

        def _process_additions(db_type, ids, count, list_length, path, dialog):
            if db_type in ('movie', 'movies'):
                movie_subscriptions_object.add_trakt_subscription_listitem(
                    db_type, ids, count, list_length, path, dialog)
            else:
                tvshow_subscriptions_object.add_trakt_subscription_listitem(
                    db_type, ids, count, list_length, path, dialog)

        def _process_removals(db_type, ids, count, list_length, path, dialog):
            if db_type in ('movie', 'movies'):
                movie_subscriptions_object.remove_trakt_subscription_listitem(
                    db_type, ids, count, list_length, path, dialog)
            else:
                tvshow_subscriptions_object.remove_trakt_subscription_listitem(
                    db_type, ids, count, list_length, path, dialog)

        def _process_additions_removals(db_type, action, list_contents):
            function = _process_additions if action == 'add' else _process_removals
            media_id_key = 'media_ids' if action == 'add' else 'media_id'
            dialog_db = '[B]Movies[/B]' if db_type in (
                'movie', 'movies') else '[B]TV Shows[/B]'
            dialog_line2 = 'Adding [B]%s[/B] %s' if action == 'add' else 'Removing [B]%s[/B] %s'
            path = settings.movies_directory() if db_type in (
                'movie', 'movies') else settings.tv_show_directory()
            threads = []
            list_length = len(list_contents)
            dialog.update(0, dialog_db,
                          dialog_line2 % (list_length, dialog_db))
            for count, item in enumerate(list_contents, 1):
                function(db_type, item[media_id_key], count, list_length, path,
                         dialog)

        if update_movies:
            add_to_subscriptions = [
                i for i in trakt_movie_compare_contents
                if not i in subscriptions_movie_compare_contents
            ]
            remove_from_subscriptions = [
                i for i in subscriptions_movie_compare_contents
                if not i in trakt_movie_compare_contents
            ]
            if len(add_to_subscriptions) > 0:
                movies_added = True
                list_contents = [
                    i for i in trakt_movie_list_contents
                    if str(i['media_ids']['tmdb']) in add_to_subscriptions
                ]
                _process_additions_removals('movies', 'add', list_contents)
            xbmc.sleep(1500)
            if len(remove_from_subscriptions) > 0:
                movies_removed = True
                list_contents = [
                    i for i in movie_subscriptions
                    if str(i['media_id']) in remove_from_subscriptions
                ]
                _process_additions_removals('movies', 'remove', list_contents)
        if update_tvshows:
            add_to_subscriptions = [
                i for i in trakt_tvshow_compare_contents
                if not i in subscriptions_tvshow_compare_contents
            ]
            remove_from_subscriptions = [
                i for i in subscriptions_tvshow_compare_contents
                if not i in trakt_tvshow_compare_contents
            ]
            if len(add_to_subscriptions) > 0:
                tvshows_added = True
                list_contents = [
                    i for i in trakt_tvshow_list_contents
                    if str(i['media_ids']['tmdb']) in add_to_subscriptions
                ]
                _process_additions_removals('tvshows', 'add', list_contents)
            xbmc.sleep(1500)
            if len(remove_from_subscriptions) > 0:
                tvshows_removed = True
                list_contents = [
                    i for i in tvshow_subscriptions
                    if str(i['media_id']) in remove_from_subscriptions
                ]
                _process_additions_removals('tvshows', 'remove', list_contents)
    dialog.update(100, 'Please Wait..', 'Finished Syncing Subscriptions')
    xbmc.sleep(1500)
    dialog.close()
    tvshow_subscriptions_object.update_subscriptions(suppress_extras=True)
    if settings.clean_library_after_service():
        if any([movies_removed, tvshows_removed]):
            import time
            xbmc.executebuiltin('CleanLibrary(video)')
            time.sleep(3)
            while xbmc.getCondVisibility("Window.IsVisible(ProgressDialog)"):
                time.sleep(1)
        else:
            notification('Nothing Removed. Skipping Clean', 4500)
    if settings.update_library_after_service():
        return xbmc.executebuiltin('UpdateLibrary(video)')
    return
Ejemplo n.º 8
0
def subscriptions_add_list(db_type):
    from modules.trakt_cache import clear_trakt_list_data
    from apis.trakt_api import get_trakt_list_selection
    from modules.nav_utils import show_busy_dialog, hide_busy_dialog, open_settings
    movie_subscriptions = Subscriptions('movie')
    tvshow_subscriptions = Subscriptions('tvshow')
    variables = ('Movies', 'movies', 'movie', 'trakt.subscriptions_movie',
                 'trakt.subscriptions_movie_display', '8.14',
                 movie_subscriptions) if db_type == 'movie' else (
                     'TV Shows', 'shows', 'show', 'trakt.subscriptions_show',
                     'trakt.subscriptions_show_display', '8.15',
                     tvshow_subscriptions)
    dialog_display = variables[0]
    trakt_list_type = variables[1]
    trakt_dbtype = variables[2]
    main_setting = variables[3]
    display_setting = variables[4]
    open_setting = variables[5]
    subscription_function = variables[6]
    clear_library, cancelled, supplied_list = (False for _ in range(3))
    path = settings.movies_directory(
    ) if db_type == 'movie' else settings.tv_show_directory()
    if xbmcgui.Dialog().yesno(
            'Fen Subscriptions',
            'Are you sure you have set your Fen [B]%s[/B] Subscription Folder as a Source for the Kodi Library?'
            % db_type.upper(), '', '', 'Already Done', 'I\'ll Do It Now'):
        return xbmc.executebuiltin('ActivateWindow(videos,files,return)')
    for i in ('my_lists', 'liked_lists'):
        try:
            clear_trakt_list_data(i)
        except:
            pass
    trakt_list = get_trakt_list_selection(list_choice='subscriptions')
    if not trakt_list: return open_settings(open_setting)
    __addon__.setSetting(main_setting, json.dumps(trakt_list))
    __addon__.setSetting(display_setting, trakt_list['name'])
    if trakt_list['name'].lower() == 'none': return open_settings(open_setting)
    if not xbmcgui.Dialog().yesno(
            'Are you sure?',
            'Fen will add all [B]%s[/B] from [B]%s[/B] to your Fen Subscriptions, and monitor this list for changes. Do you wish to continue?'
            % (dialog_display, trakt_list['name'])):
        __addon__.setSetting(main_setting, '')
        __addon__.setSetting(display_setting, 'none')
        return open_settings(open_setting)
    current_subscriptions = subscription_function.get_subscriptions()
    if len(current_subscriptions) > 0:
        if not xbmcgui.Dialog().yesno(
                'Current Subscriptions Found!',
                'You have items in your [B]%s[/B] Subscription. Fen will delete these before continuing (may take some time). Do you wish to continue?'
                % (dialog_display)):
            return open_settings(open_setting)
        clear_library = True
        show_busy_dialog()
        subscription_function.clear_subscriptions(confirm=False,
                                                  silent=True,
                                                  db_type=db_type)
        hide_busy_dialog()
    dialog = xbmcgui.DialogProgressBG()
    dialog.create('Please Wait', 'Preparing Trakt List Info...')
    if trakt_list['name'] in ('Collection', 'Watchlist'):
        from modules.trakt_cache import clear_trakt_collection_watchlist_data
        from apis.trakt_api import trakt_fetch_collection_watchlist
        list_contents = trakt_fetch_collection_watchlist(
            trakt_list['name'].lower(), trakt_list_type)
    else:
        from apis.trakt_api import get_trakt_list_contents
        from modules.trakt_cache import clear_trakt_list_contents_data
        list_contents = get_trakt_list_contents(trakt_list['user'],
                                                trakt_list['slug'])
        list_contents = [{
            'media_ids': i[trakt_dbtype]['ids'],
            'title': i[trakt_dbtype]['title']
        } for i in list_contents if i['type'] == trakt_dbtype]
    for i in list_contents:
        if i['media_ids']['tmdb'] == None:
            i['media_ids']['tmdb'] = get_trakt_tvshow_id(i['media_ids'])
    threads = []
    list_length = len(list_contents)
    for count, item in enumerate(list_contents, 1):
        subscription_function.add_trakt_subscription_listitem(
            db_type, item['media_ids'], count, list_length, path, dialog)
    dialog.close()
    end_dialog = 'Operation Cancelled! Not all items from [B]%s[/B] were added.' if cancelled else '[B]%s[/B] added to Subscriptions.'
    xbmcgui.Dialog().ok('Fen Subscriptions', end_dialog % trakt_list['name'])
    if clear_library:
        if xbmcgui.Dialog().yesno(
                'Fen Subscriptions',
                'Do you wish to clear Kodi\'s Library of your previous Subscription items?'
        ):
            import time
            xbmc.executebuiltin('CleanLibrary(video)')
            time.sleep(3)
            while xbmc.getCondVisibility("Window.IsVisible(ProgressDialog)"):
                time.sleep(1)
    if xbmcgui.Dialog().yesno(
            'Fen Subscriptions',
            'Do you wish to scan your new Subscription list into Kodi\'s Library?'
    ):
        xbmc.executebuiltin('UpdateLibrary(video)')