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.

1896 lines
57 KiB

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
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 calendar
  5. import codecs
  6. import contextlib
  7. import ctypes
  8. import datetime
  9. import email.utils
  10. import errno
  11. import functools
  12. import gzip
  13. import itertools
  14. import io
  15. import json
  16. import locale
  17. import math
  18. import operator
  19. import os
  20. import pipes
  21. import platform
  22. import re
  23. import ssl
  24. import socket
  25. import struct
  26. import subprocess
  27. import sys
  28. import tempfile
  29. import traceback
  30. import xml.etree.ElementTree
  31. import zlib
  32. from .compat import (
  33. compat_basestring,
  34. compat_chr,
  35. compat_html_entities,
  36. compat_http_client,
  37. compat_kwargs,
  38. compat_parse_qs,
  39. compat_socket_create_connection,
  40. compat_str,
  41. compat_urllib_error,
  42. compat_urllib_parse,
  43. compat_urllib_parse_urlparse,
  44. compat_urllib_request,
  45. compat_urlparse,
  46. shlex_quote,
  47. )
  48. # This is not clearly defined otherwise
  49. compiled_regex_type = type(re.compile(''))
  50. std_headers = {
  51. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/20.0 (Chrome)',
  52. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  53. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  54. 'Accept-Encoding': 'gzip, deflate',
  55. 'Accept-Language': 'en-us,en;q=0.5',
  56. }
  57. ENGLISH_MONTH_NAMES = [
  58. 'January', 'February', 'March', 'April', 'May', 'June',
  59. 'July', 'August', 'September', 'October', 'November', 'December']
  60. def preferredencoding():
  61. """Get preferred encoding.
  62. Returns the best encoding scheme for the system, based on
  63. locale.getpreferredencoding() and some further tweaks.
  64. """
  65. try:
  66. pref = locale.getpreferredencoding()
  67. 'TEST'.encode(pref)
  68. except Exception:
  69. pref = 'UTF-8'
  70. return pref
  71. def write_json_file(obj, fn):
  72. """ Encode obj as JSON and write it to fn, atomically if possible """
  73. fn = encodeFilename(fn)
  74. if sys.version_info < (3, 0) and sys.platform != 'win32':
  75. encoding = get_filesystem_encoding()
  76. # os.path.basename returns a bytes object, but NamedTemporaryFile
  77. # will fail if the filename contains non ascii characters unless we
  78. # use a unicode object
  79. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  80. # the same for os.path.dirname
  81. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  82. else:
  83. path_basename = os.path.basename
  84. path_dirname = os.path.dirname
  85. args = {
  86. 'suffix': '.tmp',
  87. 'prefix': path_basename(fn) + '.',
  88. 'dir': path_dirname(fn),
  89. 'delete': False,
  90. }
  91. # In Python 2.x, json.dump expects a bytestream.
  92. # In Python 3.x, it writes to a character stream
  93. if sys.version_info < (3, 0):
  94. args['mode'] = 'wb'
  95. else:
  96. args.update({
  97. 'mode': 'w',
  98. 'encoding': 'utf-8',
  99. })
  100. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  101. try:
  102. with tf:
  103. json.dump(obj, tf)
  104. if sys.platform == 'win32':
  105. # Need to remove existing file on Windows, else os.rename raises
  106. # WindowsError or FileExistsError.
  107. try:
  108. os.unlink(fn)
  109. except OSError:
  110. pass
  111. os.rename(tf.name, fn)
  112. except Exception:
  113. try:
  114. os.remove(tf.name)
  115. except OSError:
  116. pass
  117. raise
  118. if sys.version_info >= (2, 7):
  119. def find_xpath_attr(node, xpath, key, val):
  120. """ Find the xpath xpath[@key=val] """
  121. assert re.match(r'^[a-zA-Z-]+$', key)
  122. assert re.match(r'^[a-zA-Z0-9@\s:._-]*$', val)
  123. expr = xpath + "[@%s='%s']" % (key, val)
  124. return node.find(expr)
  125. else:
  126. def find_xpath_attr(node, xpath, key, val):
  127. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  128. # .//node does not match if a node is a direct child of . !
  129. if isinstance(xpath, compat_str):
  130. xpath = xpath.encode('ascii')
  131. for f in node.findall(xpath):
  132. if f.attrib.get(key) == val:
  133. return f
  134. return None
  135. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  136. # the namespace parameter
  137. def xpath_with_ns(path, ns_map):
  138. components = [c.split(':') for c in path.split('/')]
  139. replaced = []
  140. for c in components:
  141. if len(c) == 1:
  142. replaced.append(c[0])
  143. else:
  144. ns, tag = c
  145. replaced.append('{%s}%s' % (ns_map[ns], tag))
  146. return '/'.join(replaced)
  147. def xpath_text(node, xpath, name=None, fatal=False):
  148. if sys.version_info < (2, 7): # Crazy 2.6
  149. xpath = xpath.encode('ascii')
  150. n = node.find(xpath)
  151. if n is None or n.text is None:
  152. if fatal:
  153. name = xpath if name is None else name
  154. raise ExtractorError('Could not find XML element %s' % name)
  155. else:
  156. return None
  157. return n.text
  158. def get_element_by_id(id, html):
  159. """Return the content of the tag with the specified ID in the passed HTML document"""
  160. return get_element_by_attribute("id", id, html)
  161. def get_element_by_attribute(attribute, value, html):
  162. """Return the content of the tag with the specified attribute in the passed HTML document"""
  163. m = re.search(r'''(?xs)
  164. <([a-zA-Z0-9:._-]+)
  165. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  166. \s+%s=['"]?%s['"]?
  167. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  168. \s*>
  169. (?P<content>.*?)
  170. </\1>
  171. ''' % (re.escape(attribute), re.escape(value)), html)
  172. if not m:
  173. return None
  174. res = m.group('content')
  175. if res.startswith('"') or res.startswith("'"):
  176. res = res[1:-1]
  177. return unescapeHTML(res)
  178. def clean_html(html):
  179. """Clean an HTML snippet into a readable string"""
  180. if html is None: # Convenience for sanitizing descriptions etc.
  181. return html
  182. # Newline vs <br />
  183. html = html.replace('\n', ' ')
  184. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  185. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  186. # Strip html tags
  187. html = re.sub('<.*?>', '', html)
  188. # Replace html entities
  189. html = unescapeHTML(html)
  190. return html.strip()
  191. def sanitize_open(filename, open_mode):
  192. """Try to open the given filename, and slightly tweak it if this fails.
  193. Attempts to open the given filename. If this fails, it tries to change
  194. the filename slightly, step by step, until it's either able to open it
  195. or it fails and raises a final exception, like the standard open()
  196. function.
  197. It returns the tuple (stream, definitive_file_name).
  198. """
  199. try:
  200. if filename == '-':
  201. if sys.platform == 'win32':
  202. import msvcrt
  203. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  204. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  205. stream = open(encodeFilename(filename), open_mode)
  206. return (stream, filename)
  207. except (IOError, OSError) as err:
  208. if err.errno in (errno.EACCES,):
  209. raise
  210. # In case of error, try to remove win32 forbidden chars
  211. alt_filename = sanitize_path(filename)
  212. if alt_filename == filename:
  213. raise
  214. else:
  215. # An exception here should be caught in the caller
  216. stream = open(encodeFilename(alt_filename), open_mode)
  217. return (stream, alt_filename)
  218. def timeconvert(timestr):
  219. """Convert RFC 2822 defined time string into system timestamp"""
  220. timestamp = None
  221. timetuple = email.utils.parsedate_tz(timestr)
  222. if timetuple is not None:
  223. timestamp = email.utils.mktime_tz(timetuple)
  224. return timestamp
  225. def sanitize_filename(s, restricted=False, is_id=False):
  226. """Sanitizes a string so it could be used as part of a filename.
  227. If restricted is set, use a stricter subset of allowed characters.
  228. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  229. """
  230. def replace_insane(char):
  231. if char == '?' or ord(char) < 32 or ord(char) == 127:
  232. return ''
  233. elif char == '"':
  234. return '' if restricted else '\''
  235. elif char == ':':
  236. return '_-' if restricted else ' -'
  237. elif char in '\\/|*<>':
  238. return '_'
  239. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  240. return '_'
  241. if restricted and ord(char) > 127:
  242. return '_'
  243. return char
  244. # Handle timestamps
  245. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  246. result = ''.join(map(replace_insane, s))
  247. if not is_id:
  248. while '__' in result:
  249. result = result.replace('__', '_')
  250. result = result.strip('_')
  251. # Common case of "Foreign band name - English song title"
  252. if restricted and result.startswith('-_'):
  253. result = result[2:]
  254. if result.startswith('-'):
  255. result = '_' + result[len('-'):]
  256. result = result.lstrip('.')
  257. if not result:
  258. result = '_'
  259. return result
  260. def sanitize_path(s):
  261. """Sanitizes and normalizes path on Windows"""
  262. if sys.platform != 'win32':
  263. return s
  264. drive_or_unc, _ = os.path.splitdrive(s)
  265. if sys.version_info < (2, 7) and not drive_or_unc:
  266. drive_or_unc, _ = os.path.splitunc(s)
  267. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  268. if drive_or_unc:
  269. norm_path.pop(0)
  270. sanitized_path = [
  271. path_part if path_part in ['.', '..'] else re.sub('(?:[/<>:"\\|\\\\?\\*]|\.$)', '#', path_part)
  272. for path_part in norm_path]
  273. if drive_or_unc:
  274. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  275. return os.path.join(*sanitized_path)
  276. def orderedSet(iterable):
  277. """ Remove all duplicates from the input iterable """
  278. res = []
  279. for el in iterable:
  280. if el not in res:
  281. res.append(el)
  282. return res
  283. def _htmlentity_transform(entity):
  284. """Transforms an HTML entity to a character."""
  285. # Known non-numeric HTML entity
  286. if entity in compat_html_entities.name2codepoint:
  287. return compat_chr(compat_html_entities.name2codepoint[entity])
  288. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  289. if mobj is not None:
  290. numstr = mobj.group(1)
  291. if numstr.startswith('x'):
  292. base = 16
  293. numstr = '0%s' % numstr
  294. else:
  295. base = 10
  296. return compat_chr(int(numstr, base))
  297. # Unknown entity in name, return its literal representation
  298. return ('&%s;' % entity)
  299. def unescapeHTML(s):
  300. if s is None:
  301. return None
  302. assert type(s) == compat_str
  303. return re.sub(
  304. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  305. def get_subprocess_encoding():
  306. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  307. # For subprocess calls, encode with locale encoding
  308. # Refer to http://stackoverflow.com/a/9951851/35070
  309. encoding = preferredencoding()
  310. else:
  311. encoding = sys.getfilesystemencoding()
  312. if encoding is None:
  313. encoding = 'utf-8'
  314. return encoding
  315. def encodeFilename(s, for_subprocess=False):
  316. """
  317. @param s The name of the file
  318. """
  319. assert type(s) == compat_str
  320. # Python 3 has a Unicode API
  321. if sys.version_info >= (3, 0):
  322. return s
  323. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  324. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  325. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  326. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  327. return s
  328. return s.encode(get_subprocess_encoding(), 'ignore')
  329. def decodeFilename(b, for_subprocess=False):
  330. if sys.version_info >= (3, 0):
  331. return b
  332. if not isinstance(b, bytes):
  333. return b
  334. return b.decode(get_subprocess_encoding(), 'ignore')
  335. def encodeArgument(s):
  336. if not isinstance(s, compat_str):
  337. # Legacy code that uses byte strings
  338. # Uncomment the following line after fixing all post processors
  339. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  340. s = s.decode('ascii')
  341. return encodeFilename(s, True)
  342. def decodeArgument(b):
  343. return decodeFilename(b, True)
  344. def decodeOption(optval):
  345. if optval is None:
  346. return optval
  347. if isinstance(optval, bytes):
  348. optval = optval.decode(preferredencoding())
  349. assert isinstance(optval, compat_str)
  350. return optval
  351. def formatSeconds(secs):
  352. if secs > 3600:
  353. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  354. elif secs > 60:
  355. return '%d:%02d' % (secs // 60, secs % 60)
  356. else:
  357. return '%d' % secs
  358. def make_HTTPS_handler(params, **kwargs):
  359. opts_no_check_certificate = params.get('nocheckcertificate', False)
  360. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  361. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  362. if opts_no_check_certificate:
  363. context.check_hostname = False
  364. context.verify_mode = ssl.CERT_NONE
  365. try:
  366. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  367. except TypeError:
  368. # Python 2.7.8
  369. # (create_default_context present but HTTPSHandler has no context=)
  370. pass
  371. if sys.version_info < (3, 2):
  372. return YoutubeDLHTTPSHandler(params, **kwargs)
  373. else: # Python < 3.4
  374. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  375. context.verify_mode = (ssl.CERT_NONE
  376. if opts_no_check_certificate
  377. else ssl.CERT_REQUIRED)
  378. context.set_default_verify_paths()
  379. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  380. def bug_reports_message():
  381. if ytdl_is_updateable():
  382. update_cmd = 'type youtube-dl -U to update'
  383. else:
  384. update_cmd = 'see https://yt-dl.org/update on how to update'
  385. msg = '; please report this issue on https://yt-dl.org/bug .'
  386. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  387. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  388. return msg
  389. class ExtractorError(Exception):
  390. """Error during info extraction."""
  391. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  392. """ tb, if given, is the original traceback (so that it can be printed out).
  393. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  394. """
  395. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  396. expected = True
  397. if video_id is not None:
  398. msg = video_id + ': ' + msg
  399. if cause:
  400. msg += ' (caused by %r)' % cause
  401. if not expected:
  402. msg += bug_reports_message()
  403. super(ExtractorError, self).__init__(msg)
  404. self.traceback = tb
  405. self.exc_info = sys.exc_info() # preserve original exception
  406. self.cause = cause
  407. self.video_id = video_id
  408. def format_traceback(self):
  409. if self.traceback is None:
  410. return None
  411. return ''.join(traceback.format_tb(self.traceback))
  412. class UnsupportedError(ExtractorError):
  413. def __init__(self, url):
  414. super(UnsupportedError, self).__init__(
  415. 'Unsupported URL: %s' % url, expected=True)
  416. self.url = url
  417. class RegexNotFoundError(ExtractorError):
  418. """Error when a regex didn't match"""
  419. pass
  420. class DownloadError(Exception):
  421. """Download Error exception.
  422. This exception may be thrown by FileDownloader objects if they are not
  423. configured to continue on errors. They will contain the appropriate
  424. error message.
  425. """
  426. def __init__(self, msg, exc_info=None):
  427. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  428. super(DownloadError, self).__init__(msg)
  429. self.exc_info = exc_info
  430. class SameFileError(Exception):
  431. """Same File exception.
  432. This exception will be thrown by FileDownloader objects if they detect
  433. multiple files would have to be downloaded to the same file on disk.
  434. """
  435. pass
  436. class PostProcessingError(Exception):
  437. """Post Processing exception.
  438. This exception may be raised by PostProcessor's .run() method to
  439. indicate an error in the postprocessing task.
  440. """
  441. def __init__(self, msg):
  442. self.msg = msg
  443. class MaxDownloadsReached(Exception):
  444. """ --max-downloads limit has been reached. """
  445. pass
  446. class UnavailableVideoError(Exception):
  447. """Unavailable Format exception.
  448. This exception will be thrown when a video is requested
  449. in a format that is not available for that video.
  450. """
  451. pass
  452. class ContentTooShortError(Exception):
  453. """Content Too Short exception.
  454. This exception may be raised by FileDownloader objects when a file they
  455. download is too small for what the server announced first, indicating
  456. the connection was probably interrupted.
  457. """
  458. # Both in bytes
  459. downloaded = None
  460. expected = None
  461. def __init__(self, downloaded, expected):
  462. self.downloaded = downloaded
  463. self.expected = expected
  464. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  465. hc = http_class(*args, **kwargs)
  466. source_address = ydl_handler._params.get('source_address')
  467. if source_address is not None:
  468. sa = (source_address, 0)
  469. if hasattr(hc, 'source_address'): # Python 2.7+
  470. hc.source_address = sa
  471. else: # Python 2.6
  472. def _hc_connect(self, *args, **kwargs):
  473. sock = compat_socket_create_connection(
  474. (self.host, self.port), self.timeout, sa)
  475. if is_https:
  476. self.sock = ssl.wrap_socket(
  477. sock, self.key_file, self.cert_file,
  478. ssl_version=ssl.PROTOCOL_TLSv1)
  479. else:
  480. self.sock = sock
  481. hc.connect = functools.partial(_hc_connect, hc)
  482. return hc
  483. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  484. """Handler for HTTP requests and responses.
  485. This class, when installed with an OpenerDirector, automatically adds
  486. the standard headers to every HTTP request and handles gzipped and
  487. deflated responses from web servers. If compression is to be avoided in
  488. a particular request, the original request in the program code only has
  489. to include the HTTP header "Youtubedl-No-Compression", which will be
  490. removed before making the real request.
  491. Part of this code was copied from:
  492. http://techknack.net/python-urllib2-handlers/
  493. Andrew Rowls, the author of that code, agreed to release it to the
  494. public domain.
  495. """
  496. def __init__(self, params, *args, **kwargs):
  497. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  498. self._params = params
  499. def http_open(self, req):
  500. return self.do_open(functools.partial(
  501. _create_http_connection, self, compat_http_client.HTTPConnection, False),
  502. req)
  503. @staticmethod
  504. def deflate(data):
  505. try:
  506. return zlib.decompress(data, -zlib.MAX_WBITS)
  507. except zlib.error:
  508. return zlib.decompress(data)
  509. @staticmethod
  510. def addinfourl_wrapper(stream, headers, url, code):
  511. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  512. return compat_urllib_request.addinfourl(stream, headers, url, code)
  513. ret = compat_urllib_request.addinfourl(stream, headers, url)
  514. ret.code = code
  515. return ret
  516. def http_request(self, req):
  517. for h, v in std_headers.items():
  518. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  519. # The dict keys are capitalized because of this bug by urllib
  520. if h.capitalize() not in req.headers:
  521. req.add_header(h, v)
  522. if 'Youtubedl-no-compression' in req.headers:
  523. if 'Accept-encoding' in req.headers:
  524. del req.headers['Accept-encoding']
  525. del req.headers['Youtubedl-no-compression']
  526. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  527. # Python 2.6 is brain-dead when it comes to fragments
  528. req._Request__original = req._Request__original.partition('#')[0]
  529. req._Request__r_type = req._Request__r_type.partition('#')[0]
  530. return req
  531. def http_response(self, req, resp):
  532. old_resp = resp
  533. # gzip
  534. if resp.headers.get('Content-encoding', '') == 'gzip':
  535. content = resp.read()
  536. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  537. try:
  538. uncompressed = io.BytesIO(gz.read())
  539. except IOError as original_ioerror:
  540. # There may be junk add the end of the file
  541. # See http://stackoverflow.com/q/4928560/35070 for details
  542. for i in range(1, 1024):
  543. try:
  544. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  545. uncompressed = io.BytesIO(gz.read())
  546. except IOError:
  547. continue
  548. break
  549. else:
  550. raise original_ioerror
  551. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  552. resp.msg = old_resp.msg
  553. # deflate
  554. if resp.headers.get('Content-encoding', '') == 'deflate':
  555. gz = io.BytesIO(self.deflate(resp.read()))
  556. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  557. resp.msg = old_resp.msg
  558. return resp
  559. https_request = http_request
  560. https_response = http_response
  561. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  562. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  563. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  564. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  565. self._params = params
  566. def https_open(self, req):
  567. kwargs = {}
  568. if hasattr(self, '_context'): # python > 2.6
  569. kwargs['context'] = self._context
  570. if hasattr(self, '_check_hostname'): # python 3.x
  571. kwargs['check_hostname'] = self._check_hostname
  572. return self.do_open(functools.partial(
  573. _create_http_connection, self, self._https_conn_class, True),
  574. req, **kwargs)
  575. def parse_iso8601(date_str, delimiter='T', timezone=None):
  576. """ Return a UNIX timestamp from the given date """
  577. if date_str is None:
  578. return None
  579. if timezone is None:
  580. m = re.search(
  581. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  582. date_str)
  583. if not m:
  584. timezone = datetime.timedelta()
  585. else:
  586. date_str = date_str[:-len(m.group(0))]
  587. if not m.group('sign'):
  588. timezone = datetime.timedelta()
  589. else:
  590. sign = 1 if m.group('sign') == '+' else -1
  591. timezone = datetime.timedelta(
  592. hours=sign * int(m.group('hours')),
  593. minutes=sign * int(m.group('minutes')))
  594. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  595. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  596. return calendar.timegm(dt.timetuple())
  597. def unified_strdate(date_str, day_first=True):
  598. """Return a string with the date in the format YYYYMMDD"""
  599. if date_str is None:
  600. return None
  601. upload_date = None
  602. # Replace commas
  603. date_str = date_str.replace(',', ' ')
  604. # %z (UTC offset) is only supported in python>=3.2
  605. if not re.match(r'^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$', date_str):
  606. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  607. # Remove AM/PM + timezone
  608. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  609. format_expressions = [
  610. '%d %B %Y',
  611. '%d %b %Y',
  612. '%B %d %Y',
  613. '%b %d %Y',
  614. '%b %dst %Y %I:%M%p',
  615. '%b %dnd %Y %I:%M%p',
  616. '%b %dth %Y %I:%M%p',
  617. '%Y %m %d',
  618. '%Y-%m-%d',
  619. '%Y/%m/%d',
  620. '%Y/%m/%d %H:%M:%S',
  621. '%Y-%m-%d %H:%M:%S',
  622. '%Y-%m-%d %H:%M:%S.%f',
  623. '%d.%m.%Y %H:%M',
  624. '%d.%m.%Y %H.%M',
  625. '%Y-%m-%dT%H:%M:%SZ',
  626. '%Y-%m-%dT%H:%M:%S.%fZ',
  627. '%Y-%m-%dT%H:%M:%S.%f0Z',
  628. '%Y-%m-%dT%H:%M:%S',
  629. '%Y-%m-%dT%H:%M:%S.%f',
  630. '%Y-%m-%dT%H:%M',
  631. ]
  632. if day_first:
  633. format_expressions.extend([
  634. '%d-%m-%Y',
  635. '%d.%m.%Y',
  636. '%d/%m/%Y',
  637. '%d/%m/%y',
  638. '%d/%m/%Y %H:%M:%S',
  639. ])
  640. else:
  641. format_expressions.extend([
  642. '%m-%d-%Y',
  643. '%m.%d.%Y',
  644. '%m/%d/%Y',
  645. '%m/%d/%y',
  646. '%m/%d/%Y %H:%M:%S',
  647. ])
  648. for expression in format_expressions:
  649. try:
  650. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  651. except ValueError:
  652. pass
  653. if upload_date is None:
  654. timetuple = email.utils.parsedate_tz(date_str)
  655. if timetuple:
  656. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  657. return upload_date
  658. def determine_ext(url, default_ext='unknown_video'):
  659. if url is None:
  660. return default_ext
  661. guess = url.partition('?')[0].rpartition('.')[2]
  662. if re.match(r'^[A-Za-z0-9]+$', guess):
  663. return guess
  664. else:
  665. return default_ext
  666. def subtitles_filename(filename, sub_lang, sub_format):
  667. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  668. def date_from_str(date_str):
  669. """
  670. Return a datetime object from a string in the format YYYYMMDD or
  671. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  672. today = datetime.date.today()
  673. if date_str in ('now', 'today'):
  674. return today
  675. if date_str == 'yesterday':
  676. return today - datetime.timedelta(days=1)
  677. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  678. if match is not None:
  679. sign = match.group('sign')
  680. time = int(match.group('time'))
  681. if sign == '-':
  682. time = -time
  683. unit = match.group('unit')
  684. # A bad aproximation?
  685. if unit == 'month':
  686. unit = 'day'
  687. time *= 30
  688. elif unit == 'year':
  689. unit = 'day'
  690. time *= 365
  691. unit += 's'
  692. delta = datetime.timedelta(**{unit: time})
  693. return today + delta
  694. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  695. def hyphenate_date(date_str):
  696. """
  697. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  698. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  699. if match is not None:
  700. return '-'.join(match.groups())
  701. else:
  702. return date_str
  703. class DateRange(object):
  704. """Represents a time interval between two dates"""
  705. def __init__(self, start=None, end=None):
  706. """start and end must be strings in the format accepted by date"""
  707. if start is not None:
  708. self.start = date_from_str(start)
  709. else:
  710. self.start = datetime.datetime.min.date()
  711. if end is not None:
  712. self.end = date_from_str(end)
  713. else:
  714. self.end = datetime.datetime.max.date()
  715. if self.start > self.end:
  716. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  717. @classmethod
  718. def day(cls, day):
  719. """Returns a range that only contains the given day"""
  720. return cls(day, day)
  721. def __contains__(self, date):
  722. """Check if the date is in the range"""
  723. if not isinstance(date, datetime.date):
  724. date = date_from_str(date)
  725. return self.start <= date <= self.end
  726. def __str__(self):
  727. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  728. def platform_name():
  729. """ Returns the platform name as a compat_str """
  730. res = platform.platform()
  731. if isinstance(res, bytes):
  732. res = res.decode(preferredencoding())
  733. assert isinstance(res, compat_str)
  734. return res
  735. def _windows_write_string(s, out):
  736. """ Returns True if the string was written using special methods,
  737. False if it has yet to be written out."""
  738. # Adapted from http://stackoverflow.com/a/3259271/35070
  739. import ctypes
  740. import ctypes.wintypes
  741. WIN_OUTPUT_IDS = {
  742. 1: -11,
  743. 2: -12,
  744. }
  745. try:
  746. fileno = out.fileno()
  747. except AttributeError:
  748. # If the output stream doesn't have a fileno, it's virtual
  749. return False
  750. except io.UnsupportedOperation:
  751. # Some strange Windows pseudo files?
  752. return False
  753. if fileno not in WIN_OUTPUT_IDS:
  754. return False
  755. GetStdHandle = ctypes.WINFUNCTYPE(
  756. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  757. (b"GetStdHandle", ctypes.windll.kernel32))
  758. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  759. WriteConsoleW = ctypes.WINFUNCTYPE(
  760. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  761. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  762. ctypes.wintypes.LPVOID)((b"WriteConsoleW", ctypes.windll.kernel32))
  763. written = ctypes.wintypes.DWORD(0)
  764. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b"GetFileType", ctypes.windll.kernel32))
  765. FILE_TYPE_CHAR = 0x0002
  766. FILE_TYPE_REMOTE = 0x8000
  767. GetConsoleMode = ctypes.WINFUNCTYPE(
  768. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  769. ctypes.POINTER(ctypes.wintypes.DWORD))(
  770. (b"GetConsoleMode", ctypes.windll.kernel32))
  771. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  772. def not_a_console(handle):
  773. if handle == INVALID_HANDLE_VALUE or handle is None:
  774. return True
  775. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  776. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  777. if not_a_console(h):
  778. return False
  779. def next_nonbmp_pos(s):
  780. try:
  781. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  782. except StopIteration:
  783. return len(s)
  784. while s:
  785. count = min(next_nonbmp_pos(s), 1024)
  786. ret = WriteConsoleW(
  787. h, s, count if count else 2, ctypes.byref(written), None)
  788. if ret == 0:
  789. raise OSError('Failed to write string')
  790. if not count: # We just wrote a non-BMP character
  791. assert written.value == 2
  792. s = s[1:]
  793. else:
  794. assert written.value > 0
  795. s = s[written.value:]
  796. return True
  797. def write_string(s, out=None, encoding=None):
  798. if out is None:
  799. out = sys.stderr
  800. assert type(s) == compat_str
  801. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  802. if _windows_write_string(s, out):
  803. return
  804. if ('b' in getattr(out, 'mode', '') or
  805. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  806. byt = s.encode(encoding or preferredencoding(), 'ignore')
  807. out.write(byt)
  808. elif hasattr(out, 'buffer'):
  809. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  810. byt = s.encode(enc, 'ignore')
  811. out.buffer.write(byt)
  812. else:
  813. out.write(s)
  814. out.flush()
  815. def bytes_to_intlist(bs):
  816. if not bs:
  817. return []
  818. if isinstance(bs[0], int): # Python 3
  819. return list(bs)
  820. else:
  821. return [ord(c) for c in bs]
  822. def intlist_to_bytes(xs):
  823. if not xs:
  824. return b''
  825. return struct_pack('%dB' % len(xs), *xs)
  826. # Cross-platform file locking
  827. if sys.platform == 'win32':
  828. import ctypes.wintypes
  829. import msvcrt
  830. class OVERLAPPED(ctypes.Structure):
  831. _fields_ = [
  832. ('Internal', ctypes.wintypes.LPVOID),
  833. ('InternalHigh', ctypes.wintypes.LPVOID),
  834. ('Offset', ctypes.wintypes.DWORD),
  835. ('OffsetHigh', ctypes.wintypes.DWORD),
  836. ('hEvent', ctypes.wintypes.HANDLE),
  837. ]
  838. kernel32 = ctypes.windll.kernel32
  839. LockFileEx = kernel32.LockFileEx
  840. LockFileEx.argtypes = [
  841. ctypes.wintypes.HANDLE, # hFile
  842. ctypes.wintypes.DWORD, # dwFlags
  843. ctypes.wintypes.DWORD, # dwReserved
  844. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  845. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  846. ctypes.POINTER(OVERLAPPED) # Overlapped
  847. ]
  848. LockFileEx.restype = ctypes.wintypes.BOOL
  849. UnlockFileEx = kernel32.UnlockFileEx
  850. UnlockFileEx.argtypes = [
  851. ctypes.wintypes.HANDLE, # hFile
  852. ctypes.wintypes.DWORD, # dwReserved
  853. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  854. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  855. ctypes.POINTER(OVERLAPPED) # Overlapped
  856. ]
  857. UnlockFileEx.restype = ctypes.wintypes.BOOL
  858. whole_low = 0xffffffff
  859. whole_high = 0x7fffffff
  860. def _lock_file(f, exclusive):
  861. overlapped = OVERLAPPED()
  862. overlapped.Offset = 0
  863. overlapped.OffsetHigh = 0
  864. overlapped.hEvent = 0
  865. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  866. handle = msvcrt.get_osfhandle(f.fileno())
  867. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  868. whole_low, whole_high, f._lock_file_overlapped_p):
  869. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  870. def _unlock_file(f):
  871. assert f._lock_file_overlapped_p
  872. handle = msvcrt.get_osfhandle(f.fileno())
  873. if not UnlockFileEx(handle, 0,
  874. whole_low, whole_high, f._lock_file_overlapped_p):
  875. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  876. else:
  877. import fcntl
  878. def _lock_file(f, exclusive):
  879. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  880. def _unlock_file(f):
  881. fcntl.flock(f, fcntl.LOCK_UN)
  882. class locked_file(object):
  883. def __init__(self, filename, mode, encoding=None):
  884. assert mode in ['r', 'a', 'w']
  885. self.f = io.open(filename, mode, encoding=encoding)
  886. self.mode = mode
  887. def __enter__(self):
  888. exclusive = self.mode != 'r'
  889. try:
  890. _lock_file(self.f, exclusive)
  891. except IOError:
  892. self.f.close()
  893. raise
  894. return self
  895. def __exit__(self, etype, value, traceback):
  896. try:
  897. _unlock_file(self.f)
  898. finally:
  899. self.f.close()
  900. def __iter__(self):
  901. return iter(self.f)
  902. def write(self, *args):
  903. return self.f.write(*args)
  904. def read(self, *args):
  905. return self.f.read(*args)
  906. def get_filesystem_encoding():
  907. encoding = sys.getfilesystemencoding()
  908. return encoding if encoding is not None else 'utf-8'
  909. def shell_quote(args):
  910. quoted_args = []
  911. encoding = get_filesystem_encoding()
  912. for a in args:
  913. if isinstance(a, bytes):
  914. # We may get a filename encoded with 'encodeFilename'
  915. a = a.decode(encoding)
  916. quoted_args.append(pipes.quote(a))
  917. return ' '.join(quoted_args)
  918. def smuggle_url(url, data):
  919. """ Pass additional data in a URL for internal use. """
  920. sdata = compat_urllib_parse.urlencode(
  921. {'__youtubedl_smuggle': json.dumps(data)})
  922. return url + '#' + sdata
  923. def unsmuggle_url(smug_url, default=None):
  924. if '#__youtubedl_smuggle' not in smug_url:
  925. return smug_url, default
  926. url, _, sdata = smug_url.rpartition('#')
  927. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  928. data = json.loads(jsond)
  929. return url, data
  930. def format_bytes(bytes):
  931. if bytes is None:
  932. return 'N/A'
  933. if type(bytes) is str:
  934. bytes = float(bytes)
  935. if bytes == 0.0:
  936. exponent = 0
  937. else:
  938. exponent = int(math.log(bytes, 1024.0))
  939. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  940. converted = float(bytes) / float(1024 ** exponent)
  941. return '%.2f%s' % (converted, suffix)
  942. def parse_filesize(s):
  943. if s is None:
  944. return None
  945. # The lower-case forms are of course incorrect and inofficial,
  946. # but we support those too
  947. _UNIT_TABLE = {
  948. 'B': 1,
  949. 'b': 1,
  950. 'KiB': 1024,
  951. 'KB': 1000,
  952. 'kB': 1024,
  953. 'Kb': 1000,
  954. 'MiB': 1024 ** 2,
  955. 'MB': 1000 ** 2,
  956. 'mB': 1024 ** 2,
  957. 'Mb': 1000 ** 2,
  958. 'GiB': 1024 ** 3,
  959. 'GB': 1000 ** 3,
  960. 'gB': 1024 ** 3,
  961. 'Gb': 1000 ** 3,
  962. 'TiB': 1024 ** 4,
  963. 'TB': 1000 ** 4,
  964. 'tB': 1024 ** 4,
  965. 'Tb': 1000 ** 4,
  966. 'PiB': 1024 ** 5,
  967. 'PB': 1000 ** 5,
  968. 'pB': 1024 ** 5,
  969. 'Pb': 1000 ** 5,
  970. 'EiB': 1024 ** 6,
  971. 'EB': 1000 ** 6,
  972. 'eB': 1024 ** 6,
  973. 'Eb': 1000 ** 6,
  974. 'ZiB': 1024 ** 7,
  975. 'ZB': 1000 ** 7,
  976. 'zB': 1024 ** 7,
  977. 'Zb': 1000 ** 7,
  978. 'YiB': 1024 ** 8,
  979. 'YB': 1000 ** 8,
  980. 'yB': 1024 ** 8,
  981. 'Yb': 1000 ** 8,
  982. }
  983. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  984. m = re.match(
  985. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  986. if not m:
  987. return None
  988. num_str = m.group('num').replace(',', '.')
  989. mult = _UNIT_TABLE[m.group('unit')]
  990. return int(float(num_str) * mult)
  991. def month_by_name(name):
  992. """ Return the number of a month by (locale-independently) English name """
  993. try:
  994. return ENGLISH_MONTH_NAMES.index(name) + 1
  995. except ValueError:
  996. return None
  997. def month_by_abbreviation(abbrev):
  998. """ Return the number of a month by (locale-independently) English
  999. abbreviations """
  1000. try:
  1001. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1002. except ValueError:
  1003. return None
  1004. def fix_xml_ampersands(xml_str):
  1005. """Replace all the '&' by '&amp;' in XML"""
  1006. return re.sub(
  1007. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1008. '&amp;',
  1009. xml_str)
  1010. def setproctitle(title):
  1011. assert isinstance(title, compat_str)
  1012. try:
  1013. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  1014. except OSError:
  1015. return
  1016. title_bytes = title.encode('utf-8')
  1017. buf = ctypes.create_string_buffer(len(title_bytes))
  1018. buf.value = title_bytes
  1019. try:
  1020. libc.prctl(15, buf, 0, 0, 0)
  1021. except AttributeError:
  1022. return # Strange libc, just skip this
  1023. def remove_start(s, start):
  1024. if s.startswith(start):
  1025. return s[len(start):]
  1026. return s
  1027. def remove_end(s, end):
  1028. if s.endswith(end):
  1029. return s[:-len(end)]
  1030. return s
  1031. def url_basename(url):
  1032. path = compat_urlparse.urlparse(url).path
  1033. return path.strip('/').split('/')[-1]
  1034. class HEADRequest(compat_urllib_request.Request):
  1035. def get_method(self):
  1036. return "HEAD"
  1037. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1038. if get_attr:
  1039. if v is not None:
  1040. v = getattr(v, get_attr, None)
  1041. if v == '':
  1042. v = None
  1043. return default if v is None else (int(v) * invscale // scale)
  1044. def str_or_none(v, default=None):
  1045. return default if v is None else compat_str(v)
  1046. def str_to_int(int_str):
  1047. """ A more relaxed version of int_or_none """
  1048. if int_str is None:
  1049. return None
  1050. int_str = re.sub(r'[,\.\+]', '', int_str)
  1051. return int(int_str)
  1052. def float_or_none(v, scale=1, invscale=1, default=None):
  1053. return default if v is None else (float(v) * invscale / scale)
  1054. def parse_duration(s):
  1055. if not isinstance(s, compat_basestring):
  1056. return None
  1057. s = s.strip()
  1058. m = re.match(
  1059. r'''(?ix)(?:P?T)?
  1060. (?:
  1061. (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*|
  1062. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1063. \s*(?P<hours_reversed>[0-9]+)\s*(?:[:h]|hours?)\s*(?P<mins_reversed>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*|
  1064. (?:
  1065. (?:
  1066. (?:(?P<days>[0-9]+)\s*(?:[:d]|days?)\s*)?
  1067. (?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*
  1068. )?
  1069. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1070. )?
  1071. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1072. )$''', s)
  1073. if not m:
  1074. return None
  1075. res = 0
  1076. if m.group('only_mins'):
  1077. return float_or_none(m.group('only_mins'), invscale=60)
  1078. if m.group('only_hours'):
  1079. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1080. if m.group('secs'):
  1081. res += int(m.group('secs'))
  1082. if m.group('mins_reversed'):
  1083. res += int(m.group('mins_reversed')) * 60
  1084. if m.group('mins'):
  1085. res += int(m.group('mins')) * 60
  1086. if m.group('hours'):
  1087. res += int(m.group('hours')) * 60 * 60
  1088. if m.group('hours_reversed'):
  1089. res += int(m.group('hours_reversed')) * 60 * 60
  1090. if m.group('days'):
  1091. res += int(m.group('days')) * 24 * 60 * 60
  1092. if m.group('ms'):
  1093. res += float(m.group('ms'))
  1094. return res
  1095. def prepend_extension(filename, ext, expected_real_ext=None):
  1096. name, real_ext = os.path.splitext(filename)
  1097. return (
  1098. '{0}.{1}{2}'.format(name, ext, real_ext)
  1099. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1100. else '{0}.{1}'.format(filename, ext))
  1101. def replace_extension(filename, ext, expected_real_ext=None):
  1102. name, real_ext = os.path.splitext(filename)
  1103. return '{0}.{1}'.format(
  1104. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1105. ext)
  1106. def check_executable(exe, args=[]):
  1107. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1108. args can be a list of arguments for a short output (like -version) """
  1109. try:
  1110. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1111. except OSError:
  1112. return False
  1113. return exe
  1114. def get_exe_version(exe, args=['--version'],
  1115. version_re=None, unrecognized='present'):
  1116. """ Returns the version of the specified executable,
  1117. or False if the executable is not present """
  1118. try:
  1119. out, _ = subprocess.Popen(
  1120. [encodeArgument(exe)] + args,
  1121. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1122. except OSError:
  1123. return False
  1124. if isinstance(out, bytes): # Python 2.x
  1125. out = out.decode('ascii', 'ignore')
  1126. return detect_exe_version(out, version_re, unrecognized)
  1127. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1128. assert isinstance(output, compat_str)
  1129. if version_re is None:
  1130. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1131. m = re.search(version_re, output)
  1132. if m:
  1133. return m.group(1)
  1134. else:
  1135. return unrecognized
  1136. class PagedList(object):
  1137. def __len__(self):
  1138. # This is only useful for tests
  1139. return len(self.getslice())
  1140. class OnDemandPagedList(PagedList):
  1141. def __init__(self, pagefunc, pagesize):
  1142. self._pagefunc = pagefunc
  1143. self._pagesize = pagesize
  1144. def getslice(self, start=0, end=None):
  1145. res = []
  1146. for pagenum in itertools.count(start // self._pagesize):
  1147. firstid = pagenum * self._pagesize
  1148. nextfirstid = pagenum * self._pagesize + self._pagesize
  1149. if start >= nextfirstid:
  1150. continue
  1151. page_results = list(self._pagefunc(pagenum))
  1152. startv = (
  1153. start % self._pagesize
  1154. if firstid <= start < nextfirstid
  1155. else 0)
  1156. endv = (
  1157. ((end - 1) % self._pagesize) + 1
  1158. if (end is not None and firstid <= end <= nextfirstid)
  1159. else None)
  1160. if startv != 0 or endv is not None:
  1161. page_results = page_results[startv:endv]
  1162. res.extend(page_results)
  1163. # A little optimization - if current page is not "full", ie. does
  1164. # not contain page_size videos then we can assume that this page
  1165. # is the last one - there are no more ids on further pages -
  1166. # i.e. no need to query again.
  1167. if len(page_results) + startv < self._pagesize:
  1168. break
  1169. # If we got the whole page, but the next page is not interesting,
  1170. # break out early as well
  1171. if end == nextfirstid:
  1172. break
  1173. return res
  1174. class InAdvancePagedList(PagedList):
  1175. def __init__(self, pagefunc, pagecount, pagesize):
  1176. self._pagefunc = pagefunc
  1177. self._pagecount = pagecount
  1178. self._pagesize = pagesize
  1179. def getslice(self, start=0, end=None):
  1180. res = []
  1181. start_page = start // self._pagesize
  1182. end_page = (
  1183. self._pagecount if end is None else (end // self._pagesize + 1))
  1184. skip_elems = start - start_page * self._pagesize
  1185. only_more = None if end is None else end - start
  1186. for pagenum in range(start_page, end_page):
  1187. page = list(self._pagefunc(pagenum))
  1188. if skip_elems:
  1189. page = page[skip_elems:]
  1190. skip_elems = None
  1191. if only_more is not None:
  1192. if len(page) < only_more:
  1193. only_more -= len(page)
  1194. else:
  1195. page = page[:only_more]
  1196. res.extend(page)
  1197. break
  1198. res.extend(page)
  1199. return res
  1200. def uppercase_escape(s):
  1201. unicode_escape = codecs.getdecoder('unicode_escape')
  1202. return re.sub(
  1203. r'\\U[0-9a-fA-F]{8}',
  1204. lambda m: unicode_escape(m.group(0))[0],
  1205. s)
  1206. def lowercase_escape(s):
  1207. unicode_escape = codecs.getdecoder('unicode_escape')
  1208. return re.sub(
  1209. r'\\u[0-9a-fA-F]{4}',
  1210. lambda m: unicode_escape(m.group(0))[0],
  1211. s)
  1212. def escape_rfc3986(s):
  1213. """Escape non-ASCII characters as suggested by RFC 3986"""
  1214. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1215. s = s.encode('utf-8')
  1216. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1217. def escape_url(url):
  1218. """Escape URL as suggested by RFC 3986"""
  1219. url_parsed = compat_urllib_parse_urlparse(url)
  1220. return url_parsed._replace(
  1221. path=escape_rfc3986(url_parsed.path),
  1222. params=escape_rfc3986(url_parsed.params),
  1223. query=escape_rfc3986(url_parsed.query),
  1224. fragment=escape_rfc3986(url_parsed.fragment)
  1225. ).geturl()
  1226. try:
  1227. struct.pack('!I', 0)
  1228. except TypeError:
  1229. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1230. def struct_pack(spec, *args):
  1231. if isinstance(spec, compat_str):
  1232. spec = spec.encode('ascii')
  1233. return struct.pack(spec, *args)
  1234. def struct_unpack(spec, *args):
  1235. if isinstance(spec, compat_str):
  1236. spec = spec.encode('ascii')
  1237. return struct.unpack(spec, *args)
  1238. else:
  1239. struct_pack = struct.pack
  1240. struct_unpack = struct.unpack
  1241. def read_batch_urls(batch_fd):
  1242. def fixup(url):
  1243. if not isinstance(url, compat_str):
  1244. url = url.decode('utf-8', 'replace')
  1245. BOM_UTF8 = '\xef\xbb\xbf'
  1246. if url.startswith(BOM_UTF8):
  1247. url = url[len(BOM_UTF8):]
  1248. url = url.strip()
  1249. if url.startswith(('#', ';', ']')):
  1250. return False
  1251. return url
  1252. with contextlib.closing(batch_fd) as fd:
  1253. return [url for url in map(fixup, fd) if url]
  1254. def urlencode_postdata(*args, **kargs):
  1255. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1256. try:
  1257. etree_iter = xml.etree.ElementTree.Element.iter
  1258. except AttributeError: # Python <=2.6
  1259. etree_iter = lambda n: n.findall('.//*')
  1260. def parse_xml(s):
  1261. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1262. def doctype(self, name, pubid, system):
  1263. pass # Ignore doctypes
  1264. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1265. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1266. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1267. # Fix up XML parser in Python 2.x
  1268. if sys.version_info < (3, 0):
  1269. for n in etree_iter(tree):
  1270. if n.text is not None:
  1271. if not isinstance(n.text, compat_str):
  1272. n.text = n.text.decode('utf-8')
  1273. return tree
  1274. US_RATINGS = {
  1275. 'G': 0,
  1276. 'PG': 10,
  1277. 'PG-13': 13,
  1278. 'R': 16,
  1279. 'NC': 18,
  1280. }
  1281. def parse_age_limit(s):
  1282. if s is None:
  1283. return None
  1284. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1285. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1286. def strip_jsonp(code):
  1287. return re.sub(
  1288. r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1289. def js_to_json(code):
  1290. def fix_kv(m):
  1291. v = m.group(0)
  1292. if v in ('true', 'false', 'null'):
  1293. return v
  1294. if v.startswith('"'):
  1295. return v
  1296. if v.startswith("'"):
  1297. v = v[1:-1]
  1298. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1299. '\\\\': '\\\\',
  1300. "\\'": "'",
  1301. '"': '\\"',
  1302. }[m.group(0)], v)
  1303. return '"%s"' % v
  1304. res = re.sub(r'''(?x)
  1305. "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"|
  1306. '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'|
  1307. [a-zA-Z_][.a-zA-Z_0-9]*
  1308. ''', fix_kv, code)
  1309. res = re.sub(r',(\s*[\]}])', lambda m: m.group(1), res)
  1310. return res
  1311. def qualities(quality_ids):
  1312. """ Get a numeric quality value out of a list of possible values """
  1313. def q(qid):
  1314. try:
  1315. return quality_ids.index(qid)
  1316. except ValueError:
  1317. return -1
  1318. return q
  1319. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1320. def limit_length(s, length):
  1321. """ Add ellipses to overly long strings """
  1322. if s is None:
  1323. return None
  1324. ELLIPSES = '...'
  1325. if len(s) > length:
  1326. return s[:length - len(ELLIPSES)] + ELLIPSES
  1327. return s
  1328. def version_tuple(v):
  1329. return tuple(int(e) for e in re.split(r'[-.]', v))
  1330. def is_outdated_version(version, limit, assume_new=True):
  1331. if not version:
  1332. return not assume_new
  1333. try:
  1334. return version_tuple(version) < version_tuple(limit)
  1335. except ValueError:
  1336. return not assume_new
  1337. def ytdl_is_updateable():
  1338. """ Returns if youtube-dl can be updated with -U """
  1339. from zipimport import zipimporter
  1340. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1341. def args_to_str(args):
  1342. # Get a short string representation for a subprocess command
  1343. return ' '.join(shlex_quote(a) for a in args)
  1344. def mimetype2ext(mt):
  1345. _, _, res = mt.rpartition('/')
  1346. return {
  1347. 'x-ms-wmv': 'wmv',
  1348. 'x-mp4-fragmented': 'mp4',
  1349. }.get(res, res)
  1350. def urlhandle_detect_ext(url_handle):
  1351. try:
  1352. url_handle.headers
  1353. getheader = lambda h: url_handle.headers[h]
  1354. except AttributeError: # Python < 3
  1355. getheader = url_handle.info().getheader
  1356. cd = getheader('Content-Disposition')
  1357. if cd:
  1358. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1359. if m:
  1360. e = determine_ext(m.group('filename'), default_ext=None)
  1361. if e:
  1362. return e
  1363. return mimetype2ext(getheader('Content-Type'))
  1364. def age_restricted(content_limit, age_limit):
  1365. """ Returns True iff the content should be blocked """
  1366. if age_limit is None: # No limit set
  1367. return False
  1368. if content_limit is None:
  1369. return False # Content available for everyone
  1370. return age_limit < content_limit
  1371. def is_html(first_bytes):
  1372. """ Detect whether a file contains HTML by examining its first bytes. """
  1373. BOMS = [
  1374. (b'\xef\xbb\xbf', 'utf-8'),
  1375. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1376. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1377. (b'\xff\xfe', 'utf-16-le'),
  1378. (b'\xfe\xff', 'utf-16-be'),
  1379. ]
  1380. for bom, enc in BOMS:
  1381. if first_bytes.startswith(bom):
  1382. s = first_bytes[len(bom):].decode(enc, 'replace')
  1383. break
  1384. else:
  1385. s = first_bytes.decode('utf-8', 'replace')
  1386. return re.match(r'^\s*<', s)
  1387. def determine_protocol(info_dict):
  1388. protocol = info_dict.get('protocol')
  1389. if protocol is not None:
  1390. return protocol
  1391. url = info_dict['url']
  1392. if url.startswith('rtmp'):
  1393. return 'rtmp'
  1394. elif url.startswith('mms'):
  1395. return 'mms'
  1396. elif url.startswith('rtsp'):
  1397. return 'rtsp'
  1398. ext = determine_ext(url)
  1399. if ext == 'm3u8':
  1400. return 'm3u8'
  1401. elif ext == 'f4m':
  1402. return 'f4m'
  1403. return compat_urllib_parse_urlparse(url).scheme
  1404. def render_table(header_row, data):
  1405. """ Render a list of rows, each as a list of values """
  1406. table = [header_row] + data
  1407. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1408. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1409. return '\n'.join(format_str % tuple(row) for row in table)
  1410. def _match_one(filter_part, dct):
  1411. COMPARISON_OPERATORS = {
  1412. '<': operator.lt,
  1413. '<=': operator.le,
  1414. '>': operator.gt,
  1415. '>=': operator.ge,
  1416. '=': operator.eq,
  1417. '!=': operator.ne,
  1418. }
  1419. operator_rex = re.compile(r'''(?x)\s*
  1420. (?P<key>[a-z_]+)
  1421. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1422. (?:
  1423. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1424. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1425. )
  1426. \s*$
  1427. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1428. m = operator_rex.search(filter_part)
  1429. if m:
  1430. op = COMPARISON_OPERATORS[m.group('op')]
  1431. if m.group('strval') is not None:
  1432. if m.group('op') not in ('=', '!='):
  1433. raise ValueError(
  1434. 'Operator %s does not support string values!' % m.group('op'))
  1435. comparison_value = m.group('strval')
  1436. else:
  1437. try:
  1438. comparison_value = int(m.group('intval'))
  1439. except ValueError:
  1440. comparison_value = parse_filesize(m.group('intval'))
  1441. if comparison_value is None:
  1442. comparison_value = parse_filesize(m.group('intval') + 'B')
  1443. if comparison_value is None:
  1444. raise ValueError(
  1445. 'Invalid integer value %r in filter part %r' % (
  1446. m.group('intval'), filter_part))
  1447. actual_value = dct.get(m.group('key'))
  1448. if actual_value is None:
  1449. return m.group('none_inclusive')
  1450. return op(actual_value, comparison_value)
  1451. UNARY_OPERATORS = {
  1452. '': lambda v: v is not None,
  1453. '!': lambda v: v is None,
  1454. }
  1455. operator_rex = re.compile(r'''(?x)\s*
  1456. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1457. \s*$
  1458. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1459. m = operator_rex.search(filter_part)
  1460. if m:
  1461. op = UNARY_OPERATORS[m.group('op')]
  1462. actual_value = dct.get(m.group('key'))
  1463. return op(actual_value)
  1464. raise ValueError('Invalid filter part %r' % filter_part)
  1465. def match_str(filter_str, dct):
  1466. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1467. return all(
  1468. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1469. def match_filter_func(filter_str):
  1470. def _match_func(info_dict):
  1471. if match_str(filter_str, info_dict):
  1472. return None
  1473. else:
  1474. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1475. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1476. return _match_func
  1477. def parse_dfxp_time_expr(time_expr):
  1478. if not time_expr:
  1479. return 0.0
  1480. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1481. if mobj:
  1482. return float(mobj.group('time_offset'))
  1483. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:\.\d+)?)$', time_expr)
  1484. if mobj:
  1485. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3))
  1486. def srt_subtitles_timecode(seconds):
  1487. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1488. def dfxp2srt(dfxp_data):
  1489. _x = functools.partial(xpath_with_ns, ns_map={'ttml': 'http://www.w3.org/ns/ttml'})
  1490. def parse_node(node):
  1491. str_or_empty = functools.partial(str_or_none, default='')
  1492. out = str_or_empty(node.text)
  1493. for child in node:
  1494. if child.tag == _x('ttml:br'):
  1495. out += '\n' + str_or_empty(child.tail)
  1496. elif child.tag == _x('ttml:span'):
  1497. out += str_or_empty(parse_node(child))
  1498. else:
  1499. out += str_or_empty(xml.etree.ElementTree.tostring(child))
  1500. return out
  1501. dfxp = xml.etree.ElementTree.fromstring(dfxp_data.encode('utf-8'))
  1502. out = []
  1503. paras = dfxp.findall(_x('.//ttml:p'))
  1504. for para, index in zip(paras, itertools.count(1)):
  1505. begin_time = parse_dfxp_time_expr(para.attrib['begin'])
  1506. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1507. if not end_time:
  1508. end_time = begin_time + parse_dfxp_time_expr(para.attrib['dur'])
  1509. out.append('%d\n%s --> %s\n%s\n\n' % (
  1510. index,
  1511. srt_subtitles_timecode(begin_time),
  1512. srt_subtitles_timecode(end_time),
  1513. parse_node(para)))
  1514. return ''.join(out)
  1515. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  1516. def __init__(self, proxies=None):
  1517. # Set default handlers
  1518. for type in ('http', 'https'):
  1519. setattr(self, '%s_open' % type,
  1520. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  1521. meth(r, proxy, type))
  1522. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  1523. def proxy_open(self, req, proxy, type):
  1524. req_proxy = req.headers.get('Ytdl-request-proxy')
  1525. if req_proxy is not None:
  1526. proxy = req_proxy
  1527. del req.headers['Ytdl-request-proxy']
  1528. if proxy == '__noproxy__':
  1529. return None # No Proxy
  1530. return compat_urllib_request.ProxyHandler.proxy_open(
  1531. self, req, proxy, type)