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.

1408 lines
43 KiB

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 gzip
  12. import itertools
  13. import io
  14. import json
  15. import locale
  16. import math
  17. import os
  18. import pipes
  19. import platform
  20. import re
  21. import ssl
  22. import socket
  23. import struct
  24. import subprocess
  25. import sys
  26. import tempfile
  27. import traceback
  28. import xml.etree.ElementTree
  29. import zlib
  30. from .compat import (
  31. compat_chr,
  32. compat_getenv,
  33. compat_html_entities,
  34. compat_parse_qs,
  35. compat_str,
  36. compat_urllib_error,
  37. compat_urllib_parse,
  38. compat_urllib_parse_urlparse,
  39. compat_urllib_request,
  40. compat_urlparse,
  41. )
  42. # This is not clearly defined otherwise
  43. compiled_regex_type = type(re.compile(''))
  44. std_headers = {
  45. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 (Chrome)',
  46. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  47. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  48. 'Accept-Encoding': 'gzip, deflate',
  49. 'Accept-Language': 'en-us,en;q=0.5',
  50. }
  51. def preferredencoding():
  52. """Get preferred encoding.
  53. Returns the best encoding scheme for the system, based on
  54. locale.getpreferredencoding() and some further tweaks.
  55. """
  56. try:
  57. pref = locale.getpreferredencoding()
  58. u'TEST'.encode(pref)
  59. except:
  60. pref = 'UTF-8'
  61. return pref
  62. def write_json_file(obj, fn):
  63. """ Encode obj as JSON and write it to fn, atomically """
  64. if sys.version_info < (3, 0):
  65. encoding = get_filesystem_encoding()
  66. # os.path.basename returns a bytes object, but NamedTemporaryFile
  67. # will fail if the filename contains non ascii characters unless we
  68. # use a unicode object
  69. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  70. # the same for os.path.dirname
  71. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  72. else:
  73. path_basename = os.path.basename
  74. path_dirname = os.path.dirname
  75. args = {
  76. 'suffix': '.tmp',
  77. 'prefix': path_basename(fn) + '.',
  78. 'dir': path_dirname(fn),
  79. 'delete': False,
  80. }
  81. # In Python 2.x, json.dump expects a bytestream.
  82. # In Python 3.x, it writes to a character stream
  83. if sys.version_info < (3, 0):
  84. args['mode'] = 'wb'
  85. else:
  86. args.update({
  87. 'mode': 'w',
  88. 'encoding': 'utf-8',
  89. })
  90. tf = tempfile.NamedTemporaryFile(**args)
  91. try:
  92. with tf:
  93. json.dump(obj, tf)
  94. os.rename(tf.name, fn)
  95. except:
  96. try:
  97. os.remove(tf.name)
  98. except OSError:
  99. pass
  100. raise
  101. if sys.version_info >= (2, 7):
  102. def find_xpath_attr(node, xpath, key, val):
  103. """ Find the xpath xpath[@key=val] """
  104. assert re.match(r'^[a-zA-Z-]+$', key)
  105. assert re.match(r'^[a-zA-Z0-9@\s:._-]*$', val)
  106. expr = xpath + u"[@%s='%s']" % (key, val)
  107. return node.find(expr)
  108. else:
  109. def find_xpath_attr(node, xpath, key, val):
  110. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  111. # .//node does not match if a node is a direct child of . !
  112. if isinstance(xpath, unicode):
  113. xpath = xpath.encode('ascii')
  114. for f in node.findall(xpath):
  115. if f.attrib.get(key) == val:
  116. return f
  117. return None
  118. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  119. # the namespace parameter
  120. def xpath_with_ns(path, ns_map):
  121. components = [c.split(':') for c in path.split('/')]
  122. replaced = []
  123. for c in components:
  124. if len(c) == 1:
  125. replaced.append(c[0])
  126. else:
  127. ns, tag = c
  128. replaced.append('{%s}%s' % (ns_map[ns], tag))
  129. return '/'.join(replaced)
  130. def xpath_text(node, xpath, name=None, fatal=False):
  131. if sys.version_info < (2, 7): # Crazy 2.6
  132. xpath = xpath.encode('ascii')
  133. n = node.find(xpath)
  134. if n is None:
  135. if fatal:
  136. name = xpath if name is None else name
  137. raise ExtractorError('Could not find XML element %s' % name)
  138. else:
  139. return None
  140. return n.text
  141. def get_element_by_id(id, html):
  142. """Return the content of the tag with the specified ID in the passed HTML document"""
  143. return get_element_by_attribute("id", id, html)
  144. def get_element_by_attribute(attribute, value, html):
  145. """Return the content of the tag with the specified attribute in the passed HTML document"""
  146. m = re.search(r'''(?xs)
  147. <([a-zA-Z0-9:._-]+)
  148. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  149. \s+%s=['"]?%s['"]?
  150. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  151. \s*>
  152. (?P<content>.*?)
  153. </\1>
  154. ''' % (re.escape(attribute), re.escape(value)), html)
  155. if not m:
  156. return None
  157. res = m.group('content')
  158. if res.startswith('"') or res.startswith("'"):
  159. res = res[1:-1]
  160. return unescapeHTML(res)
  161. def clean_html(html):
  162. """Clean an HTML snippet into a readable string"""
  163. # Newline vs <br />
  164. html = html.replace('\n', ' ')
  165. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  166. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  167. # Strip html tags
  168. html = re.sub('<.*?>', '', html)
  169. # Replace html entities
  170. html = unescapeHTML(html)
  171. return html.strip()
  172. def sanitize_open(filename, open_mode):
  173. """Try to open the given filename, and slightly tweak it if this fails.
  174. Attempts to open the given filename. If this fails, it tries to change
  175. the filename slightly, step by step, until it's either able to open it
  176. or it fails and raises a final exception, like the standard open()
  177. function.
  178. It returns the tuple (stream, definitive_file_name).
  179. """
  180. try:
  181. if filename == u'-':
  182. if sys.platform == 'win32':
  183. import msvcrt
  184. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  185. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  186. stream = open(encodeFilename(filename), open_mode)
  187. return (stream, filename)
  188. except (IOError, OSError) as err:
  189. if err.errno in (errno.EACCES,):
  190. raise
  191. # In case of error, try to remove win32 forbidden chars
  192. alt_filename = os.path.join(
  193. re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', path_part)
  194. for path_part in os.path.split(filename)
  195. )
  196. if alt_filename == filename:
  197. raise
  198. else:
  199. # An exception here should be caught in the caller
  200. stream = open(encodeFilename(filename), open_mode)
  201. return (stream, alt_filename)
  202. def timeconvert(timestr):
  203. """Convert RFC 2822 defined time string into system timestamp"""
  204. timestamp = None
  205. timetuple = email.utils.parsedate_tz(timestr)
  206. if timetuple is not None:
  207. timestamp = email.utils.mktime_tz(timetuple)
  208. return timestamp
  209. def sanitize_filename(s, restricted=False, is_id=False):
  210. """Sanitizes a string so it could be used as part of a filename.
  211. If restricted is set, use a stricter subset of allowed characters.
  212. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  213. """
  214. def replace_insane(char):
  215. if char == '?' or ord(char) < 32 or ord(char) == 127:
  216. return ''
  217. elif char == '"':
  218. return '' if restricted else '\''
  219. elif char == ':':
  220. return '_-' if restricted else ' -'
  221. elif char in '\\/|*<>':
  222. return '_'
  223. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  224. return '_'
  225. if restricted and ord(char) > 127:
  226. return '_'
  227. return char
  228. result = u''.join(map(replace_insane, s))
  229. if not is_id:
  230. while '__' in result:
  231. result = result.replace('__', '_')
  232. result = result.strip('_')
  233. # Common case of "Foreign band name - English song title"
  234. if restricted and result.startswith('-_'):
  235. result = result[2:]
  236. if not result:
  237. result = '_'
  238. return result
  239. def orderedSet(iterable):
  240. """ Remove all duplicates from the input iterable """
  241. res = []
  242. for el in iterable:
  243. if el not in res:
  244. res.append(el)
  245. return res
  246. def _htmlentity_transform(entity):
  247. """Transforms an HTML entity to a character."""
  248. # Known non-numeric HTML entity
  249. if entity in compat_html_entities.name2codepoint:
  250. return compat_chr(compat_html_entities.name2codepoint[entity])
  251. mobj = re.match(r'#(x?[0-9]+)', entity)
  252. if mobj is not None:
  253. numstr = mobj.group(1)
  254. if numstr.startswith(u'x'):
  255. base = 16
  256. numstr = u'0%s' % numstr
  257. else:
  258. base = 10
  259. return compat_chr(int(numstr, base))
  260. # Unknown entity in name, return its literal representation
  261. return (u'&%s;' % entity)
  262. def unescapeHTML(s):
  263. if s is None:
  264. return None
  265. assert type(s) == compat_str
  266. return re.sub(
  267. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  268. def encodeFilename(s, for_subprocess=False):
  269. """
  270. @param s The name of the file
  271. """
  272. assert type(s) == compat_str
  273. # Python 3 has a Unicode API
  274. if sys.version_info >= (3, 0):
  275. return s
  276. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  277. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  278. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  279. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  280. if not for_subprocess:
  281. return s
  282. else:
  283. # For subprocess calls, encode with locale encoding
  284. # Refer to http://stackoverflow.com/a/9951851/35070
  285. encoding = preferredencoding()
  286. else:
  287. encoding = sys.getfilesystemencoding()
  288. if encoding is None:
  289. encoding = 'utf-8'
  290. return s.encode(encoding, 'ignore')
  291. def encodeArgument(s):
  292. if not isinstance(s, compat_str):
  293. # Legacy code that uses byte strings
  294. # Uncomment the following line after fixing all post processors
  295. #assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  296. s = s.decode('ascii')
  297. return encodeFilename(s, True)
  298. def decodeOption(optval):
  299. if optval is None:
  300. return optval
  301. if isinstance(optval, bytes):
  302. optval = optval.decode(preferredencoding())
  303. assert isinstance(optval, compat_str)
  304. return optval
  305. def formatSeconds(secs):
  306. if secs > 3600:
  307. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  308. elif secs > 60:
  309. return '%d:%02d' % (secs // 60, secs % 60)
  310. else:
  311. return '%d' % secs
  312. def make_HTTPS_handler(opts_no_check_certificate, **kwargs):
  313. if sys.version_info < (3, 2):
  314. import httplib
  315. class HTTPSConnectionV3(httplib.HTTPSConnection):
  316. def __init__(self, *args, **kwargs):
  317. httplib.HTTPSConnection.__init__(self, *args, **kwargs)
  318. def connect(self):
  319. sock = socket.create_connection((self.host, self.port), self.timeout)
  320. if getattr(self, '_tunnel_host', False):
  321. self.sock = sock
  322. self._tunnel()
  323. try:
  324. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
  325. except ssl.SSLError:
  326. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
  327. class HTTPSHandlerV3(compat_urllib_request.HTTPSHandler):
  328. def https_open(self, req):
  329. return self.do_open(HTTPSConnectionV3, req)
  330. return HTTPSHandlerV3(**kwargs)
  331. elif hasattr(ssl, 'create_default_context'): # Python >= 3.4
  332. context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  333. context.options &= ~ssl.OP_NO_SSLv3 # Allow older, not-as-secure SSLv3
  334. if opts_no_check_certificate:
  335. context.verify_mode = ssl.CERT_NONE
  336. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  337. else: # Python < 3.4
  338. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  339. context.verify_mode = (ssl.CERT_NONE
  340. if opts_no_check_certificate
  341. else ssl.CERT_REQUIRED)
  342. context.set_default_verify_paths()
  343. try:
  344. context.load_default_certs()
  345. except AttributeError:
  346. pass # Python < 3.4
  347. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  348. class ExtractorError(Exception):
  349. """Error during info extraction."""
  350. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  351. """ tb, if given, is the original traceback (so that it can be printed out).
  352. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  353. """
  354. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  355. expected = True
  356. if video_id is not None:
  357. msg = video_id + ': ' + msg
  358. if cause:
  359. msg += u' (caused by %r)' % cause
  360. if not expected:
  361. msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call youtube-dl with the --verbose flag and include its complete output. Make sure you are using the latest version; type youtube-dl -U to update.'
  362. super(ExtractorError, self).__init__(msg)
  363. self.traceback = tb
  364. self.exc_info = sys.exc_info() # preserve original exception
  365. self.cause = cause
  366. self.video_id = video_id
  367. def format_traceback(self):
  368. if self.traceback is None:
  369. return None
  370. return u''.join(traceback.format_tb(self.traceback))
  371. class RegexNotFoundError(ExtractorError):
  372. """Error when a regex didn't match"""
  373. pass
  374. class DownloadError(Exception):
  375. """Download Error exception.
  376. This exception may be thrown by FileDownloader objects if they are not
  377. configured to continue on errors. They will contain the appropriate
  378. error message.
  379. """
  380. def __init__(self, msg, exc_info=None):
  381. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  382. super(DownloadError, self).__init__(msg)
  383. self.exc_info = exc_info
  384. class SameFileError(Exception):
  385. """Same File exception.
  386. This exception will be thrown by FileDownloader objects if they detect
  387. multiple files would have to be downloaded to the same file on disk.
  388. """
  389. pass
  390. class PostProcessingError(Exception):
  391. """Post Processing exception.
  392. This exception may be raised by PostProcessor's .run() method to
  393. indicate an error in the postprocessing task.
  394. """
  395. def __init__(self, msg):
  396. self.msg = msg
  397. class MaxDownloadsReached(Exception):
  398. """ --max-downloads limit has been reached. """
  399. pass
  400. class UnavailableVideoError(Exception):
  401. """Unavailable Format exception.
  402. This exception will be thrown when a video is requested
  403. in a format that is not available for that video.
  404. """
  405. pass
  406. class ContentTooShortError(Exception):
  407. """Content Too Short exception.
  408. This exception may be raised by FileDownloader objects when a file they
  409. download is too small for what the server announced first, indicating
  410. the connection was probably interrupted.
  411. """
  412. # Both in bytes
  413. downloaded = None
  414. expected = None
  415. def __init__(self, downloaded, expected):
  416. self.downloaded = downloaded
  417. self.expected = expected
  418. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  419. """Handler for HTTP requests and responses.
  420. This class, when installed with an OpenerDirector, automatically adds
  421. the standard headers to every HTTP request and handles gzipped and
  422. deflated responses from web servers. If compression is to be avoided in
  423. a particular request, the original request in the program code only has
  424. to include the HTTP header "Youtubedl-No-Compression", which will be
  425. removed before making the real request.
  426. Part of this code was copied from:
  427. http://techknack.net/python-urllib2-handlers/
  428. Andrew Rowls, the author of that code, agreed to release it to the
  429. public domain.
  430. """
  431. @staticmethod
  432. def deflate(data):
  433. try:
  434. return zlib.decompress(data, -zlib.MAX_WBITS)
  435. except zlib.error:
  436. return zlib.decompress(data)
  437. @staticmethod
  438. def addinfourl_wrapper(stream, headers, url, code):
  439. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  440. return compat_urllib_request.addinfourl(stream, headers, url, code)
  441. ret = compat_urllib_request.addinfourl(stream, headers, url)
  442. ret.code = code
  443. return ret
  444. def http_request(self, req):
  445. for h, v in std_headers.items():
  446. if h not in req.headers:
  447. req.add_header(h, v)
  448. if 'Youtubedl-no-compression' in req.headers:
  449. if 'Accept-encoding' in req.headers:
  450. del req.headers['Accept-encoding']
  451. del req.headers['Youtubedl-no-compression']
  452. if 'Youtubedl-user-agent' in req.headers:
  453. if 'User-agent' in req.headers:
  454. del req.headers['User-agent']
  455. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  456. del req.headers['Youtubedl-user-agent']
  457. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  458. # Python 2.6 is brain-dead when it comes to fragments
  459. req._Request__original = req._Request__original.partition('#')[0]
  460. req._Request__r_type = req._Request__r_type.partition('#')[0]
  461. return req
  462. def http_response(self, req, resp):
  463. old_resp = resp
  464. # gzip
  465. if resp.headers.get('Content-encoding', '') == 'gzip':
  466. content = resp.read()
  467. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  468. try:
  469. uncompressed = io.BytesIO(gz.read())
  470. except IOError as original_ioerror:
  471. # There may be junk add the end of the file
  472. # See http://stackoverflow.com/q/4928560/35070 for details
  473. for i in range(1, 1024):
  474. try:
  475. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  476. uncompressed = io.BytesIO(gz.read())
  477. except IOError:
  478. continue
  479. break
  480. else:
  481. raise original_ioerror
  482. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  483. resp.msg = old_resp.msg
  484. # deflate
  485. if resp.headers.get('Content-encoding', '') == 'deflate':
  486. gz = io.BytesIO(self.deflate(resp.read()))
  487. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  488. resp.msg = old_resp.msg
  489. return resp
  490. https_request = http_request
  491. https_response = http_response
  492. def parse_iso8601(date_str, delimiter='T'):
  493. """ Return a UNIX timestamp from the given date """
  494. if date_str is None:
  495. return None
  496. m = re.search(
  497. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  498. date_str)
  499. if not m:
  500. timezone = datetime.timedelta()
  501. else:
  502. date_str = date_str[:-len(m.group(0))]
  503. if not m.group('sign'):
  504. timezone = datetime.timedelta()
  505. else:
  506. sign = 1 if m.group('sign') == '+' else -1
  507. timezone = datetime.timedelta(
  508. hours=sign * int(m.group('hours')),
  509. minutes=sign * int(m.group('minutes')))
  510. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  511. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  512. return calendar.timegm(dt.timetuple())
  513. def unified_strdate(date_str):
  514. """Return a string with the date in the format YYYYMMDD"""
  515. if date_str is None:
  516. return None
  517. upload_date = None
  518. #Replace commas
  519. date_str = date_str.replace(',', ' ')
  520. # %z (UTC offset) is only supported in python>=3.2
  521. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  522. format_expressions = [
  523. '%d %B %Y',
  524. '%d %b %Y',
  525. '%B %d %Y',
  526. '%b %d %Y',
  527. '%b %dst %Y %I:%M%p',
  528. '%b %dnd %Y %I:%M%p',
  529. '%b %dth %Y %I:%M%p',
  530. '%Y-%m-%d',
  531. '%Y/%m/%d',
  532. '%d.%m.%Y',
  533. '%d/%m/%Y',
  534. '%d/%m/%y',
  535. '%Y/%m/%d %H:%M:%S',
  536. '%d/%m/%Y %H:%M:%S',
  537. '%Y-%m-%d %H:%M:%S',
  538. '%Y-%m-%d %H:%M:%S.%f',
  539. '%d.%m.%Y %H:%M',
  540. '%d.%m.%Y %H.%M',
  541. '%Y-%m-%dT%H:%M:%SZ',
  542. '%Y-%m-%dT%H:%M:%S.%fZ',
  543. '%Y-%m-%dT%H:%M:%S.%f0Z',
  544. '%Y-%m-%dT%H:%M:%S',
  545. '%Y-%m-%dT%H:%M:%S.%f',
  546. '%Y-%m-%dT%H:%M',
  547. ]
  548. for expression in format_expressions:
  549. try:
  550. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  551. except ValueError:
  552. pass
  553. if upload_date is None:
  554. timetuple = email.utils.parsedate_tz(date_str)
  555. if timetuple:
  556. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  557. return upload_date
  558. def determine_ext(url, default_ext=u'unknown_video'):
  559. if url is None:
  560. return default_ext
  561. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  562. if re.match(r'^[A-Za-z0-9]+$', guess):
  563. return guess
  564. else:
  565. return default_ext
  566. def subtitles_filename(filename, sub_lang, sub_format):
  567. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  568. def date_from_str(date_str):
  569. """
  570. Return a datetime object from a string in the format YYYYMMDD or
  571. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  572. today = datetime.date.today()
  573. if date_str == 'now'or date_str == 'today':
  574. return today
  575. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  576. if match is not None:
  577. sign = match.group('sign')
  578. time = int(match.group('time'))
  579. if sign == '-':
  580. time = -time
  581. unit = match.group('unit')
  582. #A bad aproximation?
  583. if unit == 'month':
  584. unit = 'day'
  585. time *= 30
  586. elif unit == 'year':
  587. unit = 'day'
  588. time *= 365
  589. unit += 's'
  590. delta = datetime.timedelta(**{unit: time})
  591. return today + delta
  592. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  593. def hyphenate_date(date_str):
  594. """
  595. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  596. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  597. if match is not None:
  598. return '-'.join(match.groups())
  599. else:
  600. return date_str
  601. class DateRange(object):
  602. """Represents a time interval between two dates"""
  603. def __init__(self, start=None, end=None):
  604. """start and end must be strings in the format accepted by date"""
  605. if start is not None:
  606. self.start = date_from_str(start)
  607. else:
  608. self.start = datetime.datetime.min.date()
  609. if end is not None:
  610. self.end = date_from_str(end)
  611. else:
  612. self.end = datetime.datetime.max.date()
  613. if self.start > self.end:
  614. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  615. @classmethod
  616. def day(cls, day):
  617. """Returns a range that only contains the given day"""
  618. return cls(day,day)
  619. def __contains__(self, date):
  620. """Check if the date is in the range"""
  621. if not isinstance(date, datetime.date):
  622. date = date_from_str(date)
  623. return self.start <= date <= self.end
  624. def __str__(self):
  625. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  626. def platform_name():
  627. """ Returns the platform name as a compat_str """
  628. res = platform.platform()
  629. if isinstance(res, bytes):
  630. res = res.decode(preferredencoding())
  631. assert isinstance(res, compat_str)
  632. return res
  633. def _windows_write_string(s, out):
  634. """ Returns True if the string was written using special methods,
  635. False if it has yet to be written out."""
  636. # Adapted from http://stackoverflow.com/a/3259271/35070
  637. import ctypes
  638. import ctypes.wintypes
  639. WIN_OUTPUT_IDS = {
  640. 1: -11,
  641. 2: -12,
  642. }
  643. try:
  644. fileno = out.fileno()
  645. except AttributeError:
  646. # If the output stream doesn't have a fileno, it's virtual
  647. return False
  648. if fileno not in WIN_OUTPUT_IDS:
  649. return False
  650. GetStdHandle = ctypes.WINFUNCTYPE(
  651. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  652. ("GetStdHandle", ctypes.windll.kernel32))
  653. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  654. WriteConsoleW = ctypes.WINFUNCTYPE(
  655. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  656. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  657. ctypes.wintypes.LPVOID)(("WriteConsoleW", ctypes.windll.kernel32))
  658. written = ctypes.wintypes.DWORD(0)
  659. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(("GetFileType", ctypes.windll.kernel32))
  660. FILE_TYPE_CHAR = 0x0002
  661. FILE_TYPE_REMOTE = 0x8000
  662. GetConsoleMode = ctypes.WINFUNCTYPE(
  663. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  664. ctypes.POINTER(ctypes.wintypes.DWORD))(
  665. ("GetConsoleMode", ctypes.windll.kernel32))
  666. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  667. def not_a_console(handle):
  668. if handle == INVALID_HANDLE_VALUE or handle is None:
  669. return True
  670. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  671. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  672. if not_a_console(h):
  673. return False
  674. def next_nonbmp_pos(s):
  675. try:
  676. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  677. except StopIteration:
  678. return len(s)
  679. while s:
  680. count = min(next_nonbmp_pos(s), 1024)
  681. ret = WriteConsoleW(
  682. h, s, count if count else 2, ctypes.byref(written), None)
  683. if ret == 0:
  684. raise OSError('Failed to write string')
  685. if not count: # We just wrote a non-BMP character
  686. assert written.value == 2
  687. s = s[1:]
  688. else:
  689. assert written.value > 0
  690. s = s[written.value:]
  691. return True
  692. def write_string(s, out=None, encoding=None):
  693. if out is None:
  694. out = sys.stderr
  695. assert type(s) == compat_str
  696. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  697. if _windows_write_string(s, out):
  698. return
  699. if ('b' in getattr(out, 'mode', '') or
  700. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  701. byt = s.encode(encoding or preferredencoding(), 'ignore')
  702. out.write(byt)
  703. elif hasattr(out, 'buffer'):
  704. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  705. byt = s.encode(enc, 'ignore')
  706. out.buffer.write(byt)
  707. else:
  708. out.write(s)
  709. out.flush()
  710. def bytes_to_intlist(bs):
  711. if not bs:
  712. return []
  713. if isinstance(bs[0], int): # Python 3
  714. return list(bs)
  715. else:
  716. return [ord(c) for c in bs]
  717. def intlist_to_bytes(xs):
  718. if not xs:
  719. return b''
  720. return struct_pack('%dB' % len(xs), *xs)
  721. # Cross-platform file locking
  722. if sys.platform == 'win32':
  723. import ctypes.wintypes
  724. import msvcrt
  725. class OVERLAPPED(ctypes.Structure):
  726. _fields_ = [
  727. ('Internal', ctypes.wintypes.LPVOID),
  728. ('InternalHigh', ctypes.wintypes.LPVOID),
  729. ('Offset', ctypes.wintypes.DWORD),
  730. ('OffsetHigh', ctypes.wintypes.DWORD),
  731. ('hEvent', ctypes.wintypes.HANDLE),
  732. ]
  733. kernel32 = ctypes.windll.kernel32
  734. LockFileEx = kernel32.LockFileEx
  735. LockFileEx.argtypes = [
  736. ctypes.wintypes.HANDLE, # hFile
  737. ctypes.wintypes.DWORD, # dwFlags
  738. ctypes.wintypes.DWORD, # dwReserved
  739. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  740. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  741. ctypes.POINTER(OVERLAPPED) # Overlapped
  742. ]
  743. LockFileEx.restype = ctypes.wintypes.BOOL
  744. UnlockFileEx = kernel32.UnlockFileEx
  745. UnlockFileEx.argtypes = [
  746. ctypes.wintypes.HANDLE, # hFile
  747. ctypes.wintypes.DWORD, # dwReserved
  748. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  749. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  750. ctypes.POINTER(OVERLAPPED) # Overlapped
  751. ]
  752. UnlockFileEx.restype = ctypes.wintypes.BOOL
  753. whole_low = 0xffffffff
  754. whole_high = 0x7fffffff
  755. def _lock_file(f, exclusive):
  756. overlapped = OVERLAPPED()
  757. overlapped.Offset = 0
  758. overlapped.OffsetHigh = 0
  759. overlapped.hEvent = 0
  760. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  761. handle = msvcrt.get_osfhandle(f.fileno())
  762. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  763. whole_low, whole_high, f._lock_file_overlapped_p):
  764. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  765. def _unlock_file(f):
  766. assert f._lock_file_overlapped_p
  767. handle = msvcrt.get_osfhandle(f.fileno())
  768. if not UnlockFileEx(handle, 0,
  769. whole_low, whole_high, f._lock_file_overlapped_p):
  770. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  771. else:
  772. import fcntl
  773. def _lock_file(f, exclusive):
  774. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  775. def _unlock_file(f):
  776. fcntl.flock(f, fcntl.LOCK_UN)
  777. class locked_file(object):
  778. def __init__(self, filename, mode, encoding=None):
  779. assert mode in ['r', 'a', 'w']
  780. self.f = io.open(filename, mode, encoding=encoding)
  781. self.mode = mode
  782. def __enter__(self):
  783. exclusive = self.mode != 'r'
  784. try:
  785. _lock_file(self.f, exclusive)
  786. except IOError:
  787. self.f.close()
  788. raise
  789. return self
  790. def __exit__(self, etype, value, traceback):
  791. try:
  792. _unlock_file(self.f)
  793. finally:
  794. self.f.close()
  795. def __iter__(self):
  796. return iter(self.f)
  797. def write(self, *args):
  798. return self.f.write(*args)
  799. def read(self, *args):
  800. return self.f.read(*args)
  801. def get_filesystem_encoding():
  802. encoding = sys.getfilesystemencoding()
  803. return encoding if encoding is not None else 'utf-8'
  804. def shell_quote(args):
  805. quoted_args = []
  806. encoding = get_filesystem_encoding()
  807. for a in args:
  808. if isinstance(a, bytes):
  809. # We may get a filename encoded with 'encodeFilename'
  810. a = a.decode(encoding)
  811. quoted_args.append(pipes.quote(a))
  812. return u' '.join(quoted_args)
  813. def takewhile_inclusive(pred, seq):
  814. """ Like itertools.takewhile, but include the latest evaluated element
  815. (the first element so that Not pred(e)) """
  816. for e in seq:
  817. yield e
  818. if not pred(e):
  819. return
  820. def smuggle_url(url, data):
  821. """ Pass additional data in a URL for internal use. """
  822. sdata = compat_urllib_parse.urlencode(
  823. {u'__youtubedl_smuggle': json.dumps(data)})
  824. return url + u'#' + sdata
  825. def unsmuggle_url(smug_url, default=None):
  826. if not '#__youtubedl_smuggle' in smug_url:
  827. return smug_url, default
  828. url, _, sdata = smug_url.rpartition(u'#')
  829. jsond = compat_parse_qs(sdata)[u'__youtubedl_smuggle'][0]
  830. data = json.loads(jsond)
  831. return url, data
  832. def format_bytes(bytes):
  833. if bytes is None:
  834. return u'N/A'
  835. if type(bytes) is str:
  836. bytes = float(bytes)
  837. if bytes == 0.0:
  838. exponent = 0
  839. else:
  840. exponent = int(math.log(bytes, 1024.0))
  841. suffix = [u'B', u'KiB', u'MiB', u'GiB', u'TiB', u'PiB', u'EiB', u'ZiB', u'YiB'][exponent]
  842. converted = float(bytes) / float(1024 ** exponent)
  843. return u'%.2f%s' % (converted, suffix)
  844. def get_term_width():
  845. columns = compat_getenv('COLUMNS', None)
  846. if columns:
  847. return int(columns)
  848. try:
  849. sp = subprocess.Popen(
  850. ['stty', 'size'],
  851. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  852. out, err = sp.communicate()
  853. return int(out.split()[1])
  854. except:
  855. pass
  856. return None
  857. def month_by_name(name):
  858. """ Return the number of a month by (locale-independently) English name """
  859. ENGLISH_NAMES = [
  860. u'January', u'February', u'March', u'April', u'May', u'June',
  861. u'July', u'August', u'September', u'October', u'November', u'December']
  862. try:
  863. return ENGLISH_NAMES.index(name) + 1
  864. except ValueError:
  865. return None
  866. def fix_xml_ampersands(xml_str):
  867. """Replace all the '&' by '&amp;' in XML"""
  868. return re.sub(
  869. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  870. u'&amp;',
  871. xml_str)
  872. def setproctitle(title):
  873. assert isinstance(title, compat_str)
  874. try:
  875. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  876. except OSError:
  877. return
  878. title_bytes = title.encode('utf-8')
  879. buf = ctypes.create_string_buffer(len(title_bytes))
  880. buf.value = title_bytes
  881. try:
  882. libc.prctl(15, buf, 0, 0, 0)
  883. except AttributeError:
  884. return # Strange libc, just skip this
  885. def remove_start(s, start):
  886. if s.startswith(start):
  887. return s[len(start):]
  888. return s
  889. def remove_end(s, end):
  890. if s.endswith(end):
  891. return s[:-len(end)]
  892. return s
  893. def url_basename(url):
  894. path = compat_urlparse.urlparse(url).path
  895. return path.strip(u'/').split(u'/')[-1]
  896. class HEADRequest(compat_urllib_request.Request):
  897. def get_method(self):
  898. return "HEAD"
  899. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  900. if get_attr:
  901. if v is not None:
  902. v = getattr(v, get_attr, None)
  903. if v == '':
  904. v = None
  905. return default if v is None else (int(v) * invscale // scale)
  906. def str_or_none(v, default=None):
  907. return default if v is None else compat_str(v)
  908. def str_to_int(int_str):
  909. """ A more relaxed version of int_or_none """
  910. if int_str is None:
  911. return None
  912. int_str = re.sub(r'[,\.\+]', u'', int_str)
  913. return int(int_str)
  914. def float_or_none(v, scale=1, invscale=1, default=None):
  915. return default if v is None else (float(v) * invscale / scale)
  916. def parse_duration(s):
  917. if s is None:
  918. return None
  919. s = s.strip()
  920. m = re.match(
  921. r'(?i)(?:(?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)?(?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?$', s)
  922. if not m:
  923. return None
  924. res = int(m.group('secs'))
  925. if m.group('mins'):
  926. res += int(m.group('mins')) * 60
  927. if m.group('hours'):
  928. res += int(m.group('hours')) * 60 * 60
  929. if m.group('ms'):
  930. res += float(m.group('ms'))
  931. return res
  932. def prepend_extension(filename, ext):
  933. name, real_ext = os.path.splitext(filename)
  934. return u'{0}.{1}{2}'.format(name, ext, real_ext)
  935. def check_executable(exe, args=[]):
  936. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  937. args can be a list of arguments for a short output (like -version) """
  938. try:
  939. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  940. except OSError:
  941. return False
  942. return exe
  943. def get_exe_version(exe, args=['--version'],
  944. version_re=r'version\s+([0-9._-a-zA-Z]+)',
  945. unrecognized=u'present'):
  946. """ Returns the version of the specified executable,
  947. or False if the executable is not present """
  948. try:
  949. out, err = subprocess.Popen(
  950. [exe] + args,
  951. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  952. except OSError:
  953. return False
  954. firstline = out.partition(b'\n')[0].decode('ascii', 'ignore')
  955. m = re.search(version_re, firstline)
  956. if m:
  957. return m.group(1)
  958. else:
  959. return unrecognized
  960. class PagedList(object):
  961. def __len__(self):
  962. # This is only useful for tests
  963. return len(self.getslice())
  964. class OnDemandPagedList(PagedList):
  965. def __init__(self, pagefunc, pagesize):
  966. self._pagefunc = pagefunc
  967. self._pagesize = pagesize
  968. def getslice(self, start=0, end=None):
  969. res = []
  970. for pagenum in itertools.count(start // self._pagesize):
  971. firstid = pagenum * self._pagesize
  972. nextfirstid = pagenum * self._pagesize + self._pagesize
  973. if start >= nextfirstid:
  974. continue
  975. page_results = list(self._pagefunc(pagenum))
  976. startv = (
  977. start % self._pagesize
  978. if firstid <= start < nextfirstid
  979. else 0)
  980. endv = (
  981. ((end - 1) % self._pagesize) + 1
  982. if (end is not None and firstid <= end <= nextfirstid)
  983. else None)
  984. if startv != 0 or endv is not None:
  985. page_results = page_results[startv:endv]
  986. res.extend(page_results)
  987. # A little optimization - if current page is not "full", ie. does
  988. # not contain page_size videos then we can assume that this page
  989. # is the last one - there are no more ids on further pages -
  990. # i.e. no need to query again.
  991. if len(page_results) + startv < self._pagesize:
  992. break
  993. # If we got the whole page, but the next page is not interesting,
  994. # break out early as well
  995. if end == nextfirstid:
  996. break
  997. return res
  998. class InAdvancePagedList(PagedList):
  999. def __init__(self, pagefunc, pagecount, pagesize):
  1000. self._pagefunc = pagefunc
  1001. self._pagecount = pagecount
  1002. self._pagesize = pagesize
  1003. def getslice(self, start=0, end=None):
  1004. res = []
  1005. start_page = start // self._pagesize
  1006. end_page = (
  1007. self._pagecount if end is None else (end // self._pagesize + 1))
  1008. skip_elems = start - start_page * self._pagesize
  1009. only_more = None if end is None else end - start
  1010. for pagenum in range(start_page, end_page):
  1011. page = list(self._pagefunc(pagenum))
  1012. if skip_elems:
  1013. page = page[skip_elems:]
  1014. skip_elems = None
  1015. if only_more is not None:
  1016. if len(page) < only_more:
  1017. only_more -= len(page)
  1018. else:
  1019. page = page[:only_more]
  1020. res.extend(page)
  1021. break
  1022. res.extend(page)
  1023. return res
  1024. def uppercase_escape(s):
  1025. unicode_escape = codecs.getdecoder('unicode_escape')
  1026. return re.sub(
  1027. r'\\U[0-9a-fA-F]{8}',
  1028. lambda m: unicode_escape(m.group(0))[0],
  1029. s)
  1030. def escape_rfc3986(s):
  1031. """Escape non-ASCII characters as suggested by RFC 3986"""
  1032. if sys.version_info < (3, 0) and isinstance(s, unicode):
  1033. s = s.encode('utf-8')
  1034. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1035. def escape_url(url):
  1036. """Escape URL as suggested by RFC 3986"""
  1037. url_parsed = compat_urllib_parse_urlparse(url)
  1038. return url_parsed._replace(
  1039. path=escape_rfc3986(url_parsed.path),
  1040. params=escape_rfc3986(url_parsed.params),
  1041. query=escape_rfc3986(url_parsed.query),
  1042. fragment=escape_rfc3986(url_parsed.fragment)
  1043. ).geturl()
  1044. try:
  1045. struct.pack(u'!I', 0)
  1046. except TypeError:
  1047. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1048. def struct_pack(spec, *args):
  1049. if isinstance(spec, compat_str):
  1050. spec = spec.encode('ascii')
  1051. return struct.pack(spec, *args)
  1052. def struct_unpack(spec, *args):
  1053. if isinstance(spec, compat_str):
  1054. spec = spec.encode('ascii')
  1055. return struct.unpack(spec, *args)
  1056. else:
  1057. struct_pack = struct.pack
  1058. struct_unpack = struct.unpack
  1059. def read_batch_urls(batch_fd):
  1060. def fixup(url):
  1061. if not isinstance(url, compat_str):
  1062. url = url.decode('utf-8', 'replace')
  1063. BOM_UTF8 = u'\xef\xbb\xbf'
  1064. if url.startswith(BOM_UTF8):
  1065. url = url[len(BOM_UTF8):]
  1066. url = url.strip()
  1067. if url.startswith(('#', ';', ']')):
  1068. return False
  1069. return url
  1070. with contextlib.closing(batch_fd) as fd:
  1071. return [url for url in map(fixup, fd) if url]
  1072. def urlencode_postdata(*args, **kargs):
  1073. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1074. try:
  1075. etree_iter = xml.etree.ElementTree.Element.iter
  1076. except AttributeError: # Python <=2.6
  1077. etree_iter = lambda n: n.findall('.//*')
  1078. def parse_xml(s):
  1079. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1080. def doctype(self, name, pubid, system):
  1081. pass # Ignore doctypes
  1082. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1083. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1084. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1085. # Fix up XML parser in Python 2.x
  1086. if sys.version_info < (3, 0):
  1087. for n in etree_iter(tree):
  1088. if n.text is not None:
  1089. if not isinstance(n.text, compat_str):
  1090. n.text = n.text.decode('utf-8')
  1091. return tree
  1092. US_RATINGS = {
  1093. 'G': 0,
  1094. 'PG': 10,
  1095. 'PG-13': 13,
  1096. 'R': 16,
  1097. 'NC': 18,
  1098. }
  1099. def parse_age_limit(s):
  1100. if s is None:
  1101. return None
  1102. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1103. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1104. def strip_jsonp(code):
  1105. return re.sub(
  1106. r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1107. def js_to_json(code):
  1108. def fix_kv(m):
  1109. v = m.group(0)
  1110. if v in ('true', 'false', 'null'):
  1111. return v
  1112. if v.startswith('"'):
  1113. return v
  1114. if v.startswith("'"):
  1115. v = v[1:-1]
  1116. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1117. '\\\\': '\\\\',
  1118. "\\'": "'",
  1119. '"': '\\"',
  1120. }[m.group(0)], v)
  1121. return '"%s"' % v
  1122. res = re.sub(r'''(?x)
  1123. "(?:[^"\\]*(?:\\\\|\\")?)*"|
  1124. '(?:[^'\\]*(?:\\\\|\\')?)*'|
  1125. [a-zA-Z_][a-zA-Z_0-9]*
  1126. ''', fix_kv, code)
  1127. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1128. return res
  1129. def qualities(quality_ids):
  1130. """ Get a numeric quality value out of a list of possible values """
  1131. def q(qid):
  1132. try:
  1133. return quality_ids.index(qid)
  1134. except ValueError:
  1135. return -1
  1136. return q
  1137. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1138. def limit_length(s, length):
  1139. """ Add ellipses to overly long strings """
  1140. if s is None:
  1141. return None
  1142. ELLIPSES = '...'
  1143. if len(s) > length:
  1144. return s[:length - len(ELLIPSES)] + ELLIPSES
  1145. return s
  1146. def version_tuple(v):
  1147. return [int(e) for e in v.split('.')]
  1148. def is_outdated_version(version, limit, assume_new=True):
  1149. if not version:
  1150. return not assume_new
  1151. try:
  1152. return version_tuple(version) < version_tuple(limit)
  1153. except ValueError:
  1154. return not assume_new