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.

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