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.

2836 lines
85 KiB

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