Skip to content

Commit

Permalink
Return default value on failure
Browse files Browse the repository at this point in the history
  • Loading branch information
dagwieers committed Dec 9, 2019
1 parent 76dffc7 commit eb0d48f
Show file tree
Hide file tree
Showing 11 changed files with 79 additions and 90 deletions.
28 changes: 13 additions & 15 deletions resources/lib/apihelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from kodiutils import (delete_cached_thumbnail, get_global_setting, get_proxies, get_setting,
has_addon, localize, localize_from_data, log, url_for)
from metadata import Metadata
from statichelper import (add_https_method, convert_html_to_kodilabel, find_entry, from_unicode, play_url_to_id,
from statichelper import (add_https_proto, convert_html_to_kodilabel, find_entry, from_unicode, play_url_to_id,
program_to_url, realpage, strip_newlines, url_to_program)
from utils import get_cache, get_cached_url_json, get_url_json, ttl, update_cache

Expand All @@ -38,7 +38,7 @@ def __init__(self, _favorites, _resumepoints):

def get_tvshows(self, category=None, channel=None, feature=None):
''' Get all TV shows for a given category, channel or feature, optionally filtered by favorites '''
params = dict()
params = {}

if category:
params['facets[categories]'] = category
Expand All @@ -59,7 +59,7 @@ def get_tvshows(self, category=None, channel=None, feature=None):

querystring = '&'.join('{}={}'.format(key, value) for key, value in list(params.items()))
suggest_url = self._VRTNU_SUGGEST_URL + '?' + querystring
return get_cached_url_json(url=suggest_url, cache=cache_file, ttl=ttl('indirect'))
return get_cached_url_json(url=suggest_url, cache=cache_file, ttl=ttl('indirect'), fail=[])

def list_tvshows(self, category=None, channel=None, feature=None, use_favorites=False):
''' List all TV shows for a given category, channel or feature, optionally filtered by favorites '''
Expand Down Expand Up @@ -261,7 +261,7 @@ def get_upnext(self, info):

# Get all episodes from current program and sort by program, seasonTitle and episodeNumber
episodes = sorted(self.get_episodes(keywords=program), key=lambda k: (k.get('program'), k.get('seasonTitle'), k.get('episodeNumber')))
upnext = dict()
upnext = {}
for episode in episodes:
if ep_id.get('whatson_id') == episode.get('whatsonId') or \
ep_id.get('video_id') == episode.get('videoId') or \
Expand Down Expand Up @@ -406,7 +406,7 @@ def get_episode_by_air_date(self, channel_name, start_date, end_date=None):
schedule_date = onairdate
schedule_datestr = schedule_date.isoformat().split('T')[0]
url = 'https://www.vrt.be/bin/epg/schedule.%s.json' % schedule_datestr
schedule_json = get_url_json(url)
schedule_json = get_url_json(url, fail={})
episodes = schedule_json.get(channel.get('id'), [])
if not episodes:
return None
Expand Down Expand Up @@ -562,18 +562,16 @@ def get_episodes(self, program=None, season=None, episodes=None, category=None,
querystring = '&'.join('{}={}'.format(key, value) for key, value in list(params.items()))
search_url = self._VRTNU_SEARCH_URL + '?' + querystring.replace(' ', '%20') # Only encode spaces to minimize url length
if cache_file:
search_json = get_cached_url_json(url=search_url, cache=cache_file, ttl=ttl('indirect'))
search_json = get_cached_url_json(url=search_url, cache=cache_file, ttl=ttl('indirect'), fail={})
else:
search_json = get_url_json(url=search_url)
search_json = get_url_json(url=search_url, fail={})

# Check for multiple seasons
seasons = None
seasons = []
if 'facets[seasonTitle]' not in unquote(search_url):
facets = search_json.get('facets', dict()).get('facets')
facets = search_json.get('facets', {}).get('facets')
if facets:
seasons = next((f.get('buckets', []) for f in facets if f.get('name') == 'seasons' and len(f.get('buckets', [])) > 1), None)
else:
seasons = []

episodes = search_json.get('results', [{}])
show_seasons = bool(season != 'allseasons')
Expand All @@ -590,7 +588,7 @@ def get_episodes(self, program=None, season=None, episodes=None, category=None,
for api_page in range(1, api_pages):
api_page_url = search_url + '&from=' + str(api_page * api_page_size + 1)
api_page_json = get_url_json(api_page_url)
if api_page_json:
if api_page_json is not None:
episodes += api_page_json.get('results', [{}])

# Return episodes
Expand All @@ -613,7 +611,7 @@ def list_channels(self, channels=None, live=True):
continue

context_menu = []
art_dict = dict()
art_dict = {}

# Try to use the white icons for thumbnails (used for icons as well)
if has_addon('resource.images.studios.white'):
Expand Down Expand Up @@ -684,7 +682,7 @@ def list_youtube(channels=None):
continue

context_menu = []
art_dict = dict()
art_dict = {}

# Try to use the white icons for thumbnails (used for icons as well)
if has_addon('resource.images.studios.white'):
Expand Down Expand Up @@ -821,7 +819,7 @@ def get_category_thumbnail(element):
''' Return a category thumbnail, if available '''
if get_setting('showfanart', 'true') == 'true':
raw_thumbnail = element.find(class_='media').get('data-responsive-image', 'DefaultGenre.png')
return add_https_method(raw_thumbnail)
return add_https_proto(raw_thumbnail)
return 'DefaultGenre.png'

@staticmethod
Expand Down
2 changes: 1 addition & 1 deletion resources/lib/favorites.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def refresh(self, ttl=None):
}
favorites_url = 'https://video-user-data.vrt.be/favorites'
favorites_json = get_url_json(url=favorites_url, cache='favorites.json', headers=headers)
if favorites_json:
if favorites_json is not None:
self._favorites = favorites_json

def update(self, program, title, value=True):
Expand Down
63 changes: 32 additions & 31 deletions resources/lib/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
except ImportError: # Python 2
from urllib import quote_plus

import statichelper
from data import CHANNELS, SECONDS_MARGIN
from kodiutils import get_setting, localize, localize_datelong, log, url_for
from statichelper import (add_https_proto, capitalize, find_entry, from_unicode, html_to_kodilabel,
reformat_url, shorten_link, to_unicode, unescape, url_to_episode)


class Metadata:
Expand Down Expand Up @@ -73,24 +74,24 @@ def get_context_menu(self, api_data, program, cache_file):

if assetpath is not None:
# We need to ensure forward slashes are quoted
program_title = statichelper.to_unicode(quote_plus(statichelper.from_unicode(program_title)))
url = statichelper.url_to_episode(api_data.get('url', ''))
program_title = to_unicode(quote_plus(from_unicode(program_title)))
url = url_to_episode(api_data.get('url', ''))
asset_id = self._resumepoints.assetpath_to_id(assetpath)
if self._resumepoints.is_watchlater(asset_id):
extras = dict()
extras = {}
# If we are in a watchlater menu, move cursor down before removing a favorite
if plugin.path.startswith('/resumepoints/watchlater'):
extras = dict(move_down=True)
# Unwatch context menu
context_menu.append((
statichelper.capitalize(localize(30402)),
capitalize(localize(30402)),
'RunPlugin(%s)' % url_for('unwatchlater', asset_id=asset_id, title=program_title, url=url, **extras)
))
watchlater_marker = '[COLOR yellow]ᶫ[/COLOR]'
else:
# Watch context menu
context_menu.append((
statichelper.capitalize(localize(30401)),
capitalize(localize(30401)),
'RunPlugin(%s)' % url_for('watchlater', asset_id=asset_id, title=program_title, url=url)
))

Expand All @@ -117,9 +118,9 @@ def get_context_menu(self, api_data, program, cache_file):
follow_enabled = bool(api_data.get('url'))

if follow_enabled:
program_title = statichelper.to_unicode(quote_plus(statichelper.from_unicode(program_title))) # We need to ensure forward slashes are quoted
program_title = to_unicode(quote_plus(from_unicode(program_title))) # We need to ensure forward slashes are quoted
if self._favorites.is_favorite(program):
extras = dict()
extras = {}
# If we are in a favorites menu, move cursor down before removing a favorite
if plugin.path.startswith('/favorites'):
extras = dict(move_down=True)
Expand Down Expand Up @@ -178,17 +179,17 @@ def get_playcount(self, api_data):

def get_properties(self, api_data):
''' Get properties from single item json api data '''
properties = dict()
properties = {}

# Only fill in properties when using VRT NU resumepoints because setting resumetime/totaltime breaks standard Kodi watched status
if self._resumepoints.is_activated():
assetpath = self.get_assetpath(api_data)
if assetpath:
# We need to ensure forward slashes are quoted
program_title = statichelper.to_unicode(quote_plus(statichelper.from_unicode(api_data.get('program'))))
program_title = to_unicode(quote_plus(from_unicode(api_data.get('program'))))

asset_id = self._resumepoints.assetpath_to_id(assetpath)
url = statichelper.reformat_url(api_data.get('url', ''), 'medium')
url = reformat_url(api_data.get('url', ''), 'medium')
properties.update(asset_id=asset_id, url=url, title=program_title)

position = self._resumepoints.get_position(asset_id)
Expand Down Expand Up @@ -263,7 +264,7 @@ def get_plot(self, api_data, season=False, date=None):
# VRT NU Search API
if api_data.get('type') == 'episode':
if season:
plot = statichelper.convert_html_to_kodilabel(api_data.get('programDescription'))
plot = html_to_kodilabel(api_data.get('programDescription'))

# Add additional metadata to plot
plot_meta = ''
Expand Down Expand Up @@ -304,20 +305,20 @@ def get_plot(self, api_data, season=False, date=None):
plot_meta += ' '
plot_meta += localize(30201) # Geo-blocked

plot = statichelper.convert_html_to_kodilabel(api_data.get('description'))
plot = html_to_kodilabel(api_data.get('description'))

if plot_meta:
plot = '%s\n\n%s' % (plot_meta, plot)

permalink = statichelper.shorten_link(api_data.get('permalink')) or api_data.get('externalPermalink')
permalink = shorten_link(api_data.get('permalink')) or api_data.get('externalPermalink')
if permalink and get_setting('showpermalink', 'false') == 'true':
plot = '%s\n\n[COLOR yellow]%s[/COLOR]' % (plot, permalink)
return plot

# VRT NU Suggest API
if api_data.get('type') == 'program':
plot = statichelper.unescape(api_data.get('description', '???'))
# permalink = statichelper.shorten_link(api_data.get('programUrl'))
plot = unescape(api_data.get('description', '???'))
# permalink = shorten_link(api_data.get('programUrl'))
# if permalink and get_setting('showpermalink', 'false') == 'true':
# plot = '%s\n\n[COLOR yellow]%s[/COLOR]' % (plot, permalink)
return plot
Expand All @@ -342,11 +343,11 @@ def get_plotoutline(api_data, season=False):
# VRT NU Search API
if api_data.get('type') == 'episode':
if season:
plotoutline = statichelper.convert_html_to_kodilabel(api_data.get('programDescription'))
plotoutline = html_to_kodilabel(api_data.get('programDescription'))
return plotoutline

if api_data.get('displayOptions', dict()).get('showShortDescription'):
plotoutline = statichelper.convert_html_to_kodilabel(api_data.get('shortDescription'))
if api_data.get('displayOptions', {}).get('showShortDescription'):
plotoutline = html_to_kodilabel(api_data.get('shortDescription'))
return plotoutline

plotoutline = api_data.get('subtitle')
Expand Down Expand Up @@ -510,24 +511,24 @@ def get_year(api_data):
@staticmethod
def get_art(api_data, season=False):
''' Get art dict from single item json api data '''
art_dict = dict()
art_dict = {}

# VRT NU Search API
if api_data.get('type') == 'episode':
if season:
if get_setting('showfanart', 'true') == 'true':
art_dict['fanart'] = statichelper.add_https_method(api_data.get('programImageUrl', 'DefaultSets.png'))
art_dict['fanart'] = add_https_proto(api_data.get('programImageUrl', 'DefaultSets.png'))
art_dict['banner'] = art_dict.get('fanart')
if season != 'allseasons':
art_dict['thumb'] = statichelper.add_https_method(api_data.get('videoThumbnailUrl', art_dict.get('fanart')))
art_dict['thumb'] = add_https_proto(api_data.get('videoThumbnailUrl', art_dict.get('fanart')))
else:
art_dict['thumb'] = art_dict.get('fanart')
else:
art_dict['thumb'] = 'DefaultSets.png'
else:
if get_setting('showfanart', 'true') == 'true':
art_dict['thumb'] = statichelper.add_https_method(api_data.get('videoThumbnailUrl', 'DefaultAddonVideo.png'))
art_dict['fanart'] = statichelper.add_https_method(api_data.get('programImageUrl', art_dict.get('thumb')))
art_dict['thumb'] = add_https_proto(api_data.get('videoThumbnailUrl', 'DefaultAddonVideo.png'))
art_dict['fanart'] = add_https_proto(api_data.get('programImageUrl', art_dict.get('thumb')))
art_dict['banner'] = art_dict.get('fanart')
else:
art_dict['thumb'] = 'DefaultAddonVideo.png'
Expand All @@ -537,7 +538,7 @@ def get_art(api_data, season=False):
# VRT NU Suggest API
if api_data.get('type') == 'program':
if get_setting('showfanart', 'true') == 'true':
art_dict['thumb'] = statichelper.add_https_method(api_data.get('thumbnail', 'DefaultAddonVideo.png'))
art_dict['thumb'] = add_https_proto(api_data.get('thumbnail', 'DefaultAddonVideo.png'))
art_dict['fanart'] = art_dict.get('thumb')
art_dict['banner'] = art_dict.get('fanart')
else:
Expand Down Expand Up @@ -610,15 +611,15 @@ def get_info_labels(self, api_data, season=False, date=None, channel=None):
return info_labels

# Not Found
return dict()
return {}

@staticmethod
def get_label(api_data, titletype=None, return_sort=False):
''' Get an appropriate label string matching the type of listing and VRT NU provided displayOptions from single item json api data '''

# VRT NU Search API
if api_data.get('type') == 'episode':
display_options = api_data.get('displayOptions', dict())
display_options = api_data.get('displayOptions', {})

# NOTE: Hard-code showing seasons because it is unreliable (i.e; Thuis or Down the Road have it disabled)
display_options['showSeason'] = True
Expand All @@ -628,11 +629,11 @@ def get_label(api_data, titletype=None, return_sort=False):
titletype = program_type

if display_options.get('showEpisodeTitle'):
label = statichelper.convert_html_to_kodilabel(api_data.get('title') or api_data.get('shortDescription'))
label = html_to_kodilabel(api_data.get('title') or api_data.get('shortDescription'))
elif display_options.get('showShortDescription'):
label = statichelper.convert_html_to_kodilabel(api_data.get('shortDescription') or api_data.get('title'))
label = html_to_kodilabel(api_data.get('shortDescription') or api_data.get('title'))
else:
label = statichelper.convert_html_to_kodilabel(api_data.get('title') or api_data.get('shortDescription'))
label = html_to_kodilabel(api_data.get('title') or api_data.get('shortDescription'))

sort = 'unsorted'
ascending = True
Expand Down Expand Up @@ -715,7 +716,7 @@ def get_tag(api_data):
# VRT NU Search API
if api_data.get('type') == 'episode':
from data import CATEGORIES
return sorted([localize(statichelper.find_entry(CATEGORIES, 'id', category).get('msgctxt'))
return sorted([localize(find_entry(CATEGORIES, 'id', category).get('msgctxt'))
for category in api_data.get('categories')])

# VRT NU Suggest API
Expand Down
3 changes: 2 additions & 1 deletion resources/lib/playerinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
from __future__ import absolute_import, division, unicode_literals
from threading import Event, Thread
from xbmc import getInfoLabel, Player, PlayList

from apihelper import ApiHelper
from data import SECONDS_MARGIN
from favorites import Favorites
from kodiutils import addon_id, container_reload, get_advanced_setting, get_setting, has_addon, log, notify
from resumepoints import ResumePoints
from statichelper import play_url_to_id, to_unicode, url_to_episode
from kodiutils import addon_id, container_reload, get_advanced_setting, get_setting, has_addon, log, notify


class PlayerInfo(Player):
Expand Down
2 changes: 1 addition & 1 deletion resources/lib/resumepoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def refresh(self, ttl=None):
}
resumepoints_url = 'https://video-user-data.vrt.be/resume_points'
resumepoints_json = get_url_json(url=resumepoints_url, cache='resume_points.json', headers=headers)
if resumepoints_json:
if resumepoints_json is not None:
self._resumepoints = resumepoints_json

def update(self, asset_id, title, url, watch_later=None, position=None, total=None, whatson_id=None, asynchronous=False):
Expand Down
2 changes: 1 addition & 1 deletion resources/lib/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

from __future__ import absolute_import, division, unicode_literals
from favorites import Favorites
from resumepoints import ResumePoints
from kodiutils import (addon_profile, container_refresh, end_of_directory, get_search_string,
get_setting, localize, log_error, ok_dialog, open_file, show_listing, url_for)
from resumepoints import ResumePoints
from utils import ttl


Expand Down
4 changes: 2 additions & 2 deletions resources/lib/statichelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def unescape(string):
]


def convert_html_to_kodilabel(text):
def html_to_kodilabel(text):
''' Convert VRT HTML content into Kodit formatted text '''
for key, val in HTML_MAPPING:
text = key.sub(val, text)
Expand Down Expand Up @@ -179,7 +179,7 @@ def strip_newlines(text):
return text.replace('\n', '').strip()


def add_https_method(url):
def add_https_proto(url):
''' Add HTTPS protocol to URL that lacks it '''
if url.startswith('//'):
return 'https:' + url
Expand Down
Loading

0 comments on commit eb0d48f

Please sign in to comment.