Correzioni videoteca

This commit is contained in:
Alhaziel01
2021-05-21 17:35:03 +02:00
parent 6b8305f7ae
commit 529e24e4c1
7 changed files with 206 additions and 370 deletions
+1 -1
View File
@@ -451,7 +451,7 @@ def get_season_and_episode(title):
except: except:
pass pass
logger.debug("'" + title + "' -> '" + filename + "'") logger.debug(title, ' -> ', filename)
return filename return filename
+1 -1
View File
@@ -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 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 '' 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 '')\ videoitem.title = (item.title if item.channel not in ['url'] else '')\
+ (typo(videoitem.title, '_ color kod [] bold') if videoitem.title else "")\ + (typo(videoitem.title, '_ color kod [] bold') if videoitem.title else "")\
+ (typo(videoitem.quality, '_ color kod []') if videoitem.quality else "")\ + (typo(videoitem.quality, '_ color kod []') if videoitem.quality else "")\
+76 -56
View File
@@ -396,7 +396,6 @@ def save_tvshow(item, episodelist, silent=False):
return 0, 0, -1, path return 0, 0, -1, path
# set base name # set base name
base_name = set_base_name(item, _id) base_name = set_base_name(item, _id)
path = filetools.join(TVSHOWS_PATH, base_name) path = filetools.join(TVSHOWS_PATH, base_name)
@@ -488,7 +487,7 @@ def save_tvshow(item, episodelist, silent=False):
return inserted, overwritten, failed, path 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 saves in the indicated path all the chapters included in the episodelist
@type Item: str @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 @return: the number of failed episodes
""" """
# support.dbg() # 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) season_episode = scrapertools.get_season_and_episode(e.title)
if season_episode: 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)) 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.contentSeason = int(season_episode.split('x')[0])
e.contentEpisodeNumber = int(season_episode.split('x')[1]) 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) tmdb.set_infoLabels_item(e)
if not e.infoLabels.get('playcount'): e.infoLabels['playcount'] = 0 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, {}) episode = episodes.get(season_episode, {})
try: 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: if not episode:
inserted += 1 inserted += 1
episode['item'] = episode_item episode['item'] = episode_item
@@ -589,7 +558,9 @@ def save_episodes(item, episodelist, extra_info, host, silent=False, overwrite=T
remove_host(e) remove_host(e)
e.contentTitle = e.infoLabels['title'] e.contentTitle = e.infoLabels['title']
contentType = e.contentType
e.infoLabels = {} e.infoLabels = {}
e.contentType = contentType
if e.channel in epchannels and e.channel != 'download': if e.channel in epchannels and e.channel != 'download':
channels_url = [u.url for u in epchannels[e.channel]] 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] epchannels[e.channel] = [e]
episode['channels'] = epchannels episode['channels'] = epchannels
episodes[season_episode] = episode
if not filetools.exists(filetools.join(TVSHOWS_PATH, strm_path)): if not filetools.exists(filetools.join(TVSHOWS_PATH, strm_path)):
logger.debug("Creating .strm: " + 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)): # if not filetools.exists(filetools.join(TVSHOWS_PATH, nfo_path)):
# filetools.write(filetools.join(TVSHOWS_PATH, nfo_path), head_nfo) # filetools.write(filetools.join(TVSHOWS_PATH, nfo_path), head_nfo)
except: except:
logger.error(traceback.format_exc())
failed += 1 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() logger.debug()
# from core import tmdb # from core import tmdb
@@ -640,23 +645,37 @@ def save_episodes(item, episodelist, extra_info, host, silent=False, overwrite=T
# support.dbg() # support.dbg()
# for i, e in enumerate(episodelist): # for i, e in enumerate(episodelist):
# item, seasons, episodes, e, inserted, overwritten, failed = save_episode(item, seasons, current_seasons, episodes, e, inserted, overwritten, failed) # 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: 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 e.contentLanguage in item.lang_list: item.lang_list.append(e.contentLanguage)
# if not silent: # if not silent:
# p_dialog.update(int(math.ceil((i + 1) * t)), e.title) # p_dialog.update(int(math.ceil((i + 1) * t)), e.title)
i = 0 i = 0
with futures.ThreadPoolExecutor() as executor: 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): for res in futures.as_completed(itlist):
if res.result(): if res.result():
item, seasons, episodes, e, inserted, overwritten, failed = res.result() item, episode, season_episode, lang, I, O, F = res.result()
if not e.contentLanguage: e.contentLanguage = item.contentLanguage if item.contentLanguage else 'ITA' inserted += I
if not e.contentLanguage in item.lang_list: item.lang_list.append(e.contentLanguage) overwritten += O
if not silent: failed += F
i += 1 if episode:
p_dialog.update(int(math.ceil(i * t)), e.title) 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 not silent:
if len(item.lang_list) > 1: if len(item.lang_list) > 1:
@@ -882,6 +901,7 @@ def add_tvshow(item, channel=None):
global magnet_caching global magnet_caching
magnet_caching = False magnet_caching = False
inserted, overwritten, failed, path = save_tvshow(item, itemlist) inserted, overwritten, failed, path = save_tvshow(item, itemlist)
if not path: if not path:
+14 -23
View File
@@ -278,11 +278,11 @@ def dialog_select_group(heading, _list, preselect=0):
return dialog return dialog
def itemlist_refresh(): def itemlist_refresh(offset=0):
win = xbmcgui.Window(xbmcgui.getCurrentWindowId()) win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
cid = win.getFocusId() cid = win.getFocusId()
ctl = win.getControl(cid) 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") xbmc.executebuiltin("Container.Refresh")
@@ -503,29 +503,20 @@ def set_infolabels(listitem, item, player=False):
@type item: item @type item: item
""" """
infoLabels_dict = {'aired': 'aired', 'album': 'album', 'artist': 'artist', 'cast': 'cast', infoLabels_dict = {'aired': 'aired', 'album': 'album', 'artist': 'artist', 'cast': 'cast', 'castandrole': 'castandrole',
'castandrole': 'castandrole', 'tmdb_id': 'code', 'code': 'code', 'country': 'country', 'tmdb_id': 'code', 'code': 'code', 'country': 'country', 'credits': 'credits', 'release_date': 'dateadded',
'credits': 'credits', 'release_date': 'dateadded', 'dateadded': 'dateadded', 'dbid': 'dbid', 'dateadded': 'dateadded', 'dbid': 'dbid', 'director': 'director', 'duration': 'duration', 'episode': 'episode',
'director': 'director', 'duration': 'duration', 'episode': 'episode', 'episode_plot': 'episodeguide', 'episode_title': 'title', 'episode_vote_average': 'rating', 'episode_vote_count': 'votes',
'episodio_sinopsis': 'episodeguide', 'episodio_air_date': 'None', 'episodio_imagen': 'None', 'genre': 'genre', 'imdb_id': 'imdbnumber', 'imdbnumber': 'imdbnumber', 'last_air_date': 'lastplayed', 'mediatype': 'mediatype',
'episodio_titulo': 'title', 'episodio_vote_average': 'rating', 'episodio_vote_count': 'votes', 'mpaa': 'mpaa', 'originaltitle': 'originaltitle', 'overlay': 'overlay', 'poster_path': 'path', 'playcount': 'playcount',
'fanart': 'None', 'genre': 'genre', 'homepage': 'None', 'imdb_id': 'imdbnumber', 'plot': 'plot', 'plotoutline': 'plotoutline', 'premiered': 'premiered', 'rating': 'rating', 'season': 'season', 'set': 'set',
'imdbnumber': 'imdbnumber', 'in_production': 'None', 'last_air_date': 'lastplayed', 'setid': 'setid', 'setoverview': 'setoverview', 'showlink': 'showlink', 'sortepisode': 'sortepisode', 'sortseason': 'sortseason',
'mediatype': 'mediatype', 'mpaa': 'mpaa', 'number_of_episodes': 'None', 'sorttitle': 'sorttitle', 'status': 'status', 'studio': 'studio', 'tag': 'tag', 'tagline': 'tagline', 'title': 'title',
'number_of_seasons': 'None', 'original_language': 'None', 'originaltitle': 'originaltitle', 'top250': 'top250', 'tracknumber': 'tracknumber', 'trailer': 'trailer', 'tvshowtitle': 'tvshowtitle', 'userrating': 'userrating',
'overlay': 'overlay', 'poster_path': 'path', 'popularity': 'None', 'playcount': 'playcount', 'votes': 'votes', 'writer': 'writer', 'year': 'year'}
'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'}
# if item.infoLabels: # if item.infoLabels:
try: 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) listitem.setInfo("video", infoLabels_kodi)
except: except:
listitem.setInfo("video", item.infoLabels) listitem.setInfo("video", item.infoLabels)
+4 -33
View File
@@ -263,6 +263,7 @@ def mark_content_as_watched_on_kodi(item, value=1):
@param value: > 0 for seen, 0 for not seen @param value: > 0 for seen, 0 for not seen
""" """
logger.debug() logger.debug()
conn = sqlite3.connect(get_file_db())
view = 'episode' if item.contentType != 'movie' else 'movie' 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) 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]) 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) 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: if r:
sql = 'update files set playCount= {} where idFile= {}' sql = 'update files set playCount= {} where idFile= {}'
sql_actions = [sql.format(value, i[0]) for i in r] 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: for sql in sql_actions:
if type(sql) == list: if type(sql) == list:
cursor.executemany(sql) cursor.executemany(sql)
@@ -286,36 +286,9 @@ def mark_content_as_watched_on_kodi(item, value=1):
cursor.execute(sql) cursor.execute(sql)
conn.commit() conn.commit()
conn.close() conn.close()
platformtools.itemlist_refresh() 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): def set_watched_on_kod(data):
from specials import videolibrary from specials import videolibrary
@@ -380,8 +353,6 @@ def set_watched_on_kod(data):
def mark_content_as_watched_on_kod(path): def mark_content_as_watched_on_kod(path):
from specials import videolibrary from specials import videolibrary
from core import videolibrarytools 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 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 @type str: path
+3 -169
View File
@@ -115,175 +115,9 @@ def update(path, p_dialog, i, t, serie, overwrite):
return insertados_total > 0 return insertados_total > 0
def check_for_update(overwrite=True): def check_for_update():
logger.debug("Update Series...") if config.get_setting("update", "videolibrary"):
p_dialog = None videolibrary.update_videolibrary()
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 updaterCheck(): def updaterCheck():
+107 -87
View File
@@ -8,12 +8,13 @@ PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
import xbmc, os, traceback import xbmc, os, traceback
from time import time
from core import filetools, scrapertools, videolibrarytools 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 core.item import Item
from platformcode import config, launcher, logger, platformtools from platformcode import config, launcher, logger, platformtools
from core.videolibrarytools import videolibrarydb
if PY3: if PY3:
from concurrent import futures from concurrent import futures
import urllib.parse as urlparse import urllib.parse as urlparse
@@ -21,7 +22,7 @@ else:
from concurrent_py2 import futures from concurrent_py2 import futures
import urlparse import urlparse
from core.videolibrarytools import videolibrarydb
def mainlist(item): def mainlist(item):
@@ -31,7 +32,7 @@ def mainlist(item):
category=config.get_localized_string(70270), thumbnail=thumb("videolibrary_movie")), category=config.get_localized_string(70270), thumbnail=thumb("videolibrary_movie")),
Item(channel=item.channel, action="list_tvshows",title=config.get_localized_string(60600), Item(channel=item.channel, action="list_tvshows",title=config.get_localized_string(60600),
category=config.get_localized_string(70271), thumbnail=thumb("videolibrary_tvshow"), 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'), 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)] category=2, setting=1, thumbnail = thumb("setting_0"),folder=False)]
return itemlist return itemlist
@@ -197,7 +198,7 @@ def list_tvshows(item):
itemlist = sorted(itemlist, key=lambda it: it.title.lower()) itemlist = sorted(itemlist, key=lambda it: it.title.lower())
itemlist += [Item(channel=item.channel, action="update_videolibrary", thumbnail=item.thumbnail, 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)] title=typo(config.get_localized_string(70269), 'bold color kod'), folder=False)]
return itemlist return itemlist
@@ -471,15 +472,21 @@ def findvideos(item):
else: else:
videolibrary_items[key] = values videolibrary_items[key] = values
with futures.ThreadPoolExecutor() as executor: 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): for res in futures.as_completed(itlist):
itemlist += res.result() itemlist += res.result()
pl = [s for s in itemlist if s.contentLanguage in [prefered_lang, '']]
if pl: itemlist = pl
if len(itlist) > 1: if len(itlist) > 1:
for it in itemlist: for it in itemlist:
it.title = '[{}] {}'.format(it.ch_name, it.title) it.title = '[{}] {}'.format(it.ch_name, it.title)
if autoplay.play_multi_channel(item, itemlist): # hideserver if autoplay.play_multi_channel(item, itemlist): # hideserver
return [] return []
@@ -489,12 +496,23 @@ def findvideos(item):
return itemlist return itemlist
def servers(ch, items): def servers(item, ch, items):
serverlist = [] serverlist = []
from core import channeltools from core import channeltools
ch_params = channeltools.get_channel_parameters(ch) ch_params = channeltools.get_channel_parameters(ch)
ch_name = ch_params.get('title', '') 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 ch_params.get('active', False):
if os.path.isfile(os.path.join(config.get_runtime_path(), 'channels', ch + ".py")): CHANNELS = 'channels' 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)]) try: channel = __import__('%s.%s' % (CHANNELS, ch), None, None, ['%s.%s' % (CHANNELS, ch)])
except ImportError: exec("import " + CHANNELS + "." + ch + " as channel") except ImportError: exec("import " + CHANNELS + "." + ch + " as channel")
with futures.ThreadPoolExecutor() as executor: 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): for res in futures.as_completed(itlist):
serverlist += res.result() 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 return serverlist
@@ -562,101 +571,112 @@ def play(item):
return itemlist return itemlist
def update_videolibrary(item=''): def update_videolibrary(item=None):
logger.debug()
check_for_update(item)
def check_for_update(ITEM = None):
logger.debug("Update Series...") logger.debug("Update Series...")
from core import channeltools
import datetime import datetime
p_dialog = None p_dialog = None
update_when_finished = False update_when_finished = False
now = datetime.date.today() now = datetime.date.today()
try: 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) message = config.get_localized_string(60389)
p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(60037)) p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(60037))
p_dialog.update(0, '') p_dialog.update(0, '')
show_list = [] show_list = []
if ITEM and ITEM.videolibrary_id: if item and item.videolibrary_id:
show = videolibrarydb['tvshow'][ITEM.videolibrary_id] show = videolibrarydb['tvshow'][item.videolibrary_id]
for s in show['channels'].values(): for s in show['channels'].values():
show_list += s show_list += s
else: else:
shows = dict(videolibrarydb['tvshow']).values() 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: t = float(100) / len(show_list)
if show['item'].active: i = 0
for s in show['channels'].values():
show_list += s 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: except:
p_dialog.close() p_dialog.close()
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
videolibrarydb.close() videolibrarydb.close()
if ITEM:
if item and item.videolibrary_id:
update_when_finished = set_active_tvshow(show) update_when_finished = set_active_tvshow(show)
else: else :
for show in shows: update_when_finished = set_active_tvshow(list(shows))
update_when_finished = set_active_tvshow(show)
if update_when_finished: if update_when_finished:
platformtools.itemlist_refresh() platformtools.itemlist_refresh()
# if config.get_setting('trakt_sync'): # if config.get_setting('trakt_sync'):
# from core import trakt_tools # from core import trakt_tools
# trakt_tools.update_all() # 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: def set_active_tvshow(value):
a = False update_when_finished = False
update_when_finished = True def sub_thread(show, update_when_finished):
for i in range(len(episodes_list) - 1): ret = None
if len(episodes_list[i]) == len(episodes_list[i + 1]): if show['item'].active:
a = False prefered_lang = show['item'].prefered_lang
update_when_finished = True active = False if show['item'].infoLabels['status'].lower() == 'ended' else True
else: episodes = videolibrarydb['episode'][show['item'].videolibrary_id]
a = True
break if not active:
if not a: total_episodes = show['item'].infoLabels['number_of_episodes']
show['item'].active = a episodes_list = []
videolibrarydb['tvshow'][show['item'].videolibrary_id] = show for episode in episodes.values():
videolibrarydb.close() 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 return update_when_finished
@@ -948,7 +968,7 @@ def delete(item):
if config.is_xbmc() and config.get_setting("videolibrary_kodi"): if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
from platformcode import xbmc_videolibrary from platformcode import xbmc_videolibrary
xbmc_videolibrary.clean_by_id(item) xbmc_videolibrary.clean_by_id(item)
platformtools.itemlist_refresh() platformtools.itemlist_refresh(-1)
if select and select > 0: if select and select > 0:
channel_name = channels[select - 1] channel_name = channels[select - 1]
@@ -960,7 +980,7 @@ def delete(item):
seasons_dict = dict(seasons) seasons_dict = dict(seasons)
for key, episode in episodes_dict.items(): 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] del episode['channels'][channel_name]
elif channel_name in episode['channels']: elif channel_name in episode['channels']:
xbmc_videolibrary.clean_by_id(episodes[key]['item']) xbmc_videolibrary.clean_by_id(episodes[key]['item'])