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.

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