You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3278 lines
98 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import unicode_literals
  4. import base64
  5. import binascii
  6. import calendar
  7. import codecs
  8. import contextlib
  9. import ctypes
  10. import datetime
  11. import email.utils
  12. import errno
  13. import functools
  14. import gzip
  15. import io
  16. import itertools
  17. import json
  18. import locale
  19. import math
  20. import operator
  21. import os
  22. import pipes
  23. import platform
  24. import re
  25. import socket
  26. import ssl
  27. import subprocess
  28. import sys
  29. import tempfile
  30. import traceback
  31. import xml.etree.ElementTree
  32. import zlib
  33. from .compat import (
  34. compat_HTMLParser,
  35. compat_basestring,
  36. compat_chr,
  37. compat_etree_fromstring,
  38. compat_html_entities,
  39. compat_html_entities_html5,
  40. compat_http_client,
  41. compat_kwargs,
  42. compat_os_name,
  43. compat_parse_qs,
  44. compat_shlex_quote,
  45. compat_socket_create_connection,
  46. compat_str,
  47. compat_struct_pack,
  48. compat_struct_unpack,
  49. compat_urllib_error,
  50. compat_urllib_parse,
  51. compat_urllib_parse_urlencode,
  52. compat_urllib_parse_urlparse,
  53. compat_urllib_parse_unquote_plus,
  54. compat_urllib_request,
  55. compat_urlparse,
  56. compat_xpath,
  57. )
  58. from .socks import (
  59. ProxyType,
  60. sockssocket,
  61. )
  62. def register_socks_protocols():
  63. # "Register" SOCKS protocols
  64. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  65. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  66. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  67. if scheme not in compat_urlparse.uses_netloc:
  68. compat_urlparse.uses_netloc.append(scheme)
  69. # This is not clearly defined otherwise
  70. compiled_regex_type = type(re.compile(''))
  71. std_headers = {
  72. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)',
  73. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  74. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  75. 'Accept-Encoding': 'gzip, deflate',
  76. 'Accept-Language': 'en-us,en;q=0.5',
  77. }
  78. USER_AGENTS = {
  79. 'Safari': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
  80. }
  81. NO_DEFAULT = object()
  82. ENGLISH_MONTH_NAMES = [
  83. 'January', 'February', 'March', 'April', 'May', 'June',
  84. 'July', 'August', 'September', 'October', 'November', 'December']
  85. MONTH_NAMES = {
  86. 'en': ENGLISH_MONTH_NAMES,
  87. 'fr': [
  88. 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
  89. 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
  90. }
  91. KNOWN_EXTENSIONS = (
  92. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  93. 'flv', 'f4v', 'f4a', 'f4b',
  94. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  95. 'mkv', 'mka', 'mk3d',
  96. 'avi', 'divx',
  97. 'mov',
  98. 'asf', 'wmv', 'wma',
  99. '3gp', '3g2',
  100. 'mp3',
  101. 'flac',
  102. 'ape',
  103. 'wav',
  104. 'f4f', 'f4m', 'm3u8', 'smil')
  105. # needed for sanitizing filenames in restricted mode
  106. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  107. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUYP', ['ss'],
  108. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuypy')))
  109. DATE_FORMATS = (
  110. '%d %B %Y',
  111. '%d %b %Y',
  112. '%B %d %Y',
  113. '%B %dst %Y',
  114. '%B %dnd %Y',
  115. '%B %dth %Y',
  116. '%b %d %Y',
  117. '%b %dst %Y',
  118. '%b %dnd %Y',
  119. '%b %dth %Y',
  120. '%b %dst %Y %I:%M',
  121. '%b %dnd %Y %I:%M',
  122. '%b %dth %Y %I:%M',
  123. '%Y %m %d',
  124. '%Y-%m-%d',
  125. '%Y/%m/%d',
  126. '%Y/%m/%d %H:%M',
  127. '%Y/%m/%d %H:%M:%S',
  128. '%Y-%m-%d %H:%M',
  129. '%Y-%m-%d %H:%M:%S',
  130. '%Y-%m-%d %H:%M:%S.%f',
  131. '%d.%m.%Y %H:%M',
  132. '%d.%m.%Y %H.%M',
  133. '%Y-%m-%dT%H:%M:%SZ',
  134. '%Y-%m-%dT%H:%M:%S.%fZ',
  135. '%Y-%m-%dT%H:%M:%S.%f0Z',
  136. '%Y-%m-%dT%H:%M:%S',
  137. '%Y-%m-%dT%H:%M:%S.%f',
  138. '%Y-%m-%dT%H:%M',
  139. '%b %d %Y at %H:%M',
  140. '%b %d %Y at %H:%M:%S',
  141. )
  142. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  143. DATE_FORMATS_DAY_FIRST.extend([
  144. '%d-%m-%Y',
  145. '%d.%m.%Y',
  146. '%d.%m.%y',
  147. '%d/%m/%Y',
  148. '%d/%m/%y',
  149. '%d/%m/%Y %H:%M:%S',
  150. ])
  151. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  152. DATE_FORMATS_MONTH_FIRST.extend([
  153. '%m-%d-%Y',
  154. '%m.%d.%Y',
  155. '%m/%d/%Y',
  156. '%m/%d/%y',
  157. '%m/%d/%Y %H:%M:%S',
  158. ])
  159. PACKED_CODES_RE = r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
  160. def preferredencoding():
  161. """Get preferred encoding.
  162. Returns the best encoding scheme for the system, based on
  163. locale.getpreferredencoding() and some further tweaks.
  164. """
  165. try:
  166. pref = locale.getpreferredencoding()
  167. 'TEST'.encode(pref)
  168. except Exception:
  169. pref = 'UTF-8'
  170. return pref
  171. def write_json_file(obj, fn):
  172. """ Encode obj as JSON and write it to fn, atomically if possible """
  173. fn = encodeFilename(fn)
  174. if sys.version_info < (3, 0) and sys.platform != 'win32':
  175. encoding = get_filesystem_encoding()
  176. # os.path.basename returns a bytes object, but NamedTemporaryFile
  177. # will fail if the filename contains non ascii characters unless we
  178. # use a unicode object
  179. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  180. # the same for os.path.dirname
  181. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  182. else:
  183. path_basename = os.path.basename
  184. path_dirname = os.path.dirname
  185. args = {
  186. 'suffix': '.tmp',
  187. 'prefix': path_basename(fn) + '.',
  188. 'dir': path_dirname(fn),
  189. 'delete': False,
  190. }
  191. # In Python 2.x, json.dump expects a bytestream.
  192. # In Python 3.x, it writes to a character stream
  193. if sys.version_info < (3, 0):
  194. args['mode'] = 'wb'
  195. else:
  196. args.update({
  197. 'mode': 'w',
  198. 'encoding': 'utf-8',
  199. })
  200. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  201. try:
  202. with tf:
  203. json.dump(obj, tf)
  204. if sys.platform == 'win32':
  205. # Need to remove existing file on Windows, else os.rename raises
  206. # WindowsError or FileExistsError.
  207. try:
  208. os.unlink(fn)
  209. except OSError:
  210. pass
  211. os.rename(tf.name, fn)
  212. except Exception:
  213. try:
  214. os.remove(tf.name)
  215. except OSError:
  216. pass
  217. raise
  218. if sys.version_info >= (2, 7):
  219. def find_xpath_attr(node, xpath, key, val=None):
  220. """ Find the xpath xpath[@key=val] """
  221. assert re.match(r'^[a-zA-Z_-]+$', key)
  222. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  223. return node.find(expr)
  224. else:
  225. def find_xpath_attr(node, xpath, key, val=None):
  226. for f in node.findall(compat_xpath(xpath)):
  227. if key not in f.attrib:
  228. continue
  229. if val is None or f.attrib.get(key) == val:
  230. return f
  231. return None
  232. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  233. # the namespace parameter
  234. def xpath_with_ns(path, ns_map):
  235. components = [c.split(':') for c in path.split('/')]
  236. replaced = []
  237. for c in components:
  238. if len(c) == 1:
  239. replaced.append(c[0])
  240. else:
  241. ns, tag = c
  242. replaced.append('{%s}%s' % (ns_map[ns], tag))
  243. return '/'.join(replaced)
  244. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  245. def _find_xpath(xpath):
  246. return node.find(compat_xpath(xpath))
  247. if isinstance(xpath, (str, compat_str)):
  248. n = _find_xpath(xpath)
  249. else:
  250. for xp in xpath:
  251. n = _find_xpath(xp)
  252. if n is not None:
  253. break
  254. if n is None:
  255. if default is not NO_DEFAULT:
  256. return default
  257. elif fatal:
  258. name = xpath if name is None else name
  259. raise ExtractorError('Could not find XML element %s' % name)
  260. else:
  261. return None
  262. return n
  263. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  264. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  265. if n is None or n == default:
  266. return n
  267. if n.text is None:
  268. if default is not NO_DEFAULT:
  269. return default
  270. elif fatal:
  271. name = xpath if name is None else name
  272. raise ExtractorError('Could not find XML element\'s text %s' % name)
  273. else:
  274. return None
  275. return n.text
  276. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  277. n = find_xpath_attr(node, xpath, key)
  278. if n is None:
  279. if default is not NO_DEFAULT:
  280. return default
  281. elif fatal:
  282. name = '%s[@%s]' % (xpath, key) if name is None else name
  283. raise ExtractorError('Could not find XML attribute %s' % name)
  284. else:
  285. return None
  286. return n.attrib[key]
  287. def get_element_by_id(id, html):
  288. """Return the content of the tag with the specified ID in the passed HTML document"""
  289. return get_element_by_attribute('id', id, html)
  290. def get_element_by_class(class_name, html):
  291. return get_element_by_attribute(
  292. 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
  293. html, escape_value=False)
  294. def get_element_by_attribute(attribute, value, html, escape_value=True):
  295. """Return the content of the tag with the specified attribute in the passed HTML document"""
  296. value = re.escape(value) if escape_value else value
  297. m = re.search(r'''(?xs)
  298. <([a-zA-Z0-9:._-]+)
  299. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
  300. \s+%s=['"]?%s['"]?
  301. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
  302. \s*>
  303. (?P<content>.*?)
  304. </\1>
  305. ''' % (re.escape(attribute), value), html)
  306. if not m:
  307. return None
  308. res = m.group('content')
  309. if res.startswith('"') or res.startswith("'"):
  310. res = res[1:-1]
  311. return unescapeHTML(res)
  312. class HTMLAttributeParser(compat_HTMLParser):
  313. """Trivial HTML parser to gather the attributes for a single element"""
  314. def __init__(self):
  315. self.attrs = {}
  316. compat_HTMLParser.__init__(self)
  317. def handle_starttag(self, tag, attrs):
  318. self.attrs = dict(attrs)
  319. def extract_attributes(html_element):
  320. """Given a string for an HTML element such as
  321. <el
  322. a="foo" B="bar" c="&98;az" d=boz
  323. empty= noval entity="&amp;"
  324. sq='"' dq="'"
  325. >
  326. Decode and return a dictionary of attributes.
  327. {
  328. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  329. 'empty': '', 'noval': None, 'entity': '&',
  330. 'sq': '"', 'dq': '\''
  331. }.
  332. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  333. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  334. """
  335. parser = HTMLAttributeParser()
  336. parser.feed(html_element)
  337. parser.close()
  338. return parser.attrs
  339. def clean_html(html):
  340. """Clean an HTML snippet into a readable string"""
  341. if html is None: # Convenience for sanitizing descriptions etc.
  342. return html
  343. # Newline vs <br />
  344. html = html.replace('\n', ' ')
  345. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  346. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  347. # Strip html tags
  348. html = re.sub('<.*?>', '', html)
  349. # Replace html entities
  350. html = unescapeHTML(html)
  351. return html.strip()
  352. def sanitize_open(filename, open_mode):
  353. """Try to open the given filename, and slightly tweak it if this fails.
  354. Attempts to open the given filename. If this fails, it tries to change
  355. the filename slightly, step by step, until it's either able to open it
  356. or it fails and raises a final exception, like the standard open()
  357. function.
  358. It returns the tuple (stream, definitive_file_name).
  359. """
  360. try:
  361. if filename == '-':
  362. if sys.platform == 'win32':
  363. import msvcrt
  364. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  365. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  366. stream = open(encodeFilename(filename), open_mode)
  367. return (stream, filename)
  368. except (IOError, OSError) as err:
  369. if err.errno in (errno.EACCES,):
  370. raise
  371. # In case of error, try to remove win32 forbidden chars
  372. alt_filename = sanitize_path(filename)
  373. if alt_filename == filename:
  374. raise
  375. else:
  376. # An exception here should be caught in the caller
  377. stream = open(encodeFilename(alt_filename), open_mode)
  378. return (stream, alt_filename)
  379. def timeconvert(timestr):
  380. """Convert RFC 2822 defined time string into system timestamp"""
  381. timestamp = None
  382. timetuple = email.utils.parsedate_tz(timestr)
  383. if timetuple is not None:
  384. timestamp = email.utils.mktime_tz(timetuple)
  385. return timestamp
  386. def sanitize_filename(s, restricted=False, is_id=False):
  387. """Sanitizes a string so it could be used as part of a filename.
  388. If restricted is set, use a stricter subset of allowed characters.
  389. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  390. """
  391. def replace_insane(char):
  392. if restricted and char in ACCENT_CHARS:
  393. return ACCENT_CHARS[char]
  394. if char == '?' or ord(char) < 32 or ord(char) == 127:
  395. return ''
  396. elif char == '"':
  397. return '' if restricted else '\''
  398. elif char == ':':
  399. return '_-' if restricted else ' -'
  400. elif char in '\\/|*<>':
  401. return '_'
  402. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  403. return '_'
  404. if restricted and ord(char) > 127:
  405. return '_'
  406. return char
  407. # Handle timestamps
  408. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  409. result = ''.join(map(replace_insane, s))
  410. if not is_id:
  411. while '__' in result:
  412. result = result.replace('__', '_')
  413. result = result.strip('_')
  414. # Common case of "Foreign band name - English song title"
  415. if restricted and result.startswith('-_'):
  416. result = result[2:]
  417. if result.startswith('-'):
  418. result = '_' + result[len('-'):]
  419. result = result.lstrip('.')
  420. if not result:
  421. result = '_'
  422. return result
  423. def sanitize_path(s):
  424. """Sanitizes and normalizes path on Windows"""
  425. if sys.platform != 'win32':
  426. return s
  427. drive_or_unc, _ = os.path.splitdrive(s)
  428. if sys.version_info < (2, 7) and not drive_or_unc:
  429. drive_or_unc, _ = os.path.splitunc(s)
  430. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  431. if drive_or_unc:
  432. norm_path.pop(0)
  433. sanitized_path = [
  434. path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
  435. for path_part in norm_path]
  436. if drive_or_unc:
  437. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  438. return os.path.join(*sanitized_path)
  439. # Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
  440. # unwanted failures due to missing protocol
  441. def sanitize_url(url):
  442. return 'http:%s' % url if url.startswith('//') else url
  443. def sanitized_Request(url, *args, **kwargs):
  444. return compat_urllib_request.Request(sanitize_url(url), *args, **kwargs)
  445. def orderedSet(iterable):
  446. """ Remove all duplicates from the input iterable """
  447. res = []
  448. for el in iterable:
  449. if el not in res:
  450. res.append(el)
  451. return res
  452. def _htmlentity_transform(entity_with_semicolon):
  453. """Transforms an HTML entity to a character."""
  454. entity = entity_with_semicolon[:-1]
  455. # Known non-numeric HTML entity
  456. if entity in compat_html_entities.name2codepoint:
  457. return compat_chr(compat_html_entities.name2codepoint[entity])
  458. # TODO: HTML5 allows entities without a semicolon. For example,
  459. # '&Eacuteric' should be decoded as 'Éric'.
  460. if entity_with_semicolon in compat_html_entities_html5:
  461. return compat_html_entities_html5[entity_with_semicolon]
  462. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  463. if mobj is not None:
  464. numstr = mobj.group(1)
  465. if numstr.startswith('x'):
  466. base = 16
  467. numstr = '0%s' % numstr
  468. else:
  469. base = 10
  470. # See https://github.com/rg3/youtube-dl/issues/7518
  471. try:
  472. return compat_chr(int(numstr, base))
  473. except ValueError:
  474. pass
  475. # Unknown entity in name, return its literal representation
  476. return '&%s;' % entity
  477. def unescapeHTML(s):
  478. if s is None:
  479. return None
  480. assert type(s) == compat_str
  481. return re.sub(
  482. r'&([^;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  483. def get_subprocess_encoding():
  484. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  485. # For subprocess calls, encode with locale encoding
  486. # Refer to http://stackoverflow.com/a/9951851/35070
  487. encoding = preferredencoding()
  488. else:
  489. encoding = sys.getfilesystemencoding()
  490. if encoding is None:
  491. encoding = 'utf-8'
  492. return encoding
  493. def encodeFilename(s, for_subprocess=False):
  494. """
  495. @param s The name of the file
  496. """
  497. assert type(s) == compat_str
  498. # Python 3 has a Unicode API
  499. if sys.version_info >= (3, 0):
  500. return s
  501. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  502. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  503. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  504. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  505. return s
  506. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  507. if sys.platform.startswith('java'):
  508. return s
  509. return s.encode(get_subprocess_encoding(), 'ignore')
  510. def decodeFilename(b, for_subprocess=False):
  511. if sys.version_info >= (3, 0):
  512. return b
  513. if not isinstance(b, bytes):
  514. return b
  515. return b.decode(get_subprocess_encoding(), 'ignore')
  516. def encodeArgument(s):
  517. if not isinstance(s, compat_str):
  518. # Legacy code that uses byte strings
  519. # Uncomment the following line after fixing all post processors
  520. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  521. s = s.decode('ascii')
  522. return encodeFilename(s, True)
  523. def decodeArgument(b):
  524. return decodeFilename(b, True)
  525. def decodeOption(optval):
  526. if optval is None:
  527. return optval
  528. if isinstance(optval, bytes):
  529. optval = optval.decode(preferredencoding())
  530. assert isinstance(optval, compat_str)
  531. return optval
  532. def formatSeconds(secs):
  533. if secs > 3600:
  534. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  535. elif secs > 60:
  536. return '%d:%02d' % (secs // 60, secs % 60)
  537. else:
  538. return '%d' % secs
  539. def make_HTTPS_handler(params, **kwargs):
  540. opts_no_check_certificate = params.get('nocheckcertificate', False)
  541. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  542. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  543. if opts_no_check_certificate:
  544. context.check_hostname = False
  545. context.verify_mode = ssl.CERT_NONE
  546. try:
  547. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  548. except TypeError:
  549. # Python 2.7.8
  550. # (create_default_context present but HTTPSHandler has no context=)
  551. pass
  552. if sys.version_info < (3, 2):
  553. return YoutubeDLHTTPSHandler(params, **kwargs)
  554. else: # Python < 3.4
  555. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  556. context.verify_mode = (ssl.CERT_NONE
  557. if opts_no_check_certificate
  558. else ssl.CERT_REQUIRED)
  559. context.set_default_verify_paths()
  560. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  561. def bug_reports_message():
  562. if ytdl_is_updateable():
  563. update_cmd = 'type youtube-dl -U to update'
  564. else:
  565. update_cmd = 'see https://yt-dl.org/update on how to update'
  566. msg = '; please report this issue on https://yt-dl.org/bug .'
  567. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  568. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  569. return msg
  570. class ExtractorError(Exception):
  571. """Error during info extraction."""
  572. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  573. """ tb, if given, is the original traceback (so that it can be printed out).
  574. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  575. """
  576. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  577. expected = True
  578. if video_id is not None:
  579. msg = video_id + ': ' + msg
  580. if cause:
  581. msg += ' (caused by %r)' % cause
  582. if not expected:
  583. msg += bug_reports_message()
  584. super(ExtractorError, self).__init__(msg)
  585. self.traceback = tb
  586. self.exc_info = sys.exc_info() # preserve original exception
  587. self.cause = cause
  588. self.video_id = video_id
  589. def format_traceback(self):
  590. if self.traceback is None:
  591. return None
  592. return ''.join(traceback.format_tb(self.traceback))
  593. class UnsupportedError(ExtractorError):
  594. def __init__(self, url):
  595. super(UnsupportedError, self).__init__(
  596. 'Unsupported URL: %s' % url, expected=True)
  597. self.url = url
  598. class RegexNotFoundError(ExtractorError):
  599. """Error when a regex didn't match"""
  600. pass
  601. class DownloadError(Exception):
  602. """Download Error exception.
  603. This exception may be thrown by FileDownloader objects if they are not
  604. configured to continue on errors. They will contain the appropriate
  605. error message.
  606. """
  607. def __init__(self, msg, exc_info=None):
  608. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  609. super(DownloadError, self).__init__(msg)
  610. self.exc_info = exc_info
  611. class SameFileError(Exception):
  612. """Same File exception.
  613. This exception will be thrown by FileDownloader objects if they detect
  614. multiple files would have to be downloaded to the same file on disk.
  615. """
  616. pass
  617. class PostProcessingError(Exception):
  618. """Post Processing exception.
  619. This exception may be raised by PostProcessor's .run() method to
  620. indicate an error in the postprocessing task.
  621. """
  622. def __init__(self, msg):
  623. self.msg = msg
  624. class MaxDownloadsReached(Exception):
  625. """ --max-downloads limit has been reached. """
  626. pass
  627. class UnavailableVideoError(Exception):
  628. """Unavailable Format exception.
  629. This exception will be thrown when a video is requested
  630. in a format that is not available for that video.
  631. """
  632. pass
  633. class ContentTooShortError(Exception):
  634. """Content Too Short exception.
  635. This exception may be raised by FileDownloader objects when a file they
  636. download is too small for what the server announced first, indicating
  637. the connection was probably interrupted.
  638. """
  639. def __init__(self, downloaded, expected):
  640. # Both in bytes
  641. self.downloaded = downloaded
  642. self.expected = expected
  643. class XAttrMetadataError(Exception):
  644. def __init__(self, code=None, msg='Unknown error'):
  645. super(XAttrMetadataError, self).__init__(msg)
  646. self.code = code
  647. self.msg = msg
  648. # Parsing code and msg
  649. if (self.code in (errno.ENOSPC, errno.EDQUOT) or
  650. 'No space left' in self.msg or 'Disk quota excedded' in self.msg):
  651. self.reason = 'NO_SPACE'
  652. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  653. self.reason = 'VALUE_TOO_LONG'
  654. else:
  655. self.reason = 'NOT_SUPPORTED'
  656. class XAttrUnavailableError(Exception):
  657. pass
  658. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  659. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  660. # expected HTTP responses to meet HTTP/1.0 or later (see also
  661. # https://github.com/rg3/youtube-dl/issues/6727)
  662. if sys.version_info < (3, 0):
  663. kwargs[b'strict'] = True
  664. hc = http_class(*args, **kwargs)
  665. source_address = ydl_handler._params.get('source_address')
  666. if source_address is not None:
  667. sa = (source_address, 0)
  668. if hasattr(hc, 'source_address'): # Python 2.7+
  669. hc.source_address = sa
  670. else: # Python 2.6
  671. def _hc_connect(self, *args, **kwargs):
  672. sock = compat_socket_create_connection(
  673. (self.host, self.port), self.timeout, sa)
  674. if is_https:
  675. self.sock = ssl.wrap_socket(
  676. sock, self.key_file, self.cert_file,
  677. ssl_version=ssl.PROTOCOL_TLSv1)
  678. else:
  679. self.sock = sock
  680. hc.connect = functools.partial(_hc_connect, hc)
  681. return hc
  682. def handle_youtubedl_headers(headers):
  683. filtered_headers = headers
  684. if 'Youtubedl-no-compression' in filtered_headers:
  685. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  686. del filtered_headers['Youtubedl-no-compression']
  687. return filtered_headers
  688. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  689. """Handler for HTTP requests and responses.
  690. This class, when installed with an OpenerDirector, automatically adds
  691. the standard headers to every HTTP request and handles gzipped and
  692. deflated responses from web servers. If compression is to be avoided in
  693. a particular request, the original request in the program code only has
  694. to include the HTTP header "Youtubedl-no-compression", which will be
  695. removed before making the real request.
  696. Part of this code was copied from:
  697. http://techknack.net/python-urllib2-handlers/
  698. Andrew Rowls, the author of that code, agreed to release it to the
  699. public domain.
  700. """
  701. def __init__(self, params, *args, **kwargs):
  702. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  703. self._params = params
  704. def http_open(self, req):
  705. conn_class = compat_http_client.HTTPConnection
  706. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  707. if socks_proxy:
  708. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  709. del req.headers['Ytdl-socks-proxy']
  710. return self.do_open(functools.partial(
  711. _create_http_connection, self, conn_class, False),
  712. req)
  713. @staticmethod
  714. def deflate(data):
  715. try:
  716. return zlib.decompress(data, -zlib.MAX_WBITS)
  717. except zlib.error:
  718. return zlib.decompress(data)
  719. @staticmethod
  720. def addinfourl_wrapper(stream, headers, url, code):
  721. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  722. return compat_urllib_request.addinfourl(stream, headers, url, code)
  723. ret = compat_urllib_request.addinfourl(stream, headers, url)
  724. ret.code = code
  725. return ret
  726. def http_request(self, req):
  727. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  728. # always respected by websites, some tend to give out URLs with non percent-encoded
  729. # non-ASCII characters (see telemb.py, ard.py [#3412])
  730. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  731. # To work around aforementioned issue we will replace request's original URL with
  732. # percent-encoded one
  733. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  734. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  735. url = req.get_full_url()
  736. url_escaped = escape_url(url)
  737. # Substitute URL if any change after escaping
  738. if url != url_escaped:
  739. req = update_Request(req, url=url_escaped)
  740. for h, v in std_headers.items():
  741. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  742. # The dict keys are capitalized because of this bug by urllib
  743. if h.capitalize() not in req.headers:
  744. req.add_header(h, v)
  745. req.headers = handle_youtubedl_headers(req.headers)
  746. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  747. # Python 2.6 is brain-dead when it comes to fragments
  748. req._Request__original = req._Request__original.partition('#')[0]
  749. req._Request__r_type = req._Request__r_type.partition('#')[0]
  750. return req
  751. def http_response(self, req, resp):
  752. old_resp = resp
  753. # gzip
  754. if resp.headers.get('Content-encoding', '') == 'gzip':
  755. content = resp.read()
  756. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  757. try:
  758. uncompressed = io.BytesIO(gz.read())
  759. except IOError as original_ioerror:
  760. # There may be junk add the end of the file
  761. # See http://stackoverflow.com/q/4928560/35070 for details
  762. for i in range(1, 1024):
  763. try:
  764. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  765. uncompressed = io.BytesIO(gz.read())
  766. except IOError:
  767. continue
  768. break
  769. else:
  770. raise original_ioerror
  771. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  772. resp.msg = old_resp.msg
  773. del resp.headers['Content-encoding']
  774. # deflate
  775. if resp.headers.get('Content-encoding', '') == 'deflate':
  776. gz = io.BytesIO(self.deflate(resp.read()))
  777. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  778. resp.msg = old_resp.msg
  779. del resp.headers['Content-encoding']
  780. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  781. # https://github.com/rg3/youtube-dl/issues/6457).
  782. if 300 <= resp.code < 400:
  783. location = resp.headers.get('Location')
  784. if location:
  785. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  786. if sys.version_info >= (3, 0):
  787. location = location.encode('iso-8859-1').decode('utf-8')
  788. else:
  789. location = location.decode('utf-8')
  790. location_escaped = escape_url(location)
  791. if location != location_escaped:
  792. del resp.headers['Location']
  793. if sys.version_info < (3, 0):
  794. location_escaped = location_escaped.encode('utf-8')
  795. resp.headers['Location'] = location_escaped
  796. return resp
  797. https_request = http_request
  798. https_response = http_response
  799. def make_socks_conn_class(base_class, socks_proxy):
  800. assert issubclass(base_class, (
  801. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  802. url_components = compat_urlparse.urlparse(socks_proxy)
  803. if url_components.scheme.lower() == 'socks5':
  804. socks_type = ProxyType.SOCKS5
  805. elif url_components.scheme.lower() in ('socks', 'socks4'):
  806. socks_type = ProxyType.SOCKS4
  807. elif url_components.scheme.lower() == 'socks4a':
  808. socks_type = ProxyType.SOCKS4A
  809. def unquote_if_non_empty(s):
  810. if not s:
  811. return s
  812. return compat_urllib_parse_unquote_plus(s)
  813. proxy_args = (
  814. socks_type,
  815. url_components.hostname, url_components.port or 1080,
  816. True, # Remote DNS
  817. unquote_if_non_empty(url_components.username),
  818. unquote_if_non_empty(url_components.password),
  819. )
  820. class SocksConnection(base_class):
  821. def connect(self):
  822. self.sock = sockssocket()
  823. self.sock.setproxy(*proxy_args)
  824. if type(self.timeout) in (int, float):
  825. self.sock.settimeout(self.timeout)
  826. self.sock.connect((self.host, self.port))
  827. if isinstance(self, compat_http_client.HTTPSConnection):
  828. if hasattr(self, '_context'): # Python > 2.6
  829. self.sock = self._context.wrap_socket(
  830. self.sock, server_hostname=self.host)
  831. else:
  832. self.sock = ssl.wrap_socket(self.sock)
  833. return SocksConnection
  834. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  835. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  836. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  837. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  838. self._params = params
  839. def https_open(self, req):
  840. kwargs = {}
  841. conn_class = self._https_conn_class
  842. if hasattr(self, '_context'): # python > 2.6
  843. kwargs['context'] = self._context
  844. if hasattr(self, '_check_hostname'): # python 3.x
  845. kwargs['check_hostname'] = self._check_hostname
  846. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  847. if socks_proxy:
  848. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  849. del req.headers['Ytdl-socks-proxy']
  850. return self.do_open(functools.partial(
  851. _create_http_connection, self, conn_class, True),
  852. req, **kwargs)
  853. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  854. def __init__(self, cookiejar=None):
  855. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  856. def http_response(self, request, response):
  857. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  858. # characters in Set-Cookie HTTP header of last response (see
  859. # https://github.com/rg3/youtube-dl/issues/6769).
  860. # In order to at least prevent crashing we will percent encode Set-Cookie
  861. # header before HTTPCookieProcessor starts processing it.
  862. # if sys.version_info < (3, 0) and response.headers:
  863. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  864. # set_cookie = response.headers.get(set_cookie_header)
  865. # if set_cookie:
  866. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  867. # if set_cookie != set_cookie_escaped:
  868. # del response.headers[set_cookie_header]
  869. # response.headers[set_cookie_header] = set_cookie_escaped
  870. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  871. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  872. https_response = http_response
  873. def extract_timezone(date_str):
  874. m = re.search(
  875. r'^.{8,}?(?P<tz>Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  876. date_str)
  877. if not m:
  878. timezone = datetime.timedelta()
  879. else:
  880. date_str = date_str[:-len(m.group('tz'))]
  881. if not m.group('sign'):
  882. timezone = datetime.timedelta()
  883. else:
  884. sign = 1 if m.group('sign') == '+' else -1
  885. timezone = datetime.timedelta(
  886. hours=sign * int(m.group('hours')),
  887. minutes=sign * int(m.group('minutes')))
  888. return timezone, date_str
  889. def parse_iso8601(date_str, delimiter='T', timezone=None):
  890. """ Return a UNIX timestamp from the given date """
  891. if date_str is None:
  892. return None
  893. date_str = re.sub(r'\.[0-9]+', '', date_str)
  894. if timezone is None:
  895. timezone, date_str = extract_timezone(date_str)
  896. try:
  897. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  898. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  899. return calendar.timegm(dt.timetuple())
  900. except ValueError:
  901. pass
  902. def date_formats(day_first=True):
  903. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  904. def unified_strdate(date_str, day_first=True):
  905. """Return a string with the date in the format YYYYMMDD"""
  906. if date_str is None:
  907. return None
  908. upload_date = None
  909. # Replace commas
  910. date_str = date_str.replace(',', ' ')
  911. # Remove AM/PM + timezone
  912. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  913. _, date_str = extract_timezone(date_str)
  914. for expression in date_formats(day_first):
  915. try:
  916. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  917. except ValueError:
  918. pass
  919. if upload_date is None:
  920. timetuple = email.utils.parsedate_tz(date_str)
  921. if timetuple:
  922. try:
  923. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  924. except ValueError:
  925. pass
  926. if upload_date is not None:
  927. return compat_str(upload_date)
  928. def unified_timestamp(date_str, day_first=True):
  929. if date_str is None:
  930. return None
  931. date_str = date_str.replace(',', ' ')
  932. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  933. timezone, date_str = extract_timezone(date_str)
  934. # Remove AM/PM + timezone
  935. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  936. for expression in date_formats(day_first):
  937. try:
  938. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  939. return calendar.timegm(dt.timetuple())
  940. except ValueError:
  941. pass
  942. timetuple = email.utils.parsedate_tz(date_str)
  943. if timetuple:
  944. return calendar.timegm(timetuple) + pm_delta * 3600
  945. def determine_ext(url, default_ext='unknown_video'):
  946. if url is None:
  947. return default_ext
  948. guess = url.partition('?')[0].rpartition('.')[2]
  949. if re.match(r'^[A-Za-z0-9]+$', guess):
  950. return guess
  951. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  952. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  953. return guess.rstrip('/')
  954. else:
  955. return default_ext
  956. def subtitles_filename(filename, sub_lang, sub_format):
  957. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  958. def date_from_str(date_str):
  959. """
  960. Return a datetime object from a string in the format YYYYMMDD or
  961. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  962. today = datetime.date.today()
  963. if date_str in ('now', 'today'):
  964. return today
  965. if date_str == 'yesterday':
  966. return today - datetime.timedelta(days=1)
  967. match = re.match(r'(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  968. if match is not None:
  969. sign = match.group('sign')
  970. time = int(match.group('time'))
  971. if sign == '-':
  972. time = -time
  973. unit = match.group('unit')
  974. # A bad approximation?
  975. if unit == 'month':
  976. unit = 'day'
  977. time *= 30
  978. elif unit == 'year':
  979. unit = 'day'
  980. time *= 365
  981. unit += 's'
  982. delta = datetime.timedelta(**{unit: time})
  983. return today + delta
  984. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  985. def hyphenate_date(date_str):
  986. """
  987. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  988. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  989. if match is not None:
  990. return '-'.join(match.groups())
  991. else:
  992. return date_str
  993. class DateRange(object):
  994. """Represents a time interval between two dates"""
  995. def __init__(self, start=None, end=None):
  996. """start and end must be strings in the format accepted by date"""
  997. if start is not None:
  998. self.start = date_from_str(start)
  999. else:
  1000. self.start = datetime.datetime.min.date()
  1001. if end is not None:
  1002. self.end = date_from_str(end)
  1003. else:
  1004. self.end = datetime.datetime.max.date()
  1005. if self.start > self.end:
  1006. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  1007. @classmethod
  1008. def day(cls, day):
  1009. """Returns a range that only contains the given day"""
  1010. return cls(day, day)
  1011. def __contains__(self, date):
  1012. """Check if the date is in the range"""
  1013. if not isinstance(date, datetime.date):
  1014. date = date_from_str(date)
  1015. return self.start <= date <= self.end
  1016. def __str__(self):
  1017. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  1018. def platform_name():
  1019. """ Returns the platform name as a compat_str """
  1020. res = platform.platform()
  1021. if isinstance(res, bytes):
  1022. res = res.decode(preferredencoding())
  1023. assert isinstance(res, compat_str)
  1024. return res
  1025. def _windows_write_string(s, out):
  1026. """ Returns True if the string was written using special methods,
  1027. False if it has yet to be written out."""
  1028. # Adapted from http://stackoverflow.com/a/3259271/35070
  1029. import ctypes
  1030. import ctypes.wintypes
  1031. WIN_OUTPUT_IDS = {
  1032. 1: -11,
  1033. 2: -12,
  1034. }
  1035. try:
  1036. fileno = out.fileno()
  1037. except AttributeError:
  1038. # If the output stream doesn't have a fileno, it's virtual
  1039. return False
  1040. except io.UnsupportedOperation:
  1041. # Some strange Windows pseudo files?
  1042. return False
  1043. if fileno not in WIN_OUTPUT_IDS:
  1044. return False
  1045. GetStdHandle = ctypes.WINFUNCTYPE(
  1046. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  1047. (b'GetStdHandle', ctypes.windll.kernel32))
  1048. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  1049. WriteConsoleW = ctypes.WINFUNCTYPE(
  1050. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  1051. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  1052. ctypes.wintypes.LPVOID)((b'WriteConsoleW', ctypes.windll.kernel32))
  1053. written = ctypes.wintypes.DWORD(0)
  1054. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b'GetFileType', ctypes.windll.kernel32))
  1055. FILE_TYPE_CHAR = 0x0002
  1056. FILE_TYPE_REMOTE = 0x8000
  1057. GetConsoleMode = ctypes.WINFUNCTYPE(
  1058. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  1059. ctypes.POINTER(ctypes.wintypes.DWORD))(
  1060. (b'GetConsoleMode', ctypes.windll.kernel32))
  1061. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  1062. def not_a_console(handle):
  1063. if handle == INVALID_HANDLE_VALUE or handle is None:
  1064. return True
  1065. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  1066. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  1067. if not_a_console(h):
  1068. return False
  1069. def next_nonbmp_pos(s):
  1070. try:
  1071. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  1072. except StopIteration:
  1073. return len(s)
  1074. while s:
  1075. count = min(next_nonbmp_pos(s), 1024)
  1076. ret = WriteConsoleW(
  1077. h, s, count if count else 2, ctypes.byref(written), None)
  1078. if ret == 0:
  1079. raise OSError('Failed to write string')
  1080. if not count: # We just wrote a non-BMP character
  1081. assert written.value == 2
  1082. s = s[1:]
  1083. else:
  1084. assert written.value > 0
  1085. s = s[written.value:]
  1086. return True
  1087. def write_string(s, out=None, encoding=None):
  1088. if out is None:
  1089. out = sys.stderr
  1090. assert type(s) == compat_str
  1091. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  1092. if _windows_write_string(s, out):
  1093. return
  1094. if ('b' in getattr(out, 'mode', '') or
  1095. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  1096. byt = s.encode(encoding or preferredencoding(), 'ignore')
  1097. out.write(byt)
  1098. elif hasattr(out, 'buffer'):
  1099. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  1100. byt = s.encode(enc, 'ignore')
  1101. out.buffer.write(byt)
  1102. else:
  1103. out.write(s)
  1104. out.flush()
  1105. def bytes_to_intlist(bs):
  1106. if not bs:
  1107. return []
  1108. if isinstance(bs[0], int): # Python 3
  1109. return list(bs)
  1110. else:
  1111. return [ord(c) for c in bs]
  1112. def intlist_to_bytes(xs):
  1113. if not xs:
  1114. return b''
  1115. return compat_struct_pack('%dB' % len(xs), *xs)
  1116. # Cross-platform file locking
  1117. if sys.platform == 'win32':
  1118. import ctypes.wintypes
  1119. import msvcrt
  1120. class OVERLAPPED(ctypes.Structure):
  1121. _fields_ = [
  1122. ('Internal', ctypes.wintypes.LPVOID),
  1123. ('InternalHigh', ctypes.wintypes.LPVOID),
  1124. ('Offset', ctypes.wintypes.DWORD),
  1125. ('OffsetHigh', ctypes.wintypes.DWORD),
  1126. ('hEvent', ctypes.wintypes.HANDLE),
  1127. ]
  1128. kernel32 = ctypes.windll.kernel32
  1129. LockFileEx = kernel32.LockFileEx
  1130. LockFileEx.argtypes = [
  1131. ctypes.wintypes.HANDLE, # hFile
  1132. ctypes.wintypes.DWORD, # dwFlags
  1133. ctypes.wintypes.DWORD, # dwReserved
  1134. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1135. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1136. ctypes.POINTER(OVERLAPPED) # Overlapped
  1137. ]
  1138. LockFileEx.restype = ctypes.wintypes.BOOL
  1139. UnlockFileEx = kernel32.UnlockFileEx
  1140. UnlockFileEx.argtypes = [
  1141. ctypes.wintypes.HANDLE, # hFile
  1142. ctypes.wintypes.DWORD, # dwReserved
  1143. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1144. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1145. ctypes.POINTER(OVERLAPPED) # Overlapped
  1146. ]
  1147. UnlockFileEx.restype = ctypes.wintypes.BOOL
  1148. whole_low = 0xffffffff
  1149. whole_high = 0x7fffffff
  1150. def _lock_file(f, exclusive):
  1151. overlapped = OVERLAPPED()
  1152. overlapped.Offset = 0
  1153. overlapped.OffsetHigh = 0
  1154. overlapped.hEvent = 0
  1155. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  1156. handle = msvcrt.get_osfhandle(f.fileno())
  1157. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  1158. whole_low, whole_high, f._lock_file_overlapped_p):
  1159. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  1160. def _unlock_file(f):
  1161. assert f._lock_file_overlapped_p
  1162. handle = msvcrt.get_osfhandle(f.fileno())
  1163. if not UnlockFileEx(handle, 0,
  1164. whole_low, whole_high, f._lock_file_overlapped_p):
  1165. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  1166. else:
  1167. # Some platforms, such as Jython, is missing fcntl
  1168. try:
  1169. import fcntl
  1170. def _lock_file(f, exclusive):
  1171. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  1172. def _unlock_file(f):
  1173. fcntl.flock(f, fcntl.LOCK_UN)
  1174. except ImportError:
  1175. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  1176. def _lock_file(f, exclusive):
  1177. raise IOError(UNSUPPORTED_MSG)
  1178. def _unlock_file(f):
  1179. raise IOError(UNSUPPORTED_MSG)
  1180. class locked_file(object):
  1181. def __init__(self, filename, mode, encoding=None):
  1182. assert mode in ['r', 'a', 'w']
  1183. self.f = io.open(filename, mode, encoding=encoding)
  1184. self.mode = mode
  1185. def __enter__(self):
  1186. exclusive = self.mode != 'r'
  1187. try:
  1188. _lock_file(self.f, exclusive)
  1189. except IOError:
  1190. self.f.close()
  1191. raise
  1192. return self
  1193. def __exit__(self, etype, value, traceback):
  1194. try:
  1195. _unlock_file(self.f)
  1196. finally:
  1197. self.f.close()
  1198. def __iter__(self):
  1199. return iter(self.f)
  1200. def write(self, *args):
  1201. return self.f.write(*args)
  1202. def read(self, *args):
  1203. return self.f.read(*args)
  1204. def get_filesystem_encoding():
  1205. encoding = sys.getfilesystemencoding()
  1206. return encoding if encoding is not None else 'utf-8'
  1207. def shell_quote(args):
  1208. quoted_args = []
  1209. encoding = get_filesystem_encoding()
  1210. for a in args:
  1211. if isinstance(a, bytes):
  1212. # We may get a filename encoded with 'encodeFilename'
  1213. a = a.decode(encoding)
  1214. quoted_args.append(pipes.quote(a))
  1215. return ' '.join(quoted_args)
  1216. def smuggle_url(url, data):
  1217. """ Pass additional data in a URL for internal use. """
  1218. url, idata = unsmuggle_url(url, {})
  1219. data.update(idata)
  1220. sdata = compat_urllib_parse_urlencode(
  1221. {'__youtubedl_smuggle': json.dumps(data)})
  1222. return url + '#' + sdata
  1223. def unsmuggle_url(smug_url, default=None):
  1224. if '#__youtubedl_smuggle' not in smug_url:
  1225. return smug_url, default
  1226. url, _, sdata = smug_url.rpartition('#')
  1227. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  1228. data = json.loads(jsond)
  1229. return url, data
  1230. def format_bytes(bytes):
  1231. if bytes is None:
  1232. return 'N/A'
  1233. if type(bytes) is str:
  1234. bytes = float(bytes)
  1235. if bytes == 0.0:
  1236. exponent = 0
  1237. else:
  1238. exponent = int(math.log(bytes, 1024.0))
  1239. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  1240. converted = float(bytes) / float(1024 ** exponent)
  1241. return '%.2f%s' % (converted, suffix)
  1242. def lookup_unit_table(unit_table, s):
  1243. units_re = '|'.join(re.escape(u) for u in unit_table)
  1244. m = re.match(
  1245. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  1246. if not m:
  1247. return None
  1248. num_str = m.group('num').replace(',', '.')
  1249. mult = unit_table[m.group('unit')]
  1250. return int(float(num_str) * mult)
  1251. def parse_filesize(s):
  1252. if s is None:
  1253. return None
  1254. # The lower-case forms are of course incorrect and unofficial,
  1255. # but we support those too
  1256. _UNIT_TABLE = {
  1257. 'B': 1,
  1258. 'b': 1,
  1259. 'bytes': 1,
  1260. 'KiB': 1024,
  1261. 'KB': 1000,
  1262. 'kB': 1024,
  1263. 'Kb': 1000,
  1264. 'kb': 1000,
  1265. 'kilobytes': 1000,
  1266. 'kibibytes': 1024,
  1267. 'MiB': 1024 ** 2,
  1268. 'MB': 1000 ** 2,
  1269. 'mB': 1024 ** 2,
  1270. 'Mb': 1000 ** 2,
  1271. 'mb': 1000 ** 2,
  1272. 'megabytes': 1000 ** 2,
  1273. 'mebibytes': 1024 ** 2,
  1274. 'GiB': 1024 ** 3,
  1275. 'GB': 1000 ** 3,
  1276. 'gB': 1024 ** 3,
  1277. 'Gb': 1000 ** 3,
  1278. 'gb': 1000 ** 3,
  1279. 'gigabytes': 1000 ** 3,
  1280. 'gibibytes': 1024 ** 3,
  1281. 'TiB': 1024 ** 4,
  1282. 'TB': 1000 ** 4,
  1283. 'tB': 1024 ** 4,
  1284. 'Tb': 1000 ** 4,
  1285. 'tb': 1000 ** 4,
  1286. 'terabytes': 1000 ** 4,
  1287. 'tebibytes': 1024 ** 4,
  1288. 'PiB': 1024 ** 5,
  1289. 'PB': 1000 ** 5,
  1290. 'pB': 1024 ** 5,
  1291. 'Pb': 1000 ** 5,
  1292. 'pb': 1000 ** 5,
  1293. 'petabytes': 1000 ** 5,
  1294. 'pebibytes': 1024 ** 5,
  1295. 'EiB': 1024 ** 6,
  1296. 'EB': 1000 ** 6,
  1297. 'eB': 1024 ** 6,
  1298. 'Eb': 1000 ** 6,
  1299. 'eb': 1000 ** 6,
  1300. 'exabytes': 1000 ** 6,
  1301. 'exbibytes': 1024 ** 6,
  1302. 'ZiB': 1024 ** 7,
  1303. 'ZB': 1000 ** 7,
  1304. 'zB': 1024 ** 7,
  1305. 'Zb': 1000 ** 7,
  1306. 'zb': 1000 ** 7,
  1307. 'zettabytes': 1000 ** 7,
  1308. 'zebibytes': 1024 ** 7,
  1309. 'YiB': 1024 ** 8,
  1310. 'YB': 1000 ** 8,
  1311. 'yB': 1024 ** 8,
  1312. 'Yb': 1000 ** 8,
  1313. 'yb': 1000 ** 8,
  1314. 'yottabytes': 1000 ** 8,
  1315. 'yobibytes': 1024 ** 8,
  1316. }
  1317. return lookup_unit_table(_UNIT_TABLE, s)
  1318. def parse_count(s):
  1319. if s is None:
  1320. return None
  1321. s = s.strip()
  1322. if re.match(r'^[\d,.]+$', s):
  1323. return str_to_int(s)
  1324. _UNIT_TABLE = {
  1325. 'k': 1000,
  1326. 'K': 1000,
  1327. 'm': 1000 ** 2,
  1328. 'M': 1000 ** 2,
  1329. 'kk': 1000 ** 2,
  1330. 'KK': 1000 ** 2,
  1331. }
  1332. return lookup_unit_table(_UNIT_TABLE, s)
  1333. def month_by_name(name, lang='en'):
  1334. """ Return the number of a month by (locale-independently) English name """
  1335. month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
  1336. try:
  1337. return month_names.index(name) + 1
  1338. except ValueError:
  1339. return None
  1340. def month_by_abbreviation(abbrev):
  1341. """ Return the number of a month by (locale-independently) English
  1342. abbreviations """
  1343. try:
  1344. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1345. except ValueError:
  1346. return None
  1347. def fix_xml_ampersands(xml_str):
  1348. """Replace all the '&' by '&amp;' in XML"""
  1349. return re.sub(
  1350. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1351. '&amp;',
  1352. xml_str)
  1353. def setproctitle(title):
  1354. assert isinstance(title, compat_str)
  1355. # ctypes in Jython is not complete
  1356. # http://bugs.jython.org/issue2148
  1357. if sys.platform.startswith('java'):
  1358. return
  1359. try:
  1360. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  1361. except OSError:
  1362. return
  1363. title_bytes = title.encode('utf-8')
  1364. buf = ctypes.create_string_buffer(len(title_bytes))
  1365. buf.value = title_bytes
  1366. try:
  1367. libc.prctl(15, buf, 0, 0, 0)
  1368. except AttributeError:
  1369. return # Strange libc, just skip this
  1370. def remove_start(s, start):
  1371. return s[len(start):] if s is not None and s.startswith(start) else s
  1372. def remove_end(s, end):
  1373. return s[:-len(end)] if s is not None and s.endswith(end) else s
  1374. def remove_quotes(s):
  1375. if s is None or len(s) < 2:
  1376. return s
  1377. for quote in ('"', "'", ):
  1378. if s[0] == quote and s[-1] == quote:
  1379. return s[1:-1]
  1380. return s
  1381. def url_basename(url):
  1382. path = compat_urlparse.urlparse(url).path
  1383. return path.strip('/').split('/')[-1]
  1384. def base_url(url):
  1385. return re.match(r'https?://[^?#&]+/', url).group()
  1386. def urljoin(base, path):
  1387. if not isinstance(path, compat_str) or not path:
  1388. return None
  1389. if re.match(r'^(?:https?:)?//', path):
  1390. return path
  1391. if not isinstance(base, compat_str) or not re.match(r'^(?:https?:)?//', base):
  1392. return None
  1393. return compat_urlparse.urljoin(base, path)
  1394. class HEADRequest(compat_urllib_request.Request):
  1395. def get_method(self):
  1396. return 'HEAD'
  1397. class PUTRequest(compat_urllib_request.Request):
  1398. def get_method(self):
  1399. return 'PUT'
  1400. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1401. if get_attr:
  1402. if v is not None:
  1403. v = getattr(v, get_attr, None)
  1404. if v == '':
  1405. v = None
  1406. if v is None:
  1407. return default
  1408. try:
  1409. return int(v) * invscale // scale
  1410. except ValueError:
  1411. return default
  1412. def str_or_none(v, default=None):
  1413. return default if v is None else compat_str(v)
  1414. def str_to_int(int_str):
  1415. """ A more relaxed version of int_or_none """
  1416. if int_str is None:
  1417. return None
  1418. int_str = re.sub(r'[,\.\+]', '', int_str)
  1419. return int(int_str)
  1420. def float_or_none(v, scale=1, invscale=1, default=None):
  1421. if v is None:
  1422. return default
  1423. try:
  1424. return float(v) * invscale / scale
  1425. except ValueError:
  1426. return default
  1427. def strip_or_none(v):
  1428. return None if v is None else v.strip()
  1429. def parse_duration(s):
  1430. if not isinstance(s, compat_basestring):
  1431. return None
  1432. s = s.strip()
  1433. days, hours, mins, secs, ms = [None] * 5
  1434. m = re.match(r'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?Z?$', s)
  1435. if m:
  1436. days, hours, mins, secs, ms = m.groups()
  1437. else:
  1438. m = re.match(
  1439. r'''(?ix)(?:P?T)?
  1440. (?:
  1441. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  1442. )?
  1443. (?:
  1444. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  1445. )?
  1446. (?:
  1447. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  1448. )?
  1449. (?:
  1450. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  1451. )?Z?$''', s)
  1452. if m:
  1453. days, hours, mins, secs, ms = m.groups()
  1454. else:
  1455. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
  1456. if m:
  1457. hours, mins = m.groups()
  1458. else:
  1459. return None
  1460. duration = 0
  1461. if secs:
  1462. duration += float(secs)
  1463. if mins:
  1464. duration += float(mins) * 60
  1465. if hours:
  1466. duration += float(hours) * 60 * 60
  1467. if days:
  1468. duration += float(days) * 24 * 60 * 60
  1469. if ms:
  1470. duration += float(ms)
  1471. return duration
  1472. def prepend_extension(filename, ext, expected_real_ext=None):
  1473. name, real_ext = os.path.splitext(filename)
  1474. return (
  1475. '{0}.{1}{2}'.format(name, ext, real_ext)
  1476. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1477. else '{0}.{1}'.format(filename, ext))
  1478. def replace_extension(filename, ext, expected_real_ext=None):
  1479. name, real_ext = os.path.splitext(filename)
  1480. return '{0}.{1}'.format(
  1481. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1482. ext)
  1483. def check_executable(exe, args=[]):
  1484. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1485. args can be a list of arguments for a short output (like -version) """
  1486. try:
  1487. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1488. except OSError:
  1489. return False
  1490. return exe
  1491. def get_exe_version(exe, args=['--version'],
  1492. version_re=None, unrecognized='present'):
  1493. """ Returns the version of the specified executable,
  1494. or False if the executable is not present """
  1495. try:
  1496. # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
  1497. # SIGTTOU if youtube-dl is run in the background.
  1498. # See https://github.com/rg3/youtube-dl/issues/955#issuecomment-209789656
  1499. out, _ = subprocess.Popen(
  1500. [encodeArgument(exe)] + args,
  1501. stdin=subprocess.PIPE,
  1502. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1503. except OSError:
  1504. return False
  1505. if isinstance(out, bytes): # Python 2.x
  1506. out = out.decode('ascii', 'ignore')
  1507. return detect_exe_version(out, version_re, unrecognized)
  1508. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1509. assert isinstance(output, compat_str)
  1510. if version_re is None:
  1511. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1512. m = re.search(version_re, output)
  1513. if m:
  1514. return m.group(1)
  1515. else:
  1516. return unrecognized
  1517. class PagedList(object):
  1518. def __len__(self):
  1519. # This is only useful for tests
  1520. return len(self.getslice())
  1521. class OnDemandPagedList(PagedList):
  1522. def __init__(self, pagefunc, pagesize, use_cache=False):
  1523. self._pagefunc = pagefunc
  1524. self._pagesize = pagesize
  1525. self._use_cache = use_cache
  1526. if use_cache:
  1527. self._cache = {}
  1528. def getslice(self, start=0, end=None):
  1529. res = []
  1530. for pagenum in itertools.count(start // self._pagesize):
  1531. firstid = pagenum * self._pagesize
  1532. nextfirstid = pagenum * self._pagesize + self._pagesize
  1533. if start >= nextfirstid:
  1534. continue
  1535. page_results = None
  1536. if self._use_cache:
  1537. page_results = self._cache.get(pagenum)
  1538. if page_results is None:
  1539. page_results = list(self._pagefunc(pagenum))
  1540. if self._use_cache:
  1541. self._cache[pagenum] = page_results
  1542. startv = (
  1543. start % self._pagesize
  1544. if firstid <= start < nextfirstid
  1545. else 0)
  1546. endv = (
  1547. ((end - 1) % self._pagesize) + 1
  1548. if (end is not None and firstid <= end <= nextfirstid)
  1549. else None)
  1550. if startv != 0 or endv is not None:
  1551. page_results = page_results[startv:endv]
  1552. res.extend(page_results)
  1553. # A little optimization - if current page is not "full", ie. does
  1554. # not contain page_size videos then we can assume that this page
  1555. # is the last one - there are no more ids on further pages -
  1556. # i.e. no need to query again.
  1557. if len(page_results) + startv < self._pagesize:
  1558. break
  1559. # If we got the whole page, but the next page is not interesting,
  1560. # break out early as well
  1561. if end == nextfirstid:
  1562. break
  1563. return res
  1564. class InAdvancePagedList(PagedList):
  1565. def __init__(self, pagefunc, pagecount, pagesize):
  1566. self._pagefunc = pagefunc
  1567. self._pagecount = pagecount
  1568. self._pagesize = pagesize
  1569. def getslice(self, start=0, end=None):
  1570. res = []
  1571. start_page = start // self._pagesize
  1572. end_page = (
  1573. self._pagecount if end is None else (end // self._pagesize + 1))
  1574. skip_elems = start - start_page * self._pagesize
  1575. only_more = None if end is None else end - start
  1576. for pagenum in range(start_page, end_page):
  1577. page = list(self._pagefunc(pagenum))
  1578. if skip_elems:
  1579. page = page[skip_elems:]
  1580. skip_elems = None
  1581. if only_more is not None:
  1582. if len(page) < only_more:
  1583. only_more -= len(page)
  1584. else:
  1585. page = page[:only_more]
  1586. res.extend(page)
  1587. break
  1588. res.extend(page)
  1589. return res
  1590. def uppercase_escape(s):
  1591. unicode_escape = codecs.getdecoder('unicode_escape')
  1592. return re.sub(
  1593. r'\\U[0-9a-fA-F]{8}',
  1594. lambda m: unicode_escape(m.group(0))[0],
  1595. s)
  1596. def lowercase_escape(s):
  1597. unicode_escape = codecs.getdecoder('unicode_escape')
  1598. return re.sub(
  1599. r'\\u[0-9a-fA-F]{4}',
  1600. lambda m: unicode_escape(m.group(0))[0],
  1601. s)
  1602. def escape_rfc3986(s):
  1603. """Escape non-ASCII characters as suggested by RFC 3986"""
  1604. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1605. s = s.encode('utf-8')
  1606. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1607. def escape_url(url):
  1608. """Escape URL as suggested by RFC 3986"""
  1609. url_parsed = compat_urllib_parse_urlparse(url)
  1610. return url_parsed._replace(
  1611. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  1612. path=escape_rfc3986(url_parsed.path),
  1613. params=escape_rfc3986(url_parsed.params),
  1614. query=escape_rfc3986(url_parsed.query),
  1615. fragment=escape_rfc3986(url_parsed.fragment)
  1616. ).geturl()
  1617. def read_batch_urls(batch_fd):
  1618. def fixup(url):
  1619. if not isinstance(url, compat_str):
  1620. url = url.decode('utf-8', 'replace')
  1621. BOM_UTF8 = '\xef\xbb\xbf'
  1622. if url.startswith(BOM_UTF8):
  1623. url = url[len(BOM_UTF8):]
  1624. url = url.strip()
  1625. if url.startswith(('#', ';', ']')):
  1626. return False
  1627. return url
  1628. with contextlib.closing(batch_fd) as fd:
  1629. return [url for url in map(fixup, fd) if url]
  1630. def urlencode_postdata(*args, **kargs):
  1631. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  1632. def update_url_query(url, query):
  1633. if not query:
  1634. return url
  1635. parsed_url = compat_urlparse.urlparse(url)
  1636. qs = compat_parse_qs(parsed_url.query)
  1637. qs.update(query)
  1638. return compat_urlparse.urlunparse(parsed_url._replace(
  1639. query=compat_urllib_parse_urlencode(qs, True)))
  1640. def update_Request(req, url=None, data=None, headers={}, query={}):
  1641. req_headers = req.headers.copy()
  1642. req_headers.update(headers)
  1643. req_data = data or req.data
  1644. req_url = update_url_query(url or req.get_full_url(), query)
  1645. req_get_method = req.get_method()
  1646. if req_get_method == 'HEAD':
  1647. req_type = HEADRequest
  1648. elif req_get_method == 'PUT':
  1649. req_type = PUTRequest
  1650. else:
  1651. req_type = compat_urllib_request.Request
  1652. new_req = req_type(
  1653. req_url, data=req_data, headers=req_headers,
  1654. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1655. if hasattr(req, 'timeout'):
  1656. new_req.timeout = req.timeout
  1657. return new_req
  1658. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  1659. if isinstance(key_or_keys, (list, tuple)):
  1660. for key in key_or_keys:
  1661. if key not in d or d[key] is None or skip_false_values and not d[key]:
  1662. continue
  1663. return d[key]
  1664. return default
  1665. return d.get(key_or_keys, default)
  1666. def try_get(src, getter, expected_type=None):
  1667. try:
  1668. v = getter(src)
  1669. except (AttributeError, KeyError, TypeError, IndexError):
  1670. pass
  1671. else:
  1672. if expected_type is None or isinstance(v, expected_type):
  1673. return v
  1674. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1675. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1676. US_RATINGS = {
  1677. 'G': 0,
  1678. 'PG': 10,
  1679. 'PG-13': 13,
  1680. 'R': 16,
  1681. 'NC': 18,
  1682. }
  1683. TV_PARENTAL_GUIDELINES = {
  1684. 'TV-Y': 0,
  1685. 'TV-Y7': 7,
  1686. 'TV-G': 0,
  1687. 'TV-PG': 0,
  1688. 'TV-14': 14,
  1689. 'TV-MA': 17,
  1690. }
  1691. def parse_age_limit(s):
  1692. if type(s) == int:
  1693. return s if 0 <= s <= 21 else None
  1694. if not isinstance(s, compat_basestring):
  1695. return None
  1696. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1697. if m:
  1698. return int(m.group('age'))
  1699. if s in US_RATINGS:
  1700. return US_RATINGS[s]
  1701. return TV_PARENTAL_GUIDELINES.get(s)
  1702. def strip_jsonp(code):
  1703. return re.sub(
  1704. r'(?s)^[a-zA-Z0-9_.$]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1705. def js_to_json(code):
  1706. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*'
  1707. SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
  1708. INTEGER_TABLE = (
  1709. (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
  1710. (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
  1711. )
  1712. def fix_kv(m):
  1713. v = m.group(0)
  1714. if v in ('true', 'false', 'null'):
  1715. return v
  1716. elif v.startswith('/*') or v.startswith('//') or v == ',':
  1717. return ""
  1718. if v[0] in ("'", '"'):
  1719. v = re.sub(r'(?s)\\.|"', lambda m: {
  1720. '"': '\\"',
  1721. "\\'": "'",
  1722. '\\\n': '',
  1723. '\\x': '\\u00',
  1724. }.get(m.group(0), m.group(0)), v[1:-1])
  1725. for regex, base in INTEGER_TABLE:
  1726. im = re.match(regex, v)
  1727. if im:
  1728. i = int(im.group(1), base)
  1729. return '"%d":' % i if v.endswith(':') else '%d' % i
  1730. return '"%s"' % v
  1731. return re.sub(r'''(?sx)
  1732. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  1733. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  1734. {comment}|,(?={skip}[\]}}])|
  1735. [a-zA-Z_][.a-zA-Z_0-9]*|
  1736. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
  1737. [0-9]+(?={skip}:)
  1738. '''.format(comment=COMMENT_RE, skip=SKIP_RE), fix_kv, code)
  1739. def qualities(quality_ids):
  1740. """ Get a numeric quality value out of a list of possible values """
  1741. def q(qid):
  1742. try:
  1743. return quality_ids.index(qid)
  1744. except ValueError:
  1745. return -1
  1746. return q
  1747. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1748. def limit_length(s, length):
  1749. """ Add ellipses to overly long strings """
  1750. if s is None:
  1751. return None
  1752. ELLIPSES = '...'
  1753. if len(s) > length:
  1754. return s[:length - len(ELLIPSES)] + ELLIPSES
  1755. return s
  1756. def version_tuple(v):
  1757. return tuple(int(e) for e in re.split(r'[-.]', v))
  1758. def is_outdated_version(version, limit, assume_new=True):
  1759. if not version:
  1760. return not assume_new
  1761. try:
  1762. return version_tuple(version) < version_tuple(limit)
  1763. except ValueError:
  1764. return not assume_new
  1765. def ytdl_is_updateable():
  1766. """ Returns if youtube-dl can be updated with -U """
  1767. from zipimport import zipimporter
  1768. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1769. def args_to_str(args):
  1770. # Get a short string representation for a subprocess command
  1771. return ' '.join(compat_shlex_quote(a) for a in args)
  1772. def error_to_compat_str(err):
  1773. err_str = str(err)
  1774. # On python 2 error byte string must be decoded with proper
  1775. # encoding rather than ascii
  1776. if sys.version_info[0] < 3:
  1777. err_str = err_str.decode(preferredencoding())
  1778. return err_str
  1779. def mimetype2ext(mt):
  1780. if mt is None:
  1781. return None
  1782. ext = {
  1783. 'audio/mp4': 'm4a',
  1784. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  1785. # it's the most popular one
  1786. 'audio/mpeg': 'mp3',
  1787. }.get(mt)
  1788. if ext is not None:
  1789. return ext
  1790. _, _, res = mt.rpartition('/')
  1791. res = res.split(';')[0].strip().lower()
  1792. return {
  1793. '3gpp': '3gp',
  1794. 'smptett+xml': 'tt',
  1795. 'srt': 'srt',
  1796. 'ttaf+xml': 'dfxp',
  1797. 'ttml+xml': 'ttml',
  1798. 'vtt': 'vtt',
  1799. 'x-flv': 'flv',
  1800. 'x-mp4-fragmented': 'mp4',
  1801. 'x-ms-wmv': 'wmv',
  1802. 'mpegurl': 'm3u8',
  1803. 'x-mpegurl': 'm3u8',
  1804. 'vnd.apple.mpegurl': 'm3u8',
  1805. 'dash+xml': 'mpd',
  1806. 'f4m': 'f4m',
  1807. 'f4m+xml': 'f4m',
  1808. 'hds+xml': 'f4m',
  1809. 'vnd.ms-sstr+xml': 'ism',
  1810. 'quicktime': 'mov',
  1811. }.get(res, res)
  1812. def parse_codecs(codecs_str):
  1813. # http://tools.ietf.org/html/rfc6381
  1814. if not codecs_str:
  1815. return {}
  1816. splited_codecs = list(filter(None, map(
  1817. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  1818. vcodec, acodec = None, None
  1819. for full_codec in splited_codecs:
  1820. codec = full_codec.split('.')[0]
  1821. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v'):
  1822. if not vcodec:
  1823. vcodec = full_codec
  1824. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3'):
  1825. if not acodec:
  1826. acodec = full_codec
  1827. else:
  1828. write_string('WARNING: Unknown codec %s' % full_codec, sys.stderr)
  1829. if not vcodec and not acodec:
  1830. if len(splited_codecs) == 2:
  1831. return {
  1832. 'vcodec': vcodec,
  1833. 'acodec': acodec,
  1834. }
  1835. elif len(splited_codecs) == 1:
  1836. return {
  1837. 'vcodec': 'none',
  1838. 'acodec': vcodec,
  1839. }
  1840. else:
  1841. return {
  1842. 'vcodec': vcodec or 'none',
  1843. 'acodec': acodec or 'none',
  1844. }
  1845. return {}
  1846. def urlhandle_detect_ext(url_handle):
  1847. getheader = url_handle.headers.get
  1848. cd = getheader('Content-Disposition')
  1849. if cd:
  1850. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1851. if m:
  1852. e = determine_ext(m.group('filename'), default_ext=None)
  1853. if e:
  1854. return e
  1855. return mimetype2ext(getheader('Content-Type'))
  1856. def encode_data_uri(data, mime_type):
  1857. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1858. def age_restricted(content_limit, age_limit):
  1859. """ Returns True iff the content should be blocked """
  1860. if age_limit is None: # No limit set
  1861. return False
  1862. if content_limit is None:
  1863. return False # Content available for everyone
  1864. return age_limit < content_limit
  1865. def is_html(first_bytes):
  1866. """ Detect whether a file contains HTML by examining its first bytes. """
  1867. BOMS = [
  1868. (b'\xef\xbb\xbf', 'utf-8'),
  1869. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1870. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1871. (b'\xff\xfe', 'utf-16-le'),
  1872. (b'\xfe\xff', 'utf-16-be'),
  1873. ]
  1874. for bom, enc in BOMS:
  1875. if first_bytes.startswith(bom):
  1876. s = first_bytes[len(bom):].decode(enc, 'replace')
  1877. break
  1878. else:
  1879. s = first_bytes.decode('utf-8', 'replace')
  1880. return re.match(r'^\s*<', s)
  1881. def determine_protocol(info_dict):
  1882. protocol = info_dict.get('protocol')
  1883. if protocol is not None:
  1884. return protocol
  1885. url = info_dict['url']
  1886. if url.startswith('rtmp'):
  1887. return 'rtmp'
  1888. elif url.startswith('mms'):
  1889. return 'mms'
  1890. elif url.startswith('rtsp'):
  1891. return 'rtsp'
  1892. ext = determine_ext(url)
  1893. if ext == 'm3u8':
  1894. return 'm3u8'
  1895. elif ext == 'f4m':
  1896. return 'f4m'
  1897. return compat_urllib_parse_urlparse(url).scheme
  1898. def render_table(header_row, data):
  1899. """ Render a list of rows, each as a list of values """
  1900. table = [header_row] + data
  1901. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1902. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1903. return '\n'.join(format_str % tuple(row) for row in table)
  1904. def _match_one(filter_part, dct):
  1905. COMPARISON_OPERATORS = {
  1906. '<': operator.lt,
  1907. '<=': operator.le,
  1908. '>': operator.gt,
  1909. '>=': operator.ge,
  1910. '=': operator.eq,
  1911. '!=': operator.ne,
  1912. }
  1913. operator_rex = re.compile(r'''(?x)\s*
  1914. (?P<key>[a-z_]+)
  1915. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1916. (?:
  1917. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1918. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1919. )
  1920. \s*$
  1921. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1922. m = operator_rex.search(filter_part)
  1923. if m:
  1924. op = COMPARISON_OPERATORS[m.group('op')]
  1925. actual_value = dct.get(m.group('key'))
  1926. if (m.group('strval') is not None or
  1927. # If the original field is a string and matching comparisonvalue is
  1928. # a number we should respect the origin of the original field
  1929. # and process comparison value as a string (see
  1930. # https://github.com/rg3/youtube-dl/issues/11082).
  1931. actual_value is not None and m.group('intval') is not None and
  1932. isinstance(actual_value, compat_str)):
  1933. if m.group('op') not in ('=', '!='):
  1934. raise ValueError(
  1935. 'Operator %s does not support string values!' % m.group('op'))
  1936. comparison_value = m.group('strval') or m.group('intval')
  1937. else:
  1938. try:
  1939. comparison_value = int(m.group('intval'))
  1940. except ValueError:
  1941. comparison_value = parse_filesize(m.group('intval'))
  1942. if comparison_value is None:
  1943. comparison_value = parse_filesize(m.group('intval') + 'B')
  1944. if comparison_value is None:
  1945. raise ValueError(
  1946. 'Invalid integer value %r in filter part %r' % (
  1947. m.group('intval'), filter_part))
  1948. if actual_value is None:
  1949. return m.group('none_inclusive')
  1950. return op(actual_value, comparison_value)
  1951. UNARY_OPERATORS = {
  1952. '': lambda v: v is not None,
  1953. '!': lambda v: v is None,
  1954. }
  1955. operator_rex = re.compile(r'''(?x)\s*
  1956. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1957. \s*$
  1958. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1959. m = operator_rex.search(filter_part)
  1960. if m:
  1961. op = UNARY_OPERATORS[m.group('op')]
  1962. actual_value = dct.get(m.group('key'))
  1963. return op(actual_value)
  1964. raise ValueError('Invalid filter part %r' % filter_part)
  1965. def match_str(filter_str, dct):
  1966. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1967. return all(
  1968. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1969. def match_filter_func(filter_str):
  1970. def _match_func(info_dict):
  1971. if match_str(filter_str, info_dict):
  1972. return None
  1973. else:
  1974. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1975. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1976. return _match_func
  1977. def parse_dfxp_time_expr(time_expr):
  1978. if not time_expr:
  1979. return
  1980. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1981. if mobj:
  1982. return float(mobj.group('time_offset'))
  1983. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  1984. if mobj:
  1985. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  1986. def srt_subtitles_timecode(seconds):
  1987. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1988. def dfxp2srt(dfxp_data):
  1989. _x = functools.partial(xpath_with_ns, ns_map={
  1990. 'ttml': 'http://www.w3.org/ns/ttml',
  1991. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1992. 'ttaf1_0604': 'http://www.w3.org/2006/04/ttaf1',
  1993. })
  1994. class TTMLPElementParser(object):
  1995. out = ''
  1996. def start(self, tag, attrib):
  1997. if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1998. self.out += '\n'
  1999. def end(self, tag):
  2000. pass
  2001. def data(self, data):
  2002. self.out += data
  2003. def close(self):
  2004. return self.out.strip()
  2005. def parse_node(node):
  2006. target = TTMLPElementParser()
  2007. parser = xml.etree.ElementTree.XMLParser(target=target)
  2008. parser.feed(xml.etree.ElementTree.tostring(node))
  2009. return parser.close()
  2010. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  2011. out = []
  2012. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall(_x('.//ttaf1_0604:p')) or dfxp.findall('.//p')
  2013. if not paras:
  2014. raise ValueError('Invalid dfxp/TTML subtitle')
  2015. for para, index in zip(paras, itertools.count(1)):
  2016. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  2017. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  2018. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  2019. if begin_time is None:
  2020. continue
  2021. if not end_time:
  2022. if not dur:
  2023. continue
  2024. end_time = begin_time + dur
  2025. out.append('%d\n%s --> %s\n%s\n\n' % (
  2026. index,
  2027. srt_subtitles_timecode(begin_time),
  2028. srt_subtitles_timecode(end_time),
  2029. parse_node(para)))
  2030. return ''.join(out)
  2031. def cli_option(params, command_option, param):
  2032. param = params.get(param)
  2033. if param:
  2034. param = compat_str(param)
  2035. return [command_option, param] if param is not None else []
  2036. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  2037. param = params.get(param)
  2038. assert isinstance(param, bool)
  2039. if separator:
  2040. return [command_option + separator + (true_value if param else false_value)]
  2041. return [command_option, true_value if param else false_value]
  2042. def cli_valueless_option(params, command_option, param, expected_value=True):
  2043. param = params.get(param)
  2044. return [command_option] if param == expected_value else []
  2045. def cli_configuration_args(params, param, default=[]):
  2046. ex_args = params.get(param)
  2047. if ex_args is None:
  2048. return default
  2049. assert isinstance(ex_args, list)
  2050. return ex_args
  2051. class ISO639Utils(object):
  2052. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  2053. _lang_map = {
  2054. 'aa': 'aar',
  2055. 'ab': 'abk',
  2056. 'ae': 'ave',
  2057. 'af': 'afr',
  2058. 'ak': 'aka',
  2059. 'am': 'amh',
  2060. 'an': 'arg',
  2061. 'ar': 'ara',
  2062. 'as': 'asm',
  2063. 'av': 'ava',
  2064. 'ay': 'aym',
  2065. 'az': 'aze',
  2066. 'ba': 'bak',
  2067. 'be': 'bel',
  2068. 'bg': 'bul',
  2069. 'bh': 'bih',
  2070. 'bi': 'bis',
  2071. 'bm': 'bam',
  2072. 'bn': 'ben',
  2073. 'bo': 'bod',
  2074. 'br': 'bre',
  2075. 'bs': 'bos',
  2076. 'ca': 'cat',
  2077. 'ce': 'che',
  2078. 'ch': 'cha',
  2079. 'co': 'cos',
  2080. 'cr': 'cre',
  2081. 'cs': 'ces',
  2082. 'cu': 'chu',
  2083. 'cv': 'chv',
  2084. 'cy': 'cym',
  2085. 'da': 'dan',
  2086. 'de': 'deu',
  2087. 'dv': 'div',
  2088. 'dz': 'dzo',
  2089. 'ee': 'ewe',
  2090. 'el': 'ell',
  2091. 'en': 'eng',
  2092. 'eo': 'epo',
  2093. 'es': 'spa',
  2094. 'et': 'est',
  2095. 'eu': 'eus',
  2096. 'fa': 'fas',
  2097. 'ff': 'ful',
  2098. 'fi': 'fin',
  2099. 'fj': 'fij',
  2100. 'fo': 'fao',
  2101. 'fr': 'fra',
  2102. 'fy': 'fry',
  2103. 'ga': 'gle',
  2104. 'gd': 'gla',
  2105. 'gl': 'glg',
  2106. 'gn': 'grn',
  2107. 'gu': 'guj',
  2108. 'gv': 'glv',
  2109. 'ha': 'hau',
  2110. 'he': 'heb',
  2111. 'hi': 'hin',
  2112. 'ho': 'hmo',
  2113. 'hr': 'hrv',
  2114. 'ht': 'hat',
  2115. 'hu': 'hun',
  2116. 'hy': 'hye',
  2117. 'hz': 'her',
  2118. 'ia': 'ina',
  2119. 'id': 'ind',
  2120. 'ie': 'ile',
  2121. 'ig': 'ibo',
  2122. 'ii': 'iii',
  2123. 'ik': 'ipk',
  2124. 'io': 'ido',
  2125. 'is': 'isl',
  2126. 'it': 'ita',
  2127. 'iu': 'iku',
  2128. 'ja': 'jpn',
  2129. 'jv': 'jav',
  2130. 'ka': 'kat',
  2131. 'kg': 'kon',
  2132. 'ki': 'kik',
  2133. 'kj': 'kua',
  2134. 'kk': 'kaz',
  2135. 'kl': 'kal',
  2136. 'km': 'khm',
  2137. 'kn': 'kan',
  2138. 'ko': 'kor',
  2139. 'kr': 'kau',
  2140. 'ks': 'kas',
  2141. 'ku': 'kur',
  2142. 'kv': 'kom',
  2143. 'kw': 'cor',
  2144. 'ky': 'kir',
  2145. 'la': 'lat',
  2146. 'lb': 'ltz',
  2147. 'lg': 'lug',
  2148. 'li': 'lim',
  2149. 'ln': 'lin',
  2150. 'lo': 'lao',
  2151. 'lt': 'lit',
  2152. 'lu': 'lub',
  2153. 'lv': 'lav',
  2154. 'mg': 'mlg',
  2155. 'mh': 'mah',
  2156. 'mi': 'mri',
  2157. 'mk': 'mkd',
  2158. 'ml': 'mal',
  2159. 'mn': 'mon',
  2160. 'mr': 'mar',
  2161. 'ms': 'msa',
  2162. 'mt': 'mlt',
  2163. 'my': 'mya',
  2164. 'na': 'nau',
  2165. 'nb': 'nob',
  2166. 'nd': 'nde',
  2167. 'ne': 'nep',
  2168. 'ng': 'ndo',
  2169. 'nl': 'nld',
  2170. 'nn': 'nno',
  2171. 'no': 'nor',
  2172. 'nr': 'nbl',
  2173. 'nv': 'nav',
  2174. 'ny': 'nya',
  2175. 'oc': 'oci',
  2176. 'oj': 'oji',
  2177. 'om': 'orm',
  2178. 'or': 'ori',
  2179. 'os': 'oss',
  2180. 'pa': 'pan',
  2181. 'pi': 'pli',
  2182. 'pl': 'pol',
  2183. 'ps': 'pus',
  2184. 'pt': 'por',
  2185. 'qu': 'que',
  2186. 'rm': 'roh',
  2187. 'rn': 'run',
  2188. 'ro': 'ron',
  2189. 'ru': 'rus',
  2190. 'rw': 'kin',
  2191. 'sa': 'san',
  2192. 'sc': 'srd',
  2193. 'sd': 'snd',
  2194. 'se': 'sme',
  2195. 'sg': 'sag',
  2196. 'si': 'sin',
  2197. 'sk': 'slk',
  2198. 'sl': 'slv',
  2199. 'sm': 'smo',
  2200. 'sn': 'sna',
  2201. 'so': 'som',
  2202. 'sq': 'sqi',
  2203. 'sr': 'srp',
  2204. 'ss': 'ssw',
  2205. 'st': 'sot',
  2206. 'su': 'sun',
  2207. 'sv': 'swe',
  2208. 'sw': 'swa',
  2209. 'ta': 'tam',
  2210. 'te': 'tel',
  2211. 'tg': 'tgk',
  2212. 'th': 'tha',
  2213. 'ti': 'tir',
  2214. 'tk': 'tuk',
  2215. 'tl': 'tgl',
  2216. 'tn': 'tsn',
  2217. 'to': 'ton',
  2218. 'tr': 'tur',
  2219. 'ts': 'tso',
  2220. 'tt': 'tat',
  2221. 'tw': 'twi',
  2222. 'ty': 'tah',
  2223. 'ug': 'uig',
  2224. 'uk': 'ukr',
  2225. 'ur': 'urd',
  2226. 'uz': 'uzb',
  2227. 've': 'ven',
  2228. 'vi': 'vie',
  2229. 'vo': 'vol',
  2230. 'wa': 'wln',
  2231. 'wo': 'wol',
  2232. 'xh': 'xho',
  2233. 'yi': 'yid',
  2234. 'yo': 'yor',
  2235. 'za': 'zha',
  2236. 'zh': 'zho',
  2237. 'zu': 'zul',
  2238. }
  2239. @classmethod
  2240. def short2long(cls, code):
  2241. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  2242. return cls._lang_map.get(code[:2])
  2243. @classmethod
  2244. def long2short(cls, code):
  2245. """Convert language code from ISO 639-2/T to ISO 639-1"""
  2246. for short_name, long_name in cls._lang_map.items():
  2247. if long_name == code:
  2248. return short_name
  2249. class ISO3166Utils(object):
  2250. # From http://data.okfn.org/data/core/country-list
  2251. _country_map = {
  2252. 'AF': 'Afghanistan',
  2253. 'AX': 'Åland Islands',
  2254. 'AL': 'Albania',
  2255. 'DZ': 'Algeria',
  2256. 'AS': 'American Samoa',
  2257. 'AD': 'Andorra',
  2258. 'AO': 'Angola',
  2259. 'AI': 'Anguilla',
  2260. 'AQ': 'Antarctica',
  2261. 'AG': 'Antigua and Barbuda',
  2262. 'AR': 'Argentina',
  2263. 'AM': 'Armenia',
  2264. 'AW': 'Aruba',
  2265. 'AU': 'Australia',
  2266. 'AT': 'Austria',
  2267. 'AZ': 'Azerbaijan',
  2268. 'BS': 'Bahamas',
  2269. 'BH': 'Bahrain',
  2270. 'BD': 'Bangladesh',
  2271. 'BB': 'Barbados',
  2272. 'BY': 'Belarus',
  2273. 'BE': 'Belgium',
  2274. 'BZ': 'Belize',
  2275. 'BJ': 'Benin',
  2276. 'BM': 'Bermuda',
  2277. 'BT': 'Bhutan',
  2278. 'BO': 'Bolivia, Plurinational State of',
  2279. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2280. 'BA': 'Bosnia and Herzegovina',
  2281. 'BW': 'Botswana',
  2282. 'BV': 'Bouvet Island',
  2283. 'BR': 'Brazil',
  2284. 'IO': 'British Indian Ocean Territory',
  2285. 'BN': 'Brunei Darussalam',
  2286. 'BG': 'Bulgaria',
  2287. 'BF': 'Burkina Faso',
  2288. 'BI': 'Burundi',
  2289. 'KH': 'Cambodia',
  2290. 'CM': 'Cameroon',
  2291. 'CA': 'Canada',
  2292. 'CV': 'Cape Verde',
  2293. 'KY': 'Cayman Islands',
  2294. 'CF': 'Central African Republic',
  2295. 'TD': 'Chad',
  2296. 'CL': 'Chile',
  2297. 'CN': 'China',
  2298. 'CX': 'Christmas Island',
  2299. 'CC': 'Cocos (Keeling) Islands',
  2300. 'CO': 'Colombia',
  2301. 'KM': 'Comoros',
  2302. 'CG': 'Congo',
  2303. 'CD': 'Congo, the Democratic Republic of the',
  2304. 'CK': 'Cook Islands',
  2305. 'CR': 'Costa Rica',
  2306. 'CI': 'Côte d\'Ivoire',
  2307. 'HR': 'Croatia',
  2308. 'CU': 'Cuba',
  2309. 'CW': 'Curaçao',
  2310. 'CY': 'Cyprus',
  2311. 'CZ': 'Czech Republic',
  2312. 'DK': 'Denmark',
  2313. 'DJ': 'Djibouti',
  2314. 'DM': 'Dominica',
  2315. 'DO': 'Dominican Republic',
  2316. 'EC': 'Ecuador',
  2317. 'EG': 'Egypt',
  2318. 'SV': 'El Salvador',
  2319. 'GQ': 'Equatorial Guinea',
  2320. 'ER': 'Eritrea',
  2321. 'EE': 'Estonia',
  2322. 'ET': 'Ethiopia',
  2323. 'FK': 'Falkland Islands (Malvinas)',
  2324. 'FO': 'Faroe Islands',
  2325. 'FJ': 'Fiji',
  2326. 'FI': 'Finland',
  2327. 'FR': 'France',
  2328. 'GF': 'French Guiana',
  2329. 'PF': 'French Polynesia',
  2330. 'TF': 'French Southern Territories',
  2331. 'GA': 'Gabon',
  2332. 'GM': 'Gambia',
  2333. 'GE': 'Georgia',
  2334. 'DE': 'Germany',
  2335. 'GH': 'Ghana',
  2336. 'GI': 'Gibraltar',
  2337. 'GR': 'Greece',
  2338. 'GL': 'Greenland',
  2339. 'GD': 'Grenada',
  2340. 'GP': 'Guadeloupe',
  2341. 'GU': 'Guam',
  2342. 'GT': 'Guatemala',
  2343. 'GG': 'Guernsey',
  2344. 'GN': 'Guinea',
  2345. 'GW': 'Guinea-Bissau',
  2346. 'GY': 'Guyana',
  2347. 'HT': 'Haiti',
  2348. 'HM': 'Heard Island and McDonald Islands',
  2349. 'VA': 'Holy See (Vatican City State)',
  2350. 'HN': 'Honduras',
  2351. 'HK': 'Hong Kong',
  2352. 'HU': 'Hungary',
  2353. 'IS': 'Iceland',
  2354. 'IN': 'India',
  2355. 'ID': 'Indonesia',
  2356. 'IR': 'Iran, Islamic Republic of',
  2357. 'IQ': 'Iraq',
  2358. 'IE': 'Ireland',
  2359. 'IM': 'Isle of Man',
  2360. 'IL': 'Israel',
  2361. 'IT': 'Italy',
  2362. 'JM': 'Jamaica',
  2363. 'JP': 'Japan',
  2364. 'JE': 'Jersey',
  2365. 'JO': 'Jordan',
  2366. 'KZ': 'Kazakhstan',
  2367. 'KE': 'Kenya',
  2368. 'KI': 'Kiribati',
  2369. 'KP': 'Korea, Democratic People\'s Republic of',
  2370. 'KR': 'Korea, Republic of',
  2371. 'KW': 'Kuwait',
  2372. 'KG': 'Kyrgyzstan',
  2373. 'LA': 'Lao People\'s Democratic Republic',
  2374. 'LV': 'Latvia',
  2375. 'LB': 'Lebanon',
  2376. 'LS': 'Lesotho',
  2377. 'LR': 'Liberia',
  2378. 'LY': 'Libya',
  2379. 'LI': 'Liechtenstein',
  2380. 'LT': 'Lithuania',
  2381. 'LU': 'Luxembourg',
  2382. 'MO': 'Macao',
  2383. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2384. 'MG': 'Madagascar',
  2385. 'MW': 'Malawi',
  2386. 'MY': 'Malaysia',
  2387. 'MV': 'Maldives',
  2388. 'ML': 'Mali',
  2389. 'MT': 'Malta',
  2390. 'MH': 'Marshall Islands',
  2391. 'MQ': 'Martinique',
  2392. 'MR': 'Mauritania',
  2393. 'MU': 'Mauritius',
  2394. 'YT': 'Mayotte',
  2395. 'MX': 'Mexico',
  2396. 'FM': 'Micronesia, Federated States of',
  2397. 'MD': 'Moldova, Republic of',
  2398. 'MC': 'Monaco',
  2399. 'MN': 'Mongolia',
  2400. 'ME': 'Montenegro',
  2401. 'MS': 'Montserrat',
  2402. 'MA': 'Morocco',
  2403. 'MZ': 'Mozambique',
  2404. 'MM': 'Myanmar',
  2405. 'NA': 'Namibia',
  2406. 'NR': 'Nauru',
  2407. 'NP': 'Nepal',
  2408. 'NL': 'Netherlands',
  2409. 'NC': 'New Caledonia',
  2410. 'NZ': 'New Zealand',
  2411. 'NI': 'Nicaragua',
  2412. 'NE': 'Niger',
  2413. 'NG': 'Nigeria',
  2414. 'NU': 'Niue',
  2415. 'NF': 'Norfolk Island',
  2416. 'MP': 'Northern Mariana Islands',
  2417. 'NO': 'Norway',
  2418. 'OM': 'Oman',
  2419. 'PK': 'Pakistan',
  2420. 'PW': 'Palau',
  2421. 'PS': 'Palestine, State of',
  2422. 'PA': 'Panama',
  2423. 'PG': 'Papua New Guinea',
  2424. 'PY': 'Paraguay',
  2425. 'PE': 'Peru',
  2426. 'PH': 'Philippines',
  2427. 'PN': 'Pitcairn',
  2428. 'PL': 'Poland',
  2429. 'PT': 'Portugal',
  2430. 'PR': 'Puerto Rico',
  2431. 'QA': 'Qatar',
  2432. 'RE': 'Réunion',
  2433. 'RO': 'Romania',
  2434. 'RU': 'Russian Federation',
  2435. 'RW': 'Rwanda',
  2436. 'BL': 'Saint Barthélemy',
  2437. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2438. 'KN': 'Saint Kitts and Nevis',
  2439. 'LC': 'Saint Lucia',
  2440. 'MF': 'Saint Martin (French part)',
  2441. 'PM': 'Saint Pierre and Miquelon',
  2442. 'VC': 'Saint Vincent and the Grenadines',
  2443. 'WS': 'Samoa',
  2444. 'SM': 'San Marino',
  2445. 'ST': 'Sao Tome and Principe',
  2446. 'SA': 'Saudi Arabia',
  2447. 'SN': 'Senegal',
  2448. 'RS': 'Serbia',
  2449. 'SC': 'Seychelles',
  2450. 'SL': 'Sierra Leone',
  2451. 'SG': 'Singapore',
  2452. 'SX': 'Sint Maarten (Dutch part)',
  2453. 'SK': 'Slovakia',
  2454. 'SI': 'Slovenia',
  2455. 'SB': 'Solomon Islands',
  2456. 'SO': 'Somalia',
  2457. 'ZA': 'South Africa',
  2458. 'GS': 'South Georgia and the South Sandwich Islands',
  2459. 'SS': 'South Sudan',
  2460. 'ES': 'Spain',
  2461. 'LK': 'Sri Lanka',
  2462. 'SD': 'Sudan',
  2463. 'SR': 'Suriname',
  2464. 'SJ': 'Svalbard and Jan Mayen',
  2465. 'SZ': 'Swaziland',
  2466. 'SE': 'Sweden',
  2467. 'CH': 'Switzerland',
  2468. 'SY': 'Syrian Arab Republic',
  2469. 'TW': 'Taiwan, Province of China',
  2470. 'TJ': 'Tajikistan',
  2471. 'TZ': 'Tanzania, United Republic of',
  2472. 'TH': 'Thailand',
  2473. 'TL': 'Timor-Leste',
  2474. 'TG': 'Togo',
  2475. 'TK': 'Tokelau',
  2476. 'TO': 'Tonga',
  2477. 'TT': 'Trinidad and Tobago',
  2478. 'TN': 'Tunisia',
  2479. 'TR': 'Turkey',
  2480. 'TM': 'Turkmenistan',
  2481. 'TC': 'Turks and Caicos Islands',
  2482. 'TV': 'Tuvalu',
  2483. 'UG': 'Uganda',
  2484. 'UA': 'Ukraine',
  2485. 'AE': 'United Arab Emirates',
  2486. 'GB': 'United Kingdom',
  2487. 'US': 'United States',
  2488. 'UM': 'United States Minor Outlying Islands',
  2489. 'UY': 'Uruguay',
  2490. 'UZ': 'Uzbekistan',
  2491. 'VU': 'Vanuatu',
  2492. 'VE': 'Venezuela, Bolivarian Republic of',
  2493. 'VN': 'Viet Nam',
  2494. 'VG': 'Virgin Islands, British',
  2495. 'VI': 'Virgin Islands, U.S.',
  2496. 'WF': 'Wallis and Futuna',
  2497. 'EH': 'Western Sahara',
  2498. 'YE': 'Yemen',
  2499. 'ZM': 'Zambia',
  2500. 'ZW': 'Zimbabwe',
  2501. }
  2502. @classmethod
  2503. def short2full(cls, code):
  2504. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2505. return cls._country_map.get(code.upper())
  2506. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2507. def __init__(self, proxies=None):
  2508. # Set default handlers
  2509. for type in ('http', 'https'):
  2510. setattr(self, '%s_open' % type,
  2511. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2512. meth(r, proxy, type))
  2513. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2514. def proxy_open(self, req, proxy, type):
  2515. req_proxy = req.headers.get('Ytdl-request-proxy')
  2516. if req_proxy is not None:
  2517. proxy = req_proxy
  2518. del req.headers['Ytdl-request-proxy']
  2519. if proxy == '__noproxy__':
  2520. return None # No Proxy
  2521. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  2522. req.add_header('Ytdl-socks-proxy', proxy)
  2523. # youtube-dl's http/https handlers do wrapping the socket with socks
  2524. return None
  2525. return compat_urllib_request.ProxyHandler.proxy_open(
  2526. self, req, proxy, type)
  2527. def ohdave_rsa_encrypt(data, exponent, modulus):
  2528. '''
  2529. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  2530. Input:
  2531. data: data to encrypt, bytes-like object
  2532. exponent, modulus: parameter e and N of RSA algorithm, both integer
  2533. Output: hex string of encrypted data
  2534. Limitation: supports one block encryption only
  2535. '''
  2536. payload = int(binascii.hexlify(data[::-1]), 16)
  2537. encrypted = pow(payload, exponent, modulus)
  2538. return '%x' % encrypted
  2539. def encode_base_n(num, n, table=None):
  2540. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  2541. if not table:
  2542. table = FULL_TABLE[:n]
  2543. if n > len(table):
  2544. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  2545. if num == 0:
  2546. return table[0]
  2547. ret = ''
  2548. while num:
  2549. ret = table[num % n] + ret
  2550. num = num // n
  2551. return ret
  2552. def decode_packed_codes(code):
  2553. mobj = re.search(PACKED_CODES_RE, code)
  2554. obfucasted_code, base, count, symbols = mobj.groups()
  2555. base = int(base)
  2556. count = int(count)
  2557. symbols = symbols.split('|')
  2558. symbol_table = {}
  2559. while count:
  2560. count -= 1
  2561. base_n_count = encode_base_n(count, base)
  2562. symbol_table[base_n_count] = symbols[count] or base_n_count
  2563. return re.sub(
  2564. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  2565. obfucasted_code)
  2566. def parse_m3u8_attributes(attrib):
  2567. info = {}
  2568. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  2569. if val.startswith('"'):
  2570. val = val[1:-1]
  2571. info[key] = val
  2572. return info
  2573. def urshift(val, n):
  2574. return val >> n if val >= 0 else (val + 0x100000000) >> n
  2575. # Based on png2str() written by @gdkchan and improved by @yokrysty
  2576. # Originally posted at https://github.com/rg3/youtube-dl/issues/9706
  2577. def decode_png(png_data):
  2578. # Reference: https://www.w3.org/TR/PNG/
  2579. header = png_data[8:]
  2580. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  2581. raise IOError('Not a valid PNG file.')
  2582. int_map = {1: '>B', 2: '>H', 4: '>I'}
  2583. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  2584. chunks = []
  2585. while header:
  2586. length = unpack_integer(header[:4])
  2587. header = header[4:]
  2588. chunk_type = header[:4]
  2589. header = header[4:]
  2590. chunk_data = header[:length]
  2591. header = header[length:]
  2592. header = header[4:] # Skip CRC
  2593. chunks.append({
  2594. 'type': chunk_type,
  2595. 'length': length,
  2596. 'data': chunk_data
  2597. })
  2598. ihdr = chunks[0]['data']
  2599. width = unpack_integer(ihdr[:4])
  2600. height = unpack_integer(ihdr[4:8])
  2601. idat = b''
  2602. for chunk in chunks:
  2603. if chunk['type'] == b'IDAT':
  2604. idat += chunk['data']
  2605. if not idat:
  2606. raise IOError('Unable to read PNG data.')
  2607. decompressed_data = bytearray(zlib.decompress(idat))
  2608. stride = width * 3
  2609. pixels = []
  2610. def _get_pixel(idx):
  2611. x = idx % stride
  2612. y = idx // stride
  2613. return pixels[y][x]
  2614. for y in range(height):
  2615. basePos = y * (1 + stride)
  2616. filter_type = decompressed_data[basePos]
  2617. current_row = []
  2618. pixels.append(current_row)
  2619. for x in range(stride):
  2620. color = decompressed_data[1 + basePos + x]
  2621. basex = y * stride + x
  2622. left = 0
  2623. up = 0
  2624. if x > 2:
  2625. left = _get_pixel(basex - 3)
  2626. if y > 0:
  2627. up = _get_pixel(basex - stride)
  2628. if filter_type == 1: # Sub
  2629. color = (color + left) & 0xff
  2630. elif filter_type == 2: # Up
  2631. color = (color + up) & 0xff
  2632. elif filter_type == 3: # Average
  2633. color = (color + ((left + up) >> 1)) & 0xff
  2634. elif filter_type == 4: # Paeth
  2635. a = left
  2636. b = up
  2637. c = 0
  2638. if x > 2 and y > 0:
  2639. c = _get_pixel(basex - stride - 3)
  2640. p = a + b - c
  2641. pa = abs(p - a)
  2642. pb = abs(p - b)
  2643. pc = abs(p - c)
  2644. if pa <= pb and pa <= pc:
  2645. color = (color + a) & 0xff
  2646. elif pb <= pc:
  2647. color = (color + b) & 0xff
  2648. else:
  2649. color = (color + c) & 0xff
  2650. current_row.append(color)
  2651. return width, height, pixels
  2652. def write_xattr(path, key, value):
  2653. # This mess below finds the best xattr tool for the job
  2654. try:
  2655. # try the pyxattr module...
  2656. import xattr
  2657. if hasattr(xattr, 'set'): # pyxattr
  2658. # Unicode arguments are not supported in python-pyxattr until
  2659. # version 0.5.0
  2660. # See https://github.com/rg3/youtube-dl/issues/5498
  2661. pyxattr_required_version = '0.5.0'
  2662. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  2663. # TODO: fallback to CLI tools
  2664. raise XAttrUnavailableError(
  2665. 'python-pyxattr is detected but is too old. '
  2666. 'youtube-dl requires %s or above while your version is %s. '
  2667. 'Falling back to other xattr implementations' % (
  2668. pyxattr_required_version, xattr.__version__))
  2669. setxattr = xattr.set
  2670. else: # xattr
  2671. setxattr = xattr.setxattr
  2672. try:
  2673. setxattr(path, key, value)
  2674. except EnvironmentError as e:
  2675. raise XAttrMetadataError(e.errno, e.strerror)
  2676. except ImportError:
  2677. if compat_os_name == 'nt':
  2678. # Write xattrs to NTFS Alternate Data Streams:
  2679. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  2680. assert ':' not in key
  2681. assert os.path.exists(path)
  2682. ads_fn = path + ':' + key
  2683. try:
  2684. with open(ads_fn, 'wb') as f:
  2685. f.write(value)
  2686. except EnvironmentError as e:
  2687. raise XAttrMetadataError(e.errno, e.strerror)
  2688. else:
  2689. user_has_setfattr = check_executable('setfattr', ['--version'])
  2690. user_has_xattr = check_executable('xattr', ['-h'])
  2691. if user_has_setfattr or user_has_xattr:
  2692. value = value.decode('utf-8')
  2693. if user_has_setfattr:
  2694. executable = 'setfattr'
  2695. opts = ['-n', key, '-v', value]
  2696. elif user_has_xattr:
  2697. executable = 'xattr'
  2698. opts = ['-w', key, value]
  2699. cmd = ([encodeFilename(executable, True)] +
  2700. [encodeArgument(o) for o in opts] +
  2701. [encodeFilename(path, True)])
  2702. try:
  2703. p = subprocess.Popen(
  2704. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  2705. except EnvironmentError as e:
  2706. raise XAttrMetadataError(e.errno, e.strerror)
  2707. stdout, stderr = p.communicate()
  2708. stderr = stderr.decode('utf-8', 'replace')
  2709. if p.returncode != 0:
  2710. raise XAttrMetadataError(p.returncode, stderr)
  2711. else:
  2712. # On Unix, and can't find pyxattr, setfattr, or xattr.
  2713. if sys.platform.startswith('linux'):
  2714. raise XAttrUnavailableError(
  2715. "Couldn't find a tool to set the xattrs. "
  2716. "Install either the python 'pyxattr' or 'xattr' "
  2717. "modules, or the GNU 'attr' package "
  2718. "(which contains the 'setfattr' tool).")
  2719. else:
  2720. raise XAttrUnavailableError(
  2721. "Couldn't find a tool to set the xattrs. "
  2722. "Install either the python 'xattr' module, "
  2723. "or the 'xattr' binary.")