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.

1625 lines
49 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. if h not in req.headers:
  497. req.add_header(h, v)
  498. if 'Youtubedl-no-compression' in req.headers:
  499. if 'Accept-encoding' in req.headers:
  500. del req.headers['Accept-encoding']
  501. del req.headers['Youtubedl-no-compression']
  502. if 'Youtubedl-user-agent' in req.headers:
  503. if 'User-agent' in req.headers:
  504. del req.headers['User-agent']
  505. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  506. del req.headers['Youtubedl-user-agent']
  507. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  508. # Python 2.6 is brain-dead when it comes to fragments
  509. req._Request__original = req._Request__original.partition('#')[0]
  510. req._Request__r_type = req._Request__r_type.partition('#')[0]
  511. return req
  512. def http_response(self, req, resp):
  513. old_resp = resp
  514. # gzip
  515. if resp.headers.get('Content-encoding', '') == 'gzip':
  516. content = resp.read()
  517. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  518. try:
  519. uncompressed = io.BytesIO(gz.read())
  520. except IOError as original_ioerror:
  521. # There may be junk add the end of the file
  522. # See http://stackoverflow.com/q/4928560/35070 for details
  523. for i in range(1, 1024):
  524. try:
  525. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  526. uncompressed = io.BytesIO(gz.read())
  527. except IOError:
  528. continue
  529. break
  530. else:
  531. raise original_ioerror
  532. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  533. resp.msg = old_resp.msg
  534. # deflate
  535. if resp.headers.get('Content-encoding', '') == 'deflate':
  536. gz = io.BytesIO(self.deflate(resp.read()))
  537. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  538. resp.msg = old_resp.msg
  539. return resp
  540. https_request = http_request
  541. https_response = http_response
  542. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  543. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  544. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  545. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  546. self._params = params
  547. def https_open(self, req):
  548. return self.do_open(functools.partial(
  549. _create_http_connection, self, self._https_conn_class, True),
  550. req)
  551. def parse_iso8601(date_str, delimiter='T'):
  552. """ Return a UNIX timestamp from the given date """
  553. if date_str is None:
  554. return None
  555. m = re.search(
  556. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  557. date_str)
  558. if not m:
  559. timezone = datetime.timedelta()
  560. else:
  561. date_str = date_str[:-len(m.group(0))]
  562. if not m.group('sign'):
  563. timezone = datetime.timedelta()
  564. else:
  565. sign = 1 if m.group('sign') == '+' else -1
  566. timezone = datetime.timedelta(
  567. hours=sign * int(m.group('hours')),
  568. minutes=sign * int(m.group('minutes')))
  569. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  570. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  571. return calendar.timegm(dt.timetuple())
  572. def unified_strdate(date_str, day_first=True):
  573. """Return a string with the date in the format YYYYMMDD"""
  574. if date_str is None:
  575. return None
  576. upload_date = None
  577. # Replace commas
  578. date_str = date_str.replace(',', ' ')
  579. # %z (UTC offset) is only supported in python>=3.2
  580. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  581. # Remove AM/PM + timezone
  582. date_str = re.sub(r'(?i)\s*(?:AM|PM)\s+[A-Z]+', '', date_str)
  583. format_expressions = [
  584. '%d %B %Y',
  585. '%d %b %Y',
  586. '%B %d %Y',
  587. '%b %d %Y',
  588. '%b %dst %Y %I:%M%p',
  589. '%b %dnd %Y %I:%M%p',
  590. '%b %dth %Y %I:%M%p',
  591. '%Y %m %d',
  592. '%Y-%m-%d',
  593. '%Y/%m/%d',
  594. '%Y/%m/%d %H:%M:%S',
  595. '%Y-%m-%d %H:%M:%S',
  596. '%Y-%m-%d %H:%M:%S.%f',
  597. '%d.%m.%Y %H:%M',
  598. '%d.%m.%Y %H.%M',
  599. '%Y-%m-%dT%H:%M:%SZ',
  600. '%Y-%m-%dT%H:%M:%S.%fZ',
  601. '%Y-%m-%dT%H:%M:%S.%f0Z',
  602. '%Y-%m-%dT%H:%M:%S',
  603. '%Y-%m-%dT%H:%M:%S.%f',
  604. '%Y-%m-%dT%H:%M',
  605. ]
  606. if day_first:
  607. format_expressions.extend([
  608. '%d.%m.%Y',
  609. '%d/%m/%Y',
  610. '%d/%m/%y',
  611. '%d/%m/%Y %H:%M:%S',
  612. ])
  613. else:
  614. format_expressions.extend([
  615. '%m.%d.%Y',
  616. '%m/%d/%Y',
  617. '%m/%d/%y',
  618. '%m/%d/%Y %H:%M:%S',
  619. ])
  620. for expression in format_expressions:
  621. try:
  622. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  623. except ValueError:
  624. pass
  625. if upload_date is None:
  626. timetuple = email.utils.parsedate_tz(date_str)
  627. if timetuple:
  628. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  629. return upload_date
  630. def determine_ext(url, default_ext='unknown_video'):
  631. if url is None:
  632. return default_ext
  633. guess = url.partition('?')[0].rpartition('.')[2]
  634. if re.match(r'^[A-Za-z0-9]+$', guess):
  635. return guess
  636. else:
  637. return default_ext
  638. def subtitles_filename(filename, sub_lang, sub_format):
  639. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  640. def date_from_str(date_str):
  641. """
  642. Return a datetime object from a string in the format YYYYMMDD or
  643. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  644. today = datetime.date.today()
  645. if date_str in ('now', 'today'):
  646. return today
  647. if date_str == 'yesterday':
  648. return today - datetime.timedelta(days=1)
  649. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  650. if match is not None:
  651. sign = match.group('sign')
  652. time = int(match.group('time'))
  653. if sign == '-':
  654. time = -time
  655. unit = match.group('unit')
  656. # A bad aproximation?
  657. if unit == 'month':
  658. unit = 'day'
  659. time *= 30
  660. elif unit == 'year':
  661. unit = 'day'
  662. time *= 365
  663. unit += 's'
  664. delta = datetime.timedelta(**{unit: time})
  665. return today + delta
  666. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  667. def hyphenate_date(date_str):
  668. """
  669. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  670. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  671. if match is not None:
  672. return '-'.join(match.groups())
  673. else:
  674. return date_str
  675. class DateRange(object):
  676. """Represents a time interval between two dates"""
  677. def __init__(self, start=None, end=None):
  678. """start and end must be strings in the format accepted by date"""
  679. if start is not None:
  680. self.start = date_from_str(start)
  681. else:
  682. self.start = datetime.datetime.min.date()
  683. if end is not None:
  684. self.end = date_from_str(end)
  685. else:
  686. self.end = datetime.datetime.max.date()
  687. if self.start > self.end:
  688. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  689. @classmethod
  690. def day(cls, day):
  691. """Returns a range that only contains the given day"""
  692. return cls(day, day)
  693. def __contains__(self, date):
  694. """Check if the date is in the range"""
  695. if not isinstance(date, datetime.date):
  696. date = date_from_str(date)
  697. return self.start <= date <= self.end
  698. def __str__(self):
  699. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  700. def platform_name():
  701. """ Returns the platform name as a compat_str """
  702. res = platform.platform()
  703. if isinstance(res, bytes):
  704. res = res.decode(preferredencoding())
  705. assert isinstance(res, compat_str)
  706. return res
  707. def _windows_write_string(s, out):
  708. """ Returns True if the string was written using special methods,
  709. False if it has yet to be written out."""
  710. # Adapted from http://stackoverflow.com/a/3259271/35070
  711. import ctypes
  712. import ctypes.wintypes
  713. WIN_OUTPUT_IDS = {
  714. 1: -11,
  715. 2: -12,
  716. }
  717. try:
  718. fileno = out.fileno()
  719. except AttributeError:
  720. # If the output stream doesn't have a fileno, it's virtual
  721. return False
  722. if fileno not in WIN_OUTPUT_IDS:
  723. return False
  724. GetStdHandle = ctypes.WINFUNCTYPE(
  725. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  726. (b"GetStdHandle", ctypes.windll.kernel32))
  727. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  728. WriteConsoleW = ctypes.WINFUNCTYPE(
  729. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  730. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  731. ctypes.wintypes.LPVOID)((b"WriteConsoleW", ctypes.windll.kernel32))
  732. written = ctypes.wintypes.DWORD(0)
  733. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b"GetFileType", ctypes.windll.kernel32))
  734. FILE_TYPE_CHAR = 0x0002
  735. FILE_TYPE_REMOTE = 0x8000
  736. GetConsoleMode = ctypes.WINFUNCTYPE(
  737. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  738. ctypes.POINTER(ctypes.wintypes.DWORD))(
  739. (b"GetConsoleMode", ctypes.windll.kernel32))
  740. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  741. def not_a_console(handle):
  742. if handle == INVALID_HANDLE_VALUE or handle is None:
  743. return True
  744. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  745. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  746. if not_a_console(h):
  747. return False
  748. def next_nonbmp_pos(s):
  749. try:
  750. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  751. except StopIteration:
  752. return len(s)
  753. while s:
  754. count = min(next_nonbmp_pos(s), 1024)
  755. ret = WriteConsoleW(
  756. h, s, count if count else 2, ctypes.byref(written), None)
  757. if ret == 0:
  758. raise OSError('Failed to write string')
  759. if not count: # We just wrote a non-BMP character
  760. assert written.value == 2
  761. s = s[1:]
  762. else:
  763. assert written.value > 0
  764. s = s[written.value:]
  765. return True
  766. def write_string(s, out=None, encoding=None):
  767. if out is None:
  768. out = sys.stderr
  769. assert type(s) == compat_str
  770. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  771. if _windows_write_string(s, out):
  772. return
  773. if ('b' in getattr(out, 'mode', '') or
  774. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  775. byt = s.encode(encoding or preferredencoding(), 'ignore')
  776. out.write(byt)
  777. elif hasattr(out, 'buffer'):
  778. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  779. byt = s.encode(enc, 'ignore')
  780. out.buffer.write(byt)
  781. else:
  782. out.write(s)
  783. out.flush()
  784. def bytes_to_intlist(bs):
  785. if not bs:
  786. return []
  787. if isinstance(bs[0], int): # Python 3
  788. return list(bs)
  789. else:
  790. return [ord(c) for c in bs]
  791. def intlist_to_bytes(xs):
  792. if not xs:
  793. return b''
  794. return struct_pack('%dB' % len(xs), *xs)
  795. # Cross-platform file locking
  796. if sys.platform == 'win32':
  797. import ctypes.wintypes
  798. import msvcrt
  799. class OVERLAPPED(ctypes.Structure):
  800. _fields_ = [
  801. ('Internal', ctypes.wintypes.LPVOID),
  802. ('InternalHigh', ctypes.wintypes.LPVOID),
  803. ('Offset', ctypes.wintypes.DWORD),
  804. ('OffsetHigh', ctypes.wintypes.DWORD),
  805. ('hEvent', ctypes.wintypes.HANDLE),
  806. ]
  807. kernel32 = ctypes.windll.kernel32
  808. LockFileEx = kernel32.LockFileEx
  809. LockFileEx.argtypes = [
  810. ctypes.wintypes.HANDLE, # hFile
  811. ctypes.wintypes.DWORD, # dwFlags
  812. ctypes.wintypes.DWORD, # dwReserved
  813. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  814. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  815. ctypes.POINTER(OVERLAPPED) # Overlapped
  816. ]
  817. LockFileEx.restype = ctypes.wintypes.BOOL
  818. UnlockFileEx = kernel32.UnlockFileEx
  819. UnlockFileEx.argtypes = [
  820. ctypes.wintypes.HANDLE, # hFile
  821. ctypes.wintypes.DWORD, # dwReserved
  822. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  823. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  824. ctypes.POINTER(OVERLAPPED) # Overlapped
  825. ]
  826. UnlockFileEx.restype = ctypes.wintypes.BOOL
  827. whole_low = 0xffffffff
  828. whole_high = 0x7fffffff
  829. def _lock_file(f, exclusive):
  830. overlapped = OVERLAPPED()
  831. overlapped.Offset = 0
  832. overlapped.OffsetHigh = 0
  833. overlapped.hEvent = 0
  834. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  835. handle = msvcrt.get_osfhandle(f.fileno())
  836. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  837. whole_low, whole_high, f._lock_file_overlapped_p):
  838. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  839. def _unlock_file(f):
  840. assert f._lock_file_overlapped_p
  841. handle = msvcrt.get_osfhandle(f.fileno())
  842. if not UnlockFileEx(handle, 0,
  843. whole_low, whole_high, f._lock_file_overlapped_p):
  844. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  845. else:
  846. import fcntl
  847. def _lock_file(f, exclusive):
  848. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  849. def _unlock_file(f):
  850. fcntl.flock(f, fcntl.LOCK_UN)
  851. class locked_file(object):
  852. def __init__(self, filename, mode, encoding=None):
  853. assert mode in ['r', 'a', 'w']
  854. self.f = io.open(filename, mode, encoding=encoding)
  855. self.mode = mode
  856. def __enter__(self):
  857. exclusive = self.mode != 'r'
  858. try:
  859. _lock_file(self.f, exclusive)
  860. except IOError:
  861. self.f.close()
  862. raise
  863. return self
  864. def __exit__(self, etype, value, traceback):
  865. try:
  866. _unlock_file(self.f)
  867. finally:
  868. self.f.close()
  869. def __iter__(self):
  870. return iter(self.f)
  871. def write(self, *args):
  872. return self.f.write(*args)
  873. def read(self, *args):
  874. return self.f.read(*args)
  875. def get_filesystem_encoding():
  876. encoding = sys.getfilesystemencoding()
  877. return encoding if encoding is not None else 'utf-8'
  878. def shell_quote(args):
  879. quoted_args = []
  880. encoding = get_filesystem_encoding()
  881. for a in args:
  882. if isinstance(a, bytes):
  883. # We may get a filename encoded with 'encodeFilename'
  884. a = a.decode(encoding)
  885. quoted_args.append(pipes.quote(a))
  886. return ' '.join(quoted_args)
  887. def takewhile_inclusive(pred, seq):
  888. """ Like itertools.takewhile, but include the latest evaluated element
  889. (the first element so that Not pred(e)) """
  890. for e in seq:
  891. yield e
  892. if not pred(e):
  893. return
  894. def smuggle_url(url, data):
  895. """ Pass additional data in a URL for internal use. """
  896. sdata = compat_urllib_parse.urlencode(
  897. {'__youtubedl_smuggle': json.dumps(data)})
  898. return url + '#' + sdata
  899. def unsmuggle_url(smug_url, default=None):
  900. if '#__youtubedl_smuggle' not in smug_url:
  901. return smug_url, default
  902. url, _, sdata = smug_url.rpartition('#')
  903. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  904. data = json.loads(jsond)
  905. return url, data
  906. def format_bytes(bytes):
  907. if bytes is None:
  908. return 'N/A'
  909. if type(bytes) is str:
  910. bytes = float(bytes)
  911. if bytes == 0.0:
  912. exponent = 0
  913. else:
  914. exponent = int(math.log(bytes, 1024.0))
  915. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  916. converted = float(bytes) / float(1024 ** exponent)
  917. return '%.2f%s' % (converted, suffix)
  918. def parse_filesize(s):
  919. if s is None:
  920. return None
  921. # The lower-case forms are of course incorrect and inofficial,
  922. # but we support those too
  923. _UNIT_TABLE = {
  924. 'B': 1,
  925. 'b': 1,
  926. 'KiB': 1024,
  927. 'KB': 1000,
  928. 'kB': 1024,
  929. 'Kb': 1000,
  930. 'MiB': 1024 ** 2,
  931. 'MB': 1000 ** 2,
  932. 'mB': 1024 ** 2,
  933. 'Mb': 1000 ** 2,
  934. 'GiB': 1024 ** 3,
  935. 'GB': 1000 ** 3,
  936. 'gB': 1024 ** 3,
  937. 'Gb': 1000 ** 3,
  938. 'TiB': 1024 ** 4,
  939. 'TB': 1000 ** 4,
  940. 'tB': 1024 ** 4,
  941. 'Tb': 1000 ** 4,
  942. 'PiB': 1024 ** 5,
  943. 'PB': 1000 ** 5,
  944. 'pB': 1024 ** 5,
  945. 'Pb': 1000 ** 5,
  946. 'EiB': 1024 ** 6,
  947. 'EB': 1000 ** 6,
  948. 'eB': 1024 ** 6,
  949. 'Eb': 1000 ** 6,
  950. 'ZiB': 1024 ** 7,
  951. 'ZB': 1000 ** 7,
  952. 'zB': 1024 ** 7,
  953. 'Zb': 1000 ** 7,
  954. 'YiB': 1024 ** 8,
  955. 'YB': 1000 ** 8,
  956. 'yB': 1024 ** 8,
  957. 'Yb': 1000 ** 8,
  958. }
  959. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  960. m = re.match(
  961. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  962. if not m:
  963. return None
  964. num_str = m.group('num').replace(',', '.')
  965. mult = _UNIT_TABLE[m.group('unit')]
  966. return int(float(num_str) * mult)
  967. def get_term_width():
  968. columns = compat_getenv('COLUMNS', None)
  969. if columns:
  970. return int(columns)
  971. try:
  972. sp = subprocess.Popen(
  973. ['stty', 'size'],
  974. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  975. out, err = sp.communicate()
  976. return int(out.split()[1])
  977. except:
  978. pass
  979. return None
  980. def month_by_name(name):
  981. """ Return the number of a month by (locale-independently) English name """
  982. ENGLISH_NAMES = [
  983. 'January', 'February', 'March', 'April', 'May', 'June',
  984. 'July', 'August', 'September', 'October', 'November', 'December']
  985. try:
  986. return ENGLISH_NAMES.index(name) + 1
  987. except ValueError:
  988. return None
  989. def fix_xml_ampersands(xml_str):
  990. """Replace all the '&' by '&amp;' in XML"""
  991. return re.sub(
  992. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  993. '&amp;',
  994. xml_str)
  995. def setproctitle(title):
  996. assert isinstance(title, compat_str)
  997. try:
  998. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  999. except OSError:
  1000. return
  1001. title_bytes = title.encode('utf-8')
  1002. buf = ctypes.create_string_buffer(len(title_bytes))
  1003. buf.value = title_bytes
  1004. try:
  1005. libc.prctl(15, buf, 0, 0, 0)
  1006. except AttributeError:
  1007. return # Strange libc, just skip this
  1008. def remove_start(s, start):
  1009. if s.startswith(start):
  1010. return s[len(start):]
  1011. return s
  1012. def remove_end(s, end):
  1013. if s.endswith(end):
  1014. return s[:-len(end)]
  1015. return s
  1016. def url_basename(url):
  1017. path = compat_urlparse.urlparse(url).path
  1018. return path.strip('/').split('/')[-1]
  1019. class HEADRequest(compat_urllib_request.Request):
  1020. def get_method(self):
  1021. return "HEAD"
  1022. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1023. if get_attr:
  1024. if v is not None:
  1025. v = getattr(v, get_attr, None)
  1026. if v == '':
  1027. v = None
  1028. return default if v is None else (int(v) * invscale // scale)
  1029. def str_or_none(v, default=None):
  1030. return default if v is None else compat_str(v)
  1031. def str_to_int(int_str):
  1032. """ A more relaxed version of int_or_none """
  1033. if int_str is None:
  1034. return None
  1035. int_str = re.sub(r'[,\.\+]', '', int_str)
  1036. return int(int_str)
  1037. def float_or_none(v, scale=1, invscale=1, default=None):
  1038. return default if v is None else (float(v) * invscale / scale)
  1039. def parse_duration(s):
  1040. if not isinstance(s, basestring if sys.version_info < (3, 0) else compat_str):
  1041. return None
  1042. s = s.strip()
  1043. m = re.match(
  1044. r'''(?ix)(?:P?T)?
  1045. (?:
  1046. (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*|
  1047. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1048. (?:
  1049. (?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)?
  1050. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1051. )?
  1052. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1053. )$''', s)
  1054. if not m:
  1055. return None
  1056. res = 0
  1057. if m.group('only_mins'):
  1058. return float_or_none(m.group('only_mins'), invscale=60)
  1059. if m.group('only_hours'):
  1060. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1061. if m.group('secs'):
  1062. res += int(m.group('secs'))
  1063. if m.group('mins'):
  1064. res += int(m.group('mins')) * 60
  1065. if m.group('hours'):
  1066. res += int(m.group('hours')) * 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, unicode):
  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. return getheader('Content-Type').split("/")[1]
  1312. def age_restricted(content_limit, age_limit):
  1313. """ Returns True iff the content should be blocked """
  1314. if age_limit is None: # No limit set
  1315. return False
  1316. if content_limit is None:
  1317. return False # Content available for everyone
  1318. return age_limit < content_limit