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.

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