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.

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