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.

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