• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python helpers.download_file函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sickbeard.helpers.download_file函数的典型用法代码示例。如果您正苦于以下问题:Python download_file函数的具体用法?Python download_file怎么用?Python download_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了download_file函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: cache_image

    def cache_image(self, image_url):
        path = ek.ek(os.path.abspath, ek.ek(os.path.join, sickbeard.CACHE_DIR, 'images', 'imdb_popular'))

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

        full_path = os.path.join(path, os.path.basename(image_url))

        if not os.path.isfile(full_path):
            helpers.download_file(image_url, full_path, session=self.session)
开发者ID:rob356,项目名称:SickRage,代码行数:10,代码来源:imdbPopular.py


示例2: cache_image

    def cache_image(self, image_url):
        """
        Store cache of image in cache dir
        :param image_url: Source URL
        """
        path = ek(os.path.abspath, ek(os.path.join, sickbeard.CACHE_DIR, 'images', 'imdb_popular'))

        if not ek(os.path.exists, path):
            ek(os.makedirs, path)

        full_path = ek(os.path.join, path, ek(os.path.basename, image_url))

        if not ek(os.path.isfile, full_path):
            helpers.download_file(image_url, full_path, session=self.session)
开发者ID:lucianot54,项目名称:SickRage,代码行数:14,代码来源:imdbPopular.py


示例3: downloadResult

    def downloadResult(self, result):
        """
        Save the result to disk.
        """

        # check for auth
        if not self._doLogin():
            return False

        urls, filename = self._makeURL(result)

        for url in urls:
            logger.log(u"Downloading a result from " + self.name + " at " + url)
            if helpers.download_file(url, filename, session=self.session):
                if self._verify_download(filename):
                    logger.log(u"Saved result to " + filename, logger.INFO)
                    return True
                else:
                    logger.log(u"Could not download %s" % url, logger.WARNING)
                    helpers._remove_file_failed(filename)

        if len(urls):
            logger.log(u"Failed to download any results", logger.WARNING)

        return False
开发者ID:bckwltn,项目名称:SickRage-MAC-MASTER,代码行数:25,代码来源:generic.py


示例4: download_result

    def download_result(self, result):
        if not self.login():
            return False

        urls, filename = self._make_url(result)

        for url in urls:
            if 'NO_DOWNLOAD_NAME' in url:
                continue

            if url.startswith('http'):
                self.headers.update({
                    'Referer': '/'.join(url.split('/')[:3]) + '/'
                })

            logger.log(u'Downloading a result from {0} at {1}'.format(self.name, url))

            if url.endswith(GenericProvider.TORRENT) and filename.endswith(GenericProvider.NZB):
                filename = replace_extension(filename, GenericProvider.TORRENT)

            if download_file(url, filename, session=self.session, headers=self.headers, hooks={'response': self.get_url_hook}):
                if self._verify_download(filename):
                    logger.log(u'Saved result to {0}'.format(filename), logger.INFO)
                    return True

                logger.log(u'Could not download {0}'.format(url), logger.WARNING)
                remove_file_failed(filename)

        if urls:
            logger.log(u'Failed to download any results', logger.WARNING)

        return False
开发者ID:NickMolloy,项目名称:SickRage,代码行数:32,代码来源:GenericProvider.py


示例5: download_result

    def download_result(self, result):
        """
        Save the result to disk.
        """

        # check for auth
        if not self.login():
            return False

        urls, filename = self._make_url(result)

        for url in urls:
            # Search results don't return torrent files directly, it returns show sheets so we must parse showSheet to access torrent.
            data = self.get_url(url, returns='text')
            url_torrent = re.search(r'http://tumejorserie.com/descargar/.+\.torrent', data, re.DOTALL).group()

            if url_torrent.startswith('http'):
                self.headers.update({'Referer': '/'.join(url_torrent.split('/')[:3]) + '/'})

            logger.log('Downloading a result from {}'.format(url))

            if helpers.download_file(url_torrent, filename, session=self.session, headers=self.headers):
                if self._verify_download(filename):
                    logger.log('Saved result to {}'.format(filename), logger.INFO)
                    return True
                else:
                    logger.log('Could not download {}'.format(url), logger.WARNING)
                    helpers.remove_file_failed(filename)

        if len(urls):
            logger.log('Failed to download any results', logger.WARNING)

        return False
开发者ID:ratoaq2,项目名称:SickRage,代码行数:33,代码来源:newpct.py


示例6: download_result

    def download_result(self, result):
        if not self.login():
            return False

        urls, filename = self._make_url(result)

        for url in urls:
            if "NO_DOWNLOAD_NAME" in url:
                continue

            if url.startswith("http"):
                self.headers.update({"Referer": "/".join(url.split("/")[:3]) + "/"})

            logger.log(u"Downloading a result from {0} at {1}".format(self.name, url))

            if url.endswith(GenericProvider.TORRENT) and filename.endswith(GenericProvider.NZB):
                filename = replace_extension(filename, GenericProvider.TORRENT)

            if download_file(
                url, filename, session=self.session, headers=self.headers, hooks={"response": self.get_url_hook}
            ):
                if self._verify_download(filename):
                    logger.log(u"Saved result to {0}".format(filename), logger.INFO)
                    return True

                logger.log(u"Could not download {0}".format(url), logger.WARNING)
                remove_file_failed(filename)

        if urls:
            logger.log(u"Failed to download any results", logger.WARNING)

        return False
开发者ID:Rickol91,项目名称:SickRage,代码行数:32,代码来源:GenericProvider.py


示例7: downloadResult

    def downloadResult(self, result):
        """
        Save the result to disk.
        """

        # check for auth
        if not self._doLogin():
            return False

        urls, filename = self._makeURL(result)

        if self.proxy.isEnabled():
            self.headers.update({"Referer": self.proxy.getProxyURL()})
        elif "Referer" in self.headers:
            self.headers.pop("Referer")

        for url in urls:
            if "NO_DOWNLOAD_NAME" in url:
                continue

            logger.log(u"Downloading a result from " + self.name + " at " + url)
            if helpers.download_file(self.proxy._buildURL(url), filename, session=self.session, headers=self.headers):
                if self._verify_download(filename):
                    logger.log(u"Saved result to " + filename, logger.INFO)
                    return True
                else:
                    logger.log(u"Could not download %s" % url, logger.WARNING)
                    helpers._remove_file_failed(filename)

        if len(urls):
            logger.log(u"Failed to download any results", logger.WARNING)

        return False
开发者ID:brusilva,项目名称:SickRage,代码行数:33,代码来源:generic.py


示例8: _update_zoneinfo

def _update_zoneinfo():

    # now check if the zoneinfo needs update
    url_zv = 'http://github.com/Prinz23/sb_network_timezones/raw/master/zoneinfo.txt'

    url_data = helpers.getURL(url_zv)

    if url_data is None:
        # When urlData is None, trouble connecting to github
        logger.log(u"Loading zoneinfo.txt failed. Unable to get URL: " + url_zv, logger.DEBUG)
        return

    if (lib.dateutil.zoneinfo.ZONEINFOFILE != None):
        cur_zoneinfo = ek.ek(basename, lib.dateutil.zoneinfo.ZONEINFOFILE)
    else:
        cur_zoneinfo = None
    (new_zoneinfo, zoneinfo_md5) = url_data.decode('utf-8').strip().rsplit(u' ')

    if ((cur_zoneinfo != None) and (new_zoneinfo == cur_zoneinfo)):
        return

    # now load the new zoneinfo
    url_tar = u'http://github.com/Prinz23/sb_network_timezones/raw/master/' + new_zoneinfo
    zonefile = ek.ek(realpath, u'lib/dateutil/zoneinfo/' + new_zoneinfo)
    zonefile_tmp = re.sub(r"\.tar\.gz$",'.tmp', zonefile)

    if (os.path.exists(zonefile_tmp)):
        try:
            os.remove(zonefile_tmp)
        except:
            logger.log(u"Unable to delete: " + zonefile_tmp,logger.ERROR)
            return

    if not helpers.download_file(url_tar, zonefile_tmp):
        return

    new_hash = str(helpers.md5_for_file(zonefile_tmp))

    if (zoneinfo_md5.upper() == new_hash.upper()):
        logger.log(u"Updating timezone info with new one: " + new_zoneinfo,logger.MESSAGE)
        try:
            # remove the old zoneinfo file
            if (cur_zoneinfo != None):
                old_file = ek.ek(realpath, u'lib/dateutil/zoneinfo/' + cur_zoneinfo)
                if (os.path.exists(old_file)):
                    os.remove(old_file)
            # rename downloaded file
            os.rename(zonefile_tmp,zonefile)
            # load the new zoneinfo
            reload(lib.dateutil.zoneinfo)
        except:
            _remove_zoneinfo_failed(zonefile_tmp)
            return
    else:
        _remove_zoneinfo_failed(zonefile_tmp)
        logger.log(u"MD5 HASH doesn't match: " + zoneinfo_md5.upper() + ' File: ' + new_hash.upper(),logger.ERROR)
        return
开发者ID:Arakmar,项目名称:Sick-Beard,代码行数:57,代码来源:network_timezones.py


示例9: downloadResult

    def downloadResult(self, result):
        """
        Save the result to disk.
        """

        # check for auth
        if not self._doLogin():
            return False

        if self.providerType == GenericProvider.TORRENT:
            try:
                torrent_hash = re.findall('urn:btih:([\w]{32,40})', result.url)[0].upper()
                torrent_name = re.findall('dn=([^&]+)', result.url)[0]

                if len(torrent_hash) == 32:
                    torrent_hash = b16encode(b32decode(torrent_hash)).upper()

                if not torrent_hash:
                    logger.log("Unable to extract torrent hash from link: " + ex(result.url), logger.ERROR)
                    return False

                urls = [
                    'http://torcache.net/torrent/' + torrent_hash + '.torrent',
                    'http://zoink.ch/torrent/' + torrent_name + '.torrent',
                    'http://torrage.com/torrent/' + torrent_hash + '.torrent',
                ]
            except:
                urls = [result.url]

            filename = ek.ek(os.path.join, sickbeard.TORRENT_DIR,
                             helpers.sanitizeFileName(result.name) + '.' + self.providerType)
        elif self.providerType == GenericProvider.NZB:
            urls = [result.url]

            filename = ek.ek(os.path.join, sickbeard.NZB_DIR,
                             helpers.sanitizeFileName(result.name) + '.' + self.providerType)
        else:
            return

        for url in urls:
            logger.log(u"Downloading a result from " + self.name + " at " + url)
            if helpers.download_file(url, filename, session=self.session):
                if self._verify_download(filename):
                    if self.providerType == GenericProvider.TORRENT:
                        logger.log(u"Saved magnet link to " + filename, logger.INFO)
                    else:
                        logger.log(u"Saved result to " + filename, logger.INFO)
                    return True
                else:
                    logger.log(u"Could not download %s" % url, logger.WARNING)
                    helpers._remove_file_failed(filename)

        if len(urls):
            logger.log(u"Failed to download any results", logger.WARNING)

        return False
开发者ID:ingolfured,项目名称:SickRage,代码行数:56,代码来源:generic.py


示例10: cache_image

    def cache_image(self, image_url):
        """
        Store cache of image in cache dir
        :param image_url: Source URL
        """
        if not self.cache_subfolder:
            return
        
        self.image_src = ek(posixpath.join, 'images', self.cache_subfolder, ek(os.path.basename, image_url))
        
        path = ek(os.path.abspath, ek(os.path.join, sickbeard.CACHE_DIR, 'images', self.cache_subfolder))

        if not ek(os.path.exists, path):
            ek(os.makedirs, path)

        full_path = ek(posixpath.join, path, ek(os.path.basename, image_url))

        if not ek(os.path.isfile, full_path):
            helpers.download_file(image_url, full_path, session=self.session)
开发者ID:Ockin,项目名称:SickRage-1,代码行数:19,代码来源:recommended.py


示例11: download_result

    def download_result(self, result):
        """
        Save the result to disk.
        """

        # check for auth
        if not self._do_login():
            return False

        if GenericProvider.TORRENT == self.providerType:
            try:
                torrent_hash = re.findall('urn:btih:([0-9a-f]{32,40})', result.url)[0].upper()

                if 32 == len(torrent_hash):
                    torrent_hash = b16encode(b32decode(torrent_hash)).lower()

                if not torrent_hash:
                    logger.log('Unable to extract torrent hash from link: ' + ex(result.url), logger.ERROR)
                    return False

                urls = ['https://%s/%s.torrent' % (u, torrent_hash)
                        for u in ('torcache.net/torrent', 'torrage.com/torrent', 'getstrike.net/torrents/api/download')]
            except:
                urls = [result.url]

            filename = ek.ek(os.path.join, sickbeard.TORRENT_DIR,
                             helpers.sanitizeFileName(result.name) + '.' + self.providerType)
        elif GenericProvider.NZB == self.providerType:
            urls = [result.url]

            filename = ek.ek(os.path.join, sickbeard.NZB_DIR,
                             helpers.sanitizeFileName(result.name) + '.' + self.providerType)
        else:
            return

        for url in urls:
            if helpers.download_file(url, filename, session=self.session):
                logger.log(u'Downloading a result from ' + self.name + ' at ' + url)

                if GenericProvider.TORRENT == self.providerType:
                    logger.log(u'Saved magnet link to ' + filename, logger.MESSAGE)
                else:
                    logger.log(u'Saved result to ' + filename, logger.MESSAGE)

                if self._verify_download(filename):
                    return True
                elif ek.ek(os.path.isfile, filename):
                    ek.ek(os.remove, filename)

        logger.log(u'Failed to download result', logger.ERROR)
        return False
开发者ID:joshguerette,项目名称:SickGear,代码行数:51,代码来源:generic.py


示例12: downloadResult

    def downloadResult(self, result):
        """
        Save the result to disk.
        """

        # check for auth
        if not self._doLogin():
            return False

        urls, filename = self._makeURL(result)

        if self.proxy.isEnabled():
            self.headers.update({'Referer': self.proxy.getProxyURL()})
        elif 'Referer' in self.headers:
            self.headers.pop('Referer')

        for url in urls:
            if 'NO_DOWNLOAD_NAME' in url:
                continue

            if not self.proxy.isEnabled() and url.startswith('http'):
                # Let's just set a referer for every .torrent/.nzb, should work as a cover-all without side-effects
                self.headers.update({'Referer': '/'.join(url.split('/')[:3]) + '/'})

            logger.log(u"Downloading a result from " + self.name + " at " + url)

            # Support for Jackett/TorzNab
            if url.endswith(GenericProvider.TORRENT) and filename.endswith(GenericProvider.NZB):
                filename = filename.rsplit('.', 1)[0] + '.' + GenericProvider.TORRENT

            if helpers.download_file(self.proxy._buildURL(url), filename, session=self.session, headers=self.headers):
                if self._verify_download(filename):
                    logger.log(u"Saved result to " + filename, logger.INFO)
                    return True
                else:
                    logger.log(u"Could not download %s" % url, logger.WARNING)
                    helpers._remove_file_failed(filename)

        if len(urls):
            logger.log(u"Failed to download any results", logger.WARNING)

        return False
开发者ID:quindarious-gooch,项目名称:SickRage,代码行数:42,代码来源:generic.py


示例13: downloadResult

    def downloadResult(self, result):
        """
        Save the result to disk.
        """

        # check for auth
        if not self._doLogin():
            return False

        urls, filename = self._makeURL(result)

        for url in urls:
            if 'NO_DOWNLOAD_NAME' in url:
                continue

            if url.startswith('http'):
                self.headers.update({'Referer': '/'.join(url.split('/')[:3]) + '/'})

            logger.log(u"Downloading a result from " + self.name + " at " + url)

            # Support for Jackett/TorzNab
            if url.endswith(GenericProvider.TORRENT) and filename.endswith(GenericProvider.NZB):
                filename = filename.rsplit('.', 1)[0] + '.' + GenericProvider.TORRENT

            if helpers.download_file(url, filename, session=self.session, headers=self.headers):
                if self._verify_download(filename):
                    logger.log(u"Saved result to " + filename, logger.INFO)
                    return True
                else:
                    logger.log(u"Could not download %s" % url, logger.WARNING)
                    helpers.remove_file_failed(filename)

        if len(urls):
            logger.log(u"Failed to download any results", logger.WARNING)

        return False
开发者ID:hernandito,项目名称:SickRage,代码行数:36,代码来源:generic.py


示例14: cache_image

 def cache_image(self, image_url, image_path):
     # Only cache if the file does not exist yet
     if not ek(os.path.isfile, image_path):
         helpers.download_file(image_url, image_path, session=self.session)
开发者ID:Elettronik,项目名称:SickRage,代码行数:4,代码来源:traktTrending.py


示例15: search_providers


#.........这里部分代码省略.........
                                   '#%s, removing the single episode results from the list' % ep_num, logger.DEBUG)
                        del found_results[provider_id][ep_num]

        # of all the single ep results narrow it down to the best one for each episode
        final_results += set(multi_results.values())
        quality_list = use_quality_list and (None, best_qualities)[any(best_qualities)] or None
        for cur_ep in found_results[provider_id]:
            if cur_ep in (MULTI_EP_RESULT, SEASON_RESULT):
                continue

            if 0 == len(found_results[provider_id][cur_ep]):
                continue

            best_result = pick_best_result(found_results[provider_id][cur_ep], show, quality_list,
                                           filter_rls=orig_thread_name)

            # if all results were rejected move on to the next episode
            if not best_result:
                continue

            # filter out possible bad torrents from providers
            if 'torrent' == best_result.resultType:
                if not best_result.url.startswith('magnet') and None is not best_result.get_data_func:
                    best_result.url = best_result.get_data_func(best_result.url)
                    best_result.get_data_func = None  # consume only once
                    if not best_result.url:
                        continue
                if best_result.url.startswith('magnet'):
                    if 'blackhole' != sickbeard.TORRENT_METHOD:
                        best_result.content = None
                else:
                    cache_file = ek.ek(os.path.join, sickbeard.CACHE_DIR or helpers._getTempDir(),
                                       '%s.torrent' % (helpers.sanitizeFileName(best_result.name)))
                    if not helpers.download_file(best_result.url, cache_file, session=best_result.provider.session):
                        continue

                    try:
                        with open(cache_file, 'rb') as fh:
                            td = fh.read()
                        setattr(best_result, 'cache_file', cache_file)
                    except (StandardError, Exception):
                        continue

                    if getattr(best_result.provider, 'chk_td', None):
                        name = None
                        try:
                            hdr = re.findall('(\w+(\d+):)', td[0:6])[0]
                            x, v = len(hdr[0]), int(hdr[1])
                            while x < len(td):
                                y = x + v
                                name = 'name' == td[x: y]
                                w = re.findall('((?:i-?\d+e|e+|d|l+)*(\d+):)', td[y: y + 32])[0]
                                x, v = y + len(w[0]), int(w[1])
                                if name:
                                    name = td[x: x + v]
                                    break
                        except (StandardError, Exception):
                            continue
                        if name:
                            if not pass_show_wordlist_checks(name, show):
                                continue
                            if not show_name_helpers.pass_wordlist_checks(name, indexer_lookup=False):
                                logger.log('Ignored: %s (debug log has detail)' % name)
                                continue
                            best_result.name = name
开发者ID:JackDandy,项目名称:SickGear,代码行数:66,代码来源:search.py


示例16: change_unrar_tool

def change_unrar_tool(unrar_tool, alt_unrar_tool):

    # Check for failed unrar attempt, and remove it
    # Must be done before unrar is ever called or the self-extractor opens and locks startup
    bad_unrar = os.path.join(sickbeard.DATA_DIR, 'unrar.exe')
    if os.path.exists(bad_unrar) and os.path.getsize(bad_unrar) == 447440:
        try:
            os.remove(bad_unrar)
        except OSError as e:
            logger.log("Unable to delete bad unrar.exe file {0}: {1}. You should delete it manually".format(bad_unrar, e.strerror), logger.WARNING)

    try:
        rarfile.custom_check(unrar_tool)
    except (rarfile.RarCannotExec, rarfile.RarExecError, OSError, IOError):
        # Let's just return right now if the defaults work
        try:
            # noinspection PyProtectedMember
            test = rarfile._check_unrar_tool()
            if test:
                # These must always be set to something before returning
                sickbeard.UNRAR_TOOL = rarfile.UNRAR_TOOL
                sickbeard.ALT_UNRAR_TOOL = rarfile.ALT_TOOL
                return True
        except (rarfile.RarCannotExec, rarfile.RarExecError, OSError, IOError):
            pass

        if platform.system() == 'Windows':
            # Look for WinRAR installations
            found = False
            winrar_path = 'WinRAR\\UnRAR.exe'
            # Make a set of unique paths to check from existing environment variables
            check_locations = {
                os.path.join(location, winrar_path) for location in (
                    os.environ.get("ProgramW6432"), os.environ.get("ProgramFiles(x86)"),
                    os.environ.get("ProgramFiles"), re.sub(r'\s?\(x86\)', '', os.environ["ProgramFiles"])
                ) if location
            }
            check_locations.add(os.path.join(sickbeard.PROG_DIR, 'unrar\\unrar.exe'))

            for check in check_locations:
                if ek(os.path.isfile, check):
                    # Can use it?
                    try:
                        rarfile.custom_check(check)
                        unrar_tool = check
                        found = True
                        break
                    except (rarfile.RarCannotExec, rarfile.RarExecError, OSError, IOError):
                        found = False

            # Download
            if not found:
                logger.log('Trying to download unrar.exe and set the path')
                unrar_store = ek(os.path.join, sickbeard.PROG_DIR, 'unrar')  # ./unrar (folder)
                unrar_zip = ek(os.path.join, sickbeard.PROG_DIR, 'unrar_win.zip')  # file download

                if (helpers.download_file(
                    "http://sickrage.github.io/unrar/unrar_win.zip", filename=unrar_zip, session=helpers.make_session()
                ) and helpers.extractZip(archive=unrar_zip, targetDir=unrar_store)):
                    try:
                        ek(os.remove, unrar_zip)
                    except OSError as e:
                        logger.log("Unable to delete downloaded file {0}: {1}. You may delete it manually".format(unrar_zip, e.strerror))

                    check = os.path.join(unrar_store, "unrar.exe")
                    try:
                        rarfile.custom_check(check)
                        unrar_tool = check
                        logger.log('Successfully downloaded unrar.exe and set as unrar tool', )
                    except (rarfile.RarCannotExec, rarfile.RarExecError, OSError, IOError):
                        logger.log('Sorry, unrar was not set up correctly. Try installing WinRAR and make sure it is on the system PATH')
                else:
                    logger.log('Unable to download unrar.exe')

    # These must always be set to something before returning
    sickbeard.UNRAR_TOOL = rarfile.UNRAR_TOOL = rarfile.ORIG_UNRAR_TOOL = unrar_tool
    sickbeard.ALT_UNRAR_TOOL = rarfile.ALT_TOOL = alt_unrar_tool

    try:
        # noinspection PyProtectedMember
        test = rarfile._check_unrar_tool()
    except (rarfile.RarCannotExec, rarfile.RarExecError, OSError, IOError):
        if sickbeard.UNPACK == 1:
            logger.log('Disabling UNPACK setting because no unrar is installed.')
            sickbeard.UNPACK = 0
        test = False

    return test
开发者ID:ArthurGarnier,项目名称:SickRage,代码行数:88,代码来源:config.py


示例17: update

    def update(self):  # pylint: disable=too-many-statements
        """
        Downloads the latest source tarball from github and installs it over the existing version.
        """

        tar_download_url = 'http://github.com/' + sickbeard.GIT_ORG + '/' + sickbeard.GIT_REPO + '/tarball/' + self.branch

        try:
            # prepare the update dir
            sr_update_dir = ek(os.path.join, sickbeard.PROG_DIR, u'sr-update')

            if ek(os.path.isdir, sr_update_dir):
                logger.log(u"Clearing out update folder " + sr_update_dir + " before extracting")
                shutil.rmtree(sr_update_dir)

            logger.log(u"Creating update folder " + sr_update_dir + " before extracting")
            ek(os.makedirs, sr_update_dir)

            # retrieve file
            logger.log(u"Downloading update from {url}".format(url=tar_download_url))
            tar_download_path = ek(os.path.join, sr_update_dir, u'sr-update.tar')
            helpers.download_file(tar_download_url, tar_download_path, session=self.session)

            if not ek(os.path.isfile, tar_download_path):
                logger.log(u"Unable to retrieve new version from " + tar_download_url + ", can't update", logger.WARNING)
                return False

            if not ek(tarfile.is_tarfile, tar_download_path):
                logger.log(u"Retrieved version from " + tar_download_url + " is corrupt, can't update", logger.ERROR)
                return False

            # extract to sr-update dir
            logger.log(u"Extracting file " + tar_download_path)
            tar = tarfile.open(tar_download_path)
            tar.extractall(sr_update_dir)
            tar.close()

            # delete .tar.gz
            logger.log(u"Deleting file " + tar_download_path)
            ek(os.remove, tar_download_path)

            # find update dir name
            update_dir_contents = [x for x in ek(os.listdir, sr_update_dir) if
                                   ek(os.path.isdir, ek(os.path.join, sr_update_dir, x))]

            if len(update_dir_contents) != 1:
                logger.log(u"Invalid update data, update failed: " + str(update_dir_contents), logger.ERROR)
                return False

            # walk temp folder and move files to main folder
            content_dir = ek(os.path.join, sr_update_dir, update_dir_contents[0])
            logger.log(u"Moving files from " + content_dir + " to " + sickbeard.PROG_DIR)
            for dirname, stderr_, filenames in ek(os.walk, content_dir):  # @UnusedVariable
                dirname = dirname[len(content_dir) + 1:]
                for curfile in filenames:
                    old_path = ek(os.path.join, content_dir, dirname, curfile)
                    new_path = ek(os.path.join, sickbeard.PROG_DIR, dirname, curfile)

                    # Avoid DLL access problem on WIN32/64
                    # These files needing to be updated manually
                    # or find a way to kill the access from memory
                    if curfile in ('unrar.dll', 'unrar64.dll'):
                        try:
                            ek(os.chmod, new_path, stat.S_IWRITE)
                            ek(os.remove, new_path)
                            ek(os.renames, old_path, new_path)
                        except Exception as e:
                            logger.log(u"Unable to update " + new_path + ': ' + ex(e), logger.DEBUG)
                            ek(os.remove, old_path)  # Trash the updated file without moving in new path
                        continue

                    if ek(os.path.isfile, new_path):
                        ek(os.remove, new_path)
                    ek(os.renames, old_path, new_path)

            sickbeard.CUR_COMMIT_HASH = self._newest_commit_hash
            sickbeard.CUR_COMMIT_BRANCH = self.branch

        except Exception as e:
            logger.log(u"Error while trying to update: " + ex(e), logger.ERROR)
            logger.log(u"Traceback: " + traceback.format_exc(), logger.DEBUG)
            return False

        # Notify update successful
        try:
            notifiers.notify_git_update(sickbeard.CUR_COMMIT_HASH or "")
        except Exception:
            logger.log(u"Unable to send update notification. Continuing the update process", logger.DEBUG)
        return True
开发者ID:Arcanemagus,项目名称:SickRage,代码行数:89,代码来源:versionChecker.py


示例18: _update_zoneinfo

def _update_zoneinfo():
    """
    Request new zoneinfo directly from repository
    """
    global sb_timezone
    sb_timezone = tz.tzlocal()
    url_zv = 'http://sickragetv.github.io/network_timezones/zoneinfo.txt'
    try:
        url_data = helpers.getURL(url_zv, session=requests.Session())
        if not url_data:
            raise

        # Filename of existing zoneinfo
        if zoneinfo.ZONEINFOFILE is not None:
            cur_zoneinfo = ek(basename, zoneinfo.ZONEINFOFILE)
        else:
            cur_zoneinfo = None

        # Filename and hash of new zoneinfo
        (new_zoneinfo, zoneinfo_md5) = url_data.strip().rsplit(u' ')
    except Exception as e:
        logger.log(u'Loading zoneinfo.txt failed, this can happen from time to time. Unable to get URL: %s' %
                url_zv, logger.WARNING)
        return

    if (cur_zoneinfo is not None) and (new_zoneinfo == cur_zoneinfo):
        return

    # now load the new zoneinfo
    url_tar = u'http://sickragetv.github.io/network_timezones/%s' % new_zoneinfo

    zonefile = helpers.real_path(ek(join, ek(os.path.dirname, zoneinfo.__file__), new_zoneinfo))
    zonefile_tmp = re.sub(r'\.tar\.gz$', '.tmp', zonefile)

    if ek(os.path.exists, zonefile_tmp):
        try:
            ekk(os.remove, zonefile_tmp)
        except:
            logger.log(u'Unable to delete: %s' % zonefile_tmp, logger.WARNING)
            return

    if not helpers.download_file(url_tar, zonefile_tmp, session=requests.Session()):
        return

    if not ek(os.path.exists, zonefile_tmp):
        logger.log(u'Download of %s failed.' % zonefile_tmp, logger.WARNING)
        return

    new_hash = str(helpers.md5_for_file(zonefile_tmp))

    if zoneinfo_md5.upper() == new_hash.upper():
        logger.log(u'Updating timezone info with new one: %s' % new_zoneinfo, logger.INFO)
        try:
            # remove the old zoneinfo file
            if cur_zoneinfo is not None:
                old_file = helpers.real_path(
                    ek(join, ek(os.path.dirname, zoneinfo.__file__), cur_zoneinfo))
                if ek(os.path.exists, old_file):
                    ek(os.remove, old_file)
            # rename downloaded file
            ek(os.rename, zonefile_tmp, zonefile)
            # load the new zoneinfo
            reload(zoneinfo)
            sb_timezone = tz.tzlocal()
        except:
            _remove_zoneinfo_failed(zonefile_tmp)
            return
    else:
        _remove_zoneinfo_failed(zonefile_tmp)
        logger.log(u'MD5 hash does not match: %s File: %s' % (zoneinfo_md5.upper(), new_hash.upper()), logger.WARNING)
        return
开发者ID:logo000,项目名称:SickRage,代码行数:71,代码来源:network_timezones.py


示例19: update

    def update(self):
        """
        Downloads the latest source tarball from github and installs it over the existing version.
        """

        tar_download_url = 'http://github.com/' + self.github_org + '/' + self.github_repo + '/tarball/' + self.branch

        try:
            # prepare the update dir
            sr_update_dir = ek(os.path.join, sickbeard.PROG_DIR, 'sr-update')

            if ek(os.path.isdir, sr_update_dir):
                logging.info("Clearing out update folder " + sr_update_dir + " before extracting")
                ek(removetree, sr_update_dir)

            logging.info("Creating update folder " + sr_update_dir + " before extracting")
            ek(os.makedirs, sr_update_dir)

            # retrieve file
            logging.info("Downloading update from " + repr(tar_download_url))
            tar_download_path = ek(os.path.join, sr_update_dir, 'sr-update.tar')
            helpers.download_file(tar_download_url, tar_download_path, session=self.session)

            if not ek(os.path.isfile, tar_download_path):
                logging.warning("Unable to retrieve new version from " + tar_download_url + ", can't update")
                return False

            if not ek(tarfile.is_tarfile, tar_download_path):
                logging.error("Retrieved version from " + tar_download_url + " is corrupt, can't update")
                return False

            # extract to sr-update dir
            logging.info("Extracting file " + tar_download_path)
            tar = tarfile.open(tar_download_path)
            tar.extractall(sr_update_dir)
            tar.close()

            # delete .tar.gz
            logging.info("Deleting file " + tar_download_path)
            ek(os.remove, tar_download_path)

            # find update dir name
            update_dir_contents = [x for x in ek(os.listdir, sr_update_dir) if
                                   ek(os.path.isdir, ek(os.path.join, sr_update_dir, x))]
            if len(update_dir_contents) != 1:
                logging.error("Invalid update data, update failed: " + str(update_dir_contents))
                return False
            content_dir = ek(os.path.join, sr_update_dir, update_dir_contents[0])

            # walk temp folder and move files to main folder
            logging.info("Moving files from " + content_dir + " to " + sickbeard.PROG_DIR)
            for dirname, _, filenames in ek(os.walk, content_dir):  # @UnusedVariable
                dirname = dirname[len(content_dir) + 1:]
                for curfile in filenames:
                    old_path = ek(os.path.join, content_dir, dirname, curfile)
                    new_path = ek(os.path.join, sickbeard.PROG_DIR, dirname, curfile)

                    # Avoid DLL access problem on WIN32/64
                    # These files needing to be updated manually
                    # or find a way to kill the access from memory
                    if curfile in ('unrar.dll', 'unrar64.dll'):
                        try:
                            ek(os.chmod, new_path, stat.S_IWRITE)
                            ek(os.remove, new_path)
                            ek(os.renames, old_path, new_path)
                        except Exception as e:
                            logging.debug("Unable to update " + new_path + ': ' + ex(e))
                            ek(os.remove, old_path)  # Trash the updated file without moving in new path
                        continue

                    if ek(os.path.isfile, new_path):
                        ek(os.remove, new_path)
                    ek(os.renames, old_path, new_path)

            sickbeard.CUR_COMMIT_HASH = self._newest_commit_hash
            sickbeard.CUR_COMMIT_BRANCH = self.branch

        except Exception as e:
            logging.error("Error while trying to update: {}".format(ex(e)))
            logging.debug("Traceback: " + traceback.format_exc())
            return False

        # Notify update successful
        notifiers.notify_git_update(sickbeard.NEWEST_VERSION_STRING)

        return True
开发者ID:coderbone,项目名称:SickRage,代码行数:86,代码来源:versionChecker.py


示例20: _update_zoneinfo

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python helpers.encrypt函数代码示例发布时间:2022-05-27
下一篇:
Python helpers.delete_empty_folders函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap