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.

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