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.

3123 lines
92 KiB

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