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.

2737 lines
81 KiB

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