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.

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