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.

3276 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. def fix_kv(m):
  1707. v = m.group(0)
  1708. if v in ('true', 'false', 'null'):
  1709. return v
  1710. elif v.startswith('/*') or v == ',':
  1711. return ""
  1712. if v[0] in ("'", '"'):
  1713. v = re.sub(r'(?s)\\.|"', lambda m: {
  1714. '"': '\\"',
  1715. "\\'": "'",
  1716. '\\\n': '',
  1717. '\\x': '\\u00',
  1718. }.get(m.group(0), m.group(0)), v[1:-1])
  1719. INTEGER_TABLE = (
  1720. (r'^(0[xX][0-9a-fA-F]+)\s*:?$', 16),
  1721. (r'^(0+[0-7]+)\s*:?$', 8),
  1722. )
  1723. for regex, base in INTEGER_TABLE:
  1724. im = re.match(regex, v)
  1725. if im:
  1726. i = int(im.group(1), base)
  1727. return '"%d":' % i if v.endswith(':') else '%d' % i
  1728. return '"%s"' % v
  1729. return re.sub(r'''(?sx)
  1730. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  1731. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  1732. /\*.*?\*/|,(?=\s*[\]}])|
  1733. [a-zA-Z_][.a-zA-Z_0-9]*|
  1734. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
  1735. [0-9]+(?=\s*:)
  1736. ''', fix_kv, code)
  1737. def qualities(quality_ids):
  1738. """ Get a numeric quality value out of a list of possible values """
  1739. def q(qid):
  1740. try:
  1741. return quality_ids.index(qid)
  1742. except ValueError:
  1743. return -1
  1744. return q
  1745. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1746. def limit_length(s, length):
  1747. """ Add ellipses to overly long strings """
  1748. if s is None:
  1749. return None
  1750. ELLIPSES = '...'
  1751. if len(s) > length:
  1752. return s[:length - len(ELLIPSES)] + ELLIPSES
  1753. return s
  1754. def version_tuple(v):
  1755. return tuple(int(e) for e in re.split(r'[-.]', v))
  1756. def is_outdated_version(version, limit, assume_new=True):
  1757. if not version:
  1758. return not assume_new
  1759. try:
  1760. return version_tuple(version) < version_tuple(limit)
  1761. except ValueError:
  1762. return not assume_new
  1763. def ytdl_is_updateable():
  1764. """ Returns if youtube-dl can be updated with -U """
  1765. from zipimport import zipimporter
  1766. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1767. def args_to_str(args):
  1768. # Get a short string representation for a subprocess command
  1769. return ' '.join(compat_shlex_quote(a) for a in args)
  1770. def error_to_compat_str(err):
  1771. err_str = str(err)
  1772. # On python 2 error byte string must be decoded with proper
  1773. # encoding rather than ascii
  1774. if sys.version_info[0] < 3:
  1775. err_str = err_str.decode(preferredencoding())
  1776. return err_str
  1777. def mimetype2ext(mt):
  1778. if mt is None:
  1779. return None
  1780. ext = {
  1781. 'audio/mp4': 'm4a',
  1782. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  1783. # it's the most popular one
  1784. 'audio/mpeg': 'mp3',
  1785. }.get(mt)
  1786. if ext is not None:
  1787. return ext
  1788. _, _, res = mt.rpartition('/')
  1789. res = res.split(';')[0].strip().lower()
  1790. return {
  1791. '3gpp': '3gp',
  1792. 'smptett+xml': 'tt',
  1793. 'srt': 'srt',
  1794. 'ttaf+xml': 'dfxp',
  1795. 'ttml+xml': 'ttml',
  1796. 'vtt': 'vtt',
  1797. 'x-flv': 'flv',
  1798. 'x-mp4-fragmented': 'mp4',
  1799. 'x-ms-wmv': 'wmv',
  1800. 'mpegurl': 'm3u8',
  1801. 'x-mpegurl': 'm3u8',
  1802. 'vnd.apple.mpegurl': 'm3u8',
  1803. 'dash+xml': 'mpd',
  1804. 'f4m': 'f4m',
  1805. 'f4m+xml': 'f4m',
  1806. 'hds+xml': 'f4m',
  1807. 'vnd.ms-sstr+xml': 'ism',
  1808. 'quicktime': 'mov',
  1809. }.get(res, res)
  1810. def parse_codecs(codecs_str):
  1811. # http://tools.ietf.org/html/rfc6381
  1812. if not codecs_str:
  1813. return {}
  1814. splited_codecs = list(filter(None, map(
  1815. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  1816. vcodec, acodec = None, None
  1817. for full_codec in splited_codecs:
  1818. codec = full_codec.split('.')[0]
  1819. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v'):
  1820. if not vcodec:
  1821. vcodec = full_codec
  1822. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3'):
  1823. if not acodec:
  1824. acodec = full_codec
  1825. else:
  1826. write_string('WARNING: Unknown codec %s' % full_codec, sys.stderr)
  1827. if not vcodec and not acodec:
  1828. if len(splited_codecs) == 2:
  1829. return {
  1830. 'vcodec': vcodec,
  1831. 'acodec': acodec,
  1832. }
  1833. elif len(splited_codecs) == 1:
  1834. return {
  1835. 'vcodec': 'none',
  1836. 'acodec': vcodec,
  1837. }
  1838. else:
  1839. return {
  1840. 'vcodec': vcodec or 'none',
  1841. 'acodec': acodec or 'none',
  1842. }
  1843. return {}
  1844. def urlhandle_detect_ext(url_handle):
  1845. getheader = url_handle.headers.get
  1846. cd = getheader('Content-Disposition')
  1847. if cd:
  1848. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1849. if m:
  1850. e = determine_ext(m.group('filename'), default_ext=None)
  1851. if e:
  1852. return e
  1853. return mimetype2ext(getheader('Content-Type'))
  1854. def encode_data_uri(data, mime_type):
  1855. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1856. def age_restricted(content_limit, age_limit):
  1857. """ Returns True iff the content should be blocked """
  1858. if age_limit is None: # No limit set
  1859. return False
  1860. if content_limit is None:
  1861. return False # Content available for everyone
  1862. return age_limit < content_limit
  1863. def is_html(first_bytes):
  1864. """ Detect whether a file contains HTML by examining its first bytes. """
  1865. BOMS = [
  1866. (b'\xef\xbb\xbf', 'utf-8'),
  1867. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1868. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1869. (b'\xff\xfe', 'utf-16-le'),
  1870. (b'\xfe\xff', 'utf-16-be'),
  1871. ]
  1872. for bom, enc in BOMS:
  1873. if first_bytes.startswith(bom):
  1874. s = first_bytes[len(bom):].decode(enc, 'replace')
  1875. break
  1876. else:
  1877. s = first_bytes.decode('utf-8', 'replace')
  1878. return re.match(r'^\s*<', s)
  1879. def determine_protocol(info_dict):
  1880. protocol = info_dict.get('protocol')
  1881. if protocol is not None:
  1882. return protocol
  1883. url = info_dict['url']
  1884. if url.startswith('rtmp'):
  1885. return 'rtmp'
  1886. elif url.startswith('mms'):
  1887. return 'mms'
  1888. elif url.startswith('rtsp'):
  1889. return 'rtsp'
  1890. ext = determine_ext(url)
  1891. if ext == 'm3u8':
  1892. return 'm3u8'
  1893. elif ext == 'f4m':
  1894. return 'f4m'
  1895. return compat_urllib_parse_urlparse(url).scheme
  1896. def render_table(header_row, data):
  1897. """ Render a list of rows, each as a list of values """
  1898. table = [header_row] + data
  1899. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1900. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1901. return '\n'.join(format_str % tuple(row) for row in table)
  1902. def _match_one(filter_part, dct):
  1903. COMPARISON_OPERATORS = {
  1904. '<': operator.lt,
  1905. '<=': operator.le,
  1906. '>': operator.gt,
  1907. '>=': operator.ge,
  1908. '=': operator.eq,
  1909. '!=': operator.ne,
  1910. }
  1911. operator_rex = re.compile(r'''(?x)\s*
  1912. (?P<key>[a-z_]+)
  1913. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1914. (?:
  1915. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1916. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1917. )
  1918. \s*$
  1919. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1920. m = operator_rex.search(filter_part)
  1921. if m:
  1922. op = COMPARISON_OPERATORS[m.group('op')]
  1923. actual_value = dct.get(m.group('key'))
  1924. if (m.group('strval') is not None or
  1925. # If the original field is a string and matching comparisonvalue is
  1926. # a number we should respect the origin of the original field
  1927. # and process comparison value as a string (see
  1928. # https://github.com/rg3/youtube-dl/issues/11082).
  1929. actual_value is not None and m.group('intval') is not None and
  1930. isinstance(actual_value, compat_str)):
  1931. if m.group('op') not in ('=', '!='):
  1932. raise ValueError(
  1933. 'Operator %s does not support string values!' % m.group('op'))
  1934. comparison_value = m.group('strval') or m.group('intval')
  1935. else:
  1936. try:
  1937. comparison_value = int(m.group('intval'))
  1938. except ValueError:
  1939. comparison_value = parse_filesize(m.group('intval'))
  1940. if comparison_value is None:
  1941. comparison_value = parse_filesize(m.group('intval') + 'B')
  1942. if comparison_value is None:
  1943. raise ValueError(
  1944. 'Invalid integer value %r in filter part %r' % (
  1945. m.group('intval'), filter_part))
  1946. if actual_value is None:
  1947. return m.group('none_inclusive')
  1948. return op(actual_value, comparison_value)
  1949. UNARY_OPERATORS = {
  1950. '': lambda v: v is not None,
  1951. '!': lambda v: v is None,
  1952. }
  1953. operator_rex = re.compile(r'''(?x)\s*
  1954. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1955. \s*$
  1956. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1957. m = operator_rex.search(filter_part)
  1958. if m:
  1959. op = UNARY_OPERATORS[m.group('op')]
  1960. actual_value = dct.get(m.group('key'))
  1961. return op(actual_value)
  1962. raise ValueError('Invalid filter part %r' % filter_part)
  1963. def match_str(filter_str, dct):
  1964. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1965. return all(
  1966. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1967. def match_filter_func(filter_str):
  1968. def _match_func(info_dict):
  1969. if match_str(filter_str, info_dict):
  1970. return None
  1971. else:
  1972. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1973. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1974. return _match_func
  1975. def parse_dfxp_time_expr(time_expr):
  1976. if not time_expr:
  1977. return
  1978. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1979. if mobj:
  1980. return float(mobj.group('time_offset'))
  1981. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  1982. if mobj:
  1983. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  1984. def srt_subtitles_timecode(seconds):
  1985. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1986. def dfxp2srt(dfxp_data):
  1987. _x = functools.partial(xpath_with_ns, ns_map={
  1988. 'ttml': 'http://www.w3.org/ns/ttml',
  1989. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1990. 'ttaf1_0604': 'http://www.w3.org/2006/04/ttaf1',
  1991. })
  1992. class TTMLPElementParser(object):
  1993. out = ''
  1994. def start(self, tag, attrib):
  1995. if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1996. self.out += '\n'
  1997. def end(self, tag):
  1998. pass
  1999. def data(self, data):
  2000. self.out += data
  2001. def close(self):
  2002. return self.out.strip()
  2003. def parse_node(node):
  2004. target = TTMLPElementParser()
  2005. parser = xml.etree.ElementTree.XMLParser(target=target)
  2006. parser.feed(xml.etree.ElementTree.tostring(node))
  2007. return parser.close()
  2008. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  2009. out = []
  2010. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall(_x('.//ttaf1_0604:p')) or dfxp.findall('.//p')
  2011. if not paras:
  2012. raise ValueError('Invalid dfxp/TTML subtitle')
  2013. for para, index in zip(paras, itertools.count(1)):
  2014. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  2015. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  2016. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  2017. if begin_time is None:
  2018. continue
  2019. if not end_time:
  2020. if not dur:
  2021. continue
  2022. end_time = begin_time + dur
  2023. out.append('%d\n%s --> %s\n%s\n\n' % (
  2024. index,
  2025. srt_subtitles_timecode(begin_time),
  2026. srt_subtitles_timecode(end_time),
  2027. parse_node(para)))
  2028. return ''.join(out)
  2029. def cli_option(params, command_option, param):
  2030. param = params.get(param)
  2031. if param:
  2032. param = compat_str(param)
  2033. return [command_option, param] if param is not None else []
  2034. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  2035. param = params.get(param)
  2036. assert isinstance(param, bool)
  2037. if separator:
  2038. return [command_option + separator + (true_value if param else false_value)]
  2039. return [command_option, true_value if param else false_value]
  2040. def cli_valueless_option(params, command_option, param, expected_value=True):
  2041. param = params.get(param)
  2042. return [command_option] if param == expected_value else []
  2043. def cli_configuration_args(params, param, default=[]):
  2044. ex_args = params.get(param)
  2045. if ex_args is None:
  2046. return default
  2047. assert isinstance(ex_args, list)
  2048. return ex_args
  2049. class ISO639Utils(object):
  2050. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  2051. _lang_map = {
  2052. 'aa': 'aar',
  2053. 'ab': 'abk',
  2054. 'ae': 'ave',
  2055. 'af': 'afr',
  2056. 'ak': 'aka',
  2057. 'am': 'amh',
  2058. 'an': 'arg',
  2059. 'ar': 'ara',
  2060. 'as': 'asm',
  2061. 'av': 'ava',
  2062. 'ay': 'aym',
  2063. 'az': 'aze',
  2064. 'ba': 'bak',
  2065. 'be': 'bel',
  2066. 'bg': 'bul',
  2067. 'bh': 'bih',
  2068. 'bi': 'bis',
  2069. 'bm': 'bam',
  2070. 'bn': 'ben',
  2071. 'bo': 'bod',
  2072. 'br': 'bre',
  2073. 'bs': 'bos',
  2074. 'ca': 'cat',
  2075. 'ce': 'che',
  2076. 'ch': 'cha',
  2077. 'co': 'cos',
  2078. 'cr': 'cre',
  2079. 'cs': 'ces',
  2080. 'cu': 'chu',
  2081. 'cv': 'chv',
  2082. 'cy': 'cym',
  2083. 'da': 'dan',
  2084. 'de': 'deu',
  2085. 'dv': 'div',
  2086. 'dz': 'dzo',
  2087. 'ee': 'ewe',
  2088. 'el': 'ell',
  2089. 'en': 'eng',
  2090. 'eo': 'epo',
  2091. 'es': 'spa',
  2092. 'et': 'est',
  2093. 'eu': 'eus',
  2094. 'fa': 'fas',
  2095. 'ff': 'ful',
  2096. 'fi': 'fin',
  2097. 'fj': 'fij',
  2098. 'fo': 'fao',
  2099. 'fr': 'fra',
  2100. 'fy': 'fry',
  2101. 'ga': 'gle',
  2102. 'gd': 'gla',
  2103. 'gl': 'glg',
  2104. 'gn': 'grn',
  2105. 'gu': 'guj',
  2106. 'gv': 'glv',
  2107. 'ha': 'hau',
  2108. 'he': 'heb',
  2109. 'hi': 'hin',
  2110. 'ho': 'hmo',
  2111. 'hr': 'hrv',
  2112. 'ht': 'hat',
  2113. 'hu': 'hun',
  2114. 'hy': 'hye',
  2115. 'hz': 'her',
  2116. 'ia': 'ina',
  2117. 'id': 'ind',
  2118. 'ie': 'ile',
  2119. 'ig': 'ibo',
  2120. 'ii': 'iii',
  2121. 'ik': 'ipk',
  2122. 'io': 'ido',
  2123. 'is': 'isl',
  2124. 'it': 'ita',
  2125. 'iu': 'iku',
  2126. 'ja': 'jpn',
  2127. 'jv': 'jav',
  2128. 'ka': 'kat',
  2129. 'kg': 'kon',
  2130. 'ki': 'kik',
  2131. 'kj': 'kua',
  2132. 'kk': 'kaz',
  2133. 'kl': 'kal',
  2134. 'km': 'khm',
  2135. 'kn': 'kan',
  2136. 'ko': 'kor',
  2137. 'kr': 'kau',
  2138. 'ks': 'kas',
  2139. 'ku': 'kur',
  2140. 'kv': 'kom',
  2141. 'kw': 'cor',
  2142. 'ky': 'kir',
  2143. 'la': 'lat',
  2144. 'lb': 'ltz',
  2145. 'lg': 'lug',
  2146. 'li': 'lim',
  2147. 'ln': 'lin',
  2148. 'lo': 'lao',
  2149. 'lt': 'lit',
  2150. 'lu': 'lub',
  2151. 'lv': 'lav',
  2152. 'mg': 'mlg',
  2153. 'mh': 'mah',
  2154. 'mi': 'mri',
  2155. 'mk': 'mkd',
  2156. 'ml': 'mal',
  2157. 'mn': 'mon',
  2158. 'mr': 'mar',
  2159. 'ms': 'msa',
  2160. 'mt': 'mlt',
  2161. 'my': 'mya',
  2162. 'na': 'nau',
  2163. 'nb': 'nob',
  2164. 'nd': 'nde',
  2165. 'ne': 'nep',
  2166. 'ng': 'ndo',
  2167. 'nl': 'nld',
  2168. 'nn': 'nno',
  2169. 'no': 'nor',
  2170. 'nr': 'nbl',
  2171. 'nv': 'nav',
  2172. 'ny': 'nya',
  2173. 'oc': 'oci',
  2174. 'oj': 'oji',
  2175. 'om': 'orm',
  2176. 'or': 'ori',
  2177. 'os': 'oss',
  2178. 'pa': 'pan',
  2179. 'pi': 'pli',
  2180. 'pl': 'pol',
  2181. 'ps': 'pus',
  2182. 'pt': 'por',
  2183. 'qu': 'que',
  2184. 'rm': 'roh',
  2185. 'rn': 'run',
  2186. 'ro': 'ron',
  2187. 'ru': 'rus',
  2188. 'rw': 'kin',
  2189. 'sa': 'san',
  2190. 'sc': 'srd',
  2191. 'sd': 'snd',
  2192. 'se': 'sme',
  2193. 'sg': 'sag',
  2194. 'si': 'sin',
  2195. 'sk': 'slk',
  2196. 'sl': 'slv',
  2197. 'sm': 'smo',
  2198. 'sn': 'sna',
  2199. 'so': 'som',
  2200. 'sq': 'sqi',
  2201. 'sr': 'srp',
  2202. 'ss': 'ssw',
  2203. 'st': 'sot',
  2204. 'su': 'sun',
  2205. 'sv': 'swe',
  2206. 'sw': 'swa',
  2207. 'ta': 'tam',
  2208. 'te': 'tel',
  2209. 'tg': 'tgk',
  2210. 'th': 'tha',
  2211. 'ti': 'tir',
  2212. 'tk': 'tuk',
  2213. 'tl': 'tgl',
  2214. 'tn': 'tsn',
  2215. 'to': 'ton',
  2216. 'tr': 'tur',
  2217. 'ts': 'tso',
  2218. 'tt': 'tat',
  2219. 'tw': 'twi',
  2220. 'ty': 'tah',
  2221. 'ug': 'uig',
  2222. 'uk': 'ukr',
  2223. 'ur': 'urd',
  2224. 'uz': 'uzb',
  2225. 've': 'ven',
  2226. 'vi': 'vie',
  2227. 'vo': 'vol',
  2228. 'wa': 'wln',
  2229. 'wo': 'wol',
  2230. 'xh': 'xho',
  2231. 'yi': 'yid',
  2232. 'yo': 'yor',
  2233. 'za': 'zha',
  2234. 'zh': 'zho',
  2235. 'zu': 'zul',
  2236. }
  2237. @classmethod
  2238. def short2long(cls, code):
  2239. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  2240. return cls._lang_map.get(code[:2])
  2241. @classmethod
  2242. def long2short(cls, code):
  2243. """Convert language code from ISO 639-2/T to ISO 639-1"""
  2244. for short_name, long_name in cls._lang_map.items():
  2245. if long_name == code:
  2246. return short_name
  2247. class ISO3166Utils(object):
  2248. # From http://data.okfn.org/data/core/country-list
  2249. _country_map = {
  2250. 'AF': 'Afghanistan',
  2251. 'AX': 'Åland Islands',
  2252. 'AL': 'Albania',
  2253. 'DZ': 'Algeria',
  2254. 'AS': 'American Samoa',
  2255. 'AD': 'Andorra',
  2256. 'AO': 'Angola',
  2257. 'AI': 'Anguilla',
  2258. 'AQ': 'Antarctica',
  2259. 'AG': 'Antigua and Barbuda',
  2260. 'AR': 'Argentina',
  2261. 'AM': 'Armenia',
  2262. 'AW': 'Aruba',
  2263. 'AU': 'Australia',
  2264. 'AT': 'Austria',
  2265. 'AZ': 'Azerbaijan',
  2266. 'BS': 'Bahamas',
  2267. 'BH': 'Bahrain',
  2268. 'BD': 'Bangladesh',
  2269. 'BB': 'Barbados',
  2270. 'BY': 'Belarus',
  2271. 'BE': 'Belgium',
  2272. 'BZ': 'Belize',
  2273. 'BJ': 'Benin',
  2274. 'BM': 'Bermuda',
  2275. 'BT': 'Bhutan',
  2276. 'BO': 'Bolivia, Plurinational State of',
  2277. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2278. 'BA': 'Bosnia and Herzegovina',
  2279. 'BW': 'Botswana',
  2280. 'BV': 'Bouvet Island',
  2281. 'BR': 'Brazil',
  2282. 'IO': 'British Indian Ocean Territory',
  2283. 'BN': 'Brunei Darussalam',
  2284. 'BG': 'Bulgaria',
  2285. 'BF': 'Burkina Faso',
  2286. 'BI': 'Burundi',
  2287. 'KH': 'Cambodia',
  2288. 'CM': 'Cameroon',
  2289. 'CA': 'Canada',
  2290. 'CV': 'Cape Verde',
  2291. 'KY': 'Cayman Islands',
  2292. 'CF': 'Central African Republic',
  2293. 'TD': 'Chad',
  2294. 'CL': 'Chile',
  2295. 'CN': 'China',
  2296. 'CX': 'Christmas Island',
  2297. 'CC': 'Cocos (Keeling) Islands',
  2298. 'CO': 'Colombia',
  2299. 'KM': 'Comoros',
  2300. 'CG': 'Congo',
  2301. 'CD': 'Congo, the Democratic Republic of the',
  2302. 'CK': 'Cook Islands',
  2303. 'CR': 'Costa Rica',
  2304. 'CI': 'Côte d\'Ivoire',
  2305. 'HR': 'Croatia',
  2306. 'CU': 'Cuba',
  2307. 'CW': 'Curaçao',
  2308. 'CY': 'Cyprus',
  2309. 'CZ': 'Czech Republic',
  2310. 'DK': 'Denmark',
  2311. 'DJ': 'Djibouti',
  2312. 'DM': 'Dominica',
  2313. 'DO': 'Dominican Republic',
  2314. 'EC': 'Ecuador',
  2315. 'EG': 'Egypt',
  2316. 'SV': 'El Salvador',
  2317. 'GQ': 'Equatorial Guinea',
  2318. 'ER': 'Eritrea',
  2319. 'EE': 'Estonia',
  2320. 'ET': 'Ethiopia',
  2321. 'FK': 'Falkland Islands (Malvinas)',
  2322. 'FO': 'Faroe Islands',
  2323. 'FJ': 'Fiji',
  2324. 'FI': 'Finland',
  2325. 'FR': 'France',
  2326. 'GF': 'French Guiana',
  2327. 'PF': 'French Polynesia',
  2328. 'TF': 'French Southern Territories',
  2329. 'GA': 'Gabon',
  2330. 'GM': 'Gambia',
  2331. 'GE': 'Georgia',
  2332. 'DE': 'Germany',
  2333. 'GH': 'Ghana',
  2334. 'GI': 'Gibraltar',
  2335. 'GR': 'Greece',
  2336. 'GL': 'Greenland',
  2337. 'GD': 'Grenada',
  2338. 'GP': 'Guadeloupe',
  2339. 'GU': 'Guam',
  2340. 'GT': 'Guatemala',
  2341. 'GG': 'Guernsey',
  2342. 'GN': 'Guinea',
  2343. 'GW': 'Guinea-Bissau',
  2344. 'GY': 'Guyana',
  2345. 'HT': 'Haiti',
  2346. 'HM': 'Heard Island and McDonald Islands',
  2347. 'VA': 'Holy See (Vatican City State)',
  2348. 'HN': 'Honduras',
  2349. 'HK': 'Hong Kong',
  2350. 'HU': 'Hungary',
  2351. 'IS': 'Iceland',
  2352. 'IN': 'India',
  2353. 'ID': 'Indonesia',
  2354. 'IR': 'Iran, Islamic Republic of',
  2355. 'IQ': 'Iraq',
  2356. 'IE': 'Ireland',
  2357. 'IM': 'Isle of Man',
  2358. 'IL': 'Israel',
  2359. 'IT': 'Italy',
  2360. 'JM': 'Jamaica',
  2361. 'JP': 'Japan',
  2362. 'JE': 'Jersey',
  2363. 'JO': 'Jordan',
  2364. 'KZ': 'Kazakhstan',
  2365. 'KE': 'Kenya',
  2366. 'KI': 'Kiribati',
  2367. 'KP': 'Korea, Democratic People\'s Republic of',
  2368. 'KR': 'Korea, Republic of',
  2369. 'KW': 'Kuwait',
  2370. 'KG': 'Kyrgyzstan',
  2371. 'LA': 'Lao People\'s Democratic Republic',
  2372. 'LV': 'Latvia',
  2373. 'LB': 'Lebanon',
  2374. 'LS': 'Lesotho',
  2375. 'LR': 'Liberia',
  2376. 'LY': 'Libya',
  2377. 'LI': 'Liechtenstein',
  2378. 'LT': 'Lithuania',
  2379. 'LU': 'Luxembourg',
  2380. 'MO': 'Macao',
  2381. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2382. 'MG': 'Madagascar',
  2383. 'MW': 'Malawi',
  2384. 'MY': 'Malaysia',
  2385. 'MV': 'Maldives',
  2386. 'ML': 'Mali',
  2387. 'MT': 'Malta',
  2388. 'MH': 'Marshall Islands',
  2389. 'MQ': 'Martinique',
  2390. 'MR': 'Mauritania',
  2391. 'MU': 'Mauritius',
  2392. 'YT': 'Mayotte',
  2393. 'MX': 'Mexico',
  2394. 'FM': 'Micronesia, Federated States of',
  2395. 'MD': 'Moldova, Republic of',
  2396. 'MC': 'Monaco',
  2397. 'MN': 'Mongolia',
  2398. 'ME': 'Montenegro',
  2399. 'MS': 'Montserrat',
  2400. 'MA': 'Morocco',
  2401. 'MZ': 'Mozambique',
  2402. 'MM': 'Myanmar',
  2403. 'NA': 'Namibia',
  2404. 'NR': 'Nauru',
  2405. 'NP': 'Nepal',
  2406. 'NL': 'Netherlands',
  2407. 'NC': 'New Caledonia',
  2408. 'NZ': 'New Zealand',
  2409. 'NI': 'Nicaragua',
  2410. 'NE': 'Niger',
  2411. 'NG': 'Nigeria',
  2412. 'NU': 'Niue',
  2413. 'NF': 'Norfolk Island',
  2414. 'MP': 'Northern Mariana Islands',
  2415. 'NO': 'Norway',
  2416. 'OM': 'Oman',
  2417. 'PK': 'Pakistan',
  2418. 'PW': 'Palau',
  2419. 'PS': 'Palestine, State of',
  2420. 'PA': 'Panama',
  2421. 'PG': 'Papua New Guinea',
  2422. 'PY': 'Paraguay',
  2423. 'PE': 'Peru',
  2424. 'PH': 'Philippines',
  2425. 'PN': 'Pitcairn',
  2426. 'PL': 'Poland',
  2427. 'PT': 'Portugal',
  2428. 'PR': 'Puerto Rico',
  2429. 'QA': 'Qatar',
  2430. 'RE': 'Réunion',
  2431. 'RO': 'Romania',
  2432. 'RU': 'Russian Federation',
  2433. 'RW': 'Rwanda',
  2434. 'BL': 'Saint Barthélemy',
  2435. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2436. 'KN': 'Saint Kitts and Nevis',
  2437. 'LC': 'Saint Lucia',
  2438. 'MF': 'Saint Martin (French part)',
  2439. 'PM': 'Saint Pierre and Miquelon',
  2440. 'VC': 'Saint Vincent and the Grenadines',
  2441. 'WS': 'Samoa',
  2442. 'SM': 'San Marino',
  2443. 'ST': 'Sao Tome and Principe',
  2444. 'SA': 'Saudi Arabia',
  2445. 'SN': 'Senegal',
  2446. 'RS': 'Serbia',
  2447. 'SC': 'Seychelles',
  2448. 'SL': 'Sierra Leone',
  2449. 'SG': 'Singapore',
  2450. 'SX': 'Sint Maarten (Dutch part)',
  2451. 'SK': 'Slovakia',
  2452. 'SI': 'Slovenia',
  2453. 'SB': 'Solomon Islands',
  2454. 'SO': 'Somalia',
  2455. 'ZA': 'South Africa',
  2456. 'GS': 'South Georgia and the South Sandwich Islands',
  2457. 'SS': 'South Sudan',
  2458. 'ES': 'Spain',
  2459. 'LK': 'Sri Lanka',
  2460. 'SD': 'Sudan',
  2461. 'SR': 'Suriname',
  2462. 'SJ': 'Svalbard and Jan Mayen',
  2463. 'SZ': 'Swaziland',
  2464. 'SE': 'Sweden',
  2465. 'CH': 'Switzerland',
  2466. 'SY': 'Syrian Arab Republic',
  2467. 'TW': 'Taiwan, Province of China',
  2468. 'TJ': 'Tajikistan',
  2469. 'TZ': 'Tanzania, United Republic of',
  2470. 'TH': 'Thailand',
  2471. 'TL': 'Timor-Leste',
  2472. 'TG': 'Togo',
  2473. 'TK': 'Tokelau',
  2474. 'TO': 'Tonga',
  2475. 'TT': 'Trinidad and Tobago',
  2476. 'TN': 'Tunisia',
  2477. 'TR': 'Turkey',
  2478. 'TM': 'Turkmenistan',
  2479. 'TC': 'Turks and Caicos Islands',
  2480. 'TV': 'Tuvalu',
  2481. 'UG': 'Uganda',
  2482. 'UA': 'Ukraine',
  2483. 'AE': 'United Arab Emirates',
  2484. 'GB': 'United Kingdom',
  2485. 'US': 'United States',
  2486. 'UM': 'United States Minor Outlying Islands',
  2487. 'UY': 'Uruguay',
  2488. 'UZ': 'Uzbekistan',
  2489. 'VU': 'Vanuatu',
  2490. 'VE': 'Venezuela, Bolivarian Republic of',
  2491. 'VN': 'Viet Nam',
  2492. 'VG': 'Virgin Islands, British',
  2493. 'VI': 'Virgin Islands, U.S.',
  2494. 'WF': 'Wallis and Futuna',
  2495. 'EH': 'Western Sahara',
  2496. 'YE': 'Yemen',
  2497. 'ZM': 'Zambia',
  2498. 'ZW': 'Zimbabwe',
  2499. }
  2500. @classmethod
  2501. def short2full(cls, code):
  2502. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2503. return cls._country_map.get(code.upper())
  2504. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2505. def __init__(self, proxies=None):
  2506. # Set default handlers
  2507. for type in ('http', 'https'):
  2508. setattr(self, '%s_open' % type,
  2509. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2510. meth(r, proxy, type))
  2511. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2512. def proxy_open(self, req, proxy, type):
  2513. req_proxy = req.headers.get('Ytdl-request-proxy')
  2514. if req_proxy is not None:
  2515. proxy = req_proxy
  2516. del req.headers['Ytdl-request-proxy']
  2517. if proxy == '__noproxy__':
  2518. return None # No Proxy
  2519. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  2520. req.add_header('Ytdl-socks-proxy', proxy)
  2521. # youtube-dl's http/https handlers do wrapping the socket with socks
  2522. return None
  2523. return compat_urllib_request.ProxyHandler.proxy_open(
  2524. self, req, proxy, type)
  2525. def ohdave_rsa_encrypt(data, exponent, modulus):
  2526. '''
  2527. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  2528. Input:
  2529. data: data to encrypt, bytes-like object
  2530. exponent, modulus: parameter e and N of RSA algorithm, both integer
  2531. Output: hex string of encrypted data
  2532. Limitation: supports one block encryption only
  2533. '''
  2534. payload = int(binascii.hexlify(data[::-1]), 16)
  2535. encrypted = pow(payload, exponent, modulus)
  2536. return '%x' % encrypted
  2537. def encode_base_n(num, n, table=None):
  2538. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  2539. if not table:
  2540. table = FULL_TABLE[:n]
  2541. if n > len(table):
  2542. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  2543. if num == 0:
  2544. return table[0]
  2545. ret = ''
  2546. while num:
  2547. ret = table[num % n] + ret
  2548. num = num // n
  2549. return ret
  2550. def decode_packed_codes(code):
  2551. mobj = re.search(PACKED_CODES_RE, code)
  2552. obfucasted_code, base, count, symbols = mobj.groups()
  2553. base = int(base)
  2554. count = int(count)
  2555. symbols = symbols.split('|')
  2556. symbol_table = {}
  2557. while count:
  2558. count -= 1
  2559. base_n_count = encode_base_n(count, base)
  2560. symbol_table[base_n_count] = symbols[count] or base_n_count
  2561. return re.sub(
  2562. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  2563. obfucasted_code)
  2564. def parse_m3u8_attributes(attrib):
  2565. info = {}
  2566. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  2567. if val.startswith('"'):
  2568. val = val[1:-1]
  2569. info[key] = val
  2570. return info
  2571. def urshift(val, n):
  2572. return val >> n if val >= 0 else (val + 0x100000000) >> n
  2573. # Based on png2str() written by @gdkchan and improved by @yokrysty
  2574. # Originally posted at https://github.com/rg3/youtube-dl/issues/9706
  2575. def decode_png(png_data):
  2576. # Reference: https://www.w3.org/TR/PNG/
  2577. header = png_data[8:]
  2578. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  2579. raise IOError('Not a valid PNG file.')
  2580. int_map = {1: '>B', 2: '>H', 4: '>I'}
  2581. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  2582. chunks = []
  2583. while header:
  2584. length = unpack_integer(header[:4])
  2585. header = header[4:]
  2586. chunk_type = header[:4]
  2587. header = header[4:]
  2588. chunk_data = header[:length]
  2589. header = header[length:]
  2590. header = header[4:] # Skip CRC
  2591. chunks.append({
  2592. 'type': chunk_type,
  2593. 'length': length,
  2594. 'data': chunk_data
  2595. })
  2596. ihdr = chunks[0]['data']
  2597. width = unpack_integer(ihdr[:4])
  2598. height = unpack_integer(ihdr[4:8])
  2599. idat = b''
  2600. for chunk in chunks:
  2601. if chunk['type'] == b'IDAT':
  2602. idat += chunk['data']
  2603. if not idat:
  2604. raise IOError('Unable to read PNG data.')
  2605. decompressed_data = bytearray(zlib.decompress(idat))
  2606. stride = width * 3
  2607. pixels = []
  2608. def _get_pixel(idx):
  2609. x = idx % stride
  2610. y = idx // stride
  2611. return pixels[y][x]
  2612. for y in range(height):
  2613. basePos = y * (1 + stride)
  2614. filter_type = decompressed_data[basePos]
  2615. current_row = []
  2616. pixels.append(current_row)
  2617. for x in range(stride):
  2618. color = decompressed_data[1 + basePos + x]
  2619. basex = y * stride + x
  2620. left = 0
  2621. up = 0
  2622. if x > 2:
  2623. left = _get_pixel(basex - 3)
  2624. if y > 0:
  2625. up = _get_pixel(basex - stride)
  2626. if filter_type == 1: # Sub
  2627. color = (color + left) & 0xff
  2628. elif filter_type == 2: # Up
  2629. color = (color + up) & 0xff
  2630. elif filter_type == 3: # Average
  2631. color = (color + ((left + up) >> 1)) & 0xff
  2632. elif filter_type == 4: # Paeth
  2633. a = left
  2634. b = up
  2635. c = 0
  2636. if x > 2 and y > 0:
  2637. c = _get_pixel(basex - stride - 3)
  2638. p = a + b - c
  2639. pa = abs(p - a)
  2640. pb = abs(p - b)
  2641. pc = abs(p - c)
  2642. if pa <= pb and pa <= pc:
  2643. color = (color + a) & 0xff
  2644. elif pb <= pc:
  2645. color = (color + b) & 0xff
  2646. else:
  2647. color = (color + c) & 0xff
  2648. current_row.append(color)
  2649. return width, height, pixels
  2650. def write_xattr(path, key, value):
  2651. # This mess below finds the best xattr tool for the job
  2652. try:
  2653. # try the pyxattr module...
  2654. import xattr
  2655. if hasattr(xattr, 'set'): # pyxattr
  2656. # Unicode arguments are not supported in python-pyxattr until
  2657. # version 0.5.0
  2658. # See https://github.com/rg3/youtube-dl/issues/5498
  2659. pyxattr_required_version = '0.5.0'
  2660. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  2661. # TODO: fallback to CLI tools
  2662. raise XAttrUnavailableError(
  2663. 'python-pyxattr is detected but is too old. '
  2664. 'youtube-dl requires %s or above while your version is %s. '
  2665. 'Falling back to other xattr implementations' % (
  2666. pyxattr_required_version, xattr.__version__))
  2667. setxattr = xattr.set
  2668. else: # xattr
  2669. setxattr = xattr.setxattr
  2670. try:
  2671. setxattr(path, key, value)
  2672. except EnvironmentError as e:
  2673. raise XAttrMetadataError(e.errno, e.strerror)
  2674. except ImportError:
  2675. if compat_os_name == 'nt':
  2676. # Write xattrs to NTFS Alternate Data Streams:
  2677. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  2678. assert ':' not in key
  2679. assert os.path.exists(path)
  2680. ads_fn = path + ':' + key
  2681. try:
  2682. with open(ads_fn, 'wb') as f:
  2683. f.write(value)
  2684. except EnvironmentError as e:
  2685. raise XAttrMetadataError(e.errno, e.strerror)
  2686. else:
  2687. user_has_setfattr = check_executable('setfattr', ['--version'])
  2688. user_has_xattr = check_executable('xattr', ['-h'])
  2689. if user_has_setfattr or user_has_xattr:
  2690. value = value.decode('utf-8')
  2691. if user_has_setfattr:
  2692. executable = 'setfattr'
  2693. opts = ['-n', key, '-v', value]
  2694. elif user_has_xattr:
  2695. executable = 'xattr'
  2696. opts = ['-w', key, value]
  2697. cmd = ([encodeFilename(executable, True)] +
  2698. [encodeArgument(o) for o in opts] +
  2699. [encodeFilename(path, True)])
  2700. try:
  2701. p = subprocess.Popen(
  2702. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  2703. except EnvironmentError as e:
  2704. raise XAttrMetadataError(e.errno, e.strerror)
  2705. stdout, stderr = p.communicate()
  2706. stderr = stderr.decode('utf-8', 'replace')
  2707. if p.returncode != 0:
  2708. raise XAttrMetadataError(p.returncode, stderr)
  2709. else:
  2710. # On Unix, and can't find pyxattr, setfattr, or xattr.
  2711. if sys.platform.startswith('linux'):
  2712. raise XAttrUnavailableError(
  2713. "Couldn't find a tool to set the xattrs. "
  2714. "Install either the python 'pyxattr' or 'xattr' "
  2715. "modules, or the GNU 'attr' package "
  2716. "(which contains the 'setfattr' tool).")
  2717. else:
  2718. raise XAttrUnavailableError(
  2719. "Couldn't find a tool to set the xattrs. "
  2720. "Install either the python 'xattr' module, "
  2721. "or the 'xattr' binary.")