def import_advancedxml():
	userdatapath = xbmc.translatePath(os.path.join('special://home/userdata'.decode('utf-8'),''.decode('utf-8')))
	advancedsettings_var = os.path.join(userdatapath,'advancedsettings.xml')
	advancedsettingsbackup_var = os.path.join(userdatapath,'advancedsettingsbackup.xml')
	if xbmcvfs.exists(advancedsettings_var):
		print("An advanced settings XML file already exists")
		if xbmcvfs.exists(advancedsettingsbackup_var):
			print("An advanced settings backup already exists")
			xbmcvfs.delete(advancedsettingsbackup_var)
			xbmcvfs.rename(advancedsettings_var,advancedsettingsbackup_var)
			advancedname = ["Cachemembuffer=252420","freememorycachepercent=5"]
			advancedurl = ["http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettings.xml","http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettingstonicillo.xml"]
			index = xbmcgui.Dialog().select(translate(40185), advancedname)
    			if index > -1:
    				download_tools().Downloader(advancedurl[index],advancedsettings_var,translate(40059),translate(40000))
				mensagemok(translate(40000),translate(40060))
		else:	
			xbmcvfs.rename(advancedsettings_var,advancedsettingsbackup_var)
			advancedname = ["Cachemembuffer=252420","freememorycachepercent=5"]
			advancedurl = ["http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettings.xml","http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettingstonicillo.xml"]
			index = xbmcgui.Dialog().select(translate(40185), advancedname)
    			if index > -1:
    				download_tools().Downloader(advancedurl[index],advancedsettings_var,translate(40059),translate(40000))
				mensagemok(translate(40000),translate(40060))
	else:
		print("No advancedsettings.xml in the system yet")
		advancedname = ["Cachemembuffer=252420","freememorycachepercent=5"]
		advancedurl = ["http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettings.xml","http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettingstonicillo.xml"]
		index = xbmcgui.Dialog().select(translate(40185), advancedname)
    		if index > -1:
    			download_tools().Downloader(advancedurl[index],advancedsettings_var,translate(40059),translate(40000))
			mensagemok(translate(40000),translate(40060))
	xbmc.executebuiltin("Container.Refresh")
    def add_item_to_library(self, item_path, item_url):
        error = False
        new = False
        if item_path:
            item_path = xbmc.translatePath(item_path)
            dir = os.path.dirname(item_path)
            if not xbmcvfs.exists(dir):
                try:
                    xbmcvfs.mkdirs(dir)
                except Exception, e:
                    error = True
                    print('Failed to create directory 1', dir)

            if not xbmcvfs.exists(dir):
                error = True
                print('Failed to create directory 2', dir)

            if not xbmcvfs.exists(item_path):
                try:
                    file_desc = xbmcvfs.File(item_path, 'w')
                    file_desc.write(item_url)
                    file_desc.close()
                    new = True
                except Exception, e:
                    print('Failed to create .strm file: ', item_path, e)
                    error = True
def getEvent(eventID):
    event = dbops.getEvent(eventID)
    log('Listing video files for event: %s' % event[1])
    for x in library.loadLibrary():
        if event[0] == x['ID']:
            thumbPath = os.path.join(__thumbDir__, '%s-poster.jpg' % x['ID'])
            if not xbmcvfs.exists(thumbPath):
                thumbPath = os.path.join(__promotionDir__, '%s-poster.jpg' % event[2].replace(' ', ''))
            fanartPath = os.path.join(__thumbDir__, '%s-fanart.jpg' % x['ID'])
            if not xbmcvfs.exists(fanartPath):
                fanartPath = os.path.join(__promotionDir__, '%s-fanart.jpg' % event[2].replace(' ', ''))
            outline = '%s: %s, %s' % (event[3], event[4], event[5])
            try:
                description = open(os.path.join(__thumbDir__, '%s-description.txt' % event[0])).read()
            except IOError:
                description = outline
            fighterList = dbops.getFightersByEvent(eventID)
            description = description + '\n\n' + '\n'.join(fighterList)
            fileList = getVideoList(x['path'])
            if len(fileList) == 1:
                li=xbmcgui.ListItem(label = event[1], iconImage = thumbPath, thumbnailImage = thumbPath)
                li.setInfo( type="Video", infoLabels={ "title": event[1], "plot": description, "cast": fighterList, "genre": event[2], "date": event[3], "premiered": event[3], "tvshowtitle": event[2]} )
                xbmc.Player().play(fileList[0]['path'], li)
                sys.exit(0)
            else:
                for vidFile in fileList:
                    addLink(linkName = vidFile['title'], plotoutline = outline, plot = description, url = vidFile['path'], thumbPath = thumbPath, fanartPath = fanartPath, genre = event[2])
Beispiel #4
0
def video(name, url, mode, thumb, video_type='', description='', duration='', year='', mpaa='', director='', genre='',
          rating=0.0, playcount=0, remove=False):
    entries = []
    filename = utility.clean_filename(url) + '.jpg'
    cover_file = xbmc.translatePath(utility.cover_cache_dir() + filename)
    fanart_file = xbmc.translatePath(utility.fanart_cache_dir() + filename)
    if xbmcvfs.exists(cover_file):
        thumb = cover_file
    u = sys.argv[0]
    u += '?url=' + urllib.quote_plus(url)
    u += '&mode=' + mode
    u += '&name=' + urllib.quote_plus(utility.encode(name))
    u += '&thumb=' + urllib.quote_plus(thumb)
    list_item = xbmcgui.ListItem(name)
    list_item.setArt({'icon': 'DefaultTVShows.png', 'thumb': thumb})
    list_item.setInfo(type='video',
                      infoLabels={'title': name, 'plot': description, 'duration': duration, 'year': int(year),
                                  'mpaa': mpaa, 'director': director, 'genre': genre, 'rating': rating,
                                  'playcount': playcount})
    if xbmcvfs.exists(fanart_file):
        list_item.setProperty('fanart_image', fanart_file)
    elif xbmcvfs.exists(cover_file):
        list_item.setProperty('fanart_image', cover_file)
    else:
        list_item.setProperty('fanart_image', utility.addon_fanart())
    if video_type == 'tvshow':
        if utility.get_setting('browse_tv_shows') == 'true':
            entries.append((utility.get_string(30151),
                            'Container.Update(plugin://%s/?mode=play_video_main&url=%s&thumb=%s)' % (
                                utility.addon_id, urllib.quote_plus(url), urllib.quote_plus(thumb))))
        else:
            entries.append((utility.get_string(30152),
                            'Container.Update(plugin://%s/?mode=list_seasons&url=%s&thumb=%s)' % (
                                utility.addon_id, urllib.quote_plus(url), urllib.quote_plus(thumb))))
    if video_type != 'episode':
        entries.append((utility.get_string(30153), 'RunPlugin(plugin://%s/?mode=play_trailer&url=%s&type=%s)' % (
            utility.addon_id, urllib.quote_plus(utility.encode(name)), video_type)))
        if remove:
            entries.append((utility.get_string(30154), 'RunPlugin(plugin://%s/?mode=remove_from_queue&url=%s)' % (
                utility.addon_id, urllib.quote_plus(url))))
        else:
            entries.append((utility.get_string(30155), 'RunPlugin(plugin://%s/?mode=add_to_queue&url=%s)' % (
                utility.addon_id, urllib.quote_plus(url))))
        entries.append((utility.get_string(30156),
                        'Container.Update(plugin://%s/?mode=list_videos&url=%s&type=movie)' % (
                            utility.addon_id, urllib.quote_plus(utility.main_url + '/WiMovie/' + url))))
        entries.append((utility.get_string(30157), 'Container.Update(plugin://%s/?mode=list_videos&url=%s&type=tv)' % (
            utility.addon_id, urllib.quote_plus(utility.main_url + '/WiMovie/' + url))))
    if video_type == 'tvshow':
        entries.append((utility.get_string(30150),
                        'RunPlugin(plugin://%s/?mode=add_series_to_library&url=&name=%s&series_id=%s)' % (
                            utility.addon_id, urllib.quote_plus(utility.encode(name.strip())), urllib.quote_plus(url))))
    elif video_type == 'movie':
        entries.append((utility.get_string(30150),
                        'RunPlugin(plugin://%s/?mode=add_movie_to_library&url=%s&name=%s)' % (
                            utility.addon_id, urllib.quote_plus(url),
                            urllib.quote_plus(utility.encode(name.strip())) + ' (' + unicode(year) + ')')))
    list_item.addContextMenuItems(entries)
    directory_item = xbmcplugin.addDirectoryItem(handle=plugin_handle, url=u, listitem=list_item, isFolder=True)
    return directory_item
Beispiel #5
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
Beispiel #6
0
def check_login():
    if not xbmcvfs.exists(addon_profile):
        xbmcvfs.mkdir(addon_profile)

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

                if already_logged_in:
                    addon_log("Already logged in")
                    return True
                else:
                    addon_log("Not yet logged in")
                    return gamepass_login()
            else:
                return gamepass_login()
    elif subscription == "0":
        if addon.getSetting("sans_login") == "true":
            return True
    else:
        dialog = xbmcgui.Dialog()
        dialog.ok("Account Info Not Set", "Please set your Game Pass username and password", "in Add-on Settings.")
        addon_log("No account settings detected.")
        return False
def autostart():
        xbmcaddon.Addon().setSetting(id="files_overwrite", value='false')
        settings = _settings()
        settings._get_general()
        addondir = xbmc.translatePath( utils.__addon__.getAddonInfo('profile') )
        tempdir = os.path.join(addondir, 'temp')
        service_runtime  = str(settings.service_runtime + ':00')
        log('Service - Run at startup: %s'%settings.service_startup, xbmc.LOGNOTICE)        
        log('Service - Delayed startup: %s minutes'%settings.service_startupdelay, xbmc.LOGNOTICE)   
        log('Service - Run as service: %s'%settings.service_enable, xbmc.LOGNOTICE)
        log('Service - Time: %s'%service_runtime, xbmc.LOGNOTICE)
        if xbmcvfs.exists(tempdir):
            xbmcvfs.rmdir(tempdir)
            log('Removing temp folder from previous run.')
        if settings.service_startup:
            if settings.service_startupdelay != '--':
                xbmc.executebuiltin('XBMC.AlarmClock(ArtworkDownloader,XBMC.RunScript(script.artwork.downloader,silent=true),00:%s:00,silent)' %settings.service_startupdelay) 
            else:
                xbmc.executebuiltin('XBMC.AlarmClock(ArtworkDownloader,XBMC.RunScript(script.artwork.downloader,silent=true),00:00:20,silent)') 
        if settings.service_enable:
            while (not xbmc.abortRequested):
                xbmc.sleep(5000)
                if not(time.strftime('%H:%M') == service_runtime):
                    pass
                else:
                    if not xbmcvfs.exists(tempdir):
                        log('Time is %s:%s, Scheduled run starting' % (time.strftime('%H'), time.strftime('%M')))
                        xbmc.executebuiltin('XBMC.RunScript(script.artwork.downloader,silent=true)')
                    else:
                        log('Addon already running, scheduled run aborted', xbmc.LOGNOTICE)
Beispiel #8
0
def setAddonsettings():
    if not xbmcvfs.exists(SETTING("pvrthumbspath")):
        xbmcvfs.mkdirs(SETTING("pvrthumbspath"))
    if not xbmcvfs.exists("special://profile/addon_data/script.skin.helper.service/musicart/"):
        xbmcvfs.mkdirs("special://profile/addon_data/script.skin.helper.service/musicart/")
    #get the addonsettings and store them in memory
    WINDOW.setProperty("SkinHelper.pvrthumbspath",SETTING("pvrthumbspath"))
    WINDOW.setProperty("SkinHelper.cacheRecordings",SETTING("cacheRecordings"))
    WINDOW.setProperty("SkinHelper.cacheGuideEntries",SETTING("cacheGuideEntries"))
    WINDOW.setProperty("SkinHelper.customRecordingsPath",SETTING("customRecordingsPath"))
    WINDOW.setProperty("SkinHelper.useTMDBLookups",SETTING("useTMDBLookups"))
    WINDOW.setProperty("SkinHelper.useGoogleLookups",SETTING("useGoogleLookups"))
    WINDOW.setProperty("SkinHelper.useYoutubeLookups",SETTING("useYoutubeLookups"))
    WINDOW.setProperty("SkinHelper.useLocalLibraryLookups",SETTING("useLocalLibraryLookups"))
    WINDOW.setProperty("SkinHelper.customlookuppath",SETTING("customlookuppath"))
    WINDOW.setProperty("SkinHelper.useFanArtTv",SETTING("useFanArtTv"))
    WINDOW.setProperty("SkinHelper.ignorechannels",SETTING("ignorechannels"))
    WINDOW.setProperty("SkinHelper.ignoretitles",SETTING("ignoretitles"))
    WINDOW.setProperty("SkinHelper.stripwords",SETTING("stripwords"))
    WINDOW.setProperty("SkinHelper.directory_structure",SETTING("directory_structure"))
    WINDOW.setProperty("SkinHelper.lastUpdate","%s" %datetime.now())    
    WINDOW.setProperty("SkinHelper.enablewallbackgrounds",SETTING("enablewallbackgrounds"))
    WINDOW.setProperty("SkinHelper.enableMusicArtScraper",SETTING("enableMusicArtScraper"))
    WINDOW.setProperty("SkinHelper.downloadMusicArt",SETTING("downloadMusicArt"))
    WINDOW.setProperty("SkinHelper.enableLocalMusicArtLookup",SETTING("enableLocalMusicArtLookup"))
    WINDOW.setProperty("SkinHelper.enableDebugLog",SETTING("enableDebugLog"))
    WINDOW.setProperty("SkinHelper.maxNumFanArts",SETTING("maxNumFanArts"))
    WINDOW.setProperty("SkinHelper.splittitlechar",SETTING("splittitlechar"))
    WINDOW.setProperty("SkinHelper.enablePVRThumbsRecordingsOnly",SETTING("enablePVRThumbsRecordingsOnly"))
    WINDOW.setProperty("SkinHelper.preferOnlineMusicArt",SETTING("preferOnlineMusicArt"))
    WINDOW.setProperty("SkinHelper.enableWidgetsArtworkLookups",SETTING("enableWidgetsArtworkLookups"))
    WINDOW.setProperty("SkinHelper.enableSpecialsInWidgets",SETTING("enableSpecialsInWidgets"))
    WINDOW.setProperty("SkinHelper.enableWidgetsAlbumBrowse",SETTING("enableWidgetsAlbumBrowse"))
Beispiel #9
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)")
Beispiel #10
0
 def container_data(self):
     if not xbmcvfs.exists(dataPath):
         xbmcvfs.mkdir(dataPath)
     if not xbmcvfs.exists(viewData):
         file = xbmcvfs.File(viewData, 'w')
         file.write('')
         file.close()
def Get_JSON_response(url="", cache_days=7.0, folder=False, headers=False):
    now = time.time()
    hashed_url = hashlib.md5(url).hexdigest()
    path = xbmc.translatePath(os.path.join(ADDON_DATA_PATH, hashed_url + ".txt"))
    cache_seconds = int(cache_days * 86400.0)
    prop_time = HOME.getProperty(hashed_url + "_timestamp")
    if prop_time and now - float(prop_time) < cache_seconds:
        try:
            prop = simplejson.loads(HOME.getProperty(hashed_url))
            log("prop load for %s. time: %f" % (url, time.time() - now))
            return prop
        except:
            log("could not load prop data")
    if xbmcvfs.exists(path) and ((now - os.path.getmtime(path)) < cache_seconds):
        results = read_from_file(path)
        log("loaded file for %s. time: %f" % (url, time.time() - now))
    else:
        response = GetStringFromUrl(url, headers)
        try:
            results = simplejson.loads(response)
            log("download %s. time: %f" % (url, time.time() - now))
            save_to_file(results, hashed_url, ADDON_DATA_PATH)
        except:
            log("Exception: Could not get new JSON data. Tryin to fallback to cache")
            log(response)
            if xbmcvfs.exists(path):
                results = read_from_file(path)
            else:
                results = []
    HOME.setProperty(hashed_url + "_timestamp", str(now))
    HOME.setProperty(hashed_url, simplejson.dumps(results))
    return results
    def saveTorrent(self, torrentUrl):
        if not xbmcvfs.exists(torrentUrl) or re.match("^http.+$", torrentUrl):
            if re.match("^magnet\:.+$", torrentUrl):
                self.magnetLink = torrentUrl
                self.magnetToTorrent(torrentUrl)
                self.magnetLink = None
                return self.torrentFile
            else:
                if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath)
                torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent')
                try:
                    if not re.match("^http\:.+$", torrentUrl):
                        content = xbmcvfs.File(torrentUrl, "rb").read()
                    else:
                        request = urllib2.Request(torrentUrl)
                        request.add_header('Referer', torrentUrl)
                        request.add_header('Accept-encoding', 'gzip')
                        result = urllib2.urlopen(request)
                        if result.info().get('Content-Encoding') == 'gzip':
                            buf = StringIO(result.read())
                            f = gzip.GzipFile(fileobj=buf)
                            content = f.read()
                        else:
                            content = result.read()

                    localFile = xbmcvfs.File(torrentFile, "w+b")
                    localFile.write(content)
                    localFile.close()
                except Exception, e:
                    print 'Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str(
                        e)
                    return
def series(series_id, series_title, season, single_update=True):
    filename = utility.clean_filename(series_title, ' .')
    series_file = xbmc.translatePath(utility.tv_dir() + filename)
    if not xbmcvfs.exists(series_file):
        xbmcvfs.mkdir(series_file)
    content = get.series_info(series_id)
    content = json.loads(content)['video']['seasons']
    for test in content:
        episode_season = unicode(test['seq'])
        if episode_season == season or season == '':
            season_dir = utility.create_pathname(series_file, test['title'])
            if not xbmcvfs.exists(season_dir):
                xbmcvfs.mkdir(season_dir)
            for item in test['episodes']:
                episode_id = unicode(item['episodeId'])
                episode_nr = unicode(item['seq'])
                episode_title = item['title']
                if len(episode_nr) == 1:
                    episode_nr = '0' + episode_nr
                season_nr = episode_season
                if len(season_nr) == 1:
                    season_nr = '0' + season_nr
                filename = 'S' + season_nr + 'E' + episode_nr + ' - ' + episode_title + '.strm'
                filename = utility.clean_filename(filename, ' .')
                file_handler = xbmcvfs.File(utility.create_pathname(season_dir, filename), 'w')
                file_handler.write(
                    utility.encode('plugin://%s/?mode=play_video&url=%s' % (utility.addon_id, episode_id)))
                file_handler.close()
    if utility.get_setting('update_db') and single_update:
        xbmc.executebuiltin('UpdateLibrary(video)')
def _get_trailer_thumbnail( path ):
    log( "Getting Trailer Thumbnail" )
    # check for a thumb based on trailername.tbn
    thumbnail = os.path.splitext( path )[ 0 ] + ".tbn"
    log( "Looking for thumbnail: %s" % thumbnail )
    # if thumb does not exist try stripping -trailer
    if not xbmcvfs.exists( thumbnail ):
        thumbnail = os.path.splitext( path )[ 0 ] + ".jpg"
        log( "Looking for thumbnail: %s" % thumbnail )
        if not xbmcvfs.exists( thumbnail ):
            thumbnail = "%s.tbn" % ( os.path.splitext( path )[ 0 ].replace( "-trailer", "" ), )
            log( "Thumbnail not found, Trying: %s" % thumbnail )
            if not xbmcvfs.exists( thumbnail ):
                thumbnail = "%s.jpg" % ( os.path.splitext( path )[ 0 ].replace( "-trailer", "" ), )
                log( "Looking for thumbnail: %s" % thumbnail )
                if not xbmcvfs.exists( thumbnail ):
                    thumbnail = os.path.join( os.path.dirname( path ), "movie.tbn" )
                    log( "Thumbnail not found, Trying: %s" % thumbnail )
                    # if thumb does not exist return empty
                    if not xbmcvfs.exists( thumbnail ):
                        # set empty string
                        thumbnail = ""
                        log( "Thumbnail not found" )
    if thumbnail:
        log( "Thumbnail found: %s" thumbnail )
    # return result
    return thumbnail
Beispiel #15
0
def writeConfig(cfile, value=''):
    cfgfile = os.path.join(configpath, cfile)
    cfglockfile = os.path.join(configpath, cfile + '.lock')

    if not xbmcvfs.exists(configpath):
        xbmcvfs.mkdirs(configpath)

    while True:
        if not xbmcvfs.exists(cfglockfile):
            l = xbmcvfs.File(cfglockfile, 'w')
            l.write(str(time.time()))
            l.close()
            if value == '':
                xbmcvfs.delete(cfgfile)
            else:
                f = xbmcvfs.File(cfgfile, 'w')
                f.write(value.__str__())
                f.close()
            xbmcvfs.delete(cfglockfile)
            xbmcvfs.delete(cfglockfile)
            return True
        else:
            l = xbmcvfs.File(cfglockfile)
            modified = float(l.read())
            l.close()
            if time.time() - modified > 0.1:
                xbmcvfs.delete(cfglockfile)
Beispiel #16
0
    def setSRT(self, service):

        if not constants.CONST.SRT:
            return

        #load cachePath if not already loaded
        if not service.settings.cacheSRT and self.cachePath == '':
            self.cachePath = service.settings.cachePath

        #only makes sense to cache SRT if the cachePath exists
        if service.settings.cacheSRT and self.cachePath != '':
            cachePath = str(self.cachePath) + '/' + str(self.package.file.id)+'/'

            if not xbmcvfs.exists(cachePath):
                xbmcvfs.mkdirs(cachePath)
            srt = service.getSRT(self.package)
            if srt:
                for file in srt:
                    if not xbmcvfs.exists(str(cachePath) + str(file[0])):
                        service.downloadGeneralFile(file[1], str(cachePath) + str(file[0]))
                    self.srt.append(str(cachePath) + str(file[0]))

        #fetch SRT URLs but we won't cache the files
        else:
            srt = service.getSRT(self.package)
            if srt:
                for file in srt:
                    self.srt.append(str(file[1]) + '|' + service.getHeadersEncoded())
Beispiel #17
0
    def setCC(self, service):

        if not constants.CONST.CC:
            return

        #load cachePath if not already loaded
        if self.cachePath == '':
            self.cachePath = service.settings.cachePath

        # there is no cache path setting or the setting is unset -- we should assume user does not want to use caching
        # CC files need to be cached (so they can be converted to SRT) -- don't do anything if we don't have the cachePath
        if self.cachePath == '':
            return

        else:
            cachePath = str(self.cachePath) + '/' + str(self.package.file.id)+'/'
            if not xbmcvfs.exists(cachePath):
                xbmcvfs.mkdirs(cachePath)
            cachePath = str(cachePath) + str(self.package.file.id)
            cc = service.getTTS(self.package.file.srtURL)
            if cc:
                for file in cc:
                    if not xbmcvfs.exists(cachePath + str(file[0])):
                        service.downloadTTS(file[1], str(cachePath) + str(file[0]))
                    self.srt.append(str(cachePath) + str(file[0]))
Beispiel #18
0
def Filter_Fakelight(filterimage, pixels):
    md5 = hashlib.md5(filterimage).hexdigest()
    filename = md5 + "fakelight" + str(pixels) + ".png"
    targetfile = os.path.join(ADDON_DATA_PATH, filename)
    cachedthumb = xbmc.getCacheThumbName(filterimage)
    xbmc_vid_cache_file = os.path.join("special://profile/Thumbnails/Video", cachedthumb[0], cachedthumb)
    xbmc_cache_file = os.path.join("special://profile/Thumbnails/", cachedthumb[0], cachedthumb[:-4] + ".jpg")
    if filterimage == "":
        return ""
    if not xbmcvfs.exists(targetfile):
        img = None
        for i in range(1, 4):
            try:
                if xbmcvfs.exists(xbmc_cache_file):
                    
                    img = Image.open(xbmc.translatePath(xbmc_cache_file))
                    break
                elif xbmcvfs.exists(xbmc_vid_cache_file):
                    img = Image.open(xbmc.translatePath(xbmc_vid_cache_file))
                    break
                else:
                    filterimage = urllib.unquote(filterimage.replace("image://", "")).decode('utf8')
                    if filterimage.endswith("/"):
                        filterimage = filterimage[:-1]
                    xbmcvfs.copy(filterimage, targetfile)
                    img = Image.open(targetfile)
                    break
            except:
                xbmc.sleep(300)
        if not img:
            return ""
        img = fake_light(img,pixels)
        img.save(targetfile)
    return targetfile
Beispiel #19
0
def _double_dot_fix_hack(video_filename):
    """Corrects filename of downloaded subtitle from Foo-Blah..srt to Foo-Blah.es.srt"""

    log(u"video_filename = %s" % video_filename)

    work_path = video_filename
    if _subtitles_setting('storagemode'):
        custom_subs_path = _subtitles_setting('custompath')
        if custom_subs_path:
            _, fname = os.path.split(video_filename)
            work_path = pjoin(custom_subs_path, fname)

    log(u"work_path = %s" % work_path)
    parts = work_path.rsplit('.', 1)
    if len(parts) > 1:
        rest = parts[0]
        for ext in ('srt', 'ssa', 'sub', 'idx'):
            bad = rest + '..' + ext
            old = rest + '.es.' + ext
            if xbmcvfs.exists(bad):
                log(u"%s exists" % bad)
                if xbmcvfs.exists(old):
                    log(u"%s exists, removing" % old)
                    xbmcvfs.delete(old)
                log(u"renaming %s to %s" % (bad, old))
                xbmcvfs.rename(bad, old)
Beispiel #20
0
def check_login():
    if not xbmcvfs.exists(addon_profile):
        xbmcvfs.mkdir(addon_profile)

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

    elif username and password:
        if not xbmcvfs.exists(cookie_file):
            return gamepass_login()
        else:
            cookie_jar.load(cookie_file, ignore_discard=True, ignore_expires=True)
            cookies = {}
            for i in cookie_jar:
                cookies[i.name] = i.value
            login_ok = False
            if cookies.has_key('userId'):
                data = make_request('https://gamepass.nfl.com/nflgp/secure/myaccount')
                try:
                    login_ok = re.findall('Update Account Information / Change Password', data)[0]
                except IndexError:
                    addon_log('Not Logged In')
                if not login_ok:
                    return gamepass_login()
                else:
                    addon_log('Logged In')
                    data = make_request('https://gamepass.nfl.com/nflgp/secure/schedule')
                    return cache_seasons_and_weeks(data)
            else:
                return gamepass_login()
    else:
        dialog = xbmcgui.Dialog()
        dialog.ok("Account Info Not Set", "Please set your Game Pass username and password", "in Add-on Settings.")
        addon_log('No account settings detected.')
def blur(input_img, radius=25):
    if not input_img:
        return {}
    if not xbmcvfs.exists(IMAGE_PATH):
        xbmcvfs.mkdir(IMAGE_PATH)
    input_img = utils.translate_path(urllib.unquote(input_img.encode("utf-8")))
    input_img = input_img.replace("image://", "").rstrip("/")
    cachedthumb = xbmc.getCacheThumbName(input_img)
    filename = "%s-radius_%i.png" % (cachedthumb, radius)
    targetfile = os.path.join(IMAGE_PATH, filename)
    vid_cache_file = os.path.join("special://profile/Thumbnails/Video", cachedthumb[0], cachedthumb)
    cache_file = os.path.join("special://profile/Thumbnails", cachedthumb[0], cachedthumb[:-4] + ".jpg")
    if xbmcvfs.exists(targetfile):
        img = PIL.Image.open(targetfile)
        return {"ImageFilter": targetfile,
                "ImageColor": get_colors(img)}
    try:
        if xbmcvfs.exists(cache_file):
            utils.log("image already in xbmc cache: " + cache_file)
            img = PIL.Image.open(utils.translate_path(cache_file))
        elif xbmcvfs.exists(vid_cache_file):
            utils.log("image already in xbmc video cache: " + vid_cache_file)
            img = PIL.Image.open(utils.translate_path(vid_cache_file))
        else:
            xbmcvfs.copy(input_img, targetfile)
            img = PIL.Image.open(targetfile)
        img.thumbnail((200, 200), PIL.Image.ANTIALIAS)
        imgfilter = MyGaussianBlur(radius=radius)
        img = img.convert('RGB').filter(imgfilter)
        img.save(targetfile)
    except Exception:
        utils.log("Could not get image for %s" % input_img)
        return {}
    return {"ImageFilter": targetfile,
            "ImageColor": get_colors(img)}
Beispiel #22
0
def writeMediaList(url, name, cType='Other'):
    utils.addon_log('writeMediaList')
    existInList = False
    thelist = []
    thefile = xbmc.translatePath(os.path.join(profile, 'MediaList.xml'))
    theentry = '|'.join([cType, name.decode("utf-8"), url]) + '\n'  
    
    if not xbmcvfs.exists(profile): 
        xbmcvfs.mkdirs(profile)
    if not xbmcvfs.exists(thefile):
        open(thefile, 'a').close()
    
    fle = codecs.open(thefile, "r", 'UTF-8')
    thelist = fle.readlines()
    fle.close()
    del fle
    
    if len(thelist) > 0:
        for i in thelist:
            if i.split('|',2)[1] == name:
                thelist = stringUtils.replaceStringElem(thelist, theentry, theentry)
                existInList = True     
    if existInList != True:
        thelist.append(theentry)
        
    with open(thefile.decode("utf-8"), 'w') as output_file: 
        for linje in thelist:
            if not linje.startswith('\n'):
                output_file.write(linje.strip().encode('utf-8') + '\n')
            else:
                output_file.write(linje.strip())
Beispiel #23
0
 def album_info(self, album_id):
     '''get album metadata by musicbrainz id'''
     details = {"art": {}}
     data = self.get_data("/album-mb.php", {'i': album_id})
     if data and data.get("album"):
         adbdetails = data["album"][0]
         if adbdetails.get("strAlbumThumb") and xbmcvfs.exists(adbdetails.get("strAlbumThumb")):
             details["art"]["thumb"] = adbdetails.get("strAlbumThumb")
             details["art"]["thumbs"] = [adbdetails.get("strAlbumThumb")]
         if adbdetails.get("strAlbumCDart") and xbmcvfs.exists(adbdetails.get("strAlbumCDart")):
             details["art"]["discart"] = adbdetails.get("strAlbumCDart")
             details["art"]["discarts"] = [adbdetails.get("strAlbumCDart")]
         if adbdetails.get("strAlbumSpine") and xbmcvfs.exists(adbdetails.get("strAlbumSpine")):
             details["art"]["spine"] = adbdetails.get("strAlbumSpine")
         if adbdetails.get("strAlbumThumbBack") and xbmcvfs.exists(adbdetails.get("strAlbumThumbBack")):
             details["art"]["thumbback"] = adbdetails.get("strAlbumThumbBack")
         if adbdetails.get("strDescription%s" % KODI_LANGUAGE.upper()):
             details["plot"] = adbdetails.get("strDescription%s" % KODI_LANGUAGE.upper())
         if not details.get("plot") and adbdetails.get("strDescriptionEN"):
             details["plot"] = adbdetails.get("strDescriptionEN")
         if details.get("plot"):
             details["plot"] = strip_newlines(details["plot"])
         if adbdetails.get("strGenre"):
             details["genre"] = adbdetails["strGenre"].split("/")
         if adbdetails.get("strStyle"):
             details["style"] = adbdetails["strStyle"].split("/")
         if adbdetails.get("strMood"):
             details["mood"] = adbdetails["strMood"].split("/")
         if adbdetails.get("intYearReleased"):
             details["year"] = adbdetails["intYearReleased"]
         if adbdetails.get("intScore"):
             details["rating"] = adbdetails["intScore"]
         if adbdetails.get("strAlbum"):
             details["title"] = adbdetails["strAlbum"]
     return details
def housekeeper():
	file_flag = xbmcvfs.exists("special://home/userdata/addon_data/script.audio.rhapsody/.clean_me")
	files = [".albumdb.obj", ".artistdb.obj", ".genres.obj", ".rhapuser.obj"]
	#now = time.time()
	#print "current timestamp, type: %s  %s" % (str(now), type(now))
	if file_flag:
		print "Found the clean_me file! Now let's delete it"
		xbmcvfs.delete("special://home/userdata/addon_data/script.audio.rhapsody/.clean_me")
	else:
		print "No clean-me file. Let's check file dates"
		for item in files:
			f = "special://home/userdata/addon_data/script.audio.rhapsody/"+item
			f_os = xbmc.translatePath(f)
			print "Checking "+f_os
			if xbmcvfs.exists(f):
				modifiedTime = os.path.getmtime(f_os)
				if modifiedTime < AGE_STAMP:
					file_flag = True
					print "%s is too old. Let's do some housekeeping." % (item)
					break
	if file_flag:
		print "Deleting files..."
		for item in files:
			f = "special://home/userdata/addon_data/script.audio.rhapsody/"+item
			f_os = xbmc.translatePath(f)
			print "Deleting "+f_os
			if xbmcvfs.exists(f):
				xbmcvfs.delete(f)
		print "Performed housekeeping"
	else:
		print "No housekeeping necessary"
Beispiel #25
0
def getAllColors():
    # get all colors from the colors xml file and fill a list with tuples to sort later on
    allColors = []
    colors_file = xbmc.translatePath(
        "special://home/addons/script.skin.helper.service/resources/colors/colors.xml"
    ).decode("utf-8")
    if xbmcvfs.exists(colors_file):
        doc = parse(colors_file)
        listing = doc.documentElement.getElementsByTagName("color")
        for count, color in enumerate(listing):
            name = color.attributes["name"].nodeValue.lower()
            colorstring = color.childNodes[0].nodeValue.lower()
            allColors.append((name, colorstring))

    # get skin colors too
    colors_file = xbmc.translatePath("special://skin/colors/defaults.xml").decode("utf-8")
    if xbmcvfs.exists(colors_file):
        doc = parse(colors_file)
        listing = doc.documentElement.getElementsByTagName("color")
        for count, color in enumerate(listing):
            name = color.attributes["name"].nodeValue.lower()
            colorstring = color.childNodes[0].nodeValue.lower()
            allColors.append((name, colorstring))

    return allColors
Beispiel #26
0
    def setThumbnail(self, service, url=''):

        #load cachePath if not already loaded
        if self.cachePath == '':
            self.cachePath = service.settings.cachePath


        # there is no cache path setting or the setting is unset -- we should assume user does not want to use caching
        if not service.settings.cacheThumbnails or self.cachePath == '':

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

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

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

        #user doesn't want to cache thumbnails
        if not service.settings.cacheThumbnails:
            return url

        cachePath = str(self.cachePath) + str(self.package.file.id) + '/'
        cacheFile = str(self.cachePath) + str(self.package.file.id) + '.jpg'
        if not xbmcvfs.exists(cachePath):
            xbmcvfs.mkdirs(cachePath)
        if not xbmcvfs.exists(cacheFile):
            cacheFile = service.downloadGeneralFile(url, cacheFile)
            if cacheFile is None:
                return url
        return cacheFile
Beispiel #27
0
def season(name, url, mode, thumb, series_name, series_id):
    entries = []
    filename = series_id + '.jpg'
    cover_file = xbmc.translatePath(utility.cover_cache_dir() + filename)
    fanart_file = xbmc.translatePath(utility.fanart_cache_dir() + filename)
    u = sys.argv[0]
    u += '?url=' + urllib.quote_plus(unicode(url))
    u += '&mode=' + mode
    u += '&series_id=' + urllib.quote_plus(series_id)
    list_item = xbmcgui.ListItem(name)
    list_item.setArt({'icon': 'DefaultTVShows.png', 'thumb': thumb})
    list_item.setInfo(type='video', infoLabels={'title': name})
    if xbmcvfs.exists(fanart_file):
        list_item.setProperty('fanart_image', fanart_file)
    elif xbmcvfs.exists(cover_file):
        list_item.setProperty('fanart_image', cover_file)
    else:
        list_item.setProperty('fanart_image', utility.addon_fanart())
    entries.append((utility.get_string(30150),
                    'RunPlugin(plugin://%s/?mode=add_series_to_library&url=%s&name=%s&series_id=%s)' % (
                        utility.addon_id, urllib.quote_plus(unicode(url)),
                        urllib.quote_plus(utility.encode(series_name.strip())),
                        series_id)))
    list_item.addContextMenuItems(entries)
    directory_item = xbmcplugin.addDirectoryItem(handle=plugin_handle, url=u, listitem=list_item, isFolder=True)
    return directory_item
Beispiel #28
0
 def get_database(self):
     '''get reference to our sqllite database - performs basic integrity check'''
     addon = xbmcaddon.Addon(ADDON_ID)
     dbpath = addon.getAddonInfo('profile')
     dbfile = xbmc.translatePath("%s/simplecache.db" % dbpath).decode('utf-8')
     if not xbmcvfs.exists(dbpath):
         xbmcvfs.mkdirs(dbpath)
     del addon
     try:
         connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
         connection.execute('SELECT * FROM simplecache LIMIT 1')
         return connection
     except Exception as error:
         # our database is corrupt or doesn't exist yet, we simply try to recreate it
         if xbmcvfs.exists(dbfile):
             xbmcvfs.delete(dbfile)
         try:
             connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
             connection.execute(
                 """CREATE TABLE IF NOT EXISTS simplecache(
                 id TEXT UNIQUE, expires INTEGER, data TEXT, checksum INTEGER)""")
             return connection
         except Exception as error:
             self.log_msg("Exception while initializing database: %s" % str(error), xbmc.LOGWARNING)
             self.close()
             return None
Beispiel #29
0
def makeSTRM(filepath, filename, url):
    filepath = stringUtils.multiRstrip(filepath.decode("utf-8"))
    filename = filename.decode("utf-8")
    
    utils.addon_log('makeSTRM')
    filepath = os.path.join(STRM_LOC, filepath)
    
    if not xbmcvfs.exists(filepath): 
        xbmcvfs.mkdirs(filepath)
    fullpath = xbmc.translatePath(os.path.join(filepath, filename + '.strm'))

    if xbmcvfs.exists(fullpath):
        if addon.getSetting('Clear_Strms') == 'true':
            x = 0 #xbmcvfs.delete(fullpath)
        else:
            return fullpath
    else:
        try:
            fle = open(fullpath.encode("utf-8"), "w")
        except:
            fle = open(fullpath.decode("utf-8"), "w")
            pass
        fle.write("%s" % url)
        fle.close()
        del fle
        return fullpath
Beispiel #30
0
def addBiblioteca(nome, url, tipo, temporada=False, episodio=False):
    updatelibrary = True

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

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

    strm_contents = "plugin://plugin.video.tugaio/?url=" + url + "&mode=3&name=" + urllib.quote_plus(nome)
    savefile(urllib.quote_plus(title) + ".strm", strm_contents, file_folder)
    if updatelibrary:
        xbmc.executebuiltin("XBMC.UpdateLibrary(video)")
    return True
    def _updateDialogVideoInfo(self):
        # Get the location of the information dialog XML file
        dialogXml = os_path_join(self.confpath, 'DialogVideoInfo.xml')
        log("DialogVideoInfo: Confluence dialog XML file: %s" % dialogXml)

        # Make sure the file exists (It should always exist)
        if not xbmcvfs.exists(dialogXml):
            log(
                "DialogVideoInfo: Unable to find the file DialogVideoInfo.xml, skipping file",
                xbmc.LOGERROR)
            self.errorToLog = True
            return

        # Load the DialogVideoInfo.xml into a string
        dialogXmlFile = xbmcvfs.File(dialogXml, 'r')
        dialogXmlStr = dialogXmlFile.read()
        dialogXmlFile.close()

        # Now check to see if the skin file has already had the video extras bits added
        if 'script.videoextras' in dialogXmlStr:
            # Already have video extras referenced, so we do not want to do anything else
            # to this file
            log(
                "DialogVideoInfo: Video extras already referenced in %s, skipping file"
                % dialogXml, xbmc.LOGINFO)
            self.errorToLog = True
            return

        # Now add the include link to the file
        dialogXmlStr = self._addIncludeToXml(dialogXmlStr)

        # Start by adding the onLoad section
        previousOnLoad = '<controls>'

        if previousOnLoad not in dialogXmlStr:
            # The file has had a standard component deleted, so quit
            log(
                "DialogVideoInfo: Could not find controls command, skipping file",
                xbmc.LOGERROR)
            self.errorToLog = True
            return

        # Now add the Video Extras onLoad command after the allowoverlay one
        DIALOG_VIDEO_INFO_ONLOAD = '<onload condition="System.HasAddon(script.videoextras)">RunScript(script.videoextras,check,"$INFO[ListItem.FilenameAndPath]")</onload>\n\t'
        insertTxt = DIALOG_VIDEO_INFO_ONLOAD + previousOnLoad
        dialogXmlStr = dialogXmlStr.replace(previousOnLoad, insertTxt)

        # Now we need to add the button after the Final button
        previousButton = '<label>13511</label>'

        if previousButton not in dialogXmlStr:
            # The file has had a standard component deleted, so quit
            log("DialogVideoInfo: Could not find final button, skipping file",
                xbmc.LOGERROR)
            self.errorToLog = True
            return

        # Check to make sure we use a unique ID value for the button
        idOK = False
        idval = 101
        while not idOK:
            idStr = "id=\"%d\"" % idval
            if idStr not in dialogXmlStr:
                idOK = True
            else:
                idval = idval + 1

        # Now add the Video Extras button after the Final one
        DIALOG_VIDEO_INFO_BUTTON = '''\n\t\t\t\t\t</control>\n\t\t\t\t\t<control type="button" id="%d">
\t\t\t\t\t\t<description>Extras</description>
\t\t\t\t\t\t<include>ButtonInfoDialogsCommonValues</include>
\t\t\t\t\t\t<label>$ADDON[script.videoextras 32001]</label>
\t\t\t\t\t\t<onclick>RunScript(script.videoextras,display,"$INFO[ListItem.FilenameAndPath]")</onclick>
\t\t\t\t\t\t<visible>System.HasAddon(script.videoextras) + [Container.Content(movies) | Container.Content(episodes) | Container.Content(TVShows) | Container.Content(musicvideos)] + IsEmpty(Window(movieinformation).Property("HideVideoExtrasButton"))</visible>'''

        insertTxt = previousButton + (DIALOG_VIDEO_INFO_BUTTON % idval)
        dialogXmlStr = dialogXmlStr.replace(previousButton, insertTxt)

        # Now add the section for the icon overlay
        iconPrevious = 'VideoTypeHackFlaggingConditions</include>'
        if iconPrevious not in dialogXmlStr:
            log(
                "DialogVideoInfo: Could not find point to add icon overlay, skipping overlay addition",
                xbmc.LOGERROR)
            self.errorToLog = True
            return

        DIALOG_VIDEO_INFO_ICON = '''\n\t\t\t\t\t<!-- Add the Video Extras Icon -->
\t\t\t\t\t<include>VideoExtrasLargeIcon</include>
\t\t\t\t</control>
\t\t\t\t<control type="grouplist">
\t\t\t\t\t<description>Add the Video Extras Icon</description>
\t\t\t\t\t<left>210</left>
\t\t\t\t\t<top>480</top>
\t\t\t\t\t<width>600</width>
\t\t\t\t\t<align>left</align>
\t\t\t\t\t<itemgap>2</itemgap>
\t\t\t\t\t<orientation>horizontal</orientation>
\t\t\t\t\t<include>VisibleFadeEffect</include>
\t\t\t\t\t<visible>!Control.IsVisible(50) + Container.Content(tvshows) + !Container.Content(Episodes)</visible>
\t\t\t\t\t<include>VideoExtrasLargeIcon</include>'''

        insertTxt = iconPrevious + DIALOG_VIDEO_INFO_ICON
        dialogXmlStr = dialogXmlStr.replace(iconPrevious, insertTxt)

        self._saveNewFile(dialogXml, dialogXmlStr)
Beispiel #32
0
    def main(self, env):

        if (env == 'urlresolver'):
            addon('script.module.urlresolver').openSettings()
            return

        elif (env == 'metahandler'):
            addon('script.module.metahandler').openSettings()
            return

        elif (env == 'changelog_old'):
            try:
                sUrl = 'https://raw.githubusercontent.com/zombiB/zombi-addons/master/plugin.video.matrix/changelog.txt'
                oRequest =  urllib2.Request(sUrl)
                oResponse = urllib2.urlopen(oRequest)
                sContent = oResponse.read()
                self.TextBoxes('matrix Changelog', sContent)
            except:
                self.DIALOG.VSerror("%s, %s" % (self.ADDON.VSlang(30205), sUrl))
            return

        elif (env == 'changelog'):

            class XMLDialog(xbmcgui.WindowXMLDialog):

                def __init__(self, *args, **kwargs):
                    xbmcgui.WindowXMLDialog.__init__(self)
                    pass

                def onInit(self):

                    self.container = self.getControl(6)
                    self.button = self.getControl(5)
                    self.getControl(3).setVisible(False)
                    self.getControl(1).setLabel('ChangeLog')
                    self.button.setLabel('OK')

                    sUrl = 'https://api.github.com/repos/zombiB/zombi-addons/commits'
                    oRequest =  urllib2.Request(sUrl)
                    oResponse = urllib2.urlopen(oRequest)
                    sContent = oResponse.read()
                    result = json.loads(sContent)
                    listitems = []

                    for item in result:
                        #autor
                        icon = item['author']['avatar_url']
                        login = item['author']['login']
                        #message
                        try:
                            desc = item['commit']['message'].encode("utf-8")
                        except:
                            desc = 'None'

                        listitem = xbmcgui.ListItem(label = login, label2 = desc)
                        listitem.setArt({'icon': icon, 'thumb': icon})

                        listitems.append(listitem)
                    self.container.addItems(listitems)


                    self.setFocus(self.container)

                def onClick(self, controlId):
                    self.close()
                    return

                def onFocus(self, controlId):
                    self.controlId = controlId

                def _close_dialog( self ):
                    self.close()

            #path = cConfig().getAddonPath()
            path = "special://home/addons/plugin.video.matrix"
            wd = XMLDialog('DialogSelect.xml', path, "Default")
            wd.doModal()
            del wd
            return

        elif (env == 'soutient'):
            try:
                sUrl = 'https://raw.githubusercontent.com/zombiB/zombi-addons/master/plugin.video.matrix/soutient.txt'
                oRequest =  urllib2.Request(sUrl)
                oResponse = urllib2.urlopen(oRequest)
                sContent = oResponse.read()
                self.TextBoxes('matrix Soutient', sContent)
            except:
                self.DIALOG.VSerror("%s, %s" % (self.ADDON.VSlang(30205), sUrl))
            return

        elif (env == 'addon'):
            if self.DIALOG.VSyesno(self.ADDON.VSlang(30456)):
                #cached_Cache = cConfig().getFileCache()
                #cached_Cache = xbmc.translatePath(cached_Cache).decode("utf-8")
                cached_Cache = "special://home/userdata/addon_data/plugin.video.matrix/video_cache.db"
                #self.ClearDir2(cached_Cache, True)
                try:
                    xbmcvfs.delete(cached_Cache)
                    self.DIALOG.VSinfo('Clear Addon Cache, Successful[CR](Important relancer matrix)')
                except:
                    self.DIALOG.VSerror('Clear Addon Cache, Error')

            return

        elif (env == 'clean'):
            liste = ['Historiques', 'Lecture en cours', 'Marqués vues', 'Marque-Pages', 'Téléchargements']
            ret = self.DIALOG.select('BDD à supprimer', liste)
            #cached_DB = cConfig().getFileDB()
            cached_DB = "special://home/userdata/addon_data/plugin.video.matrix/matrix.db"
            #important seul xbmcvfs peux lire le special
            cached_DB = xbmc.translatePath(cached_DB).decode("utf-8")

            sql_drop = ""

            if ret > -1:

                if ret == 0:
                    sql_drop = "DROP TABLE history"
                elif ret == 1:
                    sql_drop = "DROP TABLE resume"
                elif ret == 2:
                    sql_drop = "DROP TABLE watched"
                elif ret == 3:
                    sql_drop = "DROP TABLE favorite"
                elif ret == 4:
                    sql_drop = "DROP TABLE download"

                try:
                    db = sqlite.connect(cached_DB)
                    dbcur = db.cursor()
                    dbcur.execute(sql_drop)
                    db.commit()
                    dbcur.close()
                    db.close()
                    self.DIALOG.VSok("Suppression BDD, Successful[CR](Important relancer matrix)")
                except:
                    self.DIALOG.VSerror("Suppression BDD, Error")

            return

        elif (env == 'xbmc'):
            if self.DIALOG.VSyesno(self.ADDON.VSlang(30456)):
                #temp = xbmc.translatePath('special://temp/').decode("utf-8")
                path = "special://temp/"
                #self.ClearDir(temp,True)
                try:
                    xbmcvfs.rmdir(path, True)
                    self.DIALOG.VSok('Clear Temp Cache, Successful[CR](Important relancer Kodi)')
                except:
                    self.DIALOG.VSerror('Clear Temp Cache, Error')
            return

        elif (env == 'fi'):
            if self.DIALOG.VSyesno(self.ADDON.VSlang(30456)):
                #path = xbmc.translatePath('special://temp/').decode("utf-8")
                path = "special://temp/archive_cache/"
                try:
                    xbmcvfs.rmdir(path, True)
                    self.DIALOG.VSok('Clear Archive_cache Cache, Successful[CR](Important relancer Kodi)')
                except:
                    self.DIALOG.VSerror('Clear Archive_cache Cache, Error')
                # filenames = next(os.walk(path))[2]
                # for i in filenames:
                #     if ".fi" in i:
                #         os.remove(os.path.join(path, i))
            return

        elif (env == 'uplog'):
            if self.DIALOG.VSyesno(self.ADDON.VSlang(30456)):
                #path = xbmc.translatePath('special://logpath/').decode("utf-8")
                path = "special://logpath/kodi.log"
                UA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'
                headers = {'User-Agent': UA}
                #filenames = next(os.walk(path))[2]
                #for i in filenames:
                if xbmcvfs.exists(path):
                    post_data = {}
                    cUrl = 'http://slexy.org/index.php/submit'
                    #logop = open(path + i, 'rb')
                    logop = xbmcvfs.File(path, 'rb')
                    result = logop.read()
                    logop.close()
                    post_data['raw_paste'] = result
                    post_data['author'] = 'kodi.log'
                    post_data['language'] = 'text'
                    post_data['permissions'] = 1 #private
                    post_data['expire'] = 259200 #3j
                    post_data['submit'] = 'Submit+Paste'
                    request = urllib2.Request(cUrl, urllib.urlencode(post_data), headers)
                    reponse = urllib2.urlopen(request)
                    code = reponse.geturl().replace('http://slexy.org/view/', '')
                    reponse.close()
                    self.ADDON.setSetting('service_log', code)
                    self.DIALOG.VSok('Ce code doit être transmis lorsque vous ouvrez une issue veuillez le noter:' + '  ' + code)
            return

        elif (env == 'search'):

            from resources.lib.handler.pluginHandler import cPluginHandler
            valid = '[COLOR green][x][/COLOR]'

            class XMLDialog(xbmcgui.WindowXMLDialog):

                ADDON = addon()

                def __init__(self, *args, **kwargs):
                    xbmcgui.WindowXMLDialog.__init__( self )
                    pass

                def onInit(self):

                    self.container = self.getControl(6)
                    self.button = self.getControl(5)
                    self.getControl(3).setVisible(False)
                    self.getControl(1).setLabel(self.ADDON.VSlang(30094))
                    self.button.setLabel('OK')
                    listitems = []
                    oPluginHandler = cPluginHandler()
                    aPlugins = oPluginHandler.getAllPlugins()

                    for aPlugin in aPlugins:
                        #teste si deja dans le dsip
                        sPluginSettingsName = 'plugin_' + aPlugin[1]
                        bPlugin = self.ADDON.getSetting(sPluginSettingsName)

                        #icon = os.path.join(unicode(cConfig().getRootArt(), 'utf-8'), 'sites', aPlugin[1] + '.png')
                        icon = "special://home/addons/plugin.video.matrix/resources/art/sites/%s.png" % aPlugin[1]
                        stitle = aPlugin[0].replace('[COLOR violet]', '').replace('[COLOR orange]', '').replace('[/COLOR]', '').replace('[COLOR dodgerblue]', '').replace('[COLOR coral]', '')
                        if (bPlugin == 'true'):
                            stitle = ('%s %s') % (stitle, valid)
                        listitem = xbmcgui.ListItem(label = stitle, label2 = aPlugin[2])
                        listitem.setArt({'icon': icon, 'thumb': icon})
                        listitem.setProperty('Addon.Summary', aPlugin[2])
                        listitem.setProperty('sitename', aPlugin[1])
                        if (bPlugin == 'true'):
                            listitem.select(True)

                        listitems.append(listitem)
                    self.container.addItems(listitems)


                    self.setFocus(self.container)

                def onClick(self, controlId):
                    if controlId == 5:
                        self.close()
                        return
                    elif controlId == 99:
                        window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
                        del window
                        self.close()
                        return
                    elif controlId == 7:
                        window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
                        del window
                        self.close()
                        return
                    elif controlId == 6:
                        item = self.container.getSelectedItem()
                        if item.isSelected() == True:
                            label = item.getLabel().replace(valid, '')
                            item.setLabel(label)
                            item.select(False)
                            sPluginSettingsName = ('plugin_%s') % (item.getProperty('sitename'))
                            self.ADDON.setSetting(sPluginSettingsName, str('false'))
                        else :
                            label = ('%s %s') % (item.getLabel(), valid)
                            item.setLabel(label)
                            item.select(True)
                            sPluginSettingsName = ('plugin_%s') % (item.getProperty('sitename'))
                            self.ADDON.setSetting(sPluginSettingsName, str('true'))
                        return

                def onFocus(self, controlId):
                    self.controlId = controlId

                def _close_dialog( self ):
                    self.close()

                # def onAction( self, action ):
                    # if action.getId() in ( 9, 10, 92, 216, 247, 257, 275, 61467, 61448, ):
                        # self.close()

            #path = cConfig().getAddonPath()
            path = "special://home/addons/plugin.video.matrix"
            wd = XMLDialog('DialogSelect.xml', path, "Default")
            wd.doModal()
            del wd
            return

        elif (env == 'thumb'):

            if self.DIALOG.VSyesno('Êtes-vous sûr? Ceci effacera toutes les thumbnails'):

                text = False
                #path = xbmc.translatePath('special://userdata/Thumbnails/').decode("utf-8")
                path = "special://userdata/Thumbnails/"
                path_DB = "special://userdata/Database"
                try:
                    xbmcvfs.rmdir(path, True)
                    text = 'Clear Thumbnail Folder, Successful[CR]'
                except:
                    text = 'Clear Thumbnail Folder, Error[CR]'
                #for i in os.listdir(path):
                    # folders = os.path.join(path, i).encode('utf-8')
                    # if os.path.isdir(folders):
                    #     p = next(os.walk(folders))[2]
                    #     for x in p:
                    #         os.remove(os.path.join(folders, x).encode('utf-8'))

                #filenames = next(os.walk(path2))[2]
                folder, items = xbmcvfs.listdir(path_DB)
                items.sort()
                for sItemName in items:
                    if "extures" in sItemName:
                            cached_Cache = "/".join([path_DB, sItemName])
                            try:
                                xbmcvfs.delete(cached_Cache)
                                text += 'Clear Thumbnail DB, Successful[CR]'
                            except:
                                text += 'Clear Thumbnail DB, Error[CR]'

                if text:
                    text = "%s (Important relancer Kodi)" % text
                    self.DIALOG.VSok(text)
                # for x in filenames:
                #     if "exture" in x:
                #         con = sqlite.connect(os.path.join(path2, x).encode('utf-8'))
                #         cursor = con.cursor()
                #         cursor.execute("DELETE FROM texture")
                #         con.commit()
                #         cursor.close()
                #         con.close()
            return

        elif (env == 'sauv'):
            #dialog.select('Choose a playlist', ['Playlist #1', 'Playlist #2, 'Playlist #3'])
            select = self.DIALOG.VSselect(['Import', 'Export'])
            DB = "special://home/userdata/addon_data/plugin.video.matrix/matrix.db"
            if select >= 0:
                #new = self.DIALOG.browse(3, 'matrix', 'files')
                new = self.DIALOG.browse(3, 'matrix', "files")
                if new:
                    try:
                        if select == 0:
                            xbmcvfs.delete(DB)
                            #copy(source, destination)--copy file to destination, returns true/false.
                            xbmcvfs.copy(new + 'matrix.db', DB)
                        elif select == 1:
                            #copy(source, destination)--copy file to destination, returns true/false.
                            xbmcvfs.copy(DB, new + 'matrix.db')
                        self.DIALOG.VSinfo('Import/Export DB, Successful')
                    except:
                        self.DIALOG.VSerror('Import/Export DB, Error')

                return

        else:
            return

        return
Beispiel #33
0
	def doDownloadFilm( self, filmid, quality ):
		if self.settings.downloadpath:
			film = self.db.RetrieveFilmInfo( filmid )
			if film is None:
				# film not found - should never happen
				return

			# check if the download path is reachable
			if not xbmcvfs.exists( self.settings.downloadpath ):
				self.notifier.ShowError( self.language( 30952 ), self.language( 30979 ) )
				return

			# get the best url
			if quality == '0' and film.url_video_sd:
				videourl = film.url_video_sd
			elif quality == '2' and film.url_video_hd:
				videourl = film.url_video_hd
			else:
				videourl = film.url_video

			# prepare names
			showname	= mvutils.cleanup_filename( film.show )[:64]
			filestem	= mvutils.cleanup_filename( film.title )[:64]
			extension	= os.path.splitext( videourl )[1]
			if not extension:
				extension = u'.mp4'
			if not filestem:
				filestem = u'Film-{}'.format( film.id )
			if not showname:
				showname = filestem

			# prepare download directory and determine episode number
			dirname = self.settings.downloadpath + showname + '/'
			episode = 1
			if xbmcvfs.exists( dirname ):
				( dirs, epfiles, ) = xbmcvfs.listdir( dirname )
				for epfile in epfiles:
					match = re.search( '^.* [eE][pP]([0-9]*)\.[^/]*$', epfile )
					if match and len( match.groups() ) > 0:
						if episode <= int( match.group(1) ):
							episode = int( match.group(1) ) + 1
			else:
				xbmcvfs.mkdir( dirname )

			# prepare resulting filenames
			fileepi = filestem + u' - EP%04d' % episode
			movname = dirname + fileepi + extension
			srtname = dirname + fileepi + u'.srt'
			ttmname = dirname + fileepi + u'.ttml'
			nfoname = dirname + fileepi + u'.nfo'

			# download video
			bgd = KodiBGDialog()
			bgd.Create( self.language( 30974 ), fileepi + extension )
			try:
				bgd.Update( 0 )
				result = mvutils.url_retrieve_vfs( videourl, movname, bgd.UrlRetrieveHook )
				bgd.Close()
				if result is not None:
					self.notifier.ShowNotification( self.language( 30960 ), self.language( 30976 ).format( videourl ) )
			except Exception as err:
				bgd.Close()
				self.error( 'Failure downloading {}: {}', videourl, err )
				self.notifier.ShowError( self.language( 30952 ), self.language( 30975 ).format( videourl, err ) )

			# download subtitles
			if film.url_sub:
				bgd = KodiBGDialog()
				bgd.Create( self.language( 30978 ), fileepi + u'.ttml' )
				try:
					bgd.Update( 0 )
					result = mvutils.url_retrieve_vfs( film.url_sub, ttmname, bgd.UrlRetrieveHook )
					try:
						ttml2srt( xbmcvfs.File( ttmname, 'r' ), xbmcvfs.File( srtname, 'w' ) )
					except Exception as err:
						self.info( 'Failed to convert to srt: {}', err )
					bgd.Close()
				except Exception as err:
					bgd.Close()
					self.error( 'Failure downloading {}: {}', film.url_sub, err )

			# create NFO Files
			self._make_nfo_files( film, episode, dirname, nfoname, videourl )
		else:
			self.notifier.ShowError( self.language( 30952 ), self.language( 30958 ) )
Beispiel #34
0
from datetime import datetime
import urllib
import requests, cookielib
import YDStreamExtractor

from cookielib import LWPCookieJar
cj = cookielib.CookieJar()
addon = xbmcaddon.Addon()

profile = xbmc.translatePath(addon.getAddonInfo('profile')).decode("utf-8")
temp = xbmc.translatePath(os.path.join(profile, 'temp', '')).decode("utf-8")
session = requests.session()
addon_handle = int(sys.argv[1])

thread = "https://www.kodinerds.net/index.php/Thread/11148-Was-ist-eure-Lieblingsserie-Serientalk-Empfehlungen/"
if not xbmcvfs.exists(temp):
    xbmcvfs.mkdirs(temp)


def debug(content):
    log(content, xbmc.LOGDEBUG)


def notice(content):
    log(content, xbmc.LOGNOTICE)


def log(msg, level=xbmc.LOGNOTICE):
    addon = xbmcaddon.Addon()
    addonID = addon.getAddonInfo('id')
    xbmc.log('%s: %s' % (addonID, msg), level)
    try:
        log_path = getLogPath()
        start_dir = ""
        dest_folder = xbmcgui.Dialog().browse(0, "Select folder to copy log file into", "files", "", False, False, start_dir, False)
        dest_path = "kodi " + datetime.datetime.now().strftime("%y-%m-%d %H-%M-%S") + ".log"
        dest_path = dest_folder + dest_path.replace(" ", "_")
        # Write VPN log to log before copying
        writeVPNLog()
        debugTrace("Copying " + log_path + " to " + dest_path)
        addon = xbmcaddon.Addon("service.vpn.manager")
        infoTrace("managefiles.py", "Copying log file to " + dest_path + ".  Using version " + addon.getSetting("version_number"))
        xbmcvfs.copy(log_path, dest_path)
        dialog_message = "Copied log file to:\n" + dest_path
    except:
        errorTrace("Failed to copy log from " + log_path + " to " + dest_path)
        if xbmcvfs.exists(log_path):
            dialog_message = "Error copying log, try copying it to a different location."
        else:
            dialog_messsage = "Could not find the kodi.log file."
        errorTrace("managefiles.py", dialog_message + " " + log_path + ", " + dest_path)
    xbmcgui.Dialog().ok("Log Copy", dialog_message)


# Delete the user key and cert files        
elif action == "user":
    if addon.getSetting("1_vpn_validated") == "" or xbmcgui.Dialog().yesno(addon_name, "Deleting key and certificate files will reset all VPN connections.  Connections must be re-validated before use.\nContinue?"):

        # Reset the connection before we do anything else
        if isVPNConnected(): resetVPNConnections(addon)
    
        # Select the provider
Beispiel #36
0
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])
addon = xbmcaddon.Addon()
# Lade Sprach Variablen
translation = addon.getLocalizedString


xbmcplugin.setContent(addon_handle, 'movies')

icon = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('path')+'/icon.png').decode('utf-8')
bitrate=addon.getSetting("bitrate")

profile    = xbmc.translatePath( addon.getAddonInfo('profile') ).decode("utf-8")
temp       = xbmc.translatePath( os.path.join( profile, 'temp', '') ).decode("utf-8")

if xbmcvfs.exists(temp):
  shutil.rmtree(temp)
xbmcvfs.mkdirs(temp)
cookie=os.path.join( temp, 'cookie.jar')
cj = cookielib.LWPCookieJar();

if xbmcvfs.exists(cookie):
    cj.load(cookie,ignore_discard=True, ignore_expires=True)                  

def debug(content):
    log(content, xbmc.LOGDEBUG)
    
def notice(content):
    log(content, xbmc.LOGNOTICE)

def log(msg, level=xbmc.LOGNOTICE):
Beispiel #37
0
 def make_nfo(self):
     if not xbmcvfs.exists(self.nfo_filepath):
         nfo_file = xbmcvfs.File(self.nfo_filepath, 'w')
         nfo_file.write(self.nfo_content)
         nfo_file.close()
Beispiel #38
0
def download_artwork(folderpath, artwork):
    """download artwork to local folder"""
    efa_path = ""
    new_dict = {}
    if not xbmcvfs.exists(folderpath):
        xbmcvfs.mkdir(folderpath)
    if sys.version_info.major == 3:
        for key, value in artwork.items():
            if key == "fanart":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "fanart.jpg"), value)
            elif key == "thumb":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "folder.jpg"), value)
            elif key == "discart":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "disc.png"), value)
            elif key == "banner":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "banner.jpg"), value)
            elif key == "clearlogo":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "logo.png"), value)
            elif key == "clearart":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "clearart.png"), value)
            elif key == "characterart":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "characterart.png"), value)
            elif key == "poster":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "poster.jpg"), value)
            elif key == "landscape":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "landscape.jpg"), value)
            elif key == "thumbback":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "thumbback.jpg"), value)
            elif key == "spine":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "spine.jpg"), value)
            elif key == "album3Dthumb":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "album3Dthumb.png"), value)
            elif key == "album3Dflat":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "album3Dflat.png"), value)
            elif key == "album3Dcase":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "album3Dcase.png"), value)
            elif key == "album3Dface":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "album3Dface.png"), value)
            elif key == "fanarts" and value:
                # copy extrafanarts only if the directory doesn't exist at all
                delim = "\\" if "\\" in folderpath else "/"
                efa_path = "%sextrafanart" % folderpath + delim
                if not xbmcvfs.exists(efa_path):
                    xbmcvfs.mkdir(efa_path)
                    images = []
                    for count, image in enumerate(value):
                        image = download_image(
                            os.path.join(efa_path, "fanart%s.jpg" % count),
                            image)
                        images.append(image)
                        if LIMIT_EXTRAFANART and count == LIMIT_EXTRAFANART:
                            break
                    new_dict[key] = images
            elif key == "posters" and value:
                # copy extraposters only if the directory doesn't exist at all
                delim = "\\" if "\\" in folderpath else "/"
                efa_path = "%sextraposter" % folderpath + delim
                if not xbmcvfs.exists(efa_path):
                    xbmcvfs.mkdir(efa_path)
                    images = []
                    for count, image in enumerate(value):
                        image = download_image(
                            os.path.join(efa_path, "poster%s.jpg" % count),
                            image)
                        images.append(image)
                        if LIMIT_EXTRAFANART and count == LIMIT_EXTRAFANART:
                            break
                    new_dict[key] = images
            else:
                new_dict[key] = value
    else:
        for key, value in artwork.iteritems():
            if key == "fanart":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "fanart.jpg"), value)
            elif key == "thumb":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "folder.jpg"), value)
            elif key == "discart":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "disc.png"), value)
            elif key == "banner":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "banner.jpg"), value)
            elif key == "clearlogo":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "logo.png"), value)
            elif key == "clearart":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "clearart.png"), value)
            elif key == "characterart":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "characterart.png"), value)
            elif key == "poster":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "poster.jpg"), value)
            elif key == "landscape":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "landscape.jpg"), value)
            elif key == "thumbback":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "thumbback.jpg"), value)
            elif key == "spine":
                new_dict[key] = download_image(
                    os.path.join(folderpath, "spine.jpg"), value)
            elif key == "fanarts" and value:
                # copy extrafanarts only if the directory doesn't exist at all
                delim = "\\" if "\\" in folderpath else "/"
                efa_path = "%sextrafanart" % folderpath + delim
                if not xbmcvfs.exists(efa_path):
                    xbmcvfs.mkdir(efa_path)
                    images = []
                    for count, image in enumerate(value):
                        image = download_image(
                            os.path.join(efa_path, "fanart%s.jpg" % count),
                            image)
                        images.append(image)
                        if LIMIT_EXTRAFANART and count == LIMIT_EXTRAFANART:
                            break
                    new_dict[key] = images
            elif key == "posters" and value:
                # copy extraposters only if the directory doesn't exist at all
                delim = "\\" if "\\" in folderpath else "/"
                efa_path = "%sextraposter" % folderpath + delim
                if not xbmcvfs.exists(efa_path):
                    xbmcvfs.mkdir(efa_path)
                    images = []
                    for count, image in enumerate(value):
                        image = download_image(
                            os.path.join(efa_path, "poster%s.jpg" % count),
                            image)
                        images.append(image)
                        if LIMIT_EXTRAFANART and count == LIMIT_EXTRAFANART:
                            break
                    new_dict[key] = images
            else:
                new_dict[key] = value
    if efa_path:
        new_dict["extrafanart"] = efa_path
    return new_dict
Beispiel #39
0
settings = settings()
original_settings = settings.read_settings_xml()

trivia_settings = settings.trivia_settings
trailer_settings = settings.trailer_settings
ha_settings = settings.ha_settings
video_settings = settings.video_settings
audio_formats = settings.audio_formats
extra_settings = settings.extra_settings
_3d_settings = settings._3d_settings
triggers = settings.triggers

#Check to see if module is moved to /userdata/addon_data/script.cinema.experience

if not xbmcvfs.exists(
        os.path.join(BASE_CURRENT_SOURCE_PATH, "ha_scripts",
                     "home_automation.py")) and ha_settings["ha_enable"]:
    source = os.path.join(BASE_RESOURCE_PATH, "ha_scripts",
                          "home_automation.py")
    destination = os.path.join(BASE_CURRENT_SOURCE_PATH, "ha_scripts",
                               "home_automation.py")
    xbmcvfs.mkdir(os.path.join(BASE_CURRENT_SOURCE_PATH, "ha_scripts"))
    xbmcvfs.copy(source, destination)
    utils.log("home_automation.py copied")

from launch_automation import Launch_automation


class CE_Monitor(xbmc.Monitor):
    def __init__(self, *args, **kwargs):
        xbmc.Monitor.__init__(self)
Beispiel #40
0
                               or channelLST.chkSkinPath())
        channelLST.mediaFolder = os.path.join(channelLST.skinPath, 'resources',
                                              'skins', 'default', 'media')
        channelLST.refreshPath = utils.loadJson(
            utils.unquote(params.get('refresh_path', '')) or utils.ADDON_ID)
        channelLST.refreshIntvl = int(
            utils.loadJson(utils.unquote(params.get('refresh_interval', '')))
            or '0')
        channelLST.skinFolder = os.path.join(
            channelLST.skinPath,
            'resources',
            'skins',
            'default',
            '1080i',
        ) if xbmcvfs.exists(
            os.path.join(channelLST.skinPath, 'resources', 'skins', 'default',
                         '1080i', '%s.guide.xml' %
                         utils.ADDON_ID)) else os.path.join(
                             channelLST.skinPath, 'resources', 'skins',
                             'default', '720p')
        utils.setProperty(
            'uEPG.rowCount',
            utils.loadJson(utils.unquote(params.get('row_count', '')) or '9'))
        channelLST.pluginName, channelLST.pluginAuthor, channelLST.pluginIcon, channelLST.pluginFanart, channelLST.pluginPath = utils.getPluginMeta(
            channelLST.refreshPath)

        utils.log('dataType = ' + str(dataType))
        utils.log('skinPath = ' + str(channelLST.skinPath))
        utils.log('skinFolder = ' + str(channelLST.skinFolder))
        utils.log('refreshPath = ' + str(channelLST.refreshPath))
        utils.log('refreshIntvl = ' + str(channelLST.refreshIntvl))
        utils.setProperty('PluginName', channelLST.pluginName)
Beispiel #41
0
    map_name = getKeyMapsFileName()
    xml_start = '<keymap><global><keyboard>\n'
    xml_key = '<key id="#KEY">runscript(#PATH#COMMAND)</key>\n'
    xml_long = '<key id="#KEY" mod="longpress">runscript(#PATH#COMMAND)</key>\n'
    xml_end = '</keyboard></global></keymap>\n'
    cycle_command = "cycle.py"
    table_command = "table.py"
    info_command = "infopopup.py"

    # Fix the keymap if it's been renamed by the Keymap addon
    fixKeymaps()

    lines = []

    # Read any existing keymap and the keys we're interested in
    if xbmcvfs.exists(getKeyMapsPath(map_name)):
        path = getKeyMapsPath(map_name)
        try:
            debugTrace("Writing the map file to " + path)
            map_file = open(path, 'r')
            lines = map_file.readlines()
            map_file.close()
            i = 0
            for line in lines:
                if cycle_command in line:
                    i1 = line.index("key id=\"") + 8
                    i2 = line.index("\"", i1)
                    cycle_key = line[i1:i2]
                    debugTrace("Found cycle key " + cycle_key)
                    lines[i] = ""
                if table_command in line:
def get_themes():

    ''' Add theme media locally, via strm. This is only for tv tunes.
        If another script is used, adjust this code.
    '''
    from helper.utils import normalize_string
    from helper.playutils import PlayUtils
    from helper.xmls import tvtunes_nfo

    library = xbmc.translatePath("special://profile/addon_data/plugin.video.jellyfin/library").decode('utf-8')
    play = settings('useDirectPaths') == "1"

    if not xbmcvfs.exists(library + '/'):
        xbmcvfs.mkdir(library)

    if xbmc.getCondVisibility('System.HasAddon(script.tvtunes)'):

        tvtunes = xbmcaddon.Addon(id="script.tvtunes")
        tvtunes.setSetting('custom_path_enable', "true")
        tvtunes.setSetting('custom_path', library)
        LOG.info("TV Tunes custom path is enabled and set.")
    else:
        dialog("ok", heading="{jellyfin}", line1=_(33152))

        return

    with Database('jellyfin') as jellyfindb:
        all_views = jellyfin_db.JellyfinDatabase(jellyfindb.cursor).get_views()
        views = [x[0] for x in all_views if x[2] in ('movies', 'tvshows', 'mixed')]


    items = {}
    server = TheVoid('GetServerAddress', {'ServerId': None}).get()
    token = TheVoid('GetToken', {'ServerId': None}).get()

    for view in views:
        result = TheVoid('GetThemes', {'Type': "Video", 'Id': view}).get()

        for item in result['Items']:

            folder = normalize_string(item['Name'].encode('utf-8'))
            items[item['Id']] = folder

        result = TheVoid('GetThemes', {'Type': "Song", 'Id': view}).get()

        for item in result['Items']:

            folder = normalize_string(item['Name'].encode('utf-8'))
            items[item['Id']] = folder

    for item in items:

        nfo_path = os.path.join(library, items[item])
        nfo_file = os.path.join(nfo_path, "tvtunes.nfo")

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

        themes = TheVoid('GetTheme', {'Id': item}).get()
        paths = []

        for theme in themes['ThemeVideosResult']['Items'] + themes['ThemeSongsResult']['Items']:
            putils = PlayUtils(theme, False, None, server, token)

            if play:
                paths.append(putils.direct_play(theme['MediaSources'][0]).encode('utf-8'))
            else:
                paths.append(putils.direct_url(theme['MediaSources'][0]).encode('utf-8'))

        tvtunes_nfo(nfo_file, paths)

    dialog("notification", heading="{jellyfin}", message=_(33153), icon="{jellyfin}", time=1000, sound=False)
Beispiel #43
0
 def RechercheBase(self):
     if xbmcvfs.exists(os.path.join(self.adresseVstream,'vstream.db')):
         return True
     else:
         return False
def delete_file_safe(file_path):
    if xbmcvfs.exists(file_path):
        try:
            xbmcvfs.delete(file_path)
        finally:
            pass
Beispiel #45
0
import requests
from HTMLParser import HTMLParser

pluginhandle = int(sys.argv[1])
addon = xbmcaddon.Addon()
addonID = addon.getAddonInfo('id')
_icon = addon.getAddonInfo('icon')
_fanart = addon.getAddonInfo('fanart')
channelFavsFile = xbmc.translatePath("special://profile/addon_data/" +
                                     addonID + "/" + addonID + ".favorites")
cookie_file = xbmc.translatePath("special://profile/addon_data/" + addonID +
                                 "/cookies")
pDialog = xbmcgui.DialogProgress()
familyFilter = '1'

if not xbmcvfs.exists('special://profile/addon_data/' + addonID +
                      '/settings.xml'):
    addon.openSettings()

if addon.getSetting('family_filter') == 'false':
    familyFilter = '0'
forceViewModeNew = addon.getSetting("forceViewModeNew") == "true"
viewModeNew = str(addon.getSetting("viewModeNew"))
maxVideoQuality = addon.getSetting("maxVideoQuality")
downloadDir = addon.getSetting("downloadDir")
qual = ['240', '380', '480', '720', '1080', '1440', '2160']
maxVideoQuality = qual[int(maxVideoQuality)]
language = addon.getSetting("language")
languages = [
    "ar_ES", "br_PT", "ca_EN", "ca_FR", "de_DE", "es_ES", "fr_FR", "in_EN",
    "id_ID", "it_IT", "ci_FR", "my_MS", "mx_ES", "pk_EN", "ph_EN", "tr_TR",
    "en_GB", "en_US", "vn_VI", "kr_KO", "tw_TW"
def makepath(path):
    if xbmcvfs.exists(path):
        return xbmc.translatePath(path)
    xbmcvfs.mkdirs(path)
    return xbmc.translatePath(path)
Beispiel #47
0
from StringIO import StringIO
import gzip

import xbmc
import xbmcplugin
import xbmcgui
import xbmcaddon
import xbmcvfs
import cloudflare
from jsunpack import unpack
import resolveurl
import xbmcvfs
from functools import wraps

xxx_plugins_path = 'special://home/addons/script.module.resolveurl.xxx/resources/plugins/'
if xbmcvfs.exists(xxx_plugins_path):
    resolveurl.add_plugin_dirs(xbmc.translatePath(xxx_plugins_path))

from url_dispatcher import URL_Dispatcher

url_dispatcher = URL_Dispatcher()

USER_AGENT = resolveurl.lib.net.get_ua()

headers = {'User-Agent': USER_AGENT,
           'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
           'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
           'Accept-Encoding': 'gzip',
           'Accept-Language': 'en-US,en;q=0.8',
           'Connection': 'keep-alive'}
openloadhdr = headers
Beispiel #48
0
def video(name,
          url,
          mode,
          thumb,
          video_type='',
          description='',
          duration='',
          year='',
          mpaa='',
          director='',
          genre='',
          rating=0.0,
          remove=False):
    entries = []
    if duration:
        duration = unicode(int(duration) * 60)
    filename = utility.clean_filename(url) + '.jpg'
    cover_file = xbmc.translatePath(utility.cover_cache_dir() + filename)
    fanart_file = xbmc.translatePath(utility.fanart_cache_dir() + filename)
    if xbmcvfs.exists(cover_file):
        thumb = cover_file
    u = sys.argv[0]
    u += '?url=' + urllib.quote_plus(url)
    u += '&mode=' + mode
    u += '&name=' + urllib.quote_plus(utility.encode(name))
    u += '&thumb=' + urllib.quote_plus(thumb)
    list_item = xbmcgui.ListItem(name)
    list_item.setArt({'icon': 'DefaultTVShows.png', 'thumb': thumb})
    list_item.setInfo(type='video',
                      infoLabels={
                          'title': name,
                          'plot': description,
                          'duration': duration,
                          'year': int(year),
                          'mpaa': mpaa,
                          'director': director,
                          'genre': genre,
                          'rating': rating
                      })
    if xbmcvfs.exists(fanart_file):
        list_item.setProperty('fanart_image', fanart_file)
    elif xbmcvfs.exists(cover_file):
        list_item.setProperty('fanart_image', cover_file)
    else:
        list_item.setProperty('fanart_image', utility.addon_fanart())
    if video_type == 'tvshow':
        if utility.get_setting('browse_tv_shows') == 'true':
            entries.append((utility.get_string(
                30151
            ), 'Container.Update(plugin://%s/?mode=play_video_main&url=%s&thumb=%s)'
                            % (utility.addon_id, urllib.quote_plus(url),
                               urllib.quote_plus(thumb))))
        else:
            entries.append((utility.get_string(
                30152
            ), 'Container.Update(plugin://%s/?mode=list_seasons&url=%s&thumb=%s)'
                            % (utility.addon_id, urllib.quote_plus(url),
                               urllib.quote_plus(thumb))))
    if video_type != 'episode':
        entries.append(
            (utility.get_string(30153),
             'RunPlugin(plugin://%s/?mode=play_trailer&url=%s&type=%s)' %
             (utility.addon_id, urllib.quote_plus(
                 utility.encode(name)), video_type)))
        if remove:
            entries.append(
                (utility.get_string(30154),
                 'RunPlugin(plugin://%s/?mode=remove_from_queue&url=%s)' %
                 (utility.addon_id, urllib.quote_plus(url))))
        else:
            entries.append(
                (utility.get_string(30155),
                 'RunPlugin(plugin://%s/?mode=add_to_queue&url=%s)' %
                 (utility.addon_id, urllib.quote_plus(url))))
        entries.append((
            utility.get_string(30156),
            'Container.Update(plugin://%s/?mode=list_videos&url=%s&type=movie)'
            % (utility.addon_id,
               urllib.quote_plus(utility.main_url + '/WiMovie/' + url))))
        entries.append(
            (utility.get_string(30157),
             'Container.Update(plugin://%s/?mode=list_videos&url=%s&type=tv)' %
             (utility.addon_id,
              urllib.quote_plus(utility.main_url + '/WiMovie/' + url))))
    if video_type == 'tvshow':
        entries.append(
            (utility.get_string(30150),
             'RunPlugin(plugin://%s/?mode=add_series_to_library&url=&name=%s'
             '&seriesID=%s)' %
             (utility.addon_id, urllib.quote_plus(utility.encode(
                 name.strip())), urllib.quote_plus(url))))
    elif video_type == 'movie':
        entries.append(
            (utility.get_string(30150),
             'RunPlugin(plugin://%s/?mode=add_movie_to_library&url=%s&name=%s)'
             % (utility.addon_id, urllib.quote_plus(url),
                urllib.quote_plus(utility.encode(name.strip())) + ' (' + year +
                ')')))
    list_item.addContextMenuItems(entries)
    directory_item = xbmcplugin.addDirectoryItem(handle=plugin_handle,
                                                 url=u,
                                                 listitem=list_item,
                                                 isFolder=True)
    return directory_item
Beispiel #49
0
    def authenticate(self):

        WINDOW = self.WINDOW
        addon = self.addon

        username = self.getUsername()
        server = self.getServer()
        addondir = xbmc.translatePath(self.addon.getAddonInfo('profile'))
        hasSettings = xbmcvfs.exists("%ssettings.xml" % addondir)

        # If there's no settings.xml
        if (hasSettings == 0):
            self.logMsg("No settings.xml found.")
            self.auth = False
            return
        # If no user information
        if (server == "") or (username == ""):
            self.logMsg("Missing server information.")
            self.auth = False
            return
        # If there's a token
        if (self.getToken() != ""):
            self.loadCurrUser()
            self.logMsg("Current user: %s" % self.currUser, 0)
            self.logMsg("Current userId: %s" % self.currUserId, 0)
            self.logMsg("Current accessToken: %s" % self.currToken, 0)
            return

        users = self.getPublicUsers()
        password = ""
        '''if users == "":
            self.WINDOW.setProperty("Server_status", "Stop")
            return'''
        # Find user in list
        for user in users:
            name = user[u'Name']
            userHasPassword = False

            if (unicode(username, 'utf-8') in name):
                # Verify if user has a password
                if (user.get("HasPassword") == True):
                    userHasPassword = True
                # If user has password
                if (userHasPassword):
                    password = xbmcgui.Dialog().input(
                        "Enter password for user: %s" % username,
                        option=xbmcgui.ALPHANUM_HIDE_INPUT)
                    # If password dialog is cancelled
                    if (password == ""):
                        self.logMsg("No password entered.", 0)
                        self.WINDOW.setProperty("Server_status", "Stop")
                        self.auth = False
                        return
                break
        else:
            # Manual login, user is hidden
            password = xbmcgui.Dialog().input(
                "Enter password for user: %s" % username,
                option=xbmcgui.ALPHANUM_HIDE_INPUT)

        sha1 = hashlib.sha1(password)
        sha1 = sha1.hexdigest()

        # Authenticate username and password
        url = "%s/mediabrowser/Users/AuthenticateByName?format=json" % server
        data = {'username': username, 'password': sha1}
        self.logMsg(data, 2)

        result = self.doUtils.downloadUrl(url,
                                          postBody=data,
                                          type="POST",
                                          authenticate=False)

        accessToken = None
        try:
            self.logMsg("Auth_Reponse: %s" % result, 1)
            accessToken = result[u'AccessToken']
        except:
            pass

        if (result != None and accessToken != None):
            self.currUser = username
            userId = result[u'User'][u'Id']
            addon.setSetting("accessToken%s" % username, accessToken)
            addon.setSetting("userId%s" % username, userId)
            self.logMsg("User Authenticated: %s" % accessToken)
            self.loadCurrUser()
            self.WINDOW.setProperty("Server_status", "")
            self.retry = 0
            return
        else:
            self.logMsg("User authentication failed.")
            addon.setSetting("accessToken%s" % username, "")
            addon.setSetting("userId%s" % username, "")
            xbmcgui.Dialog().ok("Error connecting",
                                "Invalid username or password.")

            # Give two attempts at entering password
            self.retry += 1
            if self.retry == 2:
                self.logMsg("Too many retries. Please restart Kodi.")
                self.WINDOW.setProperty("Server_status", "Stop")

            self.auth = False
            return
Beispiel #50
0
def _create_destination_folder(destination_folder):
    """Create destination folder, ignore error if it already exists"""
    destination_folder = xbmc.translatePath(destination_folder)
    if not xbmcvfs.exists(destination_folder):
        xbmcvfs.mkdirs(destination_folder)
Beispiel #51
0
    def parseXMLTV(self, context, f, size, logoFolder, progress_callback):
        event, root = context.next()
        elements_parsed = 0
        meta_installed = False

        try:
            xbmcaddon.Addon("plugin.video.meta")
            meta_installed = True
        except Exception:
            pass  # ignore addons that are not installed

        for event, elem in context:
            if event == "end":
                result = None
                if elem.tag == "programme":
                    channel = elem.get("channel").replace("'", "")  # Make ID safe to use as ' can cause crashes!
                    description = elem.findtext("desc")
                    rec_url = elem.findtext("rec_url")
                    set_url = elem.findtext("set_url")
                    media_type = elem.findtext("media_type")
                    scheduleid = elem.findtext("scheduleid")
                    iconElement = elem.find("icon")
                    icon = None
                    if iconElement is not None:
                        icon = iconElement.get("src")
                    if not description:
                        description = strings(NO_DESCRIPTION)
                    if not media_type:
                        media_type = 'MV'

                    season = None
                    episode = None
                    is_movie = None
                    language = elem.find("title").get("lang")
                    if meta_installed == True:
                        episode_num = elem.findtext("episode-num")
                        categories = elem.findall("category")
                        for category in categories:
                            if "movie" in category.text.lower() or channel.lower().find("sky movies") != -1 \
                                    or "film" in category.text.lower():
                                is_movie = "Movie"
                                break

                        if episode_num is not None:
                            episode_num = unicode.encode(unicode(episode_num), 'ascii','ignore')
                            if str.find(episode_num, ".") != -1:
                                splitted = str.split(episode_num, ".")
                                if splitted[0] != "":
                                    season = int(splitted[0]) + 1
                                    is_movie = None # fix for misclassification
                                    if str.find(splitted[1], "/") != -1:
                                        episode = int(splitted[1].split("/")[0]) + 1
                                    elif splitted[1] != "":
                                        episode = int(splitted[1]) + 1

                            elif str.find(episode_num.lower(), "season") != -1 and episode_num != "Season ,Episode ":
                                pattern = re.compile(r"Season\s(\d+).*?Episode\s+(\d+).*",re.I|re.U)
                                season = int(re.sub(pattern, r"\1", episode_num))
                                episode = (re.sub(pattern, r"\2", episode_num))

                    result = Program(channel, elem.findtext('title'), self.parseXMLTVDate(elem.get('start')),
                                     self.parseXMLTVDate(elem.get('stop')), description, rec_url, set_url, media_type, scheduleid, imageSmall=icon,
                                     season = season, episode = episode, is_movie = is_movie, language= language)

                elif elem.tag == "channel":
                    cid = elem.get("id").replace("'", "")  # Make ID safe to use as ' can cause crashes!
                    title = elem.findtext("display-name")
                    logo = None
                    if logoFolder:
                        logoFile = os.path.join(logoFolder, title + '.png')
                        if self.logoSource == XMLTVSource.LOGO_SOURCE_FTV:
                            logo = logoFile.replace(' ', '%20')  # needed due to fetching from a server!
                        elif xbmcvfs.exists(logoFile):
                            logo = logoFile  # local file instead of remote!
                    streamElement = elem.find("stream")
                    streamUrl = None
                    if streamElement is not None:
                        streamUrl = streamElement.text
                    visible = elem.get("visible")
                    if visible == "0":
                        visible = False
                    else:
                        visible = True
                    result = Channel(cid, title, logo, streamUrl, visible)

                if result:
                    elements_parsed += 1
                    if progress_callback and elements_parsed % 500 == 0:
                        if not progress_callback(100.0 / size * f.tell()):
                            raise SourceUpdateCanceledException()
                    yield result

            root.clear()
        f.close()
Beispiel #52
0
import urllib
import urllib2,json
import xbmcvfs
import requests,time
import os,xbmc,xbmcaddon,xbmcgui,re
addon = xbmcaddon.Addon('plugin.video.netvstream')
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' 
      
Beispiel #53
0
    def _createDatabase(self):
        # Make sure the database does not already exist
        if not xbmcvfs.exists(self.databasefile):
            # Get a connection to the database, this will create the file
            conn = sqlite3.connect(self.databasefile)
            conn.text_factory = str
            c = conn.cursor()

            # Create the version number table, this is a simple table
            # that just holds the version details of what created it
            # It should make upgrade later easier
            c.execute('''CREATE TABLE version (version text primary key)''')

            # Insert a row for the version
            versionNum = "5"

            # Run the statement passing in an array with one value
            c.execute("INSERT INTO version VALUES (?)", (versionNum, ))

            # Create a table that will be used to store each Video and its access level
            # The "id" will be auto-generated as the primary key
            # Note: Index will automatically be created for "unique" values, so no
            # need to manually create them
            c.execute(
                '''CREATE TABLE TvShows (id integer primary key, name text unique, dbid integer unique, level integer)'''
            )
            c.execute(
                '''CREATE TABLE Movies (id integer primary key, name text unique, dbid integer unique, level integer)'''
            )
            c.execute(
                '''CREATE TABLE MovieSets (id integer primary key, name text unique, dbid integer unique, level integer)'''
            )
            c.execute(
                '''CREATE TABLE Plugins (id integer primary key, name text unique, dbid text unique, level integer)'''
            )
            c.execute(
                '''CREATE TABLE Repositories (id integer primary key, name text unique, dbid text unique, level integer)'''
            )

            # This is in version 2
            c.execute(
                '''CREATE TABLE MusicVideos (id integer primary key, name text unique, dbid integer unique, level integer)'''
            )

            # This is in version 3
            c.execute(
                '''CREATE TABLE FileSources (id integer primary key, name text unique, dbid text unique, level integer)'''
            )

            # This is in version 4
            c.execute(
                '''CREATE TABLE ClassificationsMovies (id integer primary key, name text unique, dbid text, level integer)'''
            )
            c.execute(
                '''CREATE TABLE ClassificationsTV (id integer primary key, name text unique, dbid text, level integer)'''
            )

            # Save (commit) the changes
            conn.commit()

            # We can also close the connection if we are done with it.
            # Just be sure any changes have been committed or they will be lost.
            conn.close()
"""
import time
import json
import xbmc
import xbmcvfs
import xbmcaddon

addonID = xbmcaddon.Addon().getAddonInfo('id')
addon_path = xbmc.translatePath("special://profile/addon_data/" + addonID)
NOW = int(time.time())
LAST_SCAN = 872835240

#wait a little before starting
time.sleep(5)

if xbmcvfs.exists(addon_path + '//config.json'):
    with open(addon_path + '//config.json', 'r') as f:
        CONFIG = json.load(f)
        if 'last_scan' in CONFIG:
            LAST_SCAN = CONFIG['last_scan']

if __name__ == '__main__':
    monitor = xbmc.Monitor()
    while not monitor.abortRequested():
        # Sleep/wait for abort for 10 seconds
        if monitor.waitForAbort(5):
            # Abort was requested while waiting. We should exit
            break
        if (LAST_SCAN + int(xbmcaddon.Addon().getSetting('update_interval'))*3600) <= int(time.time()) and \
            xbmcaddon.Addon().getSetting('API_key') and \
            xbmcaddon.Addon().getSetting('auto_refresh'):
Beispiel #55
0
 def exists(filename):
     try:
         return xbmcvfs.exists(filename)
     except UnicodeDecodeError:
         return FileAccess.exists(ascii(filename))
     return False
Beispiel #56
0
def autoconf():
	#Configuration for LINUX 
	if xbmc.getCondVisibility('system.platform.linux') and not xbmc.getCondVisibility('system.platform.Android') and not settings.getSetting('force_android') == "true":
		print("Detected OS: Linux")
		#Linux Armv6
		if os.uname()[4] == "armv6l":
			try:
				if re.search(os.uname()[1],"openelec",re.IGNORECASE): acestream_rpi = acestream_openelec_raspberry
				elif re.search(os.uname()[1],"raspbmc",re.IGNORECASE): acestream_rpi = acestream_generic_raspberry
				elif os.path.isfile("/etc/xbian_version"): acestream_rpi = acestream_generic_raspberry
				elif "ARCH" in os.uname()[2]:
					acestream_rpi = acestream_generic_raspberry
					settings.setSetting('python_cmd',value='python2')
				else:
					mensagemok(translate(40000),translate(400007),translate(400008))
					OS_list = ["OpenELEC","Raspbmc","Xbian","Pipplware","Arch Linux Arm"]
					url_packagerpi_list = [acestream_openelec_raspberry, acestream_generic_raspberry, acestream_generic_raspberry,acestream_generic_raspberry, acestream_generic_raspberry]
					OS_Rpi_choose = xbmcgui.Dialog().select
					choose=OS_Rpi_choose('Select your OS',OS_list)
					if choose > -1:
						acestream_rpi= url_packagerpi_list[choose]
						if OS_list[choose] == "Arch Linux Arm": settings.setSetting('python_cmd',value='python2')
			except: acestream_rpi = ""
			print("Detected linux armv6 - possible Raspberry PI")
			#Sop

			SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1])
			download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(40025),translate(40000))
			import tarfile            
			if tarfile.is_tarfile(SPSC_KIT):
				path_libraries = os.path.join(pastaperfil,"sopcast")
				download_tools().extract(SPSC_KIT,path_libraries)
				xbmc.sleep(500)
				download_tools().remove(SPSC_KIT)

            		#Ace
			SPSC_KIT = os.path.join(addonpath,acestream_rpi.split("/")[-1])
			download_tools().Downloader(acestream_rpi,SPSC_KIT,translate(40026),translate(40000))
        
			if tarfile.is_tarfile(SPSC_KIT):
				path_libraries = os.path.join(pastaperfil,"acestream")
				download_tools().extract(SPSC_KIT,path_libraries)
				xbmc.sleep(500)
				download_tools().remove(SPSC_KIT)

			settings.setSetting('autoconfig',value='false')


                elif os.uname()[4] == "armv7l":
			if re.search(os.uname()[1],"openelec",re.IGNORECASE):
				OS_Choose = "OpenELEC"
			elif os.path.isfile("/etc/xbian_version"):
				OS_Choose = "Xbian"
			else:
                		mensagemok(translate(40000),translate(40109),translate(40110))
                		OS_list = ["MXLinux","OpenELEC","Xbian"]
                		choose=xbmcgui.Dialog().select('Select your OS',OS_list)
                		if choose > -1:
                			OS_Choose= OS_list[choose]

			#Linux armv7 configuration according to platform

			#MXLINUX
                	if OS_Choose == "MXLinux":
				acestream_installed = False
				sopcast_installed = False
               			print("Detected MXLinux armv7")
               			SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1])
               			download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(40025),translate(40000))
               			import tarfile
				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"sopcast")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					sopcast_installed = True

				SPSC_KIT = os.path.join(addonpath,acestream_mxlinux.split("/")[-1])
				download_tools().Downloader(acestream_mxlinux,SPSC_KIT,translate(40026),translate(40000))
        			if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"acestream")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					acestream_installed = True
				if acestream_installed and sopcast_installed:
					settings.setSetting('autoconfig',value='false')	

			#OPENELEC

                	if OS_Choose == "OpenELEC":
                		import tarfile
				acestream_installed = False
				sopcast_installed = False
                		print("Openelec armv7 platform detected")
                		SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1])
                		download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(40025),translate(40000))
				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"sopcast")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					sopcast_installed = True
				SPSC_KIT = os.path.join(addonpath,acestream_armv7_openelec.split("/")[-1])
				download_tools().Downloader(acestream_armv7_openelec,SPSC_KIT,translate(40026),translate(40000))
        			if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"acestream")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					acestream_installed = True
				if acestream_installed and sopcast_installed:
					settings.setSetting('autoconfig',value='false')	

			#XBIAN
               		if OS_Choose == "Xbian":
               			import tarfile
				acestream_installed = False
				sopcast_installed = False
               			print("Xbian armv7 platform detected")
               			SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1])
               			download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(40025),translate(40000))
				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"sopcast")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					sopcast_installed = True
				SPSC_KIT = os.path.join(addonpath,acestream_armv7_xbian.split("/")[-1])
				download_tools().Downloader(acestream_armv7_xbian,SPSC_KIT,translate(40026),translate(40000))
       				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"acestream")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					acestream_installed = True
				if acestream_installed and sopcast_installed:
					settings.setSetting('autoconfig',value='false')	


			
		elif (os.uname()[4] == "x86_64" and re.search(os.uname()[1],"openelec",re.IGNORECASE)) or settings.getSetting('openelecx86_64') == "true":
			settings.setSetting('openelecx86_64',value='true')
			print("Detected OpenELEC x86_64")
			SPSC_KIT = os.path.join(addonpath,openelecx86_64_package.split("/")[-1])
			download_tools().Downloader(openelecx86_64_package,SPSC_KIT,translate(40112),translate(40000))
			import tarfile
			if tarfile.is_tarfile(SPSC_KIT):
				download_tools().extract(SPSC_KIT,pastaperfil)
				xbmc.sleep(500)
				download_tools().remove(SPSC_KIT)
			settings.setSetting('autoconfig',value='false')

		elif (os.uname()[4] == "i386" and re.search(os.uname()[1],"openelec",re.IGNORECASE)) or (os.uname()[4] == "i686" and re.search(os.uname()[1],"openelec",re.IGNORECASE)) or settings.getSetting('openeleci386') == "true":
			settings.setSetting('openeleci386',value='true')
			print("Detected OpenELEC i386")
			SPSC_KIT = os.path.join(addonpath,openeleci386_package.split("/")[-1])
			download_tools().Downloader(openeleci386_package,SPSC_KIT,translate(40112),translate(40000))
			import tarfile
			if tarfile.is_tarfile(SPSC_KIT):
				download_tools().extract(SPSC_KIT,pastaperfil)
				xbmc.sleep(500)
				download_tools().remove(SPSC_KIT)
			settings.setSetting('autoconfig',value='false')		
	
		else:
			if os.uname()[4] == "x86_64":
				opcao= xbmcgui.Dialog().yesno(translate(40000), translate(40113))
				if opcao: 
					settings.setSetting('openelecx86_64',value='true')
					autoconf()
			elif os.uname()[4] == "i386" or os.uname()[4] == "i686":
				opcao= xbmcgui.Dialog().yesno(translate(40000), translate(600023))
				if opcao: 
					settings.setSetting('openeleci386',value='true')
					autoconf()

			else: mensagemok(translate(40000),translate(40056))
			

			#Linux but not openelec i386 nor openelec x86_64 - General Linux platforms configuration
			
			if settings.getSetting('openeleci386') == "false" and settings.getSetting('openelecx86_64') == "false":

				print("Detected Other Linux i386 Plataform")

            		#Sop
            		#Download and extract sopcast-bundle
				SPSC_KIT = os.path.join(addonpath,sopcast_linux_generico.split("/")[-1])
				download_tools().Downloader(sopcast_linux_generico,SPSC_KIT,translate(40025),translate(40000))
				import tarfile
				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"sopcast")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
				#set every single file from the bundle as executable
				path_libraries = os.path.join(pastaperfil,"sopcast")
				dirs, files = xbmcvfs.listdir(path_libraries)
				for ficheiro in files:
					binary_path = os.path.join(path_libraries,ficheiro)
					st = os.stat(binary_path)
					import stat
					os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
				path_libraries = os.path.join(path_libraries,"lib")
				dirs, files = xbmcvfs.listdir(path_libraries)
				for ficheiro in files:
					binary_path = os.path.join(path_libraries,ficheiro)
					st = os.stat(binary_path)
					import stat
					os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
	   		 
	   		 #Ace
	   		 
				if os.uname()[4] == "x86_64":
					ACE_KIT = os.path.join(addonpath,acestream_linux_x64_generic.split("/")[-1])
					download_tools().Downloader(acestream_linux_x64_generic,ACE_KIT,translate(40026),translate(40000))
					import tarfile
					if tarfile.is_tarfile(ACE_KIT):
						download_tools().extract(ACE_KIT,pastaperfil)
						xbmc.sleep(500)
						download_tools().remove(ACE_KIT)
				
					settings.setSetting('autoconfig',value='false')
					
				elif os.uname()[4] == "i386" or os.uname()[4] == "i686":
					ACE_KIT = os.path.join(addonpath,acestream_linux_i386_generic.split("/")[-1])
					download_tools().Downloader(acestream_linux_i386_generic,ACE_KIT,translate(40026),translate(40000))
					import tarfile
					if tarfile.is_tarfile(ACE_KIT):
						download_tools().extract(ACE_KIT,pastaperfil)
						xbmc.sleep(500)
						download_tools().remove(ACE_KIT)
				
					settings.setSetting('autoconfig',value='false')


	elif xbmc.getCondVisibility('system.platform.windows'):
		print("Detected OS: Windows")
		if not xbmcvfs.exists(pastaperfil): xbmcvfs.mkdir(pastaperfil)
        	#Sop
		import ctypes
                is_admin=ctypes.windll.shell32.IsUserAnAdmin() != 0
                if is_admin == False:
                    mensagemok(translate(40000),translate(40158),translate(40159))
                else:
		    import subprocess
                    cmd = ['sc','delete','sopcastp2p']
                    proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                    for line in proc.stdout:
                        print("cmd out: " + line.rstrip())
                    xbmc.sleep(1000)
                    ret = mensagemprogresso.create(translate(40000),translate(40000))
                    mensagemprogresso.update(0,translate(40160),"  ")
                    xbmc.sleep(1000)
                    import _winreg
                    aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
                    try:
                        aKey = _winreg.OpenKey(aReg, r'SOFTWARE\SopCast\Player\InstallPath',0, _winreg.KEY_READ)
                        name, value, type = _winreg.EnumValue(aKey, 0)
                        sopcast_executable = value
                        print("Installation executable of sopcast was found: " + sopcast_executable)
                        _winreg.CloseKey(aKey)
                        mensagemprogresso.update(10,translate(40160),translate(40161))
                    except:
                        sopcast_executable = ""
                        mensagemok(translate(40000),translate(40162),translate(40163))
                    if not sopcast_executable: pass
                    else:
                        xbmc.sleep(1000)
                        mensagemprogresso.update(20,translate(40164),"  ")
                        xbmc.sleep(1000)
                        print ("Getting windows users IDS")
                        aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
                        aKey = _winreg.OpenKey(aReg, r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList')
                        users = []
                        for i in range(1024):
                            try:
                                asubkey=_winreg.EnumKey(aKey,i)
                                print(asubkey)
                                aKeydois = _winreg.OpenKey(aReg, os.path.join('SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList',asubkey))
                                val=_winreg.QueryValueEx(aKeydois, "ProfileImagePath")
                                try:
                                    print(val[0])
                                except:
                                    print("Notice: User with strange characters, print cmd ignored.")
                                if "Windows" in val[0] or "%systemroot%" in val[0]:
                                    pass
                                else:
                                    users.append(asubkey)
                            except:
                                pass
                        if not users:
                            mensagemok(translate(40000),translate(40165))
                        else:
                            mensagemprogresso.update(30,translate(40164),translate(40161))
                            xbmc.sleep(200)
                            mensagemprogresso.update(30,translate(40166),"   ")
                            xbmc.sleep(1000)
                            print("System Users", users)
                            srvany_final_location = os.path.join(sopcast_executable.replace("SopCast.exe",""),"srvany.exe")
                            srvany_download_location = os.path.join(addonpath,"srvany.exe")
                            srvanytgz_download_location = os.path.join(addonpath,"srvany.tar.gz")                            
                            download_tools().Downloader(srvany_executable,srvanytgz_download_location,translate(40167),translate(40000)) 
                            xbmc.sleep(1000)
                            import tarfile
                            if tarfile.is_tarfile(srvanytgz_download_location):
                                path_libraries = addonpath
                                download_tools().extract(srvanytgz_download_location,path_libraries)
                                xbmcvfs.copy(srvany_download_location,srvany_final_location)
                                download_tools().remove(srvanytgz_download_location)
                                download_tools().remove(srvany_download_location)
                            xbmc.sleep(1000)
                            ret = mensagemprogresso.create(translate(40000),translate(40000))
                            xbmc.sleep(200)
                            mensagemprogresso.update(35,translate(40168),"  ")
                            xbmc.sleep(1000)
                            import subprocess
                            cmd = ['sc','create','sopcastp2p','binpath=',os.path.join(os.path.join(sopcast_executable.replace("SopCast.exe","")),'srvany.exe')]
                            proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                            servicecreator = False
                            for line in proc.stdout:
                                print ("cmd out: " + line.rstrip())
                                servicecreator = True
                            if servicecreator == False:
                                mensagemok(translate(40000),translate(40169))
                            else:
                                mensagemprogresso.update(40,translate(40168),translate(40161))
                                xbmc.sleep(1000)
                                mensagemprogresso.update(45,translate(40170),"  ")
                                xbmc.sleep(1000)
                                print("Trying to modify regedit....")
                                try:
                                    aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
                                    key = _winreg.CreateKey(aReg, r'SYSTEM\CurrentControlSet\Services\sopcastp2p\Parameters')
                                    _winreg.SetValueEx(key, 'AppDirectory', 0, _winreg.REG_SZ, os.path.join(sopcast_executable.replace("SopCast.exe","")))
                                    _winreg.SetValueEx(key, 'Application', 0, _winreg.REG_SZ, os.path.join(os.path.join(sopcast_executable.replace("SopCast.exe","")),"SopCast.exe"))
                                    _winreg.SetValueEx(key, 'AppParameters', 0, _winreg.REG_SZ, "sop://")
                                    mensagemprogresso.update(50,translate(40170), translate(40161))
                                    regedit = True
                                except:
                                    mensagemok(translate(40000),translate(40171))
                                    regedit = False
                                if regedit == False: pass
                                else:
                                    xbmc.sleep(1000)
                                    mensagemprogresso.update(50,translate(40172), "   ")
                                    cmd = ['sc','sdshow','sopcastp2p']
                                    proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                                    lines = []
                                    for line in proc.stdout:
					print(line.rstrip())
                                        if line.rstrip() != "" and "(" in line.rstrip(): lines.append(line.rstrip())
                                        else: pass
                                    if len(lines) != 1: mensagemok(translate(40000),translate(40173))
                                    else:
                                        linha_arr = []
                                        for user in users:
                                            linha_arr.append('(A;;RPWPCR;;;' + user + ')')
                                        linha_add = ''
                                        for linha in linha_arr:
                                            linha_add += linha
                                        print("line peace to add: " + linha_add)
                                        linha_final = lines[0].replace("S:(",linha_add + "S:(")
                                        print("Final line: " + linha_final)
                                        permissions = False
                                        xbmc.sleep(500)
                                        mensagemprogresso.update(60,translate(40172), translate(40161))
                                        xbmc.sleep(500)
                                        mensagemprogresso.update(60,translate(40174), "   ")
                                        cmd = ['sc','sdset','sopcastp2p',linha_final]
                                        proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                                        for line in proc.stdout:
                                            print(line.rstrip())
                                            permissions = True
                                        if permissions == False: mensagemok(translate(40000),translate(40175))
                                        else:
                                            mensagemprogresso.update(70,translate(40174), translate(40161))
                                            xbmc.sleep(1000)
                                            mensagemprogresso.update(70,translate(40176), "   ")
                                            print("Trying to set sopcastp2p service regedit permissions...")
                                            download_tools().Downloader(srvany_permissions,os.path.join(pastaperfil,"sopcastp2p-permissions.txt"),translate(40177),translate(40000))
                                            xbmc.sleep(500)
                                            ret = mensagemprogresso.create(translate(40000),translate(40000))
                                            xbmc.sleep(500)
                                            mensagemprogresso.update(80,translate(40178), "   ")
                                            xbmc.sleep(1000)
                                            cmd = ['regini',os.path.join(pastaperfil,"sopcastp2p-permissions.txt")]
                                            proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                                            for line in proc.stdout:
                                                print(line.rstrip())
                                            mensagemprogresso.update(90,translate(40178), translate(40178))
                                            mensagemprogresso.update(100,translate(40179), "   ")
                                            xbmc.sleep(2000)
                                            mensagemprogresso.close()
        #Ace
		SPSC_KIT = os.path.join(addonpath,acestream_windows.split("/")[-1])
		download_tools().Downloader(acestream_windows,SPSC_KIT,translate(40026),translate(40000))
		import shutil
		if xbmcvfs.exists(os.path.join(pastaperfil,"acestream")):
			shutil.rmtree(os.path.join(pastaperfil,"acestream"))
		if xbmcvfs.exists(os.path.join(pastaperfil,"player")):
			shutil.rmtree(os.path.join(pastaperfil,"player"))
		import tarfile
		if tarfile.is_tarfile(SPSC_KIT):
			path_libraries = os.path.join(pastaperfil)
			download_tools().extract(SPSC_KIT,path_libraries)
			download_tools().remove(SPSC_KIT)
		settings.setSetting('autoconfig',value='false')
    
	elif xbmc.getCondVisibility('System.Platform.OSX'):
		print("Detected OS: Mac OSX")
		available = False
		if os.uname()[-1] == "x86_64":
			mac_package = osx_x86_64
			available = True
		elif os.uname()[-1] == "i386":
			mac_package = osx_i386
			available = True
		else:
			available = False
		if available == True:		
			if not xbmcvfs.exists(pastaperfil):
				xbmcvfs.mkdir(pastaperfil)		
			MAC_KIT = os.path.join(addonpath,mac_package.split("/")[-1])
			download_tools().Downloader(mac_package,MAC_KIT,translate(40112),translate(40000))
			import tarfile
			if tarfile.is_tarfile(MAC_KIT):
				path_libraries = os.path.join(pastaperfil)
				download_tools().extract(MAC_KIT,pastaperfil)
				download_tools().remove(MAC_KIT)
				sp_sc_auth = os.path.join(pastaperfil,"sopcast","sp-sc-auth")
				st = os.stat(sp_sc_auth)
				import stat
				os.chmod(sp_sc_auth, st.st_mode | stat.S_IEXEC)
				settings.setSetting('autoconfig',value='false')
		else:
			mensagemok(translate(40000),translate(600014))
			sys.exit(0)
				
	elif xbmc.getCondVisibility('System.Platform.Android') or settings.getSetting('force_android') == "true":

		print("Detected OS: Android")
		#Sopcast configuration
		print("Starting SopCast Configuration")

		#Moving sopclient to ext4 hack - tks steeve from xbmctorrent

		sopclient_builtin_location = os.path.join(addonpath,"resources","binaries","sopclient")

		#Hack to get current xbmc app id
		xbmcfolder=xbmc.translatePath(addonpath).split("/")

		i = 0
		found = False
		sopcast_installed = False
		
		for folder in xbmcfolder:
			if folder.count('.') >= 2 and folder != addon_id :
				found = True
				break
			else:
				i+=1

		if found == True:
			uid = os.getuid()
			app_id = xbmcfolder[i]
			xbmc_data_path = os.path.join("/data", "data", app_id)
			if os.path.exists(xbmc_data_path) and uid == os.stat(xbmc_data_path).st_uid:
				android_binary_dir = os.path.join(xbmc_data_path, "files", "plugin.video.p2p-streams")
				if not os.path.exists(android_binary_dir):
            				os.makedirs(android_binary_dir)
				android_binary_path = os.path.join(android_binary_dir, "sopclient")
		        	if not os.path.exists(android_binary_path) or os.path.getsize(android_binary_path) != os.path.getsize(sopclient_builtin_location):
					import shutil
					shutil.copy2(sopclient_builtin_location, android_binary_path)
				binary_path = android_binary_path
				st = os.stat(binary_path)
				import stat
				os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
				settings.setSetting('android_sopclient',value=binary_path)
				opcao= xbmcgui.Dialog().yesno(translate(40000), translate(50011),translate(50012))
				if not opcao:
					settings.setSetting('external_sopcast',value='1')
					settings.setSetting('force_android',value='true')
					sopcast_installed = True
					mensagemok(translate(40000),translate(50014))
				else:
					mensagemok(translate(40000),translate(50013))
					if xbmcvfs.exists(os.path.join("sdcard","Download")):
						pasta = os.path.join("sdcard","Download")
						sopfile = os.path.join("sdcard","Download",sopcast_apk.split("/")[-1])
					else:
						dialog = xbmcgui.Dialog()
						pasta = dialog.browse(int(0), translate(40190), 'myprograms')
						sopfile = os.path.join(pasta,sopcast_apk.split("/")[-1])
					download_tools().Downloader(sopcast_apk,sopfile,translate(40073),translate(40000))
					import tarfile
					if tarfile.is_tarfile(sopfile):
						download_tools().extract(sopfile,pasta)
						download_tools().remove(sopfile)
					mensagemok(translate(40000),translate(50015),pasta,translate(50016))
					sopcast_installed = True
					settings.setSetting('external_sopcast',value='0')
					mensagemok(translate(40000),translate(50014))

		else:
			mensagemok(translate(40000),translate(50017))

		#acestream config for android

		if sopcast_installed == True:
			mensagemok(translate(40000),translate(50018),translate(50019),translate(50020))
			if xbmcvfs.exists(os.path.join("sdcard","Download")):
				pasta = os.path.join("sdcard","Download")
				acefile = os.path.join("sdcard","Download",acestreamengine_apk.split("/")[-1])
			else:
				dialog = xbmcgui.Dialog()
				pasta = dialog.browse(int(0), translate(40190), 'myprograms')
				acefile = os.path.join(pasta,acestreamengine_apk.split("/")[-1])
			download_tools().Downloader(acestreamengine_apk,acefile,translate(40072),translate(40000))
			import tarfile
			if tarfile.is_tarfile(acefile):
				download_tools().extract(acefile,pasta)
				download_tools().remove(acefile)
			xbmc.sleep(2000)
			mensagemok(translate(40000),translate(50021),pasta,translate(50016))
			mensagemok(translate(40000),translate(50022))
			mensagemok(translate(40000),translate(50023),translate(50024),translate(50025))
			settings.setSetting('autoconfig',value='false')	
Beispiel #57
0
def Download(url,lang):
    if not xbmcvfs.exists(__temp__.replace('\\','/')):
        xbmcvfs.mkdirs(__temp__)
    dirs, files = xbmcvfs.listdir(__temp__)
    for file in files:
        xbmcvfs.delete(os.path.join(__temp__, file))

    subtitle_list = []
    exts = [".srt", ".sub", ".smi", ".ssa", ".ass" ]
    log( sys._getframe().f_code.co_name ,"Download page: %s" % (url))
    try:
        req = urllib2.Request(url)
        req.add_header('User-Agent', UserAgent)
        socket = urllib2.urlopen(req)
        data = socket.read()
        soup = BeautifulSoup(data, 'html.parser')
        url = soup.find("li", class_="dlsub").a.get('href').encode('utf-8')
        if url[:4] != 'http':
            url = ZIMUKU_BASE + url
        log( sys._getframe().f_code.co_name ,"Download links: %s" % (url))
        req = urllib2.Request(url)
        req.add_header('User-Agent', UserAgent)
        socket = urllib2.urlopen(req)
        data = socket.read()
        socket.close()
        soup = BeautifulSoup(data, 'html.parser')
        links = soup.find("div", {"class":"clearfix"}).find_all('a')
    except:
        log( sys.exc_info()[2].tb_frame.f_code.co_name, "(%d) [%s]" % (
            sys.exc_info()[2].tb_lineno,
            sys.exc_info()[1]
            ))
        return []
    filename, data = DownloadLinks(links, url)
    if len(data) < 1024:
        return []
    t = time.time()
    ts = time.strftime("%Y%m%d%H%M%S",time.localtime(t)) + str(int((t - int(t)) * 1000))
    tempfile = os.path.join(__temp__, "subtitles%s%s" % (ts, os.path.splitext(filename)[1])).replace('\\','/')
    with open(tempfile, "wb") as subFile:
        subFile.write(data)
    subFile.close()
    xbmc.sleep(500)
    if data[:4] == 'Rar!' or data[:2] == 'PK':
        archive = urllib.quote_plus(tempfile)
        if data[:4] == 'Rar!':
            path = 'rar://%s' % (archive)
        else:
            path = 'zip://%s' % (archive)
        dirs, files = xbmcvfs.listdir(path)
        if ('__MACOSX') in dirs:
            dirs.remove('__MACOSX')
        if len(dirs) > 0:
            path = path + '/' + dirs[0].decode('utf-8')
            dirs, files = xbmcvfs.listdir(path)
        list = []
        for subfile in files:
            if (os.path.splitext( subfile )[1] in exts):
                list.append(subfile.decode('utf-8'))
        if list:
            if len(list) == 1:
                subtitle_list.append(path + '/' + list[0])
            else:
                # hack to fix encoding problem of zip file in Kodi 18
                if __kodi__['major'] >= 18 and data[:2] == 'PK':
                    try:
                        dlist = [x.encode('CP437').decode('gbk') for x in list]
                    except:
                        dlist = list
                else:
                    dlist = list

                sel = xbmcgui.Dialog().select('请选择压缩包中的字幕', dlist)
                if sel == -1:
                    sel = 0
                subtitle_list.append(path + '/' + list[sel])
    else:
        subtitle_list.append(tempfile)
    if len(subtitle_list) > 0:
        log(sys._getframe().f_code.co_name, "Get subtitle file: %s" % (subtitle_list[0]))
    return subtitle_list
Beispiel #58
0
    def createOrUpdateDB(self):
        if not xbmcvfs.exists(self.databasefile):
            # No database created yet - nothing to do
            self._createDatabase()
            return

        # The database was already created, check to see if they need to be updated
        # Check if this is an upgrade
        conn = sqlite3.connect(self.databasefile)
        conn.text_factory = str
        c = conn.cursor()
        c.execute('SELECT * FROM version')
        currentVersion = int(c.fetchone()[0])
        log("PinSentryDB: Current version number in DB is: %d" %
            currentVersion)

        # If the database is at version one, add the version 2 tables
        if currentVersion < 2:
            log("PinSentryDB: Updating to version 2")
            # Add the tables that were added in version 2
            c.execute(
                '''CREATE TABLE MusicVideos (id integer primary key, name text unique, dbid integer unique, level integer)'''
            )
            # Update the new version of the database
            currentVersion = 2
            c.execute('DELETE FROM version')
            c.execute("INSERT INTO version VALUES (?)", (currentVersion, ))
            # Save (commit) the changes
            conn.commit()

        # If the database is at version two, add the version 3 tables
        if currentVersion < 3:
            log("PinSentryDB: Updating to version 3")
            # Add the tables that were added in version 3
            c.execute(
                '''CREATE TABLE FileSources (id integer primary key, name text unique, dbid text unique, level integer)'''
            )
            # Update the new version of the database
            currentVersion = 3
            c.execute('DELETE FROM version')
            c.execute("INSERT INTO version VALUES (?)", (currentVersion, ))
            # Save (commit) the changes
            conn.commit()

        # If the database is at version three, add the version 4 tables
        if currentVersion < 4:
            log("PinSentryDB: Updating to version 4")
            # Add the tables that were added in version 4
            c.execute(
                '''CREATE TABLE ClassificationsMovies (id integer primary key, name text unique, dbid text, level integer)'''
            )
            c.execute(
                '''CREATE TABLE ClassificationsTV (id integer primary key, name text unique, dbid text, level integer)'''
            )
            # Update the new version of the database
            currentVersion = 4
            c.execute('DELETE FROM version')
            c.execute("INSERT INTO version VALUES (?)", (currentVersion, ))
            # Save (commit) the changes
            conn.commit()

        # If the database is at version three, add the version 5 tables
        if currentVersion < 5:
            log("PinSentryDB: Updating to version 5")
            # Add the tables that were added in version 5
            c.execute(
                '''CREATE TABLE Repositories (id integer primary key, name text unique, dbid text unique, level integer)'''
            )
            # Update the new version of the database
            currentVersion = 5
            c.execute('DELETE FROM version')
            c.execute("INSERT INTO version VALUES (?)", (currentVersion, ))
            # Save (commit) the changes
            conn.commit()

        conn.close()