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.

1806 lines
55 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_html_entities,
  36. compat_http_client,
  37. compat_parse_qs,
  38. compat_socket_create_connection,
  39. compat_str,
  40. compat_urllib_error,
  41. compat_urllib_parse,
  42. compat_urllib_parse_urlparse,
  43. compat_urllib_request,
  44. compat_urlparse,
  45. shlex_quote,
  46. )
  47. # This is not clearly defined otherwise
  48. compiled_regex_type = type(re.compile(''))
  49. std_headers = {
  50. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/20.0 (Chrome)',
  51. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  52. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  53. 'Accept-Encoding': 'gzip, deflate',
  54. 'Accept-Language': 'en-us,en;q=0.5',
  55. }
  56. ENGLISH_MONTH_NAMES = [
  57. 'January', 'February', 'March', 'April', 'May', 'June',
  58. 'July', 'August', 'September', 'October', 'November', 'December']
  59. def preferredencoding():
  60. """Get preferred encoding.
  61. Returns the best encoding scheme for the system, based on
  62. locale.getpreferredencoding() and some further tweaks.
  63. """
  64. try:
  65. pref = locale.getpreferredencoding()
  66. 'TEST'.encode(pref)
  67. except:
  68. pref = 'UTF-8'
  69. return pref
  70. def write_json_file(obj, fn):
  71. """ Encode obj as JSON and write it to fn, atomically if possible """
  72. fn = encodeFilename(fn)
  73. if sys.version_info < (3, 0) and sys.platform != 'win32':
  74. encoding = get_filesystem_encoding()
  75. # os.path.basename returns a bytes object, but NamedTemporaryFile
  76. # will fail if the filename contains non ascii characters unless we
  77. # use a unicode object
  78. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  79. # the same for os.path.dirname
  80. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  81. else:
  82. path_basename = os.path.basename
  83. path_dirname = os.path.dirname
  84. args = {
  85. 'suffix': '.tmp',
  86. 'prefix': path_basename(fn) + '.',
  87. 'dir': path_dirname(fn),
  88. 'delete': False,
  89. }
  90. # In Python 2.x, json.dump expects a bytestream.
  91. # In Python 3.x, it writes to a character stream
  92. if sys.version_info < (3, 0):
  93. args['mode'] = 'wb'
  94. else:
  95. args.update({
  96. 'mode': 'w',
  97. 'encoding': 'utf-8',
  98. })
  99. tf = tempfile.NamedTemporaryFile(**args)
  100. try:
  101. with tf:
  102. json.dump(obj, tf)
  103. if sys.platform == 'win32':
  104. # Need to remove existing file on Windows, else os.rename raises
  105. # WindowsError or FileExistsError.
  106. try:
  107. os.unlink(fn)
  108. except OSError:
  109. pass
  110. os.rename(tf.name, fn)
  111. except:
  112. try:
  113. os.remove(tf.name)
  114. except OSError:
  115. pass
  116. raise
  117. if sys.version_info >= (2, 7):
  118. def find_xpath_attr(node, xpath, key, val):
  119. """ Find the xpath xpath[@key=val] """
  120. assert re.match(r'^[a-zA-Z-]+$', key)
  121. assert re.match(r'^[a-zA-Z0-9@\s:._-]*$', val)
  122. expr = xpath + "[@%s='%s']" % (key, val)
  123. return node.find(expr)
  124. else:
  125. def find_xpath_attr(node, xpath, key, val):
  126. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  127. # .//node does not match if a node is a direct child of . !
  128. if isinstance(xpath, compat_str):
  129. xpath = xpath.encode('ascii')
  130. for f in node.findall(xpath):
  131. if f.attrib.get(key) == val:
  132. return f
  133. return None
  134. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  135. # the namespace parameter
  136. def xpath_with_ns(path, ns_map):
  137. components = [c.split(':') for c in path.split('/')]
  138. replaced = []
  139. for c in components:
  140. if len(c) == 1:
  141. replaced.append(c[0])
  142. else:
  143. ns, tag = c
  144. replaced.append('{%s}%s' % (ns_map[ns], tag))
  145. return '/'.join(replaced)
  146. def xpath_text(node, xpath, name=None, fatal=False):
  147. if sys.version_info < (2, 7): # Crazy 2.6
  148. xpath = xpath.encode('ascii')
  149. n = node.find(xpath)
  150. if n is None or n.text is None:
  151. if fatal:
  152. name = xpath if name is None else name
  153. raise ExtractorError('Could not find XML element %s' % name)
  154. else:
  155. return None
  156. return n.text
  157. def get_element_by_id(id, html):
  158. """Return the content of the tag with the specified ID in the passed HTML document"""
  159. return get_element_by_attribute("id", id, html)
  160. def get_element_by_attribute(attribute, value, html):
  161. """Return the content of the tag with the specified attribute in the passed HTML document"""
  162. m = re.search(r'''(?xs)
  163. <([a-zA-Z0-9:._-]+)
  164. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  165. \s+%s=['"]?%s['"]?
  166. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  167. \s*>
  168. (?P<content>.*?)
  169. </\1>
  170. ''' % (re.escape(attribute), re.escape(value)), html)
  171. if not m:
  172. return None
  173. res = m.group('content')
  174. if res.startswith('"') or res.startswith("'"):
  175. res = res[1:-1]
  176. return unescapeHTML(res)
  177. def clean_html(html):
  178. """Clean an HTML snippet into a readable string"""
  179. if html is None: # Convenience for sanitizing descriptions etc.
  180. return html
  181. # Newline vs <br />
  182. html = html.replace('\n', ' ')
  183. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  184. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  185. # Strip html tags
  186. html = re.sub('<.*?>', '', html)
  187. # Replace html entities
  188. html = unescapeHTML(html)
  189. return html.strip()
  190. def sanitize_open(filename, open_mode):
  191. """Try to open the given filename, and slightly tweak it if this fails.
  192. Attempts to open the given filename. If this fails, it tries to change
  193. the filename slightly, step by step, until it's either able to open it
  194. or it fails and raises a final exception, like the standard open()
  195. function.
  196. It returns the tuple (stream, definitive_file_name).
  197. """
  198. try:
  199. if filename == '-':
  200. if sys.platform == 'win32':
  201. import msvcrt
  202. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  203. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  204. stream = open(encodeFilename(filename), open_mode)
  205. return (stream, filename)
  206. except (IOError, OSError) as err:
  207. if err.errno in (errno.EACCES,):
  208. raise
  209. # In case of error, try to remove win32 forbidden chars
  210. alt_filename = sanitize_path(filename)
  211. if alt_filename == filename:
  212. raise
  213. else:
  214. # An exception here should be caught in the caller
  215. stream = open(encodeFilename(alt_filename), open_mode)
  216. return (stream, alt_filename)
  217. def timeconvert(timestr):
  218. """Convert RFC 2822 defined time string into system timestamp"""
  219. timestamp = None
  220. timetuple = email.utils.parsedate_tz(timestr)
  221. if timetuple is not None:
  222. timestamp = email.utils.mktime_tz(timetuple)
  223. return timestamp
  224. def sanitize_filename(s, restricted=False, is_id=False):
  225. """Sanitizes a string so it could be used as part of a filename.
  226. If restricted is set, use a stricter subset of allowed characters.
  227. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  228. """
  229. def replace_insane(char):
  230. if char == '?' or ord(char) < 32 or ord(char) == 127:
  231. return ''
  232. elif char == '"':
  233. return '' if restricted else '\''
  234. elif char == ':':
  235. return '_-' if restricted else ' -'
  236. elif char in '\\/|*<>':
  237. return '_'
  238. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  239. return '_'
  240. if restricted and ord(char) > 127:
  241. return '_'
  242. return char
  243. # Handle timestamps
  244. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  245. result = ''.join(map(replace_insane, s))
  246. if not is_id:
  247. while '__' in result:
  248. result = result.replace('__', '_')
  249. result = result.strip('_')
  250. # Common case of "Foreign band name - English song title"
  251. if restricted and result.startswith('-_'):
  252. result = result[2:]
  253. if result.startswith('-'):
  254. result = '_' + result[len('-'):]
  255. result = result.lstrip('.')
  256. if not result:
  257. result = '_'
  258. return result
  259. def sanitize_path(s):
  260. """Sanitizes and normalizes path on Windows"""
  261. if sys.platform != 'win32':
  262. return s
  263. drive, _ = os.path.splitdrive(s)
  264. unc, _ = os.path.splitunc(s)
  265. unc_or_drive = unc or drive
  266. norm_path = os.path.normpath(remove_start(s, unc_or_drive)).split(os.path.sep)
  267. if unc_or_drive:
  268. norm_path.pop(0)
  269. sanitized_path = [
  270. re.sub('(?:[/<>:"\\|\\\\?\\*]|\.$)', '#', path_part)
  271. for path_part in norm_path]
  272. if unc_or_drive:
  273. sanitized_path.insert(0, unc_or_drive + os.path.sep)
  274. return os.path.join(*sanitized_path)
  275. def orderedSet(iterable):
  276. """ Remove all duplicates from the input iterable """
  277. res = []
  278. for el in iterable:
  279. if el not in res:
  280. res.append(el)
  281. return res
  282. def _htmlentity_transform(entity):
  283. """Transforms an HTML entity to a character."""
  284. # Known non-numeric HTML entity
  285. if entity in compat_html_entities.name2codepoint:
  286. return compat_chr(compat_html_entities.name2codepoint[entity])
  287. mobj = re.match(r'#(x?[0-9]+)', entity)
  288. if mobj is not None:
  289. numstr = mobj.group(1)
  290. if numstr.startswith('x'):
  291. base = 16
  292. numstr = '0%s' % numstr
  293. else:
  294. base = 10
  295. return compat_chr(int(numstr, base))
  296. # Unknown entity in name, return its literal representation
  297. return ('&%s;' % entity)
  298. def unescapeHTML(s):
  299. if s is None:
  300. return None
  301. assert type(s) == compat_str
  302. return re.sub(
  303. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  304. def encodeFilename(s, for_subprocess=False):
  305. """
  306. @param s The name of the file
  307. """
  308. assert type(s) == compat_str
  309. # Python 3 has a Unicode API
  310. if sys.version_info >= (3, 0):
  311. return s
  312. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  313. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  314. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  315. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  316. if not for_subprocess:
  317. return s
  318. else:
  319. # For subprocess calls, encode with locale encoding
  320. # Refer to http://stackoverflow.com/a/9951851/35070
  321. encoding = preferredencoding()
  322. else:
  323. encoding = sys.getfilesystemencoding()
  324. if encoding is None:
  325. encoding = 'utf-8'
  326. return s.encode(encoding, 'ignore')
  327. def encodeArgument(s):
  328. if not isinstance(s, compat_str):
  329. # Legacy code that uses byte strings
  330. # Uncomment the following line after fixing all post processors
  331. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  332. s = s.decode('ascii')
  333. return encodeFilename(s, True)
  334. def decodeOption(optval):
  335. if optval is None:
  336. return optval
  337. if isinstance(optval, bytes):
  338. optval = optval.decode(preferredencoding())
  339. assert isinstance(optval, compat_str)
  340. return optval
  341. def formatSeconds(secs):
  342. if secs > 3600:
  343. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  344. elif secs > 60:
  345. return '%d:%02d' % (secs // 60, secs % 60)
  346. else:
  347. return '%d' % secs
  348. def make_HTTPS_handler(params, **kwargs):
  349. opts_no_check_certificate = params.get('nocheckcertificate', False)
  350. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  351. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  352. if opts_no_check_certificate:
  353. context.check_hostname = False
  354. context.verify_mode = ssl.CERT_NONE
  355. try:
  356. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  357. except TypeError:
  358. # Python 2.7.8
  359. # (create_default_context present but HTTPSHandler has no context=)
  360. pass
  361. if sys.version_info < (3, 2):
  362. return YoutubeDLHTTPSHandler(params, **kwargs)
  363. else: # Python < 3.4
  364. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  365. context.verify_mode = (ssl.CERT_NONE
  366. if opts_no_check_certificate
  367. else ssl.CERT_REQUIRED)
  368. context.set_default_verify_paths()
  369. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  370. class ExtractorError(Exception):
  371. """Error during info extraction."""
  372. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  373. """ tb, if given, is the original traceback (so that it can be printed out).
  374. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  375. """
  376. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  377. expected = True
  378. if video_id is not None:
  379. msg = video_id + ': ' + msg
  380. if cause:
  381. msg += ' (caused by %r)' % cause
  382. if not expected:
  383. if ytdl_is_updateable():
  384. update_cmd = 'type youtube-dl -U to update'
  385. else:
  386. update_cmd = 'see https://yt-dl.org/update on how to update'
  387. msg += '; please report this issue on https://yt-dl.org/bug .'
  388. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  389. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  390. super(ExtractorError, self).__init__(msg)
  391. self.traceback = tb
  392. self.exc_info = sys.exc_info() # preserve original exception
  393. self.cause = cause
  394. self.video_id = video_id
  395. def format_traceback(self):
  396. if self.traceback is None:
  397. return None
  398. return ''.join(traceback.format_tb(self.traceback))
  399. class UnsupportedError(ExtractorError):
  400. def __init__(self, url):
  401. super(UnsupportedError, self).__init__(
  402. 'Unsupported URL: %s' % url, expected=True)
  403. self.url = url
  404. class RegexNotFoundError(ExtractorError):
  405. """Error when a regex didn't match"""
  406. pass
  407. class DownloadError(Exception):
  408. """Download Error exception.
  409. This exception may be thrown by FileDownloader objects if they are not
  410. configured to continue on errors. They will contain the appropriate
  411. error message.
  412. """
  413. def __init__(self, msg, exc_info=None):
  414. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  415. super(DownloadError, self).__init__(msg)
  416. self.exc_info = exc_info
  417. class SameFileError(Exception):
  418. """Same File exception.
  419. This exception will be thrown by FileDownloader objects if they detect
  420. multiple files would have to be downloaded to the same file on disk.
  421. """
  422. pass
  423. class PostProcessingError(Exception):
  424. """Post Processing exception.
  425. This exception may be raised by PostProcessor's .run() method to
  426. indicate an error in the postprocessing task.
  427. """
  428. def __init__(self, msg):
  429. self.msg = msg
  430. class MaxDownloadsReached(Exception):
  431. """ --max-downloads limit has been reached. """
  432. pass
  433. class UnavailableVideoError(Exception):
  434. """Unavailable Format exception.
  435. This exception will be thrown when a video is requested
  436. in a format that is not available for that video.
  437. """
  438. pass
  439. class ContentTooShortError(Exception):
  440. """Content Too Short exception.
  441. This exception may be raised by FileDownloader objects when a file they
  442. download is too small for what the server announced first, indicating
  443. the connection was probably interrupted.
  444. """
  445. # Both in bytes
  446. downloaded = None
  447. expected = None
  448. def __init__(self, downloaded, expected):
  449. self.downloaded = downloaded
  450. self.expected = expected
  451. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  452. hc = http_class(*args, **kwargs)
  453. source_address = ydl_handler._params.get('source_address')
  454. if source_address is not None:
  455. sa = (source_address, 0)
  456. if hasattr(hc, 'source_address'): # Python 2.7+
  457. hc.source_address = sa
  458. else: # Python 2.6
  459. def _hc_connect(self, *args, **kwargs):
  460. sock = compat_socket_create_connection(
  461. (self.host, self.port), self.timeout, sa)
  462. if is_https:
  463. self.sock = ssl.wrap_socket(
  464. sock, self.key_file, self.cert_file,
  465. ssl_version=ssl.PROTOCOL_TLSv1)
  466. else:
  467. self.sock = sock
  468. hc.connect = functools.partial(_hc_connect, hc)
  469. return hc
  470. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  471. """Handler for HTTP requests and responses.
  472. This class, when installed with an OpenerDirector, automatically adds
  473. the standard headers to every HTTP request and handles gzipped and
  474. deflated responses from web servers. If compression is to be avoided in
  475. a particular request, the original request in the program code only has
  476. to include the HTTP header "Youtubedl-No-Compression", which will be
  477. removed before making the real request.
  478. Part of this code was copied from:
  479. http://techknack.net/python-urllib2-handlers/
  480. Andrew Rowls, the author of that code, agreed to release it to the
  481. public domain.
  482. """
  483. def __init__(self, params, *args, **kwargs):
  484. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  485. self._params = params
  486. def http_open(self, req):
  487. return self.do_open(functools.partial(
  488. _create_http_connection, self, compat_http_client.HTTPConnection, False),
  489. req)
  490. @staticmethod
  491. def deflate(data):
  492. try:
  493. return zlib.decompress(data, -zlib.MAX_WBITS)
  494. except zlib.error:
  495. return zlib.decompress(data)
  496. @staticmethod
  497. def addinfourl_wrapper(stream, headers, url, code):
  498. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  499. return compat_urllib_request.addinfourl(stream, headers, url, code)
  500. ret = compat_urllib_request.addinfourl(stream, headers, url)
  501. ret.code = code
  502. return ret
  503. def http_request(self, req):
  504. for h, v in std_headers.items():
  505. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  506. # The dict keys are capitalized because of this bug by urllib
  507. if h.capitalize() not in req.headers:
  508. req.add_header(h, v)
  509. if 'Youtubedl-no-compression' in req.headers:
  510. if 'Accept-encoding' in req.headers:
  511. del req.headers['Accept-encoding']
  512. del req.headers['Youtubedl-no-compression']
  513. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  514. # Python 2.6 is brain-dead when it comes to fragments
  515. req._Request__original = req._Request__original.partition('#')[0]
  516. req._Request__r_type = req._Request__r_type.partition('#')[0]
  517. return req
  518. def http_response(self, req, resp):
  519. old_resp = resp
  520. # gzip
  521. if resp.headers.get('Content-encoding', '') == 'gzip':
  522. content = resp.read()
  523. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  524. try:
  525. uncompressed = io.BytesIO(gz.read())
  526. except IOError as original_ioerror:
  527. # There may be junk add the end of the file
  528. # See http://stackoverflow.com/q/4928560/35070 for details
  529. for i in range(1, 1024):
  530. try:
  531. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  532. uncompressed = io.BytesIO(gz.read())
  533. except IOError:
  534. continue
  535. break
  536. else:
  537. raise original_ioerror
  538. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  539. resp.msg = old_resp.msg
  540. # deflate
  541. if resp.headers.get('Content-encoding', '') == 'deflate':
  542. gz = io.BytesIO(self.deflate(resp.read()))
  543. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  544. resp.msg = old_resp.msg
  545. return resp
  546. https_request = http_request
  547. https_response = http_response
  548. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  549. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  550. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  551. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  552. self._params = params
  553. def https_open(self, req):
  554. kwargs = {}
  555. if hasattr(self, '_context'): # python > 2.6
  556. kwargs['context'] = self._context
  557. if hasattr(self, '_check_hostname'): # python 3.x
  558. kwargs['check_hostname'] = self._check_hostname
  559. return self.do_open(functools.partial(
  560. _create_http_connection, self, self._https_conn_class, True),
  561. req, **kwargs)
  562. def parse_iso8601(date_str, delimiter='T', timezone=None):
  563. """ Return a UNIX timestamp from the given date """
  564. if date_str is None:
  565. return None
  566. if timezone is None:
  567. m = re.search(
  568. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  569. date_str)
  570. if not m:
  571. timezone = datetime.timedelta()
  572. else:
  573. date_str = date_str[:-len(m.group(0))]
  574. if not m.group('sign'):
  575. timezone = datetime.timedelta()
  576. else:
  577. sign = 1 if m.group('sign') == '+' else -1
  578. timezone = datetime.timedelta(
  579. hours=sign * int(m.group('hours')),
  580. minutes=sign * int(m.group('minutes')))
  581. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  582. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  583. return calendar.timegm(dt.timetuple())
  584. def unified_strdate(date_str, day_first=True):
  585. """Return a string with the date in the format YYYYMMDD"""
  586. if date_str is None:
  587. return None
  588. upload_date = None
  589. # Replace commas
  590. date_str = date_str.replace(',', ' ')
  591. # %z (UTC offset) is only supported in python>=3.2
  592. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  593. # Remove AM/PM + timezone
  594. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  595. format_expressions = [
  596. '%d %B %Y',
  597. '%d %b %Y',
  598. '%B %d %Y',
  599. '%b %d %Y',
  600. '%b %dst %Y %I:%M%p',
  601. '%b %dnd %Y %I:%M%p',
  602. '%b %dth %Y %I:%M%p',
  603. '%Y %m %d',
  604. '%Y-%m-%d',
  605. '%Y/%m/%d',
  606. '%Y/%m/%d %H:%M:%S',
  607. '%Y-%m-%d %H:%M:%S',
  608. '%Y-%m-%d %H:%M:%S.%f',
  609. '%d.%m.%Y %H:%M',
  610. '%d.%m.%Y %H.%M',
  611. '%Y-%m-%dT%H:%M:%SZ',
  612. '%Y-%m-%dT%H:%M:%S.%fZ',
  613. '%Y-%m-%dT%H:%M:%S.%f0Z',
  614. '%Y-%m-%dT%H:%M:%S',
  615. '%Y-%m-%dT%H:%M:%S.%f',
  616. '%Y-%m-%dT%H:%M',
  617. ]
  618. if day_first:
  619. format_expressions.extend([
  620. '%d.%m.%Y',
  621. '%d/%m/%Y',
  622. '%d/%m/%y',
  623. '%d/%m/%Y %H:%M:%S',
  624. ])
  625. else:
  626. format_expressions.extend([
  627. '%m.%d.%Y',
  628. '%m/%d/%Y',
  629. '%m/%d/%y',
  630. '%m/%d/%Y %H:%M:%S',
  631. ])
  632. for expression in format_expressions:
  633. try:
  634. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  635. except ValueError:
  636. pass
  637. if upload_date is None:
  638. timetuple = email.utils.parsedate_tz(date_str)
  639. if timetuple:
  640. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  641. return upload_date
  642. def determine_ext(url, default_ext='unknown_video'):
  643. if url is None:
  644. return default_ext
  645. guess = url.partition('?')[0].rpartition('.')[2]
  646. if re.match(r'^[A-Za-z0-9]+$', guess):
  647. return guess
  648. else:
  649. return default_ext
  650. def subtitles_filename(filename, sub_lang, sub_format):
  651. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  652. def date_from_str(date_str):
  653. """
  654. Return a datetime object from a string in the format YYYYMMDD or
  655. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  656. today = datetime.date.today()
  657. if date_str in ('now', 'today'):
  658. return today
  659. if date_str == 'yesterday':
  660. return today - datetime.timedelta(days=1)
  661. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  662. if match is not None:
  663. sign = match.group('sign')
  664. time = int(match.group('time'))
  665. if sign == '-':
  666. time = -time
  667. unit = match.group('unit')
  668. # A bad aproximation?
  669. if unit == 'month':
  670. unit = 'day'
  671. time *= 30
  672. elif unit == 'year':
  673. unit = 'day'
  674. time *= 365
  675. unit += 's'
  676. delta = datetime.timedelta(**{unit: time})
  677. return today + delta
  678. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  679. def hyphenate_date(date_str):
  680. """
  681. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  682. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  683. if match is not None:
  684. return '-'.join(match.groups())
  685. else:
  686. return date_str
  687. class DateRange(object):
  688. """Represents a time interval between two dates"""
  689. def __init__(self, start=None, end=None):
  690. """start and end must be strings in the format accepted by date"""
  691. if start is not None:
  692. self.start = date_from_str(start)
  693. else:
  694. self.start = datetime.datetime.min.date()
  695. if end is not None:
  696. self.end = date_from_str(end)
  697. else:
  698. self.end = datetime.datetime.max.date()
  699. if self.start > self.end:
  700. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  701. @classmethod
  702. def day(cls, day):
  703. """Returns a range that only contains the given day"""
  704. return cls(day, day)
  705. def __contains__(self, date):
  706. """Check if the date is in the range"""
  707. if not isinstance(date, datetime.date):
  708. date = date_from_str(date)
  709. return self.start <= date <= self.end
  710. def __str__(self):
  711. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  712. def platform_name():
  713. """ Returns the platform name as a compat_str """
  714. res = platform.platform()
  715. if isinstance(res, bytes):
  716. res = res.decode(preferredencoding())
  717. assert isinstance(res, compat_str)
  718. return res
  719. def _windows_write_string(s, out):
  720. """ Returns True if the string was written using special methods,
  721. False if it has yet to be written out."""
  722. # Adapted from http://stackoverflow.com/a/3259271/35070
  723. import ctypes
  724. import ctypes.wintypes
  725. WIN_OUTPUT_IDS = {
  726. 1: -11,
  727. 2: -12,
  728. }
  729. try:
  730. fileno = out.fileno()
  731. except AttributeError:
  732. # If the output stream doesn't have a fileno, it's virtual
  733. return False
  734. except io.UnsupportedOperation:
  735. # Some strange Windows pseudo files?
  736. return False
  737. if fileno not in WIN_OUTPUT_IDS:
  738. return False
  739. GetStdHandle = ctypes.WINFUNCTYPE(
  740. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  741. (b"GetStdHandle", ctypes.windll.kernel32))
  742. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  743. WriteConsoleW = ctypes.WINFUNCTYPE(
  744. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  745. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  746. ctypes.wintypes.LPVOID)((b"WriteConsoleW", ctypes.windll.kernel32))
  747. written = ctypes.wintypes.DWORD(0)
  748. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b"GetFileType", ctypes.windll.kernel32))
  749. FILE_TYPE_CHAR = 0x0002
  750. FILE_TYPE_REMOTE = 0x8000
  751. GetConsoleMode = ctypes.WINFUNCTYPE(
  752. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  753. ctypes.POINTER(ctypes.wintypes.DWORD))(
  754. (b"GetConsoleMode", ctypes.windll.kernel32))
  755. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  756. def not_a_console(handle):
  757. if handle == INVALID_HANDLE_VALUE or handle is None:
  758. return True
  759. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  760. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  761. if not_a_console(h):
  762. return False
  763. def next_nonbmp_pos(s):
  764. try:
  765. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  766. except StopIteration:
  767. return len(s)
  768. while s:
  769. count = min(next_nonbmp_pos(s), 1024)
  770. ret = WriteConsoleW(
  771. h, s, count if count else 2, ctypes.byref(written), None)
  772. if ret == 0:
  773. raise OSError('Failed to write string')
  774. if not count: # We just wrote a non-BMP character
  775. assert written.value == 2
  776. s = s[1:]
  777. else:
  778. assert written.value > 0
  779. s = s[written.value:]
  780. return True
  781. def write_string(s, out=None, encoding=None):
  782. if out is None:
  783. out = sys.stderr
  784. assert type(s) == compat_str
  785. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  786. if _windows_write_string(s, out):
  787. return
  788. if ('b' in getattr(out, 'mode', '') or
  789. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  790. byt = s.encode(encoding or preferredencoding(), 'ignore')
  791. out.write(byt)
  792. elif hasattr(out, 'buffer'):
  793. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  794. byt = s.encode(enc, 'ignore')
  795. out.buffer.write(byt)
  796. else:
  797. out.write(s)
  798. out.flush()
  799. def bytes_to_intlist(bs):
  800. if not bs:
  801. return []
  802. if isinstance(bs[0], int): # Python 3
  803. return list(bs)
  804. else:
  805. return [ord(c) for c in bs]
  806. def intlist_to_bytes(xs):
  807. if not xs:
  808. return b''
  809. return struct_pack('%dB' % len(xs), *xs)
  810. # Cross-platform file locking
  811. if sys.platform == 'win32':
  812. import ctypes.wintypes
  813. import msvcrt
  814. class OVERLAPPED(ctypes.Structure):
  815. _fields_ = [
  816. ('Internal', ctypes.wintypes.LPVOID),
  817. ('InternalHigh', ctypes.wintypes.LPVOID),
  818. ('Offset', ctypes.wintypes.DWORD),
  819. ('OffsetHigh', ctypes.wintypes.DWORD),
  820. ('hEvent', ctypes.wintypes.HANDLE),
  821. ]
  822. kernel32 = ctypes.windll.kernel32
  823. LockFileEx = kernel32.LockFileEx
  824. LockFileEx.argtypes = [
  825. ctypes.wintypes.HANDLE, # hFile
  826. ctypes.wintypes.DWORD, # dwFlags
  827. ctypes.wintypes.DWORD, # dwReserved
  828. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  829. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  830. ctypes.POINTER(OVERLAPPED) # Overlapped
  831. ]
  832. LockFileEx.restype = ctypes.wintypes.BOOL
  833. UnlockFileEx = kernel32.UnlockFileEx
  834. UnlockFileEx.argtypes = [
  835. ctypes.wintypes.HANDLE, # hFile
  836. ctypes.wintypes.DWORD, # dwReserved
  837. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  838. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  839. ctypes.POINTER(OVERLAPPED) # Overlapped
  840. ]
  841. UnlockFileEx.restype = ctypes.wintypes.BOOL
  842. whole_low = 0xffffffff
  843. whole_high = 0x7fffffff
  844. def _lock_file(f, exclusive):
  845. overlapped = OVERLAPPED()
  846. overlapped.Offset = 0
  847. overlapped.OffsetHigh = 0
  848. overlapped.hEvent = 0
  849. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  850. handle = msvcrt.get_osfhandle(f.fileno())
  851. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  852. whole_low, whole_high, f._lock_file_overlapped_p):
  853. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  854. def _unlock_file(f):
  855. assert f._lock_file_overlapped_p
  856. handle = msvcrt.get_osfhandle(f.fileno())
  857. if not UnlockFileEx(handle, 0,
  858. whole_low, whole_high, f._lock_file_overlapped_p):
  859. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  860. else:
  861. import fcntl
  862. def _lock_file(f, exclusive):
  863. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  864. def _unlock_file(f):
  865. fcntl.flock(f, fcntl.LOCK_UN)
  866. class locked_file(object):
  867. def __init__(self, filename, mode, encoding=None):
  868. assert mode in ['r', 'a', 'w']
  869. self.f = io.open(filename, mode, encoding=encoding)
  870. self.mode = mode
  871. def __enter__(self):
  872. exclusive = self.mode != 'r'
  873. try:
  874. _lock_file(self.f, exclusive)
  875. except IOError:
  876. self.f.close()
  877. raise
  878. return self
  879. def __exit__(self, etype, value, traceback):
  880. try:
  881. _unlock_file(self.f)
  882. finally:
  883. self.f.close()
  884. def __iter__(self):
  885. return iter(self.f)
  886. def write(self, *args):
  887. return self.f.write(*args)
  888. def read(self, *args):
  889. return self.f.read(*args)
  890. def get_filesystem_encoding():
  891. encoding = sys.getfilesystemencoding()
  892. return encoding if encoding is not None else 'utf-8'
  893. def shell_quote(args):
  894. quoted_args = []
  895. encoding = get_filesystem_encoding()
  896. for a in args:
  897. if isinstance(a, bytes):
  898. # We may get a filename encoded with 'encodeFilename'
  899. a = a.decode(encoding)
  900. quoted_args.append(pipes.quote(a))
  901. return ' '.join(quoted_args)
  902. def takewhile_inclusive(pred, seq):
  903. """ Like itertools.takewhile, but include the latest evaluated element
  904. (the first element so that Not pred(e)) """
  905. for e in seq:
  906. yield e
  907. if not pred(e):
  908. return
  909. def smuggle_url(url, data):
  910. """ Pass additional data in a URL for internal use. """
  911. sdata = compat_urllib_parse.urlencode(
  912. {'__youtubedl_smuggle': json.dumps(data)})
  913. return url + '#' + sdata
  914. def unsmuggle_url(smug_url, default=None):
  915. if '#__youtubedl_smuggle' not in smug_url:
  916. return smug_url, default
  917. url, _, sdata = smug_url.rpartition('#')
  918. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  919. data = json.loads(jsond)
  920. return url, data
  921. def format_bytes(bytes):
  922. if bytes is None:
  923. return 'N/A'
  924. if type(bytes) is str:
  925. bytes = float(bytes)
  926. if bytes == 0.0:
  927. exponent = 0
  928. else:
  929. exponent = int(math.log(bytes, 1024.0))
  930. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  931. converted = float(bytes) / float(1024 ** exponent)
  932. return '%.2f%s' % (converted, suffix)
  933. def parse_filesize(s):
  934. if s is None:
  935. return None
  936. # The lower-case forms are of course incorrect and inofficial,
  937. # but we support those too
  938. _UNIT_TABLE = {
  939. 'B': 1,
  940. 'b': 1,
  941. 'KiB': 1024,
  942. 'KB': 1000,
  943. 'kB': 1024,
  944. 'Kb': 1000,
  945. 'MiB': 1024 ** 2,
  946. 'MB': 1000 ** 2,
  947. 'mB': 1024 ** 2,
  948. 'Mb': 1000 ** 2,
  949. 'GiB': 1024 ** 3,
  950. 'GB': 1000 ** 3,
  951. 'gB': 1024 ** 3,
  952. 'Gb': 1000 ** 3,
  953. 'TiB': 1024 ** 4,
  954. 'TB': 1000 ** 4,
  955. 'tB': 1024 ** 4,
  956. 'Tb': 1000 ** 4,
  957. 'PiB': 1024 ** 5,
  958. 'PB': 1000 ** 5,
  959. 'pB': 1024 ** 5,
  960. 'Pb': 1000 ** 5,
  961. 'EiB': 1024 ** 6,
  962. 'EB': 1000 ** 6,
  963. 'eB': 1024 ** 6,
  964. 'Eb': 1000 ** 6,
  965. 'ZiB': 1024 ** 7,
  966. 'ZB': 1000 ** 7,
  967. 'zB': 1024 ** 7,
  968. 'Zb': 1000 ** 7,
  969. 'YiB': 1024 ** 8,
  970. 'YB': 1000 ** 8,
  971. 'yB': 1024 ** 8,
  972. 'Yb': 1000 ** 8,
  973. }
  974. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  975. m = re.match(
  976. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  977. if not m:
  978. return None
  979. num_str = m.group('num').replace(',', '.')
  980. mult = _UNIT_TABLE[m.group('unit')]
  981. return int(float(num_str) * mult)
  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
  1454. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  1455. def __init__(self, proxies=None):
  1456. # Set default handlers
  1457. for type in ('http', 'https'):
  1458. setattr(self, '%s_open' % type,
  1459. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  1460. meth(r, proxy, type))
  1461. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  1462. def proxy_open(self, req, proxy, type):
  1463. req_proxy = req.headers.get('Ytdl-request-proxy')
  1464. if req_proxy is not None:
  1465. proxy = req_proxy
  1466. del req.headers['Ytdl-request-proxy']
  1467. if proxy == '__noproxy__':
  1468. return None # No Proxy
  1469. return compat_urllib_request.ProxyHandler.proxy_open(
  1470. self, req, proxy, type)