mirror of
https://github.com/yt-dlp/yt-dlp.git
synced 2024-11-15 13:43:04 +00:00
Compare commits
No commits in common. "230d5c8239d6b6e211f413de26979398c1cabb04" and "f0500bd1e4e3910abd58a1be812ba35fc20049e7" have entirely different histories.
230d5c8239
...
f0500bd1e4
39
.github/workflows/build.yml
vendored
39
.github/workflows/build.yml
vendored
@ -70,16 +70,14 @@ jobs:
|
||||
|
||||
build_unix:
|
||||
needs: create_release
|
||||
runs-on: ubuntu-18.04 # Standalone executable should be built on minimum supported OS
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
sha256_bin: ${{ steps.get_sha.outputs.sha256_bin }}
|
||||
sha512_bin: ${{ steps.get_sha.outputs.sha512_bin }}
|
||||
sha256_tar: ${{ steps.get_sha.outputs.sha256_tar }}
|
||||
sha512_tar: ${{ steps.get_sha.outputs.sha512_tar }}
|
||||
sha256_linux: ${{ steps.get_sha.outputs.sha256_linux }}
|
||||
sha512_linux: ${{ steps.get_sha.outputs.sha512_linux }}
|
||||
sha256_linux_zip: ${{ steps.get_sha.outputs.sha256_linux_zip }}
|
||||
sha512_linux_zip: ${{ steps.get_sha.outputs.sha512_linux_zip }}
|
||||
sha256_unix_zip: ${{ steps.get_sha.outputs.sha256_unix_zip }}
|
||||
sha512_unix_zip: ${{ steps.get_sha.outputs.sha512_unix_zip }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
@ -96,12 +94,9 @@ jobs:
|
||||
run: |
|
||||
python devscripts/update-version.py ${{ needs.create_release.outputs.version_suffix }}
|
||||
python devscripts/make_lazy_extractors.py
|
||||
- name: Build Unix executables
|
||||
- name: Build UNIX executables
|
||||
run: |
|
||||
make all tar
|
||||
python pyinst.py --onedir
|
||||
(cd ./dist/yt-dlp_linux && zip -r ../yt-dlp_linux.zip .)
|
||||
python pyinst.py
|
||||
- name: Get SHA2-SUMS
|
||||
id: get_sha
|
||||
run: |
|
||||
@ -109,10 +104,6 @@ jobs:
|
||||
echo "::set-output name=sha512_bin::$(sha512sum yt-dlp | awk '{print $1}')"
|
||||
echo "::set-output name=sha256_tar::$(sha256sum yt-dlp.tar.gz | awk '{print $1}')"
|
||||
echo "::set-output name=sha512_tar::$(sha512sum yt-dlp.tar.gz | awk '{print $1}')"
|
||||
echo "::set-output name=sha256_linux::$(sha256sum dist/yt-dlp_linux | awk '{print $1}')"
|
||||
echo "::set-output name=sha512_linux::$(sha512sum dist/yt-dlp_linux | awk '{print $1}')"
|
||||
echo "::set-output name=sha256_linux_zip::$(sha256sum dist/yt-dlp_linux.zip | awk '{print $1}')"
|
||||
echo "::set-output name=sha512_linux_zip::$(sha512sum dist/yt-dlp_linux.zip | awk '{print $1}')"
|
||||
|
||||
- name: Upload zip binary
|
||||
uses: actions/upload-release-asset@v1
|
||||
@ -132,24 +123,6 @@ jobs:
|
||||
asset_path: ./yt-dlp.tar.gz
|
||||
asset_name: yt-dlp.tar.gz
|
||||
asset_content_type: application/gzip
|
||||
- name: Upload standalone binary
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ needs.create_release.outputs.upload_url }}
|
||||
asset_path: ./dist/yt-dlp_linux
|
||||
asset_name: yt-dlp_linux
|
||||
asset_content_type: application/octet-stream
|
||||
- name: Upload onedir binary
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ needs.create_release.outputs.upload_url }}
|
||||
asset_path: ./dist/yt-dlp_linux.zip
|
||||
asset_name: yt-dlp_linux.zip
|
||||
asset_content_type: application/zip
|
||||
|
||||
- name: Build and publish on PyPi
|
||||
env:
|
||||
@ -357,8 +330,6 @@ jobs:
|
||||
run: |
|
||||
echo "${{ needs.build_unix.outputs.sha256_bin }} yt-dlp" >> SHA2-256SUMS
|
||||
echo "${{ needs.build_unix.outputs.sha256_tar }} yt-dlp.tar.gz" >> SHA2-256SUMS
|
||||
echo "${{ needs.build_unix.outputs.sha256_linux }} yt-dlp_linux" >> SHA2-256SUMS
|
||||
echo "${{ needs.build_unix.outputs.sha256_linux_zip }} yt-dlp_linux.zip" >> SHA2-256SUMS
|
||||
echo "${{ needs.build_windows.outputs.sha256_win }} yt-dlp.exe" >> SHA2-256SUMS
|
||||
echo "${{ needs.build_windows.outputs.sha256_py2exe }} yt-dlp_min.exe" >> SHA2-256SUMS
|
||||
echo "${{ needs.build_windows32.outputs.sha256_win32 }} yt-dlp_x86.exe" >> SHA2-256SUMS
|
||||
@ -367,8 +338,6 @@ jobs:
|
||||
echo "${{ needs.build_macos.outputs.sha256_macos_zip }} yt-dlp_macos.zip" >> SHA2-256SUMS
|
||||
echo "${{ needs.build_unix.outputs.sha512_bin }} yt-dlp" >> SHA2-512SUMS
|
||||
echo "${{ needs.build_unix.outputs.sha512_tar }} yt-dlp.tar.gz" >> SHA2-512SUMS
|
||||
echo "${{ needs.build_unix.outputs.sha512_linux }} yt-dlp_linux" >> SHA2-512SUMS
|
||||
echo "${{ needs.build_unix.outputs.sha512_linux_zip }} yt-dlp_linux.zip" >> SHA2-512SUMS
|
||||
echo "${{ needs.build_windows.outputs.sha512_win }} yt-dlp.exe" >> SHA2-512SUMS
|
||||
echo "${{ needs.build_windows.outputs.sha512_py2exe }} yt-dlp_min.exe" >> SHA2-512SUMS
|
||||
echo "${{ needs.build_windows32.outputs.sha512_win32 }} yt-dlp_x86.exe" >> SHA2-512SUMS
|
||||
|
@ -248,8 +248,6 @@ File|Description
|
||||
:---|:---
|
||||
[yt-dlp_x86.exe](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_x86.exe)|Windows (Vista SP2+) standalone x86 (32-bit) binary
|
||||
[yt-dlp_min.exe](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_min.exe)|Windows (Win7 SP1+) standalone x64 binary built with `py2exe`<br/> ([Not recommended](#standalone-py2exe-builds-windows))
|
||||
[yt-dlp_linux](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux)|UNIX standalone x64 binary
|
||||
[yt-dlp_linux.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux.zip)|Unpackaged Unix executable (no auto-update)
|
||||
[yt-dlp_win.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_win.zip)|Unpackaged Windows executable (no auto-update)
|
||||
[yt-dlp_macos.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos.zip)|Unpackaged MacOS (10.15+) executable (no auto-update)
|
||||
|
||||
|
@ -5,6 +5,7 @@ import sys
|
||||
|
||||
from PyInstaller.__main__ import run as run_pyinstaller
|
||||
|
||||
|
||||
OS_NAME, ARCH = sys.platform, platform.architecture()[0][:2]
|
||||
|
||||
|
||||
@ -63,7 +64,7 @@ def exe(onedir):
|
||||
"""@returns (name, path)"""
|
||||
name = '_'.join(filter(None, (
|
||||
'yt-dlp',
|
||||
{'win32': '', 'darwin': 'macos'}.get(OS_NAME, OS_NAME),
|
||||
OS_NAME == 'darwin' and 'macos',
|
||||
ARCH == '32' and 'x86'
|
||||
)))
|
||||
return name, ''.join(filter(None, (
|
||||
|
@ -26,7 +26,7 @@ from .postprocessor import (
|
||||
MetadataFromFieldPP,
|
||||
MetadataParserPP,
|
||||
)
|
||||
from .update import Updater
|
||||
from .update import run_update
|
||||
from .utils import (
|
||||
NO_DEFAULT,
|
||||
POSTPROCESS_WHEN,
|
||||
@ -879,23 +879,17 @@ def _real_main(argv=None):
|
||||
return
|
||||
|
||||
with YoutubeDL(ydl_opts) as ydl:
|
||||
pre_process = opts.update_self or opts.rm_cachedir
|
||||
actual_use = all_urls or opts.load_info_filename
|
||||
|
||||
if opts.rm_cachedir:
|
||||
ydl.cache.remove()
|
||||
|
||||
updater = Updater(ydl)
|
||||
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'
|
||||
if opts.update_self and run_update(ydl) and actual_use:
|
||||
# If updater returns True, exit. Required for windows
|
||||
return 100, 'ERROR: The program must exit for the update to complete'
|
||||
|
||||
if not actual_use:
|
||||
if pre_process:
|
||||
if opts.update_self or opts.rm_cachedir:
|
||||
return ydl._download_retcode
|
||||
|
||||
ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
|
||||
|
@ -55,7 +55,7 @@ if compat_os_name == 'nt' and sys.version_info < (3, 8):
|
||||
def compat_realpath(path):
|
||||
while os.path.islink(path):
|
||||
path = os.path.abspath(os.readlink(path))
|
||||
return os.path.realpath(path)
|
||||
return path
|
||||
else:
|
||||
compat_realpath = os.path.realpath
|
||||
|
||||
|
@ -6,19 +6,22 @@ import re
|
||||
|
||||
from .utils import ExtractorError, remove_quotes
|
||||
|
||||
_NAME_RE = r'[a-zA-Z_$][\w$]*'
|
||||
_OPERATORS = {
|
||||
'|': operator.or_,
|
||||
'^': operator.xor,
|
||||
'&': operator.and_,
|
||||
'>>': operator.rshift,
|
||||
'<<': operator.lshift,
|
||||
'-': operator.sub,
|
||||
'+': operator.add,
|
||||
'%': operator.mod,
|
||||
'/': operator.truediv,
|
||||
'*': operator.mul,
|
||||
}
|
||||
_OPERATORS = [
|
||||
('|', operator.or_),
|
||||
('^', operator.xor),
|
||||
('&', operator.and_),
|
||||
('>>', operator.rshift),
|
||||
('<<', operator.lshift),
|
||||
('-', operator.sub),
|
||||
('+', operator.add),
|
||||
('%', operator.mod),
|
||||
('/', operator.truediv),
|
||||
('*', operator.mul),
|
||||
]
|
||||
_ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]
|
||||
_ASSIGN_OPERATORS.append(('=', (lambda cur, right: right)))
|
||||
|
||||
_NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'
|
||||
|
||||
_MATCHING_PARENS = dict(zip('({[', ')}]'))
|
||||
_QUOTES = '\'"'
|
||||
@ -47,11 +50,13 @@ class LocalNameSpace(collections.ChainMap):
|
||||
|
||||
|
||||
class JSInterpreter:
|
||||
__named_object_counter = 0
|
||||
|
||||
def __init__(self, code, objects=None):
|
||||
self.code, self._functions = code, {}
|
||||
self._objects = {} if objects is None else objects
|
||||
if objects is None:
|
||||
objects = {}
|
||||
self.code = code
|
||||
self._functions = {}
|
||||
self._objects = objects
|
||||
self.__named_object_counter = 0
|
||||
|
||||
def _named_object(self, namespace, obj):
|
||||
self.__named_object_counter += 1
|
||||
@ -88,9 +93,9 @@ class JSInterpreter:
|
||||
break
|
||||
yield expr[start:]
|
||||
|
||||
@classmethod
|
||||
def _separate_at_paren(cls, expr, delim):
|
||||
separated = list(cls._separate(expr, delim, 1))
|
||||
@staticmethod
|
||||
def _separate_at_paren(expr, delim):
|
||||
separated = list(JSInterpreter._separate(expr, delim, 1))
|
||||
if len(separated) < 2:
|
||||
raise ExtractorError(f'No terminating paren {delim} in {expr}')
|
||||
return separated[0][1:].strip(), separated[1].strip()
|
||||
@ -99,29 +104,33 @@ class JSInterpreter:
|
||||
if allow_recursion < 0:
|
||||
raise ExtractorError('Recursion limit reached')
|
||||
|
||||
should_abort = False
|
||||
sub_statements = list(self._separate(stmt, ';')) or ['']
|
||||
stmt = sub_statements.pop().lstrip()
|
||||
|
||||
sub_statements = list(self._separate(stmt, ';'))
|
||||
stmt = (sub_statements or ['']).pop()
|
||||
for sub_stmt in sub_statements:
|
||||
ret, should_abort = self.interpret_statement(sub_stmt, local_vars, allow_recursion - 1)
|
||||
if should_abort:
|
||||
return ret, should_abort
|
||||
return ret
|
||||
|
||||
m = re.match(r'(?P<var>var\s)|return(?:\s+|$)', stmt)
|
||||
if not m: # Try interpreting it as an expression
|
||||
expr = stmt
|
||||
elif m.group('var'):
|
||||
expr = stmt[len(m.group(0)):]
|
||||
should_abort = False
|
||||
stmt = stmt.lstrip()
|
||||
stmt_m = re.match(r'var\s', stmt)
|
||||
if stmt_m:
|
||||
expr = stmt[len(stmt_m.group(0)):]
|
||||
else:
|
||||
expr = stmt[len(m.group(0)):]
|
||||
should_abort = True
|
||||
return_m = re.match(r'return(?:\s+|$)', stmt)
|
||||
if return_m:
|
||||
expr = stmt[len(return_m.group(0)):]
|
||||
should_abort = True
|
||||
else:
|
||||
# Try interpreting it as an expression
|
||||
expr = stmt
|
||||
|
||||
return self.interpret_expression(expr, local_vars, allow_recursion), should_abort
|
||||
v = self.interpret_expression(expr, local_vars, allow_recursion)
|
||||
return v, should_abort
|
||||
|
||||
def interpret_expression(self, expr, local_vars, allow_recursion):
|
||||
expr = expr.strip()
|
||||
if not expr:
|
||||
if expr == '': # Empty expression
|
||||
return None
|
||||
|
||||
if expr.startswith('{'):
|
||||
@ -147,8 +156,8 @@ class JSInterpreter:
|
||||
for item in self._separate(inner)])
|
||||
expr = name + outer
|
||||
|
||||
m = re.match(r'(?P<try>try)\s*|(?:(?P<catch>catch)|(?P<for>for)|(?P<switch>switch))\s*\(', expr)
|
||||
if m and m.group('try'):
|
||||
m = re.match(r'try\s*', expr)
|
||||
if m:
|
||||
if expr[m.end()] == '{':
|
||||
try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
|
||||
else:
|
||||
@ -158,19 +167,21 @@ class JSInterpreter:
|
||||
return ret
|
||||
return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
|
||||
|
||||
elif m and m.group('catch'):
|
||||
m = re.match(r'catch\s*\(', expr)
|
||||
if m:
|
||||
# We ignore the catch block
|
||||
_, expr = self._separate_at_paren(expr, '}')
|
||||
return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
|
||||
|
||||
elif m and m.group('for'):
|
||||
m = re.match(r'for\s*\(', expr)
|
||||
if m:
|
||||
constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
|
||||
if remaining.startswith('{'):
|
||||
body, expr = self._separate_at_paren(remaining, '}')
|
||||
else:
|
||||
switch_m = re.match(r'switch\s*\(', remaining) # FIXME
|
||||
if switch_m:
|
||||
switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:], ')')
|
||||
m = re.match(r'switch\s*\(', remaining) # FIXME
|
||||
if m:
|
||||
switch_val, remaining = self._separate_at_paren(remaining[m.end() - 1:], ')')
|
||||
body, expr = self._separate_at_paren(remaining, '}')
|
||||
body = 'switch(%s){%s}' % (switch_val, body)
|
||||
else:
|
||||
@ -195,7 +206,8 @@ class JSInterpreter:
|
||||
f'Premature return in the initialization of a for loop in {constructor!r}')
|
||||
return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
|
||||
|
||||
elif m and m.group('switch'):
|
||||
m = re.match(r'switch\s*\(', expr)
|
||||
if m:
|
||||
switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
|
||||
switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
|
||||
body, expr = self._separate_at_paren(remaining, '}')
|
||||
@ -238,63 +250,55 @@ class JSInterpreter:
|
||||
ret = local_vars[var]
|
||||
expr = expr[:start] + json.dumps(ret) + expr[end:]
|
||||
|
||||
if not expr:
|
||||
return None
|
||||
|
||||
m = re.match(fr'''(?x)
|
||||
(?P<assign>
|
||||
(?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
|
||||
(?P<op>{"|".join(map(re.escape, _OPERATORS))})?
|
||||
=(?P<expr>.*)$
|
||||
)|(?P<return>
|
||||
(?!if|return|true|false|null)(?P<name>{_NAME_RE})$
|
||||
)|(?P<indexing>
|
||||
(?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
|
||||
)|(?P<attribute>
|
||||
(?P<var>{_NAME_RE})(?:\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
|
||||
)|(?P<function>
|
||||
(?P<fname>{_NAME_RE})\((?P<args>[\w$,]*)\)$
|
||||
)''', expr)
|
||||
if m and m.group('assign'):
|
||||
if not m.group('op'):
|
||||
opfunc = lambda curr, right: right
|
||||
else:
|
||||
opfunc = _OPERATORS[m.group('op')]
|
||||
for op, opfunc in _ASSIGN_OPERATORS:
|
||||
m = re.match(rf'''(?x)
|
||||
(?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?
|
||||
\s*{re.escape(op)}
|
||||
(?P<expr>.*)$''', expr)
|
||||
if not m:
|
||||
continue
|
||||
right_val = self.interpret_expression(m.group('expr'), local_vars, allow_recursion)
|
||||
left_val = local_vars.get(m.group('out'))
|
||||
|
||||
if not m.group('index'):
|
||||
local_vars[m.group('out')] = opfunc(left_val, right_val)
|
||||
return local_vars[m.group('out')]
|
||||
elif left_val is None:
|
||||
raise ExtractorError(f'Cannot index undefined variable: {m.group("out")}')
|
||||
if m.groupdict().get('index'):
|
||||
lvar = local_vars[m.group('out')]
|
||||
idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
|
||||
if not isinstance(idx, int):
|
||||
raise ExtractorError(f'List indices must be integers: {idx}')
|
||||
cur = lvar[idx]
|
||||
val = opfunc(cur, right_val)
|
||||
lvar[idx] = val
|
||||
return val
|
||||
else:
|
||||
cur = local_vars.get(m.group('out'))
|
||||
val = opfunc(cur, right_val)
|
||||
local_vars[m.group('out')] = val
|
||||
return val
|
||||
|
||||
idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
|
||||
if not isinstance(idx, int):
|
||||
raise ExtractorError(f'List indices must be integers: {idx}')
|
||||
left_val[idx] = opfunc(left_val[idx], right_val)
|
||||
return left_val[idx]
|
||||
|
||||
elif expr.isdigit():
|
||||
if expr.isdigit():
|
||||
return int(expr)
|
||||
|
||||
elif expr == 'break':
|
||||
if expr == 'break':
|
||||
raise JS_Break()
|
||||
elif expr == 'continue':
|
||||
raise JS_Continue()
|
||||
|
||||
elif m and m.group('return'):
|
||||
return local_vars[m.group('name')]
|
||||
var_m = re.match(
|
||||
r'(?!if|return|true|false|null)(?P<name>%s)$' % _NAME_RE,
|
||||
expr)
|
||||
if var_m:
|
||||
return local_vars[var_m.group('name')]
|
||||
|
||||
with contextlib.suppress(ValueError):
|
||||
return json.loads(expr)
|
||||
|
||||
if m and m.group('indexing'):
|
||||
m = re.match(
|
||||
r'(?P<in>%s)\[(?P<idx>.+)\]$' % _NAME_RE, expr)
|
||||
if m:
|
||||
val = local_vars[m.group('in')]
|
||||
idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
|
||||
return val[idx]
|
||||
|
||||
for op, opfunc in _OPERATORS.items():
|
||||
for op, opfunc in _OPERATORS:
|
||||
separated = list(self._separate(expr, op))
|
||||
if len(separated) < 2:
|
||||
continue
|
||||
@ -310,7 +314,10 @@ class JSInterpreter:
|
||||
raise ExtractorError(f'Premature right-side return of {op} in {expr!r}')
|
||||
return opfunc(left_val or 0, right_val)
|
||||
|
||||
if m and m.group('attribute'):
|
||||
m = re.match(
|
||||
r'(?P<var>%s)(?:\.(?P<member>[^(]+)|\[(?P<member2>[^]]+)\])\s*' % _NAME_RE,
|
||||
expr)
|
||||
if m:
|
||||
variable = m.group('var')
|
||||
member = remove_quotes(m.group('member') or m.group('member2'))
|
||||
arg_str = expr[m.end():]
|
||||
@ -325,6 +332,7 @@ class JSInterpreter:
|
||||
raise ExtractorError(f'{member} {msg}: {expr}')
|
||||
|
||||
def eval_method():
|
||||
nonlocal member
|
||||
if variable == 'String':
|
||||
obj = str
|
||||
elif variable in local_vars:
|
||||
@ -334,8 +342,8 @@ class JSInterpreter:
|
||||
self._objects[variable] = self.extract_object(variable)
|
||||
obj = self._objects[variable]
|
||||
|
||||
# Member access
|
||||
if arg_str is None:
|
||||
# Member access
|
||||
if member == 'length':
|
||||
return len(obj)
|
||||
return obj[member]
|
||||
@ -410,7 +418,9 @@ class JSInterpreter:
|
||||
except ValueError:
|
||||
return -1
|
||||
|
||||
return obj[int(member) if isinstance(obj, list) else member](argvals)
|
||||
if isinstance(obj, list):
|
||||
member = int(member)
|
||||
return obj[member](argvals)
|
||||
|
||||
if remaining:
|
||||
return self.interpret_expression(
|
||||
@ -419,8 +429,9 @@ class JSInterpreter:
|
||||
else:
|
||||
return eval_method()
|
||||
|
||||
elif m and m.group('function'):
|
||||
fname = m.group('fname')
|
||||
m = re.match(r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr)
|
||||
if m:
|
||||
fname = m.group('func')
|
||||
argvals = tuple(
|
||||
int(v) if v.isdigit() else local_vars[v]
|
||||
for v in self._separate(m.group('args')))
|
||||
@ -430,7 +441,8 @@ class JSInterpreter:
|
||||
self._functions[fname] = self.extract_function(fname)
|
||||
return self._functions[fname](argvals)
|
||||
|
||||
raise ExtractorError(f'Unsupported JS expression {expr!r}')
|
||||
if expr:
|
||||
raise ExtractorError('Unsupported JS expression %r' % expr)
|
||||
|
||||
def extract_object(self, objname):
|
||||
_FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
|
||||
@ -459,17 +471,14 @@ class JSInterpreter:
|
||||
""" @returns argnames, code """
|
||||
func_m = re.search(
|
||||
r'''(?x)
|
||||
(?:
|
||||
function\s+%(name)s|
|
||||
[{;,]\s*%(name)s\s*=\s*function|
|
||||
var\s+%(name)s\s*=\s*function
|
||||
)\s*
|
||||
(?:function\s+%s|[{;,]\s*%s\s*=\s*function|var\s+%s\s*=\s*function)\s*
|
||||
\((?P<args>[^)]*)\)\s*
|
||||
(?P<code>{(?:(?!};)[^"]|"([^"]|\\")*")+})''' % {'name': re.escape(funcname)},
|
||||
(?P<code>\{(?:(?!};)[^"]|"([^"]|\\")*")+\})''' % (
|
||||
re.escape(funcname), re.escape(funcname), re.escape(funcname)),
|
||||
self.code)
|
||||
code, _ = self._separate_at_paren(func_m.group('code'), '}') # refine the match
|
||||
if func_m is None:
|
||||
raise ExtractorError(f'Could not find JS function "{funcname}"')
|
||||
raise ExtractorError('Could not find JS function %r' % funcname)
|
||||
return func_m.group('args').split(','), code
|
||||
|
||||
def extract_function(self, funcname):
|
||||
@ -483,9 +492,11 @@ class JSInterpreter:
|
||||
break
|
||||
start, body_start = mobj.span()
|
||||
body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
|
||||
name = self._named_object(local_vars, self.extract_function_from_code(
|
||||
[x.strip() for x in mobj.group('args').split(',')],
|
||||
body, local_vars, *global_stack))
|
||||
name = self._named_object(
|
||||
local_vars,
|
||||
self.extract_function_from_code(
|
||||
[str.strip(x) for x in mobj.group('args').split(',')],
|
||||
body, local_vars, *global_stack))
|
||||
code = code[:start] + name + remaining
|
||||
return self.build_function(argnames, code, local_vars, *global_stack)
|
||||
|
||||
|
317
yt_dlp/update.py
317
yt_dlp/update.py
@ -1,4 +1,3 @@
|
||||
import atexit
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@ -9,11 +8,11 @@ from zipimport import zipimporter
|
||||
|
||||
from .compat import functools # isort: split
|
||||
from .compat import compat_realpath
|
||||
from .utils import Popen, shell_quote, traverse_obj, version_tuple
|
||||
from .utils import Popen, traverse_obj, version_tuple
|
||||
from .version import __version__
|
||||
|
||||
REPOSITORY = 'yt-dlp/yt-dlp'
|
||||
API_URL = f'https://api.github.com/repos/{REPOSITORY}/releases/latest'
|
||||
|
||||
RELEASE_JSON_URL = 'https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest'
|
||||
|
||||
|
||||
@functools.cache
|
||||
@ -45,13 +44,12 @@ _FILE_SUFFIXES = {
|
||||
'py2exe': '_min.exe',
|
||||
'win32_exe': '.exe',
|
||||
'darwin_exe': '_macos',
|
||||
'linux_exe': '_linux',
|
||||
}
|
||||
|
||||
_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()},
|
||||
for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS'}.items()},
|
||||
'source': 'You cannot update when running from source code; Use git to pull the latest changes',
|
||||
'unknown': 'It looks like you installed yt-dlp with a package manager, pip or setup.py; Use that to update',
|
||||
'other': 'It looks like you are using an unofficial build of yt-dlp; Build the executable again',
|
||||
@ -62,187 +60,137 @@ def is_non_updateable():
|
||||
return _NON_UPDATEABLE_REASONS.get(detect_variant(), _NON_UPDATEABLE_REASONS['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:
|
||||
def __init__(self, ydl):
|
||||
self.ydl = ydl
|
||||
|
||||
@functools.cached_property
|
||||
def _new_version_info(self):
|
||||
self.ydl.write_debug(f'Fetching release info: {API_URL}')
|
||||
return json.loads(self.ydl.urlopen(API_URL).read().decode())
|
||||
|
||||
@property
|
||||
def current_version(self):
|
||||
"""Current version"""
|
||||
return __version__
|
||||
|
||||
@property
|
||||
def new_version(self):
|
||||
"""Version of the latest release"""
|
||||
return self._new_version_info['tag_name']
|
||||
|
||||
@property
|
||||
def has_update(self):
|
||||
"""Whether there is an update available"""
|
||||
return version_tuple(__version__) < version_tuple(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=None):
|
||||
name = name or self.release_name
|
||||
url = traverse_obj(self._new_version_info, (
|
||||
'assets', lambda _, v: v['name'] == name, 'browser_download_url'), get_all=False)
|
||||
if not url:
|
||||
raise Exception('Unable to find download URL')
|
||||
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"""
|
||||
label = _FILE_SUFFIXES[detect_variant()]
|
||||
if label and platform.architecture()[0][:2] == '32':
|
||||
label = f'_x86{label}'
|
||||
return f'yt-dlp{label}'
|
||||
|
||||
@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').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)
|
||||
|
||||
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 https://github.com/{REPOSITORY}/releases/latest', True)
|
||||
|
||||
def check_update(self):
|
||||
"""Report whether there is an update available"""
|
||||
try:
|
||||
self.ydl.to_screen(
|
||||
f'Latest version: {self.new_version}, Current version: {self.current_version}')
|
||||
except Exception:
|
||||
return self._report_network_error('obtain version info', delim='; Please try again later or')
|
||||
|
||||
if not self.has_update:
|
||||
return self.ydl.to_screen(f'yt-dlp is up to date ({__version__})')
|
||||
|
||||
if not is_non_updateable():
|
||||
self.ydl.to_screen(f'Current Build Hash {_sha256_file(self.filename)}')
|
||||
return True
|
||||
|
||||
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 version {self.new_version} ...')
|
||||
|
||||
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()
|
||||
except OSError:
|
||||
return self._report_network_error('download latest version')
|
||||
except Exception:
|
||||
return self._report_network_error('fetch updates')
|
||||
|
||||
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)
|
||||
|
||||
try:
|
||||
if old_filename:
|
||||
os.rename(self.filename, old_filename)
|
||||
except OSError:
|
||||
return self._report_error('Unable to move current version')
|
||||
try:
|
||||
if old_filename:
|
||||
os.rename(new_filename, self.filename)
|
||||
except OSError:
|
||||
self._report_error('Unable to overwrite current version')
|
||||
return os.rename(old_filename, self.filename)
|
||||
|
||||
if detect_variant() not in ('win32_exe', 'py2exe'):
|
||||
if old_filename:
|
||||
os.remove(old_filename)
|
||||
else:
|
||||
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)
|
||||
|
||||
self.ydl.to_screen(f'Updated yt-dlp to version {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 hasattr(sys, 'frozen'):
|
||||
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 run_update(ydl):
|
||||
"""Update the program file with the latest version from the repository
|
||||
@returns Whether there was a successfull update (No update = False)
|
||||
"""
|
||||
return Updater(ydl).update()
|
||||
Update the program file with the latest version from the repository
|
||||
Returns whether the program should terminate
|
||||
"""
|
||||
|
||||
def report_error(msg, expected=False):
|
||||
ydl.report_error(msg, tb=False if expected else None)
|
||||
|
||||
def report_unable(action, expected=False):
|
||||
report_error(f'Unable to {action}', expected)
|
||||
|
||||
def report_permission_error(file):
|
||||
report_unable(f'write to {file}; Try running as administrator', True)
|
||||
|
||||
def report_network_error(action, delim=';'):
|
||||
report_unable(f'{action}{delim} Visit https://github.com/yt-dlp/yt-dlp/releases/latest', True)
|
||||
|
||||
def calc_sha256sum(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()
|
||||
|
||||
try:
|
||||
version_info = json.loads(ydl.urlopen(RELEASE_JSON_URL).read().decode())
|
||||
except Exception:
|
||||
return report_network_error('obtain version info', delim='; Please try again later or')
|
||||
|
||||
version_id = version_info['tag_name']
|
||||
ydl.to_screen(f'Latest version: {version_id}, Current version: {__version__}')
|
||||
if version_tuple(__version__) >= version_tuple(version_id):
|
||||
ydl.to_screen(f'yt-dlp is up to date ({__version__})')
|
||||
return
|
||||
|
||||
err = is_non_updateable()
|
||||
if err:
|
||||
return report_error(err, True)
|
||||
|
||||
variant, filename = _get_variant_and_executable_path()
|
||||
filename = compat_realpath(filename) # Absolute path, following symlinks
|
||||
|
||||
label = _FILE_SUFFIXES[variant]
|
||||
if label and platform.architecture()[0][:2] == '32':
|
||||
label = f'_x86{label}'
|
||||
release_name = f'yt-dlp{label}'
|
||||
|
||||
ydl.to_screen(f'Current Build Hash {calc_sha256sum(filename)}')
|
||||
ydl.to_screen(f'Updating to version {version_id} ...')
|
||||
|
||||
def get_file(name, fatal=True):
|
||||
error = report_network_error if fatal else lambda _: None
|
||||
url = traverse_obj(
|
||||
version_info, ('assets', lambda _, v: v['name'] == name, 'browser_download_url'), get_all=False)
|
||||
if not url:
|
||||
return error('fetch updates')
|
||||
try:
|
||||
return ydl.urlopen(url).read()
|
||||
except OSError:
|
||||
return error('download latest version')
|
||||
|
||||
def verify(content):
|
||||
if not content:
|
||||
return False
|
||||
hash_data = get_file('SHA2-256SUMS', fatal=False) or b''
|
||||
expected = dict(ln.split()[::-1] for ln in hash_data.decode().splitlines()).get(release_name)
|
||||
if not expected:
|
||||
ydl.report_warning('no hash information found for the release')
|
||||
elif hashlib.sha256(content).hexdigest() != expected:
|
||||
return report_network_error('verify the new executable')
|
||||
return True
|
||||
|
||||
directory = os.path.dirname(filename)
|
||||
if not os.access(filename, os.W_OK):
|
||||
return report_permission_error(filename)
|
||||
elif not os.access(directory, os.W_OK):
|
||||
return report_permission_error(directory)
|
||||
|
||||
new_filename, old_filename = f'{filename}.new', f'{filename}.old'
|
||||
if variant == 'zip': # Can be replaced in-place
|
||||
new_filename, old_filename = filename, None
|
||||
|
||||
try:
|
||||
if os.path.exists(old_filename or ''):
|
||||
os.remove(old_filename)
|
||||
except OSError:
|
||||
return report_unable('remove the old version')
|
||||
|
||||
newcontent = get_file(release_name)
|
||||
if not verify(newcontent):
|
||||
return
|
||||
try:
|
||||
with open(new_filename, 'wb') as outf:
|
||||
outf.write(newcontent)
|
||||
except OSError:
|
||||
return report_permission_error(new_filename)
|
||||
|
||||
try:
|
||||
if old_filename:
|
||||
os.rename(filename, old_filename)
|
||||
except OSError:
|
||||
return report_unable('move current version')
|
||||
try:
|
||||
if old_filename:
|
||||
os.rename(new_filename, filename)
|
||||
except OSError:
|
||||
report_unable('overwrite current version')
|
||||
os.rename(old_filename, filename)
|
||||
return
|
||||
|
||||
if variant not in ('win32_exe', 'py2exe'):
|
||||
if old_filename:
|
||||
os.remove(old_filename)
|
||||
ydl.to_screen(f'Updated yt-dlp to version {version_id}; Restart yt-dlp to use the new version')
|
||||
return
|
||||
|
||||
try:
|
||||
# Continues to run in the background
|
||||
Popen(f'ping 127.0.0.1 -n 5 -w 1000 & del /F "{old_filename}"',
|
||||
shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
ydl.to_screen(f'Updated yt-dlp to version {version_id}')
|
||||
return True # Exit app
|
||||
except OSError:
|
||||
report_unable('delete the old version')
|
||||
|
||||
|
||||
# Deprecated
|
||||
def update_self(to_screen, verbose, opener):
|
||||
import traceback
|
||||
|
||||
from .utils import write_string
|
||||
|
||||
write_string(
|
||||
@ -254,10 +202,12 @@ def update_self(to_screen, verbose, opener):
|
||||
class FakeYDL():
|
||||
to_screen = printfn
|
||||
|
||||
def report_warning(self, msg, *args, **kwargs):
|
||||
@staticmethod
|
||||
def report_warning(msg, *args, **kwargs):
|
||||
return printfn(f'WARNING: {msg}', *args, **kwargs)
|
||||
|
||||
def report_error(self, msg, tb=None):
|
||||
@staticmethod
|
||||
def report_error(msg, tb=None):
|
||||
printfn(f'ERROR: {msg}')
|
||||
if not verbose:
|
||||
return
|
||||
@ -274,9 +224,6 @@ def update_self(to_screen, verbose, opener):
|
||||
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)
|
||||
|
||||
|
@ -991,10 +991,9 @@ def make_HTTPS_handler(params, **kwargs):
|
||||
|
||||
|
||||
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://github.com/yt-dlp/yt-dlp/issues?q= , '
|
||||
'filling out the appropriate issue template. '
|
||||
'Confirm you are on the latest version using yt-dlp -U')
|
||||
|
||||
before = before.rstrip()
|
||||
if not before or before.endswith(('.', '!', '?')):
|
||||
|
Loading…
Reference in New Issue
Block a user