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.

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