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.

1786 lines
54 KiB

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