aboutsummaryrefslogtreecommitdiffstats
path: root/yt_dlp
diff options
context:
space:
mode:
Diffstat (limited to 'yt_dlp')
-rw-r--r--yt_dlp/YoutubeDL.py2
-rw-r--r--yt_dlp/__init__.py23
-rw-r--r--yt_dlp/downloader/hls.py4
-rw-r--r--yt_dlp/extractor/iqiyi.py174
-rw-r--r--yt_dlp/extractor/ivi.py4
-rw-r--r--yt_dlp/options.py20
-rw-r--r--yt_dlp/update.py439
-rw-r--r--yt_dlp/utils/_utils.py18
8 files changed, 21 insertions, 663 deletions
diff --git a/yt_dlp/YoutubeDL.py b/yt_dlp/YoutubeDL.py
index 666d89b46..2d2e84fc2 100644
--- a/yt_dlp/YoutubeDL.py
+++ b/yt_dlp/YoutubeDL.py
@@ -59,8 +59,6 @@ from .postprocessor import (
MoveFilesAfterDownloadPP,
get_postprocessor,
)
-from .postprocessor.ffmpeg import resolve_mapping as resolve_recode_mapping
-from .update import REPOSITORY, current_git_head, detect_variant
from .utils import (
DEFAULT_OUTTMPL,
IDENTITY,
diff --git a/yt_dlp/__init__.py b/yt_dlp/__init__.py
index 991dbcda7..b4dc12fac 100644
--- a/yt_dlp/__init__.py
+++ b/yt_dlp/__init__.py
@@ -1,10 +1,7 @@
-try:
- import contextvars # noqa: F401
-except Exception:
- raise Exception(
- f'You are using an unsupported version of Python. Only Python versions 3.7 and above are supported by yt-dlp') # noqa: F541
+#!/usr/bin/python
+f'You are using an unsupported version of Python. Only Python versions 3.6 and above are supported by yt-dlp' # noqa: F541
-__license__ = 'Public Domain'
+__license__ = 'CC0-1.0'
import collections
import getpass
@@ -32,7 +29,6 @@ from .postprocessor import (
MetadataFromFieldPP,
MetadataParserPP,
)
-from .update import Updater
from .utils import (
NO_DEFAULT,
POSTPROCESS_WHEN,
@@ -966,19 +962,6 @@ def _real_main(argv=None):
if opts.rm_cachedir:
ydl.cache.remove()
- try:
- updater = Updater(ydl, opts.update_self)
- if opts.update_self and updater.update() and actual_use:
- if updater.cmd:
- return updater.restart()
- # This code is reachable only for zip variant in py < 3.10
- # It makes sense to exit here, but the old behavior is to continue
- ydl.report_warning('Restart yt-dlp to use the updated version')
- # return 100, 'ERROR: The program must exit for the update to complete'
- except Exception:
- traceback.print_exc()
- ydl._download_retcode = 100
-
if not actual_use:
if pre_process:
return ydl._download_retcode
diff --git a/yt_dlp/downloader/hls.py b/yt_dlp/downloader/hls.py
index d4b3f0320..6eee71a8c 100644
--- a/yt_dlp/downloader/hls.py
+++ b/yt_dlp/downloader/hls.py
@@ -83,9 +83,9 @@ class HlsFD(FragmentFD):
has_ffmpeg = FFmpegFD.available()
no_crypto = not Cryptodome.AES and '#EXT-X-KEY:METHOD=AES-128' in s
if no_crypto and has_ffmpeg:
- can_download, message = False, 'The stream has AES-128 encryption and pycryptodomex is not available'
+ can_download, message = False, 'The stream has AES-128 encryption and pycryptodome is not available'
elif no_crypto:
- message = ('The stream has AES-128 encryption and neither ffmpeg nor pycryptodomex are available; '
+ message = ('The stream has AES-128 encryption and neither ffmpeg nor pycryptodome are available; '
'Decryption will be performed natively, but will be extremely slow')
elif info_dict.get('extractor_key') == 'Generic' and re.search(r'(?m)#EXT-X-MEDIA-SEQUENCE:(?!0$)', s):
install_ffmpeg = '' if has_ffmpeg else 'install ffmpeg and '
diff --git a/yt_dlp/extractor/iqiyi.py b/yt_dlp/extractor/iqiyi.py
index fa602ba88..94bcad412 100644
--- a/yt_dlp/extractor/iqiyi.py
+++ b/yt_dlp/extractor/iqiyi.py
@@ -6,13 +6,11 @@ import time
from .common import InfoExtractor
from ..compat import (
compat_str,
- compat_urllib_parse_urlencode,
compat_urllib_parse_unquote
)
from .openload import PhantomJSwrapper
from ..utils import (
clean_html,
- decode_packed_codes,
ExtractorError,
float_or_none,
format_field,
@@ -37,135 +35,6 @@ def md5_text(text):
return hashlib.md5(text.encode('utf-8')).hexdigest()
-class IqiyiSDK:
- def __init__(self, target, ip, timestamp):
- self.target = target
- self.ip = ip
- self.timestamp = timestamp
-
- @staticmethod
- def split_sum(data):
- return compat_str(sum(map(lambda p: int(p, 16), list(data))))
-
- @staticmethod
- def digit_sum(num):
- if isinstance(num, int):
- num = compat_str(num)
- return compat_str(sum(map(int, num)))
-
- def even_odd(self):
- even = self.digit_sum(compat_str(self.timestamp)[::2])
- odd = self.digit_sum(compat_str(self.timestamp)[1::2])
- return even, odd
-
- def preprocess(self, chunksize):
- self.target = md5_text(self.target)
- chunks = []
- for i in range(32 // chunksize):
- chunks.append(self.target[chunksize * i:chunksize * (i + 1)])
- if 32 % chunksize:
- chunks.append(self.target[32 - 32 % chunksize:])
- return chunks, list(map(int, self.ip.split('.')))
-
- def mod(self, modulus):
- chunks, ip = self.preprocess(32)
- self.target = chunks[0] + ''.join(map(lambda p: compat_str(p % modulus), ip))
-
- def split(self, chunksize):
- modulus_map = {
- 4: 256,
- 5: 10,
- 8: 100,
- }
-
- chunks, ip = self.preprocess(chunksize)
- ret = ''
- for i in range(len(chunks)):
- ip_part = compat_str(ip[i] % modulus_map[chunksize]) if i < 4 else ''
- if chunksize == 8:
- ret += ip_part + chunks[i]
- else:
- ret += chunks[i] + ip_part
- self.target = ret
-
- def handle_input16(self):
- self.target = md5_text(self.target)
- self.target = self.split_sum(self.target[:16]) + self.target + self.split_sum(self.target[16:])
-
- def handle_input8(self):
- self.target = md5_text(self.target)
- ret = ''
- for i in range(4):
- part = self.target[8 * i:8 * (i + 1)]
- ret += self.split_sum(part) + part
- self.target = ret
-
- def handleSum(self):
- self.target = md5_text(self.target)
- self.target = self.split_sum(self.target) + self.target
-
- def date(self, scheme):
- self.target = md5_text(self.target)
- d = time.localtime(self.timestamp)
- strings = {
- 'y': compat_str(d.tm_year),
- 'm': '%02d' % d.tm_mon,
- 'd': '%02d' % d.tm_mday,
- }
- self.target += ''.join(map(lambda c: strings[c], list(scheme)))
-
- def split_time_even_odd(self):
- even, odd = self.even_odd()
- self.target = odd + md5_text(self.target) + even
-
- def split_time_odd_even(self):
- even, odd = self.even_odd()
- self.target = even + md5_text(self.target) + odd
-
- def split_ip_time_sum(self):
- chunks, ip = self.preprocess(32)
- self.target = compat_str(sum(ip)) + chunks[0] + self.digit_sum(self.timestamp)
-
- def split_time_ip_sum(self):
- chunks, ip = self.preprocess(32)
- self.target = self.digit_sum(self.timestamp) + chunks[0] + compat_str(sum(ip))
-
-
-class IqiyiSDKInterpreter:
- def __init__(self, sdk_code):
- self.sdk_code = sdk_code
-
- def run(self, target, ip, timestamp):
- self.sdk_code = decode_packed_codes(self.sdk_code)
-
- functions = re.findall(r'input=([a-zA-Z0-9]+)\(input', self.sdk_code)
-
- sdk = IqiyiSDK(target, ip, timestamp)
-
- other_functions = {
- 'handleSum': sdk.handleSum,
- 'handleInput8': sdk.handle_input8,
- 'handleInput16': sdk.handle_input16,
- 'splitTimeEvenOdd': sdk.split_time_even_odd,
- 'splitTimeOddEven': sdk.split_time_odd_even,
- 'splitIpTimeSum': sdk.split_ip_time_sum,
- 'splitTimeIpSum': sdk.split_time_ip_sum,
- }
- for function in functions:
- if re.match(r'mod\d+', function):
- sdk.mod(int(function[3:]))
- elif re.match(r'date[ymd]{3}', function):
- sdk.date(function[4:])
- elif re.match(r'split\d+', function):
- sdk.split(int(function[5:]))
- elif function in other_functions:
- other_functions[function]()
- else:
- raise ExtractorError('Unknown function %s' % function)
-
- return sdk.target
-
-
class IqiyiIE(InfoExtractor):
IE_NAME = 'iqiyi'
IE_DESC = '爱奇艺'
@@ -246,47 +115,8 @@ class IqiyiIE(InfoExtractor):
return ohdave_rsa_encrypt(data, e, N)
- def _perform_login(self, username, password):
-
- data = self._download_json(
- 'http://kylin.iqiyi.com/get_token', None,
- note='Get token for logging', errnote='Unable to get token for logging')
- sdk = data['sdk']
- timestamp = int(time.time())
- target = '/apis/reglogin/login.action?lang=zh_TW&area_code=null&email=%s&passwd=%s&agenttype=1&from=undefined&keeplogin=0&piccode=&fromurl=&_pos=1' % (
- username, self._rsa_fun(password.encode('utf-8')))
-
- interp = IqiyiSDKInterpreter(sdk)
- sign = interp.run(target, data['ip'], timestamp)
-
- validation_params = {
- 'target': target,
- 'server': 'BEA3AA1908656AABCCFF76582C4C6660',
- 'token': data['token'],
- 'bird_src': 'f8d91d57af224da7893dd397d52d811a',
- 'sign': sign,
- 'bird_t': timestamp,
- }
- validation_result = self._download_json(
- 'http://kylin.iqiyi.com/validate?' + compat_urllib_parse_urlencode(validation_params), None,
- note='Validate credentials', errnote='Unable to validate credentials')
-
- MSG_MAP = {
- 'P00107': 'please login via the web interface and enter the CAPTCHA code',
- 'P00117': 'bad username or password',
- }
-
- code = validation_result['code']
- if code != 'A00000':
- msg = MSG_MAP.get(code)
- if not msg:
- msg = 'error %s' % code
- if validation_result.get('msg'):
- msg += ': ' + validation_result['msg']
- self.report_warning('unable to log in: ' + msg)
- return False
-
- return True
+ def _perform_login(self):
+ raise ExtractorError("iQiyi's non-free authentication algorithm has made login impossible", expected=True)
def get_raw_data(self, tvid, video_id):
tm = int(time.time() * 1000)
diff --git a/yt_dlp/extractor/ivi.py b/yt_dlp/extractor/ivi.py
index fa5ceec95..e7ba5f339 100644
--- a/yt_dlp/extractor/ivi.py
+++ b/yt_dlp/extractor/ivi.py
@@ -126,8 +126,8 @@ class IviIE(InfoExtractor):
extractor_msg = 'Video %s does not exist'
elif site == 353:
continue
- elif not Cryptodome.CMAC:
- raise ExtractorError('pycryptodomex not found. Please install', expected=True)
+ elif not pycryptodome_found:
+ raise ExtractorError('pycryptodome not found. Please install', expected=True)
elif message:
extractor_msg += ': ' + message
raise ExtractorError(extractor_msg % video_id, expected=True)
diff --git a/yt_dlp/options.py b/yt_dlp/options.py
index 163809706..9e71108ab 100644
--- a/yt_dlp/options.py
+++ b/yt_dlp/options.py
@@ -20,7 +20,6 @@ from .postprocessor import (
SponsorBlockPP,
)
from .postprocessor.modify_chapters import DEFAULT_SPONSORBLOCK_CHAPTER_TITLE
-from .update import UPDATE_SOURCES, detect_variant, is_non_updateable
from .utils import (
OUTTMPL_TYPES,
POSTPROCESS_WHEN,
@@ -157,7 +156,7 @@ class _YoutubeDLOptionParser(optparse.OptionParser):
def __init__(self):
super().__init__(
- prog='yt-dlp' if detect_variant() == 'source' else None,
+ prog='yt-dlp',
version=__version__,
usage='%prog [OPTIONS] URL [URL...]',
epilog='See full documentation at https://github.com/yt-dlp/yt-dlp#readme',
@@ -323,23 +322,6 @@ def create_parser():
action='version',
help='Print program version and exit')
general.add_option(
- '-U', '--update',
- action='store_const', dest='update_self', const=CHANNEL,
- help=format_field(
- is_non_updateable(), None, 'Check if updates are available. %s',
- default=f'Update this program to the latest {CHANNEL} version'))
- general.add_option(
- '--no-update',
- action='store_false', dest='update_self',
- help='Do not check for updates (default)')
- general.add_option(
- '--update-to',
- action='store', dest='update_self', metavar='[CHANNEL]@[TAG]',
- help=(
- 'Upgrade/downgrade to a specific version. CHANNEL can be a repository as well. '
- f'CHANNEL and TAG default to "{CHANNEL.partition("@")[0]}" and "latest" respectively if omitted; '
- f'See "UPDATE" for details. Supported channels: {", ".join(UPDATE_SOURCES)}'))
- general.add_option(
'-i', '--ignore-errors',
action='store_true', dest='ignoreerrors',
help='Ignore download and postprocessing errors. The download will be considered successful even if the postprocessing fails')
diff --git a/yt_dlp/update.py b/yt_dlp/update.py
deleted file mode 100644
index d708b09e3..000000000
--- a/yt_dlp/update.py
+++ /dev/null
@@ -1,439 +0,0 @@
-import atexit
-import contextlib
-import hashlib
-import json
-import os
-import platform
-import re
-import subprocess
-import sys
-from zipimport import zipimporter
-
-from .compat import functools # isort: split
-from .compat import compat_realpath, compat_shlex_quote
-from .networking import Request
-from .networking.exceptions import HTTPError, network_exceptions
-from .utils import (
- Popen,
- cached_method,
- deprecation_warning,
- remove_end,
- remove_start,
- shell_quote,
- system_identifier,
- version_tuple,
-)
-from .version import CHANNEL, UPDATE_HINT, VARIANT, __version__
-
-UPDATE_SOURCES = {
- 'stable': 'yt-dlp/yt-dlp',
- 'nightly': 'yt-dlp/yt-dlp-nightly-builds',
-}
-REPOSITORY = UPDATE_SOURCES['stable']
-
-_VERSION_RE = re.compile(r'(\d+\.)*\d+')
-
-API_BASE_URL = 'https://api.github.com/repos'
-
-# Backwards compatibility variables for the current channel
-API_URL = f'{API_BASE_URL}/{REPOSITORY}/releases'
-
-
-@functools.cache
-def _get_variant_and_executable_path():
- """@returns (variant, executable_path)"""
- if getattr(sys, 'frozen', False):
- path = sys.executable
- if not hasattr(sys, '_MEIPASS'):
- return 'py2exe', path
- elif sys._MEIPASS == os.path.dirname(path):
- return f'{sys.platform}_dir', path
- elif sys.platform == 'darwin':
- machine = '_legacy' if version_tuple(platform.mac_ver()[0]) < (10, 15) else ''
- else:
- machine = f'_{platform.machine().lower()}'
- # Ref: https://en.wikipedia.org/wiki/Uname#Examples
- if machine[1:] in ('x86', 'x86_64', 'amd64', 'i386', 'i686'):
- machine = '_x86' if platform.architecture()[0][:2] == '32' else ''
- return f'{remove_end(sys.platform, "32")}{machine}_exe', path
-
- path = os.path.dirname(__file__)
- if isinstance(__loader__, zipimporter):
- return 'zip', os.path.join(path, '..')
- elif (os.path.basename(sys.argv[0]) in ('__main__.py', '-m')
- and os.path.exists(os.path.join(path, '../.git/HEAD'))):
- return 'source', path
- return 'unknown', path
-
-
-def detect_variant():
- return VARIANT or _get_variant_and_executable_path()[0]
-
-
-@functools.cache
-def current_git_head():
- if detect_variant() != 'source':
- return
- with contextlib.suppress(Exception):
- stdout, _, _ = Popen.run(
- ['git', 'rev-parse', '--short', 'HEAD'],
- text=True, cwd=os.path.dirname(os.path.abspath(__file__)),
- stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- if re.fullmatch('[0-9a-f]+', stdout.strip()):
- return stdout.strip()
-
-
-_FILE_SUFFIXES = {
- 'zip': '',
- 'py2exe': '_min.exe',
- 'win_exe': '.exe',
- 'win_x86_exe': '_x86.exe',
- 'darwin_exe': '_macos',
- 'darwin_legacy_exe': '_macos_legacy',
- 'linux_exe': '_linux',
- 'linux_aarch64_exe': '_linux_aarch64',
- 'linux_armv7l_exe': '_linux_armv7l',
-}
-
-_NON_UPDATEABLE_REASONS = {
- **{variant: None for variant in _FILE_SUFFIXES}, # Updatable
- **{variant: f'Auto-update is not supported for unpackaged {name} executable; Re-download the latest release'
- for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS', 'linux_dir': 'Linux'}.items()},
- 'source': 'You cannot update when running from source code; Use git to pull the latest changes',
- 'unknown': 'You installed yt-dlp with a package manager or setup.py; Use that to update',
- 'other': 'You are using an unofficial build of yt-dlp; Build the executable again',
-}
-
-
-def is_non_updateable():
- if UPDATE_HINT:
- return UPDATE_HINT
- return _NON_UPDATEABLE_REASONS.get(
- detect_variant(), _NON_UPDATEABLE_REASONS['unknown' if VARIANT else 'other'])
-
-
-def _sha256_file(path):
- h = hashlib.sha256()
- mv = memoryview(bytearray(128 * 1024))
- with open(os.path.realpath(path), 'rb', buffering=0) as f:
- for n in iter(lambda: f.readinto(mv), 0):
- h.update(mv[:n])
- return h.hexdigest()
-
-
-class Updater:
- _exact = True
-
- def __init__(self, ydl, target=None):
- self.ydl = ydl
-
- self.target_channel, sep, self.target_tag = (target or CHANNEL).rpartition('@')
- # stable => stable@latest
- if not sep and ('/' in self.target_tag or self.target_tag in UPDATE_SOURCES):
- self.target_channel = self.target_tag
- self.target_tag = None
- elif not self.target_channel:
- self.target_channel = CHANNEL.partition('@')[0]
-
- if not self.target_tag:
- self.target_tag = 'latest'
- self._exact = False
- elif self.target_tag != 'latest':
- self.target_tag = f'tags/{self.target_tag}'
-
- if '/' in self.target_channel:
- self._target_repo = self.target_channel
- if self.target_channel not in (CHANNEL, *UPDATE_SOURCES.values()):
- self.ydl.report_warning(
- f'You are switching to an {self.ydl._format_err("unofficial", "red")} executable '
- f'from {self.ydl._format_err(self._target_repo, self.ydl.Styles.EMPHASIS)}. '
- f'Run {self.ydl._format_err("at your own risk", "light red")}')
- self._block_restart('Automatically restarting into custom builds is disabled for security reasons')
- else:
- self._target_repo = UPDATE_SOURCES.get(self.target_channel)
- if not self._target_repo:
- self._report_error(
- f'Invalid update channel {self.target_channel!r} requested. '
- f'Valid channels are {", ".join(UPDATE_SOURCES)}', True)
-
- def _version_compare(self, a, b, channel=CHANNEL):
- if self._exact and channel != self.target_channel:
- return False
-
- if _VERSION_RE.fullmatch(f'{a}.{b}'):
- a, b = version_tuple(a), version_tuple(b)
- return a == b if self._exact else a >= b
- return a == b
-
- @functools.cached_property
- def _tag(self):
- if self._version_compare(self.current_version, self.latest_version):
- return self.target_tag
-
- identifier = f'{detect_variant()} {self.target_channel} {system_identifier()}'
- for line in self._download('_update_spec', 'latest').decode().splitlines():
- if not line.startswith('lock '):
- continue
- _, tag, pattern = line.split(' ', 2)
- if re.match(pattern, identifier):
- if not self._exact:
- return f'tags/{tag}'
- elif self.target_tag == 'latest' or not self._version_compare(
- tag, self.target_tag[5:], channel=self.target_channel):
- self._report_error(
- f'yt-dlp cannot be updated above {tag} since you are on an older Python version', True)
- return f'tags/{self.current_version}'
- return self.target_tag
-
- @cached_method
- def _get_version_info(self, tag):
- url = f'{API_BASE_URL}/{self._target_repo}/releases/{tag}'
- self.ydl.write_debug(f'Fetching release info: {url}')
- return json.loads(self.ydl.urlopen(Request(url, headers={
- 'Accept': 'application/vnd.github+json',
- 'User-Agent': 'yt-dlp',
- 'X-GitHub-Api-Version': '2022-11-28',
- })).read().decode())
-
- @property
- def current_version(self):
- """Current version"""
- return __version__
-
- @staticmethod
- def _label(channel, tag):
- """Label for a given channel and tag"""
- return f'{channel}@{remove_start(tag, "tags/")}'
-
- def _get_actual_tag(self, tag):
- if tag.startswith('tags/'):
- return tag[5:]
- return self._get_version_info(tag)['tag_name']
-
- @property
- def new_version(self):
- """Version of the latest release we can update to"""
- return self._get_actual_tag(self._tag)
-
- @property
- def latest_version(self):
- """Version of the target release"""
- return self._get_actual_tag(self.target_tag)
-
- @property
- def has_update(self):
- """Whether there is an update available"""
- return not self._version_compare(self.current_version, self.new_version)
-
- @functools.cached_property
- def filename(self):
- """Filename of the executable"""
- return compat_realpath(_get_variant_and_executable_path()[1])
-
- def _download(self, name, tag):
- slug = 'latest/download' if tag == 'latest' else f'download/{tag[5:]}'
- url = f'https://github.com/{self._target_repo}/releases/{slug}/{name}'
- self.ydl.write_debug(f'Downloading {name} from {url}')
- return self.ydl.urlopen(url).read()
-
- @functools.cached_property
- def release_name(self):
- """The release filename"""
- return f'yt-dlp{_FILE_SUFFIXES[detect_variant()]}'
-
- @functools.cached_property
- def release_hash(self):
- """Hash of the latest release"""
- hash_data = dict(ln.split()[::-1] for ln in self._download('SHA2-256SUMS', self._tag).decode().splitlines())
- return hash_data[self.release_name]
-
- def _report_error(self, msg, expected=False):
- self.ydl.report_error(msg, tb=False if expected else None)
- self.ydl._download_retcode = 100
-
- def _report_permission_error(self, file):
- self._report_error(f'Unable to write to {file}; Try running as administrator', True)
-
- def _report_network_error(self, action, delim=';'):
- self._report_error(
- f'Unable to {action}{delim} visit '
- f'https://github.com/{self._target_repo}/releases/{self.target_tag.replace("tags/", "tag/")}', True)
-
- def check_update(self):
- """Report whether there is an update available"""
- if not self._target_repo:
- return False
- try:
- self.ydl.to_screen((
- f'Available version: {self._label(self.target_channel, self.latest_version)}, ' if self.target_tag == 'latest' else ''
- ) + f'Current version: {self._label(CHANNEL, self.current_version)}')
- except network_exceptions as e:
- return self._report_network_error(f'obtain version info ({e})', delim='; Please try again later or')
-
- if not is_non_updateable():
- self.ydl.to_screen(f'Current Build Hash: {_sha256_file(self.filename)}')
-
- if self.has_update:
- return True
-
- if self.target_tag == self._tag:
- self.ydl.to_screen(f'yt-dlp is up to date ({self._label(CHANNEL, self.current_version)})')
- elif not self._exact:
- self.ydl.report_warning('yt-dlp cannot be updated any further since you are on an older Python version')
- return False
-
- def update(self):
- """Update yt-dlp executable to the latest version"""
- if not self.check_update():
- return
- err = is_non_updateable()
- if err:
- return self._report_error(err, True)
- self.ydl.to_screen(f'Updating to {self._label(self.target_channel, self.new_version)} ...')
- if (_VERSION_RE.fullmatch(self.target_tag[5:])
- and version_tuple(self.target_tag[5:]) < (2023, 3, 2)):
- self.ydl.report_warning('You are downgrading to a version without --update-to')
- self._block_restart('Cannot automatically restart to a version without --update-to')
-
- directory = os.path.dirname(self.filename)
- if not os.access(self.filename, os.W_OK):
- return self._report_permission_error(self.filename)
- elif not os.access(directory, os.W_OK):
- return self._report_permission_error(directory)
-
- new_filename, old_filename = f'{self.filename}.new', f'{self.filename}.old'
- if detect_variant() == 'zip': # Can be replaced in-place
- new_filename, old_filename = self.filename, None
-
- try:
- if os.path.exists(old_filename or ''):
- os.remove(old_filename)
- except OSError:
- return self._report_error('Unable to remove the old version')
-
- try:
- newcontent = self._download(self.release_name, self._tag)
- except network_exceptions as e:
- if isinstance(e, HTTPError) and e.status == 404:
- return self._report_error(
- f'The requested tag {self._label(self.target_channel, self.target_tag)} does not exist', True)
- return self._report_network_error(f'fetch updates: {e}')
-
- try:
- expected_hash = self.release_hash
- except Exception:
- self.ydl.report_warning('no hash information found for the release')
- else:
- if hashlib.sha256(newcontent).hexdigest() != expected_hash:
- return self._report_network_error('verify the new executable')
-
- try:
- with open(new_filename, 'wb') as outf:
- outf.write(newcontent)
- except OSError:
- return self._report_permission_error(new_filename)
-
- if old_filename:
- mask = os.stat(self.filename).st_mode
- try:
- os.rename(self.filename, old_filename)
- except OSError:
- return self._report_error('Unable to move current version')
-
- try:
- os.rename(new_filename, self.filename)
- except OSError:
- self._report_error('Unable to overwrite current version')
- return os.rename(old_filename, self.filename)
-
- variant = detect_variant()
- if variant.startswith('win') or variant == 'py2exe':
- atexit.register(Popen, f'ping 127.0.0.1 -n 5 -w 1000 & del /F "{old_filename}"',
- shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- elif old_filename:
- try:
- os.remove(old_filename)
- except OSError:
- self._report_error('Unable to remove the old version')
-
- try:
- os.chmod(self.filename, mask)
- except OSError:
- return self._report_error(
- f'Unable to set permissions. Run: sudo chmod a+rx {compat_shlex_quote(self.filename)}')
-
- self.ydl.to_screen(f'Updated yt-dlp to {self._label(self.target_channel, self.new_version)}')
- return True
-
- @functools.cached_property
- def cmd(self):
- """The command-line to run the executable, if known"""
- # There is no sys.orig_argv in py < 3.10. Also, it can be [] when frozen
- if getattr(sys, 'orig_argv', None):
- return sys.orig_argv
- elif getattr(sys, 'frozen', False):
- return sys.argv
-
- def restart(self):
- """Restart the executable"""
- assert self.cmd, 'Must be frozen or Py >= 3.10'
- self.ydl.write_debug(f'Restarting: {shell_quote(self.cmd)}')
- _, _, returncode = Popen.run(self.cmd)
- return returncode
-
- def _block_restart(self, msg):
- def wrapper():
- self._report_error(f'{msg}. Restart yt-dlp to use the updated version', expected=True)
- return self.ydl._download_retcode
- self.restart = wrapper
-
-
-def run_update(ydl):
- """Update the program file with the latest version from the repository
- @returns Whether there was a successful update (No update = False)
- """
- return Updater(ydl).update()
-
-
-# Deprecated
-def update_self(to_screen, verbose, opener):
- import traceback
-
- deprecation_warning(f'"{__name__}.update_self" is deprecated and may be removed '
- f'in a future version. Use "{__name__}.run_update(ydl)" instead')
-
- printfn = to_screen
-
- class FakeYDL():
- to_screen = printfn
-
- def report_warning(self, msg, *args, **kwargs):
- return printfn(f'WARNING: {msg}', *args, **kwargs)
-
- def report_error(self, msg, tb=None):
- printfn(f'ERROR: {msg}')
- if not verbose:
- return
- if tb is None:
- # Copied from YoutubeDL.trouble
- if sys.exc_info()[0]:
- tb = ''
- if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
- tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
- tb += traceback.format_exc()
- else:
- tb_data = traceback.format_list(traceback.extract_stack())
- tb = ''.join(tb_data)
- if tb:
- printfn(tb)
-
- def write_debug(self, msg, *args, **kwargs):
- printfn(f'[debug] {msg}', *args, **kwargs)
-
- def urlopen(self, url):
- return opener.open(url)
-
- return run_update(FakeYDL())
-
-
-__all__ = ['Updater']
diff --git a/yt_dlp/utils/_utils.py b/yt_dlp/utils/_utils.py
index f5552ce80..3d27510ea 100644
--- a/yt_dlp/utils/_utils.py
+++ b/yt_dlp/utils/_utils.py
@@ -882,10 +882,9 @@ def formatSeconds(secs, delim=':', msec=False):
def bug_reports_message(before=';'):
- from ..update import REPOSITORY
-
- msg = (f'please report this issue on https://github.com/{REPOSITORY}/issues?q= , '
- 'filling out the appropriate issue template. Confirm you are on the latest version using yt-dlp -U')
+ msg = ('please report this issue on https://issues.hyperbola.info/ , '
+ 'filling out the appropriate issue template. '
+ 'Confirm you are on the latest version using pacman -Su')
before = before.rstrip()
if not before or before.endswith(('.', '!', '?')):
@@ -4613,9 +4612,14 @@ def make_dir(path, to_screen=None):
def get_executable_path():
- from ..update import _get_variant_and_executable_path
-
- return os.path.dirname(os.path.abspath(_get_variant_and_executable_path()[1]))
+ from zipimport import zipimporter
+ if hasattr(sys, 'frozen'): # Running from PyInstaller
+ path = os.path.dirname(sys.executable)
+ elif isinstance(globals().get('__loader__'), zipimporter): # Running from ZIP
+ path = os.path.join(os.path.dirname(__file__), '../..')
+ else:
+ path = os.path.join(os.path.dirname(__file__), '..')
+ return os.path.abspath(path)
def get_user_config_dirs(package_name):