def _start_stream(self, channel, max_tries=2): resp = None for _ in range(max_tries): device_id = get_from_cache("device_id") oauth_tokens = get_from_cache("OAuthTokens") try: resp = session.post(BASE_URL + "/stream/start", headers={ "Content-Type": "application/json;charset=utf-8", "X-Yelo-DeviceId": device_id, "Authorization": authorization_payload( oauth_tokens["accessToken"]) }, data=stream_payload(device_id, channel)) if resp.status_code == 401: raise Exceptions.NotAuthorizedException("Unauthorized") break except Exceptions.NotAuthorizedException: self._refresh_oauth_token() if resp: j = resp.json() if not j.get("errors"): return resp.json() title, message = YeloErrors.get_error_message( session, j["errors"][0]["code"]) KodiWrapper.dialog_ok(title, message) raise Exceptions.YeloException(message)
def __init__(self): Monitor.__init__(self) self.kodi = KodiWrapper() self.vtm_go = VtmGo(self.kodi) self.vtm_go_auth = VtmGoAuth(self.kodi) self.update_interval = 24 * 3600 # Every 24 hours self.cache_expiry = 30 * 24 * 3600 # One month
class BackgroundService(Monitor): """ Background service code """ def __init__(self): Monitor.__init__(self) self._kodi = KodiWrapper() self._player = PlayerMonitor(kodi=self._kodi) self.vtm_go = VtmGo(self._kodi) self.vtm_go_auth = VtmGoAuth(self._kodi) self.update_interval = 24 * 3600 # Every 24 hours self.cache_expiry = 30 * 24 * 3600 # One month def run(self): """ Background loop for maintenance tasks """ _LOGGER.debug('Service started') while not self.abortRequested(): # Update every `update_interval` after the last update if self._kodi.get_setting_as_bool('metadata_update') and int( self._kodi.get_setting('metadata_last_updated', 0)) + self.update_interval < time(): self._update_metadata() # Stop when abort requested if self.waitForAbort(10): break _LOGGER.debug('Service stopped') def onSettingsChanged(self): # pylint: disable=invalid-name """ Callback when a setting has changed """ # Refresh our VtmGo instance kodiwrapper.ADDON = Addon() self.vtm_go = VtmGo(self._kodi) if self.vtm_go_auth.has_credentials_changed(): _LOGGER.debug('Clearing auth tokens due to changed credentials') self.vtm_go_auth.clear_token() # Refresh container self._kodi.container_refresh() def _update_metadata(self): """ Update the metadata for the listings """ from resources.lib.modules.metadata import Metadata # Clear outdated metadata self._kodi.invalidate_cache(self.cache_expiry) def update_status(_i, _total): """ Allow to cancel the background job """ return self.abortRequested( ) or not self._kodi.get_setting_as_bool('metadata_update') success = Metadata(self._kodi).fetch_metadata(callback=update_status) # Update metadata_last_updated if success: self._kodi.set_setting('metadata_last_updated', str(int(time())))
def list_channels(self, is_folder=False): from resources.lib.kodiwrapper import KodiWrapper import dateutil.parser import datetime listing = [] tv_channels = self.get_channels() epg = self.get_epg() for i in range(len(tv_channels)): name = (tv_channels[i]["channelIdentification"]["name"]) squareLogo = tv_channels[i]["channelProperties"]["squareLogo"] stbUniqueName = tv_channels[i]["channelIdentification"]["stbUniqueName"] poster = "" guide = "" for index, item in enumerate(epg[name]): try: now = datetime.datetime.utcnow().replace(second=0, microsecond=0) start = dateutil.parser.parse(item["start"]) end = dateutil.parser.parse(item["stop"]) if start <= now <= end: try: prev_title = epg[name][index - 1]["title"] \ if "title" in epg[name][index - 1] else "" except IndexError: prev_title = "" try: next_title = epg[name][index + 1]["title"] \ if "title" in epg[name][index + 1] else "" except IndexError: next_title = "" title = item["title"] if "title" in item else "" guide = self._create_guide_from_channel_info(prev_title, title, next_title) poster = item["image"] if "image" in item else "" except: continue list_item = KodiWrapper. \ create_list_item(name, squareLogo, poster, {"plot": guide}, True, True) url = KodiWrapper.url_for("play", uniqueName=stbUniqueName) listing.append((url, list_item, is_folder)) KodiWrapper.add_dir_items(listing) KodiWrapper.end_directory()
def play_channel(base_uri, content_locator, protection_key): try: tv.request_license_token(content_locator) except DeviceLimitReachedException as ex: return KodiWrapper.error_dialog(str(ex)) streaming_format = StreamingFormat.get_streaming_format() if streaming_format == StreamingFormat.MPEG_DASH: protocol = "mpd" elif streaming_format == StreamingFormat.SMOOTH_STREAM: protocol = "ism" else: protocol = "" is_helper = inputstreamhelper.Helper(protocol, drm=DRM) if is_helper.check_inputstream(): manifest_url = tv.create_manifest_url(base_uri, protection_key) play_item = ListItem(path=manifest_url) play_item.setContentLookup(False) play_item.setMimeType('application/dash+xml') server_certificate = tv.get_server_certificate(content_locator) play_item.setProperty('inputstream.adaptive.server_certificate', server_certificate) play_item.setProperty('inputstream.adaptive.license_flags', 'persistent_storage') play_item.setProperty('inputstreamaddon', is_helper.inputstream_addon) play_item.setProperty('inputstream.adaptive.manifest_type', protocol) play_item.setProperty('inputstream.adaptive.license_type', DRM) play_item.setProperty( 'inputstream.adaptive.license_key', '%(url)s|' 'User-Agent=%(ua)s' '&Connection=keep-alive' '&Referer=https://www.telenettv.be/' '&Content-Type=application/octet-stream' '&X-OESP-Content-Locator=%(oespContentLoc)s' '&X-OESP-DRM-SchemeIdUri=%(schemeId)s' '&X-OESP-License-Token=%(oespLicToken)s' '&X-OESP-License-Token-Type=%(oespLicTokenType)s' '&X-OESP-Token=%(oespToken)s' '&X-OESP-Username=%(oespUsername)s' '&X-OESP-Profile-Id=%(profileId)s' '|%(payload)s|' % dict(url=LICENSE_URL, ua=quote(tv.USER_AGENT), schemeId="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed", oespToken=tv.oesp_token, oespUsername=tv.username, oespLicToken=tv.license_token, oespContentLoc=content_locator, oespLicTokenType="velocix", payload="R{SSM}", deviceId=tv.device_id, profileId=tv.shared_profile_id)) setResolvedUrl(plugin.handle, True, listitem=play_item)
# -*- coding: utf-8 -*- """ Tests for VTM GO API """ # pylint: disable=missing-docstring from __future__ import absolute_import, division, print_function, unicode_literals import unittest import warnings from urllib3.exceptions import InsecureRequestWarning from resources.lib.kodiwrapper import KodiWrapper from resources.lib.vtmgo import vtmgo, vtmgostream, vtmgoauth kodi = KodiWrapper() class TestVtmGo(unittest.TestCase): """ Tests for VTM GO API """ def __init__(self, *args, **kwargs): super(TestVtmGo, self).__init__(*args, **kwargs) self._vtmgoauth = vtmgoauth.VtmGoAuth(kodi) self._vtmgo = vtmgo.VtmGo(kodi) self._vtmgostream = vtmgostream.VtmGoStream(kodi) def setUp(self): # Don't warn that we don't close our HTTPS connections, this is on purpose. # warnings.simplefilter("ignore", ResourceWarning)
from __future__ import absolute_import, division, print_function, unicode_literals import unittest from resources.lib import plugin from resources.lib.kodiwrapper import KodiWrapper xbmc = __import__('xbmc') xbmcaddon = __import__('xbmcaddon') xbmcgui = __import__('xbmcgui') xbmcplugin = __import__('xbmcplugin') xbmcvfs = __import__('xbmcvfs') routing = plugin.routing kodi = KodiWrapper(globals()) class TestRouting(unittest.TestCase): """ Tests for Routing """ def __init__(self, *args, **kwargs): super(TestRouting, self).__init__(*args, **kwargs) def setUp(self): # Don't warn that we don't close our HTTPS connections, this is on purpose. # warnings.simplefilter("ignore", ResourceWarning) pass def test_main_menu(self): routing.run([routing.url_for(plugin.show_main_menu), '0', '']) routing.run(
class BackgroundService(Monitor): """ Background service code """ def __init__(self): Monitor.__init__(self) self.kodi = KodiWrapper() self.vtm_go = VtmGo(self.kodi) self.update_interval = 24 * 3600 # Every 24 hours self.cache_expiry = 30 * 24 * 3600 # One month def run(self): """ Background loop for maintenance tasks """ self.kodi.log('Service started', LOG_INFO) while not self.abortRequested(): # Update every `update_interval` after the last update if self.kodi.get_setting_as_bool('metadata_update') and int(self.kodi.get_setting('metadata_last_updated', 0)) + self.update_interval < time(): self._update_metadata() # Stop when abort requested if self.waitForAbort(10): break self.kodi.log('Service stopped', LOG_INFO) def onSettingsChanged(self): """ Callback when a setting has changed """ # Refresh our VtmGo instance self.vtm_go = VtmGo(self.kodi) def _update_metadata(self): """ Update the metadata for the listings. """ from resources.lib.modules.metadata import Metadata # Clear outdated metadata self.kodi.invalidate_cache(self.cache_expiry) # Create progress indicator progress = self.kodi.show_progress_background(message=self.kodi.localize(30715)) self.kodi.log('Updating metadata in the background') def update_status(i, total): """ Update the progress indicator """ progress.update(int(((i + 1) / total) * 100)) return self.abortRequested() or not self.kodi.get_setting_as_bool('metadata_update') success = Metadata(self.kodi).fetch_metadata(callback=update_status) # Close progress indicator progress.close() # Update metadata_last_updated if success: self.kodi.set_setting('metadata_last_updated', str(int(time())))
# -*- coding: utf-8 -*- """ Addon code """ from __future__ import absolute_import, division, unicode_literals import routing from resources.lib import GeoblockedException, UnavailableException from resources.lib.kodiwrapper import KodiWrapper, TitleItem from resources.lib.vtmgo.vtmgo import Content, VtmGo from resources.lib.vtmgo.vtmgoauth import VtmGoAuth, InvalidLoginException from resources.lib.vtmgo.vtmgoepg import VtmGoEpg from resources.lib.vtmgo.vtmgostream import VtmGoStream routing = routing.Plugin() kodi = KodiWrapper(routing=routing) vtm_go = VtmGo(kodi) @routing.route('/kids') def show_kids_index(): """ Show the main menu (kids) """ show_index() @routing.route('/') def show_index(): """ Show the main menu """ kids = kodi.kids_mode() listing = []
# -*- coding: utf-8 -*- """ Addon code """ from __future__ import absolute_import, division, unicode_literals import logging import routing from resources.lib import kodilogging from resources.lib.kodiwrapper import KodiWrapper kodilogging.config() routing = routing.Plugin() # pylint: disable=invalid-name kodi = KodiWrapper(globals()) # pylint: disable=invalid-name _LOGGER = logging.getLogger('plugin') @routing.route('/') def index(): """ Show the profile selection, or go to the main menu. """ if not kodi.has_credentials() or (kodi.get_setting_as_bool('auto_login') and bool(kodi.get_setting('profile'))): # If we have no credentials (browse only mode) or we have autologin and a profile, go directly to the main menu show_main_menu() else: # Ask the user for the profile to use select_profile()
def _login(self): creds = Credentials() if not creds.are_filled_in(): KodiWrapper.dialog_ok(KodiWrapper.get_localized_string(32014), KodiWrapper.get_localized_string(32015)) KodiWrapper.open_settings() creds.reload() resp = session.post("https://login.prd.telenet.be/openid/login.do", data=login_payload(creds.username, creds.password)) last_response = resp.history[-1] try: if "Location" in last_response.headers: token = self.extract_auth_token( last_response.headers["Location"]) if not token: raise Exceptions.NotAuthorizedException() cache_to_file({"auth_token": token}) except Exceptions.NotAuthorizedException: KodiWrapper.dialog_ok(KodiWrapper.get_localized_string(32006), KodiWrapper.get_localized_string(32007)) if self.auth_tries < 2: self.auth_tries += 1 KodiWrapper.open_settings() self._login()
def __init__(self): Monitor.__init__(self) self.kodi = KodiWrapper() self.vtm_go = VtmGo(self.kodi) self.update_interval = 24 * 3600 # Every 24 hours
class BackgroundService(Monitor): """ Background service code """ def __init__(self): Monitor.__init__(self) self.kodi = KodiWrapper() self.vtm_go = VtmGo(self.kodi) self.update_interval = 24 * 3600 # Every 24 hours def run(self): """ Background loop for maintenance tasks """ self.kodi.log('Service started', LOG_INFO) while not self.abortRequested(): # Update every `update_interval` after the last update if self.kodi.get_setting_as_bool('metadata_update') \ and int(self.kodi.get_setting('metadata_last_updated', 0)) + self.update_interval < time(): self.update_metadata() self.kodi.set_setting('metadata_last_updated', str(int(time()))) # Stop when abort requested if self.waitForAbort(10): break self.kodi.log('Service stopped', LOG_INFO) def onSettingsChanged(self): """ Callback when a setting has changed """ self.kodi.log('IN VTM GO: Settings changed') # Refresh our VtmGo instance self.vtm_go = VtmGo(self.kodi) def update_metadata(self, delay=10): """ Update the metadata for the listings. """ self.kodi.log('Updating metadata in the background') # Clear outdated metadata self.kodi.invalidate_cache(30 * 24 * 3600) # one month vtm_go = self.vtm_go progress = self.kodi.show_progress_background( message=self.kodi.localize(30715)) # Fetch all items from the catalogue items = vtm_go.get_items('all') count = len(items) # Loop over all of them and download the metadata for index, item in enumerate(items): # Update the items if item.video_type == Content.CONTENT_TYPE_MOVIE: if not vtm_go.get_movie(item.content_id, only_cache=True): vtm_go.get_movie(item.content_id) self.waitForAbort(delay / 1000) elif item.video_type == Content.CONTENT_TYPE_PROGRAM: if not vtm_go.get_program(item.content_id, only_cache=True): vtm_go.get_program(item.content_id) self.waitForAbort(delay / 1000) # Upgrade the progress bar progress.update(int(((index + 1) / count) * 100)) # Abort when the setting is disabled or kodi is exiting if self.abortRequested( ) or not self.kodi.get_setting_as_bool('metadata_update'): break # Close the progress dialog progress.close()