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.

1674 lines
50 KiB

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