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.

2760 lines
82 KiB

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