def addSeriesToLibrary(seriesID, seriesTitle, season, singleUpdate=True):
    seriesFolderName = (''.join(c for c in unicode(seriesTitle, 'utf-8') if c not in '/\\:?"*|<>')).strip(' .')
    seriesDir = os.path.join(libraryFolderTV, seriesFolderName)
    if not os.path.isdir(seriesDir):
        xbmcvfs.mkdir(seriesDir)
    content = getSeriesInfo(seriesID)
    content = json.loads(content)
    for test in content["episodes"]:
        for item in test:
            episodeSeason = str(item["season"])
            seasonCheck = True
            if season:
                seasonCheck = episodeSeason == season
            if seasonCheck:
                seasonDir = os.path.join(seriesDir, "Season "+episodeSeason)
                if not os.path.isdir(seasonDir):
                    xbmcvfs.mkdir(seasonDir)
                episodeID = str(item["episodeId"])
                episodeNr = str(item["episode"])
                episodeTitle = item["title"].encode('utf-8')
                if len(episodeNr) == 1:
                    episodeNr = "0"+episodeNr
                seasonNr = episodeSeason
                if len(seasonNr) == 1:
                    seasonNr = "0"+seasonNr
                filename = "S"+seasonNr+"E"+episodeNr+" - "+episodeTitle+".strm"
                filename = (''.join(c for c in unicode(filename, 'utf-8') if c not in '/\\:?"*|<>')).strip(' .')
                fh = xbmcvfs.File(os.path.join(seasonDir, filename), 'w')
                fh.write("plugin://plugin.video.netflixbmc/?mode=playVideo&url="+episodeID)
                fh.close()
    if updateDB and singleUpdate:
        xbmc.executebuiltin('UpdateLibrary(video)')
def write_xml(elem, dir='', output='', type=''):
    if output == '':
        output = dev.typeXml(type)
    dev.log('write_xml('+type+','+output+').')
    
    
    xbmcvfs.mkdir(vars.settingsPath) #Create the settings dir if it does not exist already
    if dir is not '': xbmcvfs.mkdir(vars.settingsPath+dir) #Create the settings dir if it does not exist already
    #Write these settings to a .xml file in the addonfolder
    output_file = os.path.join(vars.settingsPath+dir, output) #Set the outputfile to settings.xml
    
    #Creating a backup of the .xml file (in case it gets corrupted)
    backupfile = os.path.join(vars.settingsPath+dir, output+'.backup')
    if xbmcvfs.exists(output_file):
        if xbmcvfs.copy(output_file, backupfile):
            dev.log('Created a backup of the xml file at: '+backupfile)
        else:
            dev.log('Failed to create a backup of the xml file at: '+backupfile)
    else:
        dev.log(output_file+' could not be found, so not able to create a backup')
    
    
    indent( elem ) #Prettify the xml so its not on one line
    tree = ElementTree.ElementTree( elem ) #Convert the xml back to an element
    tree.write(output_file) #Save the XML in the settings file
    
    #For backup purposes, check if the xml got corrupted by writing just now
    if xml_get(type) is False:
        dev.log('corrupt .xml file')
Пример #3
0
    def traverse(self, path, cacheType, folderID, savePublic, level):
        import os
        import xbmcvfs

        xbmcvfs.mkdir(path)

        folders = self.getFolderList(folderID)
        files = self.getMediaList(folderID,cacheType)

        if files:
            for media in files:
                filename = xbmc.translatePath(os.path.join(path, media.title+'.strm'))
                strmFile = open(filename, "w")

                strmFile.write(self.PLUGIN_URL+'?mode=streamURL&url=' + self.FILE_URL+ media.id +'\n')
                strmFile.close()

        if folders and level == 1:
            count = 1
            progress = xbmcgui.DialogProgress()
            progress.create(self.addon.getLocalizedString(30000),self.addon.getLocalizedString(30036),'\n','\n')

            for folder in folders:
                max = len(folders)
                progress.update(count/max*100,self.addon.getLocalizedString(30036),folder.title,'\n')
                self.traverse( path+'/'+folder.title + '/',cacheType,folder.id,savePublic,0)
                count = count + 1

        if folders and level == 0:
            for folder in folders:
                self.traverse( path+'/'+folder.title + '/',cacheType,folder.id,savePublic,0)
Пример #4
0
 def container_data(self):
     if not xbmcvfs.exists(dataPath):
         xbmcvfs.mkdir(dataPath)
     if not xbmcvfs.exists(viewData):
         file = xbmcvfs.File(viewData, 'w')
         file.write('')
         file.close()
def restoreColorTheme():
    import shutil
    import zipfile
    zip_path = None
    userThemesPath = os.path.join(userThemesDir,"themes") + os.sep
    zip_path = get_browse_dialog(dlg_type=1,heading=ADDON.getLocalizedString(32020),mask=".zip")
    if zip_path and zip_path != "protocol://":
        #create temp path
        temp_path = xbmc.translatePath('special://temp/skinbackup/').decode("utf-8")
        if xbmcvfs.exists(temp_path):
            shutil.rmtree(temp_path)
        xbmcvfs.mkdir(temp_path)
        
        #unzip to temp
        if "\\" in zip_path:
            delim = "\\"
        else:
            delim = "/"
        
        zip_temp = xbmc.translatePath('special://temp/' + zip_path.split(delim)[-1]).decode("utf-8")
        xbmcvfs.copy(zip_path,zip_temp)
        zfile = zipfile.ZipFile(zip_temp)
        zfile.extractall(temp_path)
        zfile.close()
        xbmcvfs.delete(zip_temp)
        
        dirs, files = xbmcvfs.listdir(temp_path)
        for file in files:
            if file.endswith(".theme") or file.endswith(".jpg"):
                sourcefile = os.path.join(temp_path,file)
                destfile = os.path.join(userThemesPath,file)
                xbmcvfs.copy(sourcefile,destfile)
        xbmcgui.Dialog().ok(ADDON.getLocalizedString(32022), ADDON.getLocalizedString(32021))
Пример #6
0
def check_login():
    if not xbmcvfs.exists(addon_profile):
        xbmcvfs.mkdir(addon_profile)

    if username and password:
        if not xbmcvfs.exists(cookie_file):
            return gamepass_login()
        else:
            cookie_jar.load(cookie_file, ignore_discard=True, ignore_expires=True)
            cookies = {}
            for i in cookie_jar:
                cookies[i.name] = i.value
            login_ok = False
            if cookies.has_key("userId"):
                already_logged_in = check_for_subscription()

                if already_logged_in:
                    addon_log("Already logged in")
                    return True
                else:
                    addon_log("Not yet logged in")
                    return gamepass_login()
            else:
                return gamepass_login()
    elif subscription == "0":
        if addon.getSetting("sans_login") == "true":
            return True
    else:
        dialog = xbmcgui.Dialog()
        dialog.ok("Account Info Not Set", "Please set your Game Pass username and password", "in Add-on Settings.")
        addon_log("No account settings detected.")
        return False
Пример #7
0
def list_favourites():
    if not os.path.exists(datapath):
        xbmcvfs.mkdir(datapath)
    if not os.path.exists(programafav):
        xbmcvfs.mkdir(programafav)
    dirs, files = xbmcvfs.listdir(programafav)
    if files:
        totalit = len(files)
        for fich in files:
            text = readfile(os.path.join(programafav, fich))
            data = text.split("|")
            try:
                information = {"Title": data[0], "plot": data[3]}
                if "arquivo/" not in data[1]:
                    mode = 16
                else:
                    mode = 11
                addprograma(data[0], data[1], mode, data[2], totalit, information)
            except:
                pass
        xbmcplugin.setContent(int(sys.argv[1]), "tvshows")
        setview("show-view")
    else:
        msgok(translate(30001), translate(30024))
        sys.exit(0)
Пример #8
0
def download(name, url):
            my_addon = xbmcaddon.Addon()
            desty= my_addon.getSetting('downloads_folder')
            if not xbmcvfs.exists(desty):
                xbmcvfs.mkdir(desty)

            title=name
            name=re.sub('[^-a-zA-Z0-9_.() ]+', '', name)
            name=name.rstrip('.')
            ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:]
            if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg', 'mp3']: ext = 'mp4'
            filename = name + '.' + ext
      
            

            dest = os.path.join(desty, filename)
            new=my_addon.getSetting('new_downloader')
            if  new=='false':
                from lib.modules import commondownloader
                commondownloader.download(url, dest, 'Croatia On Demand')
            else:
                content = int(urllib.urlopen(url).info()['Content-Length'])
                size = 1024 * 1024
                mb   = content / (1024 * 1024)
                if xbmcgui.Dialog().yesno('Croatia On Demand - Potvrda preuzimanja', filename, 'Veličina datoteke je %dMB' % mb, 'Nastaviti s preuzimanjem?', 'Nastavi',  'Prekini') == 1:
                  return
                import SimpleDownloader as downloader
                downloader = downloader.SimpleDownloader()
                params = { "url": url, "download_path": desty, "Title": title }
                downloader.download(filename, params)
Пример #9
0
def _get_connection():
    import xbmcvfs, os, xbmc, xbmcaddon
    dataPath = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('profile')).decode('utf-8')
    xbmcvfs.mkdir(dataPath)
    conn = db.connect(os.path.join(dataPath, 'cache.db'))
    conn.row_factory = _dict_factory
    return conn
Пример #10
0
def installPy7ForAndroid():
    if not os.path.exists(pastaperfil): xbmcvfs.mkdir(pastaperfil)
    #Hack to get xbmc app id
    xbmcfolder=xbmc.translatePath(addonpath).split("/")
    found = False
    if 1==1:#settings.getSetting('auto_appid') == 'true':
        i = 0
        for folder in xbmcfolder:
            if folder.count('.') >= 2 and folder != addon_id :
                found = True
                break
            else:
                i+=1
        if found == True:
            uid = os.getuid()
            app_id = xbmcfolder[i]
    else:
        if settings.getSetting('custom_appid') != '':
            uid = os.getuid()
            app_id = settings.getSetting('custom_appid')
            found = True

    if found == True:
        settings.setSetting('app_id',app_id)
        if "arm" in os.uname()[4]:
            python7bundle = os.path.join(pastaperfil,python7_apk_arm.split("/")[-1])
            download_tools().Downloader(python7_apk_arm,python7bundle,"downloading python7 for Android Arm","pycrypto")
        else:
            python7bundle = os.path.join(pastaperfil,python7_apk_x86.split("/")[-1])
            download_tools().Downloader(python7_apk_x86,python7bundle,"downloading python7 for Android x86","pycrypto")
        if tarfile.is_tarfile(python7bundle):
            download_tools().extract(python7bundle,pastaperfil)
            download_tools().remove(python7bundle)
        python7folder = os.path.join(pastaperfil,"python7")
        xbmc_data_path = os.path.join("/data", "data", app_id)
        if os.path.exists(xbmc_data_path) and uid == os.stat(xbmc_data_path).st_uid:
            android_binary_dir = os.path.join(xbmc_data_path, "files", app_id)
            if not os.path.exists(android_binary_dir): os.makedirs(android_binary_dir)
                android_exec_folder = os.path.join(android_binary_dir,"python7")
                if not os.path.exists(android_exec_folder): os.makedirs(android_exec_folder)
                else:
                    #clean install for android - delete old folder
                    print android_exec_folder
                    try:
                        os.system("chmod -R 777 "+android_exec_folder+"/*")
                        os.system("rm -r '"+android_exec_folder+"'")
                    except: pass
                    try: os.makedirs(android_exec_folder)
                    except: pass
                xbmc.sleep(200)
        recursive_overwrite(python7folder, android_exec_folder, ignore=None)
        pythonbin = os.path.join(android_exec_folder,"python","bin","python")
        st = os.stat(pythonbin)
        import stat
        os.chmod(pythonbin, st.st_mode | stat.S_IEXEC)
        if os.path.exists(python7folder):
        try:
            os.system("chmod -R 777 "+python7folder+"/*")
            os.system("rm -r '"+python7folder+"'")
        except: pass                
Пример #11
0
def addBiblioteca(nome, url, tipo, temporada=False, episodio=False):
    updatelibrary = True

    if tipo == "filme":
        if not xbmcvfs.exists(pastaFilmes):
            xbmcvfs.mkdir(pastaFilmes)
    elif tipo == "serie":
        if not xbmcvfs.exists(pastaSeries):
            xbmcvfs.mkdir(pastaSeries)

    if type == "filme":
        try:
            file_folder = os.path.join(pastaFilmes, nome)
        except:
            pass
    elif type == "serie":
        file_folder1 = os.path.join(pastaSeries, nome)
        if not xbmcvfs.exists(file_folder1):
            tryFTPfolder(file_folder1)
        file_folder = os.path.join(pastaSeries, nome + "/", "S" + temporada)
        title = nome + " S" + temporada + "E" + episodio

    strm_contents = "plugin://plugin.video.tugaio/?url=" + url + "&mode=3&name=" + urllib.quote_plus(nome)
    savefile(urllib.quote_plus(title) + ".strm", strm_contents, file_folder)
    if updatelibrary:
        xbmc.executebuiltin("XBMC.UpdateLibrary(video)")
    return True
Пример #12
0
    def buildSTRM(self, path, folderID=''):

        import xbmcvfs
        xbmcvfs.mkdir(path)

        mediaItems = self.getMediaList(folderID,0)

        if mediaItems:
            for item in mediaItems:

                url = 0
                try:
                    if item.file == 0:
                        self.buildSTRM(path + '/'+item.folder.title, item.folder.id)
                    else:
                        url = PLUGIN_URL+'?mode=video&title='+item.file.title+'&filename='+item.file.id
                except:
                    url = PLUGIN_URL+'?mode=video&title='+item.file.title+'&filename='+item.file.id


                if url != 0:
                    if not os.path.exists(path + item.file.title+'.strm'):
                        filename = xbmc.translatePath(os.path.join(path, item.file.title+'.strm'))
                        strmFile = open(filename, "w")

                        strmFile.write(url+'\n')
                        strmFile.close()
Пример #13
0
    def setThumbnail(self, service, url=''):
        if self.cachePath == '':
            cachePath = service.settings.cachePath
        else:
            cachePath = self.cachePath

        if cachePath == '':
            cachePath = xbmcgui.Dialog().browse(0,service.addon.getLocalizedString(30136), 'files','',False,False,'')
            service.addon.setSetting('cache_folder', cachePath)
            self.cachePath = cachePath

        if url == '':
            url = self.package.file.thumbnail

        #simply no thumbnail
        if url == '':
            return ""

        cachePath = str(cachePath) + str(self.package.file.id) + '/'
        if not xbmcvfs.exists(cachePath):
            xbmcvfs.mkdir(cachePath)
        if not xbmcvfs.exists(cachePath + str(self.package.file.id) + '.jpg'):
            service.downloadPicture(url, cachePath + str(self.package.file.id) + '.jpg')
            print url
        return cachePath + str(self.package.file.id) + '.jpg'
Пример #14
0
def start():
    # Set a window property that let's other scripts know we are running (window properties are cleared on kodi start)
    xbmcgui.Window(10000).setProperty(__addonid__ + '_running', 'True')

    # Try to get any system arguments
    try:
        if ( sys.argv[1] == 'true' ):
            resume = True
        else: resume = False
    except: resume = None
    try:
        if ( sys.argv[2] == 'true' ):
            monitor = True
        else: monitor = False
    except: monitor = None
    
    
    # If resume argument not supplied and we are not on home window 
    #     - assume we are enabling the addon and therefore don't want it to resume
    if ( resume == None and xbmcgui.getCurrentWindowId() != 10000 ):
        resume = False
            
    # If script data directory doesn't exist - create it and assume the script is starting for the first time
    if ( not xbmcvfs.exists(__profile_dir__) ):
        xbmcvfs.mkdir(__profile_dir__)
        firstRun = True
    else: firstRun = False

    # Create and start the main service - passing it any system arguments and first run status
    m = xr_service.Service()
    m.start(resume, monitor, firstRun)
    del m
    
    # Script finishing so clear the window running property
    xbmcgui.Window(10000).clearProperty(__addonid__ + '_running')
Пример #15
0
def series(series_id, series_title, season, single_update=True):
    filename = utility.clean_filename(series_title, ' .')
    series_file = xbmc.translatePath(utility.tv_dir() + filename)
    if not xbmcvfs.exists(series_file):
        xbmcvfs.mkdir(series_file)
    content = get.series_info(series_id)
    content = json.loads(content)['video']['seasons']
    for test in content:
        episode_season = unicode(test['seq'])
        if episode_season == season or season == '':
            season_dir = utility.create_pathname(series_file, test['title'])
            if not xbmcvfs.exists(season_dir):
                xbmcvfs.mkdir(season_dir)
            for item in test['episodes']:
                episode_id = unicode(item['episodeId'])
                episode_nr = unicode(item['seq'])
                episode_title = item['title']
                if len(episode_nr) == 1:
                    episode_nr = '0' + episode_nr
                season_nr = episode_season
                if len(season_nr) == 1:
                    season_nr = '0' + season_nr
                filename = 'S' + season_nr + 'E' + episode_nr + ' - ' + episode_title + '.strm'
                filename = utility.clean_filename(filename, ' .')
                file_handler = xbmcvfs.File(utility.create_pathname(season_dir, filename), 'w')
                file_handler.write(
                    utility.encode('plugin://%s/?mode=play_video&url=%s' % (utility.addon_id, episode_id)))
                file_handler.close()
    if utility.get_setting('update_db') and single_update:
        xbmc.executebuiltin('UpdateLibrary(video)')
Пример #16
0
def get_temp_merged():
    datapath = xbmc.translatePath('special://temp')
    temp = os.path.join(datapath,'temp')
    if not xbmcvfs.exists(temp):
        xbmcvfs.mkdir(temp)
    temp_merged = os.path.join(temp, 'merged_epg.xml.gz')
    return temp_merged
Пример #17
0
def makeM3U(links):
    log("makeM3U")
    STRM_CACHE_LOC = xbmc.translatePath(get_setting("write_folder"))
    if not xbmcvfs.exists(STRM_CACHE_LOC):
        xbmcvfs.mkdir(STRM_CACHE_LOC)
    flepath = os.path.join(STRM_CACHE_LOC, "ustvnow.m3u")
    if xbmcvfs.exists(flepath):
        xbmcvfs.delete(flepath)
    playlist = open(flepath, "w")
    # Extended M3U format used here
    playlist.write("#EXTM3U" + "\n")
    if links:
        for l in links:
            # Add name based filename
            if int(get_setting("write_type")) == 3:
                playlist.write(
                    '#EXTINF:-1, tvg-id="'
                    + l["name"]
                    + '" tvg-logo="'
                    + l["name"]
                    + '" tvg-name="'
                    + l["name"]
                    + '"  group-title="USTVnow",'
                    + l["name"]
                    + "\n"
                )
            else:
                playlist.write("#EXTINF:" + l["name"] + "\n")
            # Write relative location of file
            playlist.write(l["url"] + "\n")
    playlist.close()
 def download(self , theme_url , path):
     log( "### download :" + theme_url )
     tmpdestination = xbmc.translatePath( 'special://profile/addon_data/%s/temp/%s' % ( __addonid__ , self.theme_file ) )
     destination = os.path.join( path , self.theme_file )
     try:
         def _report_hook( count, blocksize, totalsize ):
             percent = int( float( count * blocksize * 100 ) / totalsize )
             strProgressBar = str( percent )
             self.DIALOG_PROGRESS.update( percent , str(__language__(32110)) + ' ' + theme_url , str(__language__(32111)) + ' ' + destination )
         if not xbmcvfs.exists(path):
             try:
                 xbmcvfs.mkdir(path)
             except:
                 log( "problem with path: %s" % destination )
         fp , h = urllib.urlretrieve( theme_url , tmpdestination , _report_hook )
         log( h )
         copy = xbmcvfs.copy(tmpdestination, destination)
         if copy:
             log( "### copy successful" )
         else:
             log( "### copy failed" )
         xbmcvfs.delete(tmpdestination)
         return True
     except :
         log( "### Theme download Failed !!!" )
         print_exc()
         return False 
Пример #19
0
def addMovieToLibrary(title, year , url, imdbid):
    
    # get movie folder location
    # 
    # os.path.join is for translating between different OS path structure
    # xbmc.translatePath() is used for translating "speciall://sample" path to full path for writing to disk
    # xbmcaddon.Addon().getSetting('id') is for reading movie libray info from setting
    library_folder = os.path.join(xbmc.translatePath(xbmcaddon.Addon().getSetting('movie_library')))
    
    # make movie directory if not already created
    xbmcvfs.mkdir(library_folder)
    
    movie_folder_name = title +" (" + year + ")"
    
    # make movie folder
    folder = os.path.join(library_folder, movie_folder_name )
    xbmcvfs.mkdir(folder)
    
    # movie file name
    movie_file_name = movie_folder_name + ".strm"
    
    # get the path to the file
    movie_file = os.path.join(folder, movie_file_name)
    
    file = xbmcvfs.File(movie_file, 'w')
    
    content = '%s?action=playStream&imdbid=%s&title=%s&year=%s&video=%s' % (__url__, imdbid, urllib.quote_plus(title), year, url)
    
    file.write(str(content))
    
    file.close()
    
    dialog = xbmcgui.Dialog()
    dialog.notification('Movie Added to library', title + " was added to library", xbmcgui.NOTIFICATION_INFO, 5000)
Пример #20
0
def stopProfiling(pr, profileName):
    
    pr.disable()
    ps = pstats.Stats(pr)
    
    profiles = xbmc.translatePath("%sprofiles/"
                % xbmcaddon.Addon().getAddonInfo('profile')).decode('utf-8')

    if not xbmcvfs.exists(profiles):
        # Create the profiles folder
        xbmcvfs.mkdir(profiles)

    timestamp = time.strftime("%Y-%m-%d %H-%M-%S")
    profile = "%s%s_profile_(%s).tab" % (profiles, profileName, timestamp)
    
    f = xbmcvfs.File(profile, 'w')
    f.write("NumbCalls\tTotalTime\tCumulativeTime\tFunctionName\tFileName\r\n")
    for (key, value) in ps.stats.items():
        (filename, count, func_name) = key
        (ccalls, ncalls, total_time, cumulative_time, callers) = value
        try:
            f.write(
                "%s\t%s\t%s\t%s\t%s\r\n"
                % (ncalls, "{:10.4f}".format(total_time),
                    "{:10.4f}".format(cumulative_time), func_name, filename))
        except ValueError:
            f.write(
                "%s\t%s\t%s\t%s\t%s\r\n"
                % (ncalls, "{0}".format(total_time),
                    "{0}".format(cumulative_time), func_name, filename))
    f.close()
Пример #21
0
def write_strm(name, fold, videoid, show=None, season=None, episode=None, startpoint = None, endpoint = None, artist='', album='', song='', year='', type=''):
    #dev.log('strm('+name+', '+fold+', '+videoid+')')
    movieLibrary = vars.tv_folder #The path we should save in is the vars.tv_folder setting from the addon settings
    if type=='musicvideo':
        movieLibrary = vars.musicvideo_folder
    sysname = urllib.quote_plus(videoid) #Escape strings in the videoid if needed
    enc_name = dev.legal_filename(name) #Encode the filename to a legal filename
    
    if vars.__settings__.getSetting("strm_link") == "Youtube Library":
        if type == 'musicvideo':
            content = 'plugin://plugin.video.youtubelibrary/?mode=playmusicvideo'
            if startpoint != None:
                content += '&startpoint='+startpoint
            if endpoint != None:
                content += '&endpoint='+endpoint
            content += '&id=%s&artist=%s&song=%s&album=%s&year=%s&filename=%s' % (sysname, artist, song, album, year, enc_name) #Set the content of the strm file with a link back to this addon for playing the video 
        else:
            content = 'plugin://plugin.video.youtubelibrary/?mode=play&id=%s&show=%s&season=%s&episode=%s&filename=%s' % (sysname, show, season, episode, enc_name) #Set the content of the strm file with a link back to this addon for playing the video
    else:
        content = vars.KODI_ADDONLINK+'%s' % ( sysname) #Set the content of the strm file with a link to the official Kodi Youtube Addon

    xbmcvfs.mkdir(movieLibrary) #Create the maindirectory if it does not exists yet
    
    folder = os.path.join(movieLibrary, fold) #Set the folder to the maindir/dir
    xbmcvfs.mkdir(folder) #Create this subfolder if it does not exist yet

    stream = os.path.join(folder, enc_name + '.strm') #Set the file to maindir/name/name.strm
    file = xbmcvfs.File(stream, 'w') #Open / create this file for writing
    file.write(str(content.encode('UTF-8'))) #Write the content in the file
    file.close() #Close the file
    dev.log('write_strm: Written strm file: '+fold+'/'+enc_name+'.strm')
    return enc_name
Пример #22
0
    def get_libtorrent_download_dir(cls, ensure_exists=False):
        dir_path = os.path.join(cls.get_libtorrent_working_dir(ensure_exists), 'data')
        if ensure_exists and not xbmcvfs.exists(dir_path):
            logger.notice(u'Creating path: %s' % dir_path)
            xbmcvfs.mkdir(dir_path)

        return dir_path
Пример #23
0
	def __init__(self):
		self.folder = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('profile')).decode("utf-8")
		if not xbmcvfs.exists(self.folder):
			xbmcvfs.mkdir(self.folder)
		self.file_path = self.folder + "shared_data.json"
		with open(self.file_path, "w") as file:
			file.write("{}")
Пример #24
0
	def __handleCompressedFile(self, gui, filext, rom, emuParams):

		log.info("__handleCompressedFile")

		# Note: Trying to delete temporary files (from zip or 7z extraction) from last run
		# Do this before launching a new game. Otherwise game could be deleted before launch
		tempDir = os.path.join(util.getTempDir(), 'extracted', self.romCollection.name)
		# check if folder exists
		if not xbmcvfs.exists(tempDir +'\\'):
			log.info("Create temporary folder: " +tempDir)
			xbmcvfs.mkdir(tempDir)

		try:
			if xbmcvfs.exists(tempDir +'\\'):
				log.info("Trying to delete temporary rom files")
				#can't use xbmcvfs.listdir here as it seems to cache the file list and RetroPlayer won't find newly created files anymore
				files = os.listdir(tempDir)
				for f in files:
					#RetroPlayer places savestate files next to the roms. Don't delete these files.
					fname, ext = os.path.splitext(f)
					if(ext not in ('.sav', '.xml', '.png')):
						xbmcvfs.delete(os.path.join(tempDir, f))
		except Exception, (exc):
			log.error("Error deleting files after launch emu: " + str(exc))
			gui.writeMsg(util.localize(32036) + ": " + str(exc))
def addToLibrary(url):
    if mysettings.getSetting("cust_Lib_path") == "true":
        newlibraryFolderMovies = custLibFolder
    else:
        newlibraryFolderMovies = libraryFolderMovies
    movieFolderName = ("".join(c for c in unicode(gname, "utf-8") if c not in '/\\:?"*|<>')).strip(" .")
    newMovieFolderName = ""
    finalName = ""
    keyb = xbmc.Keyboard(name, "[COLOR ffffd700]Enter Title[/COLOR]")
    keyb.doModal()
    if keyb.isConfirmed():
        newMovieFolderName = keyb.getText()
    if newMovieFolderName != "":
        dir = os.path.join(newlibraryFolderMovies, newMovieFolderName)
        finalName = newMovieFolderName
    else:
        dir = os.path.join(newlibraryFolderMovies, movieFolderName)
        finalName = movieFolderName

    if not os.path.isdir(dir):
        xbmcvfs.mkdir(dir)
        fh = xbmcvfs.File(os.path.join(dir, finalName + ".strm"), "w")
        fh.write(
            "plugin://" + addonID + "/?mode=3&url=" + urllib.quote_plus(url) + "&name=" + urllib.quote_plus(finalName)
        )
        fh.close()
Пример #26
0
    def _moveToThemeFolder(self, directory):
        log("moveToThemeFolder: path = %s" % directory)

        # Handle the case where we have a disk image
        if (os_path_split(directory)[1] == 'VIDEO_TS') or (os_path_split(directory)[1] == 'BDMV'):
            directory = os_path_split(directory)[0]

        dirs, files = list_dir(directory)
        for aFile in files:
            m = re.search(Settings.getThemeFileRegEx(directory), aFile, re.IGNORECASE)
            if m:
                srcpath = os_path_join(directory, aFile)
                log("fetchAllMissingThemes: Found match: %s" % srcpath)
                targetpath = os_path_join(directory, Settings.getThemeDirectory())
                # Make sure the theme directory exists
                if not dir_exists(targetpath):
                    try:
                        xbmcvfs.mkdir(targetpath)
                    except:
                        log("fetchAllMissingThemes: Failed to create directory: %s" % targetpath, True, xbmc.LOGERROR)
                        break
                else:
                    log("moveToThemeFolder: directory already exists %s" % targetpath)
                # Add the filename to the path
                targetpath = os_path_join(targetpath, aFile)
                if not xbmcvfs.rename(srcpath, targetpath):
                    log("moveToThemeFolder: Failed to move file from %s to %s" % (srcpath, targetpath))
Пример #27
0
def add_to_addon_favourites(name,url,iconimage):
	name = name.replace("[b]","").replace("[/b]","").replace("[color orange]","").replace("[/color]","").replace("[B]","").replace("[/B]","")
	if "runplugin" in url:
		match = re.compile("url=(.+?)&mode=(.+?)&").findall(url.replace(";",""))
		for url,mode in match:
			favourite_text = str(name) + " (" + str(url) + ")|" + str(mode) + "|" + str(url) + '|' + str(iconimage)
			favouritetxt = os.path.join(pastaperfil,"Favourites",url.replace(":","").replace("/","") + ".txt")
			if not xbmcvfs.exists(os.path.join(pastaperfil,"Favourites")): xbmcvfs.mkdir(os.path.join(pastaperfil,"Favourites"))
			save(favouritetxt, favourite_text)
			xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000), translate(40148), 1,addonpath+"/icon.png"))
	else:
		if "sop://" in url:
			tipo = "sopcast"
			if not iconimage: iconimage = os.path.join(addonpath,'resources','art','sopcast_logo.jpg')
		elif "acestream://" in url:
			tipo = "acestream"
			if not iconimage: iconimage = os.path.join(addonpath,'resources','art','acelogofull.jpg')
		elif ".torrent" in url:
			tipo = "acestream"
			if not iconimage: iconimage = os.path.join(addonpath,'resources','art','acelogofull.jpg')
		elif ".acelive" in url:
			tipo = "acestream"
			if not iconimage: iconimage = os.path.join(addonpath,'resources','art','acelogofull.jpg')		
		else:
			if len(url) < 30: tipo = "sopcast"
			else: tipo = "acestream"
		if tipo == "sopcast":
			favourite_text = str(name) + " (" + str(url) + ")|" + str(2) + "|" + str(url) + '|' + str(iconimage)
		elif tipo == "acestream":
			favourite_text = str(name) + " (" + str(url) + ")|" + str(1) + "|" + str(url) + '|' + str(iconimage) 
		favouritetxt = os.path.join(pastaperfil,"Favourites",url.replace(":","").replace("/","") + ".txt")
		if not xbmcvfs.exists(os.path.join(pastaperfil,"Favourites")): xbmcvfs.mkdir(os.path.join(pastaperfil,"Favourites"))
		save(favouritetxt, favourite_text)
		xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000), translate(40148), 1,addonpath+"/icon.png"))
		xbmc.executebuiltin("Container.Refresh")
Пример #28
0
def blur(input_img, radius=25):
    if not input_img:
        return {}
    if not xbmcvfs.exists(IMAGE_PATH):
        xbmcvfs.mkdir(IMAGE_PATH)
    input_img = utils.translate_path(urllib.unquote(input_img.encode("utf-8")))
    input_img = input_img.replace("image://", "").rstrip("/")
    cachedthumb = xbmc.getCacheThumbName(input_img)
    filename = "%s-radius_%i.png" % (cachedthumb, radius)
    targetfile = os.path.join(IMAGE_PATH, filename)
    vid_cache_file = os.path.join("special://profile/Thumbnails/Video", cachedthumb[0], cachedthumb)
    cache_file = os.path.join("special://profile/Thumbnails", cachedthumb[0], cachedthumb[:-4] + ".jpg")
    if xbmcvfs.exists(targetfile):
        img = PIL.Image.open(targetfile)
        return {"ImageFilter": targetfile,
                "ImageColor": get_colors(img)}
    try:
        if xbmcvfs.exists(cache_file):
            utils.log("image already in xbmc cache: " + cache_file)
            img = PIL.Image.open(utils.translate_path(cache_file))
        elif xbmcvfs.exists(vid_cache_file):
            utils.log("image already in xbmc video cache: " + vid_cache_file)
            img = PIL.Image.open(utils.translate_path(vid_cache_file))
        else:
            xbmcvfs.copy(input_img, targetfile)
            img = PIL.Image.open(targetfile)
        img.thumbnail((200, 200), PIL.Image.ANTIALIAS)
        imgfilter = MyGaussianBlur(radius=radius)
        img = img.convert('RGB').filter(imgfilter)
        img.save(targetfile)
    except Exception:
        utils.log("Could not get image for %s" % input_img)
        return {}
    return {"ImageFilter": targetfile,
            "ImageColor": get_colors(img)}
Пример #29
0
def check_login():
    if not xbmcvfs.exists(addon_profile):
        xbmcvfs.mkdir(addon_profile)

    if addon.getSetting('sans_login') == 'true':
        data = make_request('https://gamepass.nfl.com/nflgp/secure/schedule')
        return cache_seasons_and_weeks(data)

    elif username and password:
        if not xbmcvfs.exists(cookie_file):
            return gamepass_login()
        else:
            cookie_jar.load(cookie_file, ignore_discard=True, ignore_expires=True)
            cookies = {}
            for i in cookie_jar:
                cookies[i.name] = i.value
            login_ok = False
            if cookies.has_key('userId'):
                data = make_request('https://gamepass.nfl.com/nflgp/secure/myaccount')
                try:
                    login_ok = re.findall('Update Account Information / Change Password', data)[0]
                except IndexError:
                    addon_log('Not Logged In')
                if not login_ok:
                    return gamepass_login()
                else:
                    addon_log('Logged In')
                    data = make_request('https://gamepass.nfl.com/nflgp/secure/schedule')
                    return cache_seasons_and_weeks(data)
            else:
                return gamepass_login()
    else:
        dialog = xbmcgui.Dialog()
        dialog.ok("Account Info Not Set", "Please set your Game Pass username and password", "in Add-on Settings.")
        addon_log('No account settings detected.')
Пример #30
0
    def _readHosts(self):
        data_dir = utils.data_dir()

        if(not xbmcvfs.exists(data_dir)):
            xbmcvfs.mkdir(data_dir)

        try:
            doc = xml.dom.minidom.parse(xbmc.translatePath(data_dir + "hosts.xml"))

            for node in doc.getElementsByTagName("host"):
                self.hosts.append(XbmcHost(str(node.getAttribute("name")),str(node.getAttribute("address")),int(node.getAttribute("port"))))

            #sort the lists
            self._sort()
            
        except IOError:
            #the file doesn't exist, create it
            doc = xml.dom.minidom.Document()
            rootNode = doc.createElement("hosts")
            doc.appendChild(rootNode)

            #write the file
            f = open(xbmc.translatePath(data_dir + "hosts.xml"),'w')
            doc.writexml(f,"   ")
            f.close()
Пример #31
0
def batch_add_tvshows_to_library(library_folder, show):
    id = show['id']
    showname = text.to_utf8(show['seriesname'])
    show_folder = os.path.join(library_folder, str(id) + '/')
    if not xbmcvfs.exists(show_folder):
        try:
            xbmcvfs.mkdir(show_folder)
        except:
            pass
    nfo_filepath = os.path.join(show_folder, 'tvshow.nfo')
    if not xbmcvfs.exists(nfo_filepath):
        nfo_file = xbmcvfs.File(nfo_filepath, 'w')
        content = 'https://thetvdb.com/?tab=series&id=%s' % str(id)
        nfo_file.write(content)
        nfo_file.close()
    clean_needed = True
    return clean_needed
Пример #32
0
def connection():
    path = xbmc.translatePath('special://temp/')
    if not xbmcvfs.exists(path):
        print "Making path structure: " + path
        xbmcvfs.mkdir(path)
    path = os.path.join(path, 'showdownloader.db')
    try:
        if "sqlite3" in sys.modules:
            conn = sqlite3.connect(path, check_same_thread=False)
        elif "sqlite" in sys.modules:
            conn = sqlite.connect(path)
        else:
            print "ERROR! No Sql found"

        return conn
    except Exception, e:
        xbmcvfs.delete(path)
    def _extract_widevine_from_img(self, backup_path):
        ''' Extract the Widevine CDM binary from the mounted Chrome OS image '''
        from shutil import copyfile
        from xbmcvfs import exists, mkdir

        for root, _, files in os.walk(str(self._mnt_path())):
            if str('libwidevinecdm.so') not in files:
                continue
            cdm_path = os.path.join(root, 'libwidevinecdm.so')
            log('Found libwidevinecdm.so in {path}', path=cdm_path)
            if not exists(backup_path):
                mkdir(backup_path)
            copyfile(cdm_path, os.path.join(backup_path, 'libwidevinecdm.so'))
            return True

        log('Failed to find Widevine CDM binary in Chrome OS image.')
        return False
Пример #34
0
    def _makedirs(path):
        if len(path) == 0:
            return False

        if(xbmcvfs.exists(path)):
            return True

        success = xbmcvfs.mkdir(path)

        if success == False:
            if path == os.path.dirname(path):
                return False

            if FileAccess._makedirs(os.path.dirname(path)):
                return xbmcvfs.mkdir(path)

        return xbmcvfs.exists(path)
Пример #35
0
def abrir_url(url, referer=base_url):  # TODO: main url processor?
    if not os.path.exists(datapath): xbmcvfs.mkdir(datapath)

    net = Net(cookie_file=cookie_TviFile,
              proxy='',
              user_agent=user_agent,
              http_debug=True)
    if os.path.exists(cookie_TviFile): net.set_cookies(cookie_TviFile)
    try:
        ref_data = {'Referer': referer}
        html = net.http_GET(url, headers=ref_data).content.encode(
            'latin-1', 'ignore')
        net.save_cookies(cookie_TviFile)
        return html
    except:
        xbmc.log("abrir_url fail =" + url)
        return ''
Пример #36
0
    def getScreensaverFolder():
        screenFolder = ADDON.getSetting("screensaverFolder")

        # If the screensaver folder has not been set yet, then set it to default
        if screenFolder in [None, ""]:
            addonRootDir = xbmc.translatePath(
                'special://profile/addon_data/%s' % ADDON_ID)
            screenFolder = os_path_join(addonRootDir, 'videos')
            ADDON.setSetting("screensaverFolder", screenFolder)

            # Make sure the screensaver folder exists, if not, createe it
            if not dir_exists(addonRootDir):
                xbmcvfs.mkdir(addonRootDir)
            if not dir_exists(screenFolder):
                xbmcvfs.mkdir(screenFolder)

        return screenFolder
 def __init__(self, name):
     path = ADDON.getAddonInfo("profile")
     if not xbmcvfs.exists(path):
         debug("storage path: {}".format(repr(path)))
         xbmcvfs.mkdir(path)
     path = os.path.join(path, 'storage.db')
     if Storage._static_db is None:
         Storage._static_db = Sqlite(path=path)
     self._db = Storage._static_db
     global checked
     self._data = {}
     self._last_saved = {}
     self._name = name
     if not checked:
         checked = True
         self._db.execute(self._sql_create)
     self.load()
Пример #38
0
def save_to_file(content, filename, path=""):
    import xbmcvfs
    if True:
        if path == "":
            text_file_path = get_browse_dialog() + filename + ".txt"
        else:
            if not xbmcvfs.exists(path):
                xbmcvfs.mkdir(path)
            text_file_path = os.path.join(path, filename + ".txt")
        log("save to textfile:")
        log(text_file_path)
        text_file = open(text_file_path, "w")
        simplejson.dump(content, text_file)
        text_file.close()
        return True
    else:
        return False
Пример #39
0
    def __init__(self, kodi_helper):
        """
        The Constructor checks for already existing crypto Keys.
        If they exist it will load the existing keys
        """
        self.kodi_helper = kodi_helper
        try:
            xbmcvfs.mkdir(path=self.kodi_helper.msl_data_path)
        except OSError:
            pass

        if self.file_exists(self.kodi_helper.msl_data_path, 'msl_data.json'):
            self.init_msl_data()
        elif self.file_exists(self.kodi_helper.msl_data_path, 'rsa_key.bin'):
            self.init_rsa_keys()
        else:
            self.init_generate_rsa_keys()
Пример #40
0
    def saveCacheIfDirty(self):
        '''
        Saves the disk-enabled properties that are dirty to their own files.
        '''
        # Optimised way to check if anything needs saving. Most of the time
        # 'dirtyNamesRaw' will be an empty string, easy to check for truthness.
        dirtyNamesRaw = self.window.getProperty(self.PROPERTY_DIRTY_NAMES_SET)
        if dirtyNamesRaw:
            if not xbmcvfs.exists(self.CACHE_PATH_DIR):
                xbmcvfs.mkdir(self.CACHE_PATH_DIR)

            for propName in dirtyNamesRaw.split(','):
                self._saveCacheProperty(propName)

            # Reset the dirty names set and its window property.
            self.dirtyNamesSet = set()
            self.window.setProperty(self.PROPERTY_DIRTY_NAMES_SET, '')
Пример #41
0
def create_cache(path, hexfile):
    images = walk(path)
    if not xbmcvfs.exists(CACHEFOLDER):
        xbmcvfs.mkdir(CACHEFOLDER)
    # remove old cache files
    dirs, files = xbmcvfs.listdir(CACHEFOLDER)
    for item in files:
        if item != 'settings.xml':
            xbmcvfs.delete(os.path.join(CACHEFOLDER, item))
    if images:
        # create index file
        try:
            cache = xbmcvfs.File(CACHEFILE % hexfile, 'w')
            cache.write(str(images))
            cache.close()
        except:
            log('failed to save cachefile')
Пример #42
0
 def __update_tvshows_library(self):
     tvshows = utils.call_service("load_all_contents", {
         "begin": 0,
         "category": "Serie"
     })
     if tvshows == None or len(tvshows) == 0:
         return
     self.empty_tvshows_library()
     base_series_folder = os.path.join(self.library_folder,
                                       self.tvshows_folder)
     items = TimVisionObjects.parse_collection(tvshows)
     for tvshow in items:
         title_normalized = self.__normalize_path(tvshow.title)
         if len(title_normalized) == 0:
             # TODO: FIX ME
             continue  #skip shows with unicode characters/empty title
         Logger.kodi_log("Library (TV): %s" % (title_normalized))
         normalized_show_name = "%s (%d)" % (title_normalized, tvshow.year)
         show_folder = os.path.join(base_series_folder,
                                    normalized_show_name)
         xbmcvfs.mkdir(show_folder)
         seasons_json = utils.call_service(
             "get_show_content", {
                 "contentId": tvshow.content_id,
                 "contentType": TimVisionAPI.TVSHOW_CONTENT_TYPE_SEASONS
             })
         seasons = TimVisionObjects.parse_collection(seasons_json)
         for season in seasons:
             episodes_json = utils.call_service(
                 "get_show_content", {
                     "contentId": season.content_id,
                     "contentType":
                     TimVisionAPI.TVSHOW_CONTENT_TYPE_EPISODES
                 })
             episodes = TimVisionObjects.parse_collection(episodes_json)
             for episode in episodes:
                 filename = "%s S%02dE%02d" % (
                     normalized_show_name, episode.season, episode.episode)
                 url = "plugin://plugin.video.timvision/?action=play_item&contentId=%s&videoType=%s&has_hd=%s&startPoint=%s&duration=%s" % (
                     str(episode.content_id), episode.mediatype,
                     str(episode.is_hd_available), str(
                         episode.bookmark), str(episode.duration))
                 self.write_strm(
                     os.path.join(show_folder, filename + ".strm"),
                     filename, url)
Пример #43
0
def addlista():
    opcao = xbmcgui.Dialog().yesno(translate(40000), translate(40123), "", "",
                                   translate(40124), translate(40125))
    if opcao:
        dialog = xbmcgui.Dialog()
        lista_xml = dialog.browse(1, translate(40186), 'files', '.xml|.m3u')
        keybdois = xbmc.Keyboard("", translate(40130))
        keybdois.doModal()
        if (keybdois.isConfirmed()):
            searchname = keybdois.getText()
            if searchname == '': sys.exit(0)
            encode = urllib.quote(searchname)
            if xbmcvfs.exists(os.path.join(pastaperfil, "Lists")): pass
            else: xbmcvfs.mkdir(os.path.join(pastaperfil, "Lists"))
            txt_name = searchname + ".txt"
            save(os.path.join(pastaperfil, "Lists", txt_name), lista_xml)
            mensagemok(translate(40000), translate(40129))
            xbmc.executebuiltin("XBMC.Container.Refresh")
    else:
        keyb = xbmc.Keyboard("", translate(40127))
        keyb.doModal()
        if (keyb.isConfirmed()):
            search = keyb.getText()
            if search == '': sys.exit(0)
            if "dropbox" in search and not "?dl=1" in search:
                search = search + '?dl=1'
            try:
                if not search.startswith("http://"):
                    search = "http://" + search
                code = get_page_source(search)
            except:
                mensagemok(translate(40000), translate(40128))
                sys.exit(0)
            keybdois = xbmc.Keyboard("", translate(40130))
            keybdois.doModal()
            if (keybdois.isConfirmed()):
                searchname = keybdois.getText()
                if searchname == '': sys.exit(0)
                encode = urllib.quote(searchname)
                if os.path.exists(os.path.join(pastaperfil, "Lists")): pass
                else: xbmcvfs.mkdir(os.path.join(pastaperfil, "Lists"))
                txt_name = searchname + ".txt"
                save(os.path.join(pastaperfil, "Lists", txt_name), search)
                mensagemok(translate(40000), translate(40129))
                xbmc.executebuiltin("XBMC.Container.Refresh")
Пример #44
0
    def _copylocal(self, romCollection, rom):
        if romCollection.makeLocalCopy:
            localDir = os.path.join(util.getTempDir(), romCollection.name)
            if xbmcvfs.exists(localDir + '\\'):
                log.info("Trying to delete local rom files")
                dirs, files = xbmcvfs.listdir(localDir)
                for f in files:
                    xbmcvfs.delete(os.path.join(localDir, f))
            else:
                log.info("Create temporary folder: " + localDir)
                xbmcvfs.mkdir(localDir)
            localRom = os.path.join(localDir, os.path.basename(str(rom)))
            log.info("Creating local copy: " + str(localRom))
            if xbmcvfs.copy(rom, localRom):
                log.info("Local copy created")
            rom = localRom

        return rom
Пример #45
0
def CreateDir(folder_path):
    if not xbmcvfs.exists(folder_path):
        created = xbmcvfs.mkdir(folder_path)
        if created:
            Log('Directory Created {}'.format(folder_path))
        else:
            Log('Unable to create {}'.format(folder_path))
    else:
        Log('Directory {} already exists'.format(folder_path))
Пример #46
0
def library_tv_strm(show, folder, id, season, episode):
    enc_season = ('Season %s' % season).translate(None, '\/:*?"<>|').strip('.')
    folder = os.path.join(folder, enc_season)
    try:
        xbmcvfs.mkdir(folder)
    except:
        pass
    enc_name = '%s - S%02dE%02d.strm' % (text.clean_title(
        show['seriesname']), season, episode)
    stream = os.path.join(folder, enc_name)
    if not xbmcvfs.exists(stream):
        file = xbmcvfs.File(stream, 'w')
        content = plugin.url_for('tv_play',
                                 id=id,
                                 season=season,
                                 episode=episode)
        file.write(str(content))
        file.close()
Пример #47
0
def _connect_to_db():
    """ internal command ~"""
    def dict_factory(cursor, row):
        d = {}
        for idx, col in enumerate(cursor.description):
            d[col[0]] = row[idx]
        return d

    xbmcvfs.mkdir(xbmc.translatePath(
        xbmcaddon.Addon().getAddonInfo('profile')))
    db_location = os.path.join(
        xbmc.translatePath(
            xbmcaddon.Addon().getAddonInfo('profile')).decode('utf-8'),
        'database.db')
    dbcon = database.connect(db_location)
    dbcon.row_factory = dict_factory
    dbcur = dbcon.cursor()
    return (dbcur, dbcon)
Пример #48
0
def makeSTRM(name, link):
    log('makeSTRM')
    STRM_CACHE_LOC = xbmc.translatePath(get_setting('write_folder'))
    try:
        if not xbmcvfs.exists(STRM_CACHE_LOC):
            xbmcvfs.mkdir(STRM_CACHE_LOC)
        filepath = os.path.join(STRM_CACHE_LOC, name + '.strm')
        if xbmcvfs.exists(filepath):
            return True
        else:
            fle = open(filepath, "w")
            fle.write("%s" % link)
            fle.close()
            log('writing item: %s' % (filepath))
            return True
        return False
    except:
        return False
 def __init__(self, base_url=None, handle=None):
     addon = self.get_addon()
     self.base_url = base_url
     self.handle = handle
     self.addon_path = xbmc.translatePath(addon.getAddonInfo('path'))
     self.addon_profile = xbmc.translatePath(addon.getAddonInfo('profile'))
     self.addon_name = addon.getAddonInfo('id')
     self.addon_version = addon.getAddonInfo('version')
     self.language = addon.getLocalizedString
     self.logging_prefix = '[%s-%s]' % (self.addon_name, self.addon_version)
     if not xbmcvfs.exists(self.addon_profile):
         xbmcvfs.mkdir(self.addon_profile)
     self.d = Dplay(self.addon_profile, self.get_setting('site'),
                    self.get_setting('locale'), self.logging_prefix,
                    self.get_setting('numresults'),
                    self.get_setting('cookiestxt'),
                    self.get_setting('cookiestxt_file'),
                    self.get_setting('sync_playback'))
Пример #50
0
def make_dir(mypath, dirname):
    import xbmcvfs
    
    if not xbmcvfs.exists(mypath): 
        try:
            xbmcvfs.mkdirs(mypath)
        except:
            xbmcvfs.mkdir(mypath)
    
    subpath = os.path.join(mypath, dirname)
    
    if not xbmcvfs.exists(subpath): 
        try:
            xbmcvfs.mkdirs(subpath)
        except:
            xbmcvfs.mkdir(subpath)
            
    return subpath
Пример #51
0
    def _repo_install(self):
        # if the addon folder doesn't exist, create it
        if not xbmcvfs.exists(
                xbmc.translatePath('special://home/addons/{0}'.format(
                    self.addonid))):
            xbmcvfs.mkdir(
                xbmc.translatePath('special://home/addons/{0}'.format(
                    self.addonid)))

        # if an `addon.xml` doesn't exist, create a dummy one
        with open(self.addon_xml, 'w') as f:
            f.write(dummy_addon_xml.format(self.addonid))

        self._add_to_database()

        # try to update the addon
        xbmc.executebuiltin('UpdateAddonRepos')
        xbmc.executebuiltin('XBMC.UpdateLocalAddons()')
Пример #52
0
    def __init__(self, url, dest=None, no_dialog=None):
        if dest is None:
            xbmcgui.Dialog().ok(
                'Kodi Setter-Upper',
                '`Download()` -- argument `dest` cannot be `None`')
            raise TypeError

        self.url = url
        self.dest = xbmc.translatePath(dest)

        # if the destination folder doesn't exist, create it
        if not xbmcvfs.exists(os.path.dirname(self.dest)):
            xbmcvfs.mkdir(os.path.dirname(self.dest))

        # if the destination file exists, delete it
        if xbmcvfs.exists(self.dest):
            xbmcvfs.delete(self.dest)

        # https://github.com/tvaddonsco/plugin.program.indigo/blob/master/installer.py#L987
        if no_dialog is None:
            # create a Dialog Progress box
            dp = xbmcgui.DialogProgress()
            dp.create("Download Progress:", "", '', 'Please Wait')
            dp.update(0, "Downloading: " + os.path.basename(dest), '',
                      'Please Wait')

            # download the file
            if not PY2:
                urllib.request.urlretrieve(self.url,
                                           self.dest,
                                           lambda nb, bs, fs, url=self.url:
                                           _pbhook(nb, bs, fs, url, dp))
            else:
                urllib.urlretrieve(self.url,
                                   self.dest,
                                   lambda nb, bs, fs, url=self.url: _pbhook(
                                       nb, bs, fs, url, dp))

        else:
            # download the file
            if not PY2:
                urllib.request.urlretrieve(self.url, self.dest)
            else:
                urllib.urlretrieve(self.url, self.dest)
Пример #53
0
def addlist():
    YNDialog = xbmcgui.Dialog().yesno(translate(30000), translate(30172),'','',translate(30173),translate(30174))
    if YNDialog:
        dialog = xbmcgui.Dialog()
        lista_xml = dialog.browse(1, translate(30175), 'files','.tvl|.m3u|.xml')
        xbmcKey = xbmc.Keyboard('', translate(30176))
        xbmcKey.doModal()
        if (xbmcKey.isConfirmed()):
            searchname = xbmcKey.getText()
            if searchname=='': sys.exit(0)
            encode=urllib.quote(searchname)
            if xbmcvfs.exists(os.path.join(addonprofile,'Lists')): pass
            else: xbmcvfs.mkdir(os.path.join(addonprofile,'Lists'))
            txt_name = searchname + '.txt'
            save(os.path.join(addonprofile,'Lists',txt_name),lista_xml)
            messageok(translate(30000),translate(30177))
            xbmc.executebuiltin('XBMC.Container.Refresh')
    else:
        keyb = xbmc.Keyboard('', translate(30178))
        keyb.doModal()
        if (keyb.isConfirmed()):
            search = keyb.getText()
            if search=='': sys.exit(0)
            if 'dropbox' in search and not '?dl=1' in search: search = search + '?dl=1'
            if 'tvl' not in search.split('.')[-1] and 'xml' not in search.split('.')[-1] and 'm3u' not in search.split('.')[-1]:
                messageok(translate(30000),translate(30011)); sys.exit(0)
            else:
                try:
                    code = get_page_source(search)
                except:
                    messageok(translate(30000),translate(30011))
                    sys.exit(0)
            xbmcKey = xbmc.Keyboard('', translate(30176))
            xbmcKey.doModal()
            if (xbmcKey.isConfirmed()):
                searchname = xbmcKey.getText()
                if searchname=='': sys.exit(0)
                encode=urllib.quote(searchname)
                if os.path.exists(os.path.join(addonprofile,'Lists')): pass
                else: xbmcvfs.mkdir(os.path.join(addonprofile,'Lists'))
                txt_name = searchname + '.txt'
                save(os.path.join(addonprofile,'Lists',txt_name),search)
                messageok(translate(30000),translate(30177))
                xbmc.executebuiltin('XBMC.Container.Refresh')
Пример #54
0
def generateCombinedThumbnail(v, h, width=2 * 500, height=500, padding=10):
    thumbnails_path = os.path.join(
        xbmc.translatePath(
            xbmcaddon.Addon().getAddonInfo('profile')).decode('utf-8'),
        "thumbnails")
    if not xbmcvfs.exists(thumbnails_path):
        xbmcvfs.mkdir(thumbnails_path)
    combined_thumbnail_fullname = os.path.join(
        thumbnails_path, ("%s-%s.png" % (v.lower(), h.lower())))
    if vars.use_cached_thumbnails and os.path.isfile(
            combined_thumbnail_fullname):
        return combined_thumbnail_fullname
    single_thumbnail_fullnames = [
        os.path.join(thumbnails_path, ("%s.png" % t.lower())) for t in [v, h]
    ]
    SINGLE_THUMBNAIL_URL_MASK = "http://i.cdn.turner.com/nba/nba/.element/img/1.0/teamsites/logos/teamlogos_500x500/%s.png"
    for (t, single_thumbnail_fullname) in zip([v, h],
                                              single_thumbnail_fullnames):
        if not vars.use_cached_thumbnails or not os.path.isfile(
                single_thumbnail_fullname):
            urllib.urlretrieve(SINGLE_THUMBNAIL_URL_MASK % t.lower(),
                               single_thumbnail_fullname)

    try:
        [im_v, im_h] = [
            Image.open(single_thumbnail_fullname).convert('RGBA')
            for single_thumbnail_fullname in single_thumbnail_fullnames
        ]
        [im_v, im_h] = [
            prepareSingleThumbnail(im, width / 2 - 2 * padding,
                                   height - 2 * padding)
            for im in [im_v, im_h]
        ]

        im_combined = Image.new('RGBA', (width, height))
        im_combined.paste(im_v, (padding, padding), im_v)
        im_combined.paste(im_h, (width / 2 + padding, padding), im_h)
        im_combined.save(combined_thumbnail_fullname)
        return combined_thumbnail_fullname
    except:
        log(traceback.format_exc(), xbmc.LOGERROR)
        [v_thumbnail_fullname,
         h_thumbnail_fullname] = single_thumbnail_fullnames
        return h_thumbnail_fullname
Пример #55
0
    def _download_external_subs(self, src, dst, filename):

        if not xbmcvfs.exists(dst):
            xbmcvfs.mkdir(dst)

        path = os.path.join(dst, filename)

        try:
            response = requests.get(src, stream=True)
            response.raise_for_status()
        except Exception as e:
            raise
        else:
            response.encoding = 'utf-8'
            with open(path, 'wb') as f:
                f.write(response.content)
                del response

            return path
Пример #56
0
def add_movie(mf):
    logger.debug("---------------------------------")
    originalTitle = xbmc.getInfoLabel("ListItem.Originaltitle").decode('utf-8')
    year = xbmc.getInfoLabel("ListItem.Year").decode('utf-8')
    moviePath = xbmc.getInfoLabel("ListItem.FileNameAndPath")

    dirName = mf + originalTitle + ' (' + year + ')'

    if not xbmcvfs.exists(dirName):
        xbmcvfs.mkdir(dirName)
    strmFileName = join(dirName, originalTitle + ' (' + year + ')' + '.strm')
    logger.debug("%s %s" % (strmFileName, moviePath))
    file = xbmcvfs.File(strmFileName, 'w')
    file.write(str(moviePath))
    file.close()
    # eventualne hodit notifikaciu
    # notification('Added to library', 'Movie %s was successfully added to library' % originalTitle)
    # notification(get_string(30405), get_string(30406) % originalTitle)
    xbmc.executebuiltin('UpdateLibrary(video)')
Пример #57
0
def make_dir(mypath, dirname):
    ''' Creates sub-directories if they are not found. '''
    import xbmcvfs
    
    if not xbmcvfs.exists(mypath): 
        try:
            xbmcvfs.mkdirs(mypath)
        except:
            xbmcvfs.mkdir(mypath)
    
    subpath = os.path.join(mypath, dirname)
    
    if not xbmcvfs.exists(subpath): 
        try:
            xbmcvfs.mkdirs(subpath)
        except:
            xbmcvfs.mkdir(subpath)
            
    return subpath
Пример #58
0
 def __init__(self):
     self.__sMovieFolder = xbmc.translatePath(cConfig().getSetting('Library_folder_Movies'))
     self.__sTVFolder = xbmc.translatePath(cConfig().getSetting('Library_folder_TVs'))
     
     if not self.__sMovieFolder:
         PathCache = cConfig().getSettingCache()
         self.__sMovieFolder = os.path.join(PathCache,'Movies\\')
         cConfig().setSetting('Library_folder_Movies',self.__sMovieFolder)
     if not xbmcvfs.exists(self.__sMovieFolder):
             xbmcvfs.mkdir(self.__sMovieFolder)
             
     if not self.__sTVFolder:
         PathCache = cConfig().getSettingCache()
         self.__sTVFolder = os.path.join(PathCache,'TVs\\')
         cConfig().setSetting('Library_folder_TVs',self.__sTVFolder)
     if not xbmcvfs.exists(self.__sTVFolder):
             xbmcvfs.mkdir(self.__sTVFolder)
         
     self.__sTitle = ''
Пример #59
0
    def _save_file(self):
        import urllib

        for cansave in self.cansave:
            if cansave["index"] == int(self.index):
                savepath = self.dlpath + (self.filename or cansave["infohash"])
                if cansave["format"] == "encrypted":
                    if not self.keep_enc:
                        return
                    savepath = "%s.acemedia" % savepath

                import xbmcvfs

                dirname = os.path.dirname(savepath)
                if not xbmcvfs.exists(dirname):
                    xbmcvfs.mkdir(dirname)
                self.sink.send(
                    "SAVE infohash=%s index=%s path=%s" %
                    (cansave["infohash"], self.index, urllib.quote(savepath)))
Пример #60
0
def add_to_addon_favourites(name, url, iconimage):
    name = name.replace("[b]", "").replace("[/b]", "").replace(
        "[color orange]",
        "").replace("[/color]", "").replace("[B]", "").replace("[/B]", "")
    if "runplugin" in url:
        match = re.compile("url=(.+?)&mode=(.+?)&").findall(
            url.replace(";", ""))
        for url, mode in match:
            favourite_text = name + " (" + url + ")|" + str(
                mode) + "|" + url + '|' + iconimage
            favouritetxt = os.path.join(
                pastaperfil, "Favourites",
                url.replace(":", "").replace("/", "") + ".txt")
            if not xbmcvfs.exists(os.path.join(pastaperfil, "Favourites")):
                xbmcvfs.mkdir(os.path.join(pastaperfil, "Favourites"))
            save(favouritetxt, favourite_text)
            xbmc.executebuiltin("Notification(%s,%s,%i,%s)" %
                                (translate(40000), translate(40148), 1,
                                 addonpath + "/icon.png"))
    else:
        if "sop://" in url:
            tipo = "sopcast"
        elif "acestream://" in url:
            tipo = "acestream"
        else:
            if len(url) < 30: tipo = "sopcast"
            else: tipo = "acestream"
        if tipo == "sopcast":
            favourite_text = name + " (" + url + ")|" + str(
                2) + "|" + url + '|' + iconimage
        elif tipo == "acestream":
            favourite_text = name + " (" + url + ")|" + str(
                1) + "|" + url + '|' + iconimage
        favouritetxt = os.path.join(
            pastaperfil, "Favourites",
            url.replace(":", "").replace("/", "") + ".txt")
        if not xbmcvfs.exists(os.path.join(pastaperfil, "Favourites")):
            xbmcvfs.mkdir(os.path.join(pastaperfil, "Favourites"))
        save(favouritetxt, favourite_text)
        xbmc.executebuiltin(
            "Notification(%s,%s,%i,%s)" %
            (translate(40000), translate(40148), 1, addonpath + "/icon.png"))
        xbmc.executebuiltin("Container.Refresh")