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.

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