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.

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