def __init__(self, api_key=None): '''Initialize our Module''' if api_key: self.api_key = api_key self.cache = SimpleCache() self._win = xbmcgui.Window(10000) self._addon = xbmcaddon.Addon(ADDON_ID) addonversion = self._addon.getAddonInfo('version').decode("utf-8") self.cache.global_checksum = addonversion self._log_msg("Initialized")
def __init__(self, simplecache=None, kodidb=None): '''Initialize - optionaly provide simplecache object''' if not simplecache: from simplecache import SimpleCache self.cache = SimpleCache() else: self.cache = simplecache if not kodidb: from kodidb import KodiDb self.kodidb = KodiDb(self.cache) else: self.kodidb = kodidb
def __init__(self, simplecache=None): """Initialize - optionaly provide simplecache object""" if not simplecache: from simplecache import SimpleCache self.cache = SimpleCache() else: self.cache = simplecache addon = xbmcaddon.Addon(id=ADDON_ID) api_key = addon.getSetting("adb_apikey") if api_key: self.api_key = api_key del addon
def __init__(self, sysARG=sys.argv): log('__init__, sysARG = %s' % (sysARG)) self.sysARG = sysARG self.cache = SimpleCache() self.token = (REAL_SETTINGS.getSetting('User_Token') or None) self.lastDMA = 0 self.now = datetime.datetime.now() self.lat, self.lon = self.setRegion() if self.login(REAL_SETTINGS.getSetting('User_Email'), REAL_SETTINGS.getSetting('User_Password')) == False: sys.exit() else: self.city = self.getRegion()
def __init__(self, api_key=None): '''Initialize our Module''' if api_key: self.api_key = api_key self.cache = SimpleCache() self._win = xbmcgui.Window(10000) self._addon = xbmcaddon.Addon(ADDON_ID) if sys.version_info.major == 3: addonversion = self._addon.getAddonInfo('version') else: addonversion = self._addon.getAddonInfo('version').decode("utf-8") self.cache.global_checksum = "%s%s" % (addonversion, KODI_LANGUAGE) self._log_msg("Initialized")
def __init__(self, simplecache=None, api_key=None): '''Initialize - optionaly provide simplecache object''' if not simplecache: from simplecache import SimpleCache self.cache = SimpleCache() else: self.cache = simplecache addon = xbmcaddon.Addon(id=ADDON_ID) # personal api key (preferred over provided api key) api_key = addon.getSetting("tmdb_apikey") if api_key: self.api_key = api_key del addon
def __init__(self, *args, **kwargs): xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs) if DISABLE_TRAKT: xbmcgui.Window(10000).setProperty('script.trakt.paused', 'true') self.playList = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) self.fileCount = 0 self.cache = SimpleCache() self.myPlayer = Player() self.myPlayer.myBackground = self if saveVolume(): setVolume(int(REAL_SETTINGS.getSetting('SetVolume'))) setRepeat('all')
def __init__(self, sysARG=sys.argv, dma=getLastDMA()): log('__init__, sysARG = %s' % (sysARG)) self.sysARG = sysARG self.cache = SimpleCache() self.token = (REAL_SETTINGS.getSetting('User_Token') or None) if not self.login(): sys.exit() else: self.lat, self.lon, self.zone, self.dma, self.now = self.getRegion( ) if self.dma != getLastDMA(): REAL_SETTINGS.setSetting('User_LastDMA', str(self.dma))
def __init__(self, simplecache=None, kodidb=None): """Initialize - optionaly provide SimpleCache and KodiDb object""" if not kodidb: from kodidb import KodiDb self.kodidb = KodiDb() else: self.kodidb = kodidb if not simplecache: from simplecache import SimpleCache self.cache = SimpleCache() else: self.cache = simplecache
def __init__(self, sysARG): log('__init__, sysARG = ' + str(sysARG)) self.sysARG = sysARG self.cache = SimpleCache() self.header = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36', 'content-type': 'application/json; charset=utf8', 'tenant-code': '%s' % BRAND, 'session-id': LAST_TOKEN, 'box-id': BOX_ID, 'origin': BASEWEB, 'DNT': '1' }
def get_repo_resourceaddons(filterstr=""): '''helper to retrieve all available resource addons on the kodi repo''' result = [] simplecache = SimpleCache() for item in xbmcvfs.listdir("addons://all/kodi.resource.images/")[1]: if not filterstr or item.lower().startswith(filterstr.lower()): addoninfo = get_repo_addoninfo(item, simplecache) if not addoninfo.get("name"): addoninfo = {"addonid": item, "name": item, "author": ""} addoninfo["thumbnail"] = "http://mirrors.kodi.tv/addons/krypton/%s/icon.png" % item addoninfo["path"] = "resource://%s/" % item result.append(addoninfo) simplecache.close() return result
def __init__(self, simplecache=None, kodidb=None): """Initialize - optionaly provide simplecache object""" if not simplecache: from simplecache import SimpleCache self.cache = SimpleCache() else: self.cache = simplecache if not kodidb: if sys.version_info.major == 3: from .kodidb import KodiDb else: from kodidb import KodiDb self.kodidb = KodiDb() else: self.kodidb = kodidb
def __init__(self): self.cache = SimpleCache() self.mutils = MetadataUtils() self.win = xbmcgui.Window(10000) try: self.params = dict( urlparse.parse_qsl(sys.argv[2].replace( '?', '').lower().decode("utf-8"))) log_msg("plugin called with parameters: %s" % self.params) self.main() except Exception as exc: log_exception(__name__, exc) xbmcplugin.endOfDirectory(handle=int(sys.argv[1])) # cleanup when done processing self.close()
def __init__(self, simplecache=None): """Initialize - optionaly provide simplecache object""" if not simplecache: from simplecache import SimpleCache self.cache = SimpleCache() else: self.cache = simplecache import musicbrainzngs as mbrainz mbrainz.set_useragent( "script.skin.helper.service", "1.0.0", "https://github.com/marcelveldt/script.skin.helper.service") mbrainz.set_rate_limit(limit_or_interval=2.0, new_requests=1) addon = xbmcaddon.Addon(ADDON_ID) if addon.getSetting("music_art_mb_mirror"): mbrainz.set_hostname(addon.getSetting("music_art_mb_mirror")) del addon self.mbrainz = mbrainz
def __init__(self, username, password): self._username = username self._password = password self._cache_id = "plugin.video.mubi.filminfo.%s" self._simplecache = SimpleCache() # Need a 20 digit id, hash username to make it predictable self._udid = int(hashlib.sha1(username).hexdigest(), 32) % (10**20) self._token = None self._userid = None self._country = None self._headers = { 'client': 'android', 'client-app': 'mubi', 'client-version': '4.46', 'client-device-identifier': str(self._udid) } self.login()
def __init__(self, username, password): self._username = username self._password = password self._cache_id = "plugin.video.mubi.filminfo.%s" self._simplecache = SimpleCache() # Need a 20 digit id, hash username to make it predictable self._udid = int(hashlib.sha1(username).hexdigest(), 32) % (10**20) self._token = None self._userid = None self._country = None # The new mubi API (under the route /api/v1/[...] rather than /services/android) asks for these header fields: self._headers = { 'client': 'android', 'client-app': 'mubi', 'client-version': APP_VERSION_CODE, 'client-device-identifier': str(self._udid) } self.login()
def __init__(self): '''Initialize and load all our helpers''' self._studiologos_path = "" self.cache = SimpleCache() self.addon = xbmcaddon.Addon(ADDON_ID) self.kodidb = KodiDb() self.omdb = Omdb(self.cache) self.tmdb = Tmdb(self.cache) self.channellogos = ChannelLogos(self.kodidb) self.fanarttv = FanartTv(self.cache) self.imdb = Imdb(self.cache) self.google = GoogleImages(self.cache) self.studiologos = StudioLogos(self.cache) self.animatedart = AnimatedArt(self.cache, self.kodidb) self.thetvdb = TheTvDb() self.musicart = MusicArtwork(self) self.pvrart = PvrArtwork(self) log_msg("Initialized")
def retrieveCatalog(): try: cache = SimpleCache() catalog = cache.get(ADDON_NAME + '.catalog') if catalog: log("using cached catalog") if not catalog: log("downloading catalog") opener = FancyURLopener() f = opener.open(url) catalog = json.load(f) cache.set(ADDON_NAME + '.catalog', catalog, expiration=datetime.timedelta(hours=12)) return catalog except Exception as e: log("error retrieving catalog - " + str(e), xbmc.LOGERROR) xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30003), ICON, 4000) xbmc.executebuiltin('Action(PreviousMenu)') sys.exit(0)
def __init__(self, username, password): self._username = username self._password = password self._cache_id = "plugin.video.mubi.filminfo.%s" self._simplecache = SimpleCache() # Need a 20 digit id, hash username to make it predictable self._udid = int(hashlib.sha1(username).hexdigest(), 32) % (10 ** 20) self._token = None self._userid = None self._country = None # The new mubi API (under the route /api/v1/[...] rather than /services/android) asks for these header fields: self._session = requests.Session() self._session.headers.update({ 'accept': 'application/json, text/plain, */*', 'client': 'android', 'client-app': 'mubi', 'client-version': APP_VERSION_CODE, 'client-device-identifier': str(self._udid), 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.123 Safari/537.36', 'if-none-match': 'W/"505d0033184d7877a3b351d8c94b6211"' }) self.login()
def __init__(self): '''Initialization and main code run''' self.win = xbmcgui.Window(10000) self.addon = xbmcaddon.Addon(ADDON_ID) self.kodidb = KodiDb() self.cache = SimpleCache() self.params = self.get_params() log_msg("MainModule called with parameters: %s" % self.params) action = self.params.get("action", "") # launch module for action provided by this script try: getattr(self, action)() except AttributeError: log_exception(__name__, "No such action: %s" % action) except Exception as exc: log_exception(__name__, exc) finally: xbmc.executebuiltin("dialog.Close(busydialog)") # do cleanup self.close()
def __init__(self): ''' Initialization ''' self.metadatautils = MetadataUtils() self.cache = SimpleCache() self.addon = xbmcaddon.Addon(ADDON_ID) self.win = xbmcgui.Window(10000) self.options = self.get_options() # skip if shutdown requested if self.win.getProperty("SkinHelperShutdownRequested"): log_msg("Not forfilling request: Kodi is exiting!", xbmc.LOGWARNING) xbmcplugin.endOfDirectory(handle=ADDON_HANDLE) return if not "mediatype" in self.options or not "action" in self.options: # we need both mediatype and action, so show the main listing self.mainlisting() else: # we have a mediatype and action so display the widget listing self.show_widget_listing() self.close()
def __init__(self): self.cache = SimpleCache()
def __init__( self, *args, **kwargs ): self.cache = SimpleCache() self.isExiting = False
def __init__(self): self.cache = SimpleCache() self.pyHDHR = PyHDHR.PyHDHR() self.tuners = self.getTuners() self.hasDVR = self.pyHDHR.hasSDDVR()
'plot': j['opis'].encode('utf-8'), 'mediatype': 'video', 'tracknumber': i } li.setInfo('video', itemArgs) playlist.add(url=j['stream_url'], listitem=li) player.play(item=playlist, startpos=channel_index) player.seekTime(channel_offset) addon_name = 'plugin.video.carnet-meduza' addon = xbmcaddon.Addon(addon_name) # get username/apikey from settings aai_username = addon.getSetting('aai_username') #get some data from cache simplecache = SimpleCache() tmp_store = simplecache.get(addon_name + '.tmp_store') dialog = xbmcgui.Dialog() if not tmp_store: initcheck = initCheck(addon_name) api_key, dev_reg_status = initcheck.store_key() addon.setSetting('apikey', api_key) #if aai_username missing open settings, otherwise start device registration if not aai_username and dev_reg_status == 'not_reg': info_dialog_msg = addon.getLocalizedString(30214) dialog.notification('CARNet Meduza', info_dialog_msg, xbmcgui.NOTIFICATION_INFO, 4000) xbmcaddon.Addon().openSettings() elif dev_reg_status == 'not_reg': reg_response = initcheck.dev_reg(api_key)
def __init__( self, *args, **kwargs ): self.isExiting = False self.cache = SimpleCache() self.baseAPI = BASE_API
class Addon: """Helper class for Addon communication""" cache = SimpleCache() cache.enable_mem_cache = False def __init__(self, addon_id, addon_obj, channels_uri, epg_uri): self.addon_id = addon_id self.addon_obj = addon_obj self.channels_uri = channels_uri self.epg_uri = epg_uri addon = kodiutils.get_addon(addon_id) self.addon_path = kodiutils.addon_path(addon) @staticmethod def getLocalTime(): offset = (datetime.datetime.utcnow() - datetime.datetime.now()) return datetime.datetime.fromtimestamp( float(time.time() + offset.total_seconds())) @classmethod def refresh(cls, show_progress=False, force=False): """Update channels and EPG data""" channels = [] epg = [] if show_progress: progress = kodiutils.progress( message=kodiutils.localize(30703)) # Detecting IPTV add-ons... else: progress = None addons = cls.detect_iptv_addons() for index, addon in enumerate(addons): """Check if addon requires update""" if not force and not cls.is_refresh_required(addon.addon_id): addon_epg = cls.cache.get('iptvmanager.epg.%s' % (addon.addon_id)) addon_channel = cls.cache.get('iptvmanager.channel.%s' % (addon.addon_id)) if addon_epg and addon_channel: _LOGGER.info('Update not needed for %s...', addon.addon_id) channels.append(addon_channel) epg.append(addon_epg) continue if progress: # Fetching channels and guide of {addon}... progress.update( int(100 * index / len(addons)), kodiutils.localize(30704).format( addon=kodiutils.addon_name(addon.addon_obj))) _LOGGER.info('Updating IPTV data for %s...', addon.addon_id) # Fetch channels addon_channel = dict( addon_id=addon.addon_id, addon_name=kodiutils.addon_name(addon.addon_obj), channels=addon.get_channels(), ) channels.append(addon_channel) if progress and progress.iscanceled(): progress.close() return # Fetch EPG addon_epg = addon.get_epg() cls.set_cache_n_update(cls, addon.addon_id, addon_epg, addon_channel) epg.append(addon_epg) if progress and progress.iscanceled(): progress.close() return # Write files if show_progress: progress.update( 100, kodiutils.localize(30705)) # Updating channels and guide... IptvSimple.write_playlist(channels) IptvSimple.write_epg(epg, channels) if kodiutils.get_setting_bool('iptv_simple_restart'): if show_progress: # Restart now. IptvSimple.restart(True) else: # Try to restart now. We will schedule it if the user is watching TV. IptvSimple.restart(False) # Update last_refreshed kodiutils.set_property('last_refreshed', int(time.time())) if show_progress: progress.close() @staticmethod def is_refresh_required(addon_id): refresh_required = False now = Addon.getLocalTime() if now >= dateutil.parser.parse( kodiutils.get_setting( '%s.next_update' % (addon_id), now.strftime('%Y%m%d%H%M%S %z').rstrip())): refresh_required = True _LOGGER.info('%s is refresh required? %s' % (addon_id, refresh_required)) return refresh_required def set_cache_n_update(self, addon_id, addon_epg, addon_channel): """Find epgs min. Start and min. Stop time""" now = self.getLocalTime() max_start = min([ min([ dateutil.parser.parse(program['start']) for program in programmes ], default=now) for channel, programmes in addon_epg.items() ], default=now) #earliest first start max_stop = min([ max([ dateutil.parser.parse(program['stop']) for program in programmes ], default=now) for channel, programmes in addon_epg.items() ], default=now) #earliest last stop guide_hours, r = divmod( abs(max_start - max_stop).total_seconds(), 3600) #amount of guidedata available. half_life_hours = round(guide_hours // 2) #guidedata half life (update time). next_update = (max_stop - datetime.timedelta(hours=half_life_hours) ) #start update prematurely to assure no gaps in meta. cache_life = abs(now - next_update).total_seconds() self.cache.set('iptvmanager.epg.%s' % (addon_id), addon_epg, expiration=datetime.timedelta(seconds=cache_life)) self.cache.set('iptvmanager.channel.%s' % (addon_id), addon_channel, expiration=datetime.timedelta(seconds=cache_life)) kodiutils.set_setting('%s.next_update' % (addon_id), next_update.strftime('%Y%m%d%H%M%S %z').rstrip()) _LOGGER.info( '%s next update %s, life %s' % (addon_id, next_update.strftime('%Y%m%d%H%M%S %z').rstrip(), half_life_hours)) @staticmethod def detect_iptv_addons(): """Find add-ons that provide IPTV channel data""" result = kodiutils.jsonrpc(method="Addons.GetAddons", params={ 'installed': True, 'enabled': True, 'type': 'xbmc.python.pluginsource' }) addons = [] for row in result['result'].get('addons', []): addon = kodiutils.get_addon(row['addonid']) # Check if add-on supports IPTV Manager if addon.getSetting('iptv.enabled') != 'true': continue addons.append( Addon( addon_id=row['addonid'], addon_obj=addon, channels_uri=addon.getSetting('iptv.channels_uri'), epg_uri=addon.getSetting('iptv.epg_uri'), )) return addons def get_channels(self): """Get channel data from this add-on""" _LOGGER.info('Requesting channels from %s...', self.channels_uri) if not self.channels_uri: return [] try: data = self._get_data_from_addon(self.channels_uri) _LOGGER.debug(data) except Exception as exc: # pylint: disable=broad-except _LOGGER.error('Something went wrong while calling %s: %s', self.addon_id, exc) return [] # Return M3U8-format as-is without headers if not isinstance(data, dict): return data.replace('#EXTM3U\n', '') # JSON-STREAMS format if data.get('version', 1) > CHANNELS_VERSION: _LOGGER.warning( 'Skipping %s since it uses an unsupported version: %d', self.channels_uri, data.get('version')) return [] channels = [] for channel in data.get('streams', []): # Check for required fields if not channel.get('name') or not channel.get('stream'): _LOGGER.warning('Skipping channel since it is incomplete: %s', channel) continue # Fix logo path to be absolute if not channel.get('logo'): channel['logo'] = kodiutils.addon_icon(self.addon_obj) elif not channel.get('logo').startswith( ('http://', 'https://', 'special://', 'resource://', '/')): channel['logo'] = os.path.join(self.addon_path, channel.get('logo')) # Ensure group is a set if not channel.get('group'): channel['group'] = set() # Accept string values (backward compatible) elif isinstance(channel.get('group'), (bytes, str)): channel['group'] = set(channel.get('group').split(';')) # Accept string values (backward compatible, py2 version) elif sys.version_info.major == 2 and isinstance( channel.get('group'), unicode): # noqa: F821; pylint: disable=undefined-variable channel['group'] = set(channel.get('group').split(';')) elif isinstance(channel.get('group'), list): channel['group'] = set(list(channel.get('group'))) else: _LOGGER.warning('Channel group is not a list: %s', channel) channel['group'] = set() # Add add-on name as group, if not already channel['group'].add(kodiutils.addon_name(self.addon_obj)) channels.append(channel) return channels def get_epg(self): """Get epg data from this add-on""" if not self.epg_uri: return {} _LOGGER.info('Requesting epg from %s...', self.epg_uri) try: data = self._get_data_from_addon(self.epg_uri) _LOGGER.debug(data) except Exception as exc: # pylint: disable=broad-except _LOGGER.error('Something went wrong while calling %s: %s', self.addon_id, exc) return {} # Return XMLTV-format as-is without headers and footers if not isinstance(data, dict): return re.search(r'<tv[^>]*>(.*)</tv>', data, flags=re.DOTALL).group(1).strip() # JSON-EPG format if data.get('version', 1) > EPG_VERSION: _LOGGER.warning( 'Skipping EPG from %s since it uses an unsupported version: %d', self.epg_uri, data.get('version')) return {} # Check for required fields if not data.get('epg'): _LOGGER.warning('Skipping EPG from %s since it is incomplete', self.epg_uri) return {} return data['epg'] def _get_data_from_addon(self, uri): """Request data from the specified URI""" # Plugin path if uri.startswith('plugin://'): # Prepare data sock = self._prepare_for_data() uri = update_qs(uri, port=sock.getsockname()[1]) _LOGGER.info('Executing RunPlugin(%s)...', uri) kodiutils.execute_builtin('RunPlugin', uri) # Wait for data result = self._wait_for_data(sock) # Load data data = json.loads(result) return data # Currently, only plugin:// uris are supported raise NotImplementedError @staticmethod def _prepare_for_data(): """Prepare ourselves so we can receive data""" # Bind on localhost on a free port above 1024 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 0)) _LOGGER.debug('Bound on port %s...', sock.getsockname()[1]) # Listen for one connection sock.listen(1) return sock def _wait_for_data(self, sock, timeout=10): """Wait for data to arrive on the socket""" # Set a connection timeout # The remote and should connect back as soon as possible so we know that the request is being processed sock.settimeout(timeout) try: _LOGGER.debug('Waiting for a connection from %s on port %s...', self.addon_id, sock.getsockname()[1]) # Accept one client conn, addr = sock.accept() _LOGGER.debug('Connected to %s:%s! Waiting for result...', addr[0], addr[1]) # We have no timeout when the connection is established conn.settimeout(None) # Read until the remote end closes the connection buf = '' while True: chunk = conn.recv(4096) if not chunk: break buf += chunk.decode() if not buf: # We got an empty reply, this means that something didn't go according to plan raise Exception('Something went wrong in %s' % self.addon_id) return buf except socket.timeout: raise Exception('Timout waiting for reply on port %s' % sock.getsockname()[1]) finally: # Close our socket _LOGGER.debug('Closing socket on port %s', sock.getsockname()[1]) sock.close()
def __init__(self, sysARG): log('__init__, sysARG = ' + str(sysARG)) self.sysARG = sysARG self.cache = SimpleCache() if URLTYPE == 'upnp': self.chkUPNP()
def __init__(self): log('__init__') self.cache = SimpleCache()
def __init__(self): '''Initialize and load all our helpers''' self.cache = SimpleCache() log_msg("Initialized")