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.

1758 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', timezone=None):
  545. """ Return a UNIX timestamp from the given date """
  546. if date_str is None:
  547. return None
  548. if timezone is None:
  549. m = re.search(
  550. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  551. date_str)
  552. if not m:
  553. timezone = datetime.timedelta()
  554. else:
  555. date_str = date_str[:-len(m.group(0))]
  556. if not m.group('sign'):
  557. timezone = datetime.timedelta()
  558. else:
  559. sign = 1 if m.group('sign') == '+' else -1
  560. timezone = datetime.timedelta(
  561. hours=sign * int(m.group('hours')),
  562. minutes=sign * int(m.group('minutes')))
  563. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  564. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  565. return calendar.timegm(dt.timetuple())
  566. def unified_strdate(date_str, day_first=True):
  567. """Return a string with the date in the format YYYYMMDD"""
  568. if date_str is None:
  569. return None
  570. upload_date = None
  571. # Replace commas
  572. date_str = date_str.replace(',', ' ')
  573. # %z (UTC offset) is only supported in python>=3.2
  574. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  575. # Remove AM/PM + timezone
  576. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  577. format_expressions = [
  578. '%d %B %Y',
  579. '%d %b %Y',
  580. '%B %d %Y',
  581. '%b %d %Y',
  582. '%b %dst %Y %I:%M%p',
  583. '%b %dnd %Y %I:%M%p',
  584. '%b %dth %Y %I:%M%p',
  585. '%Y %m %d',
  586. '%Y-%m-%d',
  587. '%Y/%m/%d',
  588. '%Y/%m/%d %H:%M:%S',
  589. '%Y-%m-%d %H:%M:%S',
  590. '%Y-%m-%d %H:%M:%S.%f',
  591. '%d.%m.%Y %H:%M',
  592. '%d.%m.%Y %H.%M',
  593. '%Y-%m-%dT%H:%M:%SZ',
  594. '%Y-%m-%dT%H:%M:%S.%fZ',
  595. '%Y-%m-%dT%H:%M:%S.%f0Z',
  596. '%Y-%m-%dT%H:%M:%S',
  597. '%Y-%m-%dT%H:%M:%S.%f',
  598. '%Y-%m-%dT%H:%M',
  599. ]
  600. if day_first:
  601. format_expressions.extend([
  602. '%d.%m.%Y',
  603. '%d/%m/%Y',
  604. '%d/%m/%y',
  605. '%d/%m/%Y %H:%M:%S',
  606. ])
  607. else:
  608. format_expressions.extend([
  609. '%m.%d.%Y',
  610. '%m/%d/%Y',
  611. '%m/%d/%y',
  612. '%m/%d/%Y %H:%M:%S',
  613. ])
  614. for expression in format_expressions:
  615. try:
  616. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  617. except ValueError:
  618. pass
  619. if upload_date is None:
  620. timetuple = email.utils.parsedate_tz(date_str)
  621. if timetuple:
  622. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  623. return upload_date
  624. def determine_ext(url, default_ext='unknown_video'):
  625. if url is None:
  626. return default_ext
  627. guess = url.partition('?')[0].rpartition('.')[2]
  628. if re.match(r'^[A-Za-z0-9]+$', guess):
  629. return guess
  630. else:
  631. return default_ext
  632. def subtitles_filename(filename, sub_lang, sub_format):
  633. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  634. def date_from_str(date_str):
  635. """
  636. Return a datetime object from a string in the format YYYYMMDD or
  637. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  638. today = datetime.date.today()
  639. if date_str in ('now', 'today'):
  640. return today
  641. if date_str == 'yesterday':
  642. return today - datetime.timedelta(days=1)
  643. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  644. if match is not None:
  645. sign = match.group('sign')
  646. time = int(match.group('time'))
  647. if sign == '-':
  648. time = -time
  649. unit = match.group('unit')
  650. # A bad aproximation?
  651. if unit == 'month':
  652. unit = 'day'
  653. time *= 30
  654. elif unit == 'year':
  655. unit = 'day'
  656. time *= 365
  657. unit += 's'
  658. delta = datetime.timedelta(**{unit: time})
  659. return today + delta
  660. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  661. def hyphenate_date(date_str):
  662. """
  663. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  664. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  665. if match is not None:
  666. return '-'.join(match.groups())
  667. else:
  668. return date_str
  669. class DateRange(object):
  670. """Represents a time interval between two dates"""
  671. def __init__(self, start=None, end=None):
  672. """start and end must be strings in the format accepted by date"""
  673. if start is not None:
  674. self.start = date_from_str(start)
  675. else:
  676. self.start = datetime.datetime.min.date()
  677. if end is not None:
  678. self.end = date_from_str(end)
  679. else:
  680. self.end = datetime.datetime.max.date()
  681. if self.start > self.end:
  682. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  683. @classmethod
  684. def day(cls, day):
  685. """Returns a range that only contains the given day"""
  686. return cls(day, day)
  687. def __contains__(self, date):
  688. """Check if the date is in the range"""
  689. if not isinstance(date, datetime.date):
  690. date = date_from_str(date)
  691. return self.start <= date <= self.end
  692. def __str__(self):
  693. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  694. def platform_name():
  695. """ Returns the platform name as a compat_str """
  696. res = platform.platform()
  697. if isinstance(res, bytes):
  698. res = res.decode(preferredencoding())
  699. assert isinstance(res, compat_str)
  700. return res
  701. def _windows_write_string(s, out):
  702. """ Returns True if the string was written using special methods,
  703. False if it has yet to be written out."""
  704. # Adapted from http://stackoverflow.com/a/3259271/35070
  705. import ctypes
  706. import ctypes.wintypes
  707. WIN_OUTPUT_IDS = {
  708. 1: -11,
  709. 2: -12,
  710. }
  711. try:
  712. fileno = out.fileno()
  713. except AttributeError:
  714. # If the output stream doesn't have a fileno, it's virtual
  715. return False
  716. except io.UnsupportedOperation:
  717. # Some strange Windows pseudo files?
  718. return False
  719. if fileno not in WIN_OUTPUT_IDS:
  720. return False
  721. GetStdHandle = ctypes.WINFUNCTYPE(
  722. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  723. (b"GetStdHandle", ctypes.windll.kernel32))
  724. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  725. WriteConsoleW = ctypes.WINFUNCTYPE(
  726. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  727. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  728. ctypes.wintypes.LPVOID)((b"WriteConsoleW", ctypes.windll.kernel32))
  729. written = ctypes.wintypes.DWORD(0)
  730. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b"GetFileType", ctypes.windll.kernel32))
  731. FILE_TYPE_CHAR = 0x0002
  732. FILE_TYPE_REMOTE = 0x8000
  733. GetConsoleMode = ctypes.WINFUNCTYPE(
  734. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  735. ctypes.POINTER(ctypes.wintypes.DWORD))(
  736. (b"GetConsoleMode", ctypes.windll.kernel32))
  737. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  738. def not_a_console(handle):
  739. if handle == INVALID_HANDLE_VALUE or handle is None:
  740. return True
  741. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  742. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  743. if not_a_console(h):
  744. return False
  745. def next_nonbmp_pos(s):
  746. try:
  747. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  748. except StopIteration:
  749. return len(s)
  750. while s:
  751. count = min(next_nonbmp_pos(s), 1024)
  752. ret = WriteConsoleW(
  753. h, s, count if count else 2, ctypes.byref(written), None)
  754. if ret == 0:
  755. raise OSError('Failed to write string')
  756. if not count: # We just wrote a non-BMP character
  757. assert written.value == 2
  758. s = s[1:]
  759. else:
  760. assert written.value > 0
  761. s = s[written.value:]
  762. return True
  763. def write_string(s, out=None, encoding=None):
  764. if out is None:
  765. out = sys.stderr
  766. assert type(s) == compat_str
  767. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  768. if _windows_write_string(s, out):
  769. return
  770. if ('b' in getattr(out, 'mode', '') or
  771. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  772. byt = s.encode(encoding or preferredencoding(), 'ignore')
  773. out.write(byt)
  774. elif hasattr(out, 'buffer'):
  775. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  776. byt = s.encode(enc, 'ignore')
  777. out.buffer.write(byt)
  778. else:
  779. out.write(s)
  780. out.flush()
  781. def bytes_to_intlist(bs):
  782. if not bs:
  783. return []
  784. if isinstance(bs[0], int): # Python 3
  785. return list(bs)
  786. else:
  787. return [ord(c) for c in bs]
  788. def intlist_to_bytes(xs):
  789. if not xs:
  790. return b''
  791. return struct_pack('%dB' % len(xs), *xs)
  792. # Cross-platform file locking
  793. if sys.platform == 'win32':
  794. import ctypes.wintypes
  795. import msvcrt
  796. class OVERLAPPED(ctypes.Structure):
  797. _fields_ = [
  798. ('Internal', ctypes.wintypes.LPVOID),
  799. ('InternalHigh', ctypes.wintypes.LPVOID),
  800. ('Offset', ctypes.wintypes.DWORD),
  801. ('OffsetHigh', ctypes.wintypes.DWORD),
  802. ('hEvent', ctypes.wintypes.HANDLE),
  803. ]
  804. kernel32 = ctypes.windll.kernel32
  805. LockFileEx = kernel32.LockFileEx
  806. LockFileEx.argtypes = [
  807. ctypes.wintypes.HANDLE, # hFile
  808. ctypes.wintypes.DWORD, # dwFlags
  809. ctypes.wintypes.DWORD, # dwReserved
  810. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  811. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  812. ctypes.POINTER(OVERLAPPED) # Overlapped
  813. ]
  814. LockFileEx.restype = ctypes.wintypes.BOOL
  815. UnlockFileEx = kernel32.UnlockFileEx
  816. UnlockFileEx.argtypes = [
  817. ctypes.wintypes.HANDLE, # hFile
  818. ctypes.wintypes.DWORD, # dwReserved
  819. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  820. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  821. ctypes.POINTER(OVERLAPPED) # Overlapped
  822. ]
  823. UnlockFileEx.restype = ctypes.wintypes.BOOL
  824. whole_low = 0xffffffff
  825. whole_high = 0x7fffffff
  826. def _lock_file(f, exclusive):
  827. overlapped = OVERLAPPED()
  828. overlapped.Offset = 0
  829. overlapped.OffsetHigh = 0
  830. overlapped.hEvent = 0
  831. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  832. handle = msvcrt.get_osfhandle(f.fileno())
  833. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  834. whole_low, whole_high, f._lock_file_overlapped_p):
  835. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  836. def _unlock_file(f):
  837. assert f._lock_file_overlapped_p
  838. handle = msvcrt.get_osfhandle(f.fileno())
  839. if not UnlockFileEx(handle, 0,
  840. whole_low, whole_high, f._lock_file_overlapped_p):
  841. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  842. else:
  843. import fcntl
  844. def _lock_file(f, exclusive):
  845. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  846. def _unlock_file(f):
  847. fcntl.flock(f, fcntl.LOCK_UN)
  848. class locked_file(object):
  849. def __init__(self, filename, mode, encoding=None):
  850. assert mode in ['r', 'a', 'w']
  851. self.f = io.open(filename, mode, encoding=encoding)
  852. self.mode = mode
  853. def __enter__(self):
  854. exclusive = self.mode != 'r'
  855. try:
  856. _lock_file(self.f, exclusive)
  857. except IOError:
  858. self.f.close()
  859. raise
  860. return self
  861. def __exit__(self, etype, value, traceback):
  862. try:
  863. _unlock_file(self.f)
  864. finally:
  865. self.f.close()
  866. def __iter__(self):
  867. return iter(self.f)
  868. def write(self, *args):
  869. return self.f.write(*args)
  870. def read(self, *args):
  871. return self.f.read(*args)
  872. def get_filesystem_encoding():
  873. encoding = sys.getfilesystemencoding()
  874. return encoding if encoding is not None else 'utf-8'
  875. def shell_quote(args):
  876. quoted_args = []
  877. encoding = get_filesystem_encoding()
  878. for a in args:
  879. if isinstance(a, bytes):
  880. # We may get a filename encoded with 'encodeFilename'
  881. a = a.decode(encoding)
  882. quoted_args.append(pipes.quote(a))
  883. return ' '.join(quoted_args)
  884. def takewhile_inclusive(pred, seq):
  885. """ Like itertools.takewhile, but include the latest evaluated element
  886. (the first element so that Not pred(e)) """
  887. for e in seq:
  888. yield e
  889. if not pred(e):
  890. return
  891. def smuggle_url(url, data):
  892. """ Pass additional data in a URL for internal use. """
  893. sdata = compat_urllib_parse.urlencode(
  894. {'__youtubedl_smuggle': json.dumps(data)})
  895. return url + '#' + sdata
  896. def unsmuggle_url(smug_url, default=None):
  897. if '#__youtubedl_smuggle' not in smug_url:
  898. return smug_url, default
  899. url, _, sdata = smug_url.rpartition('#')
  900. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  901. data = json.loads(jsond)
  902. return url, data
  903. def format_bytes(bytes):
  904. if bytes is None:
  905. return 'N/A'
  906. if type(bytes) is str:
  907. bytes = float(bytes)
  908. if bytes == 0.0:
  909. exponent = 0
  910. else:
  911. exponent = int(math.log(bytes, 1024.0))
  912. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  913. converted = float(bytes) / float(1024 ** exponent)
  914. return '%.2f%s' % (converted, suffix)
  915. def parse_filesize(s):
  916. if s is None:
  917. return None
  918. # The lower-case forms are of course incorrect and inofficial,
  919. # but we support those too
  920. _UNIT_TABLE = {
  921. 'B': 1,
  922. 'b': 1,
  923. 'KiB': 1024,
  924. 'KB': 1000,
  925. 'kB': 1024,
  926. 'Kb': 1000,
  927. 'MiB': 1024 ** 2,
  928. 'MB': 1000 ** 2,
  929. 'mB': 1024 ** 2,
  930. 'Mb': 1000 ** 2,
  931. 'GiB': 1024 ** 3,
  932. 'GB': 1000 ** 3,
  933. 'gB': 1024 ** 3,
  934. 'Gb': 1000 ** 3,
  935. 'TiB': 1024 ** 4,
  936. 'TB': 1000 ** 4,
  937. 'tB': 1024 ** 4,
  938. 'Tb': 1000 ** 4,
  939. 'PiB': 1024 ** 5,
  940. 'PB': 1000 ** 5,
  941. 'pB': 1024 ** 5,
  942. 'Pb': 1000 ** 5,
  943. 'EiB': 1024 ** 6,
  944. 'EB': 1000 ** 6,
  945. 'eB': 1024 ** 6,
  946. 'Eb': 1000 ** 6,
  947. 'ZiB': 1024 ** 7,
  948. 'ZB': 1000 ** 7,
  949. 'zB': 1024 ** 7,
  950. 'Zb': 1000 ** 7,
  951. 'YiB': 1024 ** 8,
  952. 'YB': 1000 ** 8,
  953. 'yB': 1024 ** 8,
  954. 'Yb': 1000 ** 8,
  955. }
  956. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  957. m = re.match(
  958. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  959. if not m:
  960. return None
  961. num_str = m.group('num').replace(',', '.')
  962. mult = _UNIT_TABLE[m.group('unit')]
  963. return int(float(num_str) * mult)
  964. def get_term_width():
  965. columns = compat_getenv('COLUMNS', None)
  966. if columns:
  967. return int(columns)
  968. try:
  969. sp = subprocess.Popen(
  970. ['stty', 'size'],
  971. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  972. out, err = sp.communicate()
  973. return int(out.split()[1])
  974. except:
  975. pass
  976. return None
  977. def month_by_name(name):
  978. """ Return the number of a month by (locale-independently) English name """
  979. ENGLISH_NAMES = [
  980. 'January', 'February', 'March', 'April', 'May', 'June',
  981. 'July', 'August', 'September', 'October', 'November', 'December']
  982. try:
  983. return ENGLISH_NAMES.index(name) + 1
  984. except ValueError:
  985. return None
  986. def fix_xml_ampersands(xml_str):
  987. """Replace all the '&' by '&amp;' in XML"""
  988. return re.sub(
  989. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  990. '&amp;',
  991. xml_str)
  992. def setproctitle(title):
  993. assert isinstance(title, compat_str)
  994. try:
  995. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  996. except OSError:
  997. return
  998. title_bytes = title.encode('utf-8')
  999. buf = ctypes.create_string_buffer(len(title_bytes))
  1000. buf.value = title_bytes
  1001. try:
  1002. libc.prctl(15, buf, 0, 0, 0)
  1003. except AttributeError:
  1004. return # Strange libc, just skip this
  1005. def remove_start(s, start):
  1006. if s.startswith(start):
  1007. return s[len(start):]
  1008. return s
  1009. def remove_end(s, end):
  1010. if s.endswith(end):
  1011. return s[:-len(end)]
  1012. return s
  1013. def url_basename(url):
  1014. path = compat_urlparse.urlparse(url).path
  1015. return path.strip('/').split('/')[-1]
  1016. class HEADRequest(compat_urllib_request.Request):
  1017. def get_method(self):
  1018. return "HEAD"
  1019. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1020. if get_attr:
  1021. if v is not None:
  1022. v = getattr(v, get_attr, None)
  1023. if v == '':
  1024. v = None
  1025. return default if v is None else (int(v) * invscale // scale)
  1026. def str_or_none(v, default=None):
  1027. return default if v is None else compat_str(v)
  1028. def str_to_int(int_str):
  1029. """ A more relaxed version of int_or_none """
  1030. if int_str is None:
  1031. return None
  1032. int_str = re.sub(r'[,\.\+]', '', int_str)
  1033. return int(int_str)
  1034. def float_or_none(v, scale=1, invscale=1, default=None):
  1035. return default if v is None else (float(v) * invscale / scale)
  1036. def parse_duration(s):
  1037. if not isinstance(s, compat_basestring):
  1038. return None
  1039. s = s.strip()
  1040. m = re.match(
  1041. r'''(?ix)(?:P?T)?
  1042. (?:
  1043. (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*|
  1044. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1045. (?:
  1046. (?:
  1047. (?:(?P<days>[0-9]+)\s*(?:[:d]|days?)\s*)?
  1048. (?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*
  1049. )?
  1050. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1051. )?
  1052. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1053. )$''', s)
  1054. if not m:
  1055. return None
  1056. res = 0
  1057. if m.group('only_mins'):
  1058. return float_or_none(m.group('only_mins'), invscale=60)
  1059. if m.group('only_hours'):
  1060. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1061. if m.group('secs'):
  1062. res += int(m.group('secs'))
  1063. if m.group('mins'):
  1064. res += int(m.group('mins')) * 60
  1065. if m.group('hours'):
  1066. res += int(m.group('hours')) * 60 * 60
  1067. if m.group('days'):
  1068. res += int(m.group('days')) * 24 * 60 * 60
  1069. if m.group('ms'):
  1070. res += float(m.group('ms'))
  1071. return res
  1072. def prepend_extension(filename, ext):
  1073. name, real_ext = os.path.splitext(filename)
  1074. return '{0}.{1}{2}'.format(name, ext, real_ext)
  1075. def check_executable(exe, args=[]):
  1076. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1077. args can be a list of arguments for a short output (like -version) """
  1078. try:
  1079. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1080. except OSError:
  1081. return False
  1082. return exe
  1083. def get_exe_version(exe, args=['--version'],
  1084. version_re=None, unrecognized='present'):
  1085. """ Returns the version of the specified executable,
  1086. or False if the executable is not present """
  1087. try:
  1088. out, _ = subprocess.Popen(
  1089. [exe] + args,
  1090. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1091. except OSError:
  1092. return False
  1093. if isinstance(out, bytes): # Python 2.x
  1094. out = out.decode('ascii', 'ignore')
  1095. return detect_exe_version(out, version_re, unrecognized)
  1096. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1097. assert isinstance(output, compat_str)
  1098. if version_re is None:
  1099. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1100. m = re.search(version_re, output)
  1101. if m:
  1102. return m.group(1)
  1103. else:
  1104. return unrecognized
  1105. class PagedList(object):
  1106. def __len__(self):
  1107. # This is only useful for tests
  1108. return len(self.getslice())
  1109. class OnDemandPagedList(PagedList):
  1110. def __init__(self, pagefunc, pagesize):
  1111. self._pagefunc = pagefunc
  1112. self._pagesize = pagesize
  1113. def getslice(self, start=0, end=None):
  1114. res = []
  1115. for pagenum in itertools.count(start // self._pagesize):
  1116. firstid = pagenum * self._pagesize
  1117. nextfirstid = pagenum * self._pagesize + self._pagesize
  1118. if start >= nextfirstid:
  1119. continue
  1120. page_results = list(self._pagefunc(pagenum))
  1121. startv = (
  1122. start % self._pagesize
  1123. if firstid <= start < nextfirstid
  1124. else 0)
  1125. endv = (
  1126. ((end - 1) % self._pagesize) + 1
  1127. if (end is not None and firstid <= end <= nextfirstid)
  1128. else None)
  1129. if startv != 0 or endv is not None:
  1130. page_results = page_results[startv:endv]
  1131. res.extend(page_results)
  1132. # A little optimization - if current page is not "full", ie. does
  1133. # not contain page_size videos then we can assume that this page
  1134. # is the last one - there are no more ids on further pages -
  1135. # i.e. no need to query again.
  1136. if len(page_results) + startv < self._pagesize:
  1137. break
  1138. # If we got the whole page, but the next page is not interesting,
  1139. # break out early as well
  1140. if end == nextfirstid:
  1141. break
  1142. return res
  1143. class InAdvancePagedList(PagedList):
  1144. def __init__(self, pagefunc, pagecount, pagesize):
  1145. self._pagefunc = pagefunc
  1146. self._pagecount = pagecount
  1147. self._pagesize = pagesize
  1148. def getslice(self, start=0, end=None):
  1149. res = []
  1150. start_page = start // self._pagesize
  1151. end_page = (
  1152. self._pagecount if end is None else (end // self._pagesize + 1))
  1153. skip_elems = start - start_page * self._pagesize
  1154. only_more = None if end is None else end - start
  1155. for pagenum in range(start_page, end_page):
  1156. page = list(self._pagefunc(pagenum))
  1157. if skip_elems:
  1158. page = page[skip_elems:]
  1159. skip_elems = None
  1160. if only_more is not None:
  1161. if len(page) < only_more:
  1162. only_more -= len(page)
  1163. else:
  1164. page = page[:only_more]
  1165. res.extend(page)
  1166. break
  1167. res.extend(page)
  1168. return res
  1169. def uppercase_escape(s):
  1170. unicode_escape = codecs.getdecoder('unicode_escape')
  1171. return re.sub(
  1172. r'\\U[0-9a-fA-F]{8}',
  1173. lambda m: unicode_escape(m.group(0))[0],
  1174. s)
  1175. def escape_rfc3986(s):
  1176. """Escape non-ASCII characters as suggested by RFC 3986"""
  1177. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1178. s = s.encode('utf-8')
  1179. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1180. def escape_url(url):
  1181. """Escape URL as suggested by RFC 3986"""
  1182. url_parsed = compat_urllib_parse_urlparse(url)
  1183. return url_parsed._replace(
  1184. path=escape_rfc3986(url_parsed.path),
  1185. params=escape_rfc3986(url_parsed.params),
  1186. query=escape_rfc3986(url_parsed.query),
  1187. fragment=escape_rfc3986(url_parsed.fragment)
  1188. ).geturl()
  1189. try:
  1190. struct.pack('!I', 0)
  1191. except TypeError:
  1192. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1193. def struct_pack(spec, *args):
  1194. if isinstance(spec, compat_str):
  1195. spec = spec.encode('ascii')
  1196. return struct.pack(spec, *args)
  1197. def struct_unpack(spec, *args):
  1198. if isinstance(spec, compat_str):
  1199. spec = spec.encode('ascii')
  1200. return struct.unpack(spec, *args)
  1201. else:
  1202. struct_pack = struct.pack
  1203. struct_unpack = struct.unpack
  1204. def read_batch_urls(batch_fd):
  1205. def fixup(url):
  1206. if not isinstance(url, compat_str):
  1207. url = url.decode('utf-8', 'replace')
  1208. BOM_UTF8 = '\xef\xbb\xbf'
  1209. if url.startswith(BOM_UTF8):
  1210. url = url[len(BOM_UTF8):]
  1211. url = url.strip()
  1212. if url.startswith(('#', ';', ']')):
  1213. return False
  1214. return url
  1215. with contextlib.closing(batch_fd) as fd:
  1216. return [url for url in map(fixup, fd) if url]
  1217. def urlencode_postdata(*args, **kargs):
  1218. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1219. try:
  1220. etree_iter = xml.etree.ElementTree.Element.iter
  1221. except AttributeError: # Python <=2.6
  1222. etree_iter = lambda n: n.findall('.//*')
  1223. def parse_xml(s):
  1224. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1225. def doctype(self, name, pubid, system):
  1226. pass # Ignore doctypes
  1227. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1228. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1229. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1230. # Fix up XML parser in Python 2.x
  1231. if sys.version_info < (3, 0):
  1232. for n in etree_iter(tree):
  1233. if n.text is not None:
  1234. if not isinstance(n.text, compat_str):
  1235. n.text = n.text.decode('utf-8')
  1236. return tree
  1237. US_RATINGS = {
  1238. 'G': 0,
  1239. 'PG': 10,
  1240. 'PG-13': 13,
  1241. 'R': 16,
  1242. 'NC': 18,
  1243. }
  1244. def parse_age_limit(s):
  1245. if s is None:
  1246. return None
  1247. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1248. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1249. def strip_jsonp(code):
  1250. return re.sub(
  1251. r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1252. def js_to_json(code):
  1253. def fix_kv(m):
  1254. v = m.group(0)
  1255. if v in ('true', 'false', 'null'):
  1256. return v
  1257. if v.startswith('"'):
  1258. return v
  1259. if v.startswith("'"):
  1260. v = v[1:-1]
  1261. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1262. '\\\\': '\\\\',
  1263. "\\'": "'",
  1264. '"': '\\"',
  1265. }[m.group(0)], v)
  1266. return '"%s"' % v
  1267. res = re.sub(r'''(?x)
  1268. "(?:[^"\\]*(?:\\\\|\\")?)*"|
  1269. '(?:[^'\\]*(?:\\\\|\\')?)*'|
  1270. [a-zA-Z_][.a-zA-Z_0-9]*
  1271. ''', fix_kv, code)
  1272. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1273. return res
  1274. def qualities(quality_ids):
  1275. """ Get a numeric quality value out of a list of possible values """
  1276. def q(qid):
  1277. try:
  1278. return quality_ids.index(qid)
  1279. except ValueError:
  1280. return -1
  1281. return q
  1282. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1283. def limit_length(s, length):
  1284. """ Add ellipses to overly long strings """
  1285. if s is None:
  1286. return None
  1287. ELLIPSES = '...'
  1288. if len(s) > length:
  1289. return s[:length - len(ELLIPSES)] + ELLIPSES
  1290. return s
  1291. def version_tuple(v):
  1292. return tuple(int(e) for e in re.split(r'[-.]', v))
  1293. def is_outdated_version(version, limit, assume_new=True):
  1294. if not version:
  1295. return not assume_new
  1296. try:
  1297. return version_tuple(version) < version_tuple(limit)
  1298. except ValueError:
  1299. return not assume_new
  1300. def ytdl_is_updateable():
  1301. """ Returns if youtube-dl can be updated with -U """
  1302. from zipimport import zipimporter
  1303. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1304. def args_to_str(args):
  1305. # Get a short string representation for a subprocess command
  1306. return ' '.join(shlex_quote(a) for a in args)
  1307. def urlhandle_detect_ext(url_handle):
  1308. try:
  1309. url_handle.headers
  1310. getheader = lambda h: url_handle.headers[h]
  1311. except AttributeError: # Python < 3
  1312. getheader = url_handle.info().getheader
  1313. cd = getheader('Content-Disposition')
  1314. if cd:
  1315. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1316. if m:
  1317. e = determine_ext(m.group('filename'), default_ext=None)
  1318. if e:
  1319. return e
  1320. return getheader('Content-Type').split("/")[1]
  1321. def age_restricted(content_limit, age_limit):
  1322. """ Returns True iff the content should be blocked """
  1323. if age_limit is None: # No limit set
  1324. return False
  1325. if content_limit is None:
  1326. return False # Content available for everyone
  1327. return age_limit < content_limit
  1328. def is_html(first_bytes):
  1329. """ Detect whether a file contains HTML by examining its first bytes. """
  1330. BOMS = [
  1331. (b'\xef\xbb\xbf', 'utf-8'),
  1332. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1333. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1334. (b'\xff\xfe', 'utf-16-le'),
  1335. (b'\xfe\xff', 'utf-16-be'),
  1336. ]
  1337. for bom, enc in BOMS:
  1338. if first_bytes.startswith(bom):
  1339. s = first_bytes[len(bom):].decode(enc, 'replace')
  1340. break
  1341. else:
  1342. s = first_bytes.decode('utf-8', 'replace')
  1343. return re.match(r'^\s*<', s)
  1344. def determine_protocol(info_dict):
  1345. protocol = info_dict.get('protocol')
  1346. if protocol is not None:
  1347. return protocol
  1348. url = info_dict['url']
  1349. if url.startswith('rtmp'):
  1350. return 'rtmp'
  1351. elif url.startswith('mms'):
  1352. return 'mms'
  1353. elif url.startswith('rtsp'):
  1354. return 'rtsp'
  1355. ext = determine_ext(url)
  1356. if ext == 'm3u8':
  1357. return 'm3u8'
  1358. elif ext == 'f4m':
  1359. return 'f4m'
  1360. return compat_urllib_parse_urlparse(url).scheme
  1361. def render_table(header_row, data):
  1362. """ Render a list of rows, each as a list of values """
  1363. table = [header_row] + data
  1364. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1365. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1366. return '\n'.join(format_str % tuple(row) for row in table)
  1367. def _match_one(filter_part, dct):
  1368. COMPARISON_OPERATORS = {
  1369. '<': operator.lt,
  1370. '<=': operator.le,
  1371. '>': operator.gt,
  1372. '>=': operator.ge,
  1373. '=': operator.eq,
  1374. '!=': operator.ne,
  1375. }
  1376. operator_rex = re.compile(r'''(?x)\s*
  1377. (?P<key>[a-z_]+)
  1378. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1379. (?:
  1380. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1381. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1382. )
  1383. \s*$
  1384. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1385. m = operator_rex.search(filter_part)
  1386. if m:
  1387. op = COMPARISON_OPERATORS[m.group('op')]
  1388. if m.group('strval') is not None:
  1389. if m.group('op') not in ('=', '!='):
  1390. raise ValueError(
  1391. 'Operator %s does not support string values!' % m.group('op'))
  1392. comparison_value = m.group('strval')
  1393. else:
  1394. try:
  1395. comparison_value = int(m.group('intval'))
  1396. except ValueError:
  1397. comparison_value = parse_filesize(m.group('intval'))
  1398. if comparison_value is None:
  1399. comparison_value = parse_filesize(m.group('intval') + 'B')
  1400. if comparison_value is None:
  1401. raise ValueError(
  1402. 'Invalid integer value %r in filter part %r' % (
  1403. m.group('intval'), filter_part))
  1404. actual_value = dct.get(m.group('key'))
  1405. if actual_value is None:
  1406. return m.group('none_inclusive')
  1407. return op(actual_value, comparison_value)
  1408. UNARY_OPERATORS = {
  1409. '': lambda v: v is not None,
  1410. '!': lambda v: v is None,
  1411. }
  1412. operator_rex = re.compile(r'''(?x)\s*
  1413. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1414. \s*$
  1415. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1416. m = operator_rex.search(filter_part)
  1417. if m:
  1418. op = UNARY_OPERATORS[m.group('op')]
  1419. actual_value = dct.get(m.group('key'))
  1420. return op(actual_value)
  1421. raise ValueError('Invalid filter part %r' % filter_part)
  1422. def match_str(filter_str, dct):
  1423. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1424. return all(
  1425. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1426. def match_filter_func(filter_str):
  1427. def _match_func(info_dict):
  1428. if match_str(filter_str, info_dict):
  1429. return None
  1430. else:
  1431. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1432. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1433. return _match_func