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.

2863 lines
86 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 try_get(src, getter, expected_type=None):
  1552. try:
  1553. v = getter(src)
  1554. except (AttributeError, KeyError, TypeError, IndexError):
  1555. pass
  1556. else:
  1557. if expected_type is None or isinstance(v, expected_type):
  1558. return v
  1559. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1560. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1561. US_RATINGS = {
  1562. 'G': 0,
  1563. 'PG': 10,
  1564. 'PG-13': 13,
  1565. 'R': 16,
  1566. 'NC': 18,
  1567. }
  1568. def parse_age_limit(s):
  1569. if s is None:
  1570. return None
  1571. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1572. return int(m.group('age')) if m else US_RATINGS.get(s)
  1573. def strip_jsonp(code):
  1574. return re.sub(
  1575. r'(?s)^[a-zA-Z0-9_.$]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1576. def js_to_json(code):
  1577. def fix_kv(m):
  1578. v = m.group(0)
  1579. if v in ('true', 'false', 'null'):
  1580. return v
  1581. elif v.startswith('/*') or v == ',':
  1582. return ""
  1583. if v[0] in ("'", '"'):
  1584. v = re.sub(r'(?s)\\.|"', lambda m: {
  1585. '"': '\\"',
  1586. "\\'": "'",
  1587. '\\\n': '',
  1588. '\\x': '\\u00',
  1589. }.get(m.group(0), m.group(0)), v[1:-1])
  1590. INTEGER_TABLE = (
  1591. (r'^0[xX][0-9a-fA-F]+', 16),
  1592. (r'^0+[0-7]+', 8),
  1593. )
  1594. for regex, base in INTEGER_TABLE:
  1595. im = re.match(regex, v)
  1596. if im:
  1597. i = int(im.group(0), base)
  1598. return '"%d":' % i if v.endswith(':') else '%d' % i
  1599. return '"%s"' % v
  1600. return re.sub(r'''(?sx)
  1601. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  1602. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  1603. /\*.*?\*/|,(?=\s*[\]}])|
  1604. [a-zA-Z_][.a-zA-Z_0-9]*|
  1605. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
  1606. [0-9]+(?=\s*:)
  1607. ''', fix_kv, code)
  1608. def qualities(quality_ids):
  1609. """ Get a numeric quality value out of a list of possible values """
  1610. def q(qid):
  1611. try:
  1612. return quality_ids.index(qid)
  1613. except ValueError:
  1614. return -1
  1615. return q
  1616. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1617. def limit_length(s, length):
  1618. """ Add ellipses to overly long strings """
  1619. if s is None:
  1620. return None
  1621. ELLIPSES = '...'
  1622. if len(s) > length:
  1623. return s[:length - len(ELLIPSES)] + ELLIPSES
  1624. return s
  1625. def version_tuple(v):
  1626. return tuple(int(e) for e in re.split(r'[-.]', v))
  1627. def is_outdated_version(version, limit, assume_new=True):
  1628. if not version:
  1629. return not assume_new
  1630. try:
  1631. return version_tuple(version) < version_tuple(limit)
  1632. except ValueError:
  1633. return not assume_new
  1634. def ytdl_is_updateable():
  1635. """ Returns if youtube-dl can be updated with -U """
  1636. from zipimport import zipimporter
  1637. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1638. def args_to_str(args):
  1639. # Get a short string representation for a subprocess command
  1640. return ' '.join(compat_shlex_quote(a) for a in args)
  1641. def error_to_compat_str(err):
  1642. err_str = str(err)
  1643. # On python 2 error byte string must be decoded with proper
  1644. # encoding rather than ascii
  1645. if sys.version_info[0] < 3:
  1646. err_str = err_str.decode(preferredencoding())
  1647. return err_str
  1648. def mimetype2ext(mt):
  1649. if mt is None:
  1650. return None
  1651. ext = {
  1652. 'audio/mp4': 'm4a',
  1653. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  1654. # it's the most popular one
  1655. 'audio/mpeg': 'mp3',
  1656. }.get(mt)
  1657. if ext is not None:
  1658. return ext
  1659. _, _, res = mt.rpartition('/')
  1660. return {
  1661. '3gpp': '3gp',
  1662. 'smptett+xml': 'tt',
  1663. 'srt': 'srt',
  1664. 'ttaf+xml': 'dfxp',
  1665. 'ttml+xml': 'ttml',
  1666. 'vtt': 'vtt',
  1667. 'x-flv': 'flv',
  1668. 'x-mp4-fragmented': 'mp4',
  1669. 'x-ms-wmv': 'wmv',
  1670. }.get(res, res)
  1671. def urlhandle_detect_ext(url_handle):
  1672. getheader = url_handle.headers.get
  1673. cd = getheader('Content-Disposition')
  1674. if cd:
  1675. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1676. if m:
  1677. e = determine_ext(m.group('filename'), default_ext=None)
  1678. if e:
  1679. return e
  1680. return mimetype2ext(getheader('Content-Type'))
  1681. def encode_data_uri(data, mime_type):
  1682. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1683. def age_restricted(content_limit, age_limit):
  1684. """ Returns True iff the content should be blocked """
  1685. if age_limit is None: # No limit set
  1686. return False
  1687. if content_limit is None:
  1688. return False # Content available for everyone
  1689. return age_limit < content_limit
  1690. def is_html(first_bytes):
  1691. """ Detect whether a file contains HTML by examining its first bytes. """
  1692. BOMS = [
  1693. (b'\xef\xbb\xbf', 'utf-8'),
  1694. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1695. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1696. (b'\xff\xfe', 'utf-16-le'),
  1697. (b'\xfe\xff', 'utf-16-be'),
  1698. ]
  1699. for bom, enc in BOMS:
  1700. if first_bytes.startswith(bom):
  1701. s = first_bytes[len(bom):].decode(enc, 'replace')
  1702. break
  1703. else:
  1704. s = first_bytes.decode('utf-8', 'replace')
  1705. return re.match(r'^\s*<', s)
  1706. def determine_protocol(info_dict):
  1707. protocol = info_dict.get('protocol')
  1708. if protocol is not None:
  1709. return protocol
  1710. url = info_dict['url']
  1711. if url.startswith('rtmp'):
  1712. return 'rtmp'
  1713. elif url.startswith('mms'):
  1714. return 'mms'
  1715. elif url.startswith('rtsp'):
  1716. return 'rtsp'
  1717. ext = determine_ext(url)
  1718. if ext == 'm3u8':
  1719. return 'm3u8'
  1720. elif ext == 'f4m':
  1721. return 'f4m'
  1722. return compat_urllib_parse_urlparse(url).scheme
  1723. def render_table(header_row, data):
  1724. """ Render a list of rows, each as a list of values """
  1725. table = [header_row] + data
  1726. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1727. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1728. return '\n'.join(format_str % tuple(row) for row in table)
  1729. def _match_one(filter_part, dct):
  1730. COMPARISON_OPERATORS = {
  1731. '<': operator.lt,
  1732. '<=': operator.le,
  1733. '>': operator.gt,
  1734. '>=': operator.ge,
  1735. '=': operator.eq,
  1736. '!=': operator.ne,
  1737. }
  1738. operator_rex = re.compile(r'''(?x)\s*
  1739. (?P<key>[a-z_]+)
  1740. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1741. (?:
  1742. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1743. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1744. )
  1745. \s*$
  1746. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1747. m = operator_rex.search(filter_part)
  1748. if m:
  1749. op = COMPARISON_OPERATORS[m.group('op')]
  1750. if m.group('strval') is not None:
  1751. if m.group('op') not in ('=', '!='):
  1752. raise ValueError(
  1753. 'Operator %s does not support string values!' % m.group('op'))
  1754. comparison_value = m.group('strval')
  1755. else:
  1756. try:
  1757. comparison_value = int(m.group('intval'))
  1758. except ValueError:
  1759. comparison_value = parse_filesize(m.group('intval'))
  1760. if comparison_value is None:
  1761. comparison_value = parse_filesize(m.group('intval') + 'B')
  1762. if comparison_value is None:
  1763. raise ValueError(
  1764. 'Invalid integer value %r in filter part %r' % (
  1765. m.group('intval'), filter_part))
  1766. actual_value = dct.get(m.group('key'))
  1767. if actual_value is None:
  1768. return m.group('none_inclusive')
  1769. return op(actual_value, comparison_value)
  1770. UNARY_OPERATORS = {
  1771. '': lambda v: v is not None,
  1772. '!': lambda v: v is None,
  1773. }
  1774. operator_rex = re.compile(r'''(?x)\s*
  1775. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1776. \s*$
  1777. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1778. m = operator_rex.search(filter_part)
  1779. if m:
  1780. op = UNARY_OPERATORS[m.group('op')]
  1781. actual_value = dct.get(m.group('key'))
  1782. return op(actual_value)
  1783. raise ValueError('Invalid filter part %r' % filter_part)
  1784. def match_str(filter_str, dct):
  1785. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1786. return all(
  1787. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1788. def match_filter_func(filter_str):
  1789. def _match_func(info_dict):
  1790. if match_str(filter_str, info_dict):
  1791. return None
  1792. else:
  1793. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1794. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1795. return _match_func
  1796. def parse_dfxp_time_expr(time_expr):
  1797. if not time_expr:
  1798. return
  1799. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1800. if mobj:
  1801. return float(mobj.group('time_offset'))
  1802. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  1803. if mobj:
  1804. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  1805. def srt_subtitles_timecode(seconds):
  1806. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1807. def dfxp2srt(dfxp_data):
  1808. _x = functools.partial(xpath_with_ns, ns_map={
  1809. 'ttml': 'http://www.w3.org/ns/ttml',
  1810. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1811. 'ttaf1_0604': 'http://www.w3.org/2006/04/ttaf1',
  1812. })
  1813. class TTMLPElementParser(object):
  1814. out = ''
  1815. def start(self, tag, attrib):
  1816. if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1817. self.out += '\n'
  1818. def end(self, tag):
  1819. pass
  1820. def data(self, data):
  1821. self.out += data
  1822. def close(self):
  1823. return self.out.strip()
  1824. def parse_node(node):
  1825. target = TTMLPElementParser()
  1826. parser = xml.etree.ElementTree.XMLParser(target=target)
  1827. parser.feed(xml.etree.ElementTree.tostring(node))
  1828. return parser.close()
  1829. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  1830. out = []
  1831. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall(_x('.//ttaf1_0604:p')) or dfxp.findall('.//p')
  1832. if not paras:
  1833. raise ValueError('Invalid dfxp/TTML subtitle')
  1834. for para, index in zip(paras, itertools.count(1)):
  1835. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  1836. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1837. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  1838. if begin_time is None:
  1839. continue
  1840. if not end_time:
  1841. if not dur:
  1842. continue
  1843. end_time = begin_time + dur
  1844. out.append('%d\n%s --> %s\n%s\n\n' % (
  1845. index,
  1846. srt_subtitles_timecode(begin_time),
  1847. srt_subtitles_timecode(end_time),
  1848. parse_node(para)))
  1849. return ''.join(out)
  1850. def cli_option(params, command_option, param):
  1851. param = params.get(param)
  1852. return [command_option, param] if param is not None else []
  1853. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  1854. param = params.get(param)
  1855. assert isinstance(param, bool)
  1856. if separator:
  1857. return [command_option + separator + (true_value if param else false_value)]
  1858. return [command_option, true_value if param else false_value]
  1859. def cli_valueless_option(params, command_option, param, expected_value=True):
  1860. param = params.get(param)
  1861. return [command_option] if param == expected_value else []
  1862. def cli_configuration_args(params, param, default=[]):
  1863. ex_args = params.get(param)
  1864. if ex_args is None:
  1865. return default
  1866. assert isinstance(ex_args, list)
  1867. return ex_args
  1868. class ISO639Utils(object):
  1869. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  1870. _lang_map = {
  1871. 'aa': 'aar',
  1872. 'ab': 'abk',
  1873. 'ae': 'ave',
  1874. 'af': 'afr',
  1875. 'ak': 'aka',
  1876. 'am': 'amh',
  1877. 'an': 'arg',
  1878. 'ar': 'ara',
  1879. 'as': 'asm',
  1880. 'av': 'ava',
  1881. 'ay': 'aym',
  1882. 'az': 'aze',
  1883. 'ba': 'bak',
  1884. 'be': 'bel',
  1885. 'bg': 'bul',
  1886. 'bh': 'bih',
  1887. 'bi': 'bis',
  1888. 'bm': 'bam',
  1889. 'bn': 'ben',
  1890. 'bo': 'bod',
  1891. 'br': 'bre',
  1892. 'bs': 'bos',
  1893. 'ca': 'cat',
  1894. 'ce': 'che',
  1895. 'ch': 'cha',
  1896. 'co': 'cos',
  1897. 'cr': 'cre',
  1898. 'cs': 'ces',
  1899. 'cu': 'chu',
  1900. 'cv': 'chv',
  1901. 'cy': 'cym',
  1902. 'da': 'dan',
  1903. 'de': 'deu',
  1904. 'dv': 'div',
  1905. 'dz': 'dzo',
  1906. 'ee': 'ewe',
  1907. 'el': 'ell',
  1908. 'en': 'eng',
  1909. 'eo': 'epo',
  1910. 'es': 'spa',
  1911. 'et': 'est',
  1912. 'eu': 'eus',
  1913. 'fa': 'fas',
  1914. 'ff': 'ful',
  1915. 'fi': 'fin',
  1916. 'fj': 'fij',
  1917. 'fo': 'fao',
  1918. 'fr': 'fra',
  1919. 'fy': 'fry',
  1920. 'ga': 'gle',
  1921. 'gd': 'gla',
  1922. 'gl': 'glg',
  1923. 'gn': 'grn',
  1924. 'gu': 'guj',
  1925. 'gv': 'glv',
  1926. 'ha': 'hau',
  1927. 'he': 'heb',
  1928. 'hi': 'hin',
  1929. 'ho': 'hmo',
  1930. 'hr': 'hrv',
  1931. 'ht': 'hat',
  1932. 'hu': 'hun',
  1933. 'hy': 'hye',
  1934. 'hz': 'her',
  1935. 'ia': 'ina',
  1936. 'id': 'ind',
  1937. 'ie': 'ile',
  1938. 'ig': 'ibo',
  1939. 'ii': 'iii',
  1940. 'ik': 'ipk',
  1941. 'io': 'ido',
  1942. 'is': 'isl',
  1943. 'it': 'ita',
  1944. 'iu': 'iku',
  1945. 'ja': 'jpn',
  1946. 'jv': 'jav',
  1947. 'ka': 'kat',
  1948. 'kg': 'kon',
  1949. 'ki': 'kik',
  1950. 'kj': 'kua',
  1951. 'kk': 'kaz',
  1952. 'kl': 'kal',
  1953. 'km': 'khm',
  1954. 'kn': 'kan',
  1955. 'ko': 'kor',
  1956. 'kr': 'kau',
  1957. 'ks': 'kas',
  1958. 'ku': 'kur',
  1959. 'kv': 'kom',
  1960. 'kw': 'cor',
  1961. 'ky': 'kir',
  1962. 'la': 'lat',
  1963. 'lb': 'ltz',
  1964. 'lg': 'lug',
  1965. 'li': 'lim',
  1966. 'ln': 'lin',
  1967. 'lo': 'lao',
  1968. 'lt': 'lit',
  1969. 'lu': 'lub',
  1970. 'lv': 'lav',
  1971. 'mg': 'mlg',
  1972. 'mh': 'mah',
  1973. 'mi': 'mri',
  1974. 'mk': 'mkd',
  1975. 'ml': 'mal',
  1976. 'mn': 'mon',
  1977. 'mr': 'mar',
  1978. 'ms': 'msa',
  1979. 'mt': 'mlt',
  1980. 'my': 'mya',
  1981. 'na': 'nau',
  1982. 'nb': 'nob',
  1983. 'nd': 'nde',
  1984. 'ne': 'nep',
  1985. 'ng': 'ndo',
  1986. 'nl': 'nld',
  1987. 'nn': 'nno',
  1988. 'no': 'nor',
  1989. 'nr': 'nbl',
  1990. 'nv': 'nav',
  1991. 'ny': 'nya',
  1992. 'oc': 'oci',
  1993. 'oj': 'oji',
  1994. 'om': 'orm',
  1995. 'or': 'ori',
  1996. 'os': 'oss',
  1997. 'pa': 'pan',
  1998. 'pi': 'pli',
  1999. 'pl': 'pol',
  2000. 'ps': 'pus',
  2001. 'pt': 'por',
  2002. 'qu': 'que',
  2003. 'rm': 'roh',
  2004. 'rn': 'run',
  2005. 'ro': 'ron',
  2006. 'ru': 'rus',
  2007. 'rw': 'kin',
  2008. 'sa': 'san',
  2009. 'sc': 'srd',
  2010. 'sd': 'snd',
  2011. 'se': 'sme',
  2012. 'sg': 'sag',
  2013. 'si': 'sin',
  2014. 'sk': 'slk',
  2015. 'sl': 'slv',
  2016. 'sm': 'smo',
  2017. 'sn': 'sna',
  2018. 'so': 'som',
  2019. 'sq': 'sqi',
  2020. 'sr': 'srp',
  2021. 'ss': 'ssw',
  2022. 'st': 'sot',
  2023. 'su': 'sun',
  2024. 'sv': 'swe',
  2025. 'sw': 'swa',
  2026. 'ta': 'tam',
  2027. 'te': 'tel',
  2028. 'tg': 'tgk',
  2029. 'th': 'tha',
  2030. 'ti': 'tir',
  2031. 'tk': 'tuk',
  2032. 'tl': 'tgl',
  2033. 'tn': 'tsn',
  2034. 'to': 'ton',
  2035. 'tr': 'tur',
  2036. 'ts': 'tso',
  2037. 'tt': 'tat',
  2038. 'tw': 'twi',
  2039. 'ty': 'tah',
  2040. 'ug': 'uig',
  2041. 'uk': 'ukr',
  2042. 'ur': 'urd',
  2043. 'uz': 'uzb',
  2044. 've': 'ven',
  2045. 'vi': 'vie',
  2046. 'vo': 'vol',
  2047. 'wa': 'wln',
  2048. 'wo': 'wol',
  2049. 'xh': 'xho',
  2050. 'yi': 'yid',
  2051. 'yo': 'yor',
  2052. 'za': 'zha',
  2053. 'zh': 'zho',
  2054. 'zu': 'zul',
  2055. }
  2056. @classmethod
  2057. def short2long(cls, code):
  2058. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  2059. return cls._lang_map.get(code[:2])
  2060. @classmethod
  2061. def long2short(cls, code):
  2062. """Convert language code from ISO 639-2/T to ISO 639-1"""
  2063. for short_name, long_name in cls._lang_map.items():
  2064. if long_name == code:
  2065. return short_name
  2066. class ISO3166Utils(object):
  2067. # From http://data.okfn.org/data/core/country-list
  2068. _country_map = {
  2069. 'AF': 'Afghanistan',
  2070. 'AX': 'Åland Islands',
  2071. 'AL': 'Albania',
  2072. 'DZ': 'Algeria',
  2073. 'AS': 'American Samoa',
  2074. 'AD': 'Andorra',
  2075. 'AO': 'Angola',
  2076. 'AI': 'Anguilla',
  2077. 'AQ': 'Antarctica',
  2078. 'AG': 'Antigua and Barbuda',
  2079. 'AR': 'Argentina',
  2080. 'AM': 'Armenia',
  2081. 'AW': 'Aruba',
  2082. 'AU': 'Australia',
  2083. 'AT': 'Austria',
  2084. 'AZ': 'Azerbaijan',
  2085. 'BS': 'Bahamas',
  2086. 'BH': 'Bahrain',
  2087. 'BD': 'Bangladesh',
  2088. 'BB': 'Barbados',
  2089. 'BY': 'Belarus',
  2090. 'BE': 'Belgium',
  2091. 'BZ': 'Belize',
  2092. 'BJ': 'Benin',
  2093. 'BM': 'Bermuda',
  2094. 'BT': 'Bhutan',
  2095. 'BO': 'Bolivia, Plurinational State of',
  2096. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2097. 'BA': 'Bosnia and Herzegovina',
  2098. 'BW': 'Botswana',
  2099. 'BV': 'Bouvet Island',
  2100. 'BR': 'Brazil',
  2101. 'IO': 'British Indian Ocean Territory',
  2102. 'BN': 'Brunei Darussalam',
  2103. 'BG': 'Bulgaria',
  2104. 'BF': 'Burkina Faso',
  2105. 'BI': 'Burundi',
  2106. 'KH': 'Cambodia',
  2107. 'CM': 'Cameroon',
  2108. 'CA': 'Canada',
  2109. 'CV': 'Cape Verde',
  2110. 'KY': 'Cayman Islands',
  2111. 'CF': 'Central African Republic',
  2112. 'TD': 'Chad',
  2113. 'CL': 'Chile',
  2114. 'CN': 'China',
  2115. 'CX': 'Christmas Island',
  2116. 'CC': 'Cocos (Keeling) Islands',
  2117. 'CO': 'Colombia',
  2118. 'KM': 'Comoros',
  2119. 'CG': 'Congo',
  2120. 'CD': 'Congo, the Democratic Republic of the',
  2121. 'CK': 'Cook Islands',
  2122. 'CR': 'Costa Rica',
  2123. 'CI': 'Côte d\'Ivoire',
  2124. 'HR': 'Croatia',
  2125. 'CU': 'Cuba',
  2126. 'CW': 'Curaçao',
  2127. 'CY': 'Cyprus',
  2128. 'CZ': 'Czech Republic',
  2129. 'DK': 'Denmark',
  2130. 'DJ': 'Djibouti',
  2131. 'DM': 'Dominica',
  2132. 'DO': 'Dominican Republic',
  2133. 'EC': 'Ecuador',
  2134. 'EG': 'Egypt',
  2135. 'SV': 'El Salvador',
  2136. 'GQ': 'Equatorial Guinea',
  2137. 'ER': 'Eritrea',
  2138. 'EE': 'Estonia',
  2139. 'ET': 'Ethiopia',
  2140. 'FK': 'Falkland Islands (Malvinas)',
  2141. 'FO': 'Faroe Islands',
  2142. 'FJ': 'Fiji',
  2143. 'FI': 'Finland',
  2144. 'FR': 'France',
  2145. 'GF': 'French Guiana',
  2146. 'PF': 'French Polynesia',
  2147. 'TF': 'French Southern Territories',
  2148. 'GA': 'Gabon',
  2149. 'GM': 'Gambia',
  2150. 'GE': 'Georgia',
  2151. 'DE': 'Germany',
  2152. 'GH': 'Ghana',
  2153. 'GI': 'Gibraltar',
  2154. 'GR': 'Greece',
  2155. 'GL': 'Greenland',
  2156. 'GD': 'Grenada',
  2157. 'GP': 'Guadeloupe',
  2158. 'GU': 'Guam',
  2159. 'GT': 'Guatemala',
  2160. 'GG': 'Guernsey',
  2161. 'GN': 'Guinea',
  2162. 'GW': 'Guinea-Bissau',
  2163. 'GY': 'Guyana',
  2164. 'HT': 'Haiti',
  2165. 'HM': 'Heard Island and McDonald Islands',
  2166. 'VA': 'Holy See (Vatican City State)',
  2167. 'HN': 'Honduras',
  2168. 'HK': 'Hong Kong',
  2169. 'HU': 'Hungary',
  2170. 'IS': 'Iceland',
  2171. 'IN': 'India',
  2172. 'ID': 'Indonesia',
  2173. 'IR': 'Iran, Islamic Republic of',
  2174. 'IQ': 'Iraq',
  2175. 'IE': 'Ireland',
  2176. 'IM': 'Isle of Man',
  2177. 'IL': 'Israel',
  2178. 'IT': 'Italy',
  2179. 'JM': 'Jamaica',
  2180. 'JP': 'Japan',
  2181. 'JE': 'Jersey',
  2182. 'JO': 'Jordan',
  2183. 'KZ': 'Kazakhstan',
  2184. 'KE': 'Kenya',
  2185. 'KI': 'Kiribati',
  2186. 'KP': 'Korea, Democratic People\'s Republic of',
  2187. 'KR': 'Korea, Republic of',
  2188. 'KW': 'Kuwait',
  2189. 'KG': 'Kyrgyzstan',
  2190. 'LA': 'Lao People\'s Democratic Republic',
  2191. 'LV': 'Latvia',
  2192. 'LB': 'Lebanon',
  2193. 'LS': 'Lesotho',
  2194. 'LR': 'Liberia',
  2195. 'LY': 'Libya',
  2196. 'LI': 'Liechtenstein',
  2197. 'LT': 'Lithuania',
  2198. 'LU': 'Luxembourg',
  2199. 'MO': 'Macao',
  2200. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2201. 'MG': 'Madagascar',
  2202. 'MW': 'Malawi',
  2203. 'MY': 'Malaysia',
  2204. 'MV': 'Maldives',
  2205. 'ML': 'Mali',
  2206. 'MT': 'Malta',
  2207. 'MH': 'Marshall Islands',
  2208. 'MQ': 'Martinique',
  2209. 'MR': 'Mauritania',
  2210. 'MU': 'Mauritius',
  2211. 'YT': 'Mayotte',
  2212. 'MX': 'Mexico',
  2213. 'FM': 'Micronesia, Federated States of',
  2214. 'MD': 'Moldova, Republic of',
  2215. 'MC': 'Monaco',
  2216. 'MN': 'Mongolia',
  2217. 'ME': 'Montenegro',
  2218. 'MS': 'Montserrat',
  2219. 'MA': 'Morocco',
  2220. 'MZ': 'Mozambique',
  2221. 'MM': 'Myanmar',
  2222. 'NA': 'Namibia',
  2223. 'NR': 'Nauru',
  2224. 'NP': 'Nepal',
  2225. 'NL': 'Netherlands',
  2226. 'NC': 'New Caledonia',
  2227. 'NZ': 'New Zealand',
  2228. 'NI': 'Nicaragua',
  2229. 'NE': 'Niger',
  2230. 'NG': 'Nigeria',
  2231. 'NU': 'Niue',
  2232. 'NF': 'Norfolk Island',
  2233. 'MP': 'Northern Mariana Islands',
  2234. 'NO': 'Norway',
  2235. 'OM': 'Oman',
  2236. 'PK': 'Pakistan',
  2237. 'PW': 'Palau',
  2238. 'PS': 'Palestine, State of',
  2239. 'PA': 'Panama',
  2240. 'PG': 'Papua New Guinea',
  2241. 'PY': 'Paraguay',
  2242. 'PE': 'Peru',
  2243. 'PH': 'Philippines',
  2244. 'PN': 'Pitcairn',
  2245. 'PL': 'Poland',
  2246. 'PT': 'Portugal',
  2247. 'PR': 'Puerto Rico',
  2248. 'QA': 'Qatar',
  2249. 'RE': 'Réunion',
  2250. 'RO': 'Romania',
  2251. 'RU': 'Russian Federation',
  2252. 'RW': 'Rwanda',
  2253. 'BL': 'Saint Barthélemy',
  2254. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2255. 'KN': 'Saint Kitts and Nevis',
  2256. 'LC': 'Saint Lucia',
  2257. 'MF': 'Saint Martin (French part)',
  2258. 'PM': 'Saint Pierre and Miquelon',
  2259. 'VC': 'Saint Vincent and the Grenadines',
  2260. 'WS': 'Samoa',
  2261. 'SM': 'San Marino',
  2262. 'ST': 'Sao Tome and Principe',
  2263. 'SA': 'Saudi Arabia',
  2264. 'SN': 'Senegal',
  2265. 'RS': 'Serbia',
  2266. 'SC': 'Seychelles',
  2267. 'SL': 'Sierra Leone',
  2268. 'SG': 'Singapore',
  2269. 'SX': 'Sint Maarten (Dutch part)',
  2270. 'SK': 'Slovakia',
  2271. 'SI': 'Slovenia',
  2272. 'SB': 'Solomon Islands',
  2273. 'SO': 'Somalia',
  2274. 'ZA': 'South Africa',
  2275. 'GS': 'South Georgia and the South Sandwich Islands',
  2276. 'SS': 'South Sudan',
  2277. 'ES': 'Spain',
  2278. 'LK': 'Sri Lanka',
  2279. 'SD': 'Sudan',
  2280. 'SR': 'Suriname',
  2281. 'SJ': 'Svalbard and Jan Mayen',
  2282. 'SZ': 'Swaziland',
  2283. 'SE': 'Sweden',
  2284. 'CH': 'Switzerland',
  2285. 'SY': 'Syrian Arab Republic',
  2286. 'TW': 'Taiwan, Province of China',
  2287. 'TJ': 'Tajikistan',
  2288. 'TZ': 'Tanzania, United Republic of',
  2289. 'TH': 'Thailand',
  2290. 'TL': 'Timor-Leste',
  2291. 'TG': 'Togo',
  2292. 'TK': 'Tokelau',
  2293. 'TO': 'Tonga',
  2294. 'TT': 'Trinidad and Tobago',
  2295. 'TN': 'Tunisia',
  2296. 'TR': 'Turkey',
  2297. 'TM': 'Turkmenistan',
  2298. 'TC': 'Turks and Caicos Islands',
  2299. 'TV': 'Tuvalu',
  2300. 'UG': 'Uganda',
  2301. 'UA': 'Ukraine',
  2302. 'AE': 'United Arab Emirates',
  2303. 'GB': 'United Kingdom',
  2304. 'US': 'United States',
  2305. 'UM': 'United States Minor Outlying Islands',
  2306. 'UY': 'Uruguay',
  2307. 'UZ': 'Uzbekistan',
  2308. 'VU': 'Vanuatu',
  2309. 'VE': 'Venezuela, Bolivarian Republic of',
  2310. 'VN': 'Viet Nam',
  2311. 'VG': 'Virgin Islands, British',
  2312. 'VI': 'Virgin Islands, U.S.',
  2313. 'WF': 'Wallis and Futuna',
  2314. 'EH': 'Western Sahara',
  2315. 'YE': 'Yemen',
  2316. 'ZM': 'Zambia',
  2317. 'ZW': 'Zimbabwe',
  2318. }
  2319. @classmethod
  2320. def short2full(cls, code):
  2321. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2322. return cls._country_map.get(code.upper())
  2323. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2324. def __init__(self, proxies=None):
  2325. # Set default handlers
  2326. for type in ('http', 'https'):
  2327. setattr(self, '%s_open' % type,
  2328. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2329. meth(r, proxy, type))
  2330. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2331. def proxy_open(self, req, proxy, type):
  2332. req_proxy = req.headers.get('Ytdl-request-proxy')
  2333. if req_proxy is not None:
  2334. proxy = req_proxy
  2335. del req.headers['Ytdl-request-proxy']
  2336. if proxy == '__noproxy__':
  2337. return None # No Proxy
  2338. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  2339. req.add_header('Ytdl-socks-proxy', proxy)
  2340. # youtube-dl's http/https handlers do wrapping the socket with socks
  2341. return None
  2342. return compat_urllib_request.ProxyHandler.proxy_open(
  2343. self, req, proxy, type)
  2344. def ohdave_rsa_encrypt(data, exponent, modulus):
  2345. '''
  2346. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  2347. Input:
  2348. data: data to encrypt, bytes-like object
  2349. exponent, modulus: parameter e and N of RSA algorithm, both integer
  2350. Output: hex string of encrypted data
  2351. Limitation: supports one block encryption only
  2352. '''
  2353. payload = int(binascii.hexlify(data[::-1]), 16)
  2354. encrypted = pow(payload, exponent, modulus)
  2355. return '%x' % encrypted
  2356. def encode_base_n(num, n, table=None):
  2357. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  2358. if not table:
  2359. table = FULL_TABLE[:n]
  2360. if n > len(table):
  2361. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  2362. if num == 0:
  2363. return table[0]
  2364. ret = ''
  2365. while num:
  2366. ret = table[num % n] + ret
  2367. num = num // n
  2368. return ret
  2369. def decode_packed_codes(code):
  2370. mobj = re.search(
  2371. r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)",
  2372. code)
  2373. obfucasted_code, base, count, symbols = mobj.groups()
  2374. base = int(base)
  2375. count = int(count)
  2376. symbols = symbols.split('|')
  2377. symbol_table = {}
  2378. while count:
  2379. count -= 1
  2380. base_n_count = encode_base_n(count, base)
  2381. symbol_table[base_n_count] = symbols[count] or base_n_count
  2382. return re.sub(
  2383. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  2384. obfucasted_code)
  2385. def parse_m3u8_attributes(attrib):
  2386. info = {}
  2387. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  2388. if val.startswith('"'):
  2389. val = val[1:-1]
  2390. info[key] = val
  2391. return info