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.

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