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.

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