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.

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