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.

2499 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[b'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. if v is None:
  1127. return default
  1128. try:
  1129. return int(v) * invscale // scale
  1130. except ValueError:
  1131. return default
  1132. def str_or_none(v, default=None):
  1133. return default if v is None else compat_str(v)
  1134. def str_to_int(int_str):
  1135. """ A more relaxed version of int_or_none """
  1136. if int_str is None:
  1137. return None
  1138. int_str = re.sub(r'[,\.\+]', '', int_str)
  1139. return int(int_str)
  1140. def float_or_none(v, scale=1, invscale=1, default=None):
  1141. if v is None:
  1142. return default
  1143. try:
  1144. return float(v) * invscale / scale
  1145. except ValueError:
  1146. return default
  1147. def parse_duration(s):
  1148. if not isinstance(s, compat_basestring):
  1149. return None
  1150. s = s.strip()
  1151. m = re.match(
  1152. r'''(?ix)(?:P?T)?
  1153. (?:
  1154. (?P<only_mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*|
  1155. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1156. \s*(?P<hours_reversed>[0-9]+)\s*(?:[:h]|hours?)\s*(?P<mins_reversed>[0-9]+)\s*(?:[:m]|mins?\.?|minutes?)\s*|
  1157. (?:
  1158. (?:
  1159. (?:(?P<days>[0-9]+)\s*(?:[:d]|days?)\s*)?
  1160. (?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*
  1161. )?
  1162. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1163. )?
  1164. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1165. )$''', s)
  1166. if not m:
  1167. return None
  1168. res = 0
  1169. if m.group('only_mins'):
  1170. return float_or_none(m.group('only_mins'), invscale=60)
  1171. if m.group('only_hours'):
  1172. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1173. if m.group('secs'):
  1174. res += int(m.group('secs'))
  1175. if m.group('mins_reversed'):
  1176. res += int(m.group('mins_reversed')) * 60
  1177. if m.group('mins'):
  1178. res += int(m.group('mins')) * 60
  1179. if m.group('hours'):
  1180. res += int(m.group('hours')) * 60 * 60
  1181. if m.group('hours_reversed'):
  1182. res += int(m.group('hours_reversed')) * 60 * 60
  1183. if m.group('days'):
  1184. res += int(m.group('days')) * 24 * 60 * 60
  1185. if m.group('ms'):
  1186. res += float(m.group('ms'))
  1187. return res
  1188. def prepend_extension(filename, ext, expected_real_ext=None):
  1189. name, real_ext = os.path.splitext(filename)
  1190. return (
  1191. '{0}.{1}{2}'.format(name, ext, real_ext)
  1192. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1193. else '{0}.{1}'.format(filename, ext))
  1194. def replace_extension(filename, ext, expected_real_ext=None):
  1195. name, real_ext = os.path.splitext(filename)
  1196. return '{0}.{1}'.format(
  1197. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1198. ext)
  1199. def check_executable(exe, args=[]):
  1200. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1201. args can be a list of arguments for a short output (like -version) """
  1202. try:
  1203. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1204. except OSError:
  1205. return False
  1206. return exe
  1207. def get_exe_version(exe, args=['--version'],
  1208. version_re=None, unrecognized='present'):
  1209. """ Returns the version of the specified executable,
  1210. or False if the executable is not present """
  1211. try:
  1212. out, _ = subprocess.Popen(
  1213. [encodeArgument(exe)] + args,
  1214. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1215. except OSError:
  1216. return False
  1217. if isinstance(out, bytes): # Python 2.x
  1218. out = out.decode('ascii', 'ignore')
  1219. return detect_exe_version(out, version_re, unrecognized)
  1220. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1221. assert isinstance(output, compat_str)
  1222. if version_re is None:
  1223. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1224. m = re.search(version_re, output)
  1225. if m:
  1226. return m.group(1)
  1227. else:
  1228. return unrecognized
  1229. class PagedList(object):
  1230. def __len__(self):
  1231. # This is only useful for tests
  1232. return len(self.getslice())
  1233. class OnDemandPagedList(PagedList):
  1234. def __init__(self, pagefunc, pagesize):
  1235. self._pagefunc = pagefunc
  1236. self._pagesize = pagesize
  1237. def getslice(self, start=0, end=None):
  1238. res = []
  1239. for pagenum in itertools.count(start // self._pagesize):
  1240. firstid = pagenum * self._pagesize
  1241. nextfirstid = pagenum * self._pagesize + self._pagesize
  1242. if start >= nextfirstid:
  1243. continue
  1244. page_results = list(self._pagefunc(pagenum))
  1245. startv = (
  1246. start % self._pagesize
  1247. if firstid <= start < nextfirstid
  1248. else 0)
  1249. endv = (
  1250. ((end - 1) % self._pagesize) + 1
  1251. if (end is not None and firstid <= end <= nextfirstid)
  1252. else None)
  1253. if startv != 0 or endv is not None:
  1254. page_results = page_results[startv:endv]
  1255. res.extend(page_results)
  1256. # A little optimization - if current page is not "full", ie. does
  1257. # not contain page_size videos then we can assume that this page
  1258. # is the last one - there are no more ids on further pages -
  1259. # i.e. no need to query again.
  1260. if len(page_results) + startv < self._pagesize:
  1261. break
  1262. # If we got the whole page, but the next page is not interesting,
  1263. # break out early as well
  1264. if end == nextfirstid:
  1265. break
  1266. return res
  1267. class InAdvancePagedList(PagedList):
  1268. def __init__(self, pagefunc, pagecount, pagesize):
  1269. self._pagefunc = pagefunc
  1270. self._pagecount = pagecount
  1271. self._pagesize = pagesize
  1272. def getslice(self, start=0, end=None):
  1273. res = []
  1274. start_page = start // self._pagesize
  1275. end_page = (
  1276. self._pagecount if end is None else (end // self._pagesize + 1))
  1277. skip_elems = start - start_page * self._pagesize
  1278. only_more = None if end is None else end - start
  1279. for pagenum in range(start_page, end_page):
  1280. page = list(self._pagefunc(pagenum))
  1281. if skip_elems:
  1282. page = page[skip_elems:]
  1283. skip_elems = None
  1284. if only_more is not None:
  1285. if len(page) < only_more:
  1286. only_more -= len(page)
  1287. else:
  1288. page = page[:only_more]
  1289. res.extend(page)
  1290. break
  1291. res.extend(page)
  1292. return res
  1293. def uppercase_escape(s):
  1294. unicode_escape = codecs.getdecoder('unicode_escape')
  1295. return re.sub(
  1296. r'\\U[0-9a-fA-F]{8}',
  1297. lambda m: unicode_escape(m.group(0))[0],
  1298. s)
  1299. def lowercase_escape(s):
  1300. unicode_escape = codecs.getdecoder('unicode_escape')
  1301. return re.sub(
  1302. r'\\u[0-9a-fA-F]{4}',
  1303. lambda m: unicode_escape(m.group(0))[0],
  1304. s)
  1305. def escape_rfc3986(s):
  1306. """Escape non-ASCII characters as suggested by RFC 3986"""
  1307. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1308. s = s.encode('utf-8')
  1309. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1310. def escape_url(url):
  1311. """Escape URL as suggested by RFC 3986"""
  1312. url_parsed = compat_urllib_parse_urlparse(url)
  1313. return url_parsed._replace(
  1314. path=escape_rfc3986(url_parsed.path),
  1315. params=escape_rfc3986(url_parsed.params),
  1316. query=escape_rfc3986(url_parsed.query),
  1317. fragment=escape_rfc3986(url_parsed.fragment)
  1318. ).geturl()
  1319. try:
  1320. struct.pack('!I', 0)
  1321. except TypeError:
  1322. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1323. def struct_pack(spec, *args):
  1324. if isinstance(spec, compat_str):
  1325. spec = spec.encode('ascii')
  1326. return struct.pack(spec, *args)
  1327. def struct_unpack(spec, *args):
  1328. if isinstance(spec, compat_str):
  1329. spec = spec.encode('ascii')
  1330. return struct.unpack(spec, *args)
  1331. else:
  1332. struct_pack = struct.pack
  1333. struct_unpack = struct.unpack
  1334. def read_batch_urls(batch_fd):
  1335. def fixup(url):
  1336. if not isinstance(url, compat_str):
  1337. url = url.decode('utf-8', 'replace')
  1338. BOM_UTF8 = '\xef\xbb\xbf'
  1339. if url.startswith(BOM_UTF8):
  1340. url = url[len(BOM_UTF8):]
  1341. url = url.strip()
  1342. if url.startswith(('#', ';', ']')):
  1343. return False
  1344. return url
  1345. with contextlib.closing(batch_fd) as fd:
  1346. return [url for url in map(fixup, fd) if url]
  1347. def urlencode_postdata(*args, **kargs):
  1348. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1349. def encode_dict(d, encoding='utf-8'):
  1350. return dict((k.encode(encoding), v.encode(encoding)) for k, v in d.items())
  1351. try:
  1352. etree_iter = xml.etree.ElementTree.Element.iter
  1353. except AttributeError: # Python <=2.6
  1354. etree_iter = lambda n: n.findall('.//*')
  1355. def parse_xml(s):
  1356. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1357. def doctype(self, name, pubid, system):
  1358. pass # Ignore doctypes
  1359. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1360. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1361. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1362. # Fix up XML parser in Python 2.x
  1363. if sys.version_info < (3, 0):
  1364. for n in etree_iter(tree):
  1365. if n.text is not None:
  1366. if not isinstance(n.text, compat_str):
  1367. n.text = n.text.decode('utf-8')
  1368. return tree
  1369. US_RATINGS = {
  1370. 'G': 0,
  1371. 'PG': 10,
  1372. 'PG-13': 13,
  1373. 'R': 16,
  1374. 'NC': 18,
  1375. }
  1376. def parse_age_limit(s):
  1377. if s is None:
  1378. return None
  1379. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1380. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1381. def strip_jsonp(code):
  1382. return re.sub(
  1383. r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1384. def js_to_json(code):
  1385. def fix_kv(m):
  1386. v = m.group(0)
  1387. if v in ('true', 'false', 'null'):
  1388. return v
  1389. if v.startswith('"'):
  1390. return v
  1391. if v.startswith("'"):
  1392. v = v[1:-1]
  1393. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1394. '\\\\': '\\\\',
  1395. "\\'": "'",
  1396. '"': '\\"',
  1397. }[m.group(0)], v)
  1398. return '"%s"' % v
  1399. res = re.sub(r'''(?x)
  1400. "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"|
  1401. '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'|
  1402. [a-zA-Z_][.a-zA-Z_0-9]*
  1403. ''', fix_kv, code)
  1404. res = re.sub(r',(\s*[\]}])', lambda m: m.group(1), res)
  1405. return res
  1406. def qualities(quality_ids):
  1407. """ Get a numeric quality value out of a list of possible values """
  1408. def q(qid):
  1409. try:
  1410. return quality_ids.index(qid)
  1411. except ValueError:
  1412. return -1
  1413. return q
  1414. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1415. def limit_length(s, length):
  1416. """ Add ellipses to overly long strings """
  1417. if s is None:
  1418. return None
  1419. ELLIPSES = '...'
  1420. if len(s) > length:
  1421. return s[:length - len(ELLIPSES)] + ELLIPSES
  1422. return s
  1423. def version_tuple(v):
  1424. return tuple(int(e) for e in re.split(r'[-.]', v))
  1425. def is_outdated_version(version, limit, assume_new=True):
  1426. if not version:
  1427. return not assume_new
  1428. try:
  1429. return version_tuple(version) < version_tuple(limit)
  1430. except ValueError:
  1431. return not assume_new
  1432. def ytdl_is_updateable():
  1433. """ Returns if youtube-dl can be updated with -U """
  1434. from zipimport import zipimporter
  1435. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1436. def args_to_str(args):
  1437. # Get a short string representation for a subprocess command
  1438. return ' '.join(shlex_quote(a) for a in args)
  1439. def mimetype2ext(mt):
  1440. _, _, res = mt.rpartition('/')
  1441. return {
  1442. 'x-ms-wmv': 'wmv',
  1443. 'x-mp4-fragmented': 'mp4',
  1444. 'ttml+xml': 'ttml',
  1445. }.get(res, res)
  1446. def urlhandle_detect_ext(url_handle):
  1447. try:
  1448. url_handle.headers
  1449. getheader = lambda h: url_handle.headers[h]
  1450. except AttributeError: # Python < 3
  1451. getheader = url_handle.info().getheader
  1452. cd = getheader('Content-Disposition')
  1453. if cd:
  1454. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1455. if m:
  1456. e = determine_ext(m.group('filename'), default_ext=None)
  1457. if e:
  1458. return e
  1459. return mimetype2ext(getheader('Content-Type'))
  1460. def age_restricted(content_limit, age_limit):
  1461. """ Returns True iff the content should be blocked """
  1462. if age_limit is None: # No limit set
  1463. return False
  1464. if content_limit is None:
  1465. return False # Content available for everyone
  1466. return age_limit < content_limit
  1467. def is_html(first_bytes):
  1468. """ Detect whether a file contains HTML by examining its first bytes. """
  1469. BOMS = [
  1470. (b'\xef\xbb\xbf', 'utf-8'),
  1471. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1472. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1473. (b'\xff\xfe', 'utf-16-le'),
  1474. (b'\xfe\xff', 'utf-16-be'),
  1475. ]
  1476. for bom, enc in BOMS:
  1477. if first_bytes.startswith(bom):
  1478. s = first_bytes[len(bom):].decode(enc, 'replace')
  1479. break
  1480. else:
  1481. s = first_bytes.decode('utf-8', 'replace')
  1482. return re.match(r'^\s*<', s)
  1483. def determine_protocol(info_dict):
  1484. protocol = info_dict.get('protocol')
  1485. if protocol is not None:
  1486. return protocol
  1487. url = info_dict['url']
  1488. if url.startswith('rtmp'):
  1489. return 'rtmp'
  1490. elif url.startswith('mms'):
  1491. return 'mms'
  1492. elif url.startswith('rtsp'):
  1493. return 'rtsp'
  1494. ext = determine_ext(url)
  1495. if ext == 'm3u8':
  1496. return 'm3u8'
  1497. elif ext == 'f4m':
  1498. return 'f4m'
  1499. return compat_urllib_parse_urlparse(url).scheme
  1500. def render_table(header_row, data):
  1501. """ Render a list of rows, each as a list of values """
  1502. table = [header_row] + data
  1503. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1504. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1505. return '\n'.join(format_str % tuple(row) for row in table)
  1506. def _match_one(filter_part, dct):
  1507. COMPARISON_OPERATORS = {
  1508. '<': operator.lt,
  1509. '<=': operator.le,
  1510. '>': operator.gt,
  1511. '>=': operator.ge,
  1512. '=': operator.eq,
  1513. '!=': operator.ne,
  1514. }
  1515. operator_rex = re.compile(r'''(?x)\s*
  1516. (?P<key>[a-z_]+)
  1517. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1518. (?:
  1519. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1520. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1521. )
  1522. \s*$
  1523. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1524. m = operator_rex.search(filter_part)
  1525. if m:
  1526. op = COMPARISON_OPERATORS[m.group('op')]
  1527. if m.group('strval') is not None:
  1528. if m.group('op') not in ('=', '!='):
  1529. raise ValueError(
  1530. 'Operator %s does not support string values!' % m.group('op'))
  1531. comparison_value = m.group('strval')
  1532. else:
  1533. try:
  1534. comparison_value = int(m.group('intval'))
  1535. except ValueError:
  1536. comparison_value = parse_filesize(m.group('intval'))
  1537. if comparison_value is None:
  1538. comparison_value = parse_filesize(m.group('intval') + 'B')
  1539. if comparison_value is None:
  1540. raise ValueError(
  1541. 'Invalid integer value %r in filter part %r' % (
  1542. m.group('intval'), filter_part))
  1543. actual_value = dct.get(m.group('key'))
  1544. if actual_value is None:
  1545. return m.group('none_inclusive')
  1546. return op(actual_value, comparison_value)
  1547. UNARY_OPERATORS = {
  1548. '': lambda v: v is not None,
  1549. '!': lambda v: v is None,
  1550. }
  1551. operator_rex = re.compile(r'''(?x)\s*
  1552. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1553. \s*$
  1554. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1555. m = operator_rex.search(filter_part)
  1556. if m:
  1557. op = UNARY_OPERATORS[m.group('op')]
  1558. actual_value = dct.get(m.group('key'))
  1559. return op(actual_value)
  1560. raise ValueError('Invalid filter part %r' % filter_part)
  1561. def match_str(filter_str, dct):
  1562. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1563. return all(
  1564. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1565. def match_filter_func(filter_str):
  1566. def _match_func(info_dict):
  1567. if match_str(filter_str, info_dict):
  1568. return None
  1569. else:
  1570. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1571. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1572. return _match_func
  1573. def parse_dfxp_time_expr(time_expr):
  1574. if not time_expr:
  1575. return 0.0
  1576. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1577. if mobj:
  1578. return float(mobj.group('time_offset'))
  1579. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:\.\d+)?)$', time_expr)
  1580. if mobj:
  1581. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3))
  1582. def srt_subtitles_timecode(seconds):
  1583. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1584. def dfxp2srt(dfxp_data):
  1585. _x = functools.partial(xpath_with_ns, ns_map={
  1586. 'ttml': 'http://www.w3.org/ns/ttml',
  1587. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1588. })
  1589. def parse_node(node):
  1590. str_or_empty = functools.partial(str_or_none, default='')
  1591. out = str_or_empty(node.text)
  1592. for child in node:
  1593. if child.tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1594. out += '\n' + str_or_empty(child.tail)
  1595. elif child.tag in (_x('ttml:span'), _x('ttaf1:span'), 'span'):
  1596. out += str_or_empty(parse_node(child))
  1597. else:
  1598. out += str_or_empty(xml.etree.ElementTree.tostring(child))
  1599. return out
  1600. dfxp = xml.etree.ElementTree.fromstring(dfxp_data.encode('utf-8'))
  1601. out = []
  1602. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall('.//p')
  1603. if not paras:
  1604. raise ValueError('Invalid dfxp/TTML subtitle')
  1605. for para, index in zip(paras, itertools.count(1)):
  1606. begin_time = parse_dfxp_time_expr(para.attrib['begin'])
  1607. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1608. if not end_time:
  1609. end_time = begin_time + parse_dfxp_time_expr(para.attrib['dur'])
  1610. out.append('%d\n%s --> %s\n%s\n\n' % (
  1611. index,
  1612. srt_subtitles_timecode(begin_time),
  1613. srt_subtitles_timecode(end_time),
  1614. parse_node(para)))
  1615. return ''.join(out)
  1616. def cli_option(params, command_option, param):
  1617. param = params.get(param)
  1618. return [command_option, param] if param is not None else []
  1619. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  1620. param = params.get(param)
  1621. assert isinstance(param, bool)
  1622. if separator:
  1623. return [command_option + separator + (true_value if param else false_value)]
  1624. return [command_option, true_value if param else false_value]
  1625. def cli_valueless_option(params, command_option, param, expected_value=True):
  1626. param = params.get(param)
  1627. return [command_option] if param == expected_value else []
  1628. def cli_configuration_args(params, param, default=[]):
  1629. ex_args = params.get(param)
  1630. if ex_args is None:
  1631. return default
  1632. assert isinstance(ex_args, list)
  1633. return ex_args
  1634. class ISO639Utils(object):
  1635. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  1636. _lang_map = {
  1637. 'aa': 'aar',
  1638. 'ab': 'abk',
  1639. 'ae': 'ave',
  1640. 'af': 'afr',
  1641. 'ak': 'aka',
  1642. 'am': 'amh',
  1643. 'an': 'arg',
  1644. 'ar': 'ara',
  1645. 'as': 'asm',
  1646. 'av': 'ava',
  1647. 'ay': 'aym',
  1648. 'az': 'aze',
  1649. 'ba': 'bak',
  1650. 'be': 'bel',
  1651. 'bg': 'bul',
  1652. 'bh': 'bih',
  1653. 'bi': 'bis',
  1654. 'bm': 'bam',
  1655. 'bn': 'ben',
  1656. 'bo': 'bod',
  1657. 'br': 'bre',
  1658. 'bs': 'bos',
  1659. 'ca': 'cat',
  1660. 'ce': 'che',
  1661. 'ch': 'cha',
  1662. 'co': 'cos',
  1663. 'cr': 'cre',
  1664. 'cs': 'ces',
  1665. 'cu': 'chu',
  1666. 'cv': 'chv',
  1667. 'cy': 'cym',
  1668. 'da': 'dan',
  1669. 'de': 'deu',
  1670. 'dv': 'div',
  1671. 'dz': 'dzo',
  1672. 'ee': 'ewe',
  1673. 'el': 'ell',
  1674. 'en': 'eng',
  1675. 'eo': 'epo',
  1676. 'es': 'spa',
  1677. 'et': 'est',
  1678. 'eu': 'eus',
  1679. 'fa': 'fas',
  1680. 'ff': 'ful',
  1681. 'fi': 'fin',
  1682. 'fj': 'fij',
  1683. 'fo': 'fao',
  1684. 'fr': 'fra',
  1685. 'fy': 'fry',
  1686. 'ga': 'gle',
  1687. 'gd': 'gla',
  1688. 'gl': 'glg',
  1689. 'gn': 'grn',
  1690. 'gu': 'guj',
  1691. 'gv': 'glv',
  1692. 'ha': 'hau',
  1693. 'he': 'heb',
  1694. 'hi': 'hin',
  1695. 'ho': 'hmo',
  1696. 'hr': 'hrv',
  1697. 'ht': 'hat',
  1698. 'hu': 'hun',
  1699. 'hy': 'hye',
  1700. 'hz': 'her',
  1701. 'ia': 'ina',
  1702. 'id': 'ind',
  1703. 'ie': 'ile',
  1704. 'ig': 'ibo',
  1705. 'ii': 'iii',
  1706. 'ik': 'ipk',
  1707. 'io': 'ido',
  1708. 'is': 'isl',
  1709. 'it': 'ita',
  1710. 'iu': 'iku',
  1711. 'ja': 'jpn',
  1712. 'jv': 'jav',
  1713. 'ka': 'kat',
  1714. 'kg': 'kon',
  1715. 'ki': 'kik',
  1716. 'kj': 'kua',
  1717. 'kk': 'kaz',
  1718. 'kl': 'kal',
  1719. 'km': 'khm',
  1720. 'kn': 'kan',
  1721. 'ko': 'kor',
  1722. 'kr': 'kau',
  1723. 'ks': 'kas',
  1724. 'ku': 'kur',
  1725. 'kv': 'kom',
  1726. 'kw': 'cor',
  1727. 'ky': 'kir',
  1728. 'la': 'lat',
  1729. 'lb': 'ltz',
  1730. 'lg': 'lug',
  1731. 'li': 'lim',
  1732. 'ln': 'lin',
  1733. 'lo': 'lao',
  1734. 'lt': 'lit',
  1735. 'lu': 'lub',
  1736. 'lv': 'lav',
  1737. 'mg': 'mlg',
  1738. 'mh': 'mah',
  1739. 'mi': 'mri',
  1740. 'mk': 'mkd',
  1741. 'ml': 'mal',
  1742. 'mn': 'mon',
  1743. 'mr': 'mar',
  1744. 'ms': 'msa',
  1745. 'mt': 'mlt',
  1746. 'my': 'mya',
  1747. 'na': 'nau',
  1748. 'nb': 'nob',
  1749. 'nd': 'nde',
  1750. 'ne': 'nep',
  1751. 'ng': 'ndo',
  1752. 'nl': 'nld',
  1753. 'nn': 'nno',
  1754. 'no': 'nor',
  1755. 'nr': 'nbl',
  1756. 'nv': 'nav',
  1757. 'ny': 'nya',
  1758. 'oc': 'oci',
  1759. 'oj': 'oji',
  1760. 'om': 'orm',
  1761. 'or': 'ori',
  1762. 'os': 'oss',
  1763. 'pa': 'pan',
  1764. 'pi': 'pli',
  1765. 'pl': 'pol',
  1766. 'ps': 'pus',
  1767. 'pt': 'por',
  1768. 'qu': 'que',
  1769. 'rm': 'roh',
  1770. 'rn': 'run',
  1771. 'ro': 'ron',
  1772. 'ru': 'rus',
  1773. 'rw': 'kin',
  1774. 'sa': 'san',
  1775. 'sc': 'srd',
  1776. 'sd': 'snd',
  1777. 'se': 'sme',
  1778. 'sg': 'sag',
  1779. 'si': 'sin',
  1780. 'sk': 'slk',
  1781. 'sl': 'slv',
  1782. 'sm': 'smo',
  1783. 'sn': 'sna',
  1784. 'so': 'som',
  1785. 'sq': 'sqi',
  1786. 'sr': 'srp',
  1787. 'ss': 'ssw',
  1788. 'st': 'sot',
  1789. 'su': 'sun',
  1790. 'sv': 'swe',
  1791. 'sw': 'swa',
  1792. 'ta': 'tam',
  1793. 'te': 'tel',
  1794. 'tg': 'tgk',
  1795. 'th': 'tha',
  1796. 'ti': 'tir',
  1797. 'tk': 'tuk',
  1798. 'tl': 'tgl',
  1799. 'tn': 'tsn',
  1800. 'to': 'ton',
  1801. 'tr': 'tur',
  1802. 'ts': 'tso',
  1803. 'tt': 'tat',
  1804. 'tw': 'twi',
  1805. 'ty': 'tah',
  1806. 'ug': 'uig',
  1807. 'uk': 'ukr',
  1808. 'ur': 'urd',
  1809. 'uz': 'uzb',
  1810. 've': 'ven',
  1811. 'vi': 'vie',
  1812. 'vo': 'vol',
  1813. 'wa': 'wln',
  1814. 'wo': 'wol',
  1815. 'xh': 'xho',
  1816. 'yi': 'yid',
  1817. 'yo': 'yor',
  1818. 'za': 'zha',
  1819. 'zh': 'zho',
  1820. 'zu': 'zul',
  1821. }
  1822. @classmethod
  1823. def short2long(cls, code):
  1824. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  1825. return cls._lang_map.get(code[:2])
  1826. @classmethod
  1827. def long2short(cls, code):
  1828. """Convert language code from ISO 639-2/T to ISO 639-1"""
  1829. for short_name, long_name in cls._lang_map.items():
  1830. if long_name == code:
  1831. return short_name
  1832. class ISO3166Utils(object):
  1833. # From http://data.okfn.org/data/core/country-list
  1834. _country_map = {
  1835. 'AF': 'Afghanistan',
  1836. 'AX': 'Åland Islands',
  1837. 'AL': 'Albania',
  1838. 'DZ': 'Algeria',
  1839. 'AS': 'American Samoa',
  1840. 'AD': 'Andorra',
  1841. 'AO': 'Angola',
  1842. 'AI': 'Anguilla',
  1843. 'AQ': 'Antarctica',
  1844. 'AG': 'Antigua and Barbuda',
  1845. 'AR': 'Argentina',
  1846. 'AM': 'Armenia',
  1847. 'AW': 'Aruba',
  1848. 'AU': 'Australia',
  1849. 'AT': 'Austria',
  1850. 'AZ': 'Azerbaijan',
  1851. 'BS': 'Bahamas',
  1852. 'BH': 'Bahrain',
  1853. 'BD': 'Bangladesh',
  1854. 'BB': 'Barbados',
  1855. 'BY': 'Belarus',
  1856. 'BE': 'Belgium',
  1857. 'BZ': 'Belize',
  1858. 'BJ': 'Benin',
  1859. 'BM': 'Bermuda',
  1860. 'BT': 'Bhutan',
  1861. 'BO': 'Bolivia, Plurinational State of',
  1862. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  1863. 'BA': 'Bosnia and Herzegovina',
  1864. 'BW': 'Botswana',
  1865. 'BV': 'Bouvet Island',
  1866. 'BR': 'Brazil',
  1867. 'IO': 'British Indian Ocean Territory',
  1868. 'BN': 'Brunei Darussalam',
  1869. 'BG': 'Bulgaria',
  1870. 'BF': 'Burkina Faso',
  1871. 'BI': 'Burundi',
  1872. 'KH': 'Cambodia',
  1873. 'CM': 'Cameroon',
  1874. 'CA': 'Canada',
  1875. 'CV': 'Cape Verde',
  1876. 'KY': 'Cayman Islands',
  1877. 'CF': 'Central African Republic',
  1878. 'TD': 'Chad',
  1879. 'CL': 'Chile',
  1880. 'CN': 'China',
  1881. 'CX': 'Christmas Island',
  1882. 'CC': 'Cocos (Keeling) Islands',
  1883. 'CO': 'Colombia',
  1884. 'KM': 'Comoros',
  1885. 'CG': 'Congo',
  1886. 'CD': 'Congo, the Democratic Republic of the',
  1887. 'CK': 'Cook Islands',
  1888. 'CR': 'Costa Rica',
  1889. 'CI': 'Côte d\'Ivoire',
  1890. 'HR': 'Croatia',
  1891. 'CU': 'Cuba',
  1892. 'CW': 'Curaçao',
  1893. 'CY': 'Cyprus',
  1894. 'CZ': 'Czech Republic',
  1895. 'DK': 'Denmark',
  1896. 'DJ': 'Djibouti',
  1897. 'DM': 'Dominica',
  1898. 'DO': 'Dominican Republic',
  1899. 'EC': 'Ecuador',
  1900. 'EG': 'Egypt',
  1901. 'SV': 'El Salvador',
  1902. 'GQ': 'Equatorial Guinea',
  1903. 'ER': 'Eritrea',
  1904. 'EE': 'Estonia',
  1905. 'ET': 'Ethiopia',
  1906. 'FK': 'Falkland Islands (Malvinas)',
  1907. 'FO': 'Faroe Islands',
  1908. 'FJ': 'Fiji',
  1909. 'FI': 'Finland',
  1910. 'FR': 'France',
  1911. 'GF': 'French Guiana',
  1912. 'PF': 'French Polynesia',
  1913. 'TF': 'French Southern Territories',
  1914. 'GA': 'Gabon',
  1915. 'GM': 'Gambia',
  1916. 'GE': 'Georgia',
  1917. 'DE': 'Germany',
  1918. 'GH': 'Ghana',
  1919. 'GI': 'Gibraltar',
  1920. 'GR': 'Greece',
  1921. 'GL': 'Greenland',
  1922. 'GD': 'Grenada',
  1923. 'GP': 'Guadeloupe',
  1924. 'GU': 'Guam',
  1925. 'GT': 'Guatemala',
  1926. 'GG': 'Guernsey',
  1927. 'GN': 'Guinea',
  1928. 'GW': 'Guinea-Bissau',
  1929. 'GY': 'Guyana',
  1930. 'HT': 'Haiti',
  1931. 'HM': 'Heard Island and McDonald Islands',
  1932. 'VA': 'Holy See (Vatican City State)',
  1933. 'HN': 'Honduras',
  1934. 'HK': 'Hong Kong',
  1935. 'HU': 'Hungary',
  1936. 'IS': 'Iceland',
  1937. 'IN': 'India',
  1938. 'ID': 'Indonesia',
  1939. 'IR': 'Iran, Islamic Republic of',
  1940. 'IQ': 'Iraq',
  1941. 'IE': 'Ireland',
  1942. 'IM': 'Isle of Man',
  1943. 'IL': 'Israel',
  1944. 'IT': 'Italy',
  1945. 'JM': 'Jamaica',
  1946. 'JP': 'Japan',
  1947. 'JE': 'Jersey',
  1948. 'JO': 'Jordan',
  1949. 'KZ': 'Kazakhstan',
  1950. 'KE': 'Kenya',
  1951. 'KI': 'Kiribati',
  1952. 'KP': 'Korea, Democratic People\'s Republic of',
  1953. 'KR': 'Korea, Republic of',
  1954. 'KW': 'Kuwait',
  1955. 'KG': 'Kyrgyzstan',
  1956. 'LA': 'Lao People\'s Democratic Republic',
  1957. 'LV': 'Latvia',
  1958. 'LB': 'Lebanon',
  1959. 'LS': 'Lesotho',
  1960. 'LR': 'Liberia',
  1961. 'LY': 'Libya',
  1962. 'LI': 'Liechtenstein',
  1963. 'LT': 'Lithuania',
  1964. 'LU': 'Luxembourg',
  1965. 'MO': 'Macao',
  1966. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  1967. 'MG': 'Madagascar',
  1968. 'MW': 'Malawi',
  1969. 'MY': 'Malaysia',
  1970. 'MV': 'Maldives',
  1971. 'ML': 'Mali',
  1972. 'MT': 'Malta',
  1973. 'MH': 'Marshall Islands',
  1974. 'MQ': 'Martinique',
  1975. 'MR': 'Mauritania',
  1976. 'MU': 'Mauritius',
  1977. 'YT': 'Mayotte',
  1978. 'MX': 'Mexico',
  1979. 'FM': 'Micronesia, Federated States of',
  1980. 'MD': 'Moldova, Republic of',
  1981. 'MC': 'Monaco',
  1982. 'MN': 'Mongolia',
  1983. 'ME': 'Montenegro',
  1984. 'MS': 'Montserrat',
  1985. 'MA': 'Morocco',
  1986. 'MZ': 'Mozambique',
  1987. 'MM': 'Myanmar',
  1988. 'NA': 'Namibia',
  1989. 'NR': 'Nauru',
  1990. 'NP': 'Nepal',
  1991. 'NL': 'Netherlands',
  1992. 'NC': 'New Caledonia',
  1993. 'NZ': 'New Zealand',
  1994. 'NI': 'Nicaragua',
  1995. 'NE': 'Niger',
  1996. 'NG': 'Nigeria',
  1997. 'NU': 'Niue',
  1998. 'NF': 'Norfolk Island',
  1999. 'MP': 'Northern Mariana Islands',
  2000. 'NO': 'Norway',
  2001. 'OM': 'Oman',
  2002. 'PK': 'Pakistan',
  2003. 'PW': 'Palau',
  2004. 'PS': 'Palestine, State of',
  2005. 'PA': 'Panama',
  2006. 'PG': 'Papua New Guinea',
  2007. 'PY': 'Paraguay',
  2008. 'PE': 'Peru',
  2009. 'PH': 'Philippines',
  2010. 'PN': 'Pitcairn',
  2011. 'PL': 'Poland',
  2012. 'PT': 'Portugal',
  2013. 'PR': 'Puerto Rico',
  2014. 'QA': 'Qatar',
  2015. 'RE': 'Réunion',
  2016. 'RO': 'Romania',
  2017. 'RU': 'Russian Federation',
  2018. 'RW': 'Rwanda',
  2019. 'BL': 'Saint Barthélemy',
  2020. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2021. 'KN': 'Saint Kitts and Nevis',
  2022. 'LC': 'Saint Lucia',
  2023. 'MF': 'Saint Martin (French part)',
  2024. 'PM': 'Saint Pierre and Miquelon',
  2025. 'VC': 'Saint Vincent and the Grenadines',
  2026. 'WS': 'Samoa',
  2027. 'SM': 'San Marino',
  2028. 'ST': 'Sao Tome and Principe',
  2029. 'SA': 'Saudi Arabia',
  2030. 'SN': 'Senegal',
  2031. 'RS': 'Serbia',
  2032. 'SC': 'Seychelles',
  2033. 'SL': 'Sierra Leone',
  2034. 'SG': 'Singapore',
  2035. 'SX': 'Sint Maarten (Dutch part)',
  2036. 'SK': 'Slovakia',
  2037. 'SI': 'Slovenia',
  2038. 'SB': 'Solomon Islands',
  2039. 'SO': 'Somalia',
  2040. 'ZA': 'South Africa',
  2041. 'GS': 'South Georgia and the South Sandwich Islands',
  2042. 'SS': 'South Sudan',
  2043. 'ES': 'Spain',
  2044. 'LK': 'Sri Lanka',
  2045. 'SD': 'Sudan',
  2046. 'SR': 'Suriname',
  2047. 'SJ': 'Svalbard and Jan Mayen',
  2048. 'SZ': 'Swaziland',
  2049. 'SE': 'Sweden',
  2050. 'CH': 'Switzerland',
  2051. 'SY': 'Syrian Arab Republic',
  2052. 'TW': 'Taiwan, Province of China',
  2053. 'TJ': 'Tajikistan',
  2054. 'TZ': 'Tanzania, United Republic of',
  2055. 'TH': 'Thailand',
  2056. 'TL': 'Timor-Leste',
  2057. 'TG': 'Togo',
  2058. 'TK': 'Tokelau',
  2059. 'TO': 'Tonga',
  2060. 'TT': 'Trinidad and Tobago',
  2061. 'TN': 'Tunisia',
  2062. 'TR': 'Turkey',
  2063. 'TM': 'Turkmenistan',
  2064. 'TC': 'Turks and Caicos Islands',
  2065. 'TV': 'Tuvalu',
  2066. 'UG': 'Uganda',
  2067. 'UA': 'Ukraine',
  2068. 'AE': 'United Arab Emirates',
  2069. 'GB': 'United Kingdom',
  2070. 'US': 'United States',
  2071. 'UM': 'United States Minor Outlying Islands',
  2072. 'UY': 'Uruguay',
  2073. 'UZ': 'Uzbekistan',
  2074. 'VU': 'Vanuatu',
  2075. 'VE': 'Venezuela, Bolivarian Republic of',
  2076. 'VN': 'Viet Nam',
  2077. 'VG': 'Virgin Islands, British',
  2078. 'VI': 'Virgin Islands, U.S.',
  2079. 'WF': 'Wallis and Futuna',
  2080. 'EH': 'Western Sahara',
  2081. 'YE': 'Yemen',
  2082. 'ZM': 'Zambia',
  2083. 'ZW': 'Zimbabwe',
  2084. }
  2085. @classmethod
  2086. def short2full(cls, code):
  2087. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2088. return cls._country_map.get(code.upper())
  2089. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2090. def __init__(self, proxies=None):
  2091. # Set default handlers
  2092. for type in ('http', 'https'):
  2093. setattr(self, '%s_open' % type,
  2094. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2095. meth(r, proxy, type))
  2096. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2097. def proxy_open(self, req, proxy, type):
  2098. req_proxy = req.headers.get('Ytdl-request-proxy')
  2099. if req_proxy is not None:
  2100. proxy = req_proxy
  2101. del req.headers['Ytdl-request-proxy']
  2102. if proxy == '__noproxy__':
  2103. return None # No Proxy
  2104. return compat_urllib_request.ProxyHandler.proxy_open(
  2105. self, req, proxy, type)