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.

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