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.

2753 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. days, hours, mins, secs, ms = [None] * 5
  1256. m = re.match(r'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?$', s)
  1257. if m:
  1258. days, hours, mins, secs, ms = m.groups()
  1259. else:
  1260. m = re.match(
  1261. r'''(?ix)(?:P?T)?
  1262. (?:
  1263. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  1264. )?
  1265. (?:
  1266. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  1267. )?
  1268. (?:
  1269. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  1270. )?
  1271. (?:
  1272. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  1273. )?$''', s)
  1274. if m:
  1275. days, hours, mins, secs, ms = m.groups()
  1276. else:
  1277. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)$', s)
  1278. if m:
  1279. hours, mins = m.groups()
  1280. else:
  1281. return None
  1282. duration = 0
  1283. if secs:
  1284. duration += float(secs)
  1285. if mins:
  1286. duration += float(mins) * 60
  1287. if hours:
  1288. duration += float(hours) * 60 * 60
  1289. if days:
  1290. duration += float(days) * 24 * 60 * 60
  1291. if ms:
  1292. duration += float(ms)
  1293. return duration
  1294. def prepend_extension(filename, ext, expected_real_ext=None):
  1295. name, real_ext = os.path.splitext(filename)
  1296. return (
  1297. '{0}.{1}{2}'.format(name, ext, real_ext)
  1298. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1299. else '{0}.{1}'.format(filename, ext))
  1300. def replace_extension(filename, ext, expected_real_ext=None):
  1301. name, real_ext = os.path.splitext(filename)
  1302. return '{0}.{1}'.format(
  1303. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1304. ext)
  1305. def check_executable(exe, args=[]):
  1306. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1307. args can be a list of arguments for a short output (like -version) """
  1308. try:
  1309. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1310. except OSError:
  1311. return False
  1312. return exe
  1313. def get_exe_version(exe, args=['--version'],
  1314. version_re=None, unrecognized='present'):
  1315. """ Returns the version of the specified executable,
  1316. or False if the executable is not present """
  1317. try:
  1318. out, _ = subprocess.Popen(
  1319. [encodeArgument(exe)] + args,
  1320. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1321. except OSError:
  1322. return False
  1323. if isinstance(out, bytes): # Python 2.x
  1324. out = out.decode('ascii', 'ignore')
  1325. return detect_exe_version(out, version_re, unrecognized)
  1326. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1327. assert isinstance(output, compat_str)
  1328. if version_re is None:
  1329. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1330. m = re.search(version_re, output)
  1331. if m:
  1332. return m.group(1)
  1333. else:
  1334. return unrecognized
  1335. class PagedList(object):
  1336. def __len__(self):
  1337. # This is only useful for tests
  1338. return len(self.getslice())
  1339. class OnDemandPagedList(PagedList):
  1340. def __init__(self, pagefunc, pagesize, use_cache=False):
  1341. self._pagefunc = pagefunc
  1342. self._pagesize = pagesize
  1343. self._use_cache = use_cache
  1344. if use_cache:
  1345. self._cache = {}
  1346. def getslice(self, start=0, end=None):
  1347. res = []
  1348. for pagenum in itertools.count(start // self._pagesize):
  1349. firstid = pagenum * self._pagesize
  1350. nextfirstid = pagenum * self._pagesize + self._pagesize
  1351. if start >= nextfirstid:
  1352. continue
  1353. page_results = None
  1354. if self._use_cache:
  1355. page_results = self._cache.get(pagenum)
  1356. if page_results is None:
  1357. page_results = list(self._pagefunc(pagenum))
  1358. if self._use_cache:
  1359. self._cache[pagenum] = page_results
  1360. startv = (
  1361. start % self._pagesize
  1362. if firstid <= start < nextfirstid
  1363. else 0)
  1364. endv = (
  1365. ((end - 1) % self._pagesize) + 1
  1366. if (end is not None and firstid <= end <= nextfirstid)
  1367. else None)
  1368. if startv != 0 or endv is not None:
  1369. page_results = page_results[startv:endv]
  1370. res.extend(page_results)
  1371. # A little optimization - if current page is not "full", ie. does
  1372. # not contain page_size videos then we can assume that this page
  1373. # is the last one - there are no more ids on further pages -
  1374. # i.e. no need to query again.
  1375. if len(page_results) + startv < self._pagesize:
  1376. break
  1377. # If we got the whole page, but the next page is not interesting,
  1378. # break out early as well
  1379. if end == nextfirstid:
  1380. break
  1381. return res
  1382. class InAdvancePagedList(PagedList):
  1383. def __init__(self, pagefunc, pagecount, pagesize):
  1384. self._pagefunc = pagefunc
  1385. self._pagecount = pagecount
  1386. self._pagesize = pagesize
  1387. def getslice(self, start=0, end=None):
  1388. res = []
  1389. start_page = start // self._pagesize
  1390. end_page = (
  1391. self._pagecount if end is None else (end // self._pagesize + 1))
  1392. skip_elems = start - start_page * self._pagesize
  1393. only_more = None if end is None else end - start
  1394. for pagenum in range(start_page, end_page):
  1395. page = list(self._pagefunc(pagenum))
  1396. if skip_elems:
  1397. page = page[skip_elems:]
  1398. skip_elems = None
  1399. if only_more is not None:
  1400. if len(page) < only_more:
  1401. only_more -= len(page)
  1402. else:
  1403. page = page[:only_more]
  1404. res.extend(page)
  1405. break
  1406. res.extend(page)
  1407. return res
  1408. def uppercase_escape(s):
  1409. unicode_escape = codecs.getdecoder('unicode_escape')
  1410. return re.sub(
  1411. r'\\U[0-9a-fA-F]{8}',
  1412. lambda m: unicode_escape(m.group(0))[0],
  1413. s)
  1414. def lowercase_escape(s):
  1415. unicode_escape = codecs.getdecoder('unicode_escape')
  1416. return re.sub(
  1417. r'\\u[0-9a-fA-F]{4}',
  1418. lambda m: unicode_escape(m.group(0))[0],
  1419. s)
  1420. def escape_rfc3986(s):
  1421. """Escape non-ASCII characters as suggested by RFC 3986"""
  1422. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1423. s = s.encode('utf-8')
  1424. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1425. def escape_url(url):
  1426. """Escape URL as suggested by RFC 3986"""
  1427. url_parsed = compat_urllib_parse_urlparse(url)
  1428. return url_parsed._replace(
  1429. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  1430. path=escape_rfc3986(url_parsed.path),
  1431. params=escape_rfc3986(url_parsed.params),
  1432. query=escape_rfc3986(url_parsed.query),
  1433. fragment=escape_rfc3986(url_parsed.fragment)
  1434. ).geturl()
  1435. try:
  1436. struct.pack('!I', 0)
  1437. except TypeError:
  1438. # In Python 2.6 and 2.7.x < 2.7.7, struct requires a bytes argument
  1439. # See https://bugs.python.org/issue19099
  1440. def struct_pack(spec, *args):
  1441. if isinstance(spec, compat_str):
  1442. spec = spec.encode('ascii')
  1443. return struct.pack(spec, *args)
  1444. def struct_unpack(spec, *args):
  1445. if isinstance(spec, compat_str):
  1446. spec = spec.encode('ascii')
  1447. return struct.unpack(spec, *args)
  1448. else:
  1449. struct_pack = struct.pack
  1450. struct_unpack = struct.unpack
  1451. def read_batch_urls(batch_fd):
  1452. def fixup(url):
  1453. if not isinstance(url, compat_str):
  1454. url = url.decode('utf-8', 'replace')
  1455. BOM_UTF8 = '\xef\xbb\xbf'
  1456. if url.startswith(BOM_UTF8):
  1457. url = url[len(BOM_UTF8):]
  1458. url = url.strip()
  1459. if url.startswith(('#', ';', ']')):
  1460. return False
  1461. return url
  1462. with contextlib.closing(batch_fd) as fd:
  1463. return [url for url in map(fixup, fd) if url]
  1464. def urlencode_postdata(*args, **kargs):
  1465. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  1466. def update_url_query(url, query):
  1467. if not query:
  1468. return url
  1469. parsed_url = compat_urlparse.urlparse(url)
  1470. qs = compat_parse_qs(parsed_url.query)
  1471. qs.update(query)
  1472. return compat_urlparse.urlunparse(parsed_url._replace(
  1473. query=compat_urllib_parse_urlencode(qs, True)))
  1474. def update_Request(req, url=None, data=None, headers={}, query={}):
  1475. req_headers = req.headers.copy()
  1476. req_headers.update(headers)
  1477. req_data = data or req.data
  1478. req_url = update_url_query(url or req.get_full_url(), query)
  1479. req_type = HEADRequest if req.get_method() == 'HEAD' else compat_urllib_request.Request
  1480. new_req = req_type(
  1481. req_url, data=req_data, headers=req_headers,
  1482. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1483. if hasattr(req, 'timeout'):
  1484. new_req.timeout = req.timeout
  1485. return new_req
  1486. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  1487. if isinstance(key_or_keys, (list, tuple)):
  1488. for key in key_or_keys:
  1489. if key not in d or d[key] is None or skip_false_values and not d[key]:
  1490. continue
  1491. return d[key]
  1492. return default
  1493. return d.get(key_or_keys, default)
  1494. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1495. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1496. US_RATINGS = {
  1497. 'G': 0,
  1498. 'PG': 10,
  1499. 'PG-13': 13,
  1500. 'R': 16,
  1501. 'NC': 18,
  1502. }
  1503. def parse_age_limit(s):
  1504. if s is None:
  1505. return None
  1506. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1507. return int(m.group('age')) if m else US_RATINGS.get(s)
  1508. def strip_jsonp(code):
  1509. return re.sub(
  1510. r'(?s)^[a-zA-Z0-9_.]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1511. def js_to_json(code):
  1512. def fix_kv(m):
  1513. v = m.group(0)
  1514. if v in ('true', 'false', 'null'):
  1515. return v
  1516. if v.startswith('"'):
  1517. v = re.sub(r"\\'", "'", v[1:-1])
  1518. elif v.startswith("'"):
  1519. v = v[1:-1]
  1520. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1521. '\\\\': '\\\\',
  1522. "\\'": "'",
  1523. '"': '\\"',
  1524. }[m.group(0)], v)
  1525. return '"%s"' % v
  1526. res = re.sub(r'''(?x)
  1527. "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"|
  1528. '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'|
  1529. [a-zA-Z_][.a-zA-Z_0-9]*
  1530. ''', fix_kv, code)
  1531. res = re.sub(r',(\s*[\]}])', lambda m: m.group(1), res)
  1532. return res
  1533. def qualities(quality_ids):
  1534. """ Get a numeric quality value out of a list of possible values """
  1535. def q(qid):
  1536. try:
  1537. return quality_ids.index(qid)
  1538. except ValueError:
  1539. return -1
  1540. return q
  1541. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1542. def limit_length(s, length):
  1543. """ Add ellipses to overly long strings """
  1544. if s is None:
  1545. return None
  1546. ELLIPSES = '...'
  1547. if len(s) > length:
  1548. return s[:length - len(ELLIPSES)] + ELLIPSES
  1549. return s
  1550. def version_tuple(v):
  1551. return tuple(int(e) for e in re.split(r'[-.]', v))
  1552. def is_outdated_version(version, limit, assume_new=True):
  1553. if not version:
  1554. return not assume_new
  1555. try:
  1556. return version_tuple(version) < version_tuple(limit)
  1557. except ValueError:
  1558. return not assume_new
  1559. def ytdl_is_updateable():
  1560. """ Returns if youtube-dl can be updated with -U """
  1561. from zipimport import zipimporter
  1562. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1563. def args_to_str(args):
  1564. # Get a short string representation for a subprocess command
  1565. return ' '.join(shlex_quote(a) for a in args)
  1566. def error_to_compat_str(err):
  1567. err_str = str(err)
  1568. # On python 2 error byte string must be decoded with proper
  1569. # encoding rather than ascii
  1570. if sys.version_info[0] < 3:
  1571. err_str = err_str.decode(preferredencoding())
  1572. return err_str
  1573. def mimetype2ext(mt):
  1574. if mt is None:
  1575. return None
  1576. ext = {
  1577. 'audio/mp4': 'm4a',
  1578. }.get(mt)
  1579. if ext is not None:
  1580. return ext
  1581. _, _, res = mt.rpartition('/')
  1582. return {
  1583. '3gpp': '3gp',
  1584. 'smptett+xml': 'tt',
  1585. 'srt': 'srt',
  1586. 'ttaf+xml': 'dfxp',
  1587. 'ttml+xml': 'ttml',
  1588. 'vtt': 'vtt',
  1589. 'x-flv': 'flv',
  1590. 'x-mp4-fragmented': 'mp4',
  1591. 'x-ms-wmv': 'wmv',
  1592. }.get(res, res)
  1593. def urlhandle_detect_ext(url_handle):
  1594. try:
  1595. url_handle.headers
  1596. getheader = lambda h: url_handle.headers[h]
  1597. except AttributeError: # Python < 3
  1598. getheader = url_handle.info().getheader
  1599. cd = getheader('Content-Disposition')
  1600. if cd:
  1601. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1602. if m:
  1603. e = determine_ext(m.group('filename'), default_ext=None)
  1604. if e:
  1605. return e
  1606. return mimetype2ext(getheader('Content-Type'))
  1607. def encode_data_uri(data, mime_type):
  1608. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1609. def age_restricted(content_limit, age_limit):
  1610. """ Returns True iff the content should be blocked """
  1611. if age_limit is None: # No limit set
  1612. return False
  1613. if content_limit is None:
  1614. return False # Content available for everyone
  1615. return age_limit < content_limit
  1616. def is_html(first_bytes):
  1617. """ Detect whether a file contains HTML by examining its first bytes. """
  1618. BOMS = [
  1619. (b'\xef\xbb\xbf', 'utf-8'),
  1620. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1621. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1622. (b'\xff\xfe', 'utf-16-le'),
  1623. (b'\xfe\xff', 'utf-16-be'),
  1624. ]
  1625. for bom, enc in BOMS:
  1626. if first_bytes.startswith(bom):
  1627. s = first_bytes[len(bom):].decode(enc, 'replace')
  1628. break
  1629. else:
  1630. s = first_bytes.decode('utf-8', 'replace')
  1631. return re.match(r'^\s*<', s)
  1632. def determine_protocol(info_dict):
  1633. protocol = info_dict.get('protocol')
  1634. if protocol is not None:
  1635. return protocol
  1636. url = info_dict['url']
  1637. if url.startswith('rtmp'):
  1638. return 'rtmp'
  1639. elif url.startswith('mms'):
  1640. return 'mms'
  1641. elif url.startswith('rtsp'):
  1642. return 'rtsp'
  1643. ext = determine_ext(url)
  1644. if ext == 'm3u8':
  1645. return 'm3u8'
  1646. elif ext == 'f4m':
  1647. return 'f4m'
  1648. return compat_urllib_parse_urlparse(url).scheme
  1649. def render_table(header_row, data):
  1650. """ Render a list of rows, each as a list of values """
  1651. table = [header_row] + data
  1652. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1653. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1654. return '\n'.join(format_str % tuple(row) for row in table)
  1655. def _match_one(filter_part, dct):
  1656. COMPARISON_OPERATORS = {
  1657. '<': operator.lt,
  1658. '<=': operator.le,
  1659. '>': operator.gt,
  1660. '>=': operator.ge,
  1661. '=': operator.eq,
  1662. '!=': operator.ne,
  1663. }
  1664. operator_rex = re.compile(r'''(?x)\s*
  1665. (?P<key>[a-z_]+)
  1666. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1667. (?:
  1668. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1669. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1670. )
  1671. \s*$
  1672. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1673. m = operator_rex.search(filter_part)
  1674. if m:
  1675. op = COMPARISON_OPERATORS[m.group('op')]
  1676. if m.group('strval') is not None:
  1677. if m.group('op') not in ('=', '!='):
  1678. raise ValueError(
  1679. 'Operator %s does not support string values!' % m.group('op'))
  1680. comparison_value = m.group('strval')
  1681. else:
  1682. try:
  1683. comparison_value = int(m.group('intval'))
  1684. except ValueError:
  1685. comparison_value = parse_filesize(m.group('intval'))
  1686. if comparison_value is None:
  1687. comparison_value = parse_filesize(m.group('intval') + 'B')
  1688. if comparison_value is None:
  1689. raise ValueError(
  1690. 'Invalid integer value %r in filter part %r' % (
  1691. m.group('intval'), filter_part))
  1692. actual_value = dct.get(m.group('key'))
  1693. if actual_value is None:
  1694. return m.group('none_inclusive')
  1695. return op(actual_value, comparison_value)
  1696. UNARY_OPERATORS = {
  1697. '': lambda v: v is not None,
  1698. '!': lambda v: v is None,
  1699. }
  1700. operator_rex = re.compile(r'''(?x)\s*
  1701. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1702. \s*$
  1703. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1704. m = operator_rex.search(filter_part)
  1705. if m:
  1706. op = UNARY_OPERATORS[m.group('op')]
  1707. actual_value = dct.get(m.group('key'))
  1708. return op(actual_value)
  1709. raise ValueError('Invalid filter part %r' % filter_part)
  1710. def match_str(filter_str, dct):
  1711. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1712. return all(
  1713. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1714. def match_filter_func(filter_str):
  1715. def _match_func(info_dict):
  1716. if match_str(filter_str, info_dict):
  1717. return None
  1718. else:
  1719. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1720. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1721. return _match_func
  1722. def parse_dfxp_time_expr(time_expr):
  1723. if not time_expr:
  1724. return
  1725. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1726. if mobj:
  1727. return float(mobj.group('time_offset'))
  1728. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  1729. if mobj:
  1730. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  1731. def srt_subtitles_timecode(seconds):
  1732. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1733. def dfxp2srt(dfxp_data):
  1734. _x = functools.partial(xpath_with_ns, ns_map={
  1735. 'ttml': 'http://www.w3.org/ns/ttml',
  1736. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1737. 'ttaf1_0604': 'http://www.w3.org/2006/04/ttaf1',
  1738. })
  1739. class TTMLPElementParser(object):
  1740. out = ''
  1741. def start(self, tag, attrib):
  1742. if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1743. self.out += '\n'
  1744. def end(self, tag):
  1745. pass
  1746. def data(self, data):
  1747. self.out += data
  1748. def close(self):
  1749. return self.out.strip()
  1750. def parse_node(node):
  1751. target = TTMLPElementParser()
  1752. parser = xml.etree.ElementTree.XMLParser(target=target)
  1753. parser.feed(xml.etree.ElementTree.tostring(node))
  1754. return parser.close()
  1755. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  1756. out = []
  1757. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall(_x('.//ttaf1_0604:p')) or dfxp.findall('.//p')
  1758. if not paras:
  1759. raise ValueError('Invalid dfxp/TTML subtitle')
  1760. for para, index in zip(paras, itertools.count(1)):
  1761. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  1762. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1763. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  1764. if begin_time is None:
  1765. continue
  1766. if not end_time:
  1767. if not dur:
  1768. continue
  1769. end_time = begin_time + dur
  1770. out.append('%d\n%s --> %s\n%s\n\n' % (
  1771. index,
  1772. srt_subtitles_timecode(begin_time),
  1773. srt_subtitles_timecode(end_time),
  1774. parse_node(para)))
  1775. return ''.join(out)
  1776. def cli_option(params, command_option, param):
  1777. param = params.get(param)
  1778. return [command_option, param] if param is not None else []
  1779. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  1780. param = params.get(param)
  1781. assert isinstance(param, bool)
  1782. if separator:
  1783. return [command_option + separator + (true_value if param else false_value)]
  1784. return [command_option, true_value if param else false_value]
  1785. def cli_valueless_option(params, command_option, param, expected_value=True):
  1786. param = params.get(param)
  1787. return [command_option] if param == expected_value else []
  1788. def cli_configuration_args(params, param, default=[]):
  1789. ex_args = params.get(param)
  1790. if ex_args is None:
  1791. return default
  1792. assert isinstance(ex_args, list)
  1793. return ex_args
  1794. class ISO639Utils(object):
  1795. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  1796. _lang_map = {
  1797. 'aa': 'aar',
  1798. 'ab': 'abk',
  1799. 'ae': 'ave',
  1800. 'af': 'afr',
  1801. 'ak': 'aka',
  1802. 'am': 'amh',
  1803. 'an': 'arg',
  1804. 'ar': 'ara',
  1805. 'as': 'asm',
  1806. 'av': 'ava',
  1807. 'ay': 'aym',
  1808. 'az': 'aze',
  1809. 'ba': 'bak',
  1810. 'be': 'bel',
  1811. 'bg': 'bul',
  1812. 'bh': 'bih',
  1813. 'bi': 'bis',
  1814. 'bm': 'bam',
  1815. 'bn': 'ben',
  1816. 'bo': 'bod',
  1817. 'br': 'bre',
  1818. 'bs': 'bos',
  1819. 'ca': 'cat',
  1820. 'ce': 'che',
  1821. 'ch': 'cha',
  1822. 'co': 'cos',
  1823. 'cr': 'cre',
  1824. 'cs': 'ces',
  1825. 'cu': 'chu',
  1826. 'cv': 'chv',
  1827. 'cy': 'cym',
  1828. 'da': 'dan',
  1829. 'de': 'deu',
  1830. 'dv': 'div',
  1831. 'dz': 'dzo',
  1832. 'ee': 'ewe',
  1833. 'el': 'ell',
  1834. 'en': 'eng',
  1835. 'eo': 'epo',
  1836. 'es': 'spa',
  1837. 'et': 'est',
  1838. 'eu': 'eus',
  1839. 'fa': 'fas',
  1840. 'ff': 'ful',
  1841. 'fi': 'fin',
  1842. 'fj': 'fij',
  1843. 'fo': 'fao',
  1844. 'fr': 'fra',
  1845. 'fy': 'fry',
  1846. 'ga': 'gle',
  1847. 'gd': 'gla',
  1848. 'gl': 'glg',
  1849. 'gn': 'grn',
  1850. 'gu': 'guj',
  1851. 'gv': 'glv',
  1852. 'ha': 'hau',
  1853. 'he': 'heb',
  1854. 'hi': 'hin',
  1855. 'ho': 'hmo',
  1856. 'hr': 'hrv',
  1857. 'ht': 'hat',
  1858. 'hu': 'hun',
  1859. 'hy': 'hye',
  1860. 'hz': 'her',
  1861. 'ia': 'ina',
  1862. 'id': 'ind',
  1863. 'ie': 'ile',
  1864. 'ig': 'ibo',
  1865. 'ii': 'iii',
  1866. 'ik': 'ipk',
  1867. 'io': 'ido',
  1868. 'is': 'isl',
  1869. 'it': 'ita',
  1870. 'iu': 'iku',
  1871. 'ja': 'jpn',
  1872. 'jv': 'jav',
  1873. 'ka': 'kat',
  1874. 'kg': 'kon',
  1875. 'ki': 'kik',
  1876. 'kj': 'kua',
  1877. 'kk': 'kaz',
  1878. 'kl': 'kal',
  1879. 'km': 'khm',
  1880. 'kn': 'kan',
  1881. 'ko': 'kor',
  1882. 'kr': 'kau',
  1883. 'ks': 'kas',
  1884. 'ku': 'kur',
  1885. 'kv': 'kom',
  1886. 'kw': 'cor',
  1887. 'ky': 'kir',
  1888. 'la': 'lat',
  1889. 'lb': 'ltz',
  1890. 'lg': 'lug',
  1891. 'li': 'lim',
  1892. 'ln': 'lin',
  1893. 'lo': 'lao',
  1894. 'lt': 'lit',
  1895. 'lu': 'lub',
  1896. 'lv': 'lav',
  1897. 'mg': 'mlg',
  1898. 'mh': 'mah',
  1899. 'mi': 'mri',
  1900. 'mk': 'mkd',
  1901. 'ml': 'mal',
  1902. 'mn': 'mon',
  1903. 'mr': 'mar',
  1904. 'ms': 'msa',
  1905. 'mt': 'mlt',
  1906. 'my': 'mya',
  1907. 'na': 'nau',
  1908. 'nb': 'nob',
  1909. 'nd': 'nde',
  1910. 'ne': 'nep',
  1911. 'ng': 'ndo',
  1912. 'nl': 'nld',
  1913. 'nn': 'nno',
  1914. 'no': 'nor',
  1915. 'nr': 'nbl',
  1916. 'nv': 'nav',
  1917. 'ny': 'nya',
  1918. 'oc': 'oci',
  1919. 'oj': 'oji',
  1920. 'om': 'orm',
  1921. 'or': 'ori',
  1922. 'os': 'oss',
  1923. 'pa': 'pan',
  1924. 'pi': 'pli',
  1925. 'pl': 'pol',
  1926. 'ps': 'pus',
  1927. 'pt': 'por',
  1928. 'qu': 'que',
  1929. 'rm': 'roh',
  1930. 'rn': 'run',
  1931. 'ro': 'ron',
  1932. 'ru': 'rus',
  1933. 'rw': 'kin',
  1934. 'sa': 'san',
  1935. 'sc': 'srd',
  1936. 'sd': 'snd',
  1937. 'se': 'sme',
  1938. 'sg': 'sag',
  1939. 'si': 'sin',
  1940. 'sk': 'slk',
  1941. 'sl': 'slv',
  1942. 'sm': 'smo',
  1943. 'sn': 'sna',
  1944. 'so': 'som',
  1945. 'sq': 'sqi',
  1946. 'sr': 'srp',
  1947. 'ss': 'ssw',
  1948. 'st': 'sot',
  1949. 'su': 'sun',
  1950. 'sv': 'swe',
  1951. 'sw': 'swa',
  1952. 'ta': 'tam',
  1953. 'te': 'tel',
  1954. 'tg': 'tgk',
  1955. 'th': 'tha',
  1956. 'ti': 'tir',
  1957. 'tk': 'tuk',
  1958. 'tl': 'tgl',
  1959. 'tn': 'tsn',
  1960. 'to': 'ton',
  1961. 'tr': 'tur',
  1962. 'ts': 'tso',
  1963. 'tt': 'tat',
  1964. 'tw': 'twi',
  1965. 'ty': 'tah',
  1966. 'ug': 'uig',
  1967. 'uk': 'ukr',
  1968. 'ur': 'urd',
  1969. 'uz': 'uzb',
  1970. 've': 'ven',
  1971. 'vi': 'vie',
  1972. 'vo': 'vol',
  1973. 'wa': 'wln',
  1974. 'wo': 'wol',
  1975. 'xh': 'xho',
  1976. 'yi': 'yid',
  1977. 'yo': 'yor',
  1978. 'za': 'zha',
  1979. 'zh': 'zho',
  1980. 'zu': 'zul',
  1981. }
  1982. @classmethod
  1983. def short2long(cls, code):
  1984. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  1985. return cls._lang_map.get(code[:2])
  1986. @classmethod
  1987. def long2short(cls, code):
  1988. """Convert language code from ISO 639-2/T to ISO 639-1"""
  1989. for short_name, long_name in cls._lang_map.items():
  1990. if long_name == code:
  1991. return short_name
  1992. class ISO3166Utils(object):
  1993. # From http://data.okfn.org/data/core/country-list
  1994. _country_map = {
  1995. 'AF': 'Afghanistan',
  1996. 'AX': 'Åland Islands',
  1997. 'AL': 'Albania',
  1998. 'DZ': 'Algeria',
  1999. 'AS': 'American Samoa',
  2000. 'AD': 'Andorra',
  2001. 'AO': 'Angola',
  2002. 'AI': 'Anguilla',
  2003. 'AQ': 'Antarctica',
  2004. 'AG': 'Antigua and Barbuda',
  2005. 'AR': 'Argentina',
  2006. 'AM': 'Armenia',
  2007. 'AW': 'Aruba',
  2008. 'AU': 'Australia',
  2009. 'AT': 'Austria',
  2010. 'AZ': 'Azerbaijan',
  2011. 'BS': 'Bahamas',
  2012. 'BH': 'Bahrain',
  2013. 'BD': 'Bangladesh',
  2014. 'BB': 'Barbados',
  2015. 'BY': 'Belarus',
  2016. 'BE': 'Belgium',
  2017. 'BZ': 'Belize',
  2018. 'BJ': 'Benin',
  2019. 'BM': 'Bermuda',
  2020. 'BT': 'Bhutan',
  2021. 'BO': 'Bolivia, Plurinational State of',
  2022. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2023. 'BA': 'Bosnia and Herzegovina',
  2024. 'BW': 'Botswana',
  2025. 'BV': 'Bouvet Island',
  2026. 'BR': 'Brazil',
  2027. 'IO': 'British Indian Ocean Territory',
  2028. 'BN': 'Brunei Darussalam',
  2029. 'BG': 'Bulgaria',
  2030. 'BF': 'Burkina Faso',
  2031. 'BI': 'Burundi',
  2032. 'KH': 'Cambodia',
  2033. 'CM': 'Cameroon',
  2034. 'CA': 'Canada',
  2035. 'CV': 'Cape Verde',
  2036. 'KY': 'Cayman Islands',
  2037. 'CF': 'Central African Republic',
  2038. 'TD': 'Chad',
  2039. 'CL': 'Chile',
  2040. 'CN': 'China',
  2041. 'CX': 'Christmas Island',
  2042. 'CC': 'Cocos (Keeling) Islands',
  2043. 'CO': 'Colombia',
  2044. 'KM': 'Comoros',
  2045. 'CG': 'Congo',
  2046. 'CD': 'Congo, the Democratic Republic of the',
  2047. 'CK': 'Cook Islands',
  2048. 'CR': 'Costa Rica',
  2049. 'CI': 'Côte d\'Ivoire',
  2050. 'HR': 'Croatia',
  2051. 'CU': 'Cuba',
  2052. 'CW': 'Curaçao',
  2053. 'CY': 'Cyprus',
  2054. 'CZ': 'Czech Republic',
  2055. 'DK': 'Denmark',
  2056. 'DJ': 'Djibouti',
  2057. 'DM': 'Dominica',
  2058. 'DO': 'Dominican Republic',
  2059. 'EC': 'Ecuador',
  2060. 'EG': 'Egypt',
  2061. 'SV': 'El Salvador',
  2062. 'GQ': 'Equatorial Guinea',
  2063. 'ER': 'Eritrea',
  2064. 'EE': 'Estonia',
  2065. 'ET': 'Ethiopia',
  2066. 'FK': 'Falkland Islands (Malvinas)',
  2067. 'FO': 'Faroe Islands',
  2068. 'FJ': 'Fiji',
  2069. 'FI': 'Finland',
  2070. 'FR': 'France',
  2071. 'GF': 'French Guiana',
  2072. 'PF': 'French Polynesia',
  2073. 'TF': 'French Southern Territories',
  2074. 'GA': 'Gabon',
  2075. 'GM': 'Gambia',
  2076. 'GE': 'Georgia',
  2077. 'DE': 'Germany',
  2078. 'GH': 'Ghana',
  2079. 'GI': 'Gibraltar',
  2080. 'GR': 'Greece',
  2081. 'GL': 'Greenland',
  2082. 'GD': 'Grenada',
  2083. 'GP': 'Guadeloupe',
  2084. 'GU': 'Guam',
  2085. 'GT': 'Guatemala',
  2086. 'GG': 'Guernsey',
  2087. 'GN': 'Guinea',
  2088. 'GW': 'Guinea-Bissau',
  2089. 'GY': 'Guyana',
  2090. 'HT': 'Haiti',
  2091. 'HM': 'Heard Island and McDonald Islands',
  2092. 'VA': 'Holy See (Vatican City State)',
  2093. 'HN': 'Honduras',
  2094. 'HK': 'Hong Kong',
  2095. 'HU': 'Hungary',
  2096. 'IS': 'Iceland',
  2097. 'IN': 'India',
  2098. 'ID': 'Indonesia',
  2099. 'IR': 'Iran, Islamic Republic of',
  2100. 'IQ': 'Iraq',
  2101. 'IE': 'Ireland',
  2102. 'IM': 'Isle of Man',
  2103. 'IL': 'Israel',
  2104. 'IT': 'Italy',
  2105. 'JM': 'Jamaica',
  2106. 'JP': 'Japan',
  2107. 'JE': 'Jersey',
  2108. 'JO': 'Jordan',
  2109. 'KZ': 'Kazakhstan',
  2110. 'KE': 'Kenya',
  2111. 'KI': 'Kiribati',
  2112. 'KP': 'Korea, Democratic People\'s Republic of',
  2113. 'KR': 'Korea, Republic of',
  2114. 'KW': 'Kuwait',
  2115. 'KG': 'Kyrgyzstan',
  2116. 'LA': 'Lao People\'s Democratic Republic',
  2117. 'LV': 'Latvia',
  2118. 'LB': 'Lebanon',
  2119. 'LS': 'Lesotho',
  2120. 'LR': 'Liberia',
  2121. 'LY': 'Libya',
  2122. 'LI': 'Liechtenstein',
  2123. 'LT': 'Lithuania',
  2124. 'LU': 'Luxembourg',
  2125. 'MO': 'Macao',
  2126. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2127. 'MG': 'Madagascar',
  2128. 'MW': 'Malawi',
  2129. 'MY': 'Malaysia',
  2130. 'MV': 'Maldives',
  2131. 'ML': 'Mali',
  2132. 'MT': 'Malta',
  2133. 'MH': 'Marshall Islands',
  2134. 'MQ': 'Martinique',
  2135. 'MR': 'Mauritania',
  2136. 'MU': 'Mauritius',
  2137. 'YT': 'Mayotte',
  2138. 'MX': 'Mexico',
  2139. 'FM': 'Micronesia, Federated States of',
  2140. 'MD': 'Moldova, Republic of',
  2141. 'MC': 'Monaco',
  2142. 'MN': 'Mongolia',
  2143. 'ME': 'Montenegro',
  2144. 'MS': 'Montserrat',
  2145. 'MA': 'Morocco',
  2146. 'MZ': 'Mozambique',
  2147. 'MM': 'Myanmar',
  2148. 'NA': 'Namibia',
  2149. 'NR': 'Nauru',
  2150. 'NP': 'Nepal',
  2151. 'NL': 'Netherlands',
  2152. 'NC': 'New Caledonia',
  2153. 'NZ': 'New Zealand',
  2154. 'NI': 'Nicaragua',
  2155. 'NE': 'Niger',
  2156. 'NG': 'Nigeria',
  2157. 'NU': 'Niue',
  2158. 'NF': 'Norfolk Island',
  2159. 'MP': 'Northern Mariana Islands',
  2160. 'NO': 'Norway',
  2161. 'OM': 'Oman',
  2162. 'PK': 'Pakistan',
  2163. 'PW': 'Palau',
  2164. 'PS': 'Palestine, State of',
  2165. 'PA': 'Panama',
  2166. 'PG': 'Papua New Guinea',
  2167. 'PY': 'Paraguay',
  2168. 'PE': 'Peru',
  2169. 'PH': 'Philippines',
  2170. 'PN': 'Pitcairn',
  2171. 'PL': 'Poland',
  2172. 'PT': 'Portugal',
  2173. 'PR': 'Puerto Rico',
  2174. 'QA': 'Qatar',
  2175. 'RE': 'Réunion',
  2176. 'RO': 'Romania',
  2177. 'RU': 'Russian Federation',
  2178. 'RW': 'Rwanda',
  2179. 'BL': 'Saint Barthélemy',
  2180. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2181. 'KN': 'Saint Kitts and Nevis',
  2182. 'LC': 'Saint Lucia',
  2183. 'MF': 'Saint Martin (French part)',
  2184. 'PM': 'Saint Pierre and Miquelon',
  2185. 'VC': 'Saint Vincent and the Grenadines',
  2186. 'WS': 'Samoa',
  2187. 'SM': 'San Marino',
  2188. 'ST': 'Sao Tome and Principe',
  2189. 'SA': 'Saudi Arabia',
  2190. 'SN': 'Senegal',
  2191. 'RS': 'Serbia',
  2192. 'SC': 'Seychelles',
  2193. 'SL': 'Sierra Leone',
  2194. 'SG': 'Singapore',
  2195. 'SX': 'Sint Maarten (Dutch part)',
  2196. 'SK': 'Slovakia',
  2197. 'SI': 'Slovenia',
  2198. 'SB': 'Solomon Islands',
  2199. 'SO': 'Somalia',
  2200. 'ZA': 'South Africa',
  2201. 'GS': 'South Georgia and the South Sandwich Islands',
  2202. 'SS': 'South Sudan',
  2203. 'ES': 'Spain',
  2204. 'LK': 'Sri Lanka',
  2205. 'SD': 'Sudan',
  2206. 'SR': 'Suriname',
  2207. 'SJ': 'Svalbard and Jan Mayen',
  2208. 'SZ': 'Swaziland',
  2209. 'SE': 'Sweden',
  2210. 'CH': 'Switzerland',
  2211. 'SY': 'Syrian Arab Republic',
  2212. 'TW': 'Taiwan, Province of China',
  2213. 'TJ': 'Tajikistan',
  2214. 'TZ': 'Tanzania, United Republic of',
  2215. 'TH': 'Thailand',
  2216. 'TL': 'Timor-Leste',
  2217. 'TG': 'Togo',
  2218. 'TK': 'Tokelau',
  2219. 'TO': 'Tonga',
  2220. 'TT': 'Trinidad and Tobago',
  2221. 'TN': 'Tunisia',
  2222. 'TR': 'Turkey',
  2223. 'TM': 'Turkmenistan',
  2224. 'TC': 'Turks and Caicos Islands',
  2225. 'TV': 'Tuvalu',
  2226. 'UG': 'Uganda',
  2227. 'UA': 'Ukraine',
  2228. 'AE': 'United Arab Emirates',
  2229. 'GB': 'United Kingdom',
  2230. 'US': 'United States',
  2231. 'UM': 'United States Minor Outlying Islands',
  2232. 'UY': 'Uruguay',
  2233. 'UZ': 'Uzbekistan',
  2234. 'VU': 'Vanuatu',
  2235. 'VE': 'Venezuela, Bolivarian Republic of',
  2236. 'VN': 'Viet Nam',
  2237. 'VG': 'Virgin Islands, British',
  2238. 'VI': 'Virgin Islands, U.S.',
  2239. 'WF': 'Wallis and Futuna',
  2240. 'EH': 'Western Sahara',
  2241. 'YE': 'Yemen',
  2242. 'ZM': 'Zambia',
  2243. 'ZW': 'Zimbabwe',
  2244. }
  2245. @classmethod
  2246. def short2full(cls, code):
  2247. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2248. return cls._country_map.get(code.upper())
  2249. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2250. def __init__(self, proxies=None):
  2251. # Set default handlers
  2252. for type in ('http', 'https'):
  2253. setattr(self, '%s_open' % type,
  2254. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2255. meth(r, proxy, type))
  2256. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2257. def proxy_open(self, req, proxy, type):
  2258. req_proxy = req.headers.get('Ytdl-request-proxy')
  2259. if req_proxy is not None:
  2260. proxy = req_proxy
  2261. del req.headers['Ytdl-request-proxy']
  2262. if proxy == '__noproxy__':
  2263. return None # No Proxy
  2264. return compat_urllib_request.ProxyHandler.proxy_open(
  2265. self, req, proxy, type)
  2266. def ohdave_rsa_encrypt(data, exponent, modulus):
  2267. '''
  2268. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  2269. Input:
  2270. data: data to encrypt, bytes-like object
  2271. exponent, modulus: parameter e and N of RSA algorithm, both integer
  2272. Output: hex string of encrypted data
  2273. Limitation: supports one block encryption only
  2274. '''
  2275. payload = int(binascii.hexlify(data[::-1]), 16)
  2276. encrypted = pow(payload, exponent, modulus)
  2277. return '%x' % encrypted
  2278. def encode_base_n(num, n, table=None):
  2279. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  2280. if not table:
  2281. table = FULL_TABLE[:n]
  2282. if n > len(table):
  2283. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  2284. if num == 0:
  2285. return table[0]
  2286. ret = ''
  2287. while num:
  2288. ret = table[num % n] + ret
  2289. num = num // n
  2290. return ret
  2291. def decode_packed_codes(code):
  2292. mobj = re.search(
  2293. r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)",
  2294. code)
  2295. obfucasted_code, base, count, symbols = mobj.groups()
  2296. base = int(base)
  2297. count = int(count)
  2298. symbols = symbols.split('|')
  2299. symbol_table = {}
  2300. while count:
  2301. count -= 1
  2302. base_n_count = encode_base_n(count, base)
  2303. symbol_table[base_n_count] = symbols[count] or base_n_count
  2304. return re.sub(
  2305. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  2306. obfucasted_code)