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.

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