Example #1
0
    def _checkValidationFile(self,path):
        result = False
        
        #copy the file and open it
        self.xbmc_vfs.put(path + "xbmcbackup.val",xbmc.translatePath(utils.data_dir() + "xbmcbackup_restore.val"))

        vFile = xbmcvfs.File(xbmc.translatePath(utils.data_dir() + "xbmcbackup_restore.val"),'r')
        jsonString = vFile.read()
        vFile.close()

        #delete after checking
        xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "xbmcbackup_restore.val"))

        try:
            json_dict = json.loads(jsonString)

            if(xbmc.getInfoLabel('System.BuildVersion') == json_dict['xbmc_version']):
                result = True
            else:
                result = xbmcgui.Dialog().yesno(utils.getString(30085),utils.getString(30086),utils.getString(30044))
                
        except ValueError:
            #may fail on older archives
            result = True

        return result
Example #2
0
def convert_subtitles(closedcaption):
	# from pycaption import detect_format, SRTWriter
	# idea taken from LearningIt(t1m)
	str_output =''
	if closedcaption[0] is not None:
		try:
			cc_content = smart_unicode(make_request(closedcaption[0]))
			# reader = detect_format(cc_content)
			if cc_content != "":
				profile = Addon.getAddonInfo('profile').decode("utf-8")
				prodir  = xbmc.translatePath(os.path.join(profile))
				if not os.path.isdir(prodir):
					os.makedirs(prodir)
				subfile = xbmc.translatePath(os.path.join(profile, 'subtitles.srt'))	
				file = open(subfile, 'w+')
				str_output = re.sub('\d+(\b,\b)\d+','.',cc_content)
				str_output = str_output.replace('WEBVTT','')
				file.write(str_output)
				str_output=''
				file.close()
			else:
				print "unknown sub type"
		except:
			print "Exception with Subs: "
			subfile = ''
	return subfile
Example #3
0
    def get_visibility(self, path):
        path = path.replace("videodb://", "library://video/")

        customPath = path.replace("library://video", os.path.join(xbmc.translatePath("special://profile".decode('utf-8')), "library", "video")) + "index.xml"
        customFile = path.replace("library://video", os.path.join(xbmc.translatePath("special://profile".decode('utf-8')), "library", "video"))[:-1] + ".xml"
        defaultPath = path.replace("library://video", os.path.join(xbmc.translatePath("special://xbmc".decode('utf-8')), "system", "library", "video")) + "index.xml"
        defaultFile = path.replace("library://video", os.path.join(xbmc.translatePath("special://xbmc".decode('utf-8')), "system", "library", "video"))[:-1] + ".xml"

        # Check whether the node exists - either as a parent node (with an index.xml) or a view node (append .xml)
        # in first custom video nodes, then default video nodes
        if xbmcvfs.exists(customPath):
            path = customPath
        elif xbmcvfs.exists(customFile):
            path = customFile
        elif xbmcvfs.exists(defaultPath):
            path = defaultPath
        elif xbmcvfs.exists(defaultFile):
            path = defaultFile
        else:
            return ""

        # Open the file
        try:
            # Load the xml file
            tree = xmltree.parse(path)
            root = tree.getroot()

            if "visible" in root.attrib:
                return root.attrib.get("visible")
            else:
                return ""
        except:
            return False
Example #4
0
def MAININDEX():
    hubpath=xbmc.translatePath(os.path.join('special://home','addons','repository.xbmchub'))
    hubnotespath=xbmc.translatePath(os.path.join('special://home','addons','plugin.program.xbmchub.notifications'))
    try:
        if not os.path.exists(hubpath): HUBINSTALL('TVADDONS.AG.Repository','http://offshoregit.com/xbmchub/xbmc-hub-repo/raw/master/repository.xbmchub/repository.xbmchub-1.0.6.zip','','addon','none')
        if not os.path.exists(hubnotespath): HUBINSTALL('TVADDONS.AG.Notifications','http://offshoregit.com/xbmchub/xbmc-hub-repo/raw/master/plugin.program.xbmchub.notifications/plugin.program.xbmchub.notifications-1.0.2.zip','','addon','none')
    except: pass
    addDir('Search by: Addon/Author',base_url+'search/?keyword=','searchaddon',getArtworkJ('Search')) #catArtwork('webinterface')) #
    #if settings.getSetting('newest')=='true':  addDir('Newest Addons',base_url,'innertabs',getArtworkJ('NewestAddons'))
    #if settings.getSetting('updated')=='true':  addDir('Recently Updated',base_url,'innertabs',getArtworkJ('RecentlyUpdated'))
    #if settings.getSetting('toprepositories')=='true':  addDir('Top Developers',base_url,'toprepolist',getArtworkJ('TopDevs'))
    if settings.getSetting('featured')=='true':       	addDir('Featured Addons',base_url+'category/featured/','addonlist',getArtworkJ('Featuredaddons')) #catArtwork('featured')) #
    if settings.getSetting('video')=='true':          	addDir('Video Addons',base_url+'category/video/','addonlist',getArtworkJ('VideoAddons')) #catArtwork('video')) #
    if settings.getSetting('audio')=='true':          	addDir('Audio Addons',base_url+'category/audio/','addonlist',getArtworkJ('AudioAddons')) #catArtwork('audio')) #
    #if settings.getSetting('picture')=='true':        	addDir('Picture Addons',base_url+'category/pictures/','addonlist',getArtworkJ('PictureAddons')) #catArtwork('pictures')) #
    if settings.getSetting('program')=='true':        	addDir('Program Addons',base_url+'category/programs/','addonlist',getArtworkJ('ProgramAddons')) #catArtwork('programs')) #
    if settings.getSetting('services')=='true':       	addDir('Service Addons',base_url+'category/services/','addonlist',getArtworkJ('ServiceAddons')) #catArtwork('services')) #
    if settings.getSetting('repositories')=='true':   	addDir('Repositories',base_url+'category/repositories/','addonlist',getArtworkJ('Repositories')) #catArtwork('repositories')) #
    #if settings.getSetting('world')=='true':          	addDir('World Section',tribeca_url+'world.php','worldlist',getArtworkJ('WorldSection')) #catArtwork('metadata')) #
    if settings.getSetting('world')=='true':          	addDir('World Section',base_url+'category/international/repositories','interlist',getArtworkJ('WorldSection')) #catArtwork('video')) #
    if settings.getSetting('adult')=='true':          	addDir('Adult Addons',tribeca_url+'xxx.php','adultlist',getArtworkJ('AdultAddons')) #catArtwork('pictures')) #
    
    ForPrimeWire(); 
    #addDir(TxtAddonUpdater,base_url+'category/featured/','autoupdate',ImgAddonUpdater); 
    ##addDir(TxtAddonUpdater,'...','autoupdate2',ImgAddonUpdater); 
    addDir('Installer Settings','none','settings',getArtworkJ('InstallerSettings')); #catArtwork('programs')) #
    AUTO_VIEW('addons')
 def GetShowBanner(self, show_id, update=False):
     image = None
     if show_id == '0':
         return ''
     file_path = xbmc.translatePath('special://temp/sb/cache/images/'+show_id+'.banner.jpg')
     if not os.path.exists(file_path) or update:
         # Download image from SB server.
         try:
             image = GetUrlData(url=settings.__url__+'?cmd=show.getbanner&tvdbid='+str(show_id), add_useragent=True, encodeType=None)
             if (image == None) or (len(image) < 1024):
                 # Get generic image instead.
                 with open(xbmc.translatePath('special://home/addons/plugin.video.sickrage/resources/images/missing_banner.jpg'), mode='rb') as f:
                     image = f.read()
         except Exception, e:
             settings.errorWindow(sys._getframe().f_code.co_name, self.CONNECT_ERROR+str(e))
             return ''
         # Write image file to local cache.
         try:
             if not os.path.exists(os.path.dirname(file_path)):
                 os.makedirs(os.path.dirname(file_path))
             f = open(file_path, 'wb+')
             f.write(image)
             f.close()
         except Exception, e:
             settings.errorWindow(sys._getframe().f_code.co_name, str(e))
def library_install():
    import os
    import sqlite3
    import xbmc
    import xbmcgui
    from contextlib import closing
    import xml.etree.ElementTree as ET

    def _make_source_node(name, path):
        source = ET.Element("source")
        ET.SubElement(source, "name").text = name
        ET.SubElement(source, "path").text = path
        return source

    sources_filename = xbmc.translatePath("special://userdata/sources.xml")
    root = ET.parse(sources_filename)
    video_node = root.find("./video")
    with closing(sqlite3.connect(_get_video_db())) as conn:
        for name, entry in LIBRARY_PATHS.items():
            if not os.path.exists(xbmc.translatePath(entry["strPath"])):
                os.makedirs(xbmc.translatePath(entry["strPath"]))
            if not [elem for elem in video_node.findall('source') if elem.find('path').text.startswith(entry["strPath"])]:
                video_node.append(_make_source_node(name, entry["strPath"]))
            if not conn.execute('''SELECT idPath FROM path WHERE strPath=:strPath''', entry).fetchone():
                keys = []
                values = []
                for key, value in entry.items():
                    keys.append(key)
                    values.append(value)
                conn.execute('''INSERT INTO path(%s) VALUES (?, ?, ?, ?, ?)''' % ", ".join(keys), values)
        conn.commit()
        root.write(sources_filename)
    _rescan_library()
    xbmcgui.Dialog().ok("XBMCtorrent", "Installation complete.", "")
Example #7
0
def install(vers,url):
    import xbmc,xbmcgui,os,re,time
    from resources.lib.modules import downloader2
    addon_folder = xbmc.translatePath('special://home/addons/script.module.streamhub/')
    path = xbmc.translatePath(os.path.join('special://home/addons','packages'))
    dp = xbmcgui.DialogProgress()
    dp.create("[COLOR red]StreamHub[/COLOR]","Installing Dependency Update v[COLOR red]%s[/COLOR]"%vers,'', 'Please Wait')
    lib=os.path.join(path, 'content.zip')
    try:
       os.remove(lib)
    except:
       pass
	   
    import shutil

    shutil.rmtree(addon_folder)
    try:
        downloader2.download(url, lib, dp)
        addonfolder = xbmc.translatePath(os.path.join('special://home','addons'))
        time.sleep(3)
    except:
        xbmcgui.Dialog().ok('[COLOR red]StreamHub[/COLOR]','Oops..Something Went Wrong Downloading The Update...Try Again')
    dp = xbmcgui.DialogProgress()
    dp.create("[COLOR red]StreamHub[/COLOR]","Installing Dependency Update Version [COLOR red]%s[/COLOR]"%vers,'', 'Please Wait')
    dp.update(0,"", "Installing... Please Wait")
    print '======================================='
    print addonfolder
    print '======================================='
    try:
        unzip(lib,addonfolder,dp)
    except:
        xbmcgui.Dialog().ok('[COLOR red]StreamHub[/COLOR]','Oops..Something Went Wrong Installing The Update...Try Again')
    def run(self):
        self.logMsg("Started")
        
        self.updateRecent()
        lastRun = datetime.today()
        lastProfilePath = xbmc.translatePath('special://profile')
        
        while (xbmc.abortRequested == False):
            td = datetime.today() - lastRun
            secTotal = td.seconds
            
            profilePath = xbmc.translatePath('special://profile')
            
            updateInterval = 60
            if (xbmc.Player().isPlaying()):
                updateInterval = 300
                
            if(secTotal > updateInterval or lastProfilePath != profilePath):
                self.updateRecent()
                lastRun = datetime.today()

            lastProfilePath = profilePath
            
            xbmc.sleep(3000)
                        
        self.logMsg("Exited")
Example #9
0
    def isGrouped( self, path ):        
        customPathVideo = path.replace( "library://video", os.path.join( xbmc.translatePath( "special://profile".decode('utf-8') ), "library", "video" ) )[:-1]
        defaultPathVideo = path.replace( "library://video", os.path.join( xbmc.translatePath( "special://xbmc".decode('utf-8') ), "system", "library", "video" ) )[:-1]
        customPathAudio = path.replace( "library://music", os.path.join( xbmc.translatePath( "special://profile".decode('utf-8') ), "library", "music" ) )[:-1]
        defaultPathAudio = path.replace( "library://music", os.path.join( xbmc.translatePath( "special://xbmc".decode('utf-8') ), "system", "library", "music" ) )[:-1]
        
        paths = [ customPathVideo, defaultPathVideo, customPathAudio, defaultPathAudio ]
        foundPath = False

        for tryPath in paths:
            if xbmcvfs.exists( tryPath ):
                path = tryPath
                foundPath = True
                break
        if foundPath == False:
            return False
        
        # Open the file
        try:
            # Load the xml file
            tree = xmltree.parse( path )
            root = tree.getroot()

            group = root.find( "group" )
            if group is None:
                return False
            else:
                return True
        except:
            return False
Example #10
0
    def walkTree(self,directory):
       
        if(self.vfs.exists(directory + "/")):
            dirs,files = self.vfs.listdir(directory)
        
            #create all the subdirs first
            for aDir in dirs:
                dirPath = xbmc.translatePath(directory + "/" + aDir)
                file_ext = aDir.split('.')[-1]
              
                self.addFile("-" + dirPath)

                #catch for "non directory" type files
                shouldWalk = True

                for s in file_ext:
                    if(s in self.not_dir):
                        shouldWalk = False
                
                if(shouldWalk):
                    self.walkTree(dirPath)  
            
            #copy all the files
            for aFile in files:
                filePath = xbmc.translatePath(directory + "/" + aFile)
                self.addFile(filePath)
 def __init__(self):
     
     #Check if a path has been set in the addon settings
     db_path = common.addon.get_setting('local_db_location')
     if db_path:
         self.path = xbmc.translatePath(db_path)
     else:
         self.path = xbmc.translatePath('special://profile/addon_data/script.icechannel/databases')
     
     self.path = common.make_dir(self.path, '')
     
     self.db = os.path.join(self.path, self.local_db_name)
     
     # connect to db at class init and use it globally
     if DB == 'mysql':
         class MySQLCursorDict(database.cursor.MySQLCursor):
             def _row_to_python(self, rowdata, desc=None):
                 row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
                 if row:
                     return dict(zip(self.column_names, row))
                 return None
         self.dbcon = database.connect(database=common.addon.get_setting('db_name'), user=common.addon.get_setting('db_user'), 
             password=common.addon.get_setting('db_pass'), host=common.addon.get_setting('db_address'), buffered=True, charset='utf8')                
         self.dbcur = self.dbcon.cursor(cursor_class=MySQLCursorDict, buffered=True)
     else:
         self.dbcon = database.connect(self.db)
         self.dbcon.row_factory = database.Row # return results indexed by field names and not numbers so we can convert to dict
         self.dbcon.text_factory = str
         self.dbcur = self.dbcon.cursor()
             
     self._create_subscription_tables()
Example #12
0
def getData(url, timeout=__cachePeriod__, name=''):
        if __DEBUG__:
            print 'url --> ' + url
            print 'name --> ' + name
        if timeout > 0:
            if name == '':
                cachePath = xbmc.translatePath(os.path.join(__PLUGIN_PATH__, 'cache', 'pages', urllib.quote(url,"")))
            else:
                cachePath = xbmc.translatePath(os.path.join(__PLUGIN_PATH__, 'cache', 'pages', name))
            if (os.path.exists(cachePath) and (time.time()-os.path.getmtime(cachePath))/60/60 <= float(timeout)):
                f = open(cachePath, 'r')
                ret = f.read()
                f.close()
                if __DEBUG__:
                    print 'returned data from cache'
                return ret
        try:     
            req = urllib2.Request(url)
            req.add_header('User-Agent', __USERAGENT__)        
            response = urllib2.urlopen(req)
            data = response.read().replace("\n","").replace("\t","").replace("\r","")
            response.close()
            if timeout > 0:
                f = open(cachePath, 'wb')
                f.write(data)
                f.close()
            if __DEBUG__:
                print data
            return data
        except:
            if __DEBUG__:
                errno, errstr = sys.exc_info()[:2]
                print 'Error in getData: ' + str(errno) + ": " + str(errstr)
            xbmc.log('Error in getData: Unable to save cache', xbmc.LOGERROR)
            return 'unavailable'
Example #13
0
def Addon_Install(name,zip_link,repo_link,repo_id,addon_id,provider_name,forum,data_path):
    print "############# ADDON INSTALL #################"
    print "repo_url: "+str(repo_link)
    print "zip_url: "+str(zip_link)
    print "repo_id: "+str(repo_id)
    forum=str(forum)
    repo_id=str(repo_id)
    status=1
    repostatus=1
    modulestatus=1
    addondownload=xbmc.translatePath(os.path.join(packages,name+'.zip'))
    addonlocation=xbmc.translatePath(os.path.join(ADDONS,addon_id))
    dp.create("Installing Addon","Please wait whilst your addon is installed",'', '')
    try:
        downloader.download(repo_link, addondownload, dp)
        extract.all(addondownload, addonfolder, dp)
    except:
        try:
            downloader.download(zip_link, addondownload, dp)
            extract.all(addondownload, addonfolder, dp)
        except:
            try:
                if not os.path.exists(addonlocation):
                    os.makedirs(addonlocation)
                link = extras.Open_URL(data_path).replace('\n','').replace('\r','')
                match=re.compile('href="(.+?)"', re.DOTALL).findall(link)
                for href in match:
                    filepath=xbmc.translatePath(os.path.join(addonlocation,href))
                    if addon_id not in href and '/' not in href:
                        try:
                            dp.update(0,"Downloading [COLOR=yellow]"+href+'[/COLOR]','','Please wait...')
                            print"downloading: "+data_path+href
                            downloader.download(data_path+href, filepath, dp)
                        except: print"failed to install"+href
                    if '/' in href and '..' not in href and 'http' not in href:
                        remote_path = data_path+href
                        Recursive_Loop(filepath,remote_path)
            except:
                dialog.ok("Error downloading add-on", 'There was an error downloading [COLOR=yellow]'+name,'[/COLOR]Please consider updating the add-on portal with details','or report the error on the forum at [COLOR=lime][B]www.totalxbmc.tv[/COLOR][/B]')             
                status=0
    if status==1:
        time.sleep(1)
        dp.update(0,"[COLOR=yellow]"+name+'[/COLOR]  [COLOR=lime]Successfully Installed[/COLOR]','','Now installing repository')
        time.sleep(1)
        repopath = xbmc.translatePath(os.path.join(ADDONS, repo_id))
        if (repo_id != 'repository.xbmc.org') and not (os.path.exists(repopath)) and (repo_id != '') and ('superrepo' not in repo_id):
            Install_Repo(repo_id)
        incremental = 'http://totalxbmc.com/totalrevolution/AddonPortal/downloadcount.php?id=%s' % (addon_id)
        extras.Open_URL(incremental)
        Dependency_Install(name,addon_id)
        xbmc.executebuiltin( 'UpdateLocalAddons' )
        xbmc.executebuiltin( 'UpdateAddonRepos' )
        if repostatus == 0:
            dialog.ok(name+" Install Complete",'The add-on has been successfully installed but','there was an error installing the repository.','This will mean the add-on fails to update')
        if modulestatus == 0:
            dialog.ok(name+" Install Complete",'The add-on has been successfully installed but','there was an error installing modules.','This could result in errors with the add-on.')
        if modulestatus != 0 and repostatus != 0 and forum != '':
            dialog.ok(name+" Install Complete",'Please support the developer(s) [COLOR=dodgerblue]'+provider_name,'[/COLOR]Support for this add-on can be found at [COLOR=yellow]'+forum,'[/COLOR][CR]Remember to visit [COLOR=lime][B]www.totalxbmc.tv[/COLOR][/B] for all your Kodi needs.')
        if modulestatus != 0 and repostatus != 0 and forum == '':
            dialog.ok(name+" Install Complete",'Please support the developer(s) [COLOR=dodgerblue]'+provider_name,'[/COLOR]No details of forum support have been given but','we\'ll be happy to help at [COLOR=lime][B]www.totalxbmc.tv[/COLOR][/B]')
Example #14
0
    def buildChannel(self):
        self.log("buildChannel, chantype = " + str(self.chantype))
        self.chnlst = ChannelList()
        self.addonDirectoryPath = []
        
        if self.chantype == 0:
            self.setting1 = xbmc.translatePath(self.Path)
            self.channame = self.chnlst.getSmartPlaylistName(self.Path)
        
        elif self.chantype == 6:
            self.setting1 = self.Label
            self.setting2 = '4'
            self.channame = self.Label
            
        elif self.chantype == 7:
            self.setting1 = xbmc.translatePath(self.Path)
            self.setting3 = str(MEDIA_LIMIT)
            self.setting4 = '0'
            self.channame = self.Label
            
        elif self.chantype == 8: 
            xmltvFle = xmltvflePath(listXMLTV())
            if self.Path.startswith('plugin://plugin.video.ustvnow'):
                self.Label = self.Label.split(' - ')[0]
                dname = "USTVnow - "+self.Label
            else:
                dname = self.Label
                
            self.channame, self.setting1 = self.chnlst.findZap2itID(dname, xmltvFle)
            self.channame = self.Label+" USTV"
            self.setting2 = self.Path
                
        elif self.chantype == 9:
            self.setting1 = '5400'
            self.setting2 = self.Path
            self.setting3 = self.Label
            self.setting4 = self.Description
            self.channame = self.Label +' - '+ self.AddonName
            
        elif self.chantype == 10:
            if self.YTtype == 1:
                self.setting1 = ((self.Path).replace('plugin://plugin.video.youtube/channel/','')).replace('/','')
            elif self.YTtype == 2:
                self.setting1 = ((self.Path).replace('plugin://plugin.video.','').replace('youtube/playlist/','').replace('spotitube/?limit&mode=listyoutubeplaylist&type=browse&url=','')).replace('/','')

            self.setting2 = str(self.YTtype)
            self.setting3 = str(MEDIA_LIMIT)
            self.setting4 = '0'
            self.channame = self.Label
            
        elif self.chantype == 15:
            self.setting1 = self.Path
            self.setting2 = ''
            self.setting3 = str(MEDIA_LIMIT)
            self.setting4 = '0'
            self.channame = self.Label +' - '+ self.AddonName
            
        self.saveSettings()
        if dlg.yesno("PseudoTV Live", 'Channel Successfully Added', 'Open Channel Manager?'):
            xbmc.executebuiltin("RunScript("+ADDON_PATH+"/config.py, %s)" %str(self.channel))
Example #15
0
def save_strm(settings, nzbname, nzb):
    info = nfo.NfoLabels()
    info_labels = info.info_labels
    m_tvshow = Tvshow(info, settings.getSetting("strm_path_tvshow"),\
               settings.getSetting("lib_save_nfo_type_tvshow").lower(),\
               nzbname, nzb)
    m_movie = Movie(info, settings.getSetting("strm_path_movie"),\
               settings.getSetting("lib_save_nfo_type_movie").lower(),\
               (settings.getSetting("lib_save_nfo_poster").lower() == "true"),\
               (settings.getSetting("lib_save_nfo_fanart").lower() == "true"),\
               nzbname, nzb)
    if 'code' in info_labels and not 'rageid' in info_labels and not 'tvdb-show' in info_labels:
        m_movie.save()
        time.sleep(3)
        xbmc.executebuiltin('UpdateLibrary(video,' + xbmc.translatePath(m_movie.strm_path_movie) + ')')
    elif 'rageid' in info_labels:
        m_tvshow.set_rageid(info_labels['rageid'])
        m_tvshow.save()
        time.sleep(3)
        xbmc.executebuiltin('UpdateLibrary(video,' + xbmc.translatePath(m_tvshow.strm_path) + ')')
    else:
        # Ask what to do and how to save
        type = xbmcgui.Dialog().select('Select library type', ['Movie', 'TV-Show'])
        if type == 1:
            m_tvshow.save()
            time.sleep(3)
            xbmc.executebuiltin('UpdateLibrary(video,' + xbmc.translatePath(m_tvshow.strm_path) + ')')
        else:
            m_movie.save()
            time.sleep(3)
            xbmc.executebuiltin('UpdateLibrary(video,' + xbmc.translatePath(m_movie.strm_path_movie) + ')')
    return
Example #16
0
def INSTALL1():
        dialog = xbmcgui.Dialog()      
        dp = xbmcgui.DialogProgress()
        dp.create("TinyOS First Run","Installing Files",'', 'Please Wait')
        
        ### Extract Files ###
        keyword      =  'update-DEMO'
        src = FILES+keyword+'.zip'
        path         =  xbmc.translatePath(os.path.join('special://home/addons','packages'))
        lib          =  os.path.join(path, keyword+'.zip')
        addonfolder  =  xbmc.translatePath(os.path.join('special://home',''))
	shutil.copy2(src, path)
        dp.update(0,"", "Extracting Zip... Please Wait")
        extract.all(lib,addonfolder,dp)
        
        ### Setup Home dir ###
        dp.update(70,"", "Setting up folders... Please Wait")
        
        #Link to External Media 
        if not os.path.exists('/root/ExternalDevices'):
            ln = "ln -s /media/ /root/ExternalDevices"
            subprocess.check_output(ln, shell=True)
        
	### Restart XBMC ###
        dp.update(100,"", "Reloading XBMC")
	time.sleep(3)
	xbmc.executebuiltin('RestartApp')
Example #17
0
def RefreshIPTVlinks():
	iptvAddon = GetIptvAddon()
	if iptvAddon == None:
		return None

	#xbmc.executebuiltin("XBMC.Notification(ISRALIVE, Updating links..., {1}, {2})".format('', 10000 ,icon))

	markedLists = GetMarkedLists()
	markedListsFilename = os.path.join(xbmc.translatePath("special://userdata/addon_data"), AddonID, "lists", "markedLists.txt") 
	
	with open(markedListsFilename, 'w') as outfile:
		json.dump(markedLists, outfile) 
	outfile.close()
	
	isIptvAddonGotham = iptvAddon.getAddonInfo('version')  >= "1.9.3"
	finalList = MakeFinalList(markedLists)
	finalM3Ulist = MakeM3U(finalList, isIptvAddonGotham)
	finalM3Ufilename = os.path.join(addon_data_dir, 'iptv.m3u') # The final m3u file. (static + filmon links)
	f = open(finalM3Ufilename, 'w') # make the finnal m3u list (this file will used in IPTVSimple)
	f.write(finalM3Ulist)
	f.close()

	dlg = xbmcgui.Dialog()
	dlg.ok('ISRAELIVE', 'Links updated.', "Please restart XBMC or PVR db.")
	
	if os.path.exists(xbmc.translatePath( "special://userdata/addon_data/pvr.iptvsimple")):
		DeleteCache()
		
	UpdateIPTVSimpleSettings(iptvAddon)
Example #18
0
def add2lib( url, name, infol, img, fanart, year ):

    img = 'http://oi62.tinypic.com/dvgj1t.jpg'
    addon.log('Add To Library %s , %s, %s' % (name,year,url))

    path = xbmc.translatePath( addon.get_setting('movie-folder') )
    string = 'plugin://plugin.video.mutttsnutz/?mode=playstream&url='+url+'&name='+name+'&infol='
    filename = '%s.strm' % name
    path = xbmc.makeLegalFilename( xbmc.translatePath(os.path.join( path, name, filename )))

    if not xbmcvfs.exists(os.path.dirname(path)):
        try:
            try: xbmcvfs.mkdirs(os.path.dirname(path))
            except: os.mkdir(os.path.dirname(path))
        except:
            addon.log('FAILED to create directory')

    if xbmcvfs.exists(path):
        addon.log( name+' Already in the library' )
        notification( addon.get_name()+' allready added', name, img)
        return
    
    notification( addon.get_name()+' adding to library', name+' adding to library', img)
    strm = xbmcvfs.File(path, 'w')
    strm.write(string)
    strm.close()
    xbmc.executebuiltin("UpdateLibrary(video)")
Example #19
0
def Transform():
    if addon.get_setting('transform') == 'true':
        return
    if xbmcvfs.exists(xbmc.translatePath('special://masterprofile/sources.xml')):
        with open(xbmc.translatePath(os.path.join( addon.get_path(), 'resources', 'sourcesapp.xml'))) as f:
            sourcesapp = f.read()
            f.close()
        with open(xbmc.translatePath('special://masterprofile/sources.xml'), 'r+') as f:
            my_file = f.read()
            if re.search(r'http://transform.mega-tron.tv/', my_file):
                addon.log('Transform Source Found in sources.xml, Not adding.')
                return
            addon.log('Adding Transform source in sources.xml')
            my_file = re.split(r'</files>\n</sources>\n', my_file)
            my_file = my_file[0]+sourcesapp
            f.seek(0)
            f.truncate()
            f.write(my_file)
            f.close()
            Addon.setSetting(id='transform', value='true')
            

    else:
        xbmcvfs.copy(xbmc.translatePath(os.path.join( addon.get_path(), 'resources', 'sources.xml')),
                       xbmc.translatePath('special://masterprofile/sources.xml'))
        Addon.setSetting(id='transform', value='true')
Example #20
0
	def getImagePath(self, path):
		# special infolabel distrologo present
		if path.lower() == '$info[distrologo]':
			logo = self.distro.lower() + '.png'
			imagepath = os.path.join(__media__, logo)
			if not os.path.isfile(imagepath):
				imagepath = os.path.join(__media__, 'kodi.png')
		# special infolabel from kodi present
		elif path.lower().find('$info') >= 0:
			imagepath = path
		# full path to the image given
		elif os.path.isfile(path):
			imagepath = path
		# look for the image in addons __media__ dir
		elif os.path.isfile(os.path.join(__media__, path)):
			imagepath = os.path.join(__media__, path)
		# look for the image in libreelec's storage dir
		elif os.path.isfile(os.path.join('/storage/', path)):
			imagepath = os.path.join('/storage/', path)
		# look for the image in kodi's configuration dir
		elif os.path.isfile(os.path.join(xbmc.translatePath('special://home'), path)):
			imagepath = os.path.join(xbmc.translatePath('special://home'), path)
		# if image could not be found, set path to error.png
		else:
			imagepath = os.path.join(__media__, 'error.png')

		return imagepath
    def _walk(self, path, recursive, types):
        filenames = []
        dirnames = []
        dirs = []
        files = []

        path = xbmc.translatePath(path)

        if xbmcvfs.exists(xbmc.translatePath(path)) or re.match(r"[a-zA-Z]:\\", path) is not None:
            subdirs, files = xbmcvfs.listdir(path)
            for dir in subdirs:
                dirnames.append(os.path.join(path, dir))

            for file in files:
                if types is not None:
                    if os.path.splitext(file)[1].upper() in types or os.path.splitext(file)[1].lower() in types:
                        filenames.append(os.path.join(path, file))
                else:
                    filenames.append(os.path.join(path, file))

            if recursive:
                for item in subdirs:
                    dirnames1, filenames1 = self._walk(os.path.join(path, item), recursive, types)
                    for item in dirnames1:
                        dirnames.append(item)
                    for item in filenames1:
                        filenames.append(item)

        return dirnames, filenames
def autopatch():
    xbmc.log('script.pseudotv.live-donordownload: autopatch')
    MSG = 'Donor Autoupdate Complete'
    
    try:
        os.remove(xbmc.translatePath(DL_DonorPath))
    except:
        pass
        
    try:
        os.remove(xbmc.translatePath(DonorPath))  
    except:
        pass
        
    try:
        urllib.urlretrieve(DonorURLPath, (xbmc.translatePath(DL_DonorPath)))
        xbmc.log('script.pseudotv.live-donordownload: autopatch, Downloading DL_DonorPath')   
        if xbmcvfs.exists(DL_DonorPath):
            REAL_SETTINGS.setSetting("AT_Donor", "true")
            REAL_SETTINGS.setSetting("COM_Donor", "true")
            REAL_SETTINGS.setSetting("TRL_Donor", "true")
            REAL_SETTINGS.setSetting("CAT_Donor", "true")
            if REAL_SETTINGS.getSetting('AT_Donor') and REAL_SETTINGS.getSetting('COM_Donor') and REAL_SETTINGS.getSetting('TRL_Donor') and REAL_SETTINGS.getSetting('CAT_Donor'):
                xbmc.log('script.pseudotv.live-donordownload: autopatch, Settings.xml Patched')
                xbmc.executebuiltin("Notification( %s, %s, %d, %s)" % ("PseudoTV Live", MSG, 1000, THUMB) ) 
    except:
        pass
def LogoDownloader():
    xbmc.log('script.pseudotv.live-donordownload: LogoDownloader')
    
    LogoPath = xbmc.translatePath(os.path.join(SETTINGS_LOC))
    
    if dlg.yesno("PseudoTV Live", "Download Color Logos or No, Download Mono Logos", ""):
        LogoDEST = LogoPath + '/PTVL_Color.zip'
        i = 1
    else:
        LogoDEST = LogoPath + '/PTVL_Mono.zip'
        i = 2

    if not DEFAULT_LOGO_LOC:
        os.makedirs(DEFAULT_LOGO_LOC)
        
    try:
        os.remove(xbmc.translatePath(LinkPath))
    except:
        pass
         
    try:
        urllib.urlretrieve(LinkURLPath, (xbmc.translatePath(LinkPath)))
        f = FileAccess.open((xbmc.translatePath(LinkPath)), "r")
        linesLST = f.readlines()
        LogoURLPath = linesLST[i] 
        download(LogoURLPath, LogoDEST)
        all(LogoDEST, LogoPath)
        REAL_SETTINGS.setSetting("ChannelLogoFolder", DEFAULT_LOGO_LOC)
        os.remove(LogoDEST)
    except:
        pass
        
    REAL_SETTINGS.openSettings()
Example #24
0
def ADDONINSTALL(name,url,description,filetype):
  path=xbmc.translatePath(os.path.join('special://home/addons','packages'))
  confirm=xbmcgui.Dialog().yesno("ATTENTION!!","                By Clicking 'YES' you agree to allow this Addon","                 Access to add repositories and other addons              ","                    ")
  
  if confirm: 
        dp=xbmcgui.DialogProgress()
        dp.create("ATTENTION:","Downloading ",'','Please Wait')
        lib=os.path.join(path,name+'.zip')
        try: os.remove(lib)
        except: pass
        downloader.download(url, lib, dp)
        if filetype == 'addon':
            addonfolder = xbmc.translatePath(os.path.join('special://','home/addons'))
        elif filetype == 'media':
             addonfolder = xbmc.translatePath(os.path.join('special://','home'))    
  ##attempt Shortcuts
        elif filetype == 'main':
             addonfolder = xbmc.translatePath(os.path.join('special://','home'))
        time.sleep(2)
        dp.update(0,"","Extracting Zip Please Wait")
        print '======================================='
        print addonfolder
        print '======================================='
        extract.all(lib,addonfolder,dp)
        dialog=xbmcgui.Dialog()
        dialog.ok("Success!","Please Reboot To Take Effect","    Brought To You By BLAZETAMER ")
  else:
      return
Example #25
0
    def setup(self):
        #create authorization helper and load default settings
        gauth = GoogleAuth(xbmc.validatePath(xbmc.translatePath(utils.addon_dir() + '/resources/lib/pydrive/settings.yaml')))
        gauth.LoadClientConfigSettings()
        
        #check if this user is already authorized
        if(not xbmcvfs.exists(xbmc.translatePath(utils.data_dir() + "google_drive.dat"))):
            settings = {"client_id":self.CLIENT_ID,'client_secret':self.CLIENT_SECRET}
    
            drive_url = gauth.GetAuthUrl(settings)
    
            utils.log("Google Drive Authorize URL: " + drive_url)

            code = xbmcgui.Dialog().input('Google Drive Validation Code','Input the Validation code after authorizing this app')

            gauth.Auth(code)
            gauth.SaveCredentialsFile(xbmc.validatePath(xbmc.translatePath(utils.data_dir() + 'google_drive.dat')))
        else:
            gauth.LoadCredentialsFile(xbmc.validatePath(xbmc.translatePath(utils.data_dir() + 'google_drive.dat')))
    
        #create the drive object
        self.drive = GoogleDrive(gauth)
        
        #make sure we have the folder we need
        xbmc_folder = self._getGoogleFile(self.root_path)
        print xbmc_folder
        if(xbmc_folder == None):
            self.mkdir(self.root_path)
Example #26
0
 def get_delete_list(self):
     results = []
     try:
         folder = os.listdir(xbmc.translatePath('special://database/'))
         for database in folder:
             if database.startswith('MyVideos') and database.endswith('.db'):                    
                 con = sqlite3.connect(xbmc.translatePath('special://database/' + database))
                 cur = con.cursor()
                 
                 query = "attach database '" + addon_db + "' as addon"
                 cur.execute(query)
          
                 query = "select tvshow.idShow,tvshow.c00 as showname , autoDelete from tvshow "
                 query += " left outer join addon.tvshowsettings on addon.tvshowsettings.idShow = tvshow.idShow"
                 
                 if self.tv_default == 'delete':
                     query += " where tvshow.idShow not in (select idShow from addon.tvshowsettings  where autoDelete = 0)"
                 else:
                     query += " where tvshow.idShow in (select idShow from addon.tvshowsettings  where autoDelete = 1)"
                 
                 
                 self.debug("Executing query on %s: %s" % (addon_db, query))
                 cur.execute(query)
                         
                 self.debug("Executing " + str(query))
                 cur.execute(query)
                 #ex = cur.fetchone()[0]
                 results = cur.fetchall()
                 return results
     
     except OSError, e:
         self.debug("Something went wrong while opening the database folder (errno: %d)" % e.errno)
         raise
Example #27
0
 def doFunction(self, url):
     func = url[0:2]
     url = url[2:]
     if func == 'DP':
         isrc, pid = url.split('pid',1)
         self.updateList(pid = pid, token = None, cmd = 'DELITEM', isrc = isrc)
     elif func == 'AP':
         token, uid = self.getAutho(getMe = True)
         html = self.getRequest(VEVOAPI + ('/user/%s/playlists?token=%s' % (uid,token)))
         a = json.loads(html)
         ilist=[]
         nlist=[]
         for b in a:
             nlist.append(b['name'])
             ilist.append(b['playlistId'])
         dialog = xbmcgui.Dialog()
         choice = dialog.select('Choose a playlist', nlist)
         pid = ilist[choice]
         self.updateList(pid = pid, token = token, cmd = 'ADDITEM', isrc = url)
     elif func == 'AL':
         artist = xbmc.getInfoLabel('ListItem.Artist').split('/',1)[0]
         artist = artist.replace(':','').replace('-','').replace('?','%3F')
         title = xbmc.getInfoLabel('ListItem.Title').split('(',1)[0]
         title = title.replace(':','').replace('-','').replace('?','%3F')
         name = artist.strip() + ' - ' + title.strip()
         profile = self.addon.getAddonInfo('profile').decode(UTF8)
         videosDir  = xbmc.translatePath(os.path.join(profile,'Videos'))
         videoDir  = xbmc.translatePath(os.path.join(videosDir, name))
         if not os.path.isdir(videoDir):
             os.makedirs(videoDir)
         strmFile = xbmc.translatePath(os.path.join(videoDir, name+'.strm'))
         with open(strmFile, 'w') as outfile:
             outfile.write('%s?mode=GV&url=%s' %(sys.argv[0], url))
         json_cmd = '{"jsonrpc":"2.0","method":"VideoLibrary.Scan", "params": {"directory":"%s/"},"id":1}' % videoDir.replace('\\','/')
         jsonRespond = xbmc.executeJSONRPC(json_cmd)
def CEDownloader():
    xbmc.log('script.pseudotv.live-donordownload: CEDownloader')

    CEURL = (BaseURL + 'CEURL.txt')
    CEDEST = xbmc.translatePath(os.path.join(SETTINGS_LOC, 'PTVL_Cinema_Experience_Pack.zip'))
    CEPath = xbmc.translatePath(os.path.join(SETTINGS_LOC))

    if dlg.yesno("PseudoTV Live", "Download Cinema Experience Pack", ""):
        
        try:
            os.remove(xbmc.translatePath(LinkPath))
        except:
            pass
            
        try:
            urllib.urlretrieve(LinkURLPath, (xbmc.translatePath(LinkPath)))
            f = FileAccess.open((xbmc.translatePath(LinkPath)), "r")
            linesLST = f.readlines()
            CEURLPath = linesLST[3]
            
            download(CEURLPath, CEDEST)
            all(CEDEST, CEPath)
            
            if xbmcvfs.exists(CE_LOC):
                REAL_SETTINGS.setSetting("CinemaPack", "true")
            else:
                REAL_SETTINGS.setSetting("CinemaPack", "false")

            os.remove(CEDEST)
        except:
            pass  
            
            REAL_SETTINGS.openSettings()
    else:
        REAL_SETTINGS.openSettings()
Example #29
0
def DEPENDINSTALL(name,url,description,filetype,repourl):
        #Split Script Depends============================
        files=url.split('/'); dependname=files[-1:]; dependname=str(dependname); 
        dependname=dependname.replace('[','').replace(']','').replace('"','').replace('[','').replace("'",'').replace(".zip",''); 
        #StoprSplit======================================
        path=xbmc.translatePath(os.path.join('special://home','addons','packages')); dp=xbmcgui.DialogProgress(); 
        dp.create("Configuring Requirments:","Downloading and ",'','Installing '+name); 
        lib=os.path.join(path,name+'.zip'); 
        try: os.remove(lib)
        except: pass
        downloader.download(url,lib,dp)
        if filetype=='addon': addonfolder=xbmc.translatePath(os.path.join('special://','home','addons'))
        time.sleep(2)
        #dp.update(0,"","Installing selections.....")
        print '======================================='; print addonfolder; print '======================================='
        extract.all(lib,addonfolder,'')
        #Start Script Depend Search==================================================================
        depends=xbmc.translatePath(os.path.join('special://home','addons',dependname,'addon.xml')); 
        source=open(depends,mode='r'); link=source.read(); source.close(); 
        dmatch=re.compile('import addon="(.+?)"').findall(link)
        for requires in dmatch:
            if not 'xbmc.python' in requires:
                print 'Script Requires --- '+requires; 
                dependspath=xbmc.translatePath(os.path.join('special://home','addons',requires))
                #if not os.path.exists(dependspath): DEPENDINSTALL(requires,'http://addonrepo.com/xbmchub/depends/'+requires+'.zip','','addon','none')
                if not os.path.exists(dependspath): DEPENDINSTALL(requires,tribeca_url2+'maintenance/modules/'+requires+'.zip','','addon','none')
Example #30
0
 def _init_vars( self ):
     self.WINDOW = xbmcgui.Window( int(self.WINDOWID) )
     self.WINDOW.clearProperty( "ArtistSlideshow.CleanupComplete" )
     if( self.ARTISTFIELD == '' ):
         self.SKINARTIST = ''
     else:
         self.SKINARTIST = "Window(%s).Property(%s)" % ( self.WINDOWID, self.ARTISTFIELD )
     if( self.TITLEFIELD == '' ):
         self.SKINTITLE = ''
     else:
         self.SKINTITLE = "Window(%s).Property(%s)" % ( self.WINDOWID, self.TITLEFIELD )
     self.ARTISTSLIDESHOW = "Window(%s).Property(%s)" % ( self.WINDOWID, "ArtistSlideshow" )
     self.ARTISTSLIDESHOWRUNNING = "Window(%s).Property(%s)" % ( self.WINDOWID, "ArtistSlideshowRunning" )
     self.EXTERNALCALL = "Window(%s).Property(%s)" % ( self.WINDOWID, "ArtistSlideshow.ExternalCall" )
     self.EXTERNALCALLSTATUS = xbmc.getInfoLabel( self.EXTERNALCALL )
     log( 'external call is set to ' + xbmc.getInfoLabel( self.EXTERNALCALL ) )
     self.NAME = ''
     self.ALLARTISTS = []
     self.LocalImagesFound = False
     self.CachedImagesFound = False
     self.ImageDownloaded = False
     self.DownloadedAllImages = False
     self.UsingFallback = False
     self.BlankDir = xbmc.translatePath('special://profile/addon_data/%s/transition' % __addonname__ )
     self.MergeDir = xbmc.translatePath('special://profile/addon_data/%s/merge' % __addonname__ )    
     self.InitDir = xbmc.translatePath('%s/resources/black' % __addonpath__ )
     LastfmApiKey = 'fbd57a1baddb983d1848a939665310f6'
     HtbackdropsApiKey = '96d681ea0dcb07ad9d27a347e64b652a'
     self.LastfmURL = 'http://ws.audioscrobbler.com/2.0/?autocorrect=1&api_key=' + LastfmApiKey
     self.HtbackdropsQueryURL = 'http://htbackdrops.com/api/' + HtbackdropsApiKey + '/searchXML?default_operator=and&fields=title&aid=1'
     self.HtbackdropsDownloadURL = 'http://htbackdrops.com/api/' + HtbackdropsApiKey + '/download/'
Example #31
0
import livegames
import json


import pyxbmct.addonwindow as pyxbmct
from addon.common.addon import Addon

dialog = xbmcgui.Dialog()

apikey = 'AIzaSyA20yLuOaZeeMPmLdV9H2LiHIWAp2lFafc'

#############################################################
#################### SET ADDON ID ###########################
_addon_id_	= 'plugin.video.neverwalkalone'
_self_			= xbmcaddon.Addon(id=_addon_id_)
icon  = xbmc.translatePath(os.path.join('special://home/addons/' + _addon_id_, 'icon.png'))

#############################################################
#################### SET ADDON THEME DIRECTORY ##############
_theme_			= _self_.getSetting('Theme')
_images_		= '/resources/' + _theme_	

#############################################################
#################### SET ADDON THEME IMAGES #################
Background_Image	= xbmc.translatePath(os.path.join('special://home/addons/' + _addon_id_ + _images_, 'lfclist.jpg'))
Listbg = xbmc.translatePath(os.path.join('special://home/addons/' + _addon_id_ + _images_, 'listbg.png'))
Addon_Image = xbmc.translatePath(os.path.join('special://home/addons/' + _addon_id_ + _images_, 'addon.png'))


########## Function To Call That Starts The Window ##########
def listwindow(ta):
Example #32
0
import threading,xbmc,xbmcplugin,xbmcgui,re,os,xbmcaddon,sys
import shutil,plugintools,installer
import zipfile
import urlparse
import urllib,urllib2,json
import common,xbmcvfs,downloader,extract
import datetime
import base64, time
import unicodedata
from datetime import datetime
from datetime import timedelta
import maintenance
AddonID = 'plugin.video.playklub'
AddonTitle = 'Rising Phoenix'
Images=xbmc.translatePath(os.path.join('special://home','addons',AddonID,'resources/art/'));
fanart = Images+'fanart.jpg'
icon = Images+'icon.png'
FabAddon = xbmcaddon.Addon('plugin.video.playklub')
ADDON=xbmcaddon.Addon(id='plugin.video.playklub')
dialog       =  xbmcgui.Dialog()
dialogprocess =  xbmcgui.DialogProgress()
USERDATA     =  xbmc.translatePath(os.path.join('special://home/userdata/',''))
FabData      =  xbmc.translatePath(os.path.join('special://home/userdata/addon_data/plugin.video.playklub/',''))
HOME         =  xbmc.translatePath('special://home/')
Username=plugintools.get_setting("Username")
Password=plugintools.get_setting("Password")
PVRon = plugintools.get_setting("PVRUpdater")
#lehekylg= base64.b64decode("aHR0cDovL3JhbmRvbXNlcnZlci5zaXRl")
#pordinumber="2086"
lehekylg= base64.b64decode("aHR0cDovL2hvc3RlbmdpbmUubGl2ZQ==")
pordinumber="25461"
Example #33
0
# Global variables
settings = xbmcaddon.Addon(id=__addon_id__)
show_scores = json.loads(settings.getSetting(id="scores"))
debug = json.loads(settings.getSetting(id="debug"))
use_cached_thumbnails = json.loads(settings.getSetting(id="cached_thumbnails"))
use_local_timezone = json.loads(settings.getSetting(id="local_timezone"))
show_cameras = json.loads(settings.getSetting(id="cameras"))
useragent = "iTunes-AppleTV/4.1"

cache = StorageServer.StorageServer("nbaleaguepass", 1)
cache.table_name = "nbaleaguepass"

cookies = ''
player_id = binascii.b2a_hex(os.urandom(16))
addon_dir = xbmc.translatePath(settings.getAddonInfo('path')).decode('utf-8')

# the default fanart image
fanart_image = os.path.join(addon_dir, "fanart.jpg")
setting_fanart_image = settings.getSetting("fanart_image")
if setting_fanart_image != '':
    fanart_image = setting_fanart_image

try:
    config_path = os.path.join(addon_dir, "config", "config.json")
    config_json = open(config_path).read()
    config = json.loads(config_json)
except:
    root_path = os.path.dirname(os.path.realpath(__file__))
    config_path = os.path.join(root_path, "..", "config", "config.json")
    config_json = open(config_path).read()
Example #34
0
import urllib
import urllib2,json
import xbmcvfs
import requests,time
import os,xbmc,xbmcaddon,xbmcgui,re
addon = xbmcaddon.Addon('plugin.video.live.BES-IPTV')
profile = xbmc.translatePath(addon.getAddonInfo('profile').decode('utf-8'))
cacheDir = os.path.join(profile, 'cachedir')
clean_cache=os.path.join(cacheDir,'cleancacheafter1month')
headers=dict({'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; rv:32.0) Gecko/20100101 Firefox/32.0'})

if not cacheDir.startswith(('smb://', 'nfs://', 'upnp://', 'ftp://')) and not os.path.isdir(cacheDir):
    os.mkdir(cacheDir)
if xbmcvfs.exists(clean_cache) and (time.time()-os.path.getmtime(clean_cache) > 60*60*24*30):
    print 'time of creation of ff',str(time.time()-os.path.getmtime(clean_cache))
    import shutil
    shutil.rmtree(cacheDir)    
else:
    with open(clean_cache,'w') as f:
        f.write('') 
utubeid  = 'www.youtube.*?v(?:=|%3D)([0-9A-Za-z_-]{11})'
def YoUTube(page_data,youtube=None,duration=None,max_page=20,nosave=None):
    pDialog = xbmcgui.DialogProgress()
    pDialog.create('Updating list', 'Downloading ...') 
    base_yt_url  ='http://gdata.youtube.com/feeds/api'
    if 'search' in page_data:
        youtube = youtube.replace(' ','+')#Lana Del Rey
        build_url= base_yt_url + '/videos?q=%s&max-results=50&v=2&alt=json&orderby=published&start-index=%s'
        if  addon.getSetting('searchlongvideos') == 'true':            #duration: #medium or long
            build_url = base_yt_url + '/videos?q=%s&max-results=20&v=2&alt=json&duration=long&start-index=%s' 
      
Example #35
0
def check():

	xbmc.executebuiltin( "ActivateWindow(busydialog)" )

#######################################################################
#			Check for Pickle Updates
#######################################################################

	U_A = 'TheWizardIsHere'

	#Information for Pickle Tools Community OTA updates.
	if os.path.exists(COMMUNITY_VERSION):
		VERSIONCHECK = COMMUNITY_VERSION
		a=open(VERSIONCHECK).read()
		FIND_URL = re.compile('<update_url>(.+?)</update_url>').findall(a)[0]
		checkurl = re.compile('<version_check>(.+?)</version_check>').findall(a)[0]
		try:
			U_A = re.compile('<user_agent>(.+?)</user_agent>').findall(a)[0]
		except: pass
		pleasecheck = 1

	#Information for Pickle Tools OTA updates.
	if os.path.exists(PICKLE_VERSION):
		VERSIONCHECK = PICKLE_VERSION
		FIND_URL = BASEURL + base64.b64decode(b'YnVpbGRzL3VwZGF0ZV93aXoudHh0')
		checkurl = BASEURL + base64.b64decode(b'YnVpbGRzL3ZlcnNpb25fY2hlY2sudHh0')
		pleasecheck = 1

	if pleasecheck == 1:
		selected = 0
		dialog = xbmcgui.Dialog()
		a=open(VERSIONCHECK).read()
		build = re.compile('<build>(.+?)</build>').findall(a)[0]
		vernumber = re.compile('<version>(.+?)</version>').findall(a)[0]
		if vernumber > 0:
			req = urllib2.Request(checkurl)
			req.add_header('User-Agent',U_A)
			try:
				response = urllib2.urlopen(req)
			except:
				dialog.ok(ADDONTITLE,'Sorry we are unable to check for updates!','The update host appears to be down.','Please check for updates later via the wizard.')
				sys.exit(1)
				xbmc.executebuiltin( "Dialog.Close(busydialog)" )
			link=response.read()
			response.close()
			try:
				match = re.compile('<build>'+build+'</build><version>(.+?)</version><fresh>(.+?)</fresh><changelog>(.+?)</changelog>').findall(link)
				for newversion,fresh,CHANGE_LOG_URL in match:
					if newversion > vernumber:
						selected = 0
						while selected == 0:
							choice = dialog.select("[COLOR red][B]Found a new update for " + build + " - [/COLOR][COLOR blue]Version: " + newversion + "[/B][/COLOR]", ['[COLOR blue]View Change Log[/COLOR]','[COLOR blue]Install Version ' + newversion + '[/COLOR]','[COLOR blue]Update Later[/COLOR]'])
							if choice == 0:
								f = requests.get(CHANGE_LOG_URL)
								Common.TextBoxesPlain("%s" % f.text)
							elif choice == 1: 
								if fresh =='false': # TRUE
									updateurl = FIND_URL
									req = urllib2.Request(updateurl)
									req.add_header('User-Agent', U_A)
									try:
										response = urllib2.urlopen(req)
									except:
										dialog.ok(ADDONTITLE,'Sorry we were unable to download the update!','The update host appears to be down.','Please check for updates later via the wizard.')
										sys.exit(1)		
									xbmc.executebuiltin( "Dialog.Close(busydialog)" )
									link=response.read()
									response.close()
									match = re.compile('<build>'+build+'</build><url>(.+?)</url>').findall(link)
									for url in match:
										
										path = xbmc.translatePath(os.path.join('special://home/addons','packages'))
										name = "build"
										dp = xbmcgui.DialogProgress()

										dp.create(ADDONTITLE,"Downloading ",'', 'Please Wait')
										lib=os.path.join(path, name+'.zip')
										try:
											os.remove(lib)
										except:
											pass
										
										downloader.download(url, lib, dp)
										addonfolder = xbmc.translatePath(os.path.join('special://','home'))
										time.sleep(2)
										dp.update(0,"", "Extracting Zip Please Wait")
										print '======================================='
										print addonfolder
										print '======================================='
										extract.all_update(lib,addonfolder,dp)
										xbmc.executebuiltin( "Dialog.Close(busydialog)" )
										dialog = xbmcgui.Dialog()
										dialog.ok(ADDONTITLE, "Your build has succesfully been updated to the latest version.","Kodi must now force close to complete the update.")							
										selected = 1
										Common.KillKodi()
								else:
									dialog.ok('[COLOR lightskyblue]A WIPE is required for the update[/COLOR]','Select the [COLOR green]YES[/COLOR] option in the NEXT WINDOW to wipe now.','Select the [COLOR lightskyblue]NO[/COLOR] option in the NEXT WINDOW to update later.','[I][COLOR smokewhite]If you wish to update later you can do so in [/COLOR][COLOR ghostwhite]Pickle[/COLOR] [COLOR lightsteelblue]Tools[/COLOR][/I]')
									xbmc.executebuiltin( "Dialog.Close(busydialog)" )
									selected = 1
									wipe.FRESHSTART()
									sys.exit(1)
							else:
								xbmc.executebuiltin( "Dialog.Close(busydialog)" )
								selected = 1
								quit()
				else:
					xbmc.executebuiltin( "Dialog.Close(busydialog)" )
					dialog.ok(ADDONTITLE,'[COLOR ghostwhite]Your build is up to date.[/COLOR]', "[COLOR ghostwhite]Current Build: [/COLOR][COLOR smokewhite]" + build + "[/COLOR]", "[COLOR ghostwhite]Current Version: [/COLOR][COLOR smokewhite]" + newversion + "[/COLOR]")
					sys.exit(1)
			except:
				if selected == 1:
					quit()
				match = re.compile('<build>'+build+'</build><version>(.+?)</version><fresh>(.+?)</fresh>').findall(link)
				for newversion,fresh in match:
					if newversion > vernumber:
						choice = dialog.select("[COLOR red][B]Found a new update for the Build " + build + " Version: " + newversion + "[/B][/COLOR]", ['[COLOR blue]Install Version ' + newversion + '[/COLOR]','[COLOR blue]Update Later[/COLOR]'])
						if choice == 0: 
							if fresh =='false': # TRUE
								updateurl = FIND_URL
								req = urllib2.Request(updateurl)
								req.add_header('User-Agent', U_A)
								try:
									response = urllib2.urlopen(req)
								except:
									dialog.ok(ADDONTITLE,'Sorry we were unable to download the update!','The update host appears to be down.','Please check for updates later via the wizard.')
									sys.exit(1)
								xbmc.executebuiltin( "Dialog.Close(busydialog)" )
								link=response.read()
								response.close()
								match = re.compile('<build>'+build+'</build><url>(.+?)</url>').findall(link)
								for url in match:
									
									path = xbmc.translatePath(os.path.join('special://home/addons','packages'))
									name = "build"
									dp = xbmcgui.DialogProgress()

									dp.create(ADDONTITLE,"Downloading ",'', 'Please Wait')
									lib=os.path.join(path, name+'.zip')
									try:
										os.remove(lib)
									except:
										pass
									
									downloader.download(url, lib, dp)
									addonfolder = xbmc.translatePath(os.path.join('special://','home'))
									time.sleep(2)
									dp.update(0,"", "Extracting Zip Please Wait")
									print '======================================='
									print addonfolder
									print '======================================='
									extract.all_update(lib,addonfolder,dp)
									xbmc.executebuiltin( "Dialog.Close(busydialog)" )
									dialog = xbmcgui.Dialog()
									dialog.ok(ADDONTITLE, "Your build has succesfully been updated to the latest version.","Kodi must now force close to complete the update.")							
									Common.KillKodi()
							else:
								dialog.ok('[COLOR lightskyblue]A WIPE is required for the update[/COLOR]','Select the [COLOR green]YES[/COLOR] option in the NEXT WINDOW to wipe now.','Select the [COLOR lightskyblue]NO[/COLOR] option in the NEXT WINDOW to update later.','[I][COLOR smokewhite]If you wish to update later you can do so in [/COLOR][COLOR ghostwhite]Pickle[/COLOR] [COLOR lightsteelblue]Tools[/COLOR][/I]')
								xbmc.executebuiltin( "Dialog.Close(busydialog)" )
								wipe.FRESHSTART()
								sys.exit(1)		
						else:
							xbmc.executebuiltin( "Dialog.Close(busydialog)" )
							sys.exit(1)		
				else:
					xbmc.executebuiltin( "Dialog.Close(busydialog)" )
					dialog.ok(ADDONTITLE,'[COLOR ghostwhite]Your build is up to date.[/COLOR]', "[COLOR ghostwhite]Current Build: [/COLOR][COLOR smokewhite]" + build + "[/COLOR]", "[COLOR ghostwhite]Current Version: [/COLOR][COLOR smokewhite]" + newversion + "[/COLOR]")
					sys.exit(1)

	#LAST LINE OF UPDATES
	xbmc.executebuiltin( "Dialog.Close(busydialog)" )
	dialog.ok(ADDONTITLE,'[COLOR ghostwhite]An unknown error occurred.[/COLOR]')
Example #36
0
import plugintools
import downloader
import time
import requests
from resources.lib.modules import common as Common
from resources.lib.modules import wipe
from urllib import FancyURLopener

class MyOpener(FancyURLopener):
	version = 'TheWizardIsHere'

myopener          = MyOpener()
urlretrieve       = MyOpener().retrieve
urlopen           = MyOpener().open
ADDONTITLE        = "[COLOR aqua]Pickle[/COLOR] [COLOR white]Tools[/COLOR]"
USERDATA          = xbmc.translatePath(os.path.join('special://home/userdata',''))
pickle_VERSION  = os.path.join(USERDATA,'pickle_build.txt')
COMMUNITY_VERSION = os.path.join(USERDATA,'pickle_community_ota.txt')
BASEURL           = base64.b64decode(b"aHR0cDovL2VjaG9jb2Rlci5jb20v")

dp = xbmcgui.DialogProgress()
dialog = xbmcgui.Dialog()

############################
###CHECK FOR UPDATES########
############################

def updateaddons():

	xbmc.executebuiltin( "ActivateWindow(busydialog)" )
	xbmc.executebuiltin('UpdateAddonRepos()')
Example #37
0
#                                                                              #
#  You should have received a copy of the GNU General Public License           #
#  along with XBMC; see the file COPYING.  If not, write to                    #
#  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.       #
#  http://www.gnu.org/copyleft/gpl.html                                        #
################################################################################

import zipfile, xbmcaddon, xbmc, uservar, sys, os, time
import wizard as wiz

ADDON_ID = uservar.ADDON_ID
ADDONTITLE = uservar.ADDONTITLE
COLOR1 = uservar.COLOR1
COLOR2 = uservar.COLOR2
ADDON = wiz.addonId(ADDON_ID)
HOME = xbmc.translatePath('special://home/')
USERDATA = os.path.join(HOME, 'userdata')
GUISETTINGS = os.path.join(USERDATA, 'guisettings.xml')
KEEPFAVS = wiz.getS('keepfavourites')
KEEPSOURCES = wiz.getS('keepsources')
KEEPPROFILES = wiz.getS('keepprofiles')
KEEPADVANCED = wiz.getS('keepadvanced')
KODIV = float(xbmc.getInfoLabel("System.BuildVersion")[:4])
LOGFILES = [
    'xbmc.log', 'xbmc.old.log', 'kodi.log', 'kodi.old.log', 'spmc.log',
    'spmc.old.log', 'tvmc.log', 'tvmc.old.log', 'Thumbs.db', '.DS_Store'
]
bad_files = [
    'onechannelcache.db', 'saltscache.db', 'saltscache.db-shm',
    'saltscache.db-wal', 'saltshd.lite.db', 'saltshd.lite.db-shm',
    'saltshd.lite.db-wal', 'queue.db', 'commoncache.db', 'access.log',
Example #38
0
import json, re, requests, os, traceback, urlparse
import koding
import xbmc, xbmcaddon, xbmcgui
from koding import route
from resources.lib.plugin import Plugin
from resources.lib.util import dom_parser
from resources.lib.util.context import get_context_items
from resources.lib.util.xml import JenItem, JenList, display_list
from unidecode import unidecode

CACHE_TIME = 10800  # change to wanted cache time in seconds

addon_fanart = xbmcaddon.Addon().getAddonInfo('fanart')
addon_icon = xbmcaddon.Addon().getAddonInfo('icon')
next_icon = os.path.join(
    xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('path')), 'resources',
    'media', 'next.png')

User_Agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'


class COBP(Plugin):
    name = "cobp"

    def process_item(self, item_xml):
        if "<cobp>" in item_xml:
            item = JenItem(item_xml)
            if "http" in item.get("cobp", ""):
                result_item = {
                    'label': item["title"],
                    'icon': item.get("thumbnail", addon_icon),
Example #39
0
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''
import urllib2, urllib, xbmcgui, xbmcplugin, xbmc, re, sys, os, urlresolver
ADDON_PATH = xbmc.translatePath(
    'special://home/addons/plugin.video.testpiece/')
ICON = ADDON_PATH + 'icon.png'
FANART = ADDON_PATH + 'fanart.jpg'
PATH = 'Testing'
VERSION = '0.0.1'
Dialog = xbmcgui.Dialog()
Base_Url = 'http://clairviusvideo.freeoda.com/'


def Main_Menu():
    OPEN = Open_Url('http://clairviusvideo.freeoda.com/movies.txt')
    Regex = re.compile(
        '<NAME>(.+?)</NAME><URL>(.+?)</URL><ICON>(.+?)</ICON><FANART>(.+?)</FANART><DESC>(.+?)</DESC>'
    ).findall(OPEN)
    for name, url, icon, fanart, desc in Regex:
        if 'php' in url:
Example #40
0
import xbmc
import time
import sys
import ast
import os

import replays

_url = sys.argv[0]
_handle = int(sys.argv[1])
addon_id = 'plugin.video.sports'
addon = xbmcaddon.Addon(id=addon_id)
addonname = addon.getAddonInfo('name')
icon = addon.getAddonInfo('icon')
path = 'special://home/addons/%s/' % addon_id
fanart = xbmc.translatePath(
    os.path.join(path, "resources/boxing/background.jpg"))


def get_url(**kwargs):
    kwargs = {
        k: unicode(v).encode('ascii', 'ignore')
        for k, v in kwargs.iteritems()
    }
    return '{0}?{1}'.format(_url, urlencode(kwargs))


def router(paramstring):
    params = dict(parse_qsl(sys.argv[2][1:]))
    params.pop('sport')
    if params:
        title = params.get('title')
import xbmc
import xbmcgui
import xbmcaddon
import json
import time
import sys
import colorsys
import os
import datetime
import math

__addon__ = xbmcaddon.Addon()
__cwd__ = __addon__.getAddonInfo('path')
__resource__ = xbmc.translatePath(os.path.join(__cwd__, 'resources', 'lib'))

sys.path.append(__resource__)

from settings import *
from tools import *

try:
    import requests
except ImportError:
    xbmc.log("ERROR: Could not locate required library requests")
    notify("Kodi Hue", "ERROR: Could not import Python requests")

xbmc.log("Kodi Hue service started, version: %s" % get_version())

capture = xbmc.RenderCapture()
fmt = capture.getImageFormat()
# BGRA or RGBA
Example #42
0
    def play(self, uri, item, subtitle=None, subtitle_provider=None):
        #
        torrent2http_options = {
            "uri": str(uri),
            # Files
            "download_path": xbmc.validatePath(xbmc.translatePath(__addon__.getSetting("download_path"))) or CACHE_DIR,
            "keep_files": __addon__.getSetting("keep_files") == 'true' and True or False,
            "keep_complete": __addon__.getSetting("keep_complete") == 'true' and True or False,
            "keep_incomplete": __addon__.getSetting("keep_incomplete") == 'true' and True or False,
            # Network
            "download_kbps": int(__addon__.getSetting("download_kbps")) or 0,
            "upload_kbps":  int(__addon__.getSetting("upload_kbps")) or 0,
            "connections_limit": int(__addon__.getSetting("connections_limit")) or 200,
            "encryption": int(__addon__.getSetting("encryption")) or 1,
            # Port
            "listen_port": int(__addon__.getSetting("listen_port")) or 6881,
            "use_random_port": __addon__.getSetting("use_random_port") == 'true' and True or False,
            # Peers
            "torrent_connect_boost": int(__addon__.getSetting("torrent_connect_boost")) or 50,
            "connection_speed": int(__addon__.getSetting("connection_speed")) or 50,
            "peer_connect_timeout": int(__addon__.getSetting("peer_connect_timeout")) or 15,
            "min_reconnect_time": int(__addon__.getSetting("min_reconnect_time")) or 60,
            "max_failcount": int(__addon__.getSetting("max_failcount")) or 3,
            # Features
            "enable_tcp": __addon__.getSetting("enable_tcp") == 'true' and False or True,
            "enable_dht": __addon__.getSetting("enable_dht") == 'true' and False or True,
            "enable_lsd": __addon__.getSetting("enable_lsd") == 'true' and False or True,
            "enable_utp": __addon__.getSetting("enable_utp") == 'true' and False or True,
            "enable_scrape": __addon__.getSetting("enable_scrape") == 'true' and True or False,
            "enable_upnp": __addon__.getSetting("enable_upnp") == 'true' and False or True,
            "enable_natpmp": __addon__.getSetting("enable_natpmp") == 'true' and False or True,
            # Additional
            "trackers": not __addon__.getSetting("trackers") == "" and __addon__.getSetting['trackers'].split(',') or None,
            "dht_routers": not __addon__.getSetting("dht_routers") == "" and __addon__.getSetting['dht_routers'].split(',') or None,
            # Log / Debug
            "log_stats": __addon__.getSetting("debug") == 'true' and True or False,
            "debug_alerts": __addon__.getSetting("debug_alerts") == 'true' and True or False,
            # Bin
            "binaries_path": os.path.join(RESOURCES_PATH, 'bin')
        }
        # List item
        self.item = item

        ###
        if torrent2http_options['download_kbps'] <= 0:
            torrent2http_options['download_kbps'] = None

        if torrent2http_options['upload_kbps'] <= 0:
            torrent2http_options['upload_kbps'] = None
        elif torrent2http_options['upload_kbps'] < 15:
            notify(__addon__.getLocalizedString(30313))
            torrent2http_options['upload_kbps'] = 15
            __addon__.setSetting('upload_kbps', '15')

        log('(Player) Start the torrent2http file', xbmc.LOGDEBUG)
        with closing(Engine(**torrent2http_options)) as engine:
            # Start engine and instruct torrent2http to begin download first file
            engine.start(0)

            log('(Player) Pre-Loading the movie', xbmc.LOGDEBUG)
            ready = False
            with closing(SafeDialogProgress(delay_create=0)) as dialog:
                dialog.create(self.item['info']['title'])
                dialog.update(self.progressed, *self._get_status_lines())

                file_id = None
                while not xbmc.abortRequested and not dialog.iscanceled():
                    xbmc.sleep(self.progressSleepTime)

                    # Get status
                    status = engine.status()
                    # Check if there is loading error and raise exception 
                    engine.check_torrent_error(status)

                    # We need a file id
                    if file_id is None:
                        # Get torrent files list, filtered by video file type only
                        files = engine.list(media_types=[MediaType.VIDEO])
                        if files is None:
                            continue
                        # Torrent has no video files
                        if not files:
                            raise AnErrorOccurred(30316)
                        # Select first matching file                    
                        file_id = files[0].index
                        file_status = files[0]

                    # Get file status
                    file_status = engine.file_status(file_id)
                    if not file_status:
                        continue

                    if status.state == State.DOWNLOADING:
                        self._calculate_progress(int(self.item['info'].get('duration', 0)), status, file_status)
                        if self.progressed >= 100:
                            ready = True
                            break
                        dialog.update(int(self.progressed), *self._get_status_lines(status))
                        continue

                    if status.state in [State.FINISHED, State.SEEDING]:
                        ready = True
                        break

                if ready:
                    log('(Player) Finished with pre-loading the movie', xbmc.LOGDEBUG)
                    # Download subtitle
                    if subtitle:
                        log('(Player) Download subtitle', xbmc.LOGDEBUG)
                        dialog.update(99, *[__addon__.getLocalizedString(30019), ' ', ' '])
                        path = file_status.save_path
                        subtitle = subtitle_provider.download(subtitle, os.path.dirname(path), ".".join([os.path.splitext(os.path.basename(path))[0], self.item['stream_info']['subtitle']['language']]))
                    dialog.update(100, *[__addon__.getLocalizedString(30020), ' ', ' '])
                elif xbmc.abortRequested or dialog.iscanceled():
                    log('(Player) Pre-Loading was canceled or interrupted', xbmc.LOGDEBUG)

            if ready:
                # Resolve URL to XBMC
                self.item.update({"path": file_status.url})

                # Starts the playback
                log('(Player) Start the playback', xbmc.LOGDEBUG)
                #xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, self.item)
                plugin.set_resolved_url(self.item)
                for _ in xrange(60):
                    if not self.isPlaying():
                        xbmc.sleep(1000)
                        continue

                    if subtitle:
                        log('(Player) Adds the subtitle to the player', xbmc.LOGDEBUG)
                        self.setSubtitles(subtitle)

                    # Wait for the playback to finish
                    log('(Player) Wait for the playback to finish', xbmc.LOGDEBUG)
                    with closing(OverlayText()) as self.overlay:
                        while not xbmc.abortRequested and self.isPlaying():
                            if self.overlay.isShowing():
                                self.overlay.setText("\n".join(self._get_status_lines(engine.status())))
                            xbmc.sleep(100)

                    log('(Player) Playback is finished', xbmc.LOGDEBUG)
                    if subtitle and torrent2http_options["keep_files"] == False and torrent2http_options["keep_complete"] == False and torrent2http_options["keep_incomplete"] == False:
                        # Delete subtitle
                        log('(Player) Delete subtitle', xbmc.LOGDEBUG)
                        subtitle_provider.remove(subtitle)
                    break
                else:
                    log('(Player) Playback is terminated due to timeout', xbmc.LOGERROR)
Example #43
0
def translate_path(path):
    return decode_utf8(xbmc.translatePath(path))
Example #44
0
# XBMC Modules
import xbmcaddon
import xbmc
import xbmcgui
import sys
import os
import threading

addonid = "script.module.osmcsetting.networking"
__addon__ = xbmcaddon.Addon(addonid)

# Custom modules
sys.path.append(
    xbmc.translatePath(
        os.path.join(
            xbmcaddon.Addon(addonid).getAddonInfo('path'), 'resources',
            'lib')))

# OSMC SETTING Modules
from networking_gui import networking_gui
import osmc_network
from osmc_advset_editor import AdvancedSettingsEditor

DIALOG = xbmcgui.Dialog()


def log(message):

    try:
        message = str(message)
    except UnicodeEncodeError:
Example #45
0
import urllib, urllib2, re, xbmcplugin, xbmcgui, xbmc, xbmcaddon, os, sys, time
import shutil
import time

#################################################
AddonID        = 'plugin.program.totalinstaller'
#################################################
dialog         =  xbmcgui.Dialog()
dp             =  xbmcgui.DialogProgress()
ADDON          =  xbmcaddon.Addon(id=AddonID)
ADDONDATA      =  xbmc.translatePath(os.path.join('special://home','userdata','addon_data'))
clean_cache    =  ADDON.getSetting('cleancache')
internetcheck  =  ADDON.getSetting('internetcheck')
cbnotifycheck  =  ADDON.getSetting('cbnotifycheck')
mynotifycheck  =  ADDON.getSetting('mynotifycheck')
idfile         =  os.path.join(ADDONDATA,AddonID,'id.xml')
TBSDATA        =  os.path.join(ADDONDATA,AddonID,'')
update_file    =  os.path.join(ADDONDATA,AddonID,'updating')

print'###### Community Portal Update Service ######'

if not os.path.exists(TBSDATA):
    os.makedirs(TBSDATA)

if not os.path.exists(idfile):
    localfile = open(idfile, mode='w+')
    localfile.write('id="None"\nname="None"')
    localfile.close()

if os.path.exists(os.path.join(TBSDATA,'scripts')):
	shutil.rmtree(os.path.join(TBSDATA,'scripts'))
Example #46
0
import time
import hashlib
import simplejson
import re
import threading
import datetime
import codecs
from functools import wraps

ADDON = xbmcaddon.Addon()
ADDON_ID = ADDON.getAddonInfo('id')
ADDON_ICON = ADDON.getAddonInfo('icon')
ADDON_NAME = ADDON.getAddonInfo('name')
ADDON_PATH = ADDON.getAddonInfo('path').decode("utf-8")
ADDON_VERSION = ADDON.getAddonInfo('version')
ADDON_DATA_PATH = xbmc.translatePath("special://profile/addon_data/%s" %
                                     ADDON_ID).decode("utf-8")
HOME = xbmcgui.Window(10000)
SETTING = ADDON.getSetting
debug_file = xbmc.translatePath(os.path.join('special://home/', 'debug.txt'))


def write(what, filelocation):
    fopen = open(filelocation, "w")
    fopen.write(what)
    fopen.close()


def LANG(label_id):
    if 31000 <= label_id <= 33000:
        return ADDON.getLocalizedString(label_id)
    else:
def addonPath(f,fe=''):
	return xbmc.translatePath(os.path.join(Config.path,f+fe))
Example #48
0
def log(message):
    xbmc.log(message)
    veces = xbmc.translatePath(
        'special://home/addons/script.module.requests/versions.txt')
Example #49
0
def video(video_id, title, thumb_url, is_episode, hide_movies, video_type,
          url):
    added = False
    director = ''
    genre = ''
    playcount = 0
    video_details = get.video_info(video_id)
    match = json.loads(video_details)['value']['videos'][video_id]
    if not title:
        title = match['title']
    year = match['releaseYear']
    if not thumb_url:
        try:
            thumb_url = match['boxarts']['_665x375']['jpg']['url']
        except Exception:
            try:
                thumb_url = match['boxarts']['_342x192']['jpg']['url']
            except Exception:
                thumb_url = utility.addon_fanart()
    mpaa = match['maturity']['rating']['value']
    duration = match['runtime']
    offset = match['bookmarkPosition']
    try:
        if (duration > 0 and float(offset) / float(duration)) >= 0.9:
            playcount = 1
    except Exception:
        pass
    type = match['summary']['type']
    if type == 'movie':
        video_type_temp = type
    else:
        video_type_temp = 'tv'
        if is_episode:
            type = 'episode'
        else:
            type = 'tvshow'
            duration = ''
    if utility.get_setting('use_tmdb') == 'true':
        year_temp = year
        title_temp = title
        if ' - ' in title_temp:
            title_temp = title_temp[title_temp.index(' - '):]
        filename = video_id + '.jpg'
        filename_none = video_id + '.none'
        cover_file = xbmc.translatePath(utility.cover_cache_dir() + filename)
        cover_file_none = xbmc.translatePath(utility.cover_cache_dir() +
                                             filename_none)
        if not (xbmcvfs.exists(cover_file) or xbmcvfs.exists(cover_file_none)):
            utility.log(
                'Downloading cover art. type: %s, video_id: %s, title: %s, year: %s'
                % (video_type_temp, video_id, title_temp, year_temp))
            get.cover(video_type_temp, video_id, title_temp, year_temp)
    description = match['details']['synopsis']
    try:
        director = match['details']['directors'][0]['name']
    except Exception:
        pass
    try:
        genre = match['details']['genres'][0]['name']
    except Exception:
        pass
    rating = match['userRating']['average']
    next_mode = 'play_video_main'
    if utility.get_setting('browse_tv_shows') == 'true' and type == 'tvshow':
        next_mode = 'list_seasons'
    if '/my-list' in url and video_type_temp == video_type:
        add.video(title,
                  video_id,
                  next_mode,
                  thumb_url,
                  type,
                  description,
                  duration,
                  year,
                  mpaa,
                  director,
                  genre,
                  rating,
                  playcount,
                  remove=True)
        added = True
    elif type == 'movie' and hide_movies:
        pass
    elif video_type_temp == video_type or video_type == 'both':
        add.video(title, video_id, next_mode, thumb_url, type, description,
                  duration, year, mpaa, director, genre, rating, playcount)
        added = True
    return added
def repox(repository,filename='',h="special://xbmc",a="addons"): 
	if len(filename)==0: return xbmc.validatePath(xbmc.translatePath(os.path.join(h,a,repository)))
	else: return xbmc.validatePath(xbmc.translatePath(os.path.join(h,a,repository,filename)))
Example #51
0
 def mkdir(self, directory):
     return xbmcvfs.mkdir(xbmc.translatePath(directory))
def art(f,fe=''): 
	fe1='.png'; fe2='.jpg'; fe3='.gif'; 
	if   fe1 in f: f=f.replace(fe1,''); fe=fe1; 
	elif fe2 in f: f=f.replace(fe2,''); fe=fe2; 
	elif fe3 in f: f=f.replace(fe3,''); fe=fe3; 
	return xbmc.translatePath(os.path.join(Config.artPath,f+fe))
Example #53
0
def add_sources(path):
    logger.info()
    from xml.dom import minidom

    SOURCES_PATH = xbmc.translatePath("special://userdata/sources.xml")

    if os.path.exists(SOURCES_PATH):
        xmldoc = minidom.parse(SOURCES_PATH)
    else:
        # Crear documento
        xmldoc = minidom.Document()
        nodo_sources = xmldoc.createElement("sources")

        for type in ['programs', 'video', 'music', 'picture', 'files']:
            nodo_type = xmldoc.createElement(type)
            element_default = xmldoc.createElement("default")
            element_default.setAttribute("pathversion", "1")
            nodo_type.appendChild(element_default)
            nodo_sources.appendChild(nodo_type)
        xmldoc.appendChild(nodo_sources)

    # Buscamos el nodo video
    nodo_video = xmldoc.childNodes[0].getElementsByTagName("video")[0]

    # Buscamos el path dentro de los nodos_path incluidos en el nodo_video
    nodos_paths = nodo_video.getElementsByTagName("path")
    list_path = [p.firstChild.data for p in nodos_paths]
    logger.debug(list_path)
    if path in list_path:
        logger.debug("La ruta %s ya esta en sources.xml" % path)
        return
    logger.debug("La ruta %s NO esta en sources.xml" % path)

    # Si llegamos aqui es por q el path no esta en sources.xml, asi q lo incluimos
    nodo_source = xmldoc.createElement("source")

    # Nodo <name>
    nodo_name = xmldoc.createElement("name")
    sep = os.sep
    if path.startswith("special://") or path.startswith("smb://"):
        sep = "/"
    name = path
    if path.endswith(sep):
        name = path[:-1]
    nodo_name.appendChild(xmldoc.createTextNode(name.rsplit(sep)[-1]))
    nodo_source.appendChild(nodo_name)

    # Nodo <path>
    nodo_path = xmldoc.createElement("path")
    nodo_path.setAttribute("pathversion", "1")
    nodo_path.appendChild(xmldoc.createTextNode(path))
    nodo_source.appendChild(nodo_path)

    # Nodo <allowsharing>
    nodo_allowsharing = xmldoc.createElement("allowsharing")
    nodo_allowsharing.appendChild(xmldoc.createTextNode('true'))
    nodo_source.appendChild(nodo_allowsharing)

    # Añadimos <source>  a <video>
    nodo_video.appendChild(nodo_source)

    # Guardamos los cambios
    filetools.write(SOURCES_PATH, '\n'.join([x for x in xmldoc.toprettyxml().encode("utf-8").splitlines() if x.strip()]))
Example #54
0
 def put(self, source, dest):
     return xbmcvfs.copy(xbmc.translatePath(source),
                         xbmc.translatePath(dest))
Example #55
0
def set_content(content_type, silent=False):
    """
    Procedimiento para auto-configurar la biblioteca de kodi con los valores por defecto
    @type content_type: str ('CINE' o 'SERIES')
    @param content_type: tipo de contenido para configurar, series o peliculas
    """
    if config.is_xbmc():
        continuar = True
        msg_text = ""
        librarypath = config.get_setting("librarypath")

        if content_type == 'CINE':
            if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'):
                if not silent:
                    # Preguntar si queremos instalar metadata.themoviedb.org
                    install = platformtools.dialog_yesno("The Movie Database",
                                                         "TheMovieDB non presente.",
                                                         "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.themoviedb.org
                        xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True)
                        logger.info("Instalado el Scraper de películas de TheMovieDB")
                    except:
                        pass

                continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'))
                if not continuar:
                    msg_text = "The Movie Database no instalado."

        else: # SERIES
            # Instalar The TVDB
            if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'):
                if not silent:
                    # Preguntar si queremos instalar metadata.tvdb.com
                    install = platformtools.dialog_yesno("The TVDB",
                                                         "The TVDB non presente.",
                                                         "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.tvdb.com
                        xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True)
                        logger.info("Instalado el Scraper de series de The TVDB")
                    except:
                        pass

                continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'))
                if not continuar:
                    msg_text = "The TVDB no instalado."

            # Instalar TheMovieDB
            if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
                continuar = False
                if not silent:
                    # Preguntar si queremos instalar metadata.tvshows.themoviedb.org
                    install = platformtools.dialog_yesno("The Movie Database",
                                                         "TheMovieDB non presente.",
                                                         "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.tvshows.themoviedb.org
                        # 1º Probar desde el repositorio ...
                        xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True)
                        if not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
                                # ...si no funciona descargar e instalar desde la web
                                url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip"
                                path_down = xbmc.translatePath(
                                    "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip")
                                path_unzip = xbmc.translatePath("special://home/addons/")
                                header = ("User-Agent",
                                          "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013")

                                from core import downloadtools
                                from core import ziptools

                                downloadtools.downloadfile(url, path_down, continuar=True, headers=[header])
                                unzipper = ziptools.ziptools()
                                unzipper.extract(path_down, path_unzip)
                                xbmc.executebuiltin('UpdateLocalAddons')

                        strSettings = '<settings>\n' \
                                      '    <setting id="fanart" value="true" />\n' \
                                      '    <setting id="keeporiginaltitle" value="false" />\n' \
                                      '    <setting id="language" value="it" />\n' \
                                      '</settings>'
                        path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml")
                        tv_themoviedb_addon_path = filetools.dirname(path_settings)
                        if not filetools.exists(tv_themoviedb_addon_path):
                            filetools.mkdir(tv_themoviedb_addon_path)
                        if filetools.write(path_settings,strSettings):
                            continuar = True

                    except:
                        pass

                continuar = (install and continuar)
                if not continuar:
                    msg_text = "The Movie Database non installato."

        idPath = 0
        idParentPath = 0
        if continuar:
            continuar = False

            # Buscamos el idPath
            sql = 'SELECT MAX(idPath) FROM path'
            nun_records, records = execute_sql_kodi(sql)
            if nun_records == 1:
                idPath = records[0][0] + 1

            sql_librarypath = librarypath
            if sql_librarypath.startswith("special://"):
                sql_librarypath = sql_librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/')
                sep = '/'
            elif sql_librarypath.startswith("smb://"):
                sep = '/'
            else:
                sep = os.sep

            if not sql_librarypath.endswith(sep):
                sql_librarypath += sep

            # Buscamos el idParentPath
            sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % sql_librarypath
            nun_records, records = execute_sql_kodi(sql)
            if nun_records == 1:
                idParentPath = records[0][0]
                librarypath = records[0][1][:-1]
                continuar = True
            else:
                # No existe librarypath en la BD: la insertamos
                sql_librarypath = librarypath
                if not sql_librarypath.endswith(sep):
                    sql_librarypath += sep

                sql = 'INSERT INTO path (idPath, strPath,  scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \
                      '(%s, "%s", 0, 0, 0, 0)' % (idPath, sql_librarypath)
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    continuar = True
                    idParentPath = idPath
                    idPath += 1
                else:
                    msg_text = "Omesso di impostare LibraryPath in BD"

        if continuar:
            continuar = False

            # Fijamos strContent, strScraper, scanRecursive y strSettings
            if content_type == 'CINE':
                strContent = 'movies'
                strScraper = 'metadata.themoviedb.org'
                scanRecursive = 2147483647
                strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \
                              "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \
                              "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \
                              "<setting id='trailer' value='true' /></settings>"
                strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per i film ?"
                if not librarypath.endswith(sep):
                    librarypath += sep
                strPath = librarypath + config.get_setting("folder_movies") + sep
            else:
                strContent = 'tvshows'
                strScraper = 'metadata.tvdb.com'
                scanRecursive = 0
                strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \
                              "<setting id='absolutenumber' value='false' />" \
                              "<setting id='dvdorder' value='false' />" \
                              "<setting id='fallback' value='true' />" \
                              "<setting id='fanart' value='true' />" \
                              "<setting id='language' value='it' /></settings>"
                strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per le serie ?"
                if not librarypath.endswith(sep):
                    librarypath += sep
                strPath = librarypath + config.get_setting("folder_tvshows") + sep

            logger.info("%s: %s" % (content_type, strPath))
            # Comprobamos si ya existe strPath en la BD para evitar duplicados
            sql = 'SELECT idPath FROM path where strPath="%s"' % strPath
            nun_records, records = execute_sql_kodi(sql)
            sql = ""
            if nun_records == 0:
                # Insertamos el scraper
                sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \
                      'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \
                      '"%s", 0, 0, %s)' % (
                      idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath)
            else:
                if not silent:
                    # Preguntar si queremos configurar themoviedb.org como opcion por defecto
                    actualizar = platformtools.dialog_yesno("The TVDB", strActualizar)
                else:
                    actualizar = True

                if actualizar:
                    # Actualizamos el scraper
                    idPath = records[0][0]
                    sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \
                          'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath)

            if sql:
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    continuar = True

            if not continuar:
                msg_text = "Omesso impostare LibraryPath in BD"


        if not continuar:
            heading = "Biblioteca %s no configurada" % content_type
        elif content_type == 'SERIES' and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
            heading = "Biblioteca %s configurata" % content_type
            msg_text = "Riavviare Kodi per attuare le modifiche."
        else:
            heading = "Biblioteca %s configurata" % content_type
            msg_text = "Libreria di Kodi configurata correttamente."
        platformtools.dialog_notification(heading, msg_text, icon=1, time=10000)
        logger.info("%s: %s" % (heading, msg_text))
Example #56
0
def sync_trakt_pelisalacarta(path_folder):
    """
       Actualiza los valores de episodios vistos si
    """
    logger.info()
    # si existe el addon hacemos la busqueda
    if xbmc.getCondVisibility('System.HasAddon("script.trakt")'):
        # importamos dependencias
        paths = ["special://home/addons/script.module.dateutil/lib/", "special://home/addons/script.module.six/lib/",
                 "special://home/addons/script.module.arrow/lib/", "special://home/addons/script.module.trakt/lib/",
                 "special://home/addons/script.trakt/"]

        for path in paths:
            import sys
            sys.path.append(xbmc.translatePath(path))

        # se obtiene las series vistas
        try:
            from resources.lib.traktapi import traktAPI
            traktapi = traktAPI()
        except:
            return

        shows = traktapi.getShowsWatched({})
        shows = shows.items()

        # obtenemos el id de la serie para comparar
        import re
        _id = re.findall("\[(.*?)\]", path_folder, flags=re.DOTALL)[0]
        logger.debug("el id es %s" % _id)

        if "tt" in _id:
            type_id = "imdb"
        elif "tvdb_" in _id:
            _id = _id.strip("tvdb_")
            type_id = "tvdb"
        elif "tmdb_" in _id:
            type_id = "tmdb"
            _id = _id.strip("tmdb_")
        else:
            logger.error("No hay _id de la serie")
            return

        # obtenemos los valores de la serie de pelisalacarta
        from core import library
        tvshow_file = filetools.join(path_folder, "tvshow.sod")
        head_nfo, serie = library.read_nfo(tvshow_file)

        # buscamos en las series de trakt
        for show in shows:
            show_aux = show[1].to_dict()

            try:
                _id_trakt = show_aux['ids'].get(type_id, None)
                # logger.debug("ID ES %s" % _id_trakt)
                if _id_trakt:
                    if _id == _id_trakt:
                        logger.debug("ENCONTRADO!! %s" % show_aux)

                        # creamos el diccionario de trakt para la serie encontrada con el valor que tiene "visto"
                        dict_trakt_show = {}

                        for idx_season, season in enumerate(show_aux['seasons']):
                            for idx_episode, episode in enumerate(show_aux['seasons'][idx_season]['episodes']):
                                sea_epi = "%sx%s" % (show_aux['seasons'][idx_season]['number'],
                                                     str(show_aux['seasons'][idx_season]['episodes'][idx_episode]['number']).zfill(2))

                                dict_trakt_show[sea_epi] = show_aux['seasons'][idx_season]['episodes'][idx_episode]['watched']
                        logger.debug("dict_trakt_show %s " % dict_trakt_show)

                        # obtenemos las keys que son episodios
                        regex_epi = re.compile('\d+x\d+')
                        keys_episodes = [key for key in serie.library_playcounts if regex_epi.match(key)]
                        # obtenemos las keys que son temporadas
                        keys_seasons = [key for key in serie.library_playcounts if 'season ' in key]
                        # obtenemos los numeros de las keys temporadas
                        seasons = [key.strip('season ') for key in keys_seasons]

                        # marcamos los episodios vistos
                        for k in keys_episodes:
                            serie.library_playcounts[k] = dict_trakt_show.get(k, 0)

                        for season in seasons:
                            episodios_temporada = 0
                            episodios_vistos_temporada = 0

                            # obtenemos las keys de los episodios de una determinada temporada
                            keys_season_episodes = [key for key in keys_episodes if key.startswith("%sx" % season)]

                            for k in keys_season_episodes:
                                episodios_temporada += 1
                                if serie.library_playcounts[k] > 0:
                                    episodios_vistos_temporada += 1

                            # se comprueba que si todos los episodios están vistos, se marque la temporada como vista
                            if episodios_temporada == episodios_vistos_temporada:
                                serie.library_playcounts.update({"season %s" % season: 1})

                        temporada = 0
                        temporada_vista = 0

                        for k in keys_seasons:
                            temporada += 1
                            if serie.library_playcounts[k] > 0:
                                temporada_vista += 1

                        # se comprueba que si todas las temporadas están vistas, se marque la serie como vista
                        if temporada == temporada_vista:
                            serie.library_playcounts.update({serie.title: 1})

                        logger.debug("los valores nuevos %s " % serie.library_playcounts)
                        filetools.write(tvshow_file, head_nfo + serie.tojson())

                        break
                    else:
                        continue

                else:
                    logger.error("no se ha podido obtener el id, trakt tiene: %s" % show_aux['ids'])

            except:
                import traceback
                logger.error(traceback.format_exc())
Example #57
0
import glob
import GoDev
import zipfile
import urlparse
import urllib, urllib2, json
import common, xbmcvfs, downloader, extract
from datetime import datetime, timedelta
import base64, time
import unicodedata
AddonID = 'plugin.video.stargate-streams'
ADDON = xbmcaddon.Addon(id='plugin.video.stargate-streams')
__icon__ = ADDON.getAddonInfo('icon')
__self__ = xbmcaddon.Addon(id='plugin.video.stargate-streams')
dialog = xbmcgui.Dialog()
dialogprocess = xbmcgui.DialogProgress()
log_path = xbmc.translatePath('special://logpath/')
USERDATA = xbmc.translatePath(os.path.join('special://home/userdata', ''))
GUI = xbmc.translatePath(os.path.join(USERDATA, 'guisettings.xml'))
GUIFIX = xbmc.translatePath(os.path.join(USERDATA, 'guifix.xml'))
INSTALL = xbmc.translatePath(os.path.join(USERDATA, 'install.xml'))
FAVS = xbmc.translatePath(os.path.join(USERDATA, 'favourites.xml'))
SOURCE = xbmc.translatePath(os.path.join(USERDATA, 'sources.xml'))
ADVANCED = xbmc.translatePath(os.path.join(USERDATA, 'advancedsettings.xml'))
PROFILES = xbmc.translatePath(os.path.join(USERDATA, 'profiles.xml'))
RSS = xbmc.translatePath(os.path.join(USERDATA, 'RssFeeds.xml'))
KEYMAPS = xbmc.translatePath(os.path.join(USERDATA, 'keymaps', 'keyboard.xml'))
HOME = xbmc.translatePath('special://home/')
zip = ADDON.getSetting('zip')
USB = xbmc.translatePath(os.path.join(zip))
skin = xbmc.getSkinDir()
Images = xbmc.translatePath(
Example #58
0
def execute_sql_kodi(sql):
    """
    Ejecuta la consulta sql contra la base de datos de kodi
    @param sql: Consulta sql valida
    @type sql: str
    @return: Numero de registros modificados o devueltos por la consulta
    @rtype nun_records: int
    @return: lista con el resultado de la consulta
    @rtype records: list of tuples
    """
    logger.info()
    file_db = ""
    nun_records = 0
    records = None

    # Buscamos el archivo de la BBDD de videos segun la version de kodi
    video_db = config.get_platform(True)['video_db']
    if video_db:
        file_db = filetools.join(xbmc.translatePath("special://userdata/Database"), video_db)

    # metodo alternativo para localizar la BBDD
    if not file_db or not filetools.exists(file_db):
        file_db = ""
        for f in filetools.listdir(xbmc.translatePath("special://userdata/Database")):
            path_f = filetools.join(xbmc.translatePath("special://userdata/Database"), f)

            if filetools.isfile(path_f) and f.lower().startswith('myvideos') and f.lower().endswith('.db'):
                file_db = path_f
                break

    if file_db:
        logger.info("Archivo de BD: %s" % file_db)
        conn = None
        try:
            import sqlite3
            conn = sqlite3.connect(file_db)
            cursor = conn.cursor()

            logger.info("Ejecutando sql: %s" % sql)
            cursor.execute(sql)
            conn.commit()

            records = cursor.fetchall()
            if sql.lower().startswith("select"):
                nun_records = len(records)
                if nun_records == 1 and records[0][0] is None:
                    nun_records = 0
                    records = []
            else:
                nun_records = conn.total_changes

            conn.close()
            logger.info("Consulta ejecutada. Registros: %s" % nun_records)

        except:
            logger.error("Error al ejecutar la consulta sql")
            if conn:
                conn.close()

    else:
        logger.debug("Base de datos no encontrada")

    return nun_records, records
Example #59
0
import xbmcvfs
import os
import json
import yaml
from distutils.util import strtobool

from traceback import format_exc

__addon__ = xbmcaddon.Addon()
__cwd__ = __addon__.getAddonInfo('path')
__scriptname__ = __addon__.getAddonInfo('name')
__version__ = __addon__.getAddonInfo('version')
__kodiversion__ = xbmc.getInfoLabel('System.BuildVersion')
__icon__ = __addon__.getAddonInfo('icon')
__ID__ = __addon__.getAddonInfo('id')
__profile__ = xbmc.translatePath(__addon__.getAddonInfo('profile'))
__ignoredshowsfile__ = xbmc.translatePath(
    os.path.join(__profile__, 'ignoredShows.yaml'))
__language__ = __addon__.getLocalizedString


def log(msg, level=xbmc.LOGDEBUG):
    xbmc.log(("### [%s] - %s" % (
        __scriptname__,
        msg,
    )), level)


def getSetting(setting):
    return __addon__.getSetting(setting).strip()
Example #60
0
def Wipe_Cache():
    xbmc_cache_path = os.path.join(xbmc.translatePath('special://home'),
                                   'cache')
    if os.path.exists(xbmc_cache_path) == True:
        for root, dirs, files in os.walk(xbmc_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    try:
                        os.unlink(os.path.join(root, f))
                    except:
                        pass
                for d in dirs:
                    try:
                        shutil.rmtree(os.path.join(root, d))
                    except:
                        pass
    if xbmc.getCondVisibility('system.platform.ATV2'):
        atv2_cache_a = os.path.join(
            '/private/var/mobile/Library/Caches/AppleTV/Video/', 'Other')
        for root, dirs, files in os.walk(atv2_cache_a):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    os.unlink(os.path.join(root, f))
                for d in dirs:
                    shutil.rmtree(os.path.join(root, d))
        atv2_cache_b = os.path.join(
            '/private/var/mobile/Library/Caches/AppleTV/Video/',
            'LocalAndRental')
        for root, dirs, files in os.walk(atv2_cache_b):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    os.unlink(os.path.join(root, f))
                for d in dirs:
                    shutil.rmtree(os.path.join(root, d))
    # Set path to script.module.simple.downloader cache files
    downloader_cache_path = os.path.join(
        xbmc.translatePath(
            'special://profile/addon_data/script.module.simple.downloader'),
        '')
    if os.path.exists(downloader_cache_path) == True:
        for root, dirs, files in os.walk(downloader_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    os.unlink(os.path.join(root, f))
                for d in dirs:
                    shutil.rmtree(os.path.join(root, d))
    # Set path to script.image.music.slideshow cache files
    imageslideshow_cache_path = os.path.join(
        xbmc.translatePath(
            'special://profile/addon_data/script.image.music.slideshow/cache'),
        '')
    if os.path.exists(imageslideshow_cache_path) == True:
        for root, dirs, files in os.walk(imageslideshow_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    os.unlink(os.path.join(root, f))
                for d in dirs:
                    shutil.rmtree(os.path.join(root, d))
    # Set path to BBC iPlayer cache files
    iplayer_cache_path = os.path.join(
        xbmc.translatePath(
            'special://profile/addon_data/plugin.video.iplayer/iplayer_http_cache'
        ), '')
    if os.path.exists(iplayer_cache_path) == True:
        for root, dirs, files in os.walk(iplayer_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    os.unlink(os.path.join(root, f))
                for d in dirs:
                    shutil.rmtree(os.path.join(root, d))
    itv_cache_path = os.path.join(
        xbmc.translatePath(
            'special://profile/addon_data/plugin.video.itv/Images'), '')
    if os.path.exists(itv_cache_path) == True:
        for root, dirs, files in os.walk(itv_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    os.unlink(os.path.join(root, f))
                for d in dirs:
                    shutil.rmtree(os.path.join(root, d))
    navix_cache_path = os.path.join(
        xbmc.translatePath('special://profile/addon_data/script.navi-x/cache'),
        '')
    if os.path.exists(navix_cache_path) == True:
        for root, dirs, files in os.walk(navix_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    os.unlink(os.path.join(root, f))
                for d in dirs:
                    shutil.rmtree(os.path.join(root, d))
    phoenix_cache_path = os.path.join(
        xbmc.translatePath(
            'special://profile/addon_data/plugin.video.phstreams/Cache'), '')
    if os.path.exists(phoenix_cache_path) == True:
        for root, dirs, files in os.walk(phoenix_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    os.unlink(os.path.join(root, f))
                for d in dirs:
                    shutil.rmtree(os.path.join(root, d))
    ramfm_cache_path = os.path.join(
        xbmc.translatePath(
            'special://profile/addon_data/plugin.audio.ramfm/cache'), '')
    if os.path.exists(ramfm_cache_path) == True:
        for root, dirs, files in os.walk(ramfm_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    os.unlink(os.path.join(root, f))
                for d in dirs:
                    shutil.rmtree(os.path.join(root, d))
    wtf_cache_path = os.path.join(
        xbmc.translatePath(
            'special://profile/addon_data/plugin.video.whatthefurk/cache'), '')
    if os.path.exists(wtf_cache_path) == True:
        for root, dirs, files in os.walk(wtf_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    os.unlink(os.path.join(root, f))
                for d in dirs:
                    shutil.rmtree(os.path.join(root, d))
    try:
        genesisCache = os.path.join(
            xbmc.translatePath(
                'special://profile/addon_data/plugin.video.genesis'),
            'cache.db')
        dbcon = database.connect(genesisCache)
        dbcur = dbcon.cursor()
        dbcur.execute("DROP TABLE IF EXISTS rel_list")
        dbcur.execute("VACUUM")
        dbcon.commit()
        dbcur.execute("DROP TABLE IF EXISTS rel_lib")
        dbcur.execute("VACUUM")
        dbcon.commit()
    except:
        pass