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.

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