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.

2503 lines
75 KiB

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