Beispiel #1
0
 def detect(self, args):
     if args is not None and len(args) == 1:
         if str(args[0]).strip().lower() in ('music', 'audio'):
             self.music = True
         elif str(args[0]).strip().lower() in ('video', 'movies'):
             self.video = True
         else:
             self.music = common.any2bool(args[0])
     if args is not None and len(args) >= 2:
         self.music = common.any2bool(args[0])
         self.video = common.any2bool(args[1])
Beispiel #2
0
 def _configurations(self):
     # get settings
     common.debug('Reading addon configuration')
     self.__BIOLANGUAGE = common.setting("biography_language")
     self.__RESTRICTCACHE = common.setting("restrict_cache")
     self.__MAXCACHESIZE = common.any2int(
         common.setting("max_cache_size")) * 1000000
     self.__SSLCHECK = common.any2bool(common.setting("ssl_check"))
     self.__NICE = common.any2int(common.setting("nice"), none=10)
Beispiel #3
0
def istrace():
    """
	Checks if the TRACE level is activated. As it was mentioning in the log function, TRACE and DEBUG levels
	can be activated to the Skin level using "trace" skin setting property. In case TRACE level is activated
	to the Skin level will provide messages in the log over NOTICE level and through a particular TRACE channel,
	on top on the default and custom channels.
	:return: True is the TRACE level is active.
	"""
    _TRACE = getSkinSetting("trace")
    if _TRACE is not None:
        return common.any2bool(_TRACE)
    else:
        return False
Beispiel #4
0
 def run(self, mode=-1):
     result = True
     if not common.any2bool(
             xbmc.getInfoLabel("Window(%s).Property(%s)" %
                               (10000, "SystemRecovery.Running"))):
         # set windows setting to true
         window = xbmcgui.Window(10000)
         window.setProperty("SystemRecovery.Running", "true")
         if self.remoteFS.RootPath is not None and self.remoteFS.RootPath != '':
             common.debug(
                 "Local directory: " + self.localFS.RootPath +
                 ", Remote directory: " + self.remoteFS.RootPath,
                 "SystemRecovery")
             if mode == self.Backup:
                 if common.setting("compress_backups"):
                     # delete old temp file
                     if self.localFS.exists(
                             common.path('special://temp/backup.zip')):
                         self.localFS.rmfile(
                             common.path('special://temp/backup.zip'))
                     # save the remote file system and use the zip vfs
                     self.savedRemoteFS = self.remoteFS
                     self.remoteFS = ZipFileSystem(
                         common.path("special://temp/backup.zip"), "w")
                 self.remoteFS.setRootPath(self.remoteFS.RootPath +
                                           time.strftime("%Y%m%d%H%M") +
                                           "/")
                 # run backup process
                 self.backup()
                 result = self.status >= 0
             elif mode == self.Restore:
                 if self.restorePoint.split('.')[-1] != 'zip':
                     self.remoteFS.setRootPath(self.remoteFS.RootPath +
                                               self.restorePoint + "/")
                 # run restore process
                 self.restore()
                 result = self.status >= 0
             else:
                 result = False
             # cleaning locations
             self.localFS.cleanup()
             self.remoteFS.cleanup()
         else:
             result = False
         # reset the window setting
         window.setProperty("SystemRecovery.Running", "")
     else:
         common.warn(
             'Script already running, no additional instance is needed')
         result = False
     return result
Beispiel #5
0
 def _LoadParameters(self):
     try:
         self.__params = dict(
             arg.split("=") for arg in sys.argv[1].split("&"))
     except:
         self.__params = {}
     common.debug("Loading parameters: %s" % str(self.__params))
     self.movies = common.any2bool(self.__params.get("movies", ""))
     self.tvshows = common.any2bool(self.__params.get("tvshows", ""))
     self.episodes = common.any2bool(self.__params.get("episodes", ""))
     self.musicvideos = common.any2bool(self.__params.get(
         "musicvideos", ""))
     self.artists = common.any2bool(self.__params.get("artists", ""))
     self.albums = common.any2bool(self.__params.get("albums", ""))
     self.songs = common.any2bool(self.__params.get("songs", ""))
     self.actors = common.any2bool(self.__params.get("actors", ""))
Beispiel #6
0
def isdebug():
    """
	Checks if the DEBUG level is activated. As it was mentioning in the log function, DEBUG level
	can be activated to the Skin level using 'debug' skin setting property, or to the Kodi system
	configuration. level (using Logging area). In case DEBUG level is activated to the Skin level
	will provide messages in the log over NOTICE level and through a particular DEBUG channel,
	on top on the default and custom channels.
	:return: True is the DEBUG level is active.
	"""
    _DEBUG = getSkinSetting("debug")
    if _DEBUG is not None:
        return common.any2bool(_DEBUG)
    else:
        return False
Beispiel #7
0
 def _providers(self):
     # read and load plugins
     common.debug('Discovering content providers')
     for cls in ContentProvider.__subclasses__():
         try:
             plugin = cls()
             module = str(cls.__name__).lower()
             if (module == 'local'
                     or common.any2bool(common.setting(module))
                 ) and not module in self.PROVIDERS:
                 self.PROVIDERS[module] = plugin
                 common.debug('Loading provider: %s ' % module)
         except BaseException as be:
             common.error(
                 'Unexpected error while loading [%s] provider: %s' %
                 (str(cls), str(be)))
Beispiel #8
0
def getproxies():
    """
	Get and merge the proxy configuration defined to the OS level and to Kodi level, over
	Kodi graphical interface.
	"""
    global PROXIES
    if PROXIES is None:
        if common.any2bool(common.getSystemSetting("network.usehttpproxy"),
                           none=False):
            httpproxytype = common.getSystemSetting("network.httpproxytype")
            httpproxyserver = common.getSystemSetting(
                "network.httpproxyserver")
            httpproxyport = common.getSystemSetting("network.httpproxyport")
            httpproxyusername = common.getSystemSetting(
                "network.httpproxyusername")
            httpproxypassword = common.getSystemSetting(
                "network.httpproxypassword")
            proxyurl = httpproxyserver + ":" + httpproxyport
            if httpproxyusername is not None and httpproxyusername != '':
                proxyurl = httpproxyusername + ":" + httpproxypassword + "@" + proxyurl
            if common.any2int(httpproxytype) == 0:
                if common.any2int(httpproxyport) == 443 or common.any2int(
                        httpproxyport) == 8443:
                    proxyurl = "https://" + proxyurl
                else:
                    proxyurl = "http://" + proxyurl
            elif common.any2int(httpproxytype) == 1 or common.any2int(
                    httpproxytype) == 2:
                proxyurl = "socks4://" + proxyurl
            elif common.any2int(httpproxytype) == 3 or common.any2int(
                    httpproxytype) == 4:
                proxyurl = "socks4://" + proxyurl
            PROXIES = {'http': proxyurl, 'https': proxyurl}
            common.trace("Detecting proxy in Kodi: %s" % proxyurl, "urlcall")
        else:
            PROXIES = {}
    return PROXIES
Beispiel #9
0
	def getImageList(self, params):
		common.trace("Starting to search images using parameters: %s" % str(params), "fanarttv")
		images = []
		url_params = {}
		filepath = os.path.join(params.get('infodir', ''), self.FILENAME)
		cachefilepath = os.path.join(params.get('infodir', ''), self.CACHETIMEFILENAME)
		if params.get('mbid', '') == '':
			common.trace("Searching for MusicBrainz ID")
			params['mbid'] = self.getMusicBrainzID(params['artist'])
		url = self.URL_MUSICSEARCH + params.get('mbid', '')
		url_params['api_key'] = params.get("clientapikey")
		json_data = self._getData(filepath, cachefilepath, url, url_params)
		if json_data is not None and json_data:
			image_list = json_data.get('artistbackground', [])
			if common.any2bool(params.get('getall', 'false')):
				image_list.extend(json_data.get('artistthumb', []))
			for image in image_list:
				url = image.get('url', '')
				if url:
					images.append(url)
		if not images:
			return []
		else:
			return self._delExclusions(images, params.get('exclusionsfile'))
Beispiel #10
0
 def any2bool(self, v, error=False, none=True):
     return common.any2bool(v, error=error, none=none)
Beispiel #11
0
	def getImageList(self, params):
		common.trace("Starting to search images using parameters: %s" %str(params), "duckgo")
		images = []
		if params.get('mbid', '') == '':
			common.warn("No artist identified over MusicBrainz, search stopped")
			return images
		if "fullname" in params and not common.isempty(params['fullname']):
			keywords = params['fullname'] + " AND (singer OR band)"
		elif "alias" in params and not common.isempty(params['alias']):
			keywords = params['alias'] + " AND (singer OR band)"
		elif "artist" in params and not common.isempty(params['artist']):
			keywords = params['artist'] + " AND (singer OR band)"
		else:
			keywords = None
		if keywords is not None and "location" in params and not common.isempty(params['location']):
			keywords = keywords + " AND " + params['location']
		elif keywords is not None and "lang" in params and not common.isempty(params['lang']):
			keywords = keywords + " AND " + params['lang']
		if keywords is not None:
			payload = {'q': keywords}
			common.trace("Hitting DuckDuckGo for token", "duckgo")
			data = common.urlcall(self.DDG_SEARCH_URL, "POST", payload=payload)
			searchObj = re.search(r'vqd=([\d-]+)\&', data, re.M | re.I)
			if not searchObj:
				common.error("Token parsing failed!", "duckgo")
				return images
			else:
				common.debug("Obtained token: %s" % searchObj.group(1), "duckgo")
			headers = {
				'authority': 'duckduckgo.com',
				'accept': 'application/json, text/javascript, */*; q=0.01',
				'sec-fetch-dest': 'empty',
				'x-requested-with': 'XMLHttpRequest',
				'user-agent': common.agent(),
				'sec-fetch-site': 'same-origin',
				'sec-fetch-mode': 'cors',
				'referer': 'https://duckduckgo.com/'
			}
			payload = {
				"q": keywords,
				"vqd": searchObj.group(1),
				"v7exp": "a",
				"o": "json",
				"l": "wt-wt",
				"f": ",,,",
				"p": '1'
			}
			data = None
			while True:
				try:
					data = common.urlcall(self.DDG_SEARCH_URL + "i.js", headers=headers, payload=payload, output='json')
					break
				except ValueError as e:
					common.trace("Calling url failure; sleep and retry", "duckgo")
					common.sleep(500)
					continue
			index = 0
			max = common.any2int(params['limit'], 0)
			for obj in data["results"]:
				contextual = str(obj["title"].encode('utf-8')).lower().find(params['artist'].lower() + " ") >= 0
				dimension = int(obj["width"]) >= 876 if common.any2bool(params.get('getall', 'false')) else int(obj["width"]) >= 1920
				if contextual and dimension:
					index += 1
					images.append(obj["image"])
				if max > 0 and index >= max:
					break
		if not images:
			return []
		else:
			return self._delExclusions(images, params.get('exclusionsfile'))
Beispiel #12
0
# -*- coding: utf-8 -*-
Beispiel #13
0
 def addonrunning(self):
     return common.any2bool(self.getSkinProperty("SlideshowAddon.Running"))
Beispiel #14
0
 def addoninfo(self):
     return common.any2bool(self.getSkinProperty("SlideshowAddon"))
Beispiel #15
0
 def run(self, index):
     """ Runs package for content discovery and processing"""
     # check if forecast workflow is enabled
     if not common.setting('Enabled'):
         return
     # check provider configuration
     provider = self.getProviderByCode(common.setting('ProviderCode'))
     common.debug("Found provider to run forecast workflow: %s" % provider)
     if provider is None:
         common.NotificationMsg(32202, 15000)
         return
     if provider is not None and (
         (common.setting('APIKey') == ''
          or common.setting('APIKey') is None)
             and common.any2bool(common.setting("ShowAPIKeyOption"))):
         common.NotificationMsg(32123, 15000)
         return
     # validate provider configuration
     if common.any2bool(common.setting("ShowAPIKeyOption")):
         try:
             provider.validate()
             common.debug(
                 "Content provider is valid, running weather forecast workflow"
             )
         except BaseException as err:
             common.debug(
                 "Content provider is invalid, reset forecast skin properties: %s"
                 % str(err))
             common.NotificationMsg(32203, 20000)
             provider.clear()
             return
     # normalize locations
     count = 0
     found = False
     for id in range(1, 6):
         locname = common.setting('Location%iAction' % id)
         locid = common.setting('Location%i' % id)
         if not found and (locname != '' and locid != ''):
             count += 1
         elif not found and (locname == '' or locid == ''):
             found = True
         if found:
             common.setSkinProperty(12600, 'Location%i' % id)
             common.setsetting('Location%iAction' % id)
             common.setsetting('Location%i' % id)
         else:
             common.setSkinProperty(12600, 'Location%i' % id, locname)
     common.setSkinProperty(12600, 'Locations', str(count))
     common.debug("Active locations: %s" % str(count))
     # identify the right location
     if index is None:
         common.debug(
             'Run GeoIP location discovery due to missing configuration')
         locname, locid = provider.geoip()
     else:
         common.debug("Using location index: %s" % str(index))
         locname = common.setting('Location%sAction' % str(index))
         locid = common.setting('Location%s' % str(index))
     if locid == '' and common.any2int(index) > 1:
         common.debug(
             'Trying first location instead, due to invalid index defined in previous configuration'
         )
         locname = common.setting('Location1Action')
         locid = common.setting('Location1')
     if locid == '':
         common.debug(
             'Run GeoIP location discovery due to wrong configuration')
         locname, locid = provider.geoip()
     # run forecast workflow
     if locname != '':
         # reset skin properties when the location is changed
         if locid != provider.skininfo("Current.Location"):
             provider.clear()
         # publish provider details
         provider.skinproperty('WeatherProvider', provider.name())
         if os.path.isfile(
                 common.path('resources', 'media',
                             provider.code() + '.png')):
             provider.skinproperty(
                 'WeatherProviderLogo',
                 common.path('resources', 'media',
                             provider.code() + '.png'))
         else:
             provider.skinproperty('WeatherProviderLogo',
                                   common.path('icon.png'))
         # call provider forecast
         common.debug('Call forecast for location %s (%s)' %
                      (locname, locid))
         provider.forecast(locname, locid)
     else:
         common.warn('No location found or configured')
         provider.clear()