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.

1623 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.CLIENT_AUTH)
  332. if opts_no_check_certificate:
  333. context.verify_mode = ssl.CERT_NONE
  334. try:
  335. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  336. except TypeError:
  337. # Python 2.7.8
  338. # (create_default_context present but HTTPSHandler has no context=)
  339. pass
  340. if sys.version_info < (3, 2):
  341. import httplib
  342. class HTTPSConnectionV3(httplib.HTTPSConnection):
  343. def __init__(self, *args, **kwargs):
  344. httplib.HTTPSConnection.__init__(self, *args, **kwargs)
  345. def connect(self):
  346. sock = socket.create_connection((self.host, self.port), self.timeout)
  347. if getattr(self, '_tunnel_host', False):
  348. self.sock = sock
  349. self._tunnel()
  350. try:
  351. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
  352. except ssl.SSLError:
  353. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
  354. return YoutubeDLHTTPSHandler(params, https_conn_class=HTTPSConnectionV3, **kwargs)
  355. else: # Python < 3.4
  356. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  357. context.verify_mode = (ssl.CERT_NONE
  358. if opts_no_check_certificate
  359. else ssl.CERT_REQUIRED)
  360. context.set_default_verify_paths()
  361. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  362. class ExtractorError(Exception):
  363. """Error during info extraction."""
  364. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  365. """ tb, if given, is the original traceback (so that it can be printed out).
  366. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  367. """
  368. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  369. expected = True
  370. if video_id is not None:
  371. msg = video_id + ': ' + msg
  372. if cause:
  373. msg += ' (caused by %r)' % cause
  374. if not expected:
  375. if ytdl_is_updateable():
  376. update_cmd = 'type youtube-dl -U to update'
  377. else:
  378. update_cmd = 'see https://yt-dl.org/update on how to update'
  379. msg += '; please report this issue on https://yt-dl.org/bug .'
  380. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  381. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  382. super(ExtractorError, self).__init__(msg)
  383. self.traceback = tb
  384. self.exc_info = sys.exc_info() # preserve original exception
  385. self.cause = cause
  386. self.video_id = video_id
  387. def format_traceback(self):
  388. if self.traceback is None:
  389. return None
  390. return ''.join(traceback.format_tb(self.traceback))
  391. class UnsupportedError(ExtractorError):
  392. def __init__(self, url):
  393. super(UnsupportedError, self).__init__(
  394. 'Unsupported URL: %s' % url, expected=True)
  395. self.url = url
  396. class RegexNotFoundError(ExtractorError):
  397. """Error when a regex didn't match"""
  398. pass
  399. class DownloadError(Exception):
  400. """Download Error exception.
  401. This exception may be thrown by FileDownloader objects if they are not
  402. configured to continue on errors. They will contain the appropriate
  403. error message.
  404. """
  405. def __init__(self, msg, exc_info=None):
  406. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  407. super(DownloadError, self).__init__(msg)
  408. self.exc_info = exc_info
  409. class SameFileError(Exception):
  410. """Same File exception.
  411. This exception will be thrown by FileDownloader objects if they detect
  412. multiple files would have to be downloaded to the same file on disk.
  413. """
  414. pass
  415. class PostProcessingError(Exception):
  416. """Post Processing exception.
  417. This exception may be raised by PostProcessor's .run() method to
  418. indicate an error in the postprocessing task.
  419. """
  420. def __init__(self, msg):
  421. self.msg = msg
  422. class MaxDownloadsReached(Exception):
  423. """ --max-downloads limit has been reached. """
  424. pass
  425. class UnavailableVideoError(Exception):
  426. """Unavailable Format exception.
  427. This exception will be thrown when a video is requested
  428. in a format that is not available for that video.
  429. """
  430. pass
  431. class ContentTooShortError(Exception):
  432. """Content Too Short exception.
  433. This exception may be raised by FileDownloader objects when a file they
  434. download is too small for what the server announced first, indicating
  435. the connection was probably interrupted.
  436. """
  437. # Both in bytes
  438. downloaded = None
  439. expected = None
  440. def __init__(self, downloaded, expected):
  441. self.downloaded = downloaded
  442. self.expected = expected
  443. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  444. hc = http_class(*args, **kwargs)
  445. source_address = ydl_handler._params.get('source_address')
  446. if source_address is not None:
  447. sa = (source_address, 0)
  448. if hasattr(hc, 'source_address'): # Python 2.7+
  449. hc.source_address = sa
  450. else: # Python 2.6
  451. def _hc_connect(self, *args, **kwargs):
  452. sock = compat_socket_create_connection(
  453. (self.host, self.port), self.timeout, sa)
  454. if is_https:
  455. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
  456. else:
  457. self.sock = sock
  458. hc.connect = functools.partial(_hc_connect, hc)
  459. return hc
  460. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  461. """Handler for HTTP requests and responses.
  462. This class, when installed with an OpenerDirector, automatically adds
  463. the standard headers to every HTTP request and handles gzipped and
  464. deflated responses from web servers. If compression is to be avoided in
  465. a particular request, the original request in the program code only has
  466. to include the HTTP header "Youtubedl-No-Compression", which will be
  467. removed before making the real request.
  468. Part of this code was copied from:
  469. http://techknack.net/python-urllib2-handlers/
  470. Andrew Rowls, the author of that code, agreed to release it to the
  471. public domain.
  472. """
  473. def __init__(self, params, *args, **kwargs):
  474. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  475. self._params = params
  476. def http_open(self, req):
  477. return self.do_open(functools.partial(
  478. _create_http_connection, self, compat_http_client.HTTPConnection, False),
  479. req)
  480. @staticmethod
  481. def deflate(data):
  482. try:
  483. return zlib.decompress(data, -zlib.MAX_WBITS)
  484. except zlib.error:
  485. return zlib.decompress(data)
  486. @staticmethod
  487. def addinfourl_wrapper(stream, headers, url, code):
  488. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  489. return compat_urllib_request.addinfourl(stream, headers, url, code)
  490. ret = compat_urllib_request.addinfourl(stream, headers, url)
  491. ret.code = code
  492. return ret
  493. def http_request(self, req):
  494. for h, v in std_headers.items():
  495. if h not in req.headers:
  496. req.add_header(h, v)
  497. if 'Youtubedl-no-compression' in req.headers:
  498. if 'Accept-encoding' in req.headers:
  499. del req.headers['Accept-encoding']
  500. del req.headers['Youtubedl-no-compression']
  501. if 'Youtubedl-user-agent' in req.headers:
  502. if 'User-agent' in req.headers:
  503. del req.headers['User-agent']
  504. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  505. del req.headers['Youtubedl-user-agent']
  506. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  507. # Python 2.6 is brain-dead when it comes to fragments
  508. req._Request__original = req._Request__original.partition('#')[0]
  509. req._Request__r_type = req._Request__r_type.partition('#')[0]
  510. return req
  511. def http_response(self, req, resp):
  512. old_resp = resp
  513. # gzip
  514. if resp.headers.get('Content-encoding', '') == 'gzip':
  515. content = resp.read()
  516. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  517. try:
  518. uncompressed = io.BytesIO(gz.read())
  519. except IOError as original_ioerror:
  520. # There may be junk add the end of the file
  521. # See http://stackoverflow.com/q/4928560/35070 for details
  522. for i in range(1, 1024):
  523. try:
  524. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  525. uncompressed = io.BytesIO(gz.read())
  526. except IOError:
  527. continue
  528. break
  529. else:
  530. raise original_ioerror
  531. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  532. resp.msg = old_resp.msg
  533. # deflate
  534. if resp.headers.get('Content-encoding', '') == 'deflate':
  535. gz = io.BytesIO(self.deflate(resp.read()))
  536. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  537. resp.msg = old_resp.msg
  538. return resp
  539. https_request = http_request
  540. https_response = http_response
  541. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  542. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  543. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  544. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  545. self._params = params
  546. def https_open(self, req):
  547. return self.do_open(functools.partial(
  548. _create_http_connection, self, self._https_conn_class, True),
  549. req)
  550. def parse_iso8601(date_str, delimiter='T'):
  551. """ Return a UNIX timestamp from the given date """
  552. if date_str is None:
  553. return None
  554. m = re.search(
  555. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  556. date_str)
  557. if not m:
  558. timezone = datetime.timedelta()
  559. else:
  560. date_str = date_str[:-len(m.group(0))]
  561. if not m.group('sign'):
  562. timezone = datetime.timedelta()
  563. else:
  564. sign = 1 if m.group('sign') == '+' else -1
  565. timezone = datetime.timedelta(
  566. hours=sign * int(m.group('hours')),
  567. minutes=sign * int(m.group('minutes')))
  568. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  569. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  570. return calendar.timegm(dt.timetuple())
  571. def unified_strdate(date_str, day_first=True):
  572. """Return a string with the date in the format YYYYMMDD"""
  573. if date_str is None:
  574. return None
  575. upload_date = None
  576. # Replace commas
  577. date_str = date_str.replace(',', ' ')
  578. # %z (UTC offset) is only supported in python>=3.2
  579. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  580. # Remove AM/PM + timezone
  581. date_str = re.sub(r'(?i)\s*(?:AM|PM)\s+[A-Z]+', '', date_str)
  582. format_expressions = [
  583. '%d %B %Y',
  584. '%d %b %Y',
  585. '%B %d %Y',
  586. '%b %d %Y',
  587. '%b %dst %Y %I:%M%p',
  588. '%b %dnd %Y %I:%M%p',
  589. '%b %dth %Y %I:%M%p',
  590. '%Y-%m-%d',
  591. '%Y/%m/%d',
  592. '%Y/%m/%d %H:%M:%S',
  593. '%Y-%m-%d %H:%M:%S',
  594. '%Y-%m-%d %H:%M:%S.%f',
  595. '%d.%m.%Y %H:%M',
  596. '%d.%m.%Y %H.%M',
  597. '%Y-%m-%dT%H:%M:%SZ',
  598. '%Y-%m-%dT%H:%M:%S.%fZ',
  599. '%Y-%m-%dT%H:%M:%S.%f0Z',
  600. '%Y-%m-%dT%H:%M:%S',
  601. '%Y-%m-%dT%H:%M:%S.%f',
  602. '%Y-%m-%dT%H:%M',
  603. ]
  604. if day_first:
  605. format_expressions.extend([
  606. '%d.%m.%Y',
  607. '%d/%m/%Y',
  608. '%d/%m/%y',
  609. '%d/%m/%Y %H:%M:%S',
  610. ])
  611. else:
  612. format_expressions.extend([
  613. '%m.%d.%Y',
  614. '%m/%d/%Y',
  615. '%m/%d/%y',
  616. '%m/%d/%Y %H:%M:%S',
  617. ])
  618. for expression in format_expressions:
  619. try:
  620. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  621. except ValueError:
  622. pass
  623. if upload_date is None:
  624. timetuple = email.utils.parsedate_tz(date_str)
  625. if timetuple:
  626. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  627. return upload_date
  628. def determine_ext(url, default_ext='unknown_video'):
  629. if url is None:
  630. return default_ext
  631. guess = url.partition('?')[0].rpartition('.')[2]
  632. if re.match(r'^[A-Za-z0-9]+$', guess):
  633. return guess
  634. else:
  635. return default_ext
  636. def subtitles_filename(filename, sub_lang, sub_format):
  637. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  638. def date_from_str(date_str):
  639. """
  640. Return a datetime object from a string in the format YYYYMMDD or
  641. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  642. today = datetime.date.today()
  643. if date_str in ('now', 'today'):
  644. return today
  645. if date_str == 'yesterday':
  646. return today - datetime.timedelta(days=1)
  647. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  648. if match is not None:
  649. sign = match.group('sign')
  650. time = int(match.group('time'))
  651. if sign == '-':
  652. time = -time
  653. unit = match.group('unit')
  654. # A bad aproximation?
  655. if unit == 'month':
  656. unit = 'day'
  657. time *= 30
  658. elif unit == 'year':
  659. unit = 'day'
  660. time *= 365
  661. unit += 's'
  662. delta = datetime.timedelta(**{unit: time})
  663. return today + delta
  664. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  665. def hyphenate_date(date_str):
  666. """
  667. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  668. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  669. if match is not None:
  670. return '-'.join(match.groups())
  671. else:
  672. return date_str
  673. class DateRange(object):
  674. """Represents a time interval between two dates"""
  675. def __init__(self, start=None, end=None):
  676. """start and end must be strings in the format accepted by date"""
  677. if start is not None:
  678. self.start = date_from_str(start)
  679. else:
  680. self.start = datetime.datetime.min.date()
  681. if end is not None:
  682. self.end = date_from_str(end)
  683. else:
  684. self.end = datetime.datetime.max.date()
  685. if self.start > self.end:
  686. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  687. @classmethod
  688. def day(cls, day):
  689. """Returns a range that only contains the given day"""
  690. return cls(day, day)
  691. def __contains__(self, date):
  692. """Check if the date is in the range"""
  693. if not isinstance(date, datetime.date):
  694. date = date_from_str(date)
  695. return self.start <= date <= self.end
  696. def __str__(self):
  697. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  698. def platform_name():
  699. """ Returns the platform name as a compat_str """
  700. res = platform.platform()
  701. if isinstance(res, bytes):
  702. res = res.decode(preferredencoding())
  703. assert isinstance(res, compat_str)
  704. return res
  705. def _windows_write_string(s, out):
  706. """ Returns True if the string was written using special methods,
  707. False if it has yet to be written out."""
  708. # Adapted from http://stackoverflow.com/a/3259271/35070
  709. import ctypes
  710. import ctypes.wintypes
  711. WIN_OUTPUT_IDS = {
  712. 1: -11,
  713. 2: -12,
  714. }
  715. try:
  716. fileno = out.fileno()
  717. except AttributeError:
  718. # If the output stream doesn't have a fileno, it's virtual
  719. return False
  720. if fileno not in WIN_OUTPUT_IDS:
  721. return False
  722. GetStdHandle = ctypes.WINFUNCTYPE(
  723. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  724. (b"GetStdHandle", ctypes.windll.kernel32))
  725. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  726. WriteConsoleW = ctypes.WINFUNCTYPE(
  727. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  728. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  729. ctypes.wintypes.LPVOID)((b"WriteConsoleW", ctypes.windll.kernel32))
  730. written = ctypes.wintypes.DWORD(0)
  731. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b"GetFileType", ctypes.windll.kernel32))
  732. FILE_TYPE_CHAR = 0x0002
  733. FILE_TYPE_REMOTE = 0x8000
  734. GetConsoleMode = ctypes.WINFUNCTYPE(
  735. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  736. ctypes.POINTER(ctypes.wintypes.DWORD))(
  737. (b"GetConsoleMode", ctypes.windll.kernel32))
  738. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  739. def not_a_console(handle):
  740. if handle == INVALID_HANDLE_VALUE or handle is None:
  741. return True
  742. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  743. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  744. if not_a_console(h):
  745. return False
  746. def next_nonbmp_pos(s):
  747. try:
  748. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  749. except StopIteration:
  750. return len(s)
  751. while s:
  752. count = min(next_nonbmp_pos(s), 1024)
  753. ret = WriteConsoleW(
  754. h, s, count if count else 2, ctypes.byref(written), None)
  755. if ret == 0:
  756. raise OSError('Failed to write string')
  757. if not count: # We just wrote a non-BMP character
  758. assert written.value == 2
  759. s = s[1:]
  760. else:
  761. assert written.value > 0
  762. s = s[written.value:]
  763. return True
  764. def write_string(s, out=None, encoding=None):
  765. if out is None:
  766. out = sys.stderr
  767. assert type(s) == compat_str
  768. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  769. if _windows_write_string(s, out):
  770. return
  771. if ('b' in getattr(out, 'mode', '') or
  772. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  773. byt = s.encode(encoding or preferredencoding(), 'ignore')
  774. out.write(byt)
  775. elif hasattr(out, 'buffer'):
  776. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  777. byt = s.encode(enc, 'ignore')
  778. out.buffer.write(byt)
  779. else:
  780. out.write(s)
  781. out.flush()
  782. def bytes_to_intlist(bs):
  783. if not bs:
  784. return []
  785. if isinstance(bs[0], int): # Python 3
  786. return list(bs)
  787. else:
  788. return [ord(c) for c in bs]
  789. def intlist_to_bytes(xs):
  790. if not xs:
  791. return b''
  792. return struct_pack('%dB' % len(xs), *xs)
  793. # Cross-platform file locking
  794. if sys.platform == 'win32':
  795. import ctypes.wintypes
  796. import msvcrt
  797. class OVERLAPPED(ctypes.Structure):
  798. _fields_ = [
  799. ('Internal', ctypes.wintypes.LPVOID),
  800. ('InternalHigh', ctypes.wintypes.LPVOID),
  801. ('Offset', ctypes.wintypes.DWORD),
  802. ('OffsetHigh', ctypes.wintypes.DWORD),
  803. ('hEvent', ctypes.wintypes.HANDLE),
  804. ]
  805. kernel32 = ctypes.windll.kernel32
  806. LockFileEx = kernel32.LockFileEx
  807. LockFileEx.argtypes = [
  808. ctypes.wintypes.HANDLE, # hFile
  809. ctypes.wintypes.DWORD, # dwFlags
  810. ctypes.wintypes.DWORD, # dwReserved
  811. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  812. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  813. ctypes.POINTER(OVERLAPPED) # Overlapped
  814. ]
  815. LockFileEx.restype = ctypes.wintypes.BOOL
  816. UnlockFileEx = kernel32.UnlockFileEx
  817. UnlockFileEx.argtypes = [
  818. ctypes.wintypes.HANDLE, # hFile
  819. ctypes.wintypes.DWORD, # dwReserved
  820. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  821. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  822. ctypes.POINTER(OVERLAPPED) # Overlapped
  823. ]
  824. UnlockFileEx.restype = ctypes.wintypes.BOOL
  825. whole_low = 0xffffffff
  826. whole_high = 0x7fffffff
  827. def _lock_file(f, exclusive):
  828. overlapped = OVERLAPPED()
  829. overlapped.Offset = 0
  830. overlapped.OffsetHigh = 0
  831. overlapped.hEvent = 0
  832. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  833. handle = msvcrt.get_osfhandle(f.fileno())
  834. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  835. whole_low, whole_high, f._lock_file_overlapped_p):
  836. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  837. def _unlock_file(f):
  838. assert f._lock_file_overlapped_p
  839. handle = msvcrt.get_osfhandle(f.fileno())
  840. if not UnlockFileEx(handle, 0,
  841. whole_low, whole_high, f._lock_file_overlapped_p):
  842. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  843. else:
  844. import fcntl
  845. def _lock_file(f, exclusive):
  846. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  847. def _unlock_file(f):
  848. fcntl.flock(f, fcntl.LOCK_UN)
  849. class locked_file(object):
  850. def __init__(self, filename, mode, encoding=None):
  851. assert mode in ['r', 'a', 'w']
  852. self.f = io.open(filename, mode, encoding=encoding)
  853. self.mode = mode
  854. def __enter__(self):
  855. exclusive = self.mode != 'r'
  856. try:
  857. _lock_file(self.f, exclusive)
  858. except IOError:
  859. self.f.close()
  860. raise
  861. return self
  862. def __exit__(self, etype, value, traceback):
  863. try:
  864. _unlock_file(self.f)
  865. finally:
  866. self.f.close()
  867. def __iter__(self):
  868. return iter(self.f)
  869. def write(self, *args):
  870. return self.f.write(*args)
  871. def read(self, *args):
  872. return self.f.read(*args)
  873. def get_filesystem_encoding():
  874. encoding = sys.getfilesystemencoding()
  875. return encoding if encoding is not None else 'utf-8'
  876. def shell_quote(args):
  877. quoted_args = []
  878. encoding = get_filesystem_encoding()
  879. for a in args:
  880. if isinstance(a, bytes):
  881. # We may get a filename encoded with 'encodeFilename'
  882. a = a.decode(encoding)
  883. quoted_args.append(pipes.quote(a))
  884. return ' '.join(quoted_args)
  885. def takewhile_inclusive(pred, seq):
  886. """ Like itertools.takewhile, but include the latest evaluated element
  887. (the first element so that Not pred(e)) """
  888. for e in seq:
  889. yield e
  890. if not pred(e):
  891. return
  892. def smuggle_url(url, data):
  893. """ Pass additional data in a URL for internal use. """
  894. sdata = compat_urllib_parse.urlencode(
  895. {'__youtubedl_smuggle': json.dumps(data)})
  896. return url + '#' + sdata
  897. def unsmuggle_url(smug_url, default=None):
  898. if '#__youtubedl_smuggle' not in smug_url:
  899. return smug_url, default
  900. url, _, sdata = smug_url.rpartition('#')
  901. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  902. data = json.loads(jsond)
  903. return url, data
  904. def format_bytes(bytes):
  905. if bytes is None:
  906. return 'N/A'
  907. if type(bytes) is str:
  908. bytes = float(bytes)
  909. if bytes == 0.0:
  910. exponent = 0
  911. else:
  912. exponent = int(math.log(bytes, 1024.0))
  913. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  914. converted = float(bytes) / float(1024 ** exponent)
  915. return '%.2f%s' % (converted, suffix)
  916. def parse_filesize(s):
  917. if s is None:
  918. return None
  919. # The lower-case forms are of course incorrect and inofficial,
  920. # but we support those too
  921. _UNIT_TABLE = {
  922. 'B': 1,
  923. 'b': 1,
  924. 'KiB': 1024,
  925. 'KB': 1000,
  926. 'kB': 1024,
  927. 'Kb': 1000,
  928. 'MiB': 1024 ** 2,
  929. 'MB': 1000 ** 2,
  930. 'mB': 1024 ** 2,
  931. 'Mb': 1000 ** 2,
  932. 'GiB': 1024 ** 3,
  933. 'GB': 1000 ** 3,
  934. 'gB': 1024 ** 3,
  935. 'Gb': 1000 ** 3,
  936. 'TiB': 1024 ** 4,
  937. 'TB': 1000 ** 4,
  938. 'tB': 1024 ** 4,
  939. 'Tb': 1000 ** 4,
  940. 'PiB': 1024 ** 5,
  941. 'PB': 1000 ** 5,
  942. 'pB': 1024 ** 5,
  943. 'Pb': 1000 ** 5,
  944. 'EiB': 1024 ** 6,
  945. 'EB': 1000 ** 6,
  946. 'eB': 1024 ** 6,
  947. 'Eb': 1000 ** 6,
  948. 'ZiB': 1024 ** 7,
  949. 'ZB': 1000 ** 7,
  950. 'zB': 1024 ** 7,
  951. 'Zb': 1000 ** 7,
  952. 'YiB': 1024 ** 8,
  953. 'YB': 1000 ** 8,
  954. 'yB': 1024 ** 8,
  955. 'Yb': 1000 ** 8,
  956. }
  957. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  958. m = re.match(
  959. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  960. if not m:
  961. return None
  962. num_str = m.group('num').replace(',', '.')
  963. mult = _UNIT_TABLE[m.group('unit')]
  964. return int(float(num_str) * mult)
  965. def get_term_width():
  966. columns = compat_getenv('COLUMNS', None)
  967. if columns:
  968. return int(columns)
  969. try:
  970. sp = subprocess.Popen(
  971. ['stty', 'size'],
  972. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  973. out, err = sp.communicate()
  974. return int(out.split()[1])
  975. except:
  976. pass
  977. return None
  978. def month_by_name(name):
  979. """ Return the number of a month by (locale-independently) English name """
  980. ENGLISH_NAMES = [
  981. 'January', 'February', 'March', 'April', 'May', 'June',
  982. 'July', 'August', 'September', 'October', 'November', 'December']
  983. try:
  984. return ENGLISH_NAMES.index(name) + 1
  985. except ValueError:
  986. return None
  987. def fix_xml_ampersands(xml_str):
  988. """Replace all the '&' by '&amp;' in XML"""
  989. return re.sub(
  990. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  991. '&amp;',
  992. xml_str)
  993. def setproctitle(title):
  994. assert isinstance(title, compat_str)
  995. try:
  996. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  997. except OSError:
  998. return
  999. title_bytes = title.encode('utf-8')
  1000. buf = ctypes.create_string_buffer(len(title_bytes))
  1001. buf.value = title_bytes
  1002. try:
  1003. libc.prctl(15, buf, 0, 0, 0)
  1004. except AttributeError:
  1005. return # Strange libc, just skip this
  1006. def remove_start(s, start):
  1007. if s.startswith(start):
  1008. return s[len(start):]
  1009. return s
  1010. def remove_end(s, end):
  1011. if s.endswith(end):
  1012. return s[:-len(end)]
  1013. return s
  1014. def url_basename(url):
  1015. path = compat_urlparse.urlparse(url).path
  1016. return path.strip('/').split('/')[-1]
  1017. class HEADRequest(compat_urllib_request.Request):
  1018. def get_method(self):
  1019. return "HEAD"
  1020. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1021. if get_attr:
  1022. if v is not None:
  1023. v = getattr(v, get_attr, None)
  1024. if v == '':
  1025. v = None
  1026. return default if v is None else (int(v) * invscale // scale)
  1027. def str_or_none(v, default=None):
  1028. return default if v is None else compat_str(v)
  1029. def str_to_int(int_str):
  1030. """ A more relaxed version of int_or_none """
  1031. if int_str is None:
  1032. return None
  1033. int_str = re.sub(r'[,\.\+]', '', int_str)
  1034. return int(int_str)
  1035. def float_or_none(v, scale=1, invscale=1, default=None):
  1036. return default if v is None else (float(v) * invscale / scale)
  1037. def parse_duration(s):
  1038. if not isinstance(s, basestring if sys.version_info < (3, 0) else compat_str):
  1039. return None
  1040. s = s.strip()
  1041. m = re.match(
  1042. r'''(?ix)T?
  1043. (?:
  1044. (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*|
  1045. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1046. (?:
  1047. (?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)?
  1048. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1049. )?
  1050. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1051. )$''', s)
  1052. if not m:
  1053. return None
  1054. res = 0
  1055. if m.group('only_mins'):
  1056. return float_or_none(m.group('only_mins'), invscale=60)
  1057. if m.group('only_hours'):
  1058. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1059. if m.group('secs'):
  1060. res += int(m.group('secs'))
  1061. if m.group('mins'):
  1062. res += int(m.group('mins')) * 60
  1063. if m.group('hours'):
  1064. res += int(m.group('hours')) * 60 * 60
  1065. if m.group('ms'):
  1066. res += float(m.group('ms'))
  1067. return res
  1068. def prepend_extension(filename, ext):
  1069. name, real_ext = os.path.splitext(filename)
  1070. return '{0}.{1}{2}'.format(name, ext, real_ext)
  1071. def check_executable(exe, args=[]):
  1072. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1073. args can be a list of arguments for a short output (like -version) """
  1074. try:
  1075. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1076. except OSError:
  1077. return False
  1078. return exe
  1079. def get_exe_version(exe, args=['--version'],
  1080. version_re=None, unrecognized='present'):
  1081. """ Returns the version of the specified executable,
  1082. or False if the executable is not present """
  1083. try:
  1084. out, _ = subprocess.Popen(
  1085. [exe] + args,
  1086. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1087. except OSError:
  1088. return False
  1089. if isinstance(out, bytes): # Python 2.x
  1090. out = out.decode('ascii', 'ignore')
  1091. return detect_exe_version(out, version_re, unrecognized)
  1092. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1093. assert isinstance(output, compat_str)
  1094. if version_re is None:
  1095. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1096. m = re.search(version_re, output)
  1097. if m:
  1098. return m.group(1)
  1099. else:
  1100. return unrecognized
  1101. class PagedList(object):
  1102. def __len__(self):
  1103. # This is only useful for tests
  1104. return len(self.getslice())
  1105. class OnDemandPagedList(PagedList):
  1106. def __init__(self, pagefunc, pagesize):
  1107. self._pagefunc = pagefunc
  1108. self._pagesize = pagesize
  1109. def getslice(self, start=0, end=None):
  1110. res = []
  1111. for pagenum in itertools.count(start // self._pagesize):
  1112. firstid = pagenum * self._pagesize
  1113. nextfirstid = pagenum * self._pagesize + self._pagesize
  1114. if start >= nextfirstid:
  1115. continue
  1116. page_results = list(self._pagefunc(pagenum))
  1117. startv = (
  1118. start % self._pagesize
  1119. if firstid <= start < nextfirstid
  1120. else 0)
  1121. endv = (
  1122. ((end - 1) % self._pagesize) + 1
  1123. if (end is not None and firstid <= end <= nextfirstid)
  1124. else None)
  1125. if startv != 0 or endv is not None:
  1126. page_results = page_results[startv:endv]
  1127. res.extend(page_results)
  1128. # A little optimization - if current page is not "full", ie. does
  1129. # not contain page_size videos then we can assume that this page
  1130. # is the last one - there are no more ids on further pages -
  1131. # i.e. no need to query again.
  1132. if len(page_results) + startv < self._pagesize:
  1133. break
  1134. # If we got the whole page, but the next page is not interesting,
  1135. # break out early as well
  1136. if end == nextfirstid:
  1137. break
  1138. return res
  1139. class InAdvancePagedList(PagedList):
  1140. def __init__(self, pagefunc, pagecount, pagesize):
  1141. self._pagefunc = pagefunc
  1142. self._pagecount = pagecount
  1143. self._pagesize = pagesize
  1144. def getslice(self, start=0, end=None):
  1145. res = []
  1146. start_page = start // self._pagesize
  1147. end_page = (
  1148. self._pagecount if end is None else (end // self._pagesize + 1))
  1149. skip_elems = start - start_page * self._pagesize
  1150. only_more = None if end is None else end - start
  1151. for pagenum in range(start_page, end_page):
  1152. page = list(self._pagefunc(pagenum))
  1153. if skip_elems:
  1154. page = page[skip_elems:]
  1155. skip_elems = None
  1156. if only_more is not None:
  1157. if len(page) < only_more:
  1158. only_more -= len(page)
  1159. else:
  1160. page = page[:only_more]
  1161. res.extend(page)
  1162. break
  1163. res.extend(page)
  1164. return res
  1165. def uppercase_escape(s):
  1166. unicode_escape = codecs.getdecoder('unicode_escape')
  1167. return re.sub(
  1168. r'\\U[0-9a-fA-F]{8}',
  1169. lambda m: unicode_escape(m.group(0))[0],
  1170. s)
  1171. def escape_rfc3986(s):
  1172. """Escape non-ASCII characters as suggested by RFC 3986"""
  1173. if sys.version_info < (3, 0) and isinstance(s, unicode):
  1174. s = s.encode('utf-8')
  1175. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1176. def escape_url(url):
  1177. """Escape URL as suggested by RFC 3986"""
  1178. url_parsed = compat_urllib_parse_urlparse(url)
  1179. return url_parsed._replace(
  1180. path=escape_rfc3986(url_parsed.path),
  1181. params=escape_rfc3986(url_parsed.params),
  1182. query=escape_rfc3986(url_parsed.query),
  1183. fragment=escape_rfc3986(url_parsed.fragment)
  1184. ).geturl()
  1185. try:
  1186. struct.pack('!I', 0)
  1187. except TypeError:
  1188. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1189. def struct_pack(spec, *args):
  1190. if isinstance(spec, compat_str):
  1191. spec = spec.encode('ascii')
  1192. return struct.pack(spec, *args)
  1193. def struct_unpack(spec, *args):
  1194. if isinstance(spec, compat_str):
  1195. spec = spec.encode('ascii')
  1196. return struct.unpack(spec, *args)
  1197. else:
  1198. struct_pack = struct.pack
  1199. struct_unpack = struct.unpack
  1200. def read_batch_urls(batch_fd):
  1201. def fixup(url):
  1202. if not isinstance(url, compat_str):
  1203. url = url.decode('utf-8', 'replace')
  1204. BOM_UTF8 = '\xef\xbb\xbf'
  1205. if url.startswith(BOM_UTF8):
  1206. url = url[len(BOM_UTF8):]
  1207. url = url.strip()
  1208. if url.startswith(('#', ';', ']')):
  1209. return False
  1210. return url
  1211. with contextlib.closing(batch_fd) as fd:
  1212. return [url for url in map(fixup, fd) if url]
  1213. def urlencode_postdata(*args, **kargs):
  1214. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1215. try:
  1216. etree_iter = xml.etree.ElementTree.Element.iter
  1217. except AttributeError: # Python <=2.6
  1218. etree_iter = lambda n: n.findall('.//*')
  1219. def parse_xml(s):
  1220. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1221. def doctype(self, name, pubid, system):
  1222. pass # Ignore doctypes
  1223. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1224. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1225. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1226. # Fix up XML parser in Python 2.x
  1227. if sys.version_info < (3, 0):
  1228. for n in etree_iter(tree):
  1229. if n.text is not None:
  1230. if not isinstance(n.text, compat_str):
  1231. n.text = n.text.decode('utf-8')
  1232. return tree
  1233. US_RATINGS = {
  1234. 'G': 0,
  1235. 'PG': 10,
  1236. 'PG-13': 13,
  1237. 'R': 16,
  1238. 'NC': 18,
  1239. }
  1240. def parse_age_limit(s):
  1241. if s is None:
  1242. return None
  1243. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1244. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1245. def strip_jsonp(code):
  1246. return re.sub(
  1247. r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1248. def js_to_json(code):
  1249. def fix_kv(m):
  1250. v = m.group(0)
  1251. if v in ('true', 'false', 'null'):
  1252. return v
  1253. if v.startswith('"'):
  1254. return v
  1255. if v.startswith("'"):
  1256. v = v[1:-1]
  1257. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1258. '\\\\': '\\\\',
  1259. "\\'": "'",
  1260. '"': '\\"',
  1261. }[m.group(0)], v)
  1262. return '"%s"' % v
  1263. res = re.sub(r'''(?x)
  1264. "(?:[^"\\]*(?:\\\\|\\")?)*"|
  1265. '(?:[^'\\]*(?:\\\\|\\')?)*'|
  1266. [a-zA-Z_][a-zA-Z_0-9]*
  1267. ''', fix_kv, code)
  1268. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1269. return res
  1270. def qualities(quality_ids):
  1271. """ Get a numeric quality value out of a list of possible values """
  1272. def q(qid):
  1273. try:
  1274. return quality_ids.index(qid)
  1275. except ValueError:
  1276. return -1
  1277. return q
  1278. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1279. def limit_length(s, length):
  1280. """ Add ellipses to overly long strings """
  1281. if s is None:
  1282. return None
  1283. ELLIPSES = '...'
  1284. if len(s) > length:
  1285. return s[:length - len(ELLIPSES)] + ELLIPSES
  1286. return s
  1287. def version_tuple(v):
  1288. return tuple(int(e) for e in re.split(r'[-.]', v))
  1289. def is_outdated_version(version, limit, assume_new=True):
  1290. if not version:
  1291. return not assume_new
  1292. try:
  1293. return version_tuple(version) < version_tuple(limit)
  1294. except ValueError:
  1295. return not assume_new
  1296. def ytdl_is_updateable():
  1297. """ Returns if youtube-dl can be updated with -U """
  1298. from zipimport import zipimporter
  1299. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1300. def args_to_str(args):
  1301. # Get a short string representation for a subprocess command
  1302. return ' '.join(shlex_quote(a) for a in args)
  1303. def urlhandle_detect_ext(url_handle):
  1304. try:
  1305. url_handle.headers
  1306. getheader = lambda h: url_handle.headers[h]
  1307. except AttributeError: # Python < 3
  1308. getheader = url_handle.info().getheader
  1309. return getheader('Content-Type').split("/")[1]
  1310. def age_restricted(content_limit, age_limit):
  1311. """ Returns True iff the content should be blocked """
  1312. if age_limit is None: # No limit set
  1313. return False
  1314. if content_limit is None:
  1315. return False # Content available for everyone
  1316. return age_limit < content_limit