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.

1675 lines
50 KiB

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