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.

2496 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. return compat_str(upload_date)
  755. def determine_ext(url, default_ext='unknown_video'):
  756. if url is None:
  757. return default_ext
  758. guess = url.partition('?')[0].rpartition('.')[2]
  759. if re.match(r'^[A-Za-z0-9]+$', guess):
  760. return guess
  761. else:
  762. return default_ext
  763. def subtitles_filename(filename, sub_lang, sub_format):
  764. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  765. def date_from_str(date_str):
  766. """
  767. Return a datetime object from a string in the format YYYYMMDD or
  768. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  769. today = datetime.date.today()
  770. if date_str in ('now', 'today'):
  771. return today
  772. if date_str == 'yesterday':
  773. return today - datetime.timedelta(days=1)
  774. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  775. if match is not None:
  776. sign = match.group('sign')
  777. time = int(match.group('time'))
  778. if sign == '-':
  779. time = -time
  780. unit = match.group('unit')
  781. # A bad aproximation?
  782. if unit == 'month':
  783. unit = 'day'
  784. time *= 30
  785. elif unit == 'year':
  786. unit = 'day'
  787. time *= 365
  788. unit += 's'
  789. delta = datetime.timedelta(**{unit: time})
  790. return today + delta
  791. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  792. def hyphenate_date(date_str):
  793. """
  794. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  795. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  796. if match is not None:
  797. return '-'.join(match.groups())
  798. else:
  799. return date_str
  800. class DateRange(object):
  801. """Represents a time interval between two dates"""
  802. def __init__(self, start=None, end=None):
  803. """start and end must be strings in the format accepted by date"""
  804. if start is not None:
  805. self.start = date_from_str(start)
  806. else:
  807. self.start = datetime.datetime.min.date()
  808. if end is not None:
  809. self.end = date_from_str(end)
  810. else:
  811. self.end = datetime.datetime.max.date()
  812. if self.start > self.end:
  813. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  814. @classmethod
  815. def day(cls, day):
  816. """Returns a range that only contains the given day"""
  817. return cls(day, day)
  818. def __contains__(self, date):
  819. """Check if the date is in the range"""
  820. if not isinstance(date, datetime.date):
  821. date = date_from_str(date)
  822. return self.start <= date <= self.end
  823. def __str__(self):
  824. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  825. def platform_name():
  826. """ Returns the platform name as a compat_str """
  827. res = platform.platform()
  828. if isinstance(res, bytes):
  829. res = res.decode(preferredencoding())
  830. assert isinstance(res, compat_str)
  831. return res
  832. def _windows_write_string(s, out):
  833. """ Returns True if the string was written using special methods,
  834. False if it has yet to be written out."""
  835. # Adapted from http://stackoverflow.com/a/3259271/35070
  836. import ctypes
  837. import ctypes.wintypes
  838. WIN_OUTPUT_IDS = {
  839. 1: -11,
  840. 2: -12,
  841. }
  842. try:
  843. fileno = out.fileno()
  844. except AttributeError:
  845. # If the output stream doesn't have a fileno, it's virtual
  846. return False
  847. except io.UnsupportedOperation:
  848. # Some strange Windows pseudo files?
  849. return False
  850. if fileno not in WIN_OUTPUT_IDS:
  851. return False
  852. GetStdHandle = ctypes.WINFUNCTYPE(
  853. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  854. (b"GetStdHandle", ctypes.windll.kernel32))
  855. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  856. WriteConsoleW = ctypes.WINFUNCTYPE(
  857. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  858. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  859. ctypes.wintypes.LPVOID)((b"WriteConsoleW", ctypes.windll.kernel32))
  860. written = ctypes.wintypes.DWORD(0)
  861. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b"GetFileType", ctypes.windll.kernel32))
  862. FILE_TYPE_CHAR = 0x0002
  863. FILE_TYPE_REMOTE = 0x8000
  864. GetConsoleMode = ctypes.WINFUNCTYPE(
  865. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  866. ctypes.POINTER(ctypes.wintypes.DWORD))(
  867. (b"GetConsoleMode", ctypes.windll.kernel32))
  868. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  869. def not_a_console(handle):
  870. if handle == INVALID_HANDLE_VALUE or handle is None:
  871. return True
  872. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  873. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  874. if not_a_console(h):
  875. return False
  876. def next_nonbmp_pos(s):
  877. try:
  878. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  879. except StopIteration:
  880. return len(s)
  881. while s:
  882. count = min(next_nonbmp_pos(s), 1024)
  883. ret = WriteConsoleW(
  884. h, s, count if count else 2, ctypes.byref(written), None)
  885. if ret == 0:
  886. raise OSError('Failed to write string')
  887. if not count: # We just wrote a non-BMP character
  888. assert written.value == 2
  889. s = s[1:]
  890. else:
  891. assert written.value > 0
  892. s = s[written.value:]
  893. return True
  894. def write_string(s, out=None, encoding=None):
  895. if out is None:
  896. out = sys.stderr
  897. assert type(s) == compat_str
  898. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  899. if _windows_write_string(s, out):
  900. return
  901. if ('b' in getattr(out, 'mode', '') or
  902. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  903. byt = s.encode(encoding or preferredencoding(), 'ignore')
  904. out.write(byt)
  905. elif hasattr(out, 'buffer'):
  906. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  907. byt = s.encode(enc, 'ignore')
  908. out.buffer.write(byt)
  909. else:
  910. out.write(s)
  911. out.flush()
  912. def bytes_to_intlist(bs):
  913. if not bs:
  914. return []
  915. if isinstance(bs[0], int): # Python 3
  916. return list(bs)
  917. else:
  918. return [ord(c) for c in bs]
  919. def intlist_to_bytes(xs):
  920. if not xs:
  921. return b''
  922. return struct_pack('%dB' % len(xs), *xs)
  923. # Cross-platform file locking
  924. if sys.platform == 'win32':
  925. import ctypes.wintypes
  926. import msvcrt
  927. class OVERLAPPED(ctypes.Structure):
  928. _fields_ = [
  929. ('Internal', ctypes.wintypes.LPVOID),
  930. ('InternalHigh', ctypes.wintypes.LPVOID),
  931. ('Offset', ctypes.wintypes.DWORD),
  932. ('OffsetHigh', ctypes.wintypes.DWORD),
  933. ('hEvent', ctypes.wintypes.HANDLE),
  934. ]
  935. kernel32 = ctypes.windll.kernel32
  936. LockFileEx = kernel32.LockFileEx
  937. LockFileEx.argtypes = [
  938. ctypes.wintypes.HANDLE, # hFile
  939. ctypes.wintypes.DWORD, # dwFlags
  940. ctypes.wintypes.DWORD, # dwReserved
  941. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  942. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  943. ctypes.POINTER(OVERLAPPED) # Overlapped
  944. ]
  945. LockFileEx.restype = ctypes.wintypes.BOOL
  946. UnlockFileEx = kernel32.UnlockFileEx
  947. UnlockFileEx.argtypes = [
  948. ctypes.wintypes.HANDLE, # hFile
  949. ctypes.wintypes.DWORD, # dwReserved
  950. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  951. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  952. ctypes.POINTER(OVERLAPPED) # Overlapped
  953. ]
  954. UnlockFileEx.restype = ctypes.wintypes.BOOL
  955. whole_low = 0xffffffff
  956. whole_high = 0x7fffffff
  957. def _lock_file(f, exclusive):
  958. overlapped = OVERLAPPED()
  959. overlapped.Offset = 0
  960. overlapped.OffsetHigh = 0
  961. overlapped.hEvent = 0
  962. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  963. handle = msvcrt.get_osfhandle(f.fileno())
  964. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  965. whole_low, whole_high, f._lock_file_overlapped_p):
  966. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  967. def _unlock_file(f):
  968. assert f._lock_file_overlapped_p
  969. handle = msvcrt.get_osfhandle(f.fileno())
  970. if not UnlockFileEx(handle, 0,
  971. whole_low, whole_high, f._lock_file_overlapped_p):
  972. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  973. else:
  974. import fcntl
  975. def _lock_file(f, exclusive):
  976. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  977. def _unlock_file(f):
  978. fcntl.flock(f, fcntl.LOCK_UN)
  979. class locked_file(object):
  980. def __init__(self, filename, mode, encoding=None):
  981. assert mode in ['r', 'a', 'w']
  982. self.f = io.open(filename, mode, encoding=encoding)
  983. self.mode = mode
  984. def __enter__(self):
  985. exclusive = self.mode != 'r'
  986. try:
  987. _lock_file(self.f, exclusive)
  988. except IOError:
  989. self.f.close()
  990. raise
  991. return self
  992. def __exit__(self, etype, value, traceback):
  993. try:
  994. _unlock_file(self.f)
  995. finally:
  996. self.f.close()
  997. def __iter__(self):
  998. return iter(self.f)
  999. def write(self, *args):
  1000. return self.f.write(*args)
  1001. def read(self, *args):
  1002. return self.f.read(*args)
  1003. def get_filesystem_encoding():
  1004. encoding = sys.getfilesystemencoding()
  1005. return encoding if encoding is not None else 'utf-8'
  1006. def shell_quote(args):
  1007. quoted_args = []
  1008. encoding = get_filesystem_encoding()
  1009. for a in args:
  1010. if isinstance(a, bytes):
  1011. # We may get a filename encoded with 'encodeFilename'
  1012. a = a.decode(encoding)
  1013. quoted_args.append(pipes.quote(a))
  1014. return ' '.join(quoted_args)
  1015. def smuggle_url(url, data):
  1016. """ Pass additional data in a URL for internal use. """
  1017. sdata = compat_urllib_parse.urlencode(
  1018. {'__youtubedl_smuggle': json.dumps(data)})
  1019. return url + '#' + sdata
  1020. def unsmuggle_url(smug_url, default=None):
  1021. if '#__youtubedl_smuggle' not in smug_url:
  1022. return smug_url, default
  1023. url, _, sdata = smug_url.rpartition('#')
  1024. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  1025. data = json.loads(jsond)
  1026. return url, data
  1027. def format_bytes(bytes):
  1028. if bytes is None:
  1029. return 'N/A'
  1030. if type(bytes) is str:
  1031. bytes = float(bytes)
  1032. if bytes == 0.0:
  1033. exponent = 0
  1034. else:
  1035. exponent = int(math.log(bytes, 1024.0))
  1036. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  1037. converted = float(bytes) / float(1024 ** exponent)
  1038. return '%.2f%s' % (converted, suffix)
  1039. def parse_filesize(s):
  1040. if s is None:
  1041. return None
  1042. # The lower-case forms are of course incorrect and inofficial,
  1043. # but we support those too
  1044. _UNIT_TABLE = {
  1045. 'B': 1,
  1046. 'b': 1,
  1047. 'KiB': 1024,
  1048. 'KB': 1000,
  1049. 'kB': 1024,
  1050. 'Kb': 1000,
  1051. 'MiB': 1024 ** 2,
  1052. 'MB': 1000 ** 2,
  1053. 'mB': 1024 ** 2,
  1054. 'Mb': 1000 ** 2,
  1055. 'GiB': 1024 ** 3,
  1056. 'GB': 1000 ** 3,
  1057. 'gB': 1024 ** 3,
  1058. 'Gb': 1000 ** 3,
  1059. 'TiB': 1024 ** 4,
  1060. 'TB': 1000 ** 4,
  1061. 'tB': 1024 ** 4,
  1062. 'Tb': 1000 ** 4,
  1063. 'PiB': 1024 ** 5,
  1064. 'PB': 1000 ** 5,
  1065. 'pB': 1024 ** 5,
  1066. 'Pb': 1000 ** 5,
  1067. 'EiB': 1024 ** 6,
  1068. 'EB': 1000 ** 6,
  1069. 'eB': 1024 ** 6,
  1070. 'Eb': 1000 ** 6,
  1071. 'ZiB': 1024 ** 7,
  1072. 'ZB': 1000 ** 7,
  1073. 'zB': 1024 ** 7,
  1074. 'Zb': 1000 ** 7,
  1075. 'YiB': 1024 ** 8,
  1076. 'YB': 1000 ** 8,
  1077. 'yB': 1024 ** 8,
  1078. 'Yb': 1000 ** 8,
  1079. }
  1080. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  1081. m = re.match(
  1082. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  1083. if not m:
  1084. return None
  1085. num_str = m.group('num').replace(',', '.')
  1086. mult = _UNIT_TABLE[m.group('unit')]
  1087. return int(float(num_str) * mult)
  1088. def month_by_name(name):
  1089. """ Return the number of a month by (locale-independently) English name """
  1090. try:
  1091. return ENGLISH_MONTH_NAMES.index(name) + 1
  1092. except ValueError:
  1093. return None
  1094. def month_by_abbreviation(abbrev):
  1095. """ Return the number of a month by (locale-independently) English
  1096. abbreviations """
  1097. try:
  1098. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1099. except ValueError:
  1100. return None
  1101. def fix_xml_ampersands(xml_str):
  1102. """Replace all the '&' by '&amp;' in XML"""
  1103. return re.sub(
  1104. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1105. '&amp;',
  1106. xml_str)
  1107. def setproctitle(title):
  1108. assert isinstance(title, compat_str)
  1109. try:
  1110. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  1111. except OSError:
  1112. return
  1113. title_bytes = title.encode('utf-8')
  1114. buf = ctypes.create_string_buffer(len(title_bytes))
  1115. buf.value = title_bytes
  1116. try:
  1117. libc.prctl(15, buf, 0, 0, 0)
  1118. except AttributeError:
  1119. return # Strange libc, just skip this
  1120. def remove_start(s, start):
  1121. if s.startswith(start):
  1122. return s[len(start):]
  1123. return s
  1124. def remove_end(s, end):
  1125. if s.endswith(end):
  1126. return s[:-len(end)]
  1127. return s
  1128. def url_basename(url):
  1129. path = compat_urlparse.urlparse(url).path
  1130. return path.strip('/').split('/')[-1]
  1131. class HEADRequest(compat_urllib_request.Request):
  1132. def get_method(self):
  1133. return "HEAD"
  1134. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1135. if get_attr:
  1136. if v is not None:
  1137. v = getattr(v, get_attr, None)
  1138. if v == '':
  1139. v = None
  1140. if v is None:
  1141. return default
  1142. try:
  1143. return int(v) * invscale // scale
  1144. except ValueError:
  1145. return default
  1146. def str_or_none(v, default=None):
  1147. return default if v is None else compat_str(v)
  1148. def str_to_int(int_str):
  1149. """ A more relaxed version of int_or_none """
  1150. if int_str is None:
  1151. return None
  1152. int_str = re.sub(r'[,\.\+]', '', int_str)
  1153. return int(int_str)
  1154. def float_or_none(v, scale=1, invscale=1, default=None):
  1155. if v is None:
  1156. return default
  1157. try:
  1158. return float(v) * invscale / scale
  1159. except ValueError:
  1160. return default
  1161. def parse_duration(s):
  1162. if not isinstance(s, compat_basestring):
  1163. return None
  1164. s = s.strip()
  1165. m = re.match(
  1166. r'''(?ix)(?:P?T)?
  1167. (?:
  1168. (?P<only_mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*|
  1169. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1170. \s*(?P<hours_reversed>[0-9]+)\s*(?:[:h]|hours?)\s*(?P<mins_reversed>[0-9]+)\s*(?:[:m]|mins?\.?|minutes?)\s*|
  1171. (?:
  1172. (?:
  1173. (?:(?P<days>[0-9]+)\s*(?:[:d]|days?)\s*)?
  1174. (?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*
  1175. )?
  1176. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1177. )?
  1178. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1179. )$''', s)
  1180. if not m:
  1181. return None
  1182. res = 0
  1183. if m.group('only_mins'):
  1184. return float_or_none(m.group('only_mins'), invscale=60)
  1185. if m.group('only_hours'):
  1186. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1187. if m.group('secs'):
  1188. res += int(m.group('secs'))
  1189. if m.group('mins_reversed'):
  1190. res += int(m.group('mins_reversed')) * 60
  1191. if m.group('mins'):
  1192. res += int(m.group('mins')) * 60
  1193. if m.group('hours'):
  1194. res += int(m.group('hours')) * 60 * 60
  1195. if m.group('hours_reversed'):
  1196. res += int(m.group('hours_reversed')) * 60 * 60
  1197. if m.group('days'):
  1198. res += int(m.group('days')) * 24 * 60 * 60
  1199. if m.group('ms'):
  1200. res += float(m.group('ms'))
  1201. return res
  1202. def prepend_extension(filename, ext, expected_real_ext=None):
  1203. name, real_ext = os.path.splitext(filename)
  1204. return (
  1205. '{0}.{1}{2}'.format(name, ext, real_ext)
  1206. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1207. else '{0}.{1}'.format(filename, ext))
  1208. def replace_extension(filename, ext, expected_real_ext=None):
  1209. name, real_ext = os.path.splitext(filename)
  1210. return '{0}.{1}'.format(
  1211. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1212. ext)
  1213. def check_executable(exe, args=[]):
  1214. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1215. args can be a list of arguments for a short output (like -version) """
  1216. try:
  1217. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1218. except OSError:
  1219. return False
  1220. return exe
  1221. def get_exe_version(exe, args=['--version'],
  1222. version_re=None, unrecognized='present'):
  1223. """ Returns the version of the specified executable,
  1224. or False if the executable is not present """
  1225. try:
  1226. out, _ = subprocess.Popen(
  1227. [encodeArgument(exe)] + args,
  1228. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1229. except OSError:
  1230. return False
  1231. if isinstance(out, bytes): # Python 2.x
  1232. out = out.decode('ascii', 'ignore')
  1233. return detect_exe_version(out, version_re, unrecognized)
  1234. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1235. assert isinstance(output, compat_str)
  1236. if version_re is None:
  1237. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1238. m = re.search(version_re, output)
  1239. if m:
  1240. return m.group(1)
  1241. else:
  1242. return unrecognized
  1243. class PagedList(object):
  1244. def __len__(self):
  1245. # This is only useful for tests
  1246. return len(self.getslice())
  1247. class OnDemandPagedList(PagedList):
  1248. def __init__(self, pagefunc, pagesize):
  1249. self._pagefunc = pagefunc
  1250. self._pagesize = pagesize
  1251. def getslice(self, start=0, end=None):
  1252. res = []
  1253. for pagenum in itertools.count(start // self._pagesize):
  1254. firstid = pagenum * self._pagesize
  1255. nextfirstid = pagenum * self._pagesize + self._pagesize
  1256. if start >= nextfirstid:
  1257. continue
  1258. page_results = list(self._pagefunc(pagenum))
  1259. startv = (
  1260. start % self._pagesize
  1261. if firstid <= start < nextfirstid
  1262. else 0)
  1263. endv = (
  1264. ((end - 1) % self._pagesize) + 1
  1265. if (end is not None and firstid <= end <= nextfirstid)
  1266. else None)
  1267. if startv != 0 or endv is not None:
  1268. page_results = page_results[startv:endv]
  1269. res.extend(page_results)
  1270. # A little optimization - if current page is not "full", ie. does
  1271. # not contain page_size videos then we can assume that this page
  1272. # is the last one - there are no more ids on further pages -
  1273. # i.e. no need to query again.
  1274. if len(page_results) + startv < self._pagesize:
  1275. break
  1276. # If we got the whole page, but the next page is not interesting,
  1277. # break out early as well
  1278. if end == nextfirstid:
  1279. break
  1280. return res
  1281. class InAdvancePagedList(PagedList):
  1282. def __init__(self, pagefunc, pagecount, pagesize):
  1283. self._pagefunc = pagefunc
  1284. self._pagecount = pagecount
  1285. self._pagesize = pagesize
  1286. def getslice(self, start=0, end=None):
  1287. res = []
  1288. start_page = start // self._pagesize
  1289. end_page = (
  1290. self._pagecount if end is None else (end // self._pagesize + 1))
  1291. skip_elems = start - start_page * self._pagesize
  1292. only_more = None if end is None else end - start
  1293. for pagenum in range(start_page, end_page):
  1294. page = list(self._pagefunc(pagenum))
  1295. if skip_elems:
  1296. page = page[skip_elems:]
  1297. skip_elems = None
  1298. if only_more is not None:
  1299. if len(page) < only_more:
  1300. only_more -= len(page)
  1301. else:
  1302. page = page[:only_more]
  1303. res.extend(page)
  1304. break
  1305. res.extend(page)
  1306. return res
  1307. def uppercase_escape(s):
  1308. unicode_escape = codecs.getdecoder('unicode_escape')
  1309. return re.sub(
  1310. r'\\U[0-9a-fA-F]{8}',
  1311. lambda m: unicode_escape(m.group(0))[0],
  1312. s)
  1313. def lowercase_escape(s):
  1314. unicode_escape = codecs.getdecoder('unicode_escape')
  1315. return re.sub(
  1316. r'\\u[0-9a-fA-F]{4}',
  1317. lambda m: unicode_escape(m.group(0))[0],
  1318. s)
  1319. def escape_rfc3986(s):
  1320. """Escape non-ASCII characters as suggested by RFC 3986"""
  1321. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1322. s = s.encode('utf-8')
  1323. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1324. def escape_url(url):
  1325. """Escape URL as suggested by RFC 3986"""
  1326. url_parsed = compat_urllib_parse_urlparse(url)
  1327. return url_parsed._replace(
  1328. path=escape_rfc3986(url_parsed.path),
  1329. params=escape_rfc3986(url_parsed.params),
  1330. query=escape_rfc3986(url_parsed.query),
  1331. fragment=escape_rfc3986(url_parsed.fragment)
  1332. ).geturl()
  1333. try:
  1334. struct.pack('!I', 0)
  1335. except TypeError:
  1336. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1337. def struct_pack(spec, *args):
  1338. if isinstance(spec, compat_str):
  1339. spec = spec.encode('ascii')
  1340. return struct.pack(spec, *args)
  1341. def struct_unpack(spec, *args):
  1342. if isinstance(spec, compat_str):
  1343. spec = spec.encode('ascii')
  1344. return struct.unpack(spec, *args)
  1345. else:
  1346. struct_pack = struct.pack
  1347. struct_unpack = struct.unpack
  1348. def read_batch_urls(batch_fd):
  1349. def fixup(url):
  1350. if not isinstance(url, compat_str):
  1351. url = url.decode('utf-8', 'replace')
  1352. BOM_UTF8 = '\xef\xbb\xbf'
  1353. if url.startswith(BOM_UTF8):
  1354. url = url[len(BOM_UTF8):]
  1355. url = url.strip()
  1356. if url.startswith(('#', ';', ']')):
  1357. return False
  1358. return url
  1359. with contextlib.closing(batch_fd) as fd:
  1360. return [url for url in map(fixup, fd) if url]
  1361. def urlencode_postdata(*args, **kargs):
  1362. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1363. def encode_dict(d, encoding='utf-8'):
  1364. return dict((k.encode(encoding), v.encode(encoding)) for k, v in d.items())
  1365. US_RATINGS = {
  1366. 'G': 0,
  1367. 'PG': 10,
  1368. 'PG-13': 13,
  1369. 'R': 16,
  1370. 'NC': 18,
  1371. }
  1372. def parse_age_limit(s):
  1373. if s is None:
  1374. return None
  1375. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1376. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1377. def strip_jsonp(code):
  1378. return re.sub(
  1379. r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1380. def js_to_json(code):
  1381. def fix_kv(m):
  1382. v = m.group(0)
  1383. if v in ('true', 'false', 'null'):
  1384. return v
  1385. if v.startswith('"'):
  1386. v = re.sub(r"\\'", "'", v[1:-1])
  1387. elif v.startswith("'"):
  1388. v = v[1:-1]
  1389. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1390. '\\\\': '\\\\',
  1391. "\\'": "'",
  1392. '"': '\\"',
  1393. }[m.group(0)], v)
  1394. return '"%s"' % v
  1395. res = re.sub(r'''(?x)
  1396. "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"|
  1397. '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'|
  1398. [a-zA-Z_][.a-zA-Z_0-9]*
  1399. ''', fix_kv, code)
  1400. res = re.sub(r',(\s*[\]}])', lambda m: m.group(1), res)
  1401. return res
  1402. def qualities(quality_ids):
  1403. """ Get a numeric quality value out of a list of possible values """
  1404. def q(qid):
  1405. try:
  1406. return quality_ids.index(qid)
  1407. except ValueError:
  1408. return -1
  1409. return q
  1410. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1411. def limit_length(s, length):
  1412. """ Add ellipses to overly long strings """
  1413. if s is None:
  1414. return None
  1415. ELLIPSES = '...'
  1416. if len(s) > length:
  1417. return s[:length - len(ELLIPSES)] + ELLIPSES
  1418. return s
  1419. def version_tuple(v):
  1420. return tuple(int(e) for e in re.split(r'[-.]', v))
  1421. def is_outdated_version(version, limit, assume_new=True):
  1422. if not version:
  1423. return not assume_new
  1424. try:
  1425. return version_tuple(version) < version_tuple(limit)
  1426. except ValueError:
  1427. return not assume_new
  1428. def ytdl_is_updateable():
  1429. """ Returns if youtube-dl can be updated with -U """
  1430. from zipimport import zipimporter
  1431. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1432. def args_to_str(args):
  1433. # Get a short string representation for a subprocess command
  1434. return ' '.join(shlex_quote(a) for a in args)
  1435. def mimetype2ext(mt):
  1436. _, _, res = mt.rpartition('/')
  1437. return {
  1438. 'x-ms-wmv': 'wmv',
  1439. 'x-mp4-fragmented': 'mp4',
  1440. 'ttml+xml': 'ttml',
  1441. }.get(res, res)
  1442. def urlhandle_detect_ext(url_handle):
  1443. try:
  1444. url_handle.headers
  1445. getheader = lambda h: url_handle.headers[h]
  1446. except AttributeError: # Python < 3
  1447. getheader = url_handle.info().getheader
  1448. cd = getheader('Content-Disposition')
  1449. if cd:
  1450. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1451. if m:
  1452. e = determine_ext(m.group('filename'), default_ext=None)
  1453. if e:
  1454. return e
  1455. return mimetype2ext(getheader('Content-Type'))
  1456. def encode_data_uri(data, mime_type):
  1457. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1458. def age_restricted(content_limit, age_limit):
  1459. """ Returns True iff the content should be blocked """
  1460. if age_limit is None: # No limit set
  1461. return False
  1462. if content_limit is None:
  1463. return False # Content available for everyone
  1464. return age_limit < content_limit
  1465. def is_html(first_bytes):
  1466. """ Detect whether a file contains HTML by examining its first bytes. """
  1467. BOMS = [
  1468. (b'\xef\xbb\xbf', 'utf-8'),
  1469. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1470. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1471. (b'\xff\xfe', 'utf-16-le'),
  1472. (b'\xfe\xff', 'utf-16-be'),
  1473. ]
  1474. for bom, enc in BOMS:
  1475. if first_bytes.startswith(bom):
  1476. s = first_bytes[len(bom):].decode(enc, 'replace')
  1477. break
  1478. else:
  1479. s = first_bytes.decode('utf-8', 'replace')
  1480. return re.match(r'^\s*<', s)
  1481. def determine_protocol(info_dict):
  1482. protocol = info_dict.get('protocol')
  1483. if protocol is not None:
  1484. return protocol
  1485. url = info_dict['url']
  1486. if url.startswith('rtmp'):
  1487. return 'rtmp'
  1488. elif url.startswith('mms'):
  1489. return 'mms'
  1490. elif url.startswith('rtsp'):
  1491. return 'rtsp'
  1492. ext = determine_ext(url)
  1493. if ext == 'm3u8':
  1494. return 'm3u8'
  1495. elif ext == 'f4m':
  1496. return 'f4m'
  1497. return compat_urllib_parse_urlparse(url).scheme
  1498. def render_table(header_row, data):
  1499. """ Render a list of rows, each as a list of values """
  1500. table = [header_row] + data
  1501. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1502. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1503. return '\n'.join(format_str % tuple(row) for row in table)
  1504. def _match_one(filter_part, dct):
  1505. COMPARISON_OPERATORS = {
  1506. '<': operator.lt,
  1507. '<=': operator.le,
  1508. '>': operator.gt,
  1509. '>=': operator.ge,
  1510. '=': operator.eq,
  1511. '!=': operator.ne,
  1512. }
  1513. operator_rex = re.compile(r'''(?x)\s*
  1514. (?P<key>[a-z_]+)
  1515. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1516. (?:
  1517. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1518. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1519. )
  1520. \s*$
  1521. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1522. m = operator_rex.search(filter_part)
  1523. if m:
  1524. op = COMPARISON_OPERATORS[m.group('op')]
  1525. if m.group('strval') is not None:
  1526. if m.group('op') not in ('=', '!='):
  1527. raise ValueError(
  1528. 'Operator %s does not support string values!' % m.group('op'))
  1529. comparison_value = m.group('strval')
  1530. else:
  1531. try:
  1532. comparison_value = int(m.group('intval'))
  1533. except ValueError:
  1534. comparison_value = parse_filesize(m.group('intval'))
  1535. if comparison_value is None:
  1536. comparison_value = parse_filesize(m.group('intval') + 'B')
  1537. if comparison_value is None:
  1538. raise ValueError(
  1539. 'Invalid integer value %r in filter part %r' % (
  1540. m.group('intval'), filter_part))
  1541. actual_value = dct.get(m.group('key'))
  1542. if actual_value is None:
  1543. return m.group('none_inclusive')
  1544. return op(actual_value, comparison_value)
  1545. UNARY_OPERATORS = {
  1546. '': lambda v: v is not None,
  1547. '!': lambda v: v is None,
  1548. }
  1549. operator_rex = re.compile(r'''(?x)\s*
  1550. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1551. \s*$
  1552. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1553. m = operator_rex.search(filter_part)
  1554. if m:
  1555. op = UNARY_OPERATORS[m.group('op')]
  1556. actual_value = dct.get(m.group('key'))
  1557. return op(actual_value)
  1558. raise ValueError('Invalid filter part %r' % filter_part)
  1559. def match_str(filter_str, dct):
  1560. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1561. return all(
  1562. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1563. def match_filter_func(filter_str):
  1564. def _match_func(info_dict):
  1565. if match_str(filter_str, info_dict):
  1566. return None
  1567. else:
  1568. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1569. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1570. return _match_func
  1571. def parse_dfxp_time_expr(time_expr):
  1572. if not time_expr:
  1573. return 0.0
  1574. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1575. if mobj:
  1576. return float(mobj.group('time_offset'))
  1577. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:\.\d+)?)$', time_expr)
  1578. if mobj:
  1579. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3))
  1580. def srt_subtitles_timecode(seconds):
  1581. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1582. def dfxp2srt(dfxp_data):
  1583. _x = functools.partial(xpath_with_ns, ns_map={
  1584. 'ttml': 'http://www.w3.org/ns/ttml',
  1585. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1586. })
  1587. def parse_node(node):
  1588. str_or_empty = functools.partial(str_or_none, default='')
  1589. out = str_or_empty(node.text)
  1590. for child in node:
  1591. if child.tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1592. out += '\n' + str_or_empty(child.tail)
  1593. elif child.tag in (_x('ttml:span'), _x('ttaf1:span'), 'span'):
  1594. out += str_or_empty(parse_node(child))
  1595. else:
  1596. out += str_or_empty(xml.etree.ElementTree.tostring(child))
  1597. return out
  1598. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  1599. out = []
  1600. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall('.//p')
  1601. if not paras:
  1602. raise ValueError('Invalid dfxp/TTML subtitle')
  1603. for para, index in zip(paras, itertools.count(1)):
  1604. begin_time = parse_dfxp_time_expr(para.attrib['begin'])
  1605. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1606. if not end_time:
  1607. end_time = begin_time + parse_dfxp_time_expr(para.attrib['dur'])
  1608. out.append('%d\n%s --> %s\n%s\n\n' % (
  1609. index,
  1610. srt_subtitles_timecode(begin_time),
  1611. srt_subtitles_timecode(end_time),
  1612. parse_node(para)))
  1613. return ''.join(out)
  1614. def cli_option(params, command_option, param):
  1615. param = params.get(param)
  1616. return [command_option, param] if param is not None else []
  1617. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  1618. param = params.get(param)
  1619. assert isinstance(param, bool)
  1620. if separator:
  1621. return [command_option + separator + (true_value if param else false_value)]
  1622. return [command_option, true_value if param else false_value]
  1623. def cli_valueless_option(params, command_option, param, expected_value=True):
  1624. param = params.get(param)
  1625. return [command_option] if param == expected_value else []
  1626. def cli_configuration_args(params, param, default=[]):
  1627. ex_args = params.get(param)
  1628. if ex_args is None:
  1629. return default
  1630. assert isinstance(ex_args, list)
  1631. return ex_args
  1632. class ISO639Utils(object):
  1633. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  1634. _lang_map = {
  1635. 'aa': 'aar',
  1636. 'ab': 'abk',
  1637. 'ae': 'ave',
  1638. 'af': 'afr',
  1639. 'ak': 'aka',
  1640. 'am': 'amh',
  1641. 'an': 'arg',
  1642. 'ar': 'ara',
  1643. 'as': 'asm',
  1644. 'av': 'ava',
  1645. 'ay': 'aym',
  1646. 'az': 'aze',
  1647. 'ba': 'bak',
  1648. 'be': 'bel',
  1649. 'bg': 'bul',
  1650. 'bh': 'bih',
  1651. 'bi': 'bis',
  1652. 'bm': 'bam',
  1653. 'bn': 'ben',
  1654. 'bo': 'bod',
  1655. 'br': 'bre',
  1656. 'bs': 'bos',
  1657. 'ca': 'cat',
  1658. 'ce': 'che',
  1659. 'ch': 'cha',
  1660. 'co': 'cos',
  1661. 'cr': 'cre',
  1662. 'cs': 'ces',
  1663. 'cu': 'chu',
  1664. 'cv': 'chv',
  1665. 'cy': 'cym',
  1666. 'da': 'dan',
  1667. 'de': 'deu',
  1668. 'dv': 'div',
  1669. 'dz': 'dzo',
  1670. 'ee': 'ewe',
  1671. 'el': 'ell',
  1672. 'en': 'eng',
  1673. 'eo': 'epo',
  1674. 'es': 'spa',
  1675. 'et': 'est',
  1676. 'eu': 'eus',
  1677. 'fa': 'fas',
  1678. 'ff': 'ful',
  1679. 'fi': 'fin',
  1680. 'fj': 'fij',
  1681. 'fo': 'fao',
  1682. 'fr': 'fra',
  1683. 'fy': 'fry',
  1684. 'ga': 'gle',
  1685. 'gd': 'gla',
  1686. 'gl': 'glg',
  1687. 'gn': 'grn',
  1688. 'gu': 'guj',
  1689. 'gv': 'glv',
  1690. 'ha': 'hau',
  1691. 'he': 'heb',
  1692. 'hi': 'hin',
  1693. 'ho': 'hmo',
  1694. 'hr': 'hrv',
  1695. 'ht': 'hat',
  1696. 'hu': 'hun',
  1697. 'hy': 'hye',
  1698. 'hz': 'her',
  1699. 'ia': 'ina',
  1700. 'id': 'ind',
  1701. 'ie': 'ile',
  1702. 'ig': 'ibo',
  1703. 'ii': 'iii',
  1704. 'ik': 'ipk',
  1705. 'io': 'ido',
  1706. 'is': 'isl',
  1707. 'it': 'ita',
  1708. 'iu': 'iku',
  1709. 'ja': 'jpn',
  1710. 'jv': 'jav',
  1711. 'ka': 'kat',
  1712. 'kg': 'kon',
  1713. 'ki': 'kik',
  1714. 'kj': 'kua',
  1715. 'kk': 'kaz',
  1716. 'kl': 'kal',
  1717. 'km': 'khm',
  1718. 'kn': 'kan',
  1719. 'ko': 'kor',
  1720. 'kr': 'kau',
  1721. 'ks': 'kas',
  1722. 'ku': 'kur',
  1723. 'kv': 'kom',
  1724. 'kw': 'cor',
  1725. 'ky': 'kir',
  1726. 'la': 'lat',
  1727. 'lb': 'ltz',
  1728. 'lg': 'lug',
  1729. 'li': 'lim',
  1730. 'ln': 'lin',
  1731. 'lo': 'lao',
  1732. 'lt': 'lit',
  1733. 'lu': 'lub',
  1734. 'lv': 'lav',
  1735. 'mg': 'mlg',
  1736. 'mh': 'mah',
  1737. 'mi': 'mri',
  1738. 'mk': 'mkd',
  1739. 'ml': 'mal',
  1740. 'mn': 'mon',
  1741. 'mr': 'mar',
  1742. 'ms': 'msa',
  1743. 'mt': 'mlt',
  1744. 'my': 'mya',
  1745. 'na': 'nau',
  1746. 'nb': 'nob',
  1747. 'nd': 'nde',
  1748. 'ne': 'nep',
  1749. 'ng': 'ndo',
  1750. 'nl': 'nld',
  1751. 'nn': 'nno',
  1752. 'no': 'nor',
  1753. 'nr': 'nbl',
  1754. 'nv': 'nav',
  1755. 'ny': 'nya',
  1756. 'oc': 'oci',
  1757. 'oj': 'oji',
  1758. 'om': 'orm',
  1759. 'or': 'ori',
  1760. 'os': 'oss',
  1761. 'pa': 'pan',
  1762. 'pi': 'pli',
  1763. 'pl': 'pol',
  1764. 'ps': 'pus',
  1765. 'pt': 'por',
  1766. 'qu': 'que',
  1767. 'rm': 'roh',
  1768. 'rn': 'run',
  1769. 'ro': 'ron',
  1770. 'ru': 'rus',
  1771. 'rw': 'kin',
  1772. 'sa': 'san',
  1773. 'sc': 'srd',
  1774. 'sd': 'snd',
  1775. 'se': 'sme',
  1776. 'sg': 'sag',
  1777. 'si': 'sin',
  1778. 'sk': 'slk',
  1779. 'sl': 'slv',
  1780. 'sm': 'smo',
  1781. 'sn': 'sna',
  1782. 'so': 'som',
  1783. 'sq': 'sqi',
  1784. 'sr': 'srp',
  1785. 'ss': 'ssw',
  1786. 'st': 'sot',
  1787. 'su': 'sun',
  1788. 'sv': 'swe',
  1789. 'sw': 'swa',
  1790. 'ta': 'tam',
  1791. 'te': 'tel',
  1792. 'tg': 'tgk',
  1793. 'th': 'tha',
  1794. 'ti': 'tir',
  1795. 'tk': 'tuk',
  1796. 'tl': 'tgl',
  1797. 'tn': 'tsn',
  1798. 'to': 'ton',
  1799. 'tr': 'tur',
  1800. 'ts': 'tso',
  1801. 'tt': 'tat',
  1802. 'tw': 'twi',
  1803. 'ty': 'tah',
  1804. 'ug': 'uig',
  1805. 'uk': 'ukr',
  1806. 'ur': 'urd',
  1807. 'uz': 'uzb',
  1808. 've': 'ven',
  1809. 'vi': 'vie',
  1810. 'vo': 'vol',
  1811. 'wa': 'wln',
  1812. 'wo': 'wol',
  1813. 'xh': 'xho',
  1814. 'yi': 'yid',
  1815. 'yo': 'yor',
  1816. 'za': 'zha',
  1817. 'zh': 'zho',
  1818. 'zu': 'zul',
  1819. }
  1820. @classmethod
  1821. def short2long(cls, code):
  1822. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  1823. return cls._lang_map.get(code[:2])
  1824. @classmethod
  1825. def long2short(cls, code):
  1826. """Convert language code from ISO 639-2/T to ISO 639-1"""
  1827. for short_name, long_name in cls._lang_map.items():
  1828. if long_name == code:
  1829. return short_name
  1830. class ISO3166Utils(object):
  1831. # From http://data.okfn.org/data/core/country-list
  1832. _country_map = {
  1833. 'AF': 'Afghanistan',
  1834. 'AX': 'Åland Islands',
  1835. 'AL': 'Albania',
  1836. 'DZ': 'Algeria',
  1837. 'AS': 'American Samoa',
  1838. 'AD': 'Andorra',
  1839. 'AO': 'Angola',
  1840. 'AI': 'Anguilla',
  1841. 'AQ': 'Antarctica',
  1842. 'AG': 'Antigua and Barbuda',
  1843. 'AR': 'Argentina',
  1844. 'AM': 'Armenia',
  1845. 'AW': 'Aruba',
  1846. 'AU': 'Australia',
  1847. 'AT': 'Austria',
  1848. 'AZ': 'Azerbaijan',
  1849. 'BS': 'Bahamas',
  1850. 'BH': 'Bahrain',
  1851. 'BD': 'Bangladesh',
  1852. 'BB': 'Barbados',
  1853. 'BY': 'Belarus',
  1854. 'BE': 'Belgium',
  1855. 'BZ': 'Belize',
  1856. 'BJ': 'Benin',
  1857. 'BM': 'Bermuda',
  1858. 'BT': 'Bhutan',
  1859. 'BO': 'Bolivia, Plurinational State of',
  1860. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  1861. 'BA': 'Bosnia and Herzegovina',
  1862. 'BW': 'Botswana',
  1863. 'BV': 'Bouvet Island',
  1864. 'BR': 'Brazil',
  1865. 'IO': 'British Indian Ocean Territory',
  1866. 'BN': 'Brunei Darussalam',
  1867. 'BG': 'Bulgaria',
  1868. 'BF': 'Burkina Faso',
  1869. 'BI': 'Burundi',
  1870. 'KH': 'Cambodia',
  1871. 'CM': 'Cameroon',
  1872. 'CA': 'Canada',
  1873. 'CV': 'Cape Verde',
  1874. 'KY': 'Cayman Islands',
  1875. 'CF': 'Central African Republic',
  1876. 'TD': 'Chad',
  1877. 'CL': 'Chile',
  1878. 'CN': 'China',
  1879. 'CX': 'Christmas Island',
  1880. 'CC': 'Cocos (Keeling) Islands',
  1881. 'CO': 'Colombia',
  1882. 'KM': 'Comoros',
  1883. 'CG': 'Congo',
  1884. 'CD': 'Congo, the Democratic Republic of the',
  1885. 'CK': 'Cook Islands',
  1886. 'CR': 'Costa Rica',
  1887. 'CI': 'Côte d\'Ivoire',
  1888. 'HR': 'Croatia',
  1889. 'CU': 'Cuba',
  1890. 'CW': 'Curaçao',
  1891. 'CY': 'Cyprus',
  1892. 'CZ': 'Czech Republic',
  1893. 'DK': 'Denmark',
  1894. 'DJ': 'Djibouti',
  1895. 'DM': 'Dominica',
  1896. 'DO': 'Dominican Republic',
  1897. 'EC': 'Ecuador',
  1898. 'EG': 'Egypt',
  1899. 'SV': 'El Salvador',
  1900. 'GQ': 'Equatorial Guinea',
  1901. 'ER': 'Eritrea',
  1902. 'EE': 'Estonia',
  1903. 'ET': 'Ethiopia',
  1904. 'FK': 'Falkland Islands (Malvinas)',
  1905. 'FO': 'Faroe Islands',
  1906. 'FJ': 'Fiji',
  1907. 'FI': 'Finland',
  1908. 'FR': 'France',
  1909. 'GF': 'French Guiana',
  1910. 'PF': 'French Polynesia',
  1911. 'TF': 'French Southern Territories',
  1912. 'GA': 'Gabon',
  1913. 'GM': 'Gambia',
  1914. 'GE': 'Georgia',
  1915. 'DE': 'Germany',
  1916. 'GH': 'Ghana',
  1917. 'GI': 'Gibraltar',
  1918. 'GR': 'Greece',
  1919. 'GL': 'Greenland',
  1920. 'GD': 'Grenada',
  1921. 'GP': 'Guadeloupe',
  1922. 'GU': 'Guam',
  1923. 'GT': 'Guatemala',
  1924. 'GG': 'Guernsey',
  1925. 'GN': 'Guinea',
  1926. 'GW': 'Guinea-Bissau',
  1927. 'GY': 'Guyana',
  1928. 'HT': 'Haiti',
  1929. 'HM': 'Heard Island and McDonald Islands',
  1930. 'VA': 'Holy See (Vatican City State)',
  1931. 'HN': 'Honduras',
  1932. 'HK': 'Hong Kong',
  1933. 'HU': 'Hungary',
  1934. 'IS': 'Iceland',
  1935. 'IN': 'India',
  1936. 'ID': 'Indonesia',
  1937. 'IR': 'Iran, Islamic Republic of',
  1938. 'IQ': 'Iraq',
  1939. 'IE': 'Ireland',
  1940. 'IM': 'Isle of Man',
  1941. 'IL': 'Israel',
  1942. 'IT': 'Italy',
  1943. 'JM': 'Jamaica',
  1944. 'JP': 'Japan',
  1945. 'JE': 'Jersey',
  1946. 'JO': 'Jordan',
  1947. 'KZ': 'Kazakhstan',
  1948. 'KE': 'Kenya',
  1949. 'KI': 'Kiribati',
  1950. 'KP': 'Korea, Democratic People\'s Republic of',
  1951. 'KR': 'Korea, Republic of',
  1952. 'KW': 'Kuwait',
  1953. 'KG': 'Kyrgyzstan',
  1954. 'LA': 'Lao People\'s Democratic Republic',
  1955. 'LV': 'Latvia',
  1956. 'LB': 'Lebanon',
  1957. 'LS': 'Lesotho',
  1958. 'LR': 'Liberia',
  1959. 'LY': 'Libya',
  1960. 'LI': 'Liechtenstein',
  1961. 'LT': 'Lithuania',
  1962. 'LU': 'Luxembourg',
  1963. 'MO': 'Macao',
  1964. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  1965. 'MG': 'Madagascar',
  1966. 'MW': 'Malawi',
  1967. 'MY': 'Malaysia',
  1968. 'MV': 'Maldives',
  1969. 'ML': 'Mali',
  1970. 'MT': 'Malta',
  1971. 'MH': 'Marshall Islands',
  1972. 'MQ': 'Martinique',
  1973. 'MR': 'Mauritania',
  1974. 'MU': 'Mauritius',
  1975. 'YT': 'Mayotte',
  1976. 'MX': 'Mexico',
  1977. 'FM': 'Micronesia, Federated States of',
  1978. 'MD': 'Moldova, Republic of',
  1979. 'MC': 'Monaco',
  1980. 'MN': 'Mongolia',
  1981. 'ME': 'Montenegro',
  1982. 'MS': 'Montserrat',
  1983. 'MA': 'Morocco',
  1984. 'MZ': 'Mozambique',
  1985. 'MM': 'Myanmar',
  1986. 'NA': 'Namibia',
  1987. 'NR': 'Nauru',
  1988. 'NP': 'Nepal',
  1989. 'NL': 'Netherlands',
  1990. 'NC': 'New Caledonia',
  1991. 'NZ': 'New Zealand',
  1992. 'NI': 'Nicaragua',
  1993. 'NE': 'Niger',
  1994. 'NG': 'Nigeria',
  1995. 'NU': 'Niue',
  1996. 'NF': 'Norfolk Island',
  1997. 'MP': 'Northern Mariana Islands',
  1998. 'NO': 'Norway',
  1999. 'OM': 'Oman',
  2000. 'PK': 'Pakistan',
  2001. 'PW': 'Palau',
  2002. 'PS': 'Palestine, State of',
  2003. 'PA': 'Panama',
  2004. 'PG': 'Papua New Guinea',
  2005. 'PY': 'Paraguay',
  2006. 'PE': 'Peru',
  2007. 'PH': 'Philippines',
  2008. 'PN': 'Pitcairn',
  2009. 'PL': 'Poland',
  2010. 'PT': 'Portugal',
  2011. 'PR': 'Puerto Rico',
  2012. 'QA': 'Qatar',
  2013. 'RE': 'Réunion',
  2014. 'RO': 'Romania',
  2015. 'RU': 'Russian Federation',
  2016. 'RW': 'Rwanda',
  2017. 'BL': 'Saint Barthélemy',
  2018. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2019. 'KN': 'Saint Kitts and Nevis',
  2020. 'LC': 'Saint Lucia',
  2021. 'MF': 'Saint Martin (French part)',
  2022. 'PM': 'Saint Pierre and Miquelon',
  2023. 'VC': 'Saint Vincent and the Grenadines',
  2024. 'WS': 'Samoa',
  2025. 'SM': 'San Marino',
  2026. 'ST': 'Sao Tome and Principe',
  2027. 'SA': 'Saudi Arabia',
  2028. 'SN': 'Senegal',
  2029. 'RS': 'Serbia',
  2030. 'SC': 'Seychelles',
  2031. 'SL': 'Sierra Leone',
  2032. 'SG': 'Singapore',
  2033. 'SX': 'Sint Maarten (Dutch part)',
  2034. 'SK': 'Slovakia',
  2035. 'SI': 'Slovenia',
  2036. 'SB': 'Solomon Islands',
  2037. 'SO': 'Somalia',
  2038. 'ZA': 'South Africa',
  2039. 'GS': 'South Georgia and the South Sandwich Islands',
  2040. 'SS': 'South Sudan',
  2041. 'ES': 'Spain',
  2042. 'LK': 'Sri Lanka',
  2043. 'SD': 'Sudan',
  2044. 'SR': 'Suriname',
  2045. 'SJ': 'Svalbard and Jan Mayen',
  2046. 'SZ': 'Swaziland',
  2047. 'SE': 'Sweden',
  2048. 'CH': 'Switzerland',
  2049. 'SY': 'Syrian Arab Republic',
  2050. 'TW': 'Taiwan, Province of China',
  2051. 'TJ': 'Tajikistan',
  2052. 'TZ': 'Tanzania, United Republic of',
  2053. 'TH': 'Thailand',
  2054. 'TL': 'Timor-Leste',
  2055. 'TG': 'Togo',
  2056. 'TK': 'Tokelau',
  2057. 'TO': 'Tonga',
  2058. 'TT': 'Trinidad and Tobago',
  2059. 'TN': 'Tunisia',
  2060. 'TR': 'Turkey',
  2061. 'TM': 'Turkmenistan',
  2062. 'TC': 'Turks and Caicos Islands',
  2063. 'TV': 'Tuvalu',
  2064. 'UG': 'Uganda',
  2065. 'UA': 'Ukraine',
  2066. 'AE': 'United Arab Emirates',
  2067. 'GB': 'United Kingdom',
  2068. 'US': 'United States',
  2069. 'UM': 'United States Minor Outlying Islands',
  2070. 'UY': 'Uruguay',
  2071. 'UZ': 'Uzbekistan',
  2072. 'VU': 'Vanuatu',
  2073. 'VE': 'Venezuela, Bolivarian Republic of',
  2074. 'VN': 'Viet Nam',
  2075. 'VG': 'Virgin Islands, British',
  2076. 'VI': 'Virgin Islands, U.S.',
  2077. 'WF': 'Wallis and Futuna',
  2078. 'EH': 'Western Sahara',
  2079. 'YE': 'Yemen',
  2080. 'ZM': 'Zambia',
  2081. 'ZW': 'Zimbabwe',
  2082. }
  2083. @classmethod
  2084. def short2full(cls, code):
  2085. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2086. return cls._country_map.get(code.upper())
  2087. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2088. def __init__(self, proxies=None):
  2089. # Set default handlers
  2090. for type in ('http', 'https'):
  2091. setattr(self, '%s_open' % type,
  2092. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2093. meth(r, proxy, type))
  2094. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2095. def proxy_open(self, req, proxy, type):
  2096. req_proxy = req.headers.get('Ytdl-request-proxy')
  2097. if req_proxy is not None:
  2098. proxy = req_proxy
  2099. del req.headers['Ytdl-request-proxy']
  2100. if proxy == '__noproxy__':
  2101. return None # No Proxy
  2102. return compat_urllib_request.ProxyHandler.proxy_open(
  2103. self, req, proxy, type)