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.

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