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.

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