Example #1
0
    def __init__(self,rootString):
        self.set_root(rootString)
        
        self.CLIENT_ID = utils.getSetting('google_drive_id')
        self.CLIENT_SECRET = utils.getSetting('google_drive_secret')

        self.setup()
Example #2
0
    def run(self):
        
        #check if there is even a file playing
        if(self.localPlayer.isPlaying()):
            #figure out what xbmc to send to
            selected_xbmc = xbmcgui.Dialog().select(utils.getString(30036),self.host_manager.listHosts())

            if(selected_xbmc != -1):
                #create a local host
                local_host = XbmcHost("Local","127.0.0.1","8080")
                
                #get the address of the host
                remote_host = self.host_manager.getHost(selected_xbmc)

                #check if the remote player is currently playing something
                remote_player = remote_host.isPlaying()

                if(remote_player >= 0 and utils.getSetting("override_destination") == 'true'):
                     #we need to stop the player before sending the new file
                     remote_host.stop()
                     self.sendTo(local_host,remote_host)
                 
                elif(remote_player >= 0 and utils.getSetting("override_destination") == "false"):
                    #we can't stop the player, notify the user
                    xbmcgui.Dialog().ok("SendTo",remote_host.name + " " + utils.getString(30039),utils.getString(30037))

                elif(remote_player == -2):
                    #catch for if the player is off
                    xbmcgui.Dialog().ok("SendTo",remote_host.name + " " + utils.getString(30040),utils.getString(30038))
                    
                else:
                    #not playing anything, send as normal
                    self.sendTo(local_host,remote_host)
Example #3
0
    def __init__(self,rootString):
        self.set_root(rootString)
        
        self.APP_KEY = utils.getSetting('dropbox_key')
        self.APP_SECRET = utils.getSetting('dropbox_secret')

        self.setup()
Example #4
0
def MainList():    
    hasClient = utils.HasClient()

    menu = getGlobalMenu()

    if SHOW_CONFIGURE:
        AddDir( 0, '[I]%s[/I]' % GETTEXT(30020), SETTINGS, isFolder=False, isPlayable=False, desc=GETTEXT(30021), contextMenu=menu)
       
    if SHOW_REFRESH:
        AddDir(10, '[I]%s[/I]' % GETTEXT(30007), CLEARCACHE, isFolder=False, isPlayable=False, desc=GETTEXT(30018), contextMenu=menu)

    if hasClient:
        if SHOW_DOWNLOAD:
            #AddDir(20, '[I]%s[/I]' % GETTEXT(30075), UPDATE_FILE_CHK, isFolder=True, isPlayable=False, desc=GETTEXT(30076), contextMenu=menu)
            xbmcgui.Window(10000).setProperty('LB_CHECK_FOR_DOWNLOADABLE', 'true') 

        #if SHOW_VIMEO:
        #    AddDir(46, GETTEXT(30026), WAITING, isFolder=False, isPlayable=True,  desc=GETTEXT(30028), contextMenu=menu)
        #    AddDir(47, GETTEXT(30027), EXAM,    isFolder=True,  isPlayable=False, desc=GETTEXT(30029), contextMenu=menu)

    if SHOW_REPLAY and len(utils.getSetting('PARAMS')) > 0:
        AddDir(45, '[I]%s[/I]' % GETTEXT(30113), REPLAY, isFolder=False, isPlayable=True, desc=GETTEXT(30114), contextMenu=menu)

    if hasClient and SHOW_AMAZON:
        try:    AddAmazonItems(50, '', menu)
        except: pass

    if SHOW_LOCAL:
        AddFolderItems(100, '', menu)

    if utils.getSetting('DEMO') == 'true':
        AddDir(999, 'Demo',  DEMO, isFolder=True, isPlayable=False, desc='Demo', contextMenu=menu)
Example #5
0
def checkForUpdate(silent = 1):

    if silent == '2' or silent=='3':
        utils.rebootCommand(silent)
        return
        
    if silent == '4':
        try:
            username   = utils.getSetting('username')
            password   = utils.getSetting('password')
            tinyosid   = getHwAddr('wlan0')
            tinyoshw   = utils.getSetting('device')
            url        = 'http://tinyhtpc.co.nz/downloads/tinyos-list.php'
            cj         = cookielib.CookieJar()
            opener     = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
            login_data = urllib.urlencode({'username' : username, 'password' : password})
            opener.open(url, login_data)
            post_id    = urllib.urlencode({'tinyosid' : tinyosid, 'tinyoshw' : tinyoshw})
            resp       = opener.open(url, post_id)
            response   = resp.read()

            #print response
        except:
            return []
        performManualUpdate(response, silent)
        return
        
    utils.saveOta()
    utils.saveHW()
    utils.saveID()
    silent = int(silent) == 1

    if silent and utils.getSetting('autoUpdate') == 'false':
        return allDone(silent)

    response = getResponse()
    isValid  = len(response) > 0

    if not isValid:
        if not silent:
            utils.ok(1, 12, 13)
        return allDone(silent)
   
    if updateAvailable(response['Version']):
        utils.log('Update Available')
        performUpdate(response, silent)    
    elif not silent:
        if downloaded():
            checkPrevious()
        else:
            utils.ok(1, 22, 13)

    allDone(silent)
Example #6
0
 def __init__(self,progressOverride):
     self.override = progressOverride
     
     #check if we should use the progress bar
     if(int(utils.getSetting('progress_mode')) != 2):
         #check if background or normal
         if(int(utils.getSetting('progress_mode')) == 0 and not self.override):
             self.mode = self.DIALOG
             self.progressBar = xbmcgui.DialogProgress()
         else:
             self.mode = self.BACKGROUND
             self.progressBar = xbmcgui.DialogProgressBG()
Example #7
0
def AddToPlaylist(title, image, url, mode=0, isFirst=False):
    windowed = utils.getSetting('PLAYBACK_MODE') == '1'

    if image == DEFAULTMOVIE:
        image = ICON  

    if mode > 0:
        u  = 'plugin://plugin.video.thelivebox/'
        u += '?mode=%d'   % (int(mode) + 10000)
        u += '&url=%s'    % urllib.quote_plus(url)
        u += '&image=%s'  % urllib.quote_plus(image)
        u += '&title=%s'  % urllib.quote_plus(title)
        u += '&window=%s' % urllib.quote_plus(str(windowed))
        url = u

    pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    if isFirst:
        pl.clear() 

    liz = xbmcgui.ListItem(title, iconImage=image, thumbnailImage=image)

    liz.setInfo(type='Video', infoLabels={'Title': title})

    pl.add(url, liz)

    if isFirst:
        SetResolvedUrl(url, success=True, listItem=liz, windowed=windowed)        
Example #8
0
    def __init__(self, addonID):        
        super(Application, self).__init__()  

        #in case it was set whilst addon not running
        xbmcgui.Window(10000).clearProperty('LB_RELAUNCH')

        self.ADDONID         = addonID
        self.skin            = utils.getSetting('SKIN')
        self.properties      = {}        
        self.lists           = []
        self.start           = None        
        self.context         = False
        self.busy            = None
        self.osd             = None
        self.showBack        = True
        self.timer           = None
        self.faves           = str(favourite.getFavourites())
        self.counter         = 0
        self.listSize        = -1

        self.playbackStart = None
        self.playbackEnd   = None

        self.firstRun             = True
        self.checkForUpdatesFreq  = 1 #immediately
        self.checkForInternetFreq = 5
        self.checkForInternet     = True
        self.checkForInternetSkip = False 
        self.checkForEmail        = True
        self.checkForInitialSetup = True

        self.updatedPageVisible = False
        self.updatePageDelay    = 0
Example #9
0
def Server():
    isServer = utils.getSetting('HOST_MODE') == '0'

    if isServer:
        AddDir(1, 'server', 0)
    else:
        AddDir(1, 'client', 0)
Example #10
0
def start():
    if isActive():
        return

    cancel()

    if utils.getSetting('PLAYBACK_LIMIT_MODE') <> '1': #i.e. not time-limit
        return

    xbmcgui.Window(10000).setProperty('LB_ALARM_ACTIVE', 'true')

    limits = [4, 8, 12, 14]
    try:    limit = int(getSetting('PLAYBACK_LIMIT'))
    except: limit = 0

    limit = limits[limit]
    limit = limit * 60 #convert to hours

    import inspect
    script =  inspect.getfile(inspect.currentframe())    #os.path.join(utils.HOME, 'playbacktimer.py')
    cmd    = 'AlarmClock(%s,RunScript(%s),%d,silent)' % (NAME, script, limit)
 
    utils.Log('Playback Timer Started: %s' % str(limit))
    utils.Log(cmd)

    xbmc.executebuiltin(cmd)
def GetTvGuideInformationFile():
    # Get the path to the mc2xml executable
    pathToExecutable = utils.getSetting('path_to_mc2xml')
    if(utils.isNullOrEmpty(pathToExecutable)):
        # Log
        utils.log("[Get Tv Guide Information File] The path to the mc2xml executable hasn't been set.")
        return None

    # Set the path of the executable and redirect to it
    path = os.path.dirname(pathToExecutable)
    os.chdir(path)

    # Get the mc2xml parameters
    mc2xmlParameters = utils.getSetting('mc2xml_parameters').strip()

    # Set the xmltv output path
    xmltvPath = os.path.join(path, "xmltv.xml")
    if(os.path.isfile(xmltvPath)):
        # Set the time difference to be 4 hours for now
        minUpdateDate = dt.datetime.now() - dt.timedelta(hours=4)

        # Get the last modify date of the output file
        lastModifiedDate = dt.datetime.fromtimestamp(os.path.getmtime(xmltvPath))

        # Ensure it hasn't been written to in the past 4 hours
        if(lastModifiedDate > minUpdateDate):
            # Log
            utils.log("[Get Tv Guide Information File] Last update was w/in 4 hours. No need to download the guide data.")
            return xmltvPath

    # Run the mc2xml command
    utils.log('[Get Tv Guide Information File] Executing the mc2xml method: ' +  pathToExecutable + ' ' + mc2xmlParameters)
    startupinfo = None
    if os.name == 'nt':
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
    proc = subprocess.Popen([pathToExecutable, mc2xmlParameters], startupinfo = startupinfo)
    proc.wait()
    utils.log('[Get Tv Guide Information File] The mc2xml execution completed.')

    # Ensure the xmltv.xml output file exists
    if(not os.path.isfile(xmltvPath)):
        # Log
        utils.log("[Get Tv Guide Information File] The xmltv.xml output file does not exist: " + xmltvPath)
        return None

    return xmltvPath
Example #12
0
    def __init__(self):
        self.local_path = xbmc.makeLegalFilename(xbmc.translatePath("special://home"),False);
      
	if(utils.getSetting('remote_selection') == '1'):
	    self.remote_path = utils.getSetting('remote_path_2')
	    utils.setSetting("remote_path","")
        elif(utils.getSetting('remote_selection') == '0'):
            self.remote_path = utils.getSetting("remote_path")

        #fix slashes
        self.remote_path = self.remote_path.replace("\\","/")
        
        #check if trailing slash is included
        if(self.remote_path[-1:] != "/"):
            self.remote_path = self.remote_path + "/"
        
        utils.log(utils.getString(30046))
Example #13
0
    def sendTo(self,local_host,remote_host,reverse=False):
        
        #get the player/playlist id
        playerid = str(local_host.isPlaying())
           
        #get the percentage played and position
        player_props = local_host.playingProperties(playerid)

        #check if the player is currently paused
        if(player_props['speed'] != 0):
            #pause the playing file
            self.pausePlayback(local_host)

        #if reverse these checks don't matter
        keep_playing = True
        if(not reverse):
            #check if we should prompt to keep playback paused
            if(utils.getSetting("pause_prompt") == "true"):
                keep_playing = not xbmcgui.Dialog().yesno(utils.getString(30000),utils.getString(30041))
        
        #get a list of all items in the playlist
        playlist = local_host.getPlaylist(playerid)

        #add these files to the other playlist
        remote_host.addItems(playlist,playerid)

        #play remote playlist
        remote_host.playPosition(str(player_props['position']),playerid)

        #pause the player
        self.pausePlayback(remote_host)

        #seek to the correct spot
        remote_host.seekFile(player_props['percentage'],playerid)

        if(utils.getSetting('continue_host_on_transfer') == 'false'):
            #stop the current player
            local_host.stop(playerid)
            local_host.executeJSON('Playlist.Clear','{"playlistid": ' + playerid + '}')
        else:
            #continue playing
            self.pausePlayback(local_host)
            
        if(keep_playing):
            #unpause
            self.pausePlayback(remote_host)
Example #14
0
def reboot():
    version = utils.getSetting('dVersion') 

    utils.setSetting('cVersion', version)
    utils.setSetting('dVersion', '0.0.0')

    cmd = 'recoveryflash /recovery/update.zip'

    utils.reboot(cmd)
Example #15
0
def _initMyEpisodes():
    username = utils.getSetting('Username')
    password = utils.getSetting('Password')

    login_notif = _language(32912)
    if not username or not password:
        utils.notif(login_notif, time=2500)
        return None

    mye = MyEpisodes(username, password)
    mye.login()
    if mye.is_logged:
        login_notif = "%s %s" % (username, _language(32911))
    utils.notif(login_notif, time=2500)

    if mye.is_logged and (not mye.populate_shows()):
        utils.notif(_language(32927), time=2500)
    return mye
Example #16
0
def validateMode(mode, name):
    if mode == SERVER_FOLDER:
        if name == GETTEXT(30057):
            if utils.IsServer():
                return False
            if utils.getSetting('FALLBACK').lower() == 'true':
                return False

    return True
Example #17
0
def getResponse():
    try:
        username   = utils.getSetting('username')
        password   = utils.getSetting('password')
        tinyosid   = getHwAddr('wlan0')
        tinyoshw   = utils.getSetting('device')
        url        = 'http://tinyhtpc.co.nz/downloads/tinyos-latest.php'
        cj         = cookielib.CookieJar()
        opener     = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        login_data = urllib.urlencode({'username' : username, 'password' : password})
        opener.open(url, login_data)
        post_id    = urllib.urlencode({'tinyosid' : tinyosid, 'tinyoshw' : tinyoshw})
        resp       = opener.open(url, post_id)
        response   = resp.read()
        #print response
    except:
        return []
    return json.loads(u"" + (response))
Example #18
0
    def run(self,mode=-1,runSilent=False):
	#check if we should use the progress bar
        if(utils.getSetting('run_silent') == 'false' and not runSilent):
            self.progressBar = xbmcgui.DialogProgress()
            self.progressBar.create(utils.getString(30010),utils.getString(30049) + "......")

        #determine backup mode
        if(mode == -1):
            mode = int(utils.getSetting('addon_mode'))

        #append backup folder name
        if(mode == self.Backup and self.remote_path != ''):
            self.remote_path = self.remote_path + time.strftime("%Y%m%d") + "/"
	elif(mode == self.Restore and utils.getSetting("backup_name") != '' and self.remote_path != ''):
	    self.remote_path = self.remote_path + utils.getSetting("backup_name") + "/"
	else:
	    self.remote_path = ""

        utils.log(utils.getString(30047) + ": " + self.local_path)
        utils.log(utils.getString(30048) + ": " + self.remote_path)

        #run the correct mode
        if(mode == self.Backup):
            utils.log(utils.getString(30023) + " - " + utils.getString(30016))
            self.fileManager = FileManager(self.local_path)

            #for backups check if remote path exists
            if(vfs.exists(self.remote_path)):
                #this will fail - need a disclaimer here
                utils.log(utils.getString(30050))

            self.syncFiles()
        else:
            utils.log(utils.getString(30023) + " - " + utils.getString(30017))
            self.fileManager = FileManager(self.remote_path)

            #for restores remote path must exist
            if(vfs.exists(self.remote_path)):
                self.restoreFiles()
            else:
                xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30045),self.remote_path)

        if(utils.getSetting('run_silent') == 'false' and not runSilent):
            self.progressBar.close()
Example #19
0
    def checkPlaybackTimes(self):
        now = datetime.datetime.today()

        if len(xbmcgui.Window(10000).getProperty('LB_RESET_START')) > 0:
            utils.Log('Reset Playback START time detected')
            xbmcgui.Window(10000).clearProperty('LB_RESET_START')
            self.playbackStart = None

        if not self.playbackStart:
            self.playbackStart = convertToTime(now.date(), utils.getSetting('PLAYBACK_START'))

            if self.playbackStart < now:
               self.playbackStart += ONE_DAY

            utils.Log('Playback Timer - START = %s' % str(self.playbackStart))

        elif now >= self.playbackStart:
            self.playbackStart += ONE_DAY
            if utils.getSetting('PLAYBACK_LIMIT_MODE') == '2':
                if not xbmc.Player().isPlaying():
                    functionality.replay()

        #-------------------------------------------------------------------------------------

        if len(xbmcgui.Window(10000).getProperty('LB_RESET_END')) > 0:
            utils.Log('Reset Playback END   time detected')
            xbmcgui.Window(10000).clearProperty('LB_RESET_END')
            self.playbackEnd = None

        if not self.playbackEnd:
            self.playbackEnd = convertToTime(now.date(), utils.getSetting('PLAYBACK_END'), isEnd=True)

            if self.playbackEnd < now:
               self.playbackEnd += ONE_DAY 

            utils.Log('Playback Timer - END   = %s' % str(self.playbackEnd))

        elif now >= self.playbackEnd:
            utils.Log('Playback Timer - END   = %s' % str(self.playbackEnd))
            self.playbackEnd += ONE_DAY
            if utils.getSetting('PLAYBACK_LIMIT_MODE') == '2':
                xbmc.Player().stop()
def startService():
    # Log
    utils.log("Main loop execution started.")

    # Run until XBMC exits
    while(not xbmc.abortRequested):
        # Get the update interval
        updateInterval = int(utils.getSetting("update_interval"))

        # Get the current time
        now = dt.datetime.now()

        # Get the last run time
        lastRunTimeString = utils.getSetting("last_run_time")

        # Ensure a run time exists and is in the correct format
        if(utils.isNullOrEmpty(lastRunTimeString) or len(lastRunTimeString) != 14):
            # Set the last run time to now minus the update interval + 1 hour to ensure it runs now
            lastRunTimeString = utils.convertDateToString(now - dt.timedelta(hours = updateInterval + 1))

            # Update the settings
            utils.setSetting("last_run_time", lastRunTimeString)

        # Convert the string to datetime
        lastRunTime = utils.convertStringToDate(lastRunTimeString)

        # Set the next run time
        nextRunTime = lastRunTime + dt.timedelta(hours = updateInterval)

        # See if an update is required
        if(nextRunTime < now):
            # Run the update
            update.UpdateGuideInformation()

            # Update the settings
            utils.setSetting("last_run_time", utils.convertDateToString(dt.datetime.now()))

        # Sleep
        time.sleep(1)

    # Log
    utils.log("Main loop execution ended.")
Example #21
0
 def configureRemote(self):
     if(utils.getSetting('remote_selection') == '1'):
         self.remote_base_path = utils.getSetting('remote_path_2');
         self.remote_vfs = XBMCFileSystem(utils.getSetting('remote_path_2'))
         utils.setSetting("remote_path","")
     elif(utils.getSetting('remote_selection') == '0'):
         self.remote_base_path = utils.getSetting('remote_path');
         self.remote_vfs = XBMCFileSystem(utils.getSetting("remote_path"))
     elif(utils.getSetting('remote_selection') == '2'):
         self.remote_base_path = "/"
         self.remote_vfs = DropboxFileSystem("/")
     elif(utils.getSetting('remote_selection') == '3'):
         self.remote_base_path = '/Kodi Backup/'
         self.remote_vfs = GoogleDriveFilesystem('/Kodi Backup/')
Example #22
0
def replay():
    global PARAMS
    PARAMS = utils.getSetting('PARAMS')

    if len(PARAMS) == 0:
        return

    global REPEAT
    REPEAT = 'RepeatAll'

    main(get_params(PARAMS)) 
       
    REPEAT = None
Example #23
0
def SetResolvedUrl(url, success=True, listItem=None, windowed=True):
    skin = utils.getSetting('SKIN')
    if skin == 'Thumbnails':
        windowed = False
    if skin == 'Thumbnails + Zoom':
        windowed = False

    #APPLICATION.setResolvedUrl(url, success=success, listItem=listItem, windowed=windowed)
    pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    xbmc.Player(xbmc.PLAYER_CORE_AUTO).play(pl, windowed=windowed)
    utils.setSetting('PARAMS', PARAMS)
    import playbackTimer
    playbackTimer.restart()
Example #24
0
def updateAvailable(latest):
    current = utils.getSetting('cVersion')
    current = current.split('.')
    latest  = latest.split('.')

    length  = min(len(current), len(latest))

    for i in range(0, length):
        if int(latest[i]) > int(current[i]):
            utils.flagUpdate()
            return True

    return False
Example #25
0
 def configureRemote(self):
     if(utils.getSetting('remote_selection') == '1'):
         self.remote_base_path = utils.getSetting('remote_path_2');
         self.remote_vfs = XBMCFileSystem(utils.getSetting('remote_path_2'))
         utils.setSetting("remote_path","")
     elif(utils.getSetting('remote_selection') == '0'):
         self.remote_base_path = utils.getSetting('remote_path');
         self.remote_vfs = XBMCFileSystem(utils.getSetting("remote_path"))
def init():
    # Get the path to the mc2xml executable
    pathToExecutable = utils.getSetting('path_to_mc2xml')
    if(not utils.isNullOrEmpty(pathToExecutable)):
        # Set the xmltv output path
        xmltvPath = os.path.join(pathToExecutable, "xmltv.xml")

        # See if the file does not exist
        if(not os.path.isfile(xmltvPath)):
            # Log
            utils.log("[Init] The tv guide information hasn't been set. Clearing the last run time to ensure it runs at startup.")

            # Clear the last run time
            utils.setSetting("last_run_time", "")
Example #27
0
    def _rotateBackups(self):
        total_backups = int(utils.getSetting('backup_rotation'))
        if(total_backups > 0):
            #get a list of valid backup folders
            dirs = self.listBackups()

            if(len(dirs) > total_backups):
                #remove backups to equal total wanted
                remove_num = 0
                self.filesTotal = self.filesTotal + remove_num + 1

                #update the progress bar if it is available
                while(remove_num < (len(dirs) - total_backups) and not self.progressBar.checkCancel()):
                    self._updateProgress(utils.getString(30054) + " " + dirs[remove_num][1])
                    utils.log("Removing backup " + dirs[remove_num][0])
                    self.remote_vfs.rmdir(self.remote_base_path + dirs[remove_num][0] + "/")
                    remove_num = remove_num + 1
Example #28
0
    def __init__(self, addonID):
        super(Application, self).__init__()
        self.ADDONID = addonID
        self.skin = utils.getSetting('SKIN')
        self.properties = {}
        self.lists = []
        self.start = None
        self.context = False
        self.busy = None
        self.showBack = False
        self.timer = None
        self.faves = str(favourites.getFavourites())
        #self.relaunch        = False
        self.counter = 0
        self.listSize = -1

        self.setProperty('LB_FOOTER', 'Powered by SWIFT')
        self.setProperty('LB_TITLE', GETTEXT(30000))
        self.setProperty('LB_MAINDESC', GETTEXT(30002))
def GetSubscribedChannelStreams():
    channels = {}

    # Log
    utils.log("[Get Subscribed Channels] Started")

    # Get the HD Homerun UPnP address
    upnpAddress = utils.getSetting('pnp_address')
    if(utils.isNullOrEmpty(upnpAddress)):
        return channels

    # Ensure it's the cable tv folder
    if(not upnpAddress.endswith("CableTV")):
        upnpAddress += "CableTV"

    # Get the subscribed channels in the hdhomerun cable tv folder
    folders, files = xbmcvfs.listdir(upnpAddress)

    # Parse the channel folders
    if(folders is not None):
        # Log
        utils.log("[Get Subscribed Channels] # of channels found: " + str(len(folders)))

        # Parse the folders
        for folder in folders:
            channelNumber = None

            # Format of the folder is CableTV%2fv[Channel Number]
            if(folder.startswith("CableTV%2f")):
                channelNumber = folder[10:]
            elif(folder.startswith("CableTV/")):
                channelNumber = folder[8:]
            else:
                continue

            # Add the channel number to the list
            channels[channelNumber[1:]] = upnpAddress + '/' + channelNumber

    # Log
    utils.log("[Get Subscribed Channels] Completed")

    # Return the subscribed channels
    return channels
Example #30
0
def checkForUpdate(silent = 1):

    if silent == '2' or silent=='3':
        utils.rebootCommand(silent)
        return
        
    if silent == '4':
        try:
            url      = 'http://cloud.thelittleblackbox.co.uk/manual.{0}.php'.format(utils.getAmlogicCpuType())
            response = urllib2.urlopen(url).read()
        except:
            return []
        performManualUpdate(response, silent)
        return
        
    utils.saveOta()
    silent = int(silent) == 1

    if silent and utils.getSetting('autoUpdate') == 'false':
        return allDone(silent)

    response = getResponse()
    isValid  = len(response) > 0

    if not isValid:
        if not silent:
            utils.ok(1, 12, 13)
        return allDone(silent)
   
    if updateAvailable(response['Version']):
        utils.log('Update Available')
        performUpdate(response, silent)    
    elif not silent:
        if downloaded():
            checkPrevious()
        else:
            utils.ok(1, 22, 13)

    allDone(silent)
Example #31
0
def checkForUpdate(silent=1):

    if silent == '2' or silent == '3':
        utils.rebootCommand(silent)
        return

    if silent == '4':
        try:
            url = 'http://navixhardware.com/manual.m3.php'
            response = urllib2.urlopen(url).read()
        except:
            return []
        performManualUpdate(response, silent)
        return

    utils.saveOta()
    silent = int(silent) == 1

    if silent and utils.getSetting('autoUpdate') == 'false':
        return allDone(silent)

    response = getResponse()
    isValid = len(response) > 0

    if not isValid:
        if not silent:
            utils.ok(1, 12, 13)
        return allDone(silent)

    if updateAvailable(response['Version']):
        utils.log('Update Available')
        performUpdate(response, silent)
    elif not silent:
        if downloaded():
            checkPrevious()
        else:
            utils.ok(1, 22, 13)

    allDone(silent)
Example #32
0
def main():
    utils.Log('Playback Timer Stopped')

    if not xbmc.Player().isPlaying():    
        utils.Log('No video playing in playback timer')
        return

    if xbmc.getCondVisibility('player.paused') <> 1:
        utils.Log('Pausing video in playback timer')
        xbmc.Player().pause()

    try:
        limit = utils.getSetting('PLAYBACK_LIMIT')
        limit = GETTEXT(35101+int(limit))
    except:
        limit = '4 hours'

    if utils.DialogYesNo(GETTEXT(30106) % limit, GETTEXT(30107), GETTEXT(30108), noLabel=GETTEXT(30109), yesLabel=GETTEXT(30110)):
        xbmc.Player().pause()
        start()
        return

    xbmc.Player().stop()
Example #33
0
    def _rotateBackups(self):
        total_backups = int(utils.getSetting('backup_rotation'))
        
        if(total_backups > 0):
            #get a list of valid backup folders
            dirs = self.listBackups()
            
            if(len(dirs) > total_backups):
                #remove backups to equal total wanted
                remove_num = 0
                self.filesTotal = self.filesTotal + remove_num + 1

                #update the progress bar if it is available
                while(remove_num < (len(dirs) - total_backups) and not self.progressBar.checkCancel()):
                    self._updateProgress(utils.getString(30054) + " " + dirs[remove_num][1])
                    utils.log("Removing backup " + dirs[remove_num][0])
                    
                    if(dirs[remove_num][0].split('.')[-1] == 'zip'):
                        #this is a file, remove it that way
                        self.remote_vfs.rmfile(self.remote_base_path + dirs[remove_num][0])
                    else:
                        self.remote_vfs.rmdir(self.remote_base_path + dirs[remove_num][0] + "/")
                        
                    remove_num = remove_num + 1
Example #34
0
def RemoveAddonShortcut():
    import glob

    path = xbmc.translatePath(os.path.join('special://home', 'addons', '*.*'))
    shortcuts = utils.getSetting('ADDONS').split('|')

    names = []

    for addon in glob.glob(path):
        try:
            name = addon.lower().rsplit(os.path.sep, 1)[-1]
            if name in shortcuts:
                realname = xbmcaddon.Addon(name).getAddonInfo('name')
                names.append([Capitalize(realname), name])
        except:
            pass

    if len(names) < 1:
        return

    names.sort()

    addons = []
    for name in names:
        addons.append(name[0])

    option = xbmcgui.Dialog().select('Select addon to remove', addons)

    if option < 0:
        return False

    update = RemoveShortcut(names[option][1])

    #   utils.setSetting('ADDONS', update)

    return True
Example #35
0
def PlayYT(id):
    xbmc.executebuiltin('Dialog.Show(busydialog)')

    video, links = yt.GetVideoInformation(id)

    xbmc.executebuiltin('Dialog.Close(busydialog)')

    if 'best' not in video:
        return False

    url = video['best']
    title = video['title']
    image = video['thumbnail']

    liz = xbmcgui.ListItem(title, iconImage=image, thumbnailImage=image)

    liz.setInfo(type="Video", infoLabels={"Title": title})

    windowed = utils.getSetting('PLAYBACK') == '1'

    APPLICATION.setResolvedUrl(url,
                               success=True,
                               listItem=liz,
                               windowed=windowed)
 def setup(self):
     self._scheme = "https" if getSetting("ssl", bool) else "http"
     self._netloc = getSetting("instance", unicode)
     _path = "{}/".format(getSetting("path", unicode).strip("/"))
     self._url = urlunsplit((self._scheme, self._netloc, _path, "", ""))
     log("service.url: '{}'".format(self._url))
Example #37
0
    def onAction(self, action):
        #see here https://github.com/xbmc/xbmc/blob/master/xbmc/guilib/Key.h for the full list

        actionId = action.getId()
        buttonId = action.getButtonCode()

        if actionId != 107:
            utils.Log('onAction actionID %d' % actionId)
            utils.Log('onAction buttonID %d' % buttonId)

        if actionId in [ACTION_CONTEXT, ACTION_RCLICK]:
            return self.onContextMenu()

        if actionId in [ACTION_PARENT_DIR, ACTION_BACK] or buttonId in [ESC]:
            if not confirmExit or utils.DialogYesNo(
                    'Are you sure you wish to quit Community Portal?'):
                return self.onBack()
            return  #            return self.onBack()

        try:
            id = self.getFocus().getId()
        except:
            id = 0

        select = (actionId == ACTION_SELECT) or (actionId == ACTION_LCLICK)

        if select and id == MAINLIST:
            liz = self.getSelectedItem()
            param = liz.getProperty('Param')
            image = liz.getProperty('Image')
            mode = int(liz.getProperty('Mode'))
            isFolder = liz.getProperty('IsFolder') == 'true'
            isPlayable = liz.getProperty('IsPlayable') == 'true'

            if mode == LISTBACK:
                return self.onBack()

            if param:
                self.stopTimer()
                self.onParams(param, isFolder)
                self.resetTimer()

        if select and id == CATEGORIES:
            categoriesList = categories.getSetting('categories').split('|')
            if categoriesList[0] == '':
                categoriesList = []

            functionality.ShowCategories(categoriesList)

        if select and id == SETTINGS:
            addonID = 'script.tvportal.epg'

            functionality.ShowSettings(addonID)

        if select and id == TOOLS:
            functionality.OpenTools()

        if select and id == TVGUIDE:
            xbmc.executebuiltin('RunScript(script.tvportal.epg)')

        if select and id == MOVIES:
            if utils.getSetting('KodiLib') == 'true':
                xbmc.executebuiltin(
                    'ActivateWindow(10501,plugin://plugin.video.genesis/?action=movieNavigator,return)'
                )
            else:
                xbmc.executebuiltin(
                    'ActivateWindow(10025,videodb://1/2,return)')

        if select and id == TVSHOWS:
            if utils.getSetting('KodiLib') == 'true':
                xbmc.executebuiltin(
                    'ActivateWindow(10501,plugin://plugin.video.genesis/?action=tvNavigator,return)'
                )

            else:
                xbmc.executebuiltin(
                    'ActivateWindow(10025,videodb://2/2,return)')

        if select and id == NETFLIX:
            xbmc.executebuiltin(
                'StartAndroidActivity("com.netflix.mediaclient"),return')

        if select and id == MOVIEANDTV:
            xbmc.executebuiltin('XBMC.RunAddon(plugin.video.genesis)')

        if select and id == WORLDTV:
            xbmc.executebuiltin('XBMC.RunAddon(plugin.video.alluc.api)')

        if select and id == ANDROID:
            xbmc.executebuiltin(
                'ActivateWindow(10025,androidapp://sources/apps,return)')

        if select and id == ADULT:
            xbmc.executebuiltin(
                'ActivateWindow(10501,plugin://plugin.program.super.favourites/?label=Adult&mode=400&path=special://userdata/addon_data/plugin.program.super.favourites/Super Favourites/Adult/,return)'
            )

        if select and id == VIDEOWINDOW:
            xbmc.executebuiltin('Action(fullscreen)')
Example #38
0
import utils as utils
import xbmc
import xbmcvfs
import xbmcgui
import zipfile
import zlib
from dropbox import client, rest, session

APP_KEY = utils.getSetting('dropbox_key')
APP_SECRET = utils.getSetting('dropbox_secret')


class Vfs:
    root_path = None

    def __init__(self, rootString):
        self.set_root(rootString)

    def set_root(self, rootString):
        old_root = self.root_path
        self.root_path = rootString

        #fix slashes
        self.root_path = self.root_path.replace("\\", "/")

        #check if trailing slash is included
        if (self.root_path[-1:] != "/"):
            self.root_path = self.root_path + "/"

        #return the old root
        return old_root
Example #39
0
try:
    import sys
    sfAddon = xbmcaddon.Addon(id=SUPERFAVES)
    sfPath = sfAddon.getAddonInfo('path')
    sys.path.insert(0, sfPath)

    import chooser
    import favourite

    SFFILE = os.path.join(PROFILE, 'favourites.xml')
except:
    SF_INSTALLED = False

IMAGES = os.path.join(HOME, 'resources', 'images')

AUTOSTREAM = utils.getSetting('AUTOSTREAM') == 'true'
KIOSKMODE = utils.getSetting('KIOSKMODE') == 'true'
showaddons = ADDON.getSetting('showaddons')
showbuilds = ADDON.getSetting('showbuilds')
showdownloads = ADDON.getSetting('showdownloads')
showhardware = ADDON.getSetting('showhardware')
showtutorials = ADDON.getSetting('showtutorials')
showepg = ADDON.getSetting('showepg')
showkeywords = ADDON.getSetting('showkeywords')
showmaintenance = ADDON.getSetting('showmaintenance')
showtv = ADDON.getSetting('showtv')
showmovies = ADDON.getSetting('showmovies')
showsearch = ADDON.getSetting('showsearch')
showfaves = ADDON.getSetting('showfaves')

GETTEXT = utils.GETTEXT
Example #40
0
def onParams(application, _params):
    global APPLICATION
    APPLICATION = application

    params = get_params(_params)
    mode = None

    try:
        mode = int(urllib.unquote_plus(params['mode']))
    except:
        pass

    try:
        url = urllib.unquote_plus(params['url'])
    except:
        url = None

    if mode == _SCRIPT:
        cmd = 'RunScript(%s)' % url
        xbmc.executebuiltin(cmd)
    elif mode == _ADDON:
        xbmc.executebuiltin('ActivateWindow(%d,"plugin://%s/",return)' %
                            (WINDOWID, url))
    elif mode == _SUPERFAVE:
        xbmc.executebuiltin(url)
    elif mode == _REMOVESUPERFAVE:
        if RemoveSFShortcut(url):
            APPLICATION.containerRefresh()
    elif mode == _MOVIES:
        if utils.getSetting('KodiLib') == 'true':
            sfmovies = xbmc.translatePath(
                'special://profile/addon_data/plugin.program.super.favourites/Super Favourites/Movies'
            )
            if not os.path.exists(sfmovies):
                try:
                    os.makedirs(sfmovies)
                except:
                    pass
            xbmc.executebuiltin(
                'ActivateWindow(10001,plugin://plugin.program.super.favourites/?label=Movies&mode=400&path=special://profile/addon_data/plugin.program.super.favourites/Super Favourites/Movies,return)'
            )
        else:
            xbmc.executebuiltin('ActivateWindow(10025,videodb://1/2,return)')
    elif mode == _TVSHOWS:
        if utils.getSetting('KodiLib') == 'true':
            sftvshows = xbmc.translatePath(
                'special://profile/addon_data/plugin.program.super.favourites/Super Favourites/TV Shows'
            )
            if not os.path.exists(sftvshows):
                try:
                    os.makedirs(sftvshows)
                except:
                    pass
            xbmc.executebuiltin(
                'ActivateWindow(10001,plugin://plugin.program.super.favourites/?label=TV Shows&mode=400&path=special://profile/addon_data/plugin.program.super.favourites/Super Favourites/TV Shows,return)'
            )
        else:
            xbmc.executebuiltin('ActivateWindow(10025,videodb://2/2,return)')
    elif mode == _CATEGORIES:
        ShowCategories(categoriesList)
    elif mode == _SETTINGS:
        ShowSettings()
    elif mode == _INI:
        cmd = 'XBMC.RunScript(special://home/addons/script.tvportal.epg/getIni.py)'
        xbmc.executebuiltin(cmd)
    elif mode == _ADDONS_POPULAR:
        xbmc.executebuiltin(
            'ActivateWindow(10001,plugin://plugin.program.totalinstaller/?mode=addonmenu,return)'
        )
        #put while folder is the CP addons folder sleep 500
        path = str(xbmc.getInfoLabel('ListItem.FolderPath'))
        while 'addon' in path:
            xbmc.sleep(500)
            path = str(xbmc.getInfoLabel('ListItem.FolderPath'))
        xbmc.executebuiltin(
            'RunScript(special://home/addons/script.community.portal/?mode=_ADDONS_POPULAR)'
        )  # % (WINDOWID, url, 'addonsmenu'))
    elif mode == _CHANNELS:
        xbmc.executebuiltin('ActivateWindow(%d,"plugin://%s/?mode=%d")' %
                            (WINDOWID, TOOLS, 1900))
    elif mode == _SKINS:
        xbmc.executebuiltin('ActivateWindow(%d,"plugin://%s/?mode=%d")' %
                            (WINDOWID, TOOLS, 2000))
    elif mode == _LOGOS:
        xbmc.executebuiltin('ActivateWindow(%d,"plugin://%s/?mode=%d")' %
                            (WINDOWID, TOOLS, 2100))
    elif mode == _TOOLS:
        ShowTools()
    elif mode == _YOUTUBE:
        PlayYT(url)
    elif mode == _VPNICITY:
        SelectVPNicity(url)
    elif mode == _CATCHUP:
        ShowCatchup()
    elif mode == _COMMUNITY_BUILDS:
        communitybuildpath = xbmc.translatePath(
            'special://home/addons/script.community.builds')
        if os.path.exists(communitybuildpath):
            xbmc.executebuiltin(
                'RunScript(special://home/addons/script.community.builds/default.py)'
            )
        else:
            choice = utils.DialogYesNo(
                'Add-on Required',
                'You need the Community Builds module installed to access this section. Would you like to install now?'
            )
            if choice == 1:
                print "download function required"
                try:
                    download.download(
                        'http://github.com/noobsandnerds/zips/script.community.builds/script.community.builds.zip',
                        os.path.join(PACKAGES, 'update.zip'))
                    extract.all(os.path.join(PACKAGES, 'update.zip'), ADDONS)
                except:
                    print "### Failed to download and extract Community Builds add-on"
#        ShowAddonsMenu()
    elif mode == _ADDONS:
        addonportalpath = xbmc.translatePath(
            'special://home/addons/script.addon.portal')
        if os.path.exists(addonportalpath):
            xbmc.executebuiltin(
                'RunScript(special://home/addons/script.addon.portal/default.py)'
            )
        else:
            choice = utils.DialogYesNo(
                'Add-on Required',
                'You need the Add-on Portal module installed to access this section. Would you like to install now?'
            )
            if choice == 1:
                print "download function required"
                try:
                    download.download(
                        'http://github.com/noobsandnerds/zips/script.addon.portal/script.addon.portal.zip',
                        os.path.join(PACKAGES, 'update.zip'))
                    extract.all(os.path.join(PACKAGES, 'update.zip'), ADDONS)
                except:
                    print "### Failed to download and extract Addon Portal"
    elif mode == _SUPERSEARCH:
        SelectSuperSearch(url)
    elif mode == _SHOWSHORTCUTS:
        ShowShortcuts()
    elif mode == _ADDSHORTCUT:
        if AddShortcut():
            APPLICATION.containerRefresh()
    elif mode == _REMOVESHORTCUT:
        if RemoveShortcut(url):
            APPLICATION.containerRefresh()

#    elif mode == _REMOVEADDONSHORTCUT:
#        RemoveAddonShortcut()

    else:
        Main()
Example #41
0
 def sendNotification(self, message):
     self.executeJSON(
         'GUI.ShowNotification',
         '{"title":"' + utils.getSetting("notification_title") +
         '","message":"' + message + '"}')
Example #42
0
def performManualUpdate(response, silent):
    try:
        import xbmcgui
        path = getDownloadPath()
        select_name = ['Cancel']
        select_url = ['Cancel']

        for i in json.loads(response):

            cVersion = utils.getSetting('cVersion')

            if not cVersion in i['Version']:
                select_name.append(i['Version'])
                select_url.append(i['Link'] + '*' + i['Version'] + '*' +
                                  i['MD5'])

        link = select_url[xbmcgui.Dialog().select(
            'Your Current Firmware ' + cVersion, select_name)]

        if 'Cancel' in link:
            return
        url = link.split('*')[0]
        version = link.split('*')[1]
        md5 = link.split('*')[2]

        if utils.generateMD5(path) != md5:
            if (not silent) and (not utils.yesno(1, 11, 0)):

                return

            dp = None

            if silent:
                dp = utils.progress(1, 14, 15)

            hash = 0
            count = 0
            nTries = 3

            if not silent:
                nTries = 1

            while (count < nTries) and (hash != md5):
                count += 1
                try:
                    download(url, path, version, dp)
                    hash = utils.generateMD5(path)
                except Exception, e:
                    utils.deleteFile(path)
                    if str(e) == 'Canceled':
                        return

            if hash != md5:
                utils.unflagUpdate()
                utils.deleteFile(path)
                utils.setSetting('dVersion', '0.0.0')
                if not silent:
                    utils.ok(1, 24, 13)
                return

        utils.setSetting('dVersion', version)

        if not utils.okReboot(1, 23, 16, 18, delay=15):
            return

        reboot()
Example #43
0
    def run(self,mode=-1,progressOverride=False):
        #set windows setting to true
        window = xbmcgui.Window(10000)
        window.setProperty(utils.__addon_id__ + ".running","true")
        
        #append backup folder name
        progressBarTitle = utils.getString(30010) + " - "
        if(mode == self.Backup and self.remote_vfs.root_path != ''):
            if(utils.getSetting("compress_backups") == 'true'):
                #delete old temp file
                if(self.xbmc_vfs.exists(xbmc.translatePath('special://temp/xbmc_backup_temp.zip'))):
                    if(not self.xbmc_vfs.rmfile(xbmc.translatePath('special://temp/xbmc_backup_temp.zip'))):
                        #we had some kind of error deleting the old file
                        xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30096),utils.getString(30097))
                        return
                    
                #save the remote file system and use the zip vfs
                self.saved_remote_vfs = self.remote_vfs
                self.remote_vfs = ZipFileSystem(xbmc.translatePath("special://temp/xbmc_backup_temp.zip"),"w")
                
            self.remote_vfs.set_root(self.remote_vfs.root_path + time.strftime("%Y%m%d%H%M") + "/")
            progressBarTitle = progressBarTitle + utils.getString(30023) + ": " + utils.getString(30016)
        elif(mode == self.Restore and self.restore_point != None and self.remote_vfs.root_path != ''):
            if(self.restore_point.split('.')[-1] != 'zip'):
                self.remote_vfs.set_root(self.remote_vfs.root_path + self.restore_point + "/")
            progressBarTitle = progressBarTitle + utils.getString(30023) + ": " + utils.getString(30017)
        else:
            #kill the program here
            self.remote_vfs = None
            return

        utils.log(utils.getString(30047) + ": " + self.xbmc_vfs.root_path)
        utils.log(utils.getString(30048) + ": " + self.remote_vfs.root_path)

        
        #setup the progress bar
        self.progressBar = BackupProgressBar(progressOverride)
        self.progressBar.create(progressBarTitle,utils.getString(30049) + "......")

        if(mode == self.Backup):
            utils.log(utils.getString(30023) + " - " + utils.getString(30016))
            #check if remote path exists
            if(self.remote_vfs.exists(self.remote_vfs.root_path)):
                #may be data in here already
                utils.log(utils.getString(30050))
            else:
                #make the remote directory
                self.remote_vfs.mkdir(self.remote_vfs.root_path)

            #create a validation file for backup rotation
            writeCheck = self._createValidationFile()
            
            if(not writeCheck):
                #we may not be able to write to this destination for some reason
                shouldContinue = xbmcgui.Dialog().yesno(utils.getString(30089),utils.getString(30090), utils.getString(30044),autoclose=25000)
                
                if(not shouldContinue):
                    return

            utils.log(utils.getString(30051))
            allFiles = []
            fileManager = FileManager(self.xbmc_vfs)
         
            #go through each of the user selected items and write them to the backup store
            if(utils.getSetting('backup_addons') == 'true'):
                fileManager.addFile("-" + xbmc.translatePath('special://home/addons'))
                fileManager.walkTree(xbmc.translatePath('special://home/addons'))

            fileManager.addFile("-" + xbmc.translatePath('special://home/userdata'))

            if(utils.getSetting('backup_addon_data') == 'true'):
                fileManager.addFile("-" + xbmc.translatePath('special://home/userdata/addon_data'))
                fileManager.walkTree(xbmc.translatePath('special://home/userdata/addon_data'))

            if(utils.getSetting('backup_database') == 'true'):
                fileManager.addFile("-" + xbmc.translatePath('special://home/userdata/Database'))
                fileManager.walkTree(xbmc.translatePath('special://home/userdata/Database'))
        
            if(utils.getSetting("backup_playlists") == 'true'):
                fileManager.addFile("-" + xbmc.translatePath('special://home/userdata/playlists'))
                fileManager.walkTree(xbmc.translatePath('special://home/userdata/playlists'))

            if(utils.getSetting('backup_profiles') == 'true'):
                fileManager.addFile("-" + xbmc.translatePath('special://home/userdata/profiles'))
                fileManager.walkTree(xbmc.translatePath('special://home/userdata/profiles'))
            
            if(utils.getSetting("backup_thumbnails") == "true"):
                fileManager.addFile("-" + xbmc.translatePath('special://home/userdata/Thumbnails'))
                fileManager.walkTree(xbmc.translatePath('special://home/userdata/Thumbnails'))
 
            if(utils.getSetting("backup_config") == "true"):
                fileManager.addFile("-" + xbmc.translatePath('special://home/userdata/keymaps'))
                fileManager.walkTree(xbmc.translatePath('special://home/userdata/keymaps'))
                
                fileManager.addFile("-" + xbmc.translatePath('special://home/userdata/peripheral_data'))
                fileManager.walkTree(xbmc.translatePath('special://home/userdata/peripheral_data'))
            
                fileManager.addFile('-' + xbmc.translatePath('special://home/userdata/library'))
                fileManager.walkTree(xbmc.translatePath('special://home/userdata/library'))
            
                #this part is an oddity
                dirs,configFiles = self.xbmc_vfs.listdir(xbmc.translatePath('special://home/userdata/'))
                for aFile in configFiles:
                    if(aFile.endswith(".xml")):
                        fileManager.addFile(xbmc.translatePath('special://home/userdata/') + aFile)

            #add to array
            self.filesTotal = fileManager.size()
            allFiles.append({"source":self.xbmc_vfs.root_path,"dest":self.remote_vfs.root_path,"files":fileManager.getFiles()})

            orig_base_path = self.remote_vfs.root_path
            
            #check if there are custom directories
            if(utils.getSetting('custom_dir_1_enable') == 'true' and utils.getSetting('backup_custom_dir_1') != ''):

                #create a special remote path with hash                
                self.xbmc_vfs.set_root(utils.getSetting('backup_custom_dir_1'))
                fileManager.addFile("-custom_" + self._createCRC(self.xbmc_vfs.root_path))

                #walk the directory
                fileManager.walkTree(self.xbmc_vfs.root_path)
                self.filesTotal = self.filesTotal + fileManager.size()
                allFiles.append({"source":self.xbmc_vfs.root_path,"dest":self.remote_vfs.root_path + "custom_" + self._createCRC(self.xbmc_vfs.root_path),"files":fileManager.getFiles()})

            if(utils.getSetting('custom_dir_2_enable') == 'true' and utils.getSetting('backup_custom_dir_2') != ''):

                #create a special remote path with hash                
                self.xbmc_vfs.set_root(utils.getSetting('backup_custom_dir_2'))
                fileManager.addFile("-custom_" + self._createCRC(self.xbmc_vfs.root_path))

                #walk the directory
                fileManager.walkTree(self.xbmc_vfs.root_path)
                self.filesTotal = self.filesTotal + fileManager.size()
                allFiles.append({"source":self.xbmc_vfs.root_path,"dest":self.remote_vfs.root_path + "custom_" + self._createCRC(self.xbmc_vfs.root_path),"files":fileManager.getFiles()})


            #backup all the files
            self.filesLeft = self.filesTotal
            for fileGroup in allFiles:
                self.xbmc_vfs.set_root(fileGroup['source'])
                self.remote_vfs.set_root(fileGroup['dest'])
                filesCopied = self.backupFiles(fileGroup['files'],self.xbmc_vfs,self.remote_vfs)
                
                if(not filesCopied):
                    utils.showNotification(utils.getString(30092))
                    utils.log(utils.getString(30092))
            
            #reset remote and xbmc vfs
            self.xbmc_vfs.set_root("special://home/")
            self.remote_vfs.set_root(orig_base_path)

            if(utils.getSetting("compress_backups") == 'true'):
                #send the zip file to the real remote vfs
                zip_name = self.remote_vfs.root_path[:-1] + ".zip"
                self.remote_vfs.cleanup()
                self.xbmc_vfs.rename(xbmc.translatePath("special://temp/xbmc_backup_temp.zip"), xbmc.translatePath("special://temp/" + zip_name))
                fileManager.addFile(xbmc.translatePath("special://temp/" + zip_name))
               
                #set root to data dir home 
                self.xbmc_vfs.set_root(xbmc.translatePath("special://temp/"))
               
                self.remote_vfs = self.saved_remote_vfs
                self.progressBar.updateProgress(98, utils.getString(30088))
                fileCopied = self.backupFiles(fileManager.getFiles(),self.xbmc_vfs, self.remote_vfs)
                
                if(not fileCopied):
                    #zip archive copy filed, inform the user
                    shouldContinue = xbmcgui.Dialog().ok(utils.getString(30089),utils.getString(30090), utils.getString(30091))
                    
                #delete the temp zip file
                self.xbmc_vfs.rmfile(xbmc.translatePath("special://temp/" + zip_name))

            #remove old backups
            self._rotateBackups()

        elif (mode == self.Restore):
            utils.log(utils.getString(30023) + " - " + utils.getString(30017))

            #catch for if the restore point is actually a zip file
            if(self.restore_point.split('.')[-1] == 'zip'):
                self.progressBar.updateProgress(2, utils.getString(30088))
                utils.log("copying zip file: " + self.restore_point)
                
                #set root to data dir home 
                self.xbmc_vfs.set_root(xbmc.translatePath("special://temp/"))
                
                if(not self.xbmc_vfs.exists(xbmc.translatePath("special://temp/" + self.restore_point))):
                    #copy just this file from the remote vfs
                    zipFile = []
                    zipFile.append(self.remote_base_path + self.restore_point)
               
                    self.backupFiles(zipFile,self.remote_vfs, self.xbmc_vfs)
                else:
                    utils.log("zip file exists already")
                
                #extract the zip file
                zip_vfs = ZipFileSystem(xbmc.translatePath("special://temp/"+ self.restore_point),'r')
                extractor = ZipExtractor()
                
                if(not extractor.extract(zip_vfs, xbmc.translatePath("special://temp/"), self.progressBar)):
                    #we had a problem extracting the archive, delete everything
                    zip_vfs.cleanup()
                    self.xbmc_vfs.rmfile(xbmc.translatePath("special://temp/" + self.restore_point))
                    
                    xbmcgui.Dialog.ok(utils.getSetting(30010),utils.getString(30101))
                    return
                    
                zip_vfs.cleanup()
                
                self.progressBar.updateProgress(0,utils.getString(30049) + "......")
                #set the new remote vfs and fix xbmc path
                self.remote_vfs = XBMCFileSystem(xbmc.translatePath("special://temp/" + self.restore_point.split(".")[0] + "/"))
                self.xbmc_vfs.set_root(xbmc.translatePath("special://home/"))
            
            #for restores remote path must exist
            if(not self.remote_vfs.exists(self.remote_vfs.root_path)):
                xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30045),self.remote_vfs.root_path)
                return

            if(not self._checkValidationFile(self.remote_vfs.root_path)):
                #don't continue
                return

            utils.log(utils.getString(30051))
            allFiles = []
            fileManager = FileManager(self.remote_vfs)
         
            #go through each of the user selected items and write them to the backup store

            if(utils.getSetting("backup_config") == "true"):
                #check for the existance of an advancedsettings file
                if(self.remote_vfs.exists(self.remote_vfs.root_path + "userdata/advancedsettings.xml") and not self.skip_advanced):
                    #let the user know there is an advanced settings file present
                    restartXbmc = xbmcgui.Dialog().yesno(utils.getString(30038),utils.getString(30039),utils.getString(30040), utils.getString(30041))

                    if(restartXbmc):
                        #add only this file to the file list
                        fileManager.addFile(self.remote_vfs.root_path + "userdata/advancedsettings.xml")
                        self.backupFiles(fileManager.getFiles(),self.remote_vfs,self.xbmc_vfs)

                        #let the service know to resume this backup on startup
                        self._createResumeBackupFile()

                        #do not continue running
                        xbmcgui.Dialog().ok(utils.getString(30077),utils.getString(30078))
                        
                        return
                
                fileManager.addFile('-' + self.remote_vfs.root_path + 'userdata/keymaps')
                fileManager.walkTree(self.remote_vfs.root_path + "userdata/keymaps")
                
                fileManager.addFile('-' + self.remote_vfs.root_path + "userdata/peripheral_data")
                fileManager.walkTree(self.remote_vfs.root_path + "userdata/peripheral_data")
            
                fileManager.addFile('-' + self.remote_vfs.root_path + "userdata/library")
                fileManager.walkTree(self.remote_vfs.root_path + "userdata/library")
            
                #this part is an oddity
                dirs,configFiles = self.remote_vfs.listdir(self.remote_vfs.root_path + "userdata/")
                for aFile in configFiles:
                    if(aFile.endswith(".xml")):
                        fileManager.addFile(self.remote_vfs.root_path + "userdata/" + aFile)

            if(utils.getSetting('backup_addons') == 'true'):
                fileManager.addFile('-' + self.remote_vfs.root_path + "addons")
                fileManager.walkTree(self.remote_vfs.root_path + "addons")

            self.xbmc_vfs.mkdir(xbmc.translatePath('special://home/userdata'))

            if(utils.getSetting('backup_addon_data') == 'true'):
                fileManager.addFile('-' + self.remote_vfs.root_path + "userdata/addon_data")
                fileManager.walkTree(self.remote_vfs.root_path + "userdata/addon_data")

            if(utils.getSetting('backup_database') == 'true'):
                fileManager.addFile('-' + self.remote_vfs.root_path + "userdata/Database")
                fileManager.walkTree(self.remote_vfs.root_path + "userdata/Database")
        
            if(utils.getSetting("backup_playlists") == 'true'):
                fileManager.addFile('-' + self.remote_vfs.root_path + "userdata/playlists")
                fileManager.walkTree(self.remote_vfs.root_path + "userdata/playlists")

            if(utils.getSetting('backup_profiles') == 'true'):
                fileManager.addFile('-' + self.remote_vfs.root_path + "userdata/profiles")
                fileManager.walkTree(self.remote_vfs.root_path + "userdata/profiles")
                
            if(utils.getSetting("backup_thumbnails") == "true"):
                fileManager.addFile('-' + self.remote_vfs.root_path + "userdata/Thumbnails")
                fileManager.walkTree(self.remote_vfs.root_path + "userdata/Thumbnails")

            #add to array
            self.filesTotal = fileManager.size()
            allFiles.append({"source":self.remote_vfs.root_path,"dest":self.xbmc_vfs.root_path,"files":fileManager.getFiles()})    

            #check if there are custom directories
            if(utils.getSetting('custom_dir_1_enable') == 'true' and utils.getSetting('backup_custom_dir_1') != ''):

                self.xbmc_vfs.set_root(utils.getSetting('backup_custom_dir_1'))
                if(self.remote_vfs.exists(self.remote_vfs.root_path + "custom_" + self._createCRC(self.xbmc_vfs.root_path) + "/")):
                    #index files to restore
                    fileManager.walkTree(self.remote_vfs.root_path + "custom_" + self._createCRC(self.xbmc_vfs.root_path))
                    self.filesTotal = self.filesTotal + fileManager.size()
                    allFiles.append({"source":self.remote_vfs.root_path + "custom_" + self._createCRC(self.xbmc_vfs.root_path),"dest":self.xbmc_vfs.root_path,"files":fileManager.getFiles()})
                else:
                    utils.log("error path not found: " + self.remote_vfs.root_path + "custom_" + self._createCRC(self.xbmc_vfs.root_path))
                    xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30045),self.remote_vfs.root_path + "custom_" + self._createCRC(utils.getSetting('backup_custom_dir_1')))

            if(utils.getSetting('custom_dir_2_enable') == 'true' and utils.getSetting('backup_custom_dir_2') != ''):

                self.xbmc_vfs.set_root(utils.getSetting('backup_custom_dir_2'))
                if(self.remote_vfs.exists(self.remote_vfs.root_path + "custom_" + self._createCRC(self.xbmc_vfs.root_path) + "/")):
                    #index files to restore
                    fileManager.walkTree(self.remote_vfs.root_path + "custom_" + self._createCRC(self.xbmc_vfs.root_path))
                    self.filesTotal = self.filesTotal + fileManager.size()
                    allFiles.append({"source":self.remote_vfs.root_path + "custom_" + self._createCRC(self.xbmc_vfs.root_path),"dest":self.xbmc_vfs.root_path,"files":fileManager.getFiles()})
                else:
                    utils.log("error path not found: " + self.remote_vfs.root_path + "custom_" + self._createCRC(self.xbmc_vfs.root_path))
                    xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30045),self.remote_vfs.root_path + "custom_" + self._createCRC(utils.getSetting('backup_custom_dir_2')))


            #restore all the files
            self.filesLeft = self.filesTotal
            for fileGroup in allFiles:
                self.remote_vfs.set_root(fileGroup['source'])
                self.xbmc_vfs.set_root(fileGroup['dest'])
                self.backupFiles(fileGroup['files'],self.remote_vfs,self.xbmc_vfs)

            self.progressBar.updateProgress(99,"Clean up operations .....")

            if(self.restore_point.split('.')[-1] == 'zip'):
                #delete the zip file and the extracted directory
                self.xbmc_vfs.rmfile(xbmc.translatePath("special://temp/" + self.restore_point))
                self.xbmc_vfs.rmdir(self.remote_vfs.root_path)

            if(utils.getSetting("backup_config") == "true"):
                #update the guisettings information (or what we can from it)
                gui_settings = GuiSettingsManager('special://home/userdata/guisettings.xml')
                gui_settings.run()

            #call update addons to refresh everything
            xbmc.executebuiltin('UpdateLocalAddons')

        self.xbmc_vfs.cleanup()
        self.remote_vfs.cleanup()
        self.progressBar.close()

        #reset the window setting
        window.setProperty(utils.__addon_id__ + ".running","")
import scipy.sparse as sp
import time
from model.preprocessing import gen_train_edges, preprocess_graph, normalize_vectors, sparse_to_tuple, construct_feed_dict
from sklearn.manifold import TSNE
from finch import FINCH
from os.path import abspath, dirname, join
from utils import getSetting, PCAAnanlyse, clustering, pairwise_precision_recall_f1, lossPrint, tSNEAnanlyse, settings, sNEComparingAnanlyse
from utils.inputData import load_local_data
from sklearn.metrics import silhouette_score

from model import DualGCNGraphFusion, OptimizerDualGCNAutoEncoder

from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelEncoder

flags = getSetting()
FLAGS = flags.FLAGS
model_str = FLAGS.model
name_str = FLAGS.name


def AdjPreprocessing(adj):
    adj_orig = adj
    adj_orig = adj_orig - sp.dia_matrix(
        (adj_orig.diagonal()[np.newaxis, :], [0]), shape=adj_orig.shape)
    adj_orig.eliminate_zeros()
    adj_train = gen_train_edges(adj)
    return adj_train


def BuildModel(placeholders, input_feature_dim, num_nodes, name, num_logits):
Example #45
0
 def onSettingsChanged(self):
     if self._search_history and not getSetting("search_history", bool):
         _clearSearchHistory()
     self.setup()
Example #46
0
#       Copyright (C) 2013
#       Written on behalf of Flirc
#       by Sean Poyser ([email protected])
#

import utils

utils.log("Service Starting")

try:
    if utils.getSetting('autoStart') == 'true':
        utils.log("Initialising Automatic Programming Mode")

        import default
        default.main(utils.MINIMAL, True)

except Exception, e:
    utils.log("******************* ERROR IN SERVICE *******************")
    utils.log(e)
Example #47
0
#  http://www.gnu.org/copyleft/gpl.html
#

import xbmc
import xbmcgui
import xbmcaddon
import os
import re

import utils as utils

ADDONID = 'script.tvportal.epg'
ADDON = xbmcaddon.Addon(ADDONID)
PROFILE = ADDON.getAddonInfo('profile')
PATH = xbmc.translatePath(os.path.join(PROFILE, 'cats.xml'))
SKIN = utils.getSetting('SKIN')

datapath = utils.PROFILE
skinfolder = os.path.join(datapath, 'skins')
skinpath = os.path.join(skinfolder, SKIN)
xml_file = os.path.join('categories.xml')

if os.path.join(SKIN, 'skins', 'Default', '720p', xml_file):
    XML = xml_file

ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10

KEY_NAV_BACK = 92

Example #48
0
 def video(self, **kwargs):
     args = client.video(local=getSetting("proxy", bool), **kwargs)
     return self.play(*args) if args else False
 def enabled(self):
     try:
         optional = self["optional"]
     except KeyError:
         optional = False
     return getSetting(self.type, bool) if optional else True
Example #50
0
# -*- coding: utf-8 -*-

import utils

import smotreshka

import mainform

if __name__ == '__main__':

    login = utils.getSetting("login")
    password = utils.getSetting("password")
    if (not login) or (not password):
        utils.showMessage("не заданы параметры подключения к сервису")
    else:
        sm = smotreshka.Smotreshka(login, password, utils.DATA_PATH)
        if not sm.check():
            utils.showMessage(
                "не удается подключиться к сервису, проверьте логин и пароль")
        else:
            utils.showMessage("запускаем приложение")
            w = mainform.WMainForm("mainform.xml", utils.ADDON_PATH, "flinty")
            w.smApi = sm
            w.doModal()
            del w
Example #51
0
def doChangelogDisplay():
    if getSetting('currAddonVersion') != getAddonVersion():
        updateSavedAddonVersion()
        xbmcgui.Dialog().textviewer('Hyperion Control - Changelog', getAddonChangelog())