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.

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