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.

2687 lines
80 KiB

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