Python xbmcvfs.File() Examples

The following are 30 code examples of xbmcvfs.File(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xbmcvfs , or try the search function .
Example #1
Source File: context.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 6 votes vote down vote up
def library_getnfo_tmdbid(basedir=None, folder=None):
    """ Checks .nfo file and returns TMDB ID it contains """
    tmdb_id = None
    folder_list = xbmcvfs.listdir(basedir)[0]
    if folder in folder_list:
        nfo_folder = basedir + folder + '/'
        nfo = None
        for x in xbmcvfs.listdir(nfo_folder)[1]:
            if x.endswith('.nfo'):
                nfo = x
        if nfo:
            vfs_file = xbmcvfs.File(nfo_folder + nfo)
            content = ''
            try:
                content = vfs_file.read()
            finally:
                vfs_file.close()
            tmdb_id = content.replace('https://www.themoviedb.org/tv/', '')
            tmdb_id = tmdb_id.replace('&islocal=True', '')
    return tmdb_id 
Example #2
Source File: filetools.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def getsize(path, silent=False, vfs=True):
    """
    Obtiene el tamaño de un archivo
    @param path: ruta del fichero
    @type path: str
    @rtype: str
    @return: tamaño del fichero
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            if not exists(path): return long(0)
            f = xbmcvfs.File(path)
            s = f.size()
            f.close()
            return s
        elif path.lower().startswith("smb://"):
            return long(samba.get_attributes(path).file_size)
        else:
            return os.path.getsize(path)
    except:
        logger.error("ERROR al obtener el tamaño: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
        return long(0) 
Example #3
Source File: rpc.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def GetCurrentView(self):
        skinPath = xbmc.translatePath('special://skin/')
        xml = os.path.join(skinPath, 'addon.xml')
        f = xbmcvfs.File(xml)
        read = f.read()
        f.close()
        try:
            src = re.search('defaultresolution="([^"]+)', read, re.DOTALL).group(1)
        except:
            src = re.search('<res.+?folder="([^"]+)', read, re.DOTALL).group(1)
        src = os.path.join(skinPath, src, 'MyVideoNav.xml')
        f = xbmcvfs.File(src)
        read = f.read()
        f.close()
        match = re.search('<views>([^<]+)', read, re.DOTALL)
        if match:
            views = match.group(1)
            log.info("Skin's ViewModes: %s" % views)
            for view in views.split(','):
                if xbmc.getInfoLabel('Control.GetLabel(%s)' % view):
                    return view 
Example #4
Source File: main.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 6 votes vote down vote up
def convert(path):
    input = xbmcvfs.File(path,'rb')
    output = xbmcvfs.File(path.replace('.ts','.mp4'),'wb')
    error = open(xbmc.translatePath("special://profile/addon_data/plugin.video.iptv.recorder/errors.txt"),"w")

    cmd = [ffmpeg_location(),"-fflags","+genpts","-y","-i","-","-vcodec","copy","-acodec","copy","-f", "mpegts", "-"]
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=error, shell=windows())
    t = threading.Thread(target=read_thread,args=[p,output])
    t.start()

    while True:
        data = input.read(100000)
        log(("read",len(data)))
        if not data:
            break
        p.stdin.write(data)
    p.stdin.close()
    error.close() 
Example #5
Source File: kodi.py    From script.module.resolveurl with GNU General Public License v2.0 6 votes vote down vote up
def get_current_view():
    skinPath = translate_path('special://skin/')
    xml = os.path.join(skinPath, 'addon.xml')
    f = xbmcvfs.File(xml)
    read = f.read()
    f.close()
    try:
        src = re.search('defaultresolution="([^"]+)', read, re.DOTALL).group(1)
    except:
        src = re.search('<res.+?folder="([^"]+)', read, re.DOTALL).group(1)
    src = os.path.join(skinPath, src, 'MyVideoNav.xml')
    f = xbmcvfs.File(src)
    read = f.read()
    f.close()
    match = re.search('<views>([^<]+)', read, re.DOTALL)
    if match:
        views = match.group(1)
        for view in views.split(','):
            if xbmc.getInfoLabel('Control.GetLabel(%s)' % view):
                return view 
Example #6
Source File: koditidal.py    From plugin.audio.tidal2 with GNU General Public License v3.0 6 votes vote down vote up
def load_cache(self):
        try:
            fd = xbmcvfs.File(FAVORITES_FILE, 'r')
            self.ids_content = fd.read()
            self.ids = eval(self.ids_content)
            if not 'locked_artists' in self.ids:
                self.ids['locked_artists'] = [VARIOUS_ARTIST_ID]
            fd.close()
            self.ids_loaded = not (self.ids['artists'] == None or self.ids['albums'] == None or
                                   self.ids['playlists'] == None or self.ids['tracks'] == None or
                                   self.ids['videos'] == None)
            if self.ids_loaded:
                log('Loaded %s Favorites from disk.' % sum(len(self.ids[content]) for content in ['artists', 'albums', 'playlists', 'tracks', 'videos']))
        except:
            self.ids_loaded = False
            self.reset()
        return self.ids_loaded 
Example #7
Source File: nfofile.py    From script.artwork.beef with MIT License 6 votes vote down vote up
def read_nfofile(filename):
    if not xbmcvfs.exists(filename):
        return None
    with closing(xbmcvfs.File(filename)) as nfofile:
        try:
            return ET.parse(nfofile).getroot()
        except ParseError:
            pass
        # maybe it's all XML except the last line, like the wiki suggests for XML + URL
        nfofile.seek(0, 0)
        lines = nfofile.read().split('\n')
        while lines and not lines[-1].strip():
            del lines[-1] # Remove final blank lines
        if lines: # Remove the line that possibly contains the URL
            del lines[-1]
        if lines:
            try:
                return ET.XML('\n'.join(lines))
            except ParseError:
                pass 
Example #8
Source File: kodi.py    From script.module.urlresolver with GNU General Public License v2.0 6 votes vote down vote up
def get_current_view():
    skinPath = translate_path('special://skin/')
    xml = os.path.join(skinPath, 'addon.xml')
    f = xbmcvfs.File(xml)
    read = f.read()
    f.close()
    try:
        src = re.search('defaultresolution="([^"]+)', read, re.DOTALL).group(1)
    except:
        src = re.search('<res.+?folder="([^"]+)', read, re.DOTALL).group(1)
    src = os.path.join(skinPath, src, 'MyVideoNav.xml')
    f = xbmcvfs.File(src)
    read = f.read()
    f.close()
    match = re.search('<views>([^<]+)', read, re.DOTALL)
    if match:
        views = match.group(1)
        for view in views.split(','):
            if xbmc.getInfoLabel('Control.GetLabel(%s)' % view):
                return view 
Example #9
Source File: lib_tvshows.py    From plugin.video.openmeta with GNU General Public License v3.0 6 votes vote down vote up
def batch_add_tvshows_to_library(library_folder, show):
	id = show['id']
	showname = text.to_utf8(show['seriesname'])
	show_folder = os.path.join(library_folder, str(id) + '/')
	if not xbmcvfs.exists(show_folder):
		try:
			xbmcvfs.mkdir(show_folder)
		except:
			pass
	nfo_filepath = os.path.join(show_folder, 'tvshow.nfo')
	if not xbmcvfs.exists(nfo_filepath):
		nfo_file = xbmcvfs.File(nfo_filepath, 'w')
		content = 'https://thetvdb.com/?tab=series&id=%s' % str(id)
		nfo_file.write(content)
		nfo_file.close()
	clean_needed = True
	return clean_needed 
Example #10
Source File: nav_movies.py    From plugin.video.openmeta with GNU General Public License v3.0 6 votes vote down vote up
def movies_add_all_to_library(items, noscan=False):
	library_folder = lib_movies.setup_library(plugin.get_setting('movies_library_folder', unicode))
	if 'results' in items:
		ids = '\n'.join([str(r['id']) for r in items['results']])
	else:
		ids = '\n'.join([i['movie']['ids']['imdb'] if i['movie']['ids']['imdb'] != None and i['movie']['ids']['imdb'] != '' else str(i['movie']['ids']['tmdb']) for i in items])
	movies_batch_add_file = plugin.get_setting('movies_batch_add_file_path', unicode)
	if xbmcvfs.exists(movies_batch_add_file):
		batch_add_file = xbmcvfs.File(movies_batch_add_file)
		pre_ids = batch_add_file.read()
		xids = pre_ids.split('\n')
		for id in xids:
			if id != '' and id != None and id not in ids:
				ids = ids + str(id) + '\n'
		batch_add_file.close()
		xbmcvfs.delete(movies_batch_add_file)
	batch_add_file = xbmcvfs.File(movies_batch_add_file, 'w')
	batch_add_file.write(str(ids))
	batch_add_file.close()
	xbmc.executebuiltin('RunPlugin(plugin://plugin.video.openmeta/movies/batch_add_to_library)') 
Example #11
Source File: meta_players.py    From plugin.video.openmeta with GNU General Public License v3.0 6 votes vote down vote up
def get_players(media, filters={}):
	assert media in ('tvshows', 'movies')
	players = []
	players_path = 'special://profile/addon_data/plugin.video.openmeta/Players/'
	files = [x for x in xbmcvfs.listdir(players_path)[1] if x.endswith('.json')]
	for file in files:
		path = players_path + file
		try:
			f = xbmcvfs.File(path)
			try:
				content = f.read()
				meta = json.loads(content)
			finally:
				f.close()
			player = AddonPlayer(file, media, meta)
			if not player.is_empty():
				players.append(player)
		except:
			xbmcgui.Dialog().ok('Invalid player', 'player %s is invalid' % file)
	return sort_players(players, filters) 
Example #12
Source File: nav_tvshows.py    From plugin.video.openmeta with GNU General Public License v3.0 6 votes vote down vote up
def tv_add_all_to_library(items, noscan=False):
	library_folder = lib_tvshows.setup_library(plugin.get_setting('tv_library_folder', unicode))
	ids = ''
	if 'results' in items:
		preids = []
		for tvdb_show, tmdb_show in executor.execute(tmdb_to_tvdb, items['results'], workers=10):
			if tvdb_show is not None:
				preids.append(tvdb_show['id'])
		ids = '\n'.join(preids)
	else:
		ids = '\n'.join([str(i['show']['ids']['tvdb']) if i['show']['ids']['tvdb'] != None and i['show']['ids']['tvdb'] != '' else i['show']['ids']['imdb'] for i in items])
	shows_batch_add_file = plugin.get_setting('tv_batch_add_file_path', unicode)
	if xbmcvfs.exists(shows_batch_add_file):
		batch_add_file = xbmcvfs.File(shows_batch_add_file)
		pre_ids = batch_add_file.read()
		xids = pre_ids.split('\n')
		for id in xids:
			if id != '' and id != None and id not in ids:
				ids = ids + str(id) + '\n'
		batch_add_file.close()
		xbmcvfs.delete(shows_batch_add_file)
	batch_add_file = xbmcvfs.File(shows_batch_add_file, 'w')
	batch_add_file.write(str(ids))
	batch_add_file.close()
	xbmc.executebuiltin('RunPlugin(plugin://plugin.video.openmeta/tv/batch_add_to_library)') 
Example #13
Source File: sutils.py    From plugin.video.sosac.ph with GNU General Public License v2.0 6 votes vote down vote up
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
                    util.error('Failed to create directory 1: ' + 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:
                    util.error('Failed to create .strm file: ' +
                               item_path + " | " + str(e))
                    error = True 
Example #14
Source File: webservice.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def images(self):

        ''' Return a dummy image for unwanted images requests over the webservice.
            Required to prevent freezing of widget playback if the file url has no
            local textures cached yet.
        '''
        image = xbmc.translatePath("special://home/addons/plugin.video.emby/icon.png").decode('utf-8')

        self.send_response(200)
        self.send_header('Content-type', 'image/png')
        modified = xbmcvfs.Stat(image).st_mtime()
        self.send_header('Last-Modified', "%s" % modified)
        image = xbmcvfs.File(image)
        size = image.size()
        self.send_header('Content-Length', str(size))
        self.end_headers()

        self.wfile.write(image.readBytes())
        image.close() 
Example #15
Source File: logging.py    From xbmc with GNU General Public License v3.0 5 votes vote down vote up
def WriteLog(data, fn=''):
    if not s.verbLog:
        return

    fn = '-' + fn if fn else ''
    fn = 'avod{}.log'.format(fn)
    path = OSPJoin(g.HOME_PATH, fn)
    logfile = xbmcvfs.File(path, 'w')
    logfile.write(py2_encode(data))
    logfile.close() 
Example #16
Source File: lib_tvshows.py    From plugin.video.openmeta with GNU General Public License v3.0 5 votes vote down vote up
def library_tv_strm(show, folder, id, season, episode):
	enc_season = ('Season %s' % season).translate(None, '\/:*?"<>|').strip('.')
	folder = os.path.join(folder, enc_season)
	try:
		xbmcvfs.mkdir(folder)
	except:
		pass
	enc_name = '%s - S%02dE%02d.strm' % (text.clean_title(show['seriesname']), season, episode)
	stream = os.path.join(folder, enc_name)
	if not xbmcvfs.exists(stream):
		file = xbmcvfs.File(stream, 'w')
		content = plugin.url_for('tv_play', id=id, season=season, episode=episode)
		file.write(str(content))
		file.close() 
Example #17
Source File: subtitles.py    From plugin.video.youtube with GNU General Public License v2.0 5 votes vote down vote up
def _write_file(self, _file, contents):
        self.context.log_debug('Writing subtitle file: %s' % _file)
        try:
            f = xbmcvfs.File(_file, 'w')
            f.write(contents)
            f.close()
            return True
        except:
            self.context.log_debug('File write failed for: %s' % _file)
            return False 
Example #18
Source File: koditidal.py    From plugin.audio.tidal2 with GNU General Public License v3.0 5 votes vote down vote up
def save_cache(self):
        try:
            if self.playlists_loaded:
                fd = xbmcvfs.File(PLAYLISTS_FILE, 'w')
                fd.write(repr(self.playlists_cache))
                fd.close()
                log('Saved %s Playlists to disk.' % len(self.playlists_cache.keys()))
        except:
            return False
        return True 
Example #19
Source File: lib_movies.py    From plugin.video.openmeta with GNU General Public License v3.0 5 votes vote down vote up
def batch_add_movies_to_library(library_folder, id):
	if id == None:
		return
	changed = False
	movie_folder = os.path.join(library_folder, str(id) + '/')
	if not xbmcvfs.exists(movie_folder):
		try:
			xbmcvfs.mkdir(movie_folder)
		except:
			pass
	nfo_filepath = os.path.join(movie_folder, str(id) + '.nfo')
	if not xbmcvfs.exists(nfo_filepath):
		changed = True
		nfo_file = xbmcvfs.File(nfo_filepath, 'w')
		content = 'https://www.imdb.com/title/%s/' % str(id)
		nfo_file.write(content)
		nfo_file.close()
	strm_filepath = os.path.join(movie_folder, str(id) + '.strm')
	src = 'imdb'
	if not xbmcvfs.exists(strm_filepath):
		changed = True
		strm_file = xbmcvfs.File(strm_filepath, 'w')
		try:
			content = plugin.url_for('movies_play', src=src, id=id)
			strm_file.write(content)
			strm_file.close()
		except:
			pass
	return changed 
Example #20
Source File: main.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 5 votes vote down vote up
def delete_job(job, kill=True, ask=True):
    conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
    cursor = conn.cursor()

    job_details = cursor.execute("SELECT uuid FROM jobs WHERE uuid=?", (job, )).fetchone()
    if not job_details:
        return

    if ask and not (xbmcgui.Dialog().yesno("IPTV Recorder", _("Cancel Record?"))):
        return

    if windows() and plugin.get_setting('task.scheduler') == 'true':
        cmd = ["schtasks", "/delete", "/f", "/tn", job]
        subprocess.Popen(cmd, shell=True)
    else:
        xbmc.executebuiltin('CancelAlarm(%s, True)' % job)

    directory = "special://profile/addon_data/plugin.video.iptv.recorder/jobs/"
    xbmcvfs.mkdirs(directory)
    pyjob = directory + job + ".py"

    pid = xbmcvfs.File(pyjob+'.pid').read()

    xbmcvfs.delete(pyjob)
    xbmcvfs.delete(pyjob+'.pid')

    if pid and kill:
        if windows():
            subprocess.Popen(["taskkill", "/im", pid], shell=True)
        else:
            #TODO correct kill switch
            subprocess.Popen(["kill", "-9", pid])

    conn.execute("DELETE FROM jobs WHERE uuid=?", (job, ))
    conn.commit()
    conn.close()

    refresh() 
Example #21
Source File: filetools.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def write(path, data, mode="wb", silent=False, vfs=True):
    """
    Guarda los datos en un archivo
    @param path: ruta del archivo a guardar
    @type path: str
    @param data: datos a guardar
    @type data: str
    @rtype: bool
    @return: devuelve True si se ha escrito correctamente o False si ha dado un error
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            f = xbmcvfs.File(path, mode)
            result = f.write(data)
            f.close()
            return bool(result)
        elif path.lower().startswith("smb://"):
            f = samba.smb_open(path, mode)
        else:
            f = open(path, mode)

        f.write(data)
        f.close()
    except:
        logger.error("ERROR al guardar el archivo: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
        return False
    else:
        return True 
Example #22
Source File: player.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 5 votes vote down vote up
def build_players(self, tmdbtype=None):
        basedirs = ['special://profile/addon_data/plugin.video.themoviedb.helper/players/']
        if self.addon.getSettingBool('bundled_players'):
            basedirs.append('special://home/addons/plugin.video.themoviedb.helper/resources/players/')
        for basedir in basedirs:
            files = [x for x in xbmcvfs.listdir(basedir)[1] if x.endswith('.json')]
            for file in files:
                vfs_file = xbmcvfs.File(basedir + file)
                try:
                    content = vfs_file.read()
                    meta = loads(content) or {}
                finally:
                    vfs_file.close()

                self.players[file] = meta

                plugins = meta.get('plugin') or 'plugin.undefined'  # Give dummy name to undefined plugins so that they fail the check
                plugins = plugins if isinstance(plugins, list) else [plugins]  # Listify for simplicity of code
                for plugin in plugins:
                    if not xbmc.getCondVisibility(u'System.HasAddon({0})'.format(plugin)):
                        break  # System doesn't have a required plugin so skip this player
                else:  # If the system has all the listed addons then build the player
                    tmdbtype = tmdbtype or self.tmdbtype
                    priority = utils.try_parse_int(meta.get('priority')) or 1000
                    if tmdbtype == 'movie' and meta.get('search_movie'):
                        self.search_movie.append((file, priority))
                    if tmdbtype == 'movie' and meta.get('play_movie'):
                        self.play_movie.append((file, priority))
                    if tmdbtype == 'tv' and meta.get('search_episode'):
                        self.search_episode.append((file, priority))
                    if tmdbtype == 'tv' and meta.get('play_episode'):
                        self.play_episode.append((file, priority)) 
Example #23
Source File: downloader.py    From plugin.video.mediathekview with MIT License 5 votes vote down vote up
def _make_movie_nfo_file(self, film, filmurl, pathname, filename):
        # create movie NFO file
        # See: https://kodi.wiki/view/NFO_files/Movies
        # pylint: disable=broad-except
        if self.settings.makenfo > 0:
            try:
                # bug of pylint 1.7.1 - See https://github.com/PyCQA/pylint/issues/1444
                # pylint: disable=no-member
                with closing(xbmcvfs.File(pathname + filename + u'.nfo', 'w')) as nfofile:
                    nfofile.write(bytearray('<movie>\n', 'utf-8'))
                    nfofile.write(
                        bytearray('\t<title>{}</title>\n'.format(film.title), 'utf-8'))
                    nfofile.write(
                        bytearray('\t<plot>{}</plot>\n'.format(film.description), 'utf-8'))
                    nfofile.write(
                        bytearray('\t<studio>{}</studio>\n'.format(film.channel), 'utf-8'))
                    aired = self._matches(
                        '([12][0-9][0-9][0-9].[0-9][0-9].[0-9][0-9])', str(film.aired))
                    if aired is not None:
                        nfofile.write(
                            bytearray('\t<aired>{}</aired>\n'.format(aired), 'utf-8'))
                    year = self._matches(
                        '([12][0-9][0-9][0-9])', str(film.aired))
                    if year is not None:
                        nfofile.write(
                            bytearray('\t<year>{}</year>\n'.format(year), 'utf-8'))
                    if film.seconds > 60:
                        nfofile.write(
                            bytearray(
                                '\t<runtime>{}</runtime>\n'.format(
                                    int(film.seconds / 60)
                                ),
                                'utf-8'
                            )
                        )
                    nfofile.write(bytearray('</movie>\n', 'utf-8'))
            except Exception as err:
                self.plugin.error(
                    'Failure creating episode NFO file for {}: {}', filmurl, err) 
Example #24
Source File: downloader.py    From plugin.video.mediathekview with MIT License 5 votes vote down vote up
def download_subtitle(self, film, ttmname, srtname, filename):
        """
        Downloads and converts a subtitle track of a film
        to SRT format.

        Args:
            film(Film): the film object loaded from the database

            ttmname(str): the filename of the downloaded subtitle
                in original format

            srtname(str): the filename of the downloaded subtitle
                file after conversion to SRT format

            filename(str): a filename stub without extension for
                UI display
        """
        ret = False
        if film.url_sub:
            progress = KodiProgressDialog()
            progress.create(30978, filename + u'.ttml')
            # pylint: disable=broad-except
            try:
                progress.update(0)
                mvutils.url_retrieve_vfs(
                    film.url_sub, ttmname, progress.url_retrieve_hook)
                try:
                    ttml2srtConverter = ttml2srt()
                    ttml2srtConverter.do(xbmcvfs.File(ttmname, 'r'),
                             xbmcvfs.File(srtname, 'w'))
                    ret = True
                except Exception as err:
                    self.plugin.info('Failed to convert to srt: {}', err)
                progress.close()
            except Exception as err:
                progress.close()
                self.plugin.error(
                    'Failure downloading {}: {}', film.url_sub, err)
        return ret 
Example #25
Source File: player.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 5 votes vote down vote up
def localfile(self, file):
        if not file:
            return
        if file.endswith('.strm'):
            f = xbmcvfs.File(file)
            contents = f.read()
            f.close()
            if contents.startswith('plugin://plugin.video.themoviedb.helper'):
                return
        return file 
Example #26
Source File: mvutils.py    From plugin.video.mediathekview with MIT License 5 votes vote down vote up
def url_retrieve_vfs(url, filename, reporthook, chunk_size=8192, aborthook=None):
    """
    Copy a network object denoted by a URL to a local file using
    Kodi's VFS functions

    Args:
        url(str): the source url of the object to retrieve

        filename(str): the destination filename

        reporthook(function): a hook function that will be called once on
            establishment of the network connection and once after each
            block read thereafter. The hook will be passed three arguments;
            a count of blocks transferred so far, a block size in bytes,
            and the total size of the file.

        chunk_size(int, optional): size of the chunks read by the function.
            Default is 8192

        aborthook(function, optional): a hook function that will be called
            once on establishment of the network connection and once after
            each block read thereafter. If specified the operation will be
            aborted if the hook function returns `True`
    """
    with closing(urlopen(url, timeout = 10)) as src, closing(xbmcvfs.File(filename, 'wb')) as dst:
        _chunked_url_copier(src, dst, reporthook, chunk_size, aborthook) 
Example #27
Source File: advancedsettings.py    From script.artwork.beef with MIT License 5 votes vote down vote up
def save_xml(advancedsettings):
    indent(advancedsettings)
    with closing(xbmcvfs.File(FILENAME, 'w')) as as_xml:
        ET.ElementTree(advancedsettings).write(as_xml, 'utf-8', True) 
Example #28
Source File: advancedsettings.py    From script.artwork.beef with MIT License 5 votes vote down vote up
def read_xml():
    if not xbmcvfs.exists(FILENAME):
        return ET.Element(ROOT_TAG)

    parser = ET.XMLParser(target=CommentedTreeBuilder())
    with closing(xbmcvfs.File(FILENAME)) as as_xml:
        try:
            return ET.parse(as_xml, parser).getroot()
        except ET.ParseError:
            log("Can't parse advancedsettings.xml", xbmc.LOGWARNING) 
Example #29
Source File: downloader.py    From screensaver.atv4 with GNU General Public License v2.0 5 votes vote down vote up
def downloadall(self,urllist):
        self.dp = xbmcgui.DialogProgress()
        self.dp.create(translate(32000), translate(32019))
        # video checksums - download only the videos that were not downloaded previously
        if addon.getSetting("enable-checksums") == "true":
            with open(os.path.join(addon_path, "resources", "checksums.json")) as f:
                checksums = f.read()

            checksums = json.loads(checksums)

        for url in urllist:
            if not self.stop:
                video_file = url.split("/")[-1]
                localfile = os.path.join(addon.getSetting("download-folder"),video_file)

                if xbmcvfs.exists(localfile):
                    if addon.getSetting("enable-checksums") == "true":
                        f = xbmcvfs.File(xbmc.translatePath(localfile))
                        file_checksum = hashlib.md5(f.read()).hexdigest()
                        f.close()

                        if video_file in checksums.keys() and checksums[video_file] != file_checksum:
                            self.download(localfile,url,url.split("/")[-1])
                    else:
                        self.download(localfile,url,url.split("/")[-1])
                else:
                    self.download(localfile,url,url.split("/")[-1])
            else:
                break 
Example #30
Source File: downloader.py    From screensaver.atv4 with GNU General Public License v2.0 5 votes vote down vote up
def download(self,path,url,name):
        if xbmcvfs.exists(path):
            xbmcvfs.delete(path)

        self.dp.update(0,name)
        self.path = xbmc.translatePath(path)
        xbmc.sleep(500)
        start_time = time.time()

        u = urlopen(url)
        meta = u.info()
        meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all
        meta_length = meta_func("Content-Length")
        file_size = None
        block_sz = 8192
        if meta_length:
            file_size = int(meta_length[0])

        file_size_dl = 0
        f = xbmcvfs.File(self.path, 'wb')
        numblocks = 0

        while not self.stop:
            buffer = u.read(block_sz)
            if not buffer:
                break

            f.write(buffer)
            file_size_dl += len(buffer)
            numblocks += 1
            self.dialogdown(name, numblocks, block_sz, file_size, self.dp, start_time)

        f.close()
        return