Exemple #1
0
 def get_platform():
     if xbmc.getCondVisibility('system.platform.windows') == True:
         return WINDOWS
     elif xbmc.getCondVisibility('system.platform.linux') == True:
         return LINUX
     elif xbmc.getCondVisibility('system.platform.xbox') == True:
         return XBOX
    def __init__(self):
        self._parse_argv()

        self.tokens = {}
        sortLetterList = list()
        # 0 if false, 1 if true
        hasParentItem = xbmc.getCondVisibility('System.GetBool(filelists.showparentdiritems)')
        ignoreArticles = xbmc.getCondVisibility('System.GetBool(filelists.ignorethewhensorting)')
        wid = xbmcgui.getCurrentWindowId()
        currentWindow = xbmcgui.Window(wid)

        # get sort tokens from advancedsettings.xml
        f = xbmcvfs.File(xbmc.translatePath('special://userdata/advancedsettings.xml'))
        advancedsettings = f.read()
        f.close()

        if advancedsettings:
            root = ET.fromstring(advancedsettings)
            sorttokens = root.find('sorttokens')
            # user specified tokens, proceed to create dictionary
            if sorttokens is not None:
                self.tokens = { token.text.encode('utf-8') : u'' for token in sorttokens.findall('token') }

        if self.TYPE == "scroll":
            xbmcplugin.setResolvedUrl(handle=self.handle, succeeded=False, listitem=xbmcgui.ListItem())
            containerId = self._get_view_mode()
            targetList = currentWindow.getControl(containerId)
            targetList.selectItem(int(self.pos))
            currentWindow.setFocus(targetList)
        elif self.path:
            xbmcplugin.setContent(self.handle, 'files')
            self._parse_files(sortLetterList, hasParentItem, ignoreArticles)
            xbmcplugin.addDirectoryItems(self.handle, sortLetterList)
            xbmcplugin.endOfDirectory(handle=self.handle)
        return
  def playing_type(self):
    type = 'unkown'
    if type == 'unkown':
		
		oncenb=0
	  
    if (self.isPlayingAudio()):
		type = "music"
		oncenb=1
	
    if xbmc.getCondVisibility('VideoPlayer.Content(movies)'):
        filename = ''
        isMovie = True
        try:
          filename = self.getPlayingFile()
        except:
          pass
        if filename != '':
          for string in self.substrings:
            if string in filename:
              isMovie = False
              break
        if isMovie:
          type = "movie"
    if xbmc.getCondVisibility('VideoPlayer.Content(episodes)'):
        # Check for tv show title and season to make sure it's really an episode
        if xbmc.getInfoLabel('VideoPlayer.Season') != "" and xbmc.getInfoLabel('VideoPlayer.TVShowTitle') != "":
           type = "episode"
		
	#else:
		#type = 'unkown'
		
    return 'type=' + type 
Exemple #4
0
 def multi_select(options, window_header=""):
     '''allows the user to choose from multiple options'''
     listitems = []
     for option in options:
         if not option["condition"] or xbmc.getCondVisibility(option["condition"]):
             listitem = xbmcgui.ListItem(label=option["label"], label2=option["description"])
             listitem.setProperty("id", option["id"])
             if xbmc.getCondVisibility("Skin.HasSetting(%s)" % option["id"]) or (not xbmc.getInfoLabel(
                     "Skin.String(defaultset_%s)" % option["id"]) and xbmc.getCondVisibility(option["default"])):
                 listitem.select(selected=True)
             listitems.append(listitem)
     # show select dialog
     dialog = DialogSelect("DialogSelect.xml", "", listing=listitems, windowtitle=window_header, multiselect=True)
     dialog.doModal()
     result = dialog.result
     if result:
         for item in result:
             if item.isSelected():
                 # option is enabled
                 xbmc.executebuiltin("Skin.SetBool(%s)" % item.getProperty("id"))
             else:
                 # option is disabled
                 xbmc.executebuiltin("Skin.Reset(%s)" % item.getProperty("id"))
         # always set additional prop to define the defaults
         xbmc.executebuiltin("Skin.SetString(defaultset_%s,defaultset)" % item.getProperty("id"))
     del dialog
  def onPlayBackStopped(self):
	log('player stops')
	type = 'unkown'
	if (self.isPlayingAudio()):
	  type = "music"
	else:
		if xbmc.getCondVisibility('VideoPlayer.Content(movies)'):
			filename = ''
			isMovie = True
		try:
			filename = self.getPlayingFile()
		except:
			pass
		if filename != '':
			for string in self.substrings:
				if string in filename:
					isMovie = False
					break
		if isMovie:
			type = "movie"
		elif xbmc.getCondVisibility('VideoPlayer.Content(episodes)'):
	  # Check for tv show title and season to make sure it's really an episode
			if xbmc.getInfoLabel('VideoPlayer.Season') != "" and xbmc.getInfoLabel('VideoPlayer.TVShowTitle') != "":
				type = "episode"
	typevar=type
	
	if typevar!="music":
		global script_playerV_stops
		log('Going to execute script = "' + script_playerV_stops + '"')
		xbmc.executebuiltin('XBMC.RunScript('+script_playerV_stops+ ", " + self.playing_type()+')')
	if typevar=="music":
		global script_playerA_stops
		log('Going to execute script = "' + script_playerA_stops + '"')
		xbmc.executebuiltin('XBMC.RunScript('+script_playerA_stops+ ", " + self.playing_type()+')')
Exemple #6
0
def check_for_updates():
	try:
		version_source = get_page_source(version_control)
	except: version_source = ""
	if version_source:
		version_source = eval(version_source)
		if xbmc.getCondVisibility('system.platform.linux') and not xbmc.getCondVisibility('system.platform.Android'):
			if "arm" in os.uname()[4]:
				if settings.getSetting('rpi2') == "true": platf = "rpi2"		
			elif os.uname()[4] == "i386" or os.uname()[4] == "i686":
				if settings.getSetting('openeleci386') == "true": platf = "openeleci386"
				else: platf = "linuxi386"
			elif os.uname()[4] == "x86_64": 
				if settings.getSetting('openelecx86_64') == "true": platf = "openelecx64"
				else: platf = "linux_x86_64"
		elif xbmc.getCondVisibility('system.platform.windows'): platf = "windows"
		elif xbmc.getCondVisibility('system.platform.Android'): platf = "android"
		elif xbmc.getCondVisibility('System.Platform.OSX'):
			if os.uname()[4] == "i386" or os.uname()[4] == "i686": platf = "osx32"
			elif os.uname()[4] == "x86_64": platf = "osx64"
		try:
			if version_source["sopcast"][platf] != settings.getSetting('sopcast_version'): configure_sopcast(version_source["sopcast"][platf])
			sopcast_update = True
		except: sopcast_update = False
		try:
			if version_source["acestream"][platf] != settings.getSetting('acestream_version'): configure_acestream(version_source["acestream"][platf])
			acestream_update = True
		except: acestream_update = False
		if acestream_update and sopcast_update: settings.setSetting('last_version_check',value=versao)
		return
 def get_spotty_binary(self):
     '''find the correct spotty binary belonging to the platform'''
     sp_binary = None
     if xbmc.getCondVisibility("System.Platform.Windows"):
         sp_binary = os.path.join(os.path.dirname(__file__), "spotty", "windows", "spotty.exe")
     elif xbmc.getCondVisibility("System.Platform.OSX"):
         # macos binary is x86_64 intel
         sp_binary = os.path.join(os.path.dirname(__file__), "spotty", "darwin", "spotty")
     elif xbmc.getCondVisibility("System.Platform.Linux + !System.Platform.Android"):
         # try to find out the correct architecture by trial and error
         import platform
         architecture = platform.machine()
         log_msg("reported architecture: %s" % architecture)
         if architecture.startswith('AMD64') or architecture.startswith('x86_64'):
             # generic linux x86_64 binary
             sp_binary = os.path.join(os.path.dirname(__file__), "spotty", "x86-linux", "spotty-x86_64")
         else:
             # just try to get the correct binary path if we're unsure about the platform/cpu
             paths = []
             paths.append(os.path.join(os.path.dirname(__file__), "spotty", "arm-linux", "spotty-muslhf"))
             paths.append(os.path.join(os.path.dirname(__file__), "spotty", "arm-linux", "spotty-hf"))
             paths.append(os.path.join(os.path.dirname(__file__), "spotty", "arm-linux", "spotty"))
             paths.append(os.path.join(os.path.dirname(__file__), "spotty", "x86-linux", "spotty"))
             for binary_path in paths:
                 if self.test_spotty(binary_path):
                     sp_binary = binary_path
                     break
     if sp_binary:
         st = os.stat(sp_binary)
         os.chmod(sp_binary, st.st_mode | stat.S_IEXEC)
         log_msg("Architecture detected. Using spotty binary %s" % sp_binary)
     else:
         log_msg("Failed to detect architecture or platform not supported ! Local playback will not be available.")
     return sp_binary
 def update(self):
     hours_list = [2, 5, 10, 15, 24]
     hours = hours_list[subscription_timer()]
     xbmc.log('[IMDb Watchlists] Updating', level=xbmc.LOGNOTICE)
     time.sleep(1)
     if update_watchlists():
         xbmc.log('[IMDb Watchlists] Updating Watchlists', level=xbmc.LOGNOTICE)
         xbmc.executebuiltin('RunPlugin(plugin://plugin.video.imdb.watchlists/update_watchlists)')
     if update_tv():
         xbmc.log('[IMDb Watchlists] Updating TV Shows', level=xbmc.LOGNOTICE)
         xbmc.executebuiltin('RunPlugin(plugin://plugin.video.imdb.watchlists/update_tv)')
     now = datetime.datetime.now()
     ADDON.setSetting('service_time', str(now + timedelta(hours=hours)).split('.')[0])
     xbmc.log("[IMDb Watchlists] Library updated. Next run at " + ADDON.getSetting('service_time'), level=xbmc.LOGNOTICE)
     if ADDON.getSetting('update_main') == "true":
         while (xbmc.getCondVisibility('Library.IsScanningVideo') == True):
             time.sleep(1)
             if xbmc.abortRequested:
                 return
         xbmc.log('[IMDb Watchlists] Updating Kodi Library', level=xbmc.LOGNOTICE)
         xbmc.executebuiltin('UpdateLibrary(video)')
     if ADDON.getSetting('update_clean') == "true":
         time.sleep(1)
         while (xbmc.getCondVisibility('Library.IsScanningVideo') == True):
             time.sleep(1)
             if xbmc.abortRequested:
                 return
         xbmc.log('[IMDb Watchlists] Cleaning Kodi Library', level=xbmc.LOGNOTICE)
         xbmc.executebuiltin('CleanLibrary(video)')
Exemple #9
0
 def __init__(self):
     footprints()
     self.WINDOW = xbmcgui.Window(10000)
     self.date = date.today()
     self.datestr = str(self.date)
     self.weekday = date.today().weekday()
     self.days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
     self.ampm = xbmc.getCondVisibility("substring(System.Time,Am)") or xbmc.getCondVisibility(
         "substring(System.Time,Pm)"
     )
     self._parse_argv()
     # if __settings__.getSetting( "AddonVersion" ) != __version__:
     #    __settings__.setSetting ( id = "AddonVersion", value = "%s" % __version__ )
     #    self.FORCEUPDATE = True
     if self.BACKEND:
         self.run_backend()
     else:
         self.update_data()
         if self.SILENT == "":
             self.show_gui()
         else:
             oldweekday = date.today().weekday()
             while not xbmc.abortRequested:
                 xbmc.sleep(1000)
                 newweekday = date.today().weekday()
                 if newweekday != oldweekday:
                     oldweekday = newweekday
                     self.FORCEUPDATE = True
                     log("### it's midnight, force update")
                     self.update_data()
             self.close("xbmc is closing, stop script")
    def _manage_shortcuts( self, group, defaultGroup, nolabels, groupname ):
        homeWindow = xbmcgui.Window( 10000 )
        if homeWindow.getProperty( "skinshortcuts-loading" ) and int( calendar.timegm( gmtime() ) ) - int( homeWindow.getProperty( "skinshortcuts-loading" ) ) <= 5:
            return

        # Get current Super Favourites context menu status
        sfMenu = None
        if xbmc.getCondVisibility( "System.HasAddon(plugin.program.super.favourites)" ):
            sfMenu = xbmcaddon.Addon( "plugin.program.super.favourites" ).getSetting( "CONTEXT" )
            # Set it to disabled
            xbmcaddon.Addon( "plugin.program.super.favourites" ).setSetting( "CONTEXT", "false" )

        homeWindow.setProperty( "skinshortcuts-loading", str( calendar.timegm( gmtime() ) ) )
        import gui
        ui= gui.GUI( "script-skinshortcuts.xml", CWD, "default", group=group, defaultGroup=defaultGroup, nolabels=nolabels, groupname=groupname )
        ui.doModal()
        del ui

        # Reset Super Favourites context menu
        if xbmc.getCondVisibility( "System.HasAddon(plugin.program.super.favourites)" ):
            xbmcaddon.Addon( "plugin.program.super.favourites" ).setSetting( "CONTEXT", sfMenu )        
        
        # Update home window property (used to automatically refresh type=settings)
        homeWindow.setProperty( "skinshortcuts",strftime( "%Y%m%d%H%M%S",gmtime() ) )
        
        # Clear window properties for this group, and for backgrounds, widgets, properties
        homeWindow.clearProperty( "skinshortcuts-" + group )        
        homeWindow.clearProperty( "skinshortcutsWidgets" )        
        homeWindow.clearProperty( "skinshortcutsCustomProperties" )        
        homeWindow.clearProperty( "skinshortcutsBackgrounds" )        
def myPlayerChanged(state):
  log('PlayerChanged(%s)' % state)
  xbmc.sleep(100)
  if state == 'stop':
    ret = "static"
  else:
    currentPlayingFile = xbmc.Player().getPlayingFile()
    if re.search(r'3D Movies', currentPlayingFile, re.I):
      if re.search(r'OU', currentPlayingFile, re.I):
        ret = "3dTAB"
      elif re.search(r'SBS', currentPlayingFile, re.I):
        ret = "3dSBS"
      else:
        ret = "movie"
    elif xbmc.getCondVisibility("VideoPlayer.Content(musicvideos)"):
      ret = "musicvideo"
    elif xbmc.getCondVisibility("Player.HasAudio()"):
      ret = "static"
    else:
      ret = "movie"

    if settings.overwrite_cat:                  # fix his out when other isn't
      if settings.overwrite_cat_val == 0 and ret != "3dTAB" and ret != "3dSBS":       # the static light anymore
        ret = "movie"
      elif ret != "3dTAB" and ret != "3dSBS":
        ret = "musicvideo"
  settings.handleCategory(ret)
Exemple #12
0
def installSkin(skin, version):
    if HELIX:
        sourceSkin = skin + '-Helix'
    elif JARVIS:
        sourceSkin = skin + '-Jarvis'
    else:
        return

    src = os.path.join(HOME, 'resources', sourceSkin)
    dst = os.path.join('special://home', 'addons', skin)

    if validateSkin(skin, version):
        return True

    busy = showBusy()

    sfile.copytree(src, dst)

    count = 15 * 10 #15 seconds
    xbmc.executebuiltin('UpdateLocalAddons')

    xbmc.sleep(1000)
    installed = xbmc.getCondVisibility('System.HasAddon(%s)' % skin) == 1 and compareVersions(xbmcaddon.Addon(skin).getAddonInfo('version'), version) >= 0

    while not installed and count > 0:
        count -= 1
        xbmc.sleep(100)
        installed = xbmc.getCondVisibility('System.HasAddon(%s)' % skin) == 1 and compareVersions(xbmcaddon.Addon(skin).getAddonInfo('version'), version) >= 0

    busy.close()

    return installed
 def onPlayBackStarted(self):
     xbmc.sleep(1000)
     # Set values based on the file content
     if (self.isPlayingAudio()):
         self.type = "music"
     else:
         if xbmc.getCondVisibility('VideoPlayer.Content(movies)'):
             filename = ''
             isMovie = True
             try:
                 filename = self.getPlayingFile()
             except:
                 pass
             if filename != '':
                 for string in self.substrings:
                     if string in filename:
                         isMovie = False
                         break
             if isMovie:
                 self.type = "movie"
         elif xbmc.getCondVisibility('VideoPlayer.Content(episodes)'):
             # Check for tv show title and season
             # to make sure it's really an episode
             if xbmc.getInfoLabel('VideoPlayer.Season') != "" and xbmc.getInfoLabel('VideoPlayer.TVShowTitle') != "":
                 self.type = "episode"
         elif xbmc.getCondVisibility('VideoPlayer.Content(musicvideos)'):
             self.type = "musicvideo"
Exemple #14
0
def get_platform():
    ret = {"arch": sys.maxsize > 2 ** 32 and "x64" or "x86"}
    if xbmc.getCondVisibility("system.platform.android"):
        ret["os"] = "android"
        if "arm" in os.uname()[4]:
            ret["arch"] = "arm"
    elif xbmc.getCondVisibility("system.platform.linux"):
        ret["os"] = "linux"
        uname = platform.uname()[4].lower()
        if "arm" in uname:
            if "armv7" in uname or "aarch64" in uname:
                ret["arch"] = "armv7"
            elif "armv6" in uname:
                ret["arch"] = "armv6"
            else:
                ret["arch"] = "arm"
    elif xbmc.getCondVisibility("system.platform.windows"):
        ret["os"] = "windows"
    elif xbmc.getCondVisibility("system.platform.osx"):
        ret["os"] = "darwin"
    elif xbmc.getCondVisibility("system.platform.ios"):
        ret["os"] = "ios"
        ret["arch"] = "arm"
    ret = get_system(ret)
    return ret
Exemple #15
0
def APP_LAUNCH():
        if xbmc.getCondVisibility('system.platform.osx'):
            if xbmc.getCondVisibility('system.platform.atv2'):
                log_path = '/var/mobile/Library/Preferences'
                log = os.path.join(log_path, 'xbmc.log')
                logfile = open(log, 'r').read()
            else:
                log_path = os.path.join(os.path.expanduser('~'), 'Library/Logs')
                log = os.path.join(log_path, 'xbmc.log')
                logfile = open(log, 'r').read()
        elif xbmc.getCondVisibility('system.platform.ios'):
            log_path = '/var/mobile/Library/Preferences'
            log = os.path.join(log_path, 'xbmc.log')
            logfile = open(log, 'r').read()
        elif xbmc.getCondVisibility('system.platform.windows'):
            log_path = xbmc.translatePath('special://home')
            log = os.path.join(log_path, 'xbmc.log')
            logfile = open(log, 'r').read()
        elif xbmc.getCondVisibility('system.platform.linux'):
            log_path = xbmc.translatePath('special://home/temp')
            log = os.path.join(log_path, 'xbmc.log')
            logfile = open(log, 'r').read()
        else:
            logfile='Starting XBMC (Unknown Git:.+?Platform: Unknown. Built.+?'
        print '==========================   '+PATH+' '+VERSION+'   =========================='
        try:
            from hashlib import md5
        except:
            from md5 import md5
        from random import randint
        import time
        from urllib import unquote, quote
        from os import environ
        from hashlib import sha1
        import platform
        VISITOR = ADDON.getSetting('visitor_ga')
        match=re.compile('Starting XBMC \((.+?) Git:.+?Platform: (.+?)\. Built.+?').findall(logfile)
        for build, PLATFORM in match:
            if re.search('12.0',build,re.IGNORECASE): 
                build="Frodo" 
            if re.search('11.0',build,re.IGNORECASE): 
                build="Eden" 
            if re.search('13.0',build,re.IGNORECASE): 
                build="Gotham" 
            print build
            print PLATFORM
            utm_gif_location = "http://www.google-analytics.com/__utm.gif"
            utm_track = utm_gif_location + "?" + \
                    "utmwv=" + VERSION + \
                    "&utmn=" + str(randint(0, 0x7fffffff)) + \
                    "&utmt=" + "event" + \
                    "&utme="+ quote("5(APP LAUNCH*"+build+"*"+PLATFORM+")")+\
                    "&utmp=" + quote(PATH) + \
                    "&utmac=" + UATRACK + \
                    "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR,VISITOR,"2"])
            try:
                print "============================ POSTING APP LAUNCH TRACK EVENT ============================"
                send_request_to_google_analytics(utm_track)
            except:
                print "============================  CANNOT POST APP LAUNCH TRACK EVENT ============================"
Exemple #16
0
def set_library_paths(base_dir):
	arch_str = get_architecture()
	
	if xbmc.getCondVisibility('System.Platform.Linux'):
		if arch_str in(None, 'x86'):
			add_library_path(os.path.join(base_dir, 'linux/x86'))
		
		if arch_str in(None, 'x86_64'):
			add_library_path(os.path.join(base_dir, 'linux/x86_64'))
		
		if arch_str in(None, 'armv6'):
			add_library_path(os.path.join(base_dir, 'linux/armv6hf'))
			add_library_path(os.path.join(base_dir, 'linux/armv6'))
	
	elif xbmc.getCondVisibility('System.Platform.Windows'):
		if arch_str in(None, 'x86'):
			add_library_path(os.path.join(base_dir, 'windows/x86'))
		else:
			raise OSError('Sorry, only 32bit Windows is supported.')
	
	elif xbmc.getCondVisibility('System.Platform.OSX'):
		add_library_path(os.path.join(base_dir, 'osx'))
	
	else:
		raise OSError('Sorry, this platform is not supported.')
 def cacheAllExtras(self):
     if not (xbmc.abortRequested or xbmc.getCondVisibility("Window.IsVisible(shutdownmenu)")):
         self.createExtrasCache('GetMovies', Settings.MOVIES, 'movieid')
     if not (xbmc.abortRequested or xbmc.getCondVisibility("Window.IsVisible(shutdownmenu)")):
         self.createExtrasCache('GetTVShows', Settings.TVSHOWS, 'tvshowid')
     if not (xbmc.abortRequested or xbmc.getCondVisibility("Window.IsVisible(shutdownmenu)")):
         self.createExtrasCache('GetMusicVideos', Settings.MUSICVIDEOS, 'musicvideoid')
	def __init__(self):
		intro = False
		while (not xbmc.abortRequested):
			if not intro:
				print " _____ _____ _____    _____ _____ _____ __    _____"
				print "|  _  |  |  | __  |  |_   _|     |     |  |  |   __|"
				print "|   __|  |  |    -|    | | |  |  |  |  |  |__|__   |"
				print "|__|   \___/|__|__|    |_| |_____|_____|_____|_____|"
				print "Service started..."
				intro = True
			try:
				t1 = datetime.datetime.strptime(xbmcaddon.Addon().getSetting("last_merge"), "%Y-%m-%d %H:%M:%S.%f")
				t2 = datetime.datetime.now()
				interval = int(xbmcaddon.Addon().getSetting("check_interval"))
				update = abs(t2 - t1) > datetime.timedelta(days=interval)
				if update is False: raise Exception()
				if not (xbmc.Player().isPlaying() or xbmc.getCondVisibility('Library.IsScanningVideo')):
					xmltvmerger.xml_merge()
					xbmcaddon.Addon().setSetting("last_merge", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
			except:
				pass
			try:
				t1 = datetime.datetime.strptime(xbmcaddon.Addon().getSetting("last_merge_m3u"), "%Y-%m-%d %H:%M:%S.%f")
				t2 = datetime.datetime.now()
				interval = int(xbmcaddon.Addon().getSetting("check_interval_m3u"))
				update = abs(t2 - t1) > datetime.timedelta(hours=interval)
				if update is False: raise Exception()
				if not (xbmc.Player().isPlaying() or xbmc.getCondVisibility('Library.IsScanningVideo')):
					listmerger.m3u_merge()
					xbmcaddon.Addon().setSetting("last_merge_m3u", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
			except:
				pass

			xbmc.sleep(200)
def check_for_updates():
	try:
		version_source = get_page_source("http://p2p-strm.googlecode.com/svn/trunk/ModuleVersions/versions.info")
	except: version_source = ""
	if version_source:
		version_source = eval(version_source)
		if xbmc.getCondVisibility('system.platform.linux') and not xbmc.getCondVisibility('system.platform.Android') and not settings.getSetting('force_android') == "true":
			if os.uname()[4] == "armv6l":
				if settings.getSetting('openelecarm6') == "true": platf = "openelec_arm6"
				else: platf = "raspberrypi"
			elif os.uname()[4] == "armv7l":
				if settings.getSetting('openelecarm7') == "true": platf = "openelec_armv7"
				elif settings.getSetting('mxlinuxarm7') == "true": platf = "mxlinux_armv7"
				elif settings.getSetting('xbianarm7') == "true": platf = "xbian_armv7"
			elif os.uname()[4] == "i386" or os.uname()[4] == "i686":
				if settings.getSetting('openeleci386') == "true": platf = "openeleci386"
				else: platf = "linuxi386"
			elif os.uname()[4] == "x86_64": 
				if settings.getSetting('openelecx86_64') == "true": platf = "openelecx64"
				else: platf = "linux_x86_64"
		elif xbmc.getCondVisibility('system.platform.windows'): platf = "windows"
		elif xbmc.getCondVisibility('system.platform.Android') or settings.getSetting('force_android') == "true": platf = "android"
		elif xbmc.getCondVisibility('System.Platform.OSX'):
			if os.uname()[4] == "i386" or os.uname()[4] == "i686": platf = "osx32"
			elif os.uname()[4] == "x86_64": platf = "osx64"
		try:
			if version_source["sopcast"][platf] != settings.getSetting('sopcast_version'): configure_sopcast(version_source["sopcast"][platf])
			sopcast_update = True
		except: sopcast_update = False
		try:
			if version_source["acestream"][platf] != settings.getSetting('acestream_version'): configure_acestream(version_source["acestream"][platf])
			acestream_update = True
		except: acestream_update = False
		if acestream_update and sopcast_update: settings.setSetting('last_version_check',value=versao)
		return
def menu(handle):
    list = GetHistoryItems()
    total_items = len(list)
    for show_name, name, tvdbid, season, episode in list:
        episode_status_args = ", "+tvdbid+", "+str(season)+", "+str(episode)

        context_items = []
        context_items.append(('Episode List', 'XBMC.Container.Update(plugin://{0}?mode={1}&tvdb_id={2}&show_name={3})'.format(settings.pluginID, 4, tvdbid, urllib.quote_plus(show_name.encode("utf-8")))))
        context_items.append(('Show Info', 'XBMC.Action(Info)'))
        context_items.append(('Open Show Folder', 'XBMC.RunPlugin(plugin://{0}?mode={1}&tvdb_id={2}&show_name={3})'.format(settings.pluginID, 15, tvdbid, urllib.quote_plus(show_name.encode("utf-8")))))
        if xbmc.getCondVisibility('System.HasAddon(script.extendedinfo)'):
            context_items.append(('ExtendedInfo', 'XBMC.RunScript(script.extendedinfo, info=extendedtvinfo, tvdb_id={0})'.format(tvdbid)))
        context_items.append(('Set Episode Status', 'XBMC.RunScript(special://home/addons/{0}/resources/lib/setstatus.py, {1}, {2}, {3})'.format(settings.pluginID, tvdbid, season, episode)))
        context_items.append(('Add New Show', 'XBMC.RunScript(special://home/addons/{0}/resources/lib/addshow.py)'.format(settings.pluginID)))
        if xbmc.getCondVisibility('System.HasAddon(plugin.program.qbittorrent)'):
            context_items.append(('Search qBittorrent', 'XBMC.Container.Update(plugin://plugin.program.qbittorrent?mode=1&keywords={}+S{:02d}E{:02d})'.format(urllib.quote_plus(show_name.encode('utf-8')), int(season), int(episode))))
        context_items.append(('Delete Show', 'XBMC.RunScript(special://home/addons/{0}/resources/lib/deleteshow.py, {1}, {2})'.format(settings.pluginID, tvdbid, show_name)))
        context_items.append(('Force Server Update', 'XBMC.RunScript(special://home/addons/{0}/resources/lib/forcesearch.py, {1})'.format(settings.pluginID, tvdbid)))
        context_items.append(('Update Cache from TVdb', 'XBMC.RunScript(special://home/addons/{0}/resources/lib/cache.py, {1}, {2}, {3})'.format(settings.pluginID, tvdbid, season, episode)))
        context_items.append(('Refresh List', 'XBMC.Container.Refresh'))
        context_items.append(('Go Back', 'XBMC.Action(back)'))
        
        thumbnail_path = Sickbeard.GetShowPoster(tvdbid)
        fanart_path = Sickbeard.GetShowFanArt(tvdbid)
        banner_path = Sickbeard.GetShowBanner(tvdbid)
        addDirectory(handle, show_name, name, tvdbid, season, episode, thumbnail_path, fanart_path, banner_path, total_items, context_items)

    xbmcplugin.addSortMethod(handle=int(handle), sortMethod=xbmcplugin.SORT_METHOD_DATE)
    xbmcplugin.addSortMethod(handle=int(handle), sortMethod=xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE)
    xbmcplugin.setContent(handle=int(handle), content='tvshows')
    xbmcplugin.endOfDirectory(int(handle))
    common.CreateNotification(header='Show List', message=str(total_items)+' Shows in list', icon=xbmcgui.NOTIFICATION_INFO, time=3000, sound=False)
Exemple #21
0
    def setview(self):
        '''sets the selected viewmode for the container'''
        xbmc.executebuiltin("ActivateWindow(busydialog)")
        content_type = get_current_content_type()
        if not content_type:
            content_type = "files"
        current_view = xbmc.getInfoLabel("Container.Viewmode").decode("utf-8")
        view_id, view_label = self.selectview(content_type, current_view)
        current_forced_view = xbmc.getInfoLabel("Skin.String(SkinHelper.ForcedViews.%s)" % content_type)

        if view_id is not None:
            # also store forced view
            if (content_type and current_forced_view and current_forced_view != "None" and
                    xbmc.getCondVisibility("Skin.HasSetting(SkinHelper.ForcedViews.Enabled)")):
                xbmc.executebuiltin("Skin.SetString(SkinHelper.ForcedViews.%s,%s)" % (content_type, view_id))
                xbmc.executebuiltin("Skin.SetString(SkinHelper.ForcedViews.%s.label,%s)" % (content_type, view_label))
                self.win.setProperty("SkinHelper.ForcedView", view_id)
                if not xbmc.getCondVisibility("Control.HasFocus(%s)" % current_forced_view):
                    xbmc.sleep(100)
                    xbmc.executebuiltin("Container.SetViewMode(%s)" % view_id)
                    xbmc.executebuiltin("SetFocus(%s)" % view_id)
            else:
                self.win.clearProperty("SkinHelper.ForcedView")
            # set view
            xbmc.executebuiltin("Container.SetViewMode(%s)" % view_id)
def main():
    if xbmc.getCondVisibility("Container.Content(movies)"):
        xbmc.executebuiltin("RunScript(script.extendedinfo,info=ratemedia,type=movie,dbid=%s,id=%s)" % (xbmc.getInfoLabel("ListItem.DBID"), xbmc.getInfoLabel("ListItem.Property(id)")))
    elif xbmc.getCondVisibility("Container.Content(tvshows)"):
        xbmc.executebuiltin("RunScript(script.extendedinfo,info=ratemedia,type=tv,dbid=%s,id=%s)" % (xbmc.getInfoLabel("ListItem.DBID"), xbmc.getInfoLabel("ListItem.Property(id)")))
    elif xbmc.getCondVisibility("Container.Content(episodes)"):
        xbmc.executebuiltin("RunScript(script.extendedinfo,info=ratemedia,type=episode,tvshow=%s,season=%s)" % (xbmc.getInfoLabel("ListItem.TVShowTitle"), xbmc.getInfoLabel("ListItem.Season")))
def set_linux_engine_setting(url):
	if xbmc.getCondVisibility('system.platform.linux') and not xbmc.getCondVisibility('system.platform.Android'):
		acestream_settings_file = os.path.join(os.getenv("HOME"),'.ACEStream','playerconf.pickle')
	elif xbmc.getCondVisibility('system.platform.Android'):
		acestream_settings_file = os.path.join('/sdcard','.ACEStream','playerconf.pickle')
	elif xbmc.getCondVisibility('system.platform.windows'):
		acestream_settings_file = os.path.join(os.getenv("APPDATA"),".ACEStream","playerconf.pickle")
	settings_content = readfile(acestream_settings_file)
	keyb = xbmc.Keyboard('',translate(600024))
	keyb.doModal()
	if (keyb.isConfirmed()):
		search = keyb.getText()
		try:
			int(search)
			integer = True
		except: integer = False
		if integer == True:
			if len(url.split('|')) == 3:
				settings_content = settings_content.replace('p'+str(eval(url.split('|')[1])[0][0])+'\nI'+str(eval(url.split('|')[1])[0][1]),'p'+str(eval(url.split('|')[1])[0][0])+'\nI'+search)
				save(acestream_settings_file, settings_content)
				xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000), translate(600026), 1,addonpath+"/icon.png"))
				xbmc.executebuiltin("Container.Refresh")
			else:
				settings_content = settings_content.replace('s.',"sS'"+url.split('|')[0]+"'\np"+url.split('|')[1]+"\nI"+search+"\ns.")
				save(acestream_settings_file, settings_content)
				xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000), translate(600026), 1,addonpath+"/icon.png"))
				xbmc.executebuiltin("Container.Refresh")
			if 'total_max_download_rate' in url: settings.setSetting('total_max_download_rate',value=search)
			if 'total_max_upload_rate' in url:	settings.setSetting('total_max_upload_rate',value=search)	
		else:
			mensagemok(translate(40000),translate(600025))
			sys.exit(0)
    def run(self):
        try:
            while not self._stop:  # the code
                if not xbmc.getCondVisibility("Window.IsVisible(10025)"):
                    self.stop()  # destroy threading

                if (
                    xbmc.getCondVisibility("Container.Content(Seasons)")
                    or xbmc.getCondVisibility("Container.Content(Episodes)")
                    and not xbmc.Player().isPlaying()
                    and "plugin://" not in xbmc.getInfoLabel("ListItem.Path")
                    and not xbmc.getInfoLabel("container.folderpath") == "videodb://5/"
                ):
                    if self.enable_custom_path == "true":
                        self.newpath = self.custom_path + xbmc.getInfoLabel("ListItem.TVShowTitle")
                    else:
                        self.newpath = xbmc.getInfoLabel("ListItem.Path")
                    if (
                        not self.newpath == self.oldpath
                        and not self.newpath == ""
                        and not self.newpath == "videodb://2/2/"
                    ):
                        log("### old path: %s" % self.oldpath)
                        log("### new path: %s" % self.newpath)
                        self.oldpath = self.newpath
                        if not xbmc.Player().isPlaying():
                            self.start_playing()
                        else:
                            log("### player already playing")

                if (
                    xbmc.getInfoLabel("Window(10025).Property(TvTunesIsAlive)") == "true"
                    and not xbmc.Player().isPlaying()
                ):
                    log("### playing ends")
                    if self.loud:
                        self.raise_volume()
                    xbmcgui.Window(10025).clearProperty("TvTunesIsAlive")

                if (
                    xbmc.getCondVisibility("Container.Content(tvshows)")
                    and self.playpath
                    and not xbmc.getCondVisibility("Window.IsVisible(12003)")
                ):
                    log("### reinit condition")
                    self.newpath = ""
                    self.oldpath = ""
                    self.playpath = ""
                    log("### stop playing")
                    if __addon__.getSetting("fade") == "true":
                        self.fade_out()
                    else:
                        xbmc.Player().stop()
                    if self.loud:
                        self.raise_volume()
                    xbmcgui.Window(10025).clearProperty("TvTunesIsAlive")
                time.sleep(0.5)
        except:
            print_exc()
            self.stop()
def main():
    if xbmc.getCondVisibility('Container.Content(tvshows)'):
        mediatype = 'tvshow'
    elif xbmc.getCondVisibility('Container.Content(movies)'):
        mediatype = 'movie'
    elif xbmc.getCondVisibility('Container.Content(episodes)'):
        mediatype = 'episode'
    elif xbmc.getCondVisibility('Container.Content(musicvideos)'):
        mediatype = 'musicvideo'
    else:
        xbmc.executebuiltin('Notification(Select Artwork to Download cannot proceed, "Got an unexpected content type. Try again, it will probably work.", 6000, DefaultIconWarning.png)')
        return

    infolabel = xbmc.getInfoLabel('ListItem.Label')
    truelabel = sys.listitem.getLabel()
    mismatch = infolabel != truelabel
    if mismatch:
        log("InfoLabel does not match selected item: InfoLabel('ListItem.Label'): '%s', sys.listitem '%s'" % (infolabel, truelabel), xbmc.LOGWARNING)
        dbid = get_realdbid(sys.listitem)
    else:
        dbid = xbmc.getInfoLabel('ListItem.DBID')

    artworkaddon = xbmcaddon.Addon().getSetting('artwork_addon')
    if not xbmc.getCondVisibility('System.HasAddon({0})'.format(artworkaddon)):
        xbmcgui.Dialog().ok('Select Artwork to Download', "The add-on {0} is not installed. Please install it or configure this context item to use another add-on.".format(artworkaddon))
        return
    xbmc.executebuiltin('RunScript({0}, mode=gui, mediatype={1}, dbid={2})'.format(artworkaddon, mediatype, dbid))
def stop_any_sop_traces(pid=None):
    if not xbmc.getCondVisibility('system.platform.windows'):
        try: os.kill(pid,9)
        except: pass
        xbmc.sleep(100)
        try:os.system("killall -9 "+SPSC_BINARY)
        except:pass
        xbmc.sleep(100)
        try:spsc.kill()
        except:pass
        xbmc.sleep(100)
        try:spsc.wait()
        except:pass
        if xbmc.getCondVisibility('system.platform.OSX'):
            try:xbmcvfs.delete(os.path.join(pastaperfil,'sopcast.avi'))
            except:pass
    else:
        cmd = ['sc','stop','sopcastp2p']
        import subprocess
        proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
        servicecreator = False
        for line in proc.stdout:
            print("result line" + line.rstrip())
        #dirty hack to break sopcast.exe player codec - renaming the file now!
        break_sopcast()
    return
 def _set_languages( self, dbid, dbtype ):
     try:
         if xbmc.getCondVisibility('Container.Content(movies)') or self.type == "movie" or dbtype == "movie":
             json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"properties": ["streamdetails"], "movieid":%s }, "id": 1}' % dbid)
             json_query = unicode(json_query, 'utf-8', errors='ignore')
             log(json_query)
             json_response = simplejson.loads(json_query)
             if json_response['result'].has_key('moviedetails'):
                 self._set_properties(json_response['result']['moviedetails']['streamdetails']['audio'], json_response['result']['moviedetails']['streamdetails']['subtitle'])
         elif xbmc.getCondVisibility('Container.Content(episodes)') or self.type == "episode" or dbtype == "episode":
             json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodeDetails", "params": {"properties": ["streamdetails"], "episodeid":%s }, "id": 1}' % dbid)
             json_query = unicode(json_query, 'utf-8', errors='ignore')
             log(json_query)
             json_response = simplejson.loads(json_query)
             if json_response['result'].has_key('episodedetails'):
                 self._set_properties(json_response['result']['episodedetails']['streamdetails']['audio'], json_response['result']['episodedetails']['streamdetails']['subtitle'])
         elif xbmc.getCondVisibility('Container.Content(musicvideos)') or self.type == "musicvideo" or dbtype == "musicvideo":
             json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMusicVideoDetails", "params": {"properties": ["streamdetails"], "musicvideoid":%s }, "id": 1}' % dbid)
             json_query = unicode(json_query, 'utf-8', errors='ignore')
             log(json_query)
             json_response = simplejson.loads(json_query)
             if json_response['result'].has_key('musicvideodetails'):
                 self._set_properties(json_response['result']['musicvideodetails']['streamdetails']['audio'], json_response['result']['musicvideodetails']['streamdetails']['subtitle'])
     except:
         pass
 def run( self ):        
     try:             
         while not self._stop:           # le code                
             if not xbmc.getCondVisibility( "Window.IsVisible(10025)"): self.stop()      #destroy threading
                 
             if xbmc.getCondVisibility( "Container.Content(Seasons)" ) or xbmc.getCondVisibility( "Container.Content(Episodes)" ) and not xbmc.Player().isPlaying() and "plugin://" not in xbmc.getInfoLabel( "ListItem.Path" ) and not xbmc.getInfoLabel( "container.folderpath" ) == "videodb://5/":
                 self.newpath = xbmc.getInfoLabel( "ListItem.Path" )
                 if not self.newpath == self.oldpath and not self.newpath == "" and not self.newpath == "videodb://2/2/":
                     print "### old path: %s" % self.oldpath
                     print "### new path: %s" % self.newpath
                     self.oldpath = self.newpath
                     if not xbmc.Player().isPlaying() : self.start_playing()
                     else: print "### player already playing"
                     
             if xbmc.getInfoLabel( "Window(10025).Property(TvTunesIsAlive)" ) == "true" and not xbmc.Player().isPlaying():
                 print "### playing ends"
                 if self.loud: self.raise_volume()
                 xbmcgui.Window( 10025 ).clearProperty('TvTunesIsAlive')
                 
             if xbmc.getCondVisibility( "Container.Content(tvshows)" ) and self.playpath and not xbmc.getCondVisibility( "Window.IsVisible(12003)" ):
                 print "### reinit condition"
                 self.newpath = ""
                 self.oldpath = ""
                 self.playpath = ""
                 print "### stop playing"
                 xbmc.Player().stop()
                 if self.loud: self.raise_volume()
                 xbmcgui.Window( 10025 ).clearProperty('TvTunesIsAlive')
                 
             time.sleep( .5 )
     except:
         print_exc()
         self.stop()
def _get_query(dbtype, dbid):
    if not dbtype:
        if xbmc.getCondVisibility("VideoPlayer.Content(movies)"):
            dbtype = 'movie'
        elif xbmc.getCondVisibility("VideoPlayer.Content(episodes)"):
            dbtype = 'episode'
        elif xbmc.getCondVisibility("VideoPlayer.Content(musicvideos)"):
            dbtype = 'musicvideo'
    if dbtype == "movie":
        method = '"VideoLibrary.GetMovieDetails"'
        param = '"movieid"'
    elif dbtype == "tvshow":
        method = '"VideoLibrary.GetTVShowDetails"'
        param = '"tvshowid"'
    elif dbtype == "episode":
        method = '"VideoLibrary.GetEpisodeDetails"'
        param = '"episodeid"'
    elif dbtype == "musicvideo":
        method = '"VideoLibrary.GetMusicVideoDetails"'
        param = '"musicvideoid"'
    elif dbtype == "song":
        method = '"AudioLibrary.GetSongDetails"'
        param = '"songid"'
    json_query = xbmc.executeJSONRPC('''{ "jsonrpc": "2.0", "method": %s,
                                                            "params": {%s: %d,
                                                            "properties": ["title", "file", "cast"]},
                                                            "id": 1 }''' % (method, param, int(dbid)))
    return json_query
Exemple #30
0
 def __get_logs(self):
     versionNumber=int(xbmc.getInfoLabel("System.BuildVersion" )[0:2])
     if versionNumber < 12:
         if xbmc.getCondVisibility('system.platform.osx'):
             if xbmc.getCondVisibility('system.platform.atv2'): log_path='/var/mobile/Library/Preferences'
             else: log_path=os.path.join(os.path.expanduser('~'),'Library/Logs')
         elif xbmc.getCondVisibility('system.platform.ios'): log_path='/var/mobile/Library/Preferences'
         elif xbmc.getCondVisibility('system.platform.windows'): log_path=xbmc.translatePath('special://home'); log=os.path.join(log_path,'xbmc.log'); logfile=open(log,'r').read()
         elif xbmc.getCondVisibility('system.platform.linux'): log_path=xbmc.translatePath('special://home/temp')
     else: log_path=xbmc.translatePath('special://logpath')
     crashlog_path=None; crashfile_match=None
     if   condtition('system.platform.osx') or condtition('system.platform.ios'): crashlog_path=os.path.join(os.path.expanduser('~'),'Library/Logs/CrashReporter'); crashfile_match='XBMC'
     elif condtition('system.platform.windows'): crashlog_path=log_path; crashfile_match='.dmp'
     elif condtition('system.platform.linux'): crashlog_path=os.path.expanduser('~'); crashfile_match='xbmc_crashlog'
     log=os.path.join(log_path,'xbmc.log'); log_old=os.path.join(log_path,'xbmc.old.log') # get fullpath for xbmc.log and xbmc.old.log
     log_crash=None # check for XBMC crashlogs
     if crashlog_path and crashfile_match:
         crashlog_files=[s for s in os.listdir(crashlog_path)
                           if os.path.isfile(os.path.join(crashlog_path,s))
                           and crashfile_match in s]
         if crashlog_files: crashlog_files=self.__sort_files_by_date(crashlog_path,crashlog_files); log_crash=os.path.join(crashlog_path,crashlog_files[-1]) # we have crashlogs, get fullpath from the last one by time
     found_logs=[]
     if os.path.isfile(log): found_logs.append({'title':'xbmc.log','path':log})
     if not self.skip_oldlog and os.path.isfile(log_old): found_logs.append({'title':'xbmc.old.log','path':log_old})
     if log_crash and os.path.isfile(log_crash): found_logs.append({'title':'crash.log','path':log_crash})
     return found_logs
    def run(self):
        '''our main loop monitoring the listitem and folderpath changes'''
        log_msg("ListItemMonitor - started")
        self.get_settings()

        while not self.exit:

            # check screensaver and OSD
            self.check_screensaver()
            self.check_osd()

            # do some background stuff every 30 minutes
            if (self.delayed_task_interval >= 1800) and not self.exit:
                thread.start_new_thread(self.do_background_work, ())
                self.delayed_task_interval = 0

            # skip if any of the artwork context menus is opened
            if self.win.getProperty("SkinHelper.Artwork.ManualLookup"):
                self.reset_win_props()
                self.last_listitem = ""
                self.listitem_details = {}
                self.kodimonitor.waitForAbort(3)
                self.delayed_task_interval += 3

            # skip when modal dialogs are opened (e.g. textviewer in musicinfo dialog)
            elif xbmc.getCondVisibility(
                    "Window.IsActive(DialogSelect.xml) | Window.IsActive(progressdialog) | "
                    "Window.IsActive(contextmenu) | Window.IsActive(busydialog)"
            ):
                self.kodimonitor.waitForAbort(2)
                self.delayed_task_interval += 2
                self.last_listitem = ""

            # skip when container scrolling
            elif xbmc.getCondVisibility(
                    "Container.OnScrollNext | Container.OnScrollPrevious | Container.Scrolling"
            ):
                self.kodimonitor.waitForAbort(1)
                self.delayed_task_interval += 1
                self.last_listitem = ""

            # media window is opened or widgetcontainer set - start listitem monitoring!
            elif xbmc.getCondVisibility(
                    "Window.IsMedia | "
                    "!IsEmpty(Window(Home).Property(SkinHelper.WidgetContainer))"
            ):
                self.monitor_listitem()
                self.kodimonitor.waitForAbort(0.15)
                self.delayed_task_interval += 0.15

            # flush any remaining window properties
            elif self.all_window_props:
                self.reset_win_props()
                self.win.clearProperty("SkinHelper.ContentHeader")
                self.win.clearProperty("contenttype")
                self.win.clearProperty("curlistitem")
                self.last_listitem = ""

            # other window active - do nothing
            else:
                self.kodimonitor.waitForAbort(1)
                self.delayed_task_interval += 1
		yes=DIALOG.yesno(ADDONTITLE, '[COLOR %s]%s[/COLOR] [COLOR %s]was not installed correctly!' % (COLOR1, COLOR2, BUILDNAME), 'Installed: [COLOR %s]%s[/COLOR] / Error Count: [COLOR %s]%s[/COLOR]' % (COLOR1, EXTRACT, COLOR1, EXTERROR), 'Would you like to try again?[/COLOR]', nolabel='[B]No Thanks![/B]', yeslabel='[B]Retry Install[/B]')
		wiz.clearS('build')
		FAILED = True
		if yes: 
			wiz.ebi("PlayMedia(plugin://%s/?mode=install&name=%s&url=fresh)" % (ADDON_ID, urllib.quote_plus(BUILDNAME)))
			wiz.log("[Installed Check] Instalacao Limpa Re-activated", xbmc.LOGNOTICE)
		else: wiz.log("[Installed Check] Reinstall Ignored")
	elif SKIN in ['skin.confluence', 'skin.estuary']:
		wiz.log("[Installed Check] Incorrect skin: %s" % SKIN, xbmc.LOGNOTICE)
		defaults = wiz.getS('defaultskin')
		if not defaults == '':
			if os.path.exists(os.path.join(ADDONS, defaults)):
				skinSwitch.swapSkins(defaults)
				x = 0
				xbmc.sleep(1000)
				while not xbmc.getCondVisibility("Window.isVisible(yesnodialog)") and x < 150:
					x += 1
					xbmc.sleep(200)

				if xbmc.getCondVisibility("Window.isVisible(yesnodialog)"):
					wiz.ebi('SendClick(11)')
					wiz.lookandFeelData('restore')
		if not wiz.currSkin() == defaults and not BUILDNAME == "":
			gui = wiz.checkBuild(BUILDNAME, 'gui')
			FAILED = True
			if gui == 'http://':
				wiz.log("[Installed Check] Guifix was set to http://", xbmc.LOGNOTICE)
				DIALOG.ok(ADDONTITLE, "[COLOR %s]It looks like the skin settings was not applied to the build." % COLOR2, "Sadly no gui fix was attatched to the build", "You will need to reinstall the build and make sure to do a force close[/COLOR]")
			elif wiz.workingURL(gui):
				yes=DIALOG.yesno(ADDONTITLE, '%s was not installed correctly!' % BUILDNAME, 'It looks like the skin settings was not applied to the build.', 'Would you like to apply the GuiFix?', nolabel='[B]No, Cancel[/B]', yeslabel='[B]Apply Fix[/B]')
				if yes: wiz.ebi("PlayMedia(plugin://%s/?mode=install&name=%s&url=gui)" % (ADDON_ID, urllib.quote_plus(BUILDNAME))); wiz.log("[Installed Check] Guifix attempting to install")
Exemple #33
0
def auto_scroll(list_data):
    """
    Auto scroll the current viewed list to select the last partial watched or next episode to be watched,
    works only with Sync of watched status with netflix
    """
    # A sad implementation to a Kodi feature available only for the Kodi library
    if not g.ADDON.getSettingBool(
            'ProgressManager_enabled') or not g.ADDON.getSettingBool(
                'select_first_unwatched'):
        return
    total_items = len(list_data)
    if total_items:
        # Delay a bit to wait for the completion of the screen update
        xbmc.sleep(100)
        # Check if view sort method is "Episode" (ID 23 = SortByEpisodeNumber)
        is_sort_method_episode = xbmc.getCondVisibility(
            'Container.SortMethod(23)')
        if not is_sort_method_episode:
            return
        # Check if a selection is already done (CurrentItem return the index)
        if int(xbmc.getInfoLabel('ListItem.CurrentItem') or 2) > 1:
            return
        # Check if all items are already watched
        watched_items = sum(dict_item['info'].get('PlayCount', '0') != '0'
                            for dict_item in list_data)
        to_resume_items = sum(
            dict_item.get('ResumeTime', '0') != '0' for dict_item in list_data)
        if total_items == watched_items or (watched_items +
                                            to_resume_items) == 0:
            return
        steps = 0
        # Find last watched item
        for index in range(total_items - 1, -1, -1):
            dict_item = list_data[index]
            if dict_item['info'].get('PlayCount', '0') != '0':
                # Last watched item
                steps += index + 1
                break
            if dict_item.get('ResumeTime', '0') != '0':
                # Last partial watched item
                steps += index
                break
        # Get the sort order of the view
        is_sort_descending = xbmc.getInfoLabel(
            'Container.SortOrder') == 'Descending'
        if is_sort_descending:
            steps = (total_items - 1) - steps
        gui_sound_mode = common.json_rpc(
            'Settings.GetSettingValue',
            {'setting': 'audiooutput.guisoundmode'})['value']
        if gui_sound_mode != 0:
            # Disable GUI sounds to avoid squirting sound with item selections
            common.json_rpc('Settings.SetSettingValue', {
                'setting': 'audiooutput.guisoundmode',
                'value': 0
            })
        # Auto scroll the list
        for _ in range(0, steps + 1):
            common.json_rpc('Input.Down')
        if gui_sound_mode != 0:
            # Restore GUI sounds
            common.json_rpc('Settings.SetSettingValue', {
                'setting': 'audiooutput.guisoundmode',
                'value': gui_sound_mode
            })
Exemple #34
0
def delete_ffmpeg():
    if xbmc.getCondVisibility('system.platform.android'):
        ffmpeg_dst = '/data/data/%s/ffmpeg' % android_get_current_appid()
        xbmcvfs.delete(ffmpeg_dst)
Exemple #35
0
def index():
    items = []
    context_items = []
    context_items.append(
        ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Clear Trakt Movies Folders',
         'XBMC.RunPlugin(%s)' % (plugin.url_for(clear_trakt_movies))))
    context_items.append(
        ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Clear Trakt Shows Folders',
         'XBMC.RunPlugin(%s)' % (plugin.url_for(clear_trakt_shows))))

    items.append({
        'label': "Favourite Folders",
        'path': plugin.url_for('favourite_folders'),
        'thumbnail': get_icon_path('favourites'),
        'context_menu': context_items,
    })

    items.append({
        'label':
        "Library",
        'path':
        plugin.url_for('folder', path="library://video", label="Library"),
        'thumbnail':
        get_icon_path('movies'),
        'context_menu':
        context_items,
    })

    items.append({
        'label': "Rules",
        'path': plugin.url_for('rules'),
        'thumbnail': get_icon_path('search'),
        'context_menu': context_items,
    })
    context_items.append(
        ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Cancel Recordings',
         'XBMC.RunPlugin(%s)' % (plugin.url_for(cancel_recordings))))
    context_items.append(
        ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Clear Recordings',
         'XBMC.RunPlugin(%s)' % (plugin.url_for(clear_recordings))))
    context_items.append(
        ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Clear All Recordings',
         'XBMC.RunPlugin(%s)' % (plugin.url_for(clear_all_recordings))))
    items.append({
        'label': "Recordings",
        'path': plugin.get_setting('download'),
        'thumbnail': get_icon_path('recordings'),
        'context_menu': context_items,
    })
    context_items.append(
        ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Clear Last Played',
         'XBMC.RunPlugin(%s)' % (plugin.url_for(clear_database))))

    items.append({
        'label': "Last Played",
        'path': plugin.url_for('browse', table='links'),
        'thumbnail': get_icon_path('search'),
        'context_menu': context_items,
    })
    items.append({
        'label': "Record",
        'path': plugin.url_for('service'),
        'thumbnail': get_icon_path('settings'),
        'context_menu': context_items,
    })

    if xbmc.getCondVisibility('system.platform.android'):
        context_items.append(
            ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Delete ffmpeg',
             'XBMC.RunPlugin(%s)' % (plugin.url_for(delete_ffmpeg))))

    return items
Exemple #36
0
def RtlGetVideo(SERIES, EPISODE, REFERER):
    j_query = xbmc.executeJSONRPC(
        '{"jsonrpc": "2.0", "method": "Addons.GetAddonDetails", "params": {"addonid":"plugin.video.rtlnow", "properties": ["enabled"]}, "id":1}'
    )
    if '"enabled":false' in j_query:
        try:
            xbmc.executeJSONRPC(
                '{"jsonrpc": "2.0", "method": "Addons.SetAddonEnabled", "params": {"addonid":"plugin.video.rtlnow", "enabled":true}, "id":1}'
            )
        except:
            pass
    if xbmc.getCondVisibility('System.HasAddon(plugin.video.rtlnow)'):
        #http://api.tvnow.de/v3/movies/shopping-queen/2361-lisa-marie-nuernberg-flower-power-praesentiere-dich-in-deinem-neuen-bluetenkleid?fields=manifest,isDrm,free
        streamURL = False
        try:
            content = getUrl(
                'http://api.tvnow.de/v3/movies/{0}/{1}?fields=manifest,isDrm,free'
                .format(SERIES, EPISODE))
            response = json.loads(content)
            drm = response["isDrm"]
            free = response["free"]
            log("(RtlGetVideo) --- RTL-Optionen : ### DRM = {0} ### FREE = {1} ### ---"
                .format(drm, free))
            videoFREE = response["manifest"]["dashclear"].strip()
            if drm == True:
                debug_MS("(RtlGetVideo) ~~~ Video ist DRM - geschützt ~~~")
                try:
                    videoDRM = response["manifest"]["dash"].strip()
                except:
                    videoDRM = "0"
                log("(RtlGetVideo) videoDRM : {0}".format(videoDRM))
            else:
                videoDRM = "0"
                log("(RtlGetVideo) videoFREE : {0}".format(videoFREE))
            if videoDRM != "0":
                streamURL = videoDRM.replace(
                    'vodnowusodash.secure.footprint.net',
                    'vodnowusodash-a.akamaihd.net').split('.mpd')[0] + '.mpd'
                protected = "1"
            else:
                streamURL = videoFREE.replace(
                    'vodnowusodash.secure.footprint.net',
                    'vodnowusodash-a.akamaihd.net').split('.mpd')[0] + '.mpd'
                protected = "0"
            if streamURL:
                log("(RtlGetVideo) END-Qualität (TV-Now) : {0}".format(
                    streamURL))
                listitem = xbmcgui.ListItem(
                    path='plugin://plugin.video.rtlnow/?mode=playdash&xstream='
                    + str(streamURL) + '&xlink=' + REFERER + '&xdrm=' +
                    protected)
                xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
        except:
            failing(
                "(RtlGetVideo) AbspielLink-00 (TV-Now) : *TVNow-Plugin* Der angeforderte -VideoLink- existiert NICHT !!!"
            )
            xbmcgui.Dialog().notification(
                (translation(30523).format('TVNow - Plugin')),
                translation(30525), icon, 8000)
    else:
        log("(RtlGetVideo) AbspielLink-00 (TV-Now) : KEIN *TVNow-Addon* zur Wiedergabe vorhanden !!!"
            )
        xbmcgui.Dialog().notification(
            (translation(30523).format('TVNow - Addon')),
            (translation(30524).format('TVNow-Addon')), icon, 8000)
        pass
    log("(playVideo) --- ENDE WIEDERGABE ANFORDERUNG ---")
Exemple #37
0
def has_addon(addon_id):
    return xbmc.getCondVisibility('System.HasAddon(%s)' % addon_id) == 1
Exemple #38
0
def play_from_library(item):
    """
        Los .strm al reproducirlos desde kodi, este espera que sea un archivo "reproducible" asi que no puede contener
        más items, como mucho se puede colocar un dialogo de seleccion.
        Esto lo solucionamos "engañando a kodi" y haciendole creer que se ha reproducido algo, asi despues mediante
        "Container.Update()" cargamos el strm como si un item desde dentro de pelisalacarta se tratara, quitando todas
        las limitaciones y permitiendo reproducir mediante la funcion general sin tener que crear nuevos métodos para
        la biblioteca.
        @type item: item
        @param item: elemento con información
    """
    logger.info("streamondemand.platformcode.launcher play_from_library")
    # logger.debug("item: \n" + item.tostring('\n'))

    import xbmcgui
    import xbmcplugin
    import xbmc
    # Intentamos reproducir una imagen (esto no hace nada y ademas no da error)
    xbmcplugin.setResolvedUrl(
        int(sys.argv[1]), True,
        xbmcgui.ListItem(
            path=os.path.join(config.get_runtime_path(), "icon.png")))

    # Por si acaso la imagen hiciera (en futuras versiones) le damos a stop para detener la reproduccion
    xbmc.Player().stop()

    # modificamos el action (actualmente la biblioteca necesita "findvideos" ya que es donde se buscan las fuentes
    item.action = "findvideos"

    # y volvemos a lanzar kodi
    if xbmc.getCondVisibility('Window.IsMedia'):
        xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" +
                            item.tourl() + ")")

    else:
        from channels import biblioteca
        from platformcode import xbmc_library
        p_dialog = platformtools.dialog_progress_bg('streamondemand',
                                                    'Caricamento in corso...')
        p_dialog.update(0, '')

        itemlist = biblioteca.findvideos(item)

        p_dialog.update(50, '')

        if len(itemlist) > 0:
            # El usuario elige el mirror
            opciones = []
            for item in itemlist:
                opciones.append(item.title)

            seleccion = platformtools.dialog_select(
                config.get_localized_string(30163), opciones)
            if seleccion == -1:
                return

            item = biblioteca.play(itemlist[seleccion])[0]
            p_dialog.update(100, '')

            platformtools.play_video(item)
            p_dialog.close()
            xbmc_library.mark_auto_as_watched(itemlist[seleccion])
                if dlg.yesno("Exit?", "Are you sure you want to exit Furk Trailers?"):
                    self.end()
                    return  # Don't release the semaphore
                else:
                    self.startSleepTimer()

                del dlg
        elif action == ACTION_SHOW_INFO:
            if self.ignoreInfoAction:
                self.ignoreInfoAction = False
            else:
                if self.showingInfo:
                    self.hideInfo()

                    if xbmc.getCondVisibility('Player.ShowInfo'):
                        xbmc.executeJSONRPC("Input.Info")
                        self.ignoreInfoAction = True
                else:
                    self.showInfo(10.0)

        elif action == ACTION_OSD:
            xbmc.executebuiltin("ActivateWindow(12901)")

        self.actionSemaphore.release()
        self.log('onAction return')


    # Reset the sleep timer
    def startSleepTimer(self):
        if self.sleepTimeValue == 0:
Exemple #40
0
def get_context_items(item):
    """generate context menu for item
    Keyword Arguments:
    item -- JenItem to generate menu for
    """
    context = []
    content = item["content"]
    # cache
    if content == "":
        context.append((_("Try Uncached"), "Container.Update({0})".format(
            get_addon_url("get_list_uncached", item["link"]))))
    # information
    context.append(
        (xbmcaddon.Addon().getLocalizedString(30708), "XBMC.Action(Info)"))

    # view modes
    if content == "movie":
        context.append(
            (_("Set Movie View"),
             "RunPlugin({0})".format(get_addon_url("save_view_mode",
                                                   "movies"))))
    elif content == "tvshow":
        context.append(
            (_("Set TV Show View"),
             "RunPlugin({0})".format(get_addon_url("save_view_mode",
                                                   "tvshows"))))
    elif content == "season":
        context.append(
            (_("Set Season View"),
             "RunPlugin({0})".format(get_addon_url("save_view_mode",
                                                   "seasons"))))
    elif content == "episode":
        context.append((_("Set Episode View"), "RunPlugin({0})".format(
            get_addon_url("save_view_mode", "episodes"))))
    else:
        context.append(
            (_("Set View"),
             "RunPlugin({0})".format(get_addon_url("save_view_mode",
                                                   "other"))))

    # extended info mod/qlickplay
    if xbmc.getCondVisibility("system.hasaddon(script.qlickplay)") or \
       xbmc.getCondVisibility("system.hasaddon(script.extendedinfo)"):
        if content == "movie":
            context.append((_("Extended info"), "RunPlugin({0})".format(
                get_addon_url("movie_extended_info", item["imdb"]))))
        elif content == "tvshow":
            context.append((_("Extended info"), "RunPlugin({0})".format(
                get_addon_url("tvshow_extended_info", item["imdb"]))))
        elif content == "season":
            url = "{'imdb': '%s', 'season': %s}" %\
                  (item["imdb"], item["season"])
            context.append((_("Extended info"), "RunPlugin({0})".format(
                get_addon_url("season_extended_info", url))))
        elif content == "episode":
            url = "{'imdb': '%s', 'season': %s, 'episode': %s}" %\
                  (item["imdb"], item["season"], item["episode"])
            context.append((_("Extended info"), "RunPlugin({0})".format(
                get_addon_url("episode_extended_info", url))))

    # queue
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    if playlist.size() > 0:
        context.append((_("Play Queue"),
                        "RunPlugin({0})".format(get_addon_url("play_queue"))))
        context.append((_('Show Queue'), 'Action("Playlist")'))
        context.append((_("Clear Queue"),
                        "RunPlugin({0})".format(get_addon_url("clear_queue"))))
    try:
        if content == "movie":
            context.append((_("Queue Movie"), "RunPlugin({0})".format(
                get_addon_url("queue", item.item_string))))
        elif content == "tvshow":
            context.append((_("Queue TV Show"), "RunPlugin({0})".format(
                get_addon_url("queue", item.item_string))))
        elif content == "season":
            context.append((_("Queue Season"), "RunPlugin({0})".format(
                get_addon_url("queue", item.item_string))))
        elif content == "episode":
            context.append((_("Queue Episode"), "RunPlugin({0})".format(
                get_addon_url("queue", item.item_string))))
        else:
            context.append((_("Queue Item"), "RunPlugin({0})".format(
                get_addon_url("queue", item.item_string))))
    except:
        pass

    hook_result = run_hook("get_context_items", item, context)
    if hook_result:
        return hook_result

    return context
Exemple #41
0
def checkForWindow():
    if not xbmc.getCondVisibility('IsEmpty(Window.Property(pushbullet))'):
        xbmc.executebuiltin('Action(info)')
        return True
Exemple #42
0
def checkSkin():
    wiz.log("[Build Check] Invalid Skin Check Start")
    DEFAULTSKIN = wiz.getS('defaultskin')
    DEFAULTNAME = wiz.getS('defaultskinname')
    DEFAULTIGNORE = wiz.getS('defaultskinignore')
    gotoskin = False
    if not DEFAULTSKIN == '':
        if os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)):
            if DIALOG.yesno(
                    ADDONTITLE,
                    "[COLOR %s]It seems that the skin has been set back to [COLOR %s]%s[/COLOR]"
                    % (COLOR2, COLOR1, SKIN[5:].title()),
                    "Would you like to set the skin back to:[/COLOR]",
                    '[COLOR %s]%s[/COLOR]' % (COLOR1, DEFAULTNAME)):
                gotoskin = DEFAULTSKIN
                gotoname = DEFAULTNAME
            else:
                wiz.log("Skin was not reset", xbmc.LOGNOTICE)
                wiz.setS('defaultskinignore', 'true')
                gotoskin = False
        else:
            wiz.setS('defaultskin', '')
            wiz.setS('defaultskinname', '')
            DEFAULTSKIN = ''
            DEFAULTNAME = ''
    if DEFAULTSKIN == '':
        skinname = []
        skinlist = []
        for folder in glob.glob(os.path.join(ADDONS, 'skin.*/')):
            xml = "%s/addon.xml" % folder
            if os.path.exists(xml):
                f = open(xml, mode='r')
                g = f.read().replace('\n', '').replace('\r',
                                                       '').replace('\t', '')
                f.close()
                match = wiz.parseDOM(g, 'addon', ret='id')
                match2 = wiz.parseDOM(g, 'addon', ret='name')
                wiz.log("%s: %s" % (folder, str(match[0])), xbmc.LOGNOTICE)
                if len(match) > 0:
                    skinlist.append(str(match[0]))
                    skinname.append(str(match2[0]))
                else:
                    wiz.log("ID not found for %s" % folder, xbmc.LOGNOTICE)
            else:
                wiz.log("ID not found for %s" % folder, xbmc.LOGNOTICE)
        if len(skinlist) > 0:
            if len(skinlist) > 1:
                if DIALOG.yesno(
                        ADDONTITLE,
                        "[COLOR %s]It seems that the skin has been set back to [COLOR %s]%s[/COLOR]"
                        % (COLOR2, COLOR1, SKIN[5:].title()),
                        "Would you like to view a list of avaliable skins?[/COLOR]"
                ):
                    choice = DIALOG.select("Select skin to switch to!",
                                           skinname)
                    if choice == -1:
                        wiz.log("Skin was not reset", xbmc.LOGNOTICE)
                        wiz.setS('defaultskinignore', 'true')
                    else:
                        gotoskin = skinlist[choice]
                        gotoname = skinname[choice]
                else:
                    wiz.log("Skin was not reset", xbmc.LOGNOTICE)
                    wiz.setS('defaultskinignore', 'true')
            else:
                if DIALOG.yesno(
                        ADDONTITLE,
                        "[COLOR %s]It seems that the skin has been set back to [COLOR %s]%s[/COLOR]"
                        % (COLOR2, COLOR1, SKIN[5:].title()),
                        "Would you like to set the skin back to:[/COLOR]",
                        '[COLOR %s]%s[/COLOR]' % (COLOR1, skinname[0])):
                    gotoskin = skinlist[0]
                    gotoname = skinname[0]
                else:
                    wiz.log("Skin was not reset", xbmc.LOGNOTICE)
                    wiz.setS('defaultskinignore', 'true')
        else:
            wiz.log("No skins found in addons folder.", xbmc.LOGNOTICE)
            wiz.setS('defaultskinignore', 'true')
            gotoskin = False
    if gotoskin:
        skinSwitch.swapSkins(gotoskin)
        x = 0
        xbmc.sleep(1000)
        while not xbmc.getCondVisibility(
                "Window.isVisible(yesnodialog)") and x < 150:
            x += 1
            xbmc.sleep(200)

        if xbmc.getCondVisibility("Window.isVisible(yesnodialog)"):
            wiz.ebi('SendClick(11)')
            wiz.lookandFeelData('restore')
        else:
            wiz.LogNotify("[COLOR %s]%s[/COLOR]" % (COLOR1, ADDONTITLE),
                          '[COLOR %s]Skin Swap Timed Out![/COLOR]' % COLOR2)
    wiz.log("[Build Check] Invalid Skin Check End", xbmc.LOGNOTICE)
        def onScreensaverDeactivated(self):
            self.exit_callback()

    def onInit(self):
        self.exit_monitor = self.ExitMonitor(self.exit)
        xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "method": "Input.ContextMenu", "id": 1}')

    def exit(self):
        self.close()
        #Call the screensaver asynchronously and die
        xbmc.executebuiltin('RunAddon(script.screensaver.themealdb,teste)')


if __name__ == '__main__':
    if not xbmc.getCondVisibility(
            'Window.IsActive(script-themealdb-Mealplayer.xml)'):
        #Start preview window
        screensaver = ScreensaverPreview(
            'script-themealdb-preview.xml',
            addon_path,
            'default',
            '',
        )
        screensaver.doModal()
        xbmc.sleep(100)
        del screensaver

    else:
        sys.exit(0)
Exemple #44
0
    skinshortcuts.py
    Methods to connect skinhelper to skinshortcuts for smartshortcuts, widgets and backgrounds
'''

from utils import kodi_json, log_msg, urlencode
from artutils import detect_plugin_content
import xbmc
import xbmcvfs
import xbmcplugin
import xbmcgui
import xbmcaddon
import sys

# extendedinfo has some login-required widgets, these must not be probed without login details
EXTINFO_CREDS = False
if xbmc.getCondVisibility("System.Hasaddon(script.extendedinfo)"):
    exinfoaddon = xbmcaddon.Addon(id="script.extendedinfo")
    if exinfoaddon.getSetting("tmdb_username") and exinfoaddon.getSetting(
            "tmdb_password"):
        EXTINFO_CREDS = True
    del exinfoaddon


def add_directoryitem(entry, is_folder=True, widget=None, widget2=None):
    '''helper to create a listitem for our smartshortcut node'''
    label = "$INFO[Window(Home).Property(%s.title)]" % entry
    path = "$INFO[Window(Home).Property(%s.path)]" % entry
    content = "$INFO[Window(Home).Property(%s.content)]" % entry
    image = "$INFO[Window(Home).Property(%s.image)]" % entry
    mediatype = "$INFO[Window(Home).Property(%s.type)]" % entry
    os.path.join('special://home', 'addons', 'plugin.video.freshstart'))
oldmain2 = xbmc.translatePath(
    os.path.join('special://home', 'addons', 'plugin.video.hubmaintool'))
# #############################

# Check for old maintenance tools and remove them
old_maintenance = (oldinstaller, oldnotify, oldmain, oldwiz, oldfresh)
for old_file in old_maintenance:
    if os.path.exists(old_file):
        try:
            shutil.rmtree(old_file)
        except IOError:
            pass

# #############################
if xbmc.getCondVisibility('System.HasAddon(script.service.twitter)'):
    search_string = xbmcaddon.Addon('script.service.twitter').getSetting(
        'search_string')
    search_string = search_string.replace('from:@', 'from:')
    xbmcaddon.Addon('script.service.twitter').setSetting(
        'search_string', search_string)
    xbmcaddon.Addon('script.service.twitter').setSetting(
        'enable_service', 'false')

# ################################################## ##
date = datetime.datetime.today().weekday()
if (kodi.get_setting("clearday")
        == date) or kodi.get_setting("acstartup") == "true":
    import maintool
    maintool.auto_clean(True)
Exemple #46
0
		if os.path.isfile(os.path.join(Custom_Emus_Path,Emu_Name,'system/ROMS.metadata')): os.remove(os.path.join(Custom_Emus_Path,Emu_Name,'system/ROMS.metadata'))
		if not os.path.isdir(os.path.join(Custom_Emus_Path,Emu_Name,'autobootrom')): os.makedirs(os.path.join(Custom_Emus_Path,Emu_Name,'autobootrom'))
		if os.path.isfile(os.path.join(Custom_Emus_Path,Emu_Name,'autobootrom','clone.rom')): os.remove(os.path.join(Custom_Emus_Path,Emu_Name,'autobootrom','clone.rom'))
		Mame_Rom = Rom_Name_Path.split('--',1)[0]
		Mame_Rom_Clone = Rom_Name_Path.split('--',1)[1]
		for zip in os.listdir(os.path.join(Custom_Emus_Path,Emu_Name,'autobootrom')):
			if zip.endswith('.zip'): shutil.move(os.path.join(Custom_Emus_Path,Emu_Name,'autobootrom\\'+zip), os.path.join(Custom_Roms_Path,Emu_Name))
		shutil.move(os.path.join(Custom_Roms_Path,Emu_Name,Mame_Rom+'.zip'), os.path.join(Custom_Emus_Path,Emu_Name,'autobootrom'))
		if not Mame_Rom_Clone == 'parent':
			shutil.move(os.path.join(Custom_Roms_Path,Emu_Name,Mame_Rom_Clone+'.zip'), os.path.join(Custom_Emus_Path,Emu_Name,'autobootrom'))
			with open(os.path.join(Custom_Emus_Path,Emu_Name,'autobootrom\\clone.rom'), 'w') as f: f.write('')
		if os.path.isfile(os.path.join(Custom_Emus_Path,Emu_Name,'default.xbe')): os.rename(os.path.join(Custom_Emus_Path,Emu_Name,'default.xbe'),os.path.join(Custom_Emus_Path,Emu_Name,'default disabled.xbe'))
		with open(os.path.join(Custom_Emus_Path,Emu_Name,'autobootrom\\autobootrom.rom'), 'w') as f: f.write('')
		with open(os.path.join(Custom_Emus_Path,Emu_Name,'system\\disable_ui'), 'w') as f: f.write('')
		with open(os.path.join(Root_Directory,'emustation\\scripts\\return_rom.py') , 'w') as autoexec: autoexec.write("import os, shutil, time, xbmc\nif xbmc.getInfoLabel('Skin.String(emuname)') == 'mame':\n	Emu_Path_XBE = os.path.join(xbmc.getInfoLabel('skin.string(custom_emulator_path)'),xbmc.getInfoLabel('Skin.String(emuname)'))\n	Autobootrom_Path = os.path.join(xbmc.getInfoLabel('skin.string(custom_emulator_path)'),xbmc.getInfoLabel('Skin.String(emuname)'),'autobootrom')\n	EmuRom_Path = os.path.join(xbmc.getInfoLabel('skin.string(custom_roms_path)'),xbmc.getInfoLabel('Skin.String(emuname)'))\n	time.sleep(2)\n	try:\n		if os.path.isfile(os.path.join(Autobootrom_Path,'autobootrom.rom')):\n			for zip in os.listdir(Autobootrom_Path):\n				if zip.endswith('.zip'):\n					shutil.move(os.path.join(Autobootrom_Path,zip),EmuRom_Path)\n			if os.path.isfile(os.path.join(Autobootrom_Path,'clone.rom')): os.remove(Autobootrom_Path+'/clone.rom')\n			os.remove(Autobootrom_Path+'/autobootrom.rom')\n			os.rename(os.path.join(Emu_Path_XBE,'default disabled.xbe'),os.path.join(Emu_Path_XBE,'default.xbe'))\n	except: pass")
##
	if not Favourite_Launch and xbmc.getCondVisibility('Skin.HasSetting(lastromlist)'):
		xbmc.executebuiltin('Skin.SetBool(gameloaded)')
		if not os.path.isfile('Q:\\system\\introplay'):
			with open('Q:\\system\\introplay', 'w') as introplay: introplay.write('')
	else: pass
##
	if not Emu_Name == 'favs': time.sleep(1)
##
	if xbmc.getCondVisibility('Skin.HasSetting(reloademustation)'): write_igr_file()
	time.sleep(1)
	xbmc.executebuiltin('Dialog.Close(134,false)')
	xbmc.executebuiltin('runxbe(z:\\tmp.cut)')
except:
	xbmc.executebuiltin('Dialog.close(1101,true)')
	xbmcgui.Dialog().ok('Error','Something went wrong.','Please rescan your roms/games.')
 def get_cond_visibility(condition):
     """ Test a condition in XBMC """
     return xbmc.getCondVisibility(condition)
Exemple #48
0
    #    global initDone, androidClient,USEDec,popenProcess,authkey,portNumber
    #    if initDone: return
    initDone = True


try:
    from Crypto.Cipher import AES

    USEDec = 1  ## 1==crypto 2==local, local pycrypto
    print 'using pycrypt wooot woot'
except:
    print 'pycrypt not available trying other options'
    print traceback.print_exc()
    USEDec = 3  ## 1==crypto 2==local, local pycrypto
    #check if its android
    if xbmc.getCondVisibility('System.Platform.Android'):
        try:
            import androidsslPy
            AES = androidsslPy._load_crypto_libcrypto()
            USEDec = 2  ## android
            print 'using android ssllib woot woot'
        except:
            print traceback.print_exc()
            print 'android copy not available'
            from utils import python_aes
            print 'using slow decryption'
    else:
        print 'using slow decryption'
        from utils import python_aes

value_unsafe = '%+&;#'
Exemple #49
0
def killkodi():
    dialog = xbmcgui.Dialog()
    choice = 1
    #choice = xbmcgui.Dialog().yesno('Close Kodi?', 'Yes to force close Kodi (faster).', 'No to close Normally (saves skin settings).', nolabel='No, Cancel',yeslabel='Yes, Close')
    if choice == 0:
        xbmc.executebuiltin('ActivateWindow(ShutdownMenu)')
        #xbmc.executebuiltin('Quit')
        return
    elif choice == 1:
        pass
    log_path = xbmc.translatePath('special://logpath')
    #
    #################################
    # Windows and Pulsar and Quasar
    #################################
    if xbmc.getCondVisibility('system.platform.windows'):
        pulsar_path = xbmc.translatePath(
            'special://home/addons/plugin.video.pulsar')
        if os.path.exists(pulsar_path) == True:
            os.system('start TASKKILL /im pulsar.exe /f')
            os.system('tskill pulsar.exe')
        #
        quasar_path = xbmc.translatePath(
            'special://home/addons/plugin.video.quasar')
        if os.path.exists(quasar_path) == True:
            os.system('start TASKKILL /im quasar.exe /f')
            os.system('tskill quasar.exe')
        #
        xbmc_log_path = os.path.join(log_path, 'kodi.log')
        if os.path.exists(xbmc_log_path) == True:
            os.system('start TASKKILL /im kodi.exe /f')
            os.system('tskill Kodi.exe')
        #
        xbmc_log_path = os.path.join(log_path, 'smc.log')
        if os.path.exists(xbmc_log_path) == True:
            os.system('start TASKKILL /im SMC.exe /f')
            os.system('tskill SMC.exe')
        #
        xbmc_log_path = os.path.join(log_path, 'xbmc.log')
        if os.path.exists(xbmc_log_path) == True:
            os.system('start TASKKILL /im xbmc.exe /f')
            os.system('tskill xbmc.exe')
        #
        xbmc_log_path = os.path.join(log_path, 'tvmc.log')
        if os.path.exists(xbmc_log_path) == True:
            os.system('start TASKKILL /im TVMC.exe /f')
            os.system('tskill TVMC.exe')
        #

    if xbmc.getCondVisibility('system.platform.android'):
        try:
            os.system('adb shell am force-stop org.kodi')
        except:
            pass
        try:
            os.system('adb shell am force-stop org.xbmc.kodi')
        except:
            pass
        try:
            os.system('adb shell am force-stop org.xbmc.xbmc')
        except:
            pass
        try:
            os.system('adb shell am force-stop org.xbmc')
        except:
            pass
        try:
            os.system('adb shell am force-stop org.smc')
        except:
            pass
        try:
            os.system('adb shell am force-stop org.tvmc')
        except:
            pass
        #

    if xbmc.getCondVisibility('system.platform.linux'):
        try:
            os.system('killall Kodi')
        except:
            pass
        try:
            os.system('killall SMC')
        except:
            pass
        try:
            os.system('killall XBMC')
        except:
            pass
        try:
            os.system('killall -9 xbmc.bin')
        except:
            pass
        try:
            os.system('killall -9 SMC.bin')
        except:
            pass
        try:
            os.system('killall -9 kodi.bin')
        except:
            pass
        #

    if xbmc.getCondVisibility('system.platform.osx'):
        try:
            os.system('killall -9 Kodi')
        except:
            pass
        try:
            os.system('killall -9 SMC')
        except:
            pass
        try:
            os.system('killall -9 XBMC')
        except:
            pass
        #
    if xbmc.getCondVisibility('system.platform.ios'):
        print 'ios'
        #
    if xbmc.getCondVisibility('system.platform.atv2'):
        try:
            os.system('killall AppleTV')
        except:
            pass
        #
        print "############   try raspbmc force close  #################"  #OSMC / Raspbmc
        try:
            os.system('sudo initctl stop kodi')
        except:
            pass
        try:
            os.system('sudo initctl stop xbmc')
        except:
            pass
        try:
            os.system('sudo initctl stop tvmc')
        except:
            pass
        try:
            os.system('sudo initctl stop smc')
        except:
            pass
        #
    else:
        print "############   try raspbmc force close  #################"  #OSMC / Raspbmc
        try:
            os.system('sudo initctl stop kodi')
        except:
            pass
        try:
            os.system('sudo initctl stop xbmc')
        except:
            pass
        try:
            os.system('sudo initctl stop tvmc')
        except:
            pass
        try:
            os.system('sudo initctl stop smc')
        except:
            pass

        #
    #dialog.ok("WARNING", "Force Close was unsuccessful.","Closing Kodi normally...",'')
    #xbmc.executebuiltin('Quit')
    xbmc.executebuiltin('ActivateWindow(ShutdownMenu)')
 def has_inputstream_adaptive(self):
     """ Whether InputStream Adaptive is installed and enabled in add-on settings """
     return self.get_setting(
         'useinputstreamadaptive',
         'true') == 'true' and xbmc.getCondVisibility(
             'System.HasAddon(inputstream.adaptive)') == 1
Exemple #51
0
def isBusyDialog():
    return xbmc.getCondVisibility('Window.IsActive(busydialog)')
def deletecachefiles(url):
    print '############################################################       DELETING STANDARD CACHE             ###############################################################'
    xbmc_cache_path = os.path.join(xbmc.translatePath('special://home'), 'cache')
    if os.path.exists(xbmc_cache_path)==True:    
        for root, dirs, files in os.walk(xbmc_cache_path):
            file_count = 0
            file_count += len(files)
        
        # Count files and give option to delete
            if file_count > 0:
    
                dialog = xbmcgui.Dialog()
                if dialog.yesno("Delete Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
                
                    for f in files:
                        try:
                            os.unlink(os.path.join(root, f))
                        except:
                            pass
                    for d in dirs:
                        try:
                            shutil.rmtree(os.path.join(root, d))
                        except:
                            pass
                        
            else:
                pass
    if xbmc.getCondVisibility('system.platform.ATV2'):
        atv2_cache_a = os.path.join('/private/var/mobile/Library/Caches/AppleTV/Video/', 'Other')
        
        for root, dirs, files in os.walk(atv2_cache_a):
            file_count = 0
            file_count += len(files)
        
            if file_count > 0:

                dialog = xbmcgui.Dialog()
                if dialog.yesno("Delete ATV2 Cache Files", str(file_count) + " files found in 'Other'", "Do you want to delete them?"):
                
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
                        
            else:
                pass
        atv2_cache_b = os.path.join('/private/var/mobile/Library/Caches/AppleTV/Video/', 'LocalAndRental')
        
        for root, dirs, files in os.walk(atv2_cache_b):
            file_count = 0
            file_count += len(files)
        
            if file_count > 0:

                dialog = xbmcgui.Dialog()
                if dialog.yesno("Delete ATV2 Cache Files", str(file_count) + " files found in 'LocalAndRental'", "Do you want to delete them?"):
                
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
                        
            else:
                pass
              # Set path to Cydia Archives cache files
                             

    # Set path to What th Furk cache files
    wtf_cache_path = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.whatthefurk/cache'), '')
    if os.path.exists(wtf_cache_path)==True:    
        for root, dirs, files in os.walk(wtf_cache_path):
            file_count = 0
            file_count += len(files)
        
        # Count files and give option to delete
            if file_count > 0:
    
                dialog = xbmcgui.Dialog()
                if dialog.yesno("Delete WTF Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
                
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
                        
            else:
                pass
                
                # Set path to 4oD cache files
    channel4_cache_path= os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.4od/cache'), '')
    if os.path.exists(channel4_cache_path)==True:    
        for root, dirs, files in os.walk(channel4_cache_path):
            file_count = 0
            file_count += len(files)
        
        # Count files and give option to delete
            if file_count > 0:
    
                dialog = xbmcgui.Dialog()
                if dialog.yesno("Delete 4oD Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
                
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
                        
            else:
                pass
                
                # Set path to BBC iPlayer cache files
    iplayer_cache_path= os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.iplayer/iplayer_http_cache'), '')
    if os.path.exists(iplayer_cache_path)==True:    
        for root, dirs, files in os.walk(iplayer_cache_path):
            file_count = 0
            file_count += len(files)
        
        # Count files and give option to delete
            if file_count > 0:
    
                dialog = xbmcgui.Dialog()
                if dialog.yesno("Delete BBC iPlayer Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
                
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
                        
            else:
                pass
                
                
                # Set path to Simple Downloader cache files
    downloader_cache_path = os.path.join(xbmc.translatePath('special://profile/addon_data/script.module.simple.downloader'), '')
    if os.path.exists(downloader_cache_path)==True:    
        for root, dirs, files in os.walk(downloader_cache_path):
            file_count = 0
            file_count += len(files)
        
        # Count files and give option to delete
            if file_count > 0:
    
                dialog = xbmcgui.Dialog()
                if dialog.yesno("Delete Simple Downloader Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
                
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
                        
            else:
                pass
                
                # Set path to ITV cache files
    itv_cache_path = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.itv/Images'), '')
    if os.path.exists(itv_cache_path)==True:    
        for root, dirs, files in os.walk(itv_cache_path):
            file_count = 0
            file_count += len(files)
        
        # Count files and give option to delete
            if file_count > 0:
    
                dialog = xbmcgui.Dialog()
                if dialog.yesno("Delete ITV Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
                
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
                        
            else:
                pass
				
                # Set path to temp cache files
    temp_cache_path = os.path.join(xbmc.translatePath('special://home/temp'), '')
    if os.path.exists(temp_cache_path)==True:    
        for root, dirs, files in os.walk(temp_cache_path):
            file_count = 0
            file_count += len(files)
        
        # Count files and give option to delete
            if file_count > 0:
    
                dialog = xbmcgui.Dialog()
                if dialog.yesno("Delete TEMP dir Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
                
                    for f in files:
                        os.unlink(os.path.join(root, f))
                    for d in dirs:
                        shutil.rmtree(os.path.join(root, d))
                        
            else:
                pass
				

    dialog = xbmcgui.Dialog()
    dialog.ok("ARB Updater", " All Cache Files Removed", "[COLOR steelblue]Brought To You By ARB[/COLOR]")
Exemple #53
0
def update_external_addon(addon_name):
    logger.info(addon_name)

    try:
        #Verificamos que el addon está instalado
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' %
                                  addon_name):
            #Path de actualizaciones de Alfa
            alfa_addon_updates_mig = filetools.join(config.get_runtime_path(),
                                                    "lib")
            alfa_addon_updates = filetools.join(alfa_addon_updates_mig,
                                                addon_name)

            #Path de destino en addon externo
            __settings__ = xbmcaddon.Addon(id="plugin.video." + addon_name)
            if addon_name.lower() in ['quasar', 'elementum']:
                addon_path_mig = filetools.join(xbmc.translatePath(__settings__.getAddonInfo('Path')), \
                        filetools.join("resources", "site-packages"))
                addon_path = filetools.join(addon_path_mig, addon_name)
            else:
                addon_path_mig = ''
                addon_path = ''

            #Hay modificaciones en Alfa? Las copiamos al addon, incuidas las carpetas de migración a PY3
            if filetools.exists(alfa_addon_updates) and filetools.exists(
                    addon_path):
                for root, folders, files in filetools.walk(
                        alfa_addon_updates_mig):
                    if ('future' in root
                            or 'past' in root) and not 'concurrent' in root:
                        for file in files:
                            alfa_addon_updates_mig_folder = root.replace(
                                alfa_addon_updates_mig, addon_path_mig)
                            if not filetools.exists(
                                    alfa_addon_updates_mig_folder):
                                filetools.mkdir(alfa_addon_updates_mig_folder)
                            if file.endswith('.pyo') or file.endswith('.pyd'):
                                continue
                            input_file = filetools.join(root, file)
                            output_file = input_file.replace(
                                alfa_addon_updates_mig, addon_path_mig)
                            if not filetools.copy(
                                    input_file, output_file, silent=True):
                                logger.error(
                                    'Error en la copia de MIGRACIÓN: Input: %s o Output: %s'
                                    % (input_file, output_file))
                                return False

                for root, folders, files in filetools.walk(alfa_addon_updates):
                    for file in files:
                        input_file = filetools.join(root, file)
                        output_file = input_file.replace(
                            alfa_addon_updates, addon_path)
                        if not filetools.copy(
                                input_file, output_file, silent=True):
                            logger.error(
                                'Error en la copia: Input: %s o Output: %s' %
                                (input_file, output_file))
                            return False
                return True
            else:
                logger.error('Alguna carpeta no existe: Alfa: %s o %s: %s' %
                             (alfa_addon_updates, addon_name, addon_path))
        # Se ha desinstalado Quasar, reseteamos la opción
        else:
            config.set_setting('addon_quasar_update', False)
            if filetools.exists(
                    filetools.join(config.get_data_path(),
                                   "%s.json" % addon_name)):
                filetools.remove(
                    filetools.join(config.get_data_path(),
                                   "%s.json" % addon_name))
            return True
    except:
        logger.error(traceback.format_exc())

    return False
Exemple #54
0
class Config:
    """Class with all the configuration constants"""
    def __init__(self):
        pass

    try:
        import xbmcaddon
        # calling xbmcaddon.Addon() only works on newer XBMC's. Should see if it keeps working
        # if not, then the addonId should be hard coded here.
        __addon = xbmcaddon.Addon()
        __path = __addon.getAddonInfo('path')
        __addon = None  # : Free up the static variable to make sure it is garbage collected
        pathDetection = "addon.getAddonInfo('path')"
    except:
        # This was a xbmc.LOGWARNING, but that is not allowed according to the Kodi add-on rules.
        xbmc.log("Retrospect: using os.getcwd()", xbmc.LOGDEBUG)
        __path = os.getcwd()
        pathDetection = "os.getcwd()"

    if isinstance(__path, bytes):
        # the Kodi libs return unicode info, so we need to convert this
        #noinspection PyArgumentEqualDefault
        __path = __path.decode('utf-8')

    # get rootDir, addonsDir and profileDir
    rootDir = __path.replace(";", "").rstrip(
        os.sep)  # : The root directory where Retrospect resides.
    addonDir = os.path.split(rootDir)[-1]  # : The add-on directory of Kodi.
    rootDir = os.path.join(
        rootDir, '')  # : The root directory where Retrospect resides.
    icon = os.path.join(rootDir, "resources", "media", "icon.png")
    fanart = os.path.join(rootDir, "resources", "media", "fanart.jpg")

    # determine the profile directory, where user data is stored.
    if xbmc.getCondVisibility("system.platform.xbox"):
        profileDir = os.path.join(
            xbmc.translatePath("special://profile/script_data/"), addonDir)
        profileUri = os.path.join("special://profile/script_data/", addonDir)
    else:
        profileDir = os.path.join(
            xbmc.translatePath("special://profile/addon_data/"), addonDir)
        profileUri = os.path.join("special://profile/addon_data/", addonDir)

    # the XBMC libs return unicode info, so we need to convert this
    if isinstance(profileDir, bytes):
        profileDir = profileDir.decode('utf-8')
    if isinstance(profileUri, bytes):
        profileUri = profileUri.decode('utf-8')

    cacheDir = os.path.join(profileDir, 'cache', '')  # : The cache directory.
    favouriteDir = os.path.join(profileDir,
                                'favourites')  # : The favourites directory

    appName = "Retrospect"  # : Name of the XOT application (could be overwritten from the addon.xml)
    cacheValidTime = 7 * 24 * 3600  # : Time the cache files are valid in seconds.

    logLevel = 10  # : Minimum log level that is being logged. (from logger.py) Defaults to Debug
    logFileNameAddon = "retrospect.log"  # : Filename of the log file of the plugin

    # must be single quotes for build script
    __addonXmlPath = os.path.join(rootDir, 'addon.xml')
    __addonXmlcontents = xml.dom.minidom.parse(__addonXmlPath)
    for addonentry in __addonXmlcontents.getElementsByTagName("addon"):
        addonId = str(addonentry.getAttribute(
            "id"))  # : The ID the addon has in Kodi (from addon.xml)
        __version = addonentry.getAttribute(
            "version")  # : The Version of the addon (from addon.xml) in text
        version = Version(
            version=__version)  # : The Version of the addon (from addon.xml)
        #noinspection PyRedeclaration
        appName = str(addonentry.getAttribute(
            "name"))  # : The name from the addon (from addon.xml)

    updateUrl = "https://api.github.com/repos/retrospect-addon/plugin.video.retrospect/releases"

    textureMode = "Cached"  # : The mode for the textures: Local, Remote, Cached or Resources
    textureUrl = "https://cdn.rieter.net/" \
                 "resource.images.retrospect/resources"       # : The URL for the remote texture location
    textureResource = "resource.images.retrospect"  # : The resource add-on to use for textures

    logSenderApi = "1786d25d01392d572659bba76f95174f"  # : The Retrospect logsender API (Google Shortner API or PasteBinAPI)
def add_tvshow(item, channel=None):
    """
        Guarda contenido en la libreria de series. Este contenido puede ser uno de estos dos:
            - La serie con todos los capitulos incluidos en la lista episodelist.
            - Un solo capitulo descargado previamente en local.

        Para añadir episodios descargados en local, el item debe tener exclusivamente:
            - contentSerieName (o show): Titulo de la serie
            - contentTitle: titulo del episodio para extraer season_and_episode ("1x01 Piloto")
            - title: titulo a mostrar junto al listado de enlaces -findvideos- ("Reproducir video local")
            - infoLabels["tmdb_id"] o infoLabels["imdb_id"]
            - contentType != "movie"
            - channel = "downloads"
            - url : ruta local al video

        @type item: item
        @param item: item que representa la serie a guardar
        @type channel: modulo
        @param channel: canal desde el que se guardara la serie.
            Por defecto se importara item.from_channel o item.channel

    """
    logger.info("show=#" + item.show + "#")

    if item.channel == "downloads":
        itemlist = [item.clone()]

    else:
        # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
        item.action = item.extra
        if isinstance(item.extra, str) and "###" in item.extra:
            item.action = item.extra.split("###")[0]
            item.extra = item.extra.split("###")[1]

        if item.from_action:
            item.__dict__["action"] = item.__dict__.pop("from_action")
        if item.from_channel:
            item.__dict__["channel"] = item.__dict__.pop("from_channel")

        if not channel:
            try:
                channel = __import__('channels.%s' % item.channel,
                                     fromlist=["channels.%s" % item.channel])
            except ImportError:
                exec "import channels." + item.channel + " as channel"

        #Para desambiguar títulos, se provoca que TMDB pregunte por el título realmente deseado
        #El usuario puede seleccionar el título entre los ofrecidos en la primera pantalla
        #o puede cancelar e introducir un nuevo título en la segunda pantalla
        #Si lo hace en "Introducir otro nombre", TMDB buscará automáticamente el nuevo título
        #Si lo hace en "Completar Información", cambia parcialmente al nuevo título, pero no busca en TMDB.  Hay que hacerlo
        #Si se cancela la segunda pantalla, la variable "scraper_return" estará en False.  El usuario no quiere seguir

        item = generictools.update_title(
            item
        )  #Llamamos al método que actualiza el título con tmdb.find_and_set_infoLabels
        #if item.tmdb_stat:
        #    del item.tmdb_stat          #Limpiamos el status para que no se grabe en la Videoteca

        # Obtiene el listado de episodios
        itemlist = getattr(channel, item.action)(item)

    global magnet_caching
    magnet_caching = False
    insertados, sobreescritos, fallidos, path = save_tvshow(item, itemlist)

    if not insertados and not sobreescritos and not fallidos:
        platformtools.dialog_ok(config.get_localized_string(30131),
                                config.get_localized_string(60067))
        logger.error(
            "La serie %s no se ha podido añadir a la videoteca. No se ha podido obtener ningun episodio"
            % item.show)

    elif fallidos == -1:
        platformtools.dialog_ok(config.get_localized_string(30131),
                                config.get_localized_string(60068))
        logger.error("La serie %s no se ha podido añadir a la videoteca" %
                     item.show)

    elif fallidos > 0:
        platformtools.dialog_ok(config.get_localized_string(30131),
                                config.get_localized_string(60069))
        logger.error(
            "No se han podido añadir %s episodios de la serie %s a la videoteca"
            % (fallidos, item.show))

    else:
        platformtools.dialog_ok(config.get_localized_string(30131),
                                config.get_localized_string(60070))
        logger.info(
            "Se han añadido %s episodios de la serie %s a la videoteca" %
            (insertados, item.show))
        if config.is_xbmc():
            if config.get_setting("sync_trakt_new_tvshow", "videolibrary"):
                import xbmc
                from platformcode import xbmc_videolibrary
                if config.get_setting("sync_trakt_new_tvshow_wait",
                                      "videolibrary"):
                    # Comprobar que no se esta buscando contenido en la videoteca de Kodi
                    while xbmc.getCondVisibility('Library.IsScanningVideo()'):
                        xbmc.sleep(1000)
                # Se lanza la sincronizacion para la videoteca de Kodi
                xbmc_videolibrary.sync_trakt_kodi()
                # Se lanza la sincronización para la videoteca del addon
                xbmc_videolibrary.sync_trakt_addon(path)
Exemple #56
0
def update_libtorrent():
    logger.info()

    if not config.get_setting("mct_buffer", server="torrent", default=""):
        default = config.get_setting("torrent_client",
                                     server="torrent",
                                     default=0)
        config.set_setting("torrent_client", default, server="torrent")
        config.set_setting("mct_buffer", "50", server="torrent")
        if config.get_setting("mct_download_path",
                              server="torrent",
                              default=config.get_setting("downloadpath")):
            config.set_setting("mct_download_path",
                               config.get_setting("downloadpath"),
                               server="torrent")
        config.set_setting("mct_background_download", True, server="torrent")
        config.set_setting("mct_rar_unpack", True, server="torrent")
        config.set_setting("bt_buffer", "50", server="torrent")
        if config.get_setting("bt_download_path",
                              server="torrent",
                              default=config.get_setting("downloadpath")):
            config.set_setting("bt_download_path",
                               config.get_setting("downloadpath"),
                               server="torrent")
        config.set_setting("mct_download_limit", "", server="torrent")
        config.set_setting("magnet2torrent", False, server="torrent")

    if not filetools.exists(filetools.join(config.get_runtime_path(), "custom_code.json")) or not \
                    config.get_setting("unrar_path", server="torrent", default=""):

        path = filetools.join(config.get_runtime_path(), 'lib', 'rarfiles')
        creationflags = ''
        sufix = ''
        unrar = ''
        for device in filetools.listdir(path):
            if xbmc.getCondVisibility(
                    "system.platform.android") and 'android' not in device:
                continue
            if xbmc.getCondVisibility(
                    "system.platform.windows") and 'windows' not in device:
                continue
            if not xbmc.getCondVisibility("system.platform.windows") and not  xbmc.getCondVisibility("system.platform.android") \
                        and ('android' in device or 'windows' in device):
                continue
            if 'windows' in device:
                creationflags = 0x08000000
                sufix = '.exe'
            else:
                creationflags = ''
                sufix = ''
            unrar = filetools.join(path, device, 'unrar%s') % sufix
            if not filetools.exists(unrar): unrar = ''
            if unrar:
                if not xbmc.getCondVisibility("system.platform.windows"):
                    try:
                        if xbmc.getCondVisibility("system.platform.android"):
                            # Para Android copiamos el binario a la partición del sistema
                            unrar_org = unrar
                            unrar = filetools.join(
                                xbmc.translatePath('special://xbmc/'),
                                'files').replace('/cache/apk/assets', '')
                            if not filetools.exists(unrar):
                                filetools.mkdir(unrar)
                            unrar = filetools.join(unrar, 'unrar')
                            filetools.copy(unrar_org, unrar, silent=True)

                        command = ['chmod', '777', '%s' % unrar]
                        p = subprocess.Popen(command,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.PIPE)
                        output_cmd, error_cmd = p.communicate()
                        command = ['ls', '-l', unrar]
                        p = subprocess.Popen(command,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.PIPE)
                        output_cmd, error_cmd = p.communicate()
                        xbmc.log('######## UnRAR file: %s' % str(output_cmd),
                                 xbmc.LOGNOTICE)
                    except:
                        xbmc.log(
                            '######## UnRAR ERROR in path: %s' % str(unrar),
                            xbmc.LOGNOTICE)
                        logger.error(traceback.format_exc(1))

                try:
                    if xbmc.getCondVisibility("system.platform.windows"):
                        p = subprocess.Popen(unrar,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.PIPE,
                                             creationflags=creationflags)
                    else:
                        p = subprocess.Popen(unrar,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.PIPE)
                    output_cmd, error_cmd = p.communicate()
                    if p.returncode != 0 or error_cmd:
                        xbmc.log('######## UnRAR returncode in module %s: %s, %s in %s' % \
                                (device, str(p.returncode), str(error_cmd), unrar), xbmc.LOGNOTICE)
                        unrar = ''
                    else:
                        xbmc.log(
                            '######## UnRAR OK in %s: %s' % (device, unrar),
                            xbmc.LOGNOTICE)
                        break
                except:
                    xbmc.log(
                        '######## UnRAR ERROR in module %s: %s' %
                        (device, unrar), xbmc.LOGNOTICE)
                    logger.error(traceback.format_exc(1))
                    unrar = ''

        if unrar: config.set_setting("unrar_path", unrar, server="torrent")

    if filetools.exists(filetools.join(config.get_runtime_path(), "custom_code.json")) and \
                    config.get_setting("libtorrent_path", server="torrent", default="") :
        return

    try:
        from lib.python_libtorrent.python_libtorrent import get_libtorrent
    except Exception as e:
        logger.error(traceback.format_exc(1))
        if not PY3:
            e = unicode(str(e), "utf8", errors="replace").encode("utf8")
        config.set_setting("libtorrent_path", "", server="torrent")
        if not config.get_setting(
                "libtorrent_error", server="torrent", default=''):
            config.set_setting("libtorrent_error", str(e), server="torrent")

    return
Exemple #57
0
def settingsIsOpen():
    return xbmc.getCondVisibility(
        'Window.IsVisible(10140)') or xbmc.getCondVisibility(
            'Window.IsActive(10140)') or xbmc.getCondVisibility(
                'Window.IsVisible(12002)')
Exemple #58
0
def _record_playstate(status, ended):
    if not status['plex_id']:
        LOG.debug('No Plex id found to record playstate for status %s', status)
        return
    if status['plex_type'] not in v.PLEX_VIDEOTYPES:
        LOG.debug('Not messing with non-video entries')
        return
    with PlexDB() as plexdb:
        db_item = plexdb.item_by_id(status['plex_id'], status['plex_type'])
    if not db_item:
        # Item not (yet) in Kodi library
        LOG.debug('No playstate update due to Plex id not found: %s', status)
        return
    totaltime = float(timing.kodi_time_to_millis(status['totaltime'])) / 1000
    if status['external_player']:
        # video has either been entirely watched - or not.
        # "ended" won't work, need a workaround
        ended = _external_player_correct_plex_watch_count(db_item)
        if ended:
            progress = 0.99
            time = v.IGNORE_SECONDS_AT_START + 1
        else:
            progress = 0.0
            time = 0.0
    else:
        if ended:
            progress = 0.99
            time = v.IGNORE_SECONDS_AT_START + 1
        else:
            time = float(timing.kodi_time_to_millis(status['time'])) / 1000
            try:
                progress = time / totaltime
            except ZeroDivisionError:
                progress = 0.0
            LOG.debug('Playback progress %s (%s of %s seconds)', progress,
                      time, totaltime)
    playcount = status['playcount']
    last_played = timing.kodi_now()
    if playcount is None:
        LOG.debug('playcount not found, looking it up in the Kodi DB')
        with kodi_db.KodiVideoDB() as kodidb:
            playcount = kodidb.get_playcount(db_item['kodi_fileid'])
        playcount = 0 if playcount is None else playcount
    if time < v.IGNORE_SECONDS_AT_START:
        LOG.debug('Ignoring playback less than %s seconds',
                  v.IGNORE_SECONDS_AT_START)
        # Annoying Plex bug - it'll reset an already watched video to unwatched
        playcount = None
        last_played = None
        time = 0
    elif progress >= v.MARK_PLAYED_AT:
        LOG.debug('Recording entirely played video since progress > %s',
                  v.MARK_PLAYED_AT)
        playcount += 1
        time = 0
    with kodi_db.KodiVideoDB() as kodidb:
        kodidb.set_resume(db_item['kodi_fileid'], time, totaltime, playcount,
                          last_played)
        if 'kodi_fileid_2' in db_item and db_item['kodi_fileid_2']:
            # Dirty hack for our episodes
            kodidb.set_resume(db_item['kodi_fileid_2'], time, totaltime,
                              playcount, last_played)
    # Hack to force "in progress" widget to appear if it wasn't visible before
    if (app.APP.force_reload_skin
            and xbmc.getCondVisibility('Window.IsVisible(Home.xml)')):
        LOG.debug('Refreshing skin to update widgets')
        xbmc.executebuiltin('ReloadSkin()')
    task = backgroundthread.FunctionAsTask(_clean_file_table, None)
    backgroundthread.BGThreader.addTasksToFront([task])
Exemple #59
0
 def hasTV(self):
     return bool(xbmc.getCondVisibility('Library.HasContent(TVShows)'))
Exemple #60
0
def get_environment():
    """
    Devuelve las variables de entorno del OS, de Kodi y de Alfa más habituales,
    necesarias para el diagnóstico de fallos 
    """

    try:
        import base64
        import ast

        environment = config.get_platform(full_version=True)
        environment['num_version'] = str(environment['num_version'])
        environment['python_version'] = str(platform.python_version())

        environment['os_release'] = str(platform.release())
        if xbmc.getCondVisibility("system.platform.Windows"):
            try:
                if platform._syscmd_ver()[2]:
                    environment['os_release'] = str(platform._syscmd_ver()[2])
            except:
                pass
        environment['prod_model'] = ''
        if xbmc.getCondVisibility("system.platform.Android"):
            environment['os_name'] = 'Android'
            try:
                for label_a in subprocess.check_output('getprop').split('\n'):
                    if 'build.version.release' in label_a:
                        environment['os_release'] = str(
                            scrapertools.find_single_match(
                                label_a, ':\s*\[(.*?)\]$'))
                    if 'product.model' in label_a:
                        environment['prod_model'] = str(
                            scrapertools.find_single_match(
                                label_a, ':\s*\[(.*?)\]$'))
            except:
                try:
                    for label_a in filetools.read(os.environ['ANDROID_ROOT'] +
                                                  '/build.prop').split():
                        if 'build.version.release' in label_a:
                            environment['os_release'] = str(
                                scrapertools.find_single_match(
                                    label_a, '=(.*?)$'))
                        if 'product.model' in label_a:
                            environment['prod_model'] = str(
                                scrapertools.find_single_match(
                                    label_a, '=(.*?)$'))
                except:
                    pass

        elif xbmc.getCondVisibility("system.platform.Linux.RaspberryPi"):
            environment['os_name'] = 'RaspberryPi'
        else:
            environment['os_name'] = str(platform.system())

        environment['machine'] = str(platform.machine())
        environment['architecture'] = str(sys.maxsize > 2**32 and "64-bit"
                                          or "32-bit")
        environment['language'] = str(xbmc.getInfoLabel('System.Language'))

        environment['cpu_usage'] = str(xbmc.getInfoLabel('System.CpuUsage'))

        environment['mem_total'] = str(
            xbmc.getInfoLabel('System.Memory(total)')).replace('MB',
                                                               '').replace(
                                                                   'KB', '')
        environment['mem_free'] = str(
            xbmc.getInfoLabel('System.Memory(free)')).replace('MB',
                                                              '').replace(
                                                                  'KB', '')
        if not environment['mem_total'] or not environment['mem_free']:
            try:
                if environment['os_name'].lower() == 'windows':
                    kernel32 = ctypes.windll.kernel32
                    c_ulong = ctypes.c_ulong
                    c_ulonglong = ctypes.c_ulonglong

                    class MEMORYSTATUS(ctypes.Structure):
                        _fields_ = [('dwLength', c_ulong),
                                    ('dwMemoryLoad', c_ulong),
                                    ('dwTotalPhys', c_ulonglong),
                                    ('dwAvailPhys', c_ulonglong),
                                    ('dwTotalPageFile', c_ulonglong),
                                    ('dwAvailPageFile', c_ulonglong),
                                    ('dwTotalVirtual', c_ulonglong),
                                    ('dwAvailVirtual', c_ulonglong),
                                    ('availExtendedVirtual', c_ulonglong)]

                    memoryStatus = MEMORYSTATUS()
                    memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
                    kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
                    environment['mem_total'] = str(
                        int(memoryStatus.dwTotalPhys) / (1024**2))
                    environment['mem_free'] = str(
                        int(memoryStatus.dwAvailPhys) / (1024**2))

                else:
                    with open('/proc/meminfo') as f:
                        meminfo = f.read()
                    environment['mem_total'] = str(
                        int(
                            re.search(r'MemTotal:\s+(\d+)',
                                      meminfo).groups()[0]) / 1024)
                    environment['mem_free'] = str(
                        int(
                            re.search(r'MemAvailable:\s+(\d+)',
                                      meminfo).groups()[0]) / 1024)
            except:
                environment['mem_total'] = ''
                environment['mem_free'] = ''

        try:
            environment['kodi_buffer'] = '20'
            environment['kodi_bmode'] = '0'
            environment['kodi_rfactor'] = '4.0'
            if filetools.exists(
                    filetools.join(xbmc.translatePath("special://userdata"),
                                   "advancedsettings.xml")):
                advancedsettings = filetools.read(
                    filetools.join(xbmc.translatePath("special://userdata"),
                                   "advancedsettings.xml")).split('\n')
                for label_a in advancedsettings:
                    if 'memorysize' in label_a:
                        environment['kodi_buffer'] = str(
                            int(
                                scrapertools.find_single_match(
                                    label_a, '>(\d+)<\/')) / 1024**2)
                    if 'buffermode' in label_a:
                        environment['kodi_bmode'] = str(
                            scrapertools.find_single_match(
                                label_a, '>(\d+)<\/'))
                    if 'readfactor' in label_a:
                        environment['kodi_rfactor'] = str(
                            scrapertools.find_single_match(
                                label_a, '>(.*?)<\/'))
        except:
            pass

        environment['userdata_path'] = str(
            xbmc.translatePath(config.get_data_path()))
        try:
            if environment['os_name'].lower() == 'windows':
                free_bytes = ctypes.c_ulonglong(0)
                ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                    ctypes.c_wchar_p(environment['userdata_path']), None, None,
                    ctypes.pointer(free_bytes))
                environment['userdata_free'] = str(
                    round(float(free_bytes.value) / (1024**3), 3))
            else:
                disk_space = os.statvfs(environment['userdata_path'])
                if not disk_space.f_frsize:
                    disk_space.f_frsize = disk_space.f_frsize.f_bsize
                environment['userdata_free'] = str(round((float(disk_space.f_bavail) / \
                                (1024**3)) * float(disk_space.f_frsize), 3))
        except:
            environment['userdata_free'] = '?'

        try:
            environment['videolab_series'] = '?'
            environment['videolab_episodios'] = '?'
            environment['videolab_pelis'] = '?'
            environment['videolab_path'] = str(
                xbmc.translatePath(config.get_videolibrary_path()))
            if filetools.exists(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_tvshows"))):
                environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_tvshows")))))
                counter = 0
                for root, folders, files in filetools.walk(filetools.join(environment['videolab_path'], \
                                    config.get_setting("folder_tvshows"))):
                    for file in files:
                        if file.endswith('.strm'): counter += 1
                environment['videolab_episodios'] = str(counter)
            if filetools.exists(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_movies"))):
                environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_movies")))))
        except:
            pass
        try:
            video_updates = ['No', 'Inicio', 'Una vez', 'Inicio+Una vez']
            environment['videolab_update'] = str(
                video_updates[config.get_setting("update", "videolibrary")])
        except:
            environment['videolab_update'] = '?'
        try:
            if environment['os_name'].lower() == 'windows':
                free_bytes = ctypes.c_ulonglong(0)
                ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                    ctypes.c_wchar_p(environment['videolab_path']), None, None,
                    ctypes.pointer(free_bytes))
                environment['videolab_free'] = str(
                    round(float(free_bytes.value) / (1024**3), 3))
            else:
                disk_space = os.statvfs(environment['videolab_path'])
                if not disk_space.f_frsize:
                    disk_space.f_frsize = disk_space.f_frsize.f_bsize
                environment['videolab_free'] = str(round((float(disk_space.f_bavail) / \
                                (1024**3)) * float(disk_space.f_frsize), 3))
        except:
            environment['videolab_free'] = '?'

        environment['torrentcli_name'] = ''
        environment['torrentcli_dload_path'] = ''
        environment['torrentcli_buffer'] = ''
        environment['torrentcli_dload_estrgy'] = ''
        environment['torrentcli_mem_size'] = ''
        environment['torrentcli_free'] = ''
        if config.get_setting("torrent_client", server="torrent") == 4:
            __settings__ = xbmcaddon.Addon(id="plugin.video.torrenter")
            environment['torrentcli_name'] = 'Torrenter'
            environment['torrentcli_dload_path'] = str(
                xbmc.translatePath(__settings__.getSetting('storage')))
            environment['torrentcli_buffer'] = str(
                __settings__.getSetting('pre_buffer_bytes'))
        elif config.get_setting("torrent_client", server="torrent") == 3:
            for client_torrent in ['quasar', 'elementum']:
                if xbmc.getCondVisibility(
                        'System.HasAddon("plugin.video.%s" )' %
                        client_torrent):
                    __settings__ = xbmcaddon.Addon(id="plugin.video.%s" %
                                                   client_torrent)
                    environment['torrentcli_name'] = str(client_torrent)
                    environment['torrentcli_dload_path'] = str(
                        xbmc.translatePath(
                            __settings__.getSetting('download_path')))
                    environment['torrentcli_buffer'] = str(
                        __settings__.getSetting('buffer_size'))
                    environment['torrentcli_dload_estrgy'] = str(
                        __settings__.getSetting('download_storage'))
                    environment['torrentcli_mem_size'] = str(
                        __settings__.getSetting('memory_size'))

        if environment['torrentcli_dload_path']:
            try:
                if environment['os_name'].lower() == 'windows':
                    free_bytes = ctypes.c_ulonglong(0)
                    ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                        ctypes.c_wchar_p(environment['torrentcli_dload_path']),
                        None, None, ctypes.pointer(free_bytes))
                    environment['torrentcli_free'] = str(round(float(free_bytes.value) / \
                                (1024**3), 3))
                else:
                    disk_space = os.statvfs(
                        environment['torrentcli_dload_path'])
                    if not disk_space.f_frsize:
                        disk_space.f_frsize = disk_space.f_frsize.f_bsize
                    environment['torrentcli_free'] = str(round((float(disk_space.f_bavail) / \
                                (1024**3)) * float(disk_space.f_frsize), 3))
            except:
                environment['torrentcli_free'] = '?'

        environment['proxy_active'] = ''
        try:
            proxy_channel_bloqued_str = base64.b64decode(
                config.get_setting('proxy_channel_bloqued')).decode('utf-8')
            proxy_channel_bloqued = dict()
            proxy_channel_bloqued = ast.literal_eval(proxy_channel_bloqued_str)
            for channel_bloqued, proxy_active in proxy_channel_bloqued.items():
                if proxy_active == 'ON':
                    environment['proxy_active'] += channel_bloqued + ', '
        except:
            pass
        if not environment['proxy_active']: environment['proxy_active'] = 'OFF'
        environment['proxy_active'] = environment['proxy_active'].rstrip(', ')

        for root, folders, files in filetools.walk(
                xbmc.translatePath("special://logpath/")):
            for file in files:
                if file.lower() in ['kodi.log', 'jarvis.log', 'spmc.log', 'cemc.log', \
                                'mygica.log', 'wonderbox.log', 'leiapp,log', \
                                'leianmc.log', 'kodiapp.log', 'anmc.log', \
                                'latin-anmc.log']:
                    environment['log_path'] = str(filetools.join(root, file))
                    break
            else:
                environment['log_path'] = ''
            break

        if environment['log_path']:
            environment['log_size_bytes'] = str(
                filetools.getsize(environment['log_path']))
            environment['log_size'] = str(round(float(environment['log_size_bytes']) / \
                                (1024*1024), 3))
        else:
            environment['log_size_bytes'] = ''
            environment['log_size'] = ''

        environment['debug'] = str(config.get_setting('debug'))
        environment['addon_version'] = str(config.get_addon_version())

    except:
        logger.error(traceback.format_exc())
        environment = {}
        environment['log_size'] = ''
        environment['cpu_usage'] = ''
        environment['python_version'] = ''
        environment['log_path'] = ''
        environment['userdata_free'] = ''
        environment['mem_total'] = ''
        environment['torrentcli_mem_size'] = ''
        environment['torrentcli_dload_path'] = ''
        environment['torrentcli_dload_estrgy'] = ''
        environment['machine'] = ''
        environment['platform'] = ''
        environment['torrentcli_buffer'] = ''
        environment['videolab_path'] = ''
        environment['num_version'] = ''
        environment['os_name'] = ''
        environment['torrentcli_free'] = ''
        environment['video_db'] = ''
        environment['userdata_path'] = ''
        environment['log_size_bytes'] = ''
        environment['name_version'] = ''
        environment['language'] = ''
        environment['mem_free'] = ''
        environment['prod_model'] = ''
        environment['proxy_active'] = ''
        environment['architecture'] = ''
        environment['os_release'] = ''
        environment['videolab_free'] = ''
        environment['torrentcli_name'] = ''
        environment['kodi_buffer'] = ''
        environment['kodi_bmode'] = ''
        environment['kodi_rfactor'] = ''
        environment['videolab_series'] = ''
        environment['videolab_episodios'] = ''
        environment['videolab_pelis'] = ''
        environment['videolab_update'] = ''
        environment['debug'] = ''
        environment['addon_version'] = ''

    return environment