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.

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