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.

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