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.

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