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.

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