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.

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