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.

1512 lines
45 KiB

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