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.

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