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.

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