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.

2489 lines
75 KiB

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