diff --git a/core/scrapertools.py b/core/scrapertools.py index 8961dfef..1d5b5f2e 100644 --- a/core/scrapertools.py +++ b/core/scrapertools.py @@ -451,7 +451,7 @@ def get_season_and_episode(title): except: pass - logger.debug("'" + title + "' -> '" + filename + "'") + logger.debug(title, ' -> ', filename) return filename diff --git a/core/support.py b/core/support.py index 92fcbc14..c26a5179 100755 --- a/core/support.py +++ b/core/support.py @@ -1208,7 +1208,7 @@ def server(item, data='', itemlist=[], headers='', AutoPlay=True, CheckLinks=Tru item.title = typo(item.contentTitle.strip(), 'bold') if item.contentType == 'movie' and item.contentTitle or (config.get_localized_string(30161) in item.fulltitle) else item.fulltitle quality = videoitem.quality if videoitem.quality else item.quality if item.quality else '' - videoitem.contentLanguage = videoitem.contentLanguage if videoitem.contentLanguage else item.contentLanguage + videoitem.contentLanguage = videoitem.contentLanguage if videoitem.contentLanguage else item.contentLanguage if item.contentLanguage else 'ITA' videoitem.title = (item.title if item.channel not in ['url'] else '')\ + (typo(videoitem.title, '_ color kod [] bold') if videoitem.title else "")\ + (typo(videoitem.quality, '_ color kod []') if videoitem.quality else "")\ diff --git a/core/videolibrarytools.py b/core/videolibrarytools.py index e0e33dd3..9688600d 100644 --- a/core/videolibrarytools.py +++ b/core/videolibrarytools.py @@ -396,7 +396,6 @@ def save_tvshow(item, episodelist, silent=False): return 0, 0, -1, path # set base name - base_name = set_base_name(item, _id) path = filetools.join(TVSHOWS_PATH, base_name) @@ -488,7 +487,7 @@ def save_tvshow(item, episodelist, silent=False): return inserted, overwritten, failed, path -def save_episodes(item, episodelist, extra_info, host, silent=False, overwrite=True): +def save_episodes(item, episodelist, extra_info, host, silent=False): """ saves in the indicated path all the chapters included in the episodelist @type Item: str @@ -509,20 +508,24 @@ def save_episodes(item, episodelist, extra_info, host, silent=False, overwrite=T @return: the number of failed episodes """ # support.dbg() - def save_episode(item, seasons, current_seasons, episodes, e, inserted, overwritten, failed): + def save_episode(item, episodes, e): + inserted = 0 + overwritten = 0 + failed = 0 + episode = None + season_episode = None + season_episode = scrapertools.get_season_and_episode(e.title) if season_episode: - # local = True if season_episode in included_files else False - # if local: - # strm_path = filetools.join(item.base_name, included_files[season_episode]) - # else: strm_path = filetools.join(item.base_name, "{}.strm".format(season_episode)) - nfo_path = filetools.join(item.base_name, "{}.nfo".format(season_episode)) e.contentSeason = int(season_episode.split('x')[0]) e.contentEpisodeNumber = int(season_episode.split('x')[1]) + if item.infoLabels.get('imdb_id'): e.infoLabels['imdb_id'] = item.infoLabels['imdb_id'] + if item.infoLabels.get('tmdb_id'): e.infoLabels['tmdb_id'] = item.infoLabels['tmdb_id'] + if item.infoLabels.get('tvdb_id'): e.infoLabels['tvdb_id'] = item.infoLabels['tvdb_id'] tmdb.set_infoLabels_item(e) if not e.infoLabels.get('playcount'): e.infoLabels['playcount'] = 0 @@ -544,40 +547,6 @@ def save_episodes(item, episodelist, extra_info, host, silent=False, overwrite=T episode = episodes.get(season_episode, {}) try: - if e.contentSeason not in current_seasons: - tmdb_info = tmdb.Tmdb(id_Tmdb = e.infoLabels['tmdb_id'], search_type='tv') - seasoninfo = tmdb.get_season_dic(tmdb_info.get_season(e.contentSeason)) - infoLabels = {} - - if seasoninfo.get('season_posters'): infoLabels['posters'] = seasoninfo.get('season_posters') + extra_info['poster'].get(str(e.contentSeason), []) - if seasoninfo.get('season_fanarts'): infoLabels['fanarts'] = seasoninfo.get('season_fanarts') + extra_info['fanart'].get(str(e.contentSeason), []) - if seasoninfo.get('season_trailer'): infoLabels['trailer'] = seasoninfo.get('season_trailer') - infoLabels['landscapes'] = extra_info['landscape'].get(str(e.contentSeason), []) - infoLabels['banners'] = extra_info['banner'].get(str(e.contentSeason), []) - infoLabels['clearlogos'] = item.infoLabels.get('clearlogos', []) - infoLabels['cleararts'] = item.infoLabels.get('cleararts', []) - if e.contentSeason in seasons: infoLabels['playcount'] = seasons[e.contentSeason].infoLabels.get('playcount', 0) - - season_item = Item(action="get_episodes", - channel='videolibrary', - title=seasoninfo.get('season_title'), - thumbnail = seasoninfo.get('season_poster') if seasoninfo.get('season_poster') else item.thumbnail, - fanart = item.fanart, - plot = seasoninfo.get('season_plot') if seasoninfo.get('season_plot') else item.infoLabels.get('plot'), - contentType = 'season', - infoLabels = infoLabels, - contentSeason = e.contentSeason, - videolibrary_id = item.videolibrary_id, - playcount=0) - - if infoLabels['clearlogos']: season_item.clearlogo = infoLabels['clearlogos'][0] - if infoLabels['cleararts']: season_item.clearart = infoLabels['cleararts'][0] - if infoLabels['landscapes']: season_item.landscape = infoLabels['landscapes'][0] - if infoLabels['banners']: season_item.banner = infoLabels['banners'][0] - - seasons[e.contentSeason] = season_item - current_seasons.append(e.contentSeason) - if not episode: inserted += 1 episode['item'] = episode_item @@ -589,7 +558,9 @@ def save_episodes(item, episodelist, extra_info, host, silent=False, overwrite=T remove_host(e) e.contentTitle = e.infoLabels['title'] + contentType = e.contentType e.infoLabels = {} + e.contentType = contentType if e.channel in epchannels and e.channel != 'download': channels_url = [u.url for u in epchannels[e.channel]] @@ -603,7 +574,6 @@ def save_episodes(item, episodelist, extra_info, host, silent=False, overwrite=T epchannels[e.channel] = [e] episode['channels'] = epchannels - episodes[season_episode] = episode if not filetools.exists(filetools.join(TVSHOWS_PATH, strm_path)): logger.debug("Creating .strm: " + strm_path) @@ -612,8 +582,43 @@ def save_episodes(item, episodelist, extra_info, host, silent=False, overwrite=T # if not filetools.exists(filetools.join(TVSHOWS_PATH, nfo_path)): # filetools.write(filetools.join(TVSHOWS_PATH, nfo_path), head_nfo) except: + logger.error(traceback.format_exc()) failed += 1 - return item, seasons, episodes, e, inserted, overwritten, failed + return item, episode, season_episode, e.contentLanguage, inserted, overwritten, failed + + def save_season(item, seasons, s): + tmdb_info = tmdb.Tmdb(id_Tmdb = item.infoLabels['tmdb_id'], search_type='tv') + seasoninfo = tmdb.get_season_dic(tmdb_info.get_season(s)) + infoLabels = {} + + if seasoninfo.get('season_posters'): infoLabels['posters'] = seasoninfo.get('season_posters') + extra_info['poster'].get(str(s), []) + if seasoninfo.get('season_fanarts'): infoLabels['fanarts'] = seasoninfo.get('season_fanarts') + extra_info['fanart'].get(str(s), []) + if seasoninfo.get('season_trailer'): infoLabels['trailer'] = seasoninfo.get('season_trailer') + infoLabels['landscapes'] = extra_info['landscape'].get(str(s), []) + infoLabels['banners'] = extra_info['banner'].get(str(s), []) + infoLabels['clearlogos'] = item.infoLabels.get('clearlogos', []) + infoLabels['cleararts'] = item.infoLabels.get('cleararts', []) + if s in seasons: infoLabels['playcount'] = seasons[s].infoLabels.get('playcount', 0) + + season_item = Item(action="get_episodes", + channel='videolibrary', + title=seasoninfo.get('season_title'), + thumbnail = seasoninfo.get('season_poster') if seasoninfo.get('season_poster') else item.thumbnail, + fanart = item.fanart, + plot = seasoninfo.get('season_plot') if seasoninfo.get('season_plot') else item.infoLabels.get('plot'), + contentType = 'season', + infoLabels = infoLabels, + contentSeason = s, + videolibrary_id = item.videolibrary_id, + playcount=0) + + if infoLabels['clearlogos']: season_item.clearlogo = infoLabels['clearlogos'][0] + if infoLabels['cleararts']: season_item.clearart = infoLabels['cleararts'][0] + if infoLabels['landscapes']: season_item.landscape = infoLabels['landscapes'][0] + if infoLabels['banners']: season_item.banner = infoLabels['banners'][0] + + return s, season_item + logger.debug() # from core import tmdb @@ -640,23 +645,37 @@ def save_episodes(item, episodelist, extra_info, host, silent=False, overwrite=T # support.dbg() # for i, e in enumerate(episodelist): - # item, seasons, episodes, e, inserted, overwritten, failed = save_episode(item, seasons, current_seasons, episodes, e, inserted, overwritten, failed) - # if not e.contentLanguage: e.contentLanguage = item.contentLanguage if item.contentLanguage else 'ITA' - # if not e.contentLanguage in item.lang_list: item.lang_list.append(e.contentLanguage) - # if not silent: - # p_dialog.update(int(math.ceil((i + 1) * t)), e.title) + # item, seasons, episodes, e, inserted, overwritten, failed = save_episode(item, episodes, e) + # if not e.contentLanguage: e.contentLanguage = item.contentLanguage if item.contentLanguage else 'ITA' + # if not e.contentLanguage in item.lang_list: item.lang_list.append(e.contentLanguage) + # if not silent: + # p_dialog.update(int(math.ceil((i + 1) * t)), e.title) i = 0 with futures.ThreadPoolExecutor() as executor: - itlist = [executor.submit(save_episode, item, seasons, current_seasons, episodes, e, inserted, overwritten, failed) for e in episodelist] + itlist = [executor.submit(save_episode, item, episodes, e) for e in episodelist] for res in futures.as_completed(itlist): if res.result(): - item, seasons, episodes, e, inserted, overwritten, failed = res.result() - if not e.contentLanguage: e.contentLanguage = item.contentLanguage if item.contentLanguage else 'ITA' - if not e.contentLanguage in item.lang_list: item.lang_list.append(e.contentLanguage) - if not silent: - i += 1 - p_dialog.update(int(math.ceil(i * t)), e.title) + item, episode, season_episode, lang, I, O, F = res.result() + inserted += I + overwritten += O + failed += F + if episode: + episodes[season_episode] = episode + e = episode['item'] + if not e.contentSeason in current_seasons: current_seasons.append(e.contentSeason) + if not lang: lang = item.contentLanguage if item.contentLanguage else 'ITA' + if not lang in item.lang_list: item.lang_list.append(lang) + if not silent: + i += 1 + p_dialog.update(int(math.ceil(i * t)), message=e.title) + + with futures.ThreadPoolExecutor() as executor: + itlist = [executor.submit(save_season, item, seasons, s) for s in current_seasons] + for res in futures.as_completed(itlist): + if res.result(): + s, season_item = res.result() + seasons[s] = season_item if not silent: if len(item.lang_list) > 1: @@ -882,6 +901,7 @@ def add_tvshow(item, channel=None): global magnet_caching magnet_caching = False + inserted, overwritten, failed, path = save_tvshow(item, itemlist) if not path: diff --git a/platformcode/platformtools.py b/platformcode/platformtools.py index 171788ac..c15b1c63 100644 --- a/platformcode/platformtools.py +++ b/platformcode/platformtools.py @@ -278,11 +278,11 @@ def dialog_select_group(heading, _list, preselect=0): return dialog -def itemlist_refresh(): +def itemlist_refresh(offset=0): win = xbmcgui.Window(xbmcgui.getCurrentWindowId()) cid = win.getFocusId() ctl = win.getControl(cid) - pos = Item().fromurl(xbmc.getInfoLabel('ListItem.FileNameAndPath')).itemlistPosition + pos = Item().fromurl(xbmc.getInfoLabel('ListItem.FileNameAndPath')).itemlistPosition + offset xbmc.executebuiltin("Container.Refresh") @@ -503,29 +503,20 @@ def set_infolabels(listitem, item, player=False): @type item: item """ - infoLabels_dict = {'aired': 'aired', 'album': 'album', 'artist': 'artist', 'cast': 'cast', - 'castandrole': 'castandrole', 'tmdb_id': 'code', 'code': 'code', 'country': 'country', - 'credits': 'credits', 'release_date': 'dateadded', 'dateadded': 'dateadded', 'dbid': 'dbid', - 'director': 'director', 'duration': 'duration', 'episode': 'episode', - 'episodio_sinopsis': 'episodeguide', 'episodio_air_date': 'None', 'episodio_imagen': 'None', - 'episodio_titulo': 'title', 'episodio_vote_average': 'rating', 'episodio_vote_count': 'votes', - 'fanart': 'None', 'genre': 'genre', 'homepage': 'None', 'imdb_id': 'imdbnumber', - 'imdbnumber': 'imdbnumber', 'in_production': 'None', 'last_air_date': 'lastplayed', - 'mediatype': 'mediatype', 'mpaa': 'mpaa', 'number_of_episodes': 'None', - 'number_of_seasons': 'None', 'original_language': 'None', 'originaltitle': 'originaltitle', - 'overlay': 'overlay', 'poster_path': 'path', 'popularity': 'None', 'playcount': 'playcount', - 'plot': 'plot', 'plotoutline': 'plotoutline', 'premiered': 'premiered', 'quality': 'None', - 'rating': 'rating', 'season': 'season', 'set': 'set', 'setid': 'setid', - 'setoverview': 'setoverview', 'showlink': 'showlink', 'sortepisode': 'sortepisode', - 'sortseason': 'sortseason', 'sorttitle': 'sorttitle', 'status': 'status', 'studio': 'studio', - 'tag': 'tag', 'tagline': 'tagline', 'temporada_air_date': 'None', 'temporada_nombre': 'None', - 'temporada_num_episodios': 'None', 'temporada_poster': 'None', 'title': 'title', - 'top250': 'top250', 'tracknumber': 'tracknumber', 'trailer': 'trailer', 'thumbnail': 'None', - 'tvdb_id': 'None', 'tvshowtitle': 'tvshowtitle', 'type': 'None', 'userrating': 'userrating', - 'url_scraper': 'None', 'votes': 'votes', 'writer': 'writer', 'year': 'year'} + infoLabels_dict = {'aired': 'aired', 'album': 'album', 'artist': 'artist', 'cast': 'cast', 'castandrole': 'castandrole', + 'tmdb_id': 'code', 'code': 'code', 'country': 'country', 'credits': 'credits', 'release_date': 'dateadded', + 'dateadded': 'dateadded', 'dbid': 'dbid', 'director': 'director', 'duration': 'duration', 'episode': 'episode', + 'episode_plot': 'episodeguide', 'episode_title': 'title', 'episode_vote_average': 'rating', 'episode_vote_count': 'votes', + 'genre': 'genre', 'imdb_id': 'imdbnumber', 'imdbnumber': 'imdbnumber', 'last_air_date': 'lastplayed', 'mediatype': 'mediatype', + 'mpaa': 'mpaa', 'originaltitle': 'originaltitle', 'overlay': 'overlay', 'poster_path': 'path', 'playcount': 'playcount', + 'plot': 'plot', 'plotoutline': 'plotoutline', 'premiered': 'premiered', 'rating': 'rating', 'season': 'season', 'set': 'set', + 'setid': 'setid', 'setoverview': 'setoverview', 'showlink': 'showlink', 'sortepisode': 'sortepisode', 'sortseason': 'sortseason', + 'sorttitle': 'sorttitle', 'status': 'status', 'studio': 'studio', 'tag': 'tag', 'tagline': 'tagline', 'title': 'title', + 'top250': 'top250', 'tracknumber': 'tracknumber', 'trailer': 'trailer', 'tvshowtitle': 'tvshowtitle', 'userrating': 'userrating', + 'votes': 'votes', 'writer': 'writer', 'year': 'year'} # if item.infoLabels: try: - infoLabels_kodi = {infoLabels_dict[label_tag]: item.infoLabels[label_tag] for label_tag, label_value in list(item.infoLabels.items()) if infoLabels_dict[label_tag] != 'None' and label_tag in infoLabels_dict} + infoLabels_kodi = {infoLabels_dict[label_tag]: item.infoLabels[label_tag] for label_tag, label_value in list(item.infoLabels.items()) if label_tag in infoLabels_dict} listitem.setInfo("video", infoLabels_kodi) except: listitem.setInfo("video", item.infoLabels) diff --git a/platformcode/xbmc_videolibrary.py b/platformcode/xbmc_videolibrary.py index ead4129b..c03ef8d9 100644 --- a/platformcode/xbmc_videolibrary.py +++ b/platformcode/xbmc_videolibrary.py @@ -263,6 +263,7 @@ def mark_content_as_watched_on_kodi(item, value=1): @param value: > 0 for seen, 0 for not seen """ logger.debug() + conn = sqlite3.connect(get_file_db()) view = 'episode' if item.contentType != 'movie' else 'movie' path = '%{}%'.format(item.strm_path.split('\\')[0].split('/')[0] if item.strm_path else item.base_name) @@ -272,13 +273,12 @@ def mark_content_as_watched_on_kodi(item, value=1): if item.contentEpisodeNumber: request_episode = ' and strFileName= "{}"'.format(item.strm_path.split('\\')[-1].split('/')[-1]) sql = 'select idFile from {}_view where strPath like "{}"{}{}'.format(view, path, request_episode, request_season) - n, r = execute_sql_kodi(sql) + n, r = execute_sql_kodi(sql, conn=conn) if r: sql = 'update files set playCount= {} where idFile= {}' sql_actions = [sql.format(value, i[0]) for i in r] - conn = sqlite3.connect(get_file_db()) - cursor = conn.cursor() + cursor = conn.cursor() for sql in sql_actions: if type(sql) == list: cursor.executemany(sql) @@ -286,36 +286,9 @@ def mark_content_as_watched_on_kodi(item, value=1): cursor.execute(sql) conn.commit() conn.close() + platformtools.itemlist_refresh() -def mark_season_as_watched_on_kodi(item, value=1): - """ - mark the entire season as seen or unseen in the Kodi library - @type item: item - @param item: element to mark - @type value: int - @param value: > 0 for seen, 0 for not seen - """ - logger.debug() - # support.dbg() - # logger.debug("item:\n" + item.tostring('\n')) - - # We can only mark the season as seen in the Kodi database if the database is local, in case of sharing database this functionality will not work - if config.get_setting("db_mode", "videolibrary"): - return - - if value == 0: - value = 'Null' - - request_season = '' - if item.contentSeason > -1: - request_season = ' and c12= %s' % item.contentSeason - - tvshows_path = filetools.join(config.config.get_videolibrary_config_path(), config.get_setting("folder_tvshows")) - - sql = 'update files set playCount= %s where idFile in (select idfile from episode_view where (strPath like "%s" or strPath like "%s")%s)' % (value, request_season) - - execute_sql_kodi(sql) def set_watched_on_kod(data): from specials import videolibrary @@ -380,8 +353,6 @@ def set_watched_on_kod(data): def mark_content_as_watched_on_kod(path): from specials import videolibrary from core import videolibrarytools - - """ mark the entire series or movie as viewed or unseen in the Alpha Video Library based on their status in the Kodi Video Library @type str: path diff --git a/service.py b/service.py index cf225499..da037205 100644 --- a/service.py +++ b/service.py @@ -115,175 +115,9 @@ def update(path, p_dialog, i, t, serie, overwrite): return insertados_total > 0 -def check_for_update(overwrite=True): - logger.debug("Update Series...") - p_dialog = None - serie_actualizada = False - update_when_finished = False - hoy = datetime.date.today() - estado_verify_playcount_series = False - - try: - if config.get_setting("update", "videolibrary") != 0 or overwrite: - config.set_setting("updatelibrary_last_check", hoy.strftime('%Y-%m-%d'), "videolibrary") - - heading = config.get_localized_string(60389) - p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), heading) - p_dialog.update(0, '') - show_list = [] - # show_ep_num = [] - - for path, folders, files in filetools.walk(videolibrarytools.TVSHOWS_PATH): - if 'tvshow.nfo' in files: - show_list.extend([filetools.join(path, f) for f in files if f == "tvshow.nfo"]) - # show_ep_num.append(len([f for f in files if f.endswith('.nfo') and f != 'tvshow.nfo'])) - - if show_list: - t = float(100) / len(show_list) - - for i, tvshow_file in enumerate(show_list): - head_nfo, serie = videolibrarytools.read_nfo(tvshow_file) - # ep_count = show_ep_num[i] + (len(serie.local_episodes_list) if serie.local_episodes_path else 0) - # if serie.infoLabels['status'].lower() == 'ended' and \ - # ep_count >= serie.infoLabels['number_of_episodes']: - # serie.active = 0 - # filetools.write(tvshow_file, head_nfo + serie.tojson()) - path = filetools.dirname(tvshow_file) - - logger.debug("serie=" + serie.contentSerieName) - - # Check the status of the series.library_playcounts of the Series in case it is incomplete - try: - estado = False - # If we have not done the verification or do not have a playcount, we enter - estado = config.get_setting("verify_playcount", "videolibrary") - if not estado or estado == False or not serie.library_playcounts: # If it hasn't happened before, we do it now - serie, estado = videolibrary.verify_playcount_series(serie, path) # Also happens if a PlayCount is missing completely - except: - logger.error(traceback.format_exc()) - else: - if estado: # If the update was successful ... - estado_verify_playcount_series = True # ... is checked to change the Video Library option - - try: - interval = int(serie.active) # Could be the bool type - except: - interval = 1 - - if not serie.active: - # if the series is not active discard - if not overwrite: - # Synchronize the episodes seen from the Kodi video library with that of Alpha, even if the series is deactivated - try: - if config.is_xbmc(): # If it's Kodi, we do it - from platformcode import xbmc_videolibrary - xbmc_videolibrary.mark_content_as_watched_on_kod(filetools.join(path,'tvshow.nfo')) - except: - logger.error(traceback.format_exc()) - - continue - - p_dialog.update(int(math.ceil((i + 1) * t)), heading, serie.contentSerieName) - - # Obtain the update date and the next scheduled for this series - update_next = serie.update_next - if update_next: - y, m, d = update_next.split('-') - update_next = datetime.date(int(y), int(m), int(d)) - else: - update_next = hoy - - update_last = serie.update_last - if update_last: - y, m, d = update_last.split('-') - update_last = datetime.date(int(y), int(m), int(d)) - else: - update_last = hoy - - # if the series is active ... - if overwrite or config.get_setting("updatetvshows_interval", "videolibrary") == 0: - # ... force update regardless of interval - serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) - if not serie_actualizada: - update_next = hoy + datetime.timedelta(days=interval) - - elif interval == 1 and update_next <= hoy: - # ...daily update - serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) - if not serie_actualizada and update_last <= hoy - datetime.timedelta(days=7): - # if it hasn't been updated for a week, change the interval to weekly - interval = 7 - update_next = hoy + datetime.timedelta(days=interval) - - elif interval == 7 and update_next <= hoy: - # ... weekly update - serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) - if not serie_actualizada: - if update_last <= hoy - datetime.timedelta(days=14): - # if it has not been updated for 2 weeks, change the interval to monthly - interval = 30 - - update_next += datetime.timedelta(days=interval) - - elif interval == 30 and update_next <= hoy: - # ... monthly update - serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) - if not serie_actualizada: - update_next += datetime.timedelta(days=interval) - - if serie_actualizada: - update_last = hoy - update_next = hoy + datetime.timedelta(days=interval) - - head_nfo, serie = videolibrarytools.read_nfo(tvshow_file) # Reread the .nfo, which has been modified - if interval != int(serie.active) or update_next.strftime('%Y-%m-%d') != serie.update_next or update_last.strftime('%Y-%m-%d') != serie.update_last: - serie.update_last = update_last.strftime('%Y-%m-%d') - if update_next > hoy: - serie.update_next = update_next.strftime('%Y-%m-%d') - serie.active = interval - serie.channel = "videolibrary" - serie.action = "get_seasons" - filetools.write(tvshow_file, head_nfo + serie.tojson()) - - if serie_actualizada: - if config.get_setting("search_new_content", "videolibrary") == 0: - # We update the Kodi video library: Find content in the series folder - if config.is_xbmc() and config.get_setting("videolibrary_kodi"): - from platformcode import xbmc_videolibrary - xbmc_videolibrary.update(folder=filetools.basename(path)) - else: - update_when_finished = True - - if estado_verify_playcount_series: # If any playcount has been changed, ... - estado = config.set_setting("verify_playcount", True, "videolibrary") # ... we update the Videolibrary option - - if config.get_setting("search_new_content", "videolibrary") == 1 and update_when_finished: - # We update the Kodi video library: Find content in all series - if config.is_xbmc() and config.get_setting("videolibrary_kodi"): - from platformcode import xbmc_videolibrary - xbmc_videolibrary.update() - - p_dialog.close() - - else: - logger.debug("Not update the video library, it is disabled") - - except Exception as ex: - logger.error("An error occurred while updating the series") - template = "An exception of type %s occured. Arguments:\n%r" - message = template % (type(ex).__name__, ex.args) - logger.error(message) - - if p_dialog: - p_dialog.close() - - from core.item import Item - item_dummy = Item() - videolibrary.list_movies(item_dummy, silent=True) - - if config.get_setting('trakt_sync'): - from core import trakt_tools - trakt_tools.update_all() +def check_for_update(): + if config.get_setting("update", "videolibrary"): + videolibrary.update_videolibrary() def updaterCheck(): diff --git a/specials/videolibrary.py b/specials/videolibrary.py index e99ea0f6..c869c87b 100644 --- a/specials/videolibrary.py +++ b/specials/videolibrary.py @@ -8,12 +8,13 @@ PY3 = False if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int import xbmc, os, traceback -from time import time from core import filetools, scrapertools, videolibrarytools -from core.support import typo, thumb, videolibrary +from core.support import typo, thumb from core.item import Item from platformcode import config, launcher, logger, platformtools +from core.videolibrarytools import videolibrarydb + if PY3: from concurrent import futures import urllib.parse as urlparse @@ -21,7 +22,7 @@ else: from concurrent_py2 import futures import urlparse -from core.videolibrarytools import videolibrarydb + def mainlist(item): @@ -31,7 +32,7 @@ def mainlist(item): category=config.get_localized_string(70270), thumbnail=thumb("videolibrary_movie")), Item(channel=item.channel, action="list_tvshows",title=config.get_localized_string(60600), category=config.get_localized_string(70271), thumbnail=thumb("videolibrary_tvshow"), - context=[{"channel":"videolibrary", "action":"update_videolibrary", "title":config.get_localized_string(70269)}]), + context=[{"channel":"videolibrary", "action":"update_videolibrary", "title":config.get_localized_string(70269), 'forced':True}]), Item(channel='shortcuts', action="SettingOnPosition", title=typo(config.get_localized_string(70287),'bold color kod'), category=2, setting=1, thumbnail = thumb("setting_0"),folder=False)] return itemlist @@ -197,7 +198,7 @@ def list_tvshows(item): itemlist = sorted(itemlist, key=lambda it: it.title.lower()) itemlist += [Item(channel=item.channel, action="update_videolibrary", thumbnail=item.thumbnail, - fanart=item.thumbnail, landscape=item.thumbnail, + fanart=item.thumbnail, landscape=item.thumbnail, forced=True, title=typo(config.get_localized_string(70269), 'bold color kod'), folder=False)] return itemlist @@ -471,15 +472,21 @@ def findvideos(item): else: videolibrary_items[key] = values + with futures.ThreadPoolExecutor() as executor: - itlist = [executor.submit(servers, ch, value) for ch, value in videolibrary_items.items() if ch not in disabled] + itlist = [executor.submit(servers, item, ch, value) for ch, value in videolibrary_items.items() if ch not in disabled] for res in futures.as_completed(itlist): itemlist += res.result() + pl = [s for s in itemlist if s.contentLanguage in [prefered_lang, '']] + if pl: itemlist = pl + + if len(itlist) > 1: for it in itemlist: it.title = '[{}] {}'.format(it.ch_name, it.title) + if autoplay.play_multi_channel(item, itemlist): # hideserver return [] @@ -489,12 +496,23 @@ def findvideos(item): return itemlist -def servers(ch, items): +def servers(item, ch, items): serverlist = [] from core import channeltools ch_params = channeltools.get_channel_parameters(ch) ch_name = ch_params.get('title', '') + def channel_servers(item, it, channel, ch_name): + serverlist = [] + it.contentChannel = 'videolibrary' + it = get_host(it, channel) + it.contentTitle = it.fulltitle = item.title + for item in getattr(channel, it.action)(it): + if item.server and item.channel: + item.ch_name = ch_name + serverlist.append(item) + return serverlist + if ch_params.get('active', False): if os.path.isfile(os.path.join(config.get_runtime_path(), 'channels', ch + ".py")): CHANNELS = 'channels' @@ -502,19 +520,10 @@ def servers(ch, items): try: channel = __import__('%s.%s' % (CHANNELS, ch), None, None, ['%s.%s' % (CHANNELS, ch)]) except ImportError: exec("import " + CHANNELS + "." + ch + " as channel") with futures.ThreadPoolExecutor() as executor: - itlist = [executor.submit(channel_servers, it, channel, ch_name) for it in items] + itlist = [executor.submit(channel_servers, item, it, channel, ch_name) for it in items] for res in futures.as_completed(itlist): serverlist += res.result() - return serverlist -def channel_servers(it, channel, ch_name): - serverlist = [] - it.contentChannel = 'videolibrary' - it = get_host(it, channel) - for item in getattr(channel, it.action)(it): - if item.server and item.channel: - item.ch_name = ch_name - serverlist.append(item) return serverlist @@ -562,101 +571,112 @@ def play(item): return itemlist -def update_videolibrary(item=''): - logger.debug() - check_for_update(item) - - -def check_for_update(ITEM = None): +def update_videolibrary(item=None): logger.debug("Update Series...") - + from core import channeltools import datetime p_dialog = None update_when_finished = False now = datetime.date.today() - try: - if config.get_setting("update", "videolibrary") != 0: - config.set_setting("updatelibrary_last_check", now.strftime('%Y-%m-%d'), "videolibrary") + config.set_setting("updatelibrary_last_check", now.strftime('%Y-%m-%d'), "videolibrary") - heading = config.get_localized_string(60389) - p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(60037)) - p_dialog.update(0, '') - show_list = [] + message = config.get_localized_string(60389) + p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(60037)) + p_dialog.update(0, '') + show_list = [] - if ITEM and ITEM.videolibrary_id: - show = videolibrarydb['tvshow'][ITEM.videolibrary_id] + if item and item.videolibrary_id: + show = videolibrarydb['tvshow'][item.videolibrary_id] - for s in show['channels'].values(): + for s in show['channels'].values(): show_list += s - else: - shows = dict(videolibrarydb['tvshow']).values() + else: + shows = dict(videolibrarydb['tvshow']).values() + for show in shows: + if show['item'].active or item.forced: + for s in show['channels'].values(): + show_list += s - for show in shows: - if show['item'].active: - for s in show['channels'].values(): - show_list += s + t = float(100) / len(show_list) + i = 0 + + for it in show_list: + i += 1 + chname = channeltools.get_channel_parameters(it.channel)['title'] + p_dialog.update(int(i * t), message=message % (it.fulltitle, chname)) + it = get_host(it) + try: channel = __import__('channels.%s' % it.channel, fromlist=["channels.%s" % it.channel]) + except: channel = __import__('specials.%s' % it.channel, fromlist=["specials.%s" % it.channel]) + itemlist = getattr(channel, it.action)(it) + videolibrarytools.save_tvshow(it, itemlist, True) + p_dialog.close() - t = float(100) / len(show_list) - i = 0 - for item in show_list: - i += 1 - p_dialog.update(int(i * t), heading % (item.fulltitle, item.channel) ) - item = get_host(item) - try: channel = __import__('channels.%s' % item.channel, fromlist=["channels.%s" % item.channel]) - except: channel = __import__('specials.%s' % item.channel, fromlist=["specials.%s" % item.channel]) - itemlist = getattr(channel, item.action)(item) - videolibrarytools.save_tvshow(item, itemlist) - p_dialog.close() except: p_dialog.close() logger.error(traceback.format_exc()) + videolibrarydb.close() - if ITEM: + + if item and item.videolibrary_id: update_when_finished = set_active_tvshow(show) - else: - for show in shows: - update_when_finished = set_active_tvshow(show) + else : + update_when_finished = set_active_tvshow(list(shows)) if update_when_finished: platformtools.itemlist_refresh() - - # if config.get_setting('trakt_sync'): # from core import trakt_tools # trakt_tools.update_all() -def set_active_tvshow(show): - update_when_finished = False - if show['item'].active: - prefered_lang = show['item'].prefered_lang - active = False if show['item'].infoLabels['status'].lower() == 'ended' else True - episodes = videolibrarydb['episode'][show['item'].videolibrary_id] - videolibrarydb.close() - if not active: - total_episodes = show['item'].infoLabels['number_of_episodes'] - episodes_list = [] - for episode in episodes.values(): - for ep in episode['channels'].values(): - ep_list = [e for e in ep if e.contentLanguage == prefered_lang] - if ep_list: episodes_list.append(ep_list) - if len(episodes_list) == total_episodes: - a = False - update_when_finished = True - for i in range(len(episodes_list) - 1): - if len(episodes_list[i]) == len(episodes_list[i + 1]): - a = False - update_when_finished = True - else: - a = True - break - if not a: - show['item'].active = a - videolibrarydb['tvshow'][show['item'].videolibrary_id] = show - videolibrarydb.close() +def set_active_tvshow(value): + update_when_finished = False + def sub_thread(show, update_when_finished): + ret = None + if show['item'].active: + prefered_lang = show['item'].prefered_lang + active = False if show['item'].infoLabels['status'].lower() == 'ended' else True + episodes = videolibrarydb['episode'][show['item'].videolibrary_id] + + if not active: + total_episodes = show['item'].infoLabels['number_of_episodes'] + episodes_list = [] + for episode in episodes.values(): + for ep in episode['channels'].values(): + ep_list = [e for e in ep if e.contentLanguage == prefered_lang] + if ep_list: episodes_list.append(ep_list) + + if len(episodes_list) == total_episodes: + a = False + update_when_finished = True + for i in range(len(episodes_list) - 1): + if len(episodes_list[i]) == len(episodes_list[i + 1]): + a = False + update_when_finished = True + else: + a = True + break + if not a: + show['item'].active = a + ret = show + return show, ret, update_when_finished + + if type(value) == list: + with futures.ThreadPoolExecutor() as executor: + _list = [executor.submit(sub_thread, s, update_when_finished) for s in value] + for res in futures.as_completed(_list): + if res.result() and res.result()[1]: + videolibrarydb['tvshow'][res.result()[0]['item'].videolibrary_id] = res.result()[1] + if res.result()[2]: + update_when_finished = True + else: + show, ret, update_when_finished = sub_thread(value, update_when_finished) + if ret: + videolibrarydb['tvshow'][show['item'].videolibrary_id] = ret + return update_when_finished @@ -948,7 +968,7 @@ def delete(item): if config.is_xbmc() and config.get_setting("videolibrary_kodi"): from platformcode import xbmc_videolibrary xbmc_videolibrary.clean_by_id(item) - platformtools.itemlist_refresh() + platformtools.itemlist_refresh(-1) if select and select > 0: channel_name = channels[select - 1] @@ -960,7 +980,7 @@ def delete(item): seasons_dict = dict(seasons) for key, episode in episodes_dict.items(): - if len(episode['channels']) > 1: + if len(episode['channels']) > 1 and channel_name in episode['channels']: del episode['channels'][channel_name] elif channel_name in episode['channels']: xbmc_videolibrary.clean_by_id(episodes[key]['item'])