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.

2812 lines
84 KiB

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