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.

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