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.

1791 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_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 = os.path.join(
  211. re.sub('[/<>:"\\|\\\\?\\*]', '#', path_part)
  212. for path_part in os.path.split(filename)
  213. )
  214. if alt_filename == filename:
  215. raise
  216. else:
  217. # An exception here should be caught in the caller
  218. stream = open(encodeFilename(filename), open_mode)
  219. return (stream, alt_filename)
  220. def timeconvert(timestr):
  221. """Convert RFC 2822 defined time string into system timestamp"""
  222. timestamp = None
  223. timetuple = email.utils.parsedate_tz(timestr)
  224. if timetuple is not None:
  225. timestamp = email.utils.mktime_tz(timetuple)
  226. return timestamp
  227. def sanitize_filename(s, restricted=False, is_id=False):
  228. """Sanitizes a string so it could be used as part of a filename.
  229. If restricted is set, use a stricter subset of allowed characters.
  230. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  231. """
  232. def replace_insane(char):
  233. if char == '?' or ord(char) < 32 or ord(char) == 127:
  234. return ''
  235. elif char == '"':
  236. return '' if restricted else '\''
  237. elif char == ':':
  238. return '_-' if restricted else ' -'
  239. elif char in '\\/|*<>':
  240. return '_'
  241. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  242. return '_'
  243. if restricted and ord(char) > 127:
  244. return '_'
  245. return char
  246. # Handle timestamps
  247. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  248. result = ''.join(map(replace_insane, s))
  249. if not is_id:
  250. while '__' in result:
  251. result = result.replace('__', '_')
  252. result = result.strip('_')
  253. # Common case of "Foreign band name - English song title"
  254. if restricted and result.startswith('-_'):
  255. result = result[2:]
  256. if result.startswith('-'):
  257. result = '_' + result[len('-'):]
  258. result = result.lstrip('.')
  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 month_by_name(name):
  970. """ Return the number of a month by (locale-independently) English name """
  971. try:
  972. return ENGLISH_MONTH_NAMES.index(name) + 1
  973. except ValueError:
  974. return None
  975. def month_by_abbreviation(abbrev):
  976. """ Return the number of a month by (locale-independently) English
  977. abbreviations """
  978. try:
  979. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  980. except ValueError:
  981. return None
  982. def fix_xml_ampersands(xml_str):
  983. """Replace all the '&' by '&amp;' in XML"""
  984. return re.sub(
  985. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  986. '&amp;',
  987. xml_str)
  988. def setproctitle(title):
  989. assert isinstance(title, compat_str)
  990. try:
  991. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  992. except OSError:
  993. return
  994. title_bytes = title.encode('utf-8')
  995. buf = ctypes.create_string_buffer(len(title_bytes))
  996. buf.value = title_bytes
  997. try:
  998. libc.prctl(15, buf, 0, 0, 0)
  999. except AttributeError:
  1000. return # Strange libc, just skip this
  1001. def remove_start(s, start):
  1002. if s.startswith(start):
  1003. return s[len(start):]
  1004. return s
  1005. def remove_end(s, end):
  1006. if s.endswith(end):
  1007. return s[:-len(end)]
  1008. return s
  1009. def url_basename(url):
  1010. path = compat_urlparse.urlparse(url).path
  1011. return path.strip('/').split('/')[-1]
  1012. class HEADRequest(compat_urllib_request.Request):
  1013. def get_method(self):
  1014. return "HEAD"
  1015. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1016. if get_attr:
  1017. if v is not None:
  1018. v = getattr(v, get_attr, None)
  1019. if v == '':
  1020. v = None
  1021. return default if v is None else (int(v) * invscale // scale)
  1022. def str_or_none(v, default=None):
  1023. return default if v is None else compat_str(v)
  1024. def str_to_int(int_str):
  1025. """ A more relaxed version of int_or_none """
  1026. if int_str is None:
  1027. return None
  1028. int_str = re.sub(r'[,\.\+]', '', int_str)
  1029. return int(int_str)
  1030. def float_or_none(v, scale=1, invscale=1, default=None):
  1031. return default if v is None else (float(v) * invscale / scale)
  1032. def parse_duration(s):
  1033. if not isinstance(s, compat_basestring):
  1034. return None
  1035. s = s.strip()
  1036. m = re.match(
  1037. r'''(?ix)(?:P?T)?
  1038. (?:
  1039. (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*|
  1040. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1041. \s*(?P<hours_reversed>[0-9]+)\s*(?:[:h]|hours?)\s*(?P<mins_reversed>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*|
  1042. (?:
  1043. (?:
  1044. (?:(?P<days>[0-9]+)\s*(?:[:d]|days?)\s*)?
  1045. (?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*
  1046. )?
  1047. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1048. )?
  1049. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1050. )$''', s)
  1051. if not m:
  1052. return None
  1053. res = 0
  1054. if m.group('only_mins'):
  1055. return float_or_none(m.group('only_mins'), invscale=60)
  1056. if m.group('only_hours'):
  1057. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1058. if m.group('secs'):
  1059. res += int(m.group('secs'))
  1060. if m.group('mins_reversed'):
  1061. res += int(m.group('mins_reversed')) * 60
  1062. if m.group('mins'):
  1063. res += int(m.group('mins')) * 60
  1064. if m.group('hours'):
  1065. res += int(m.group('hours')) * 60 * 60
  1066. if m.group('hours_reversed'):
  1067. res += int(m.group('hours_reversed')) * 60 * 60
  1068. if m.group('days'):
  1069. res += int(m.group('days')) * 24 * 60 * 60
  1070. if m.group('ms'):
  1071. res += float(m.group('ms'))
  1072. return res
  1073. def prepend_extension(filename, ext):
  1074. name, real_ext = os.path.splitext(filename)
  1075. return '{0}.{1}{2}'.format(name, ext, real_ext)
  1076. def check_executable(exe, args=[]):
  1077. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1078. args can be a list of arguments for a short output (like -version) """
  1079. try:
  1080. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1081. except OSError:
  1082. return False
  1083. return exe
  1084. def get_exe_version(exe, args=['--version'],
  1085. version_re=None, unrecognized='present'):
  1086. """ Returns the version of the specified executable,
  1087. or False if the executable is not present """
  1088. try:
  1089. out, _ = subprocess.Popen(
  1090. [exe] + args,
  1091. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1092. except OSError:
  1093. return False
  1094. if isinstance(out, bytes): # Python 2.x
  1095. out = out.decode('ascii', 'ignore')
  1096. return detect_exe_version(out, version_re, unrecognized)
  1097. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1098. assert isinstance(output, compat_str)
  1099. if version_re is None:
  1100. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1101. m = re.search(version_re, output)
  1102. if m:
  1103. return m.group(1)
  1104. else:
  1105. return unrecognized
  1106. class PagedList(object):
  1107. def __len__(self):
  1108. # This is only useful for tests
  1109. return len(self.getslice())
  1110. class OnDemandPagedList(PagedList):
  1111. def __init__(self, pagefunc, pagesize):
  1112. self._pagefunc = pagefunc
  1113. self._pagesize = pagesize
  1114. def getslice(self, start=0, end=None):
  1115. res = []
  1116. for pagenum in itertools.count(start // self._pagesize):
  1117. firstid = pagenum * self._pagesize
  1118. nextfirstid = pagenum * self._pagesize + self._pagesize
  1119. if start >= nextfirstid:
  1120. continue
  1121. page_results = list(self._pagefunc(pagenum))
  1122. startv = (
  1123. start % self._pagesize
  1124. if firstid <= start < nextfirstid
  1125. else 0)
  1126. endv = (
  1127. ((end - 1) % self._pagesize) + 1
  1128. if (end is not None and firstid <= end <= nextfirstid)
  1129. else None)
  1130. if startv != 0 or endv is not None:
  1131. page_results = page_results[startv:endv]
  1132. res.extend(page_results)
  1133. # A little optimization - if current page is not "full", ie. does
  1134. # not contain page_size videos then we can assume that this page
  1135. # is the last one - there are no more ids on further pages -
  1136. # i.e. no need to query again.
  1137. if len(page_results) + startv < self._pagesize:
  1138. break
  1139. # If we got the whole page, but the next page is not interesting,
  1140. # break out early as well
  1141. if end == nextfirstid:
  1142. break
  1143. return res
  1144. class InAdvancePagedList(PagedList):
  1145. def __init__(self, pagefunc, pagecount, pagesize):
  1146. self._pagefunc = pagefunc
  1147. self._pagecount = pagecount
  1148. self._pagesize = pagesize
  1149. def getslice(self, start=0, end=None):
  1150. res = []
  1151. start_page = start // self._pagesize
  1152. end_page = (
  1153. self._pagecount if end is None else (end // self._pagesize + 1))
  1154. skip_elems = start - start_page * self._pagesize
  1155. only_more = None if end is None else end - start
  1156. for pagenum in range(start_page, end_page):
  1157. page = list(self._pagefunc(pagenum))
  1158. if skip_elems:
  1159. page = page[skip_elems:]
  1160. skip_elems = None
  1161. if only_more is not None:
  1162. if len(page) < only_more:
  1163. only_more -= len(page)
  1164. else:
  1165. page = page[:only_more]
  1166. res.extend(page)
  1167. break
  1168. res.extend(page)
  1169. return res
  1170. def uppercase_escape(s):
  1171. unicode_escape = codecs.getdecoder('unicode_escape')
  1172. return re.sub(
  1173. r'\\U[0-9a-fA-F]{8}',
  1174. lambda m: unicode_escape(m.group(0))[0],
  1175. s)
  1176. def escape_rfc3986(s):
  1177. """Escape non-ASCII characters as suggested by RFC 3986"""
  1178. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1179. s = s.encode('utf-8')
  1180. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1181. def escape_url(url):
  1182. """Escape URL as suggested by RFC 3986"""
  1183. url_parsed = compat_urllib_parse_urlparse(url)
  1184. return url_parsed._replace(
  1185. path=escape_rfc3986(url_parsed.path),
  1186. params=escape_rfc3986(url_parsed.params),
  1187. query=escape_rfc3986(url_parsed.query),
  1188. fragment=escape_rfc3986(url_parsed.fragment)
  1189. ).geturl()
  1190. try:
  1191. struct.pack('!I', 0)
  1192. except TypeError:
  1193. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1194. def struct_pack(spec, *args):
  1195. if isinstance(spec, compat_str):
  1196. spec = spec.encode('ascii')
  1197. return struct.pack(spec, *args)
  1198. def struct_unpack(spec, *args):
  1199. if isinstance(spec, compat_str):
  1200. spec = spec.encode('ascii')
  1201. return struct.unpack(spec, *args)
  1202. else:
  1203. struct_pack = struct.pack
  1204. struct_unpack = struct.unpack
  1205. def read_batch_urls(batch_fd):
  1206. def fixup(url):
  1207. if not isinstance(url, compat_str):
  1208. url = url.decode('utf-8', 'replace')
  1209. BOM_UTF8 = '\xef\xbb\xbf'
  1210. if url.startswith(BOM_UTF8):
  1211. url = url[len(BOM_UTF8):]
  1212. url = url.strip()
  1213. if url.startswith(('#', ';', ']')):
  1214. return False
  1215. return url
  1216. with contextlib.closing(batch_fd) as fd:
  1217. return [url for url in map(fixup, fd) if url]
  1218. def urlencode_postdata(*args, **kargs):
  1219. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1220. try:
  1221. etree_iter = xml.etree.ElementTree.Element.iter
  1222. except AttributeError: # Python <=2.6
  1223. etree_iter = lambda n: n.findall('.//*')
  1224. def parse_xml(s):
  1225. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1226. def doctype(self, name, pubid, system):
  1227. pass # Ignore doctypes
  1228. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1229. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1230. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1231. # Fix up XML parser in Python 2.x
  1232. if sys.version_info < (3, 0):
  1233. for n in etree_iter(tree):
  1234. if n.text is not None:
  1235. if not isinstance(n.text, compat_str):
  1236. n.text = n.text.decode('utf-8')
  1237. return tree
  1238. US_RATINGS = {
  1239. 'G': 0,
  1240. 'PG': 10,
  1241. 'PG-13': 13,
  1242. 'R': 16,
  1243. 'NC': 18,
  1244. }
  1245. def parse_age_limit(s):
  1246. if s is None:
  1247. return None
  1248. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1249. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1250. def strip_jsonp(code):
  1251. return re.sub(
  1252. r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1253. def js_to_json(code):
  1254. def fix_kv(m):
  1255. v = m.group(0)
  1256. if v in ('true', 'false', 'null'):
  1257. return v
  1258. if v.startswith('"'):
  1259. return v
  1260. if v.startswith("'"):
  1261. v = v[1:-1]
  1262. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1263. '\\\\': '\\\\',
  1264. "\\'": "'",
  1265. '"': '\\"',
  1266. }[m.group(0)], v)
  1267. return '"%s"' % v
  1268. res = re.sub(r'''(?x)
  1269. "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"|
  1270. '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'|
  1271. [a-zA-Z_][.a-zA-Z_0-9]*
  1272. ''', fix_kv, code)
  1273. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1274. return res
  1275. def qualities(quality_ids):
  1276. """ Get a numeric quality value out of a list of possible values """
  1277. def q(qid):
  1278. try:
  1279. return quality_ids.index(qid)
  1280. except ValueError:
  1281. return -1
  1282. return q
  1283. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1284. def limit_length(s, length):
  1285. """ Add ellipses to overly long strings """
  1286. if s is None:
  1287. return None
  1288. ELLIPSES = '...'
  1289. if len(s) > length:
  1290. return s[:length - len(ELLIPSES)] + ELLIPSES
  1291. return s
  1292. def version_tuple(v):
  1293. return tuple(int(e) for e in re.split(r'[-.]', v))
  1294. def is_outdated_version(version, limit, assume_new=True):
  1295. if not version:
  1296. return not assume_new
  1297. try:
  1298. return version_tuple(version) < version_tuple(limit)
  1299. except ValueError:
  1300. return not assume_new
  1301. def ytdl_is_updateable():
  1302. """ Returns if youtube-dl can be updated with -U """
  1303. from zipimport import zipimporter
  1304. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1305. def args_to_str(args):
  1306. # Get a short string representation for a subprocess command
  1307. return ' '.join(shlex_quote(a) for a in args)
  1308. def mimetype2ext(mt):
  1309. _, _, res = mt.rpartition('/')
  1310. return {
  1311. 'x-ms-wmv': 'wmv',
  1312. 'x-mp4-fragmented': 'mp4',
  1313. }.get(res, res)
  1314. def urlhandle_detect_ext(url_handle):
  1315. try:
  1316. url_handle.headers
  1317. getheader = lambda h: url_handle.headers[h]
  1318. except AttributeError: # Python < 3
  1319. getheader = url_handle.info().getheader
  1320. cd = getheader('Content-Disposition')
  1321. if cd:
  1322. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1323. if m:
  1324. e = determine_ext(m.group('filename'), default_ext=None)
  1325. if e:
  1326. return e
  1327. return mimetype2ext(getheader('Content-Type'))
  1328. def age_restricted(content_limit, age_limit):
  1329. """ Returns True iff the content should be blocked """
  1330. if age_limit is None: # No limit set
  1331. return False
  1332. if content_limit is None:
  1333. return False # Content available for everyone
  1334. return age_limit < content_limit
  1335. def is_html(first_bytes):
  1336. """ Detect whether a file contains HTML by examining its first bytes. """
  1337. BOMS = [
  1338. (b'\xef\xbb\xbf', 'utf-8'),
  1339. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1340. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1341. (b'\xff\xfe', 'utf-16-le'),
  1342. (b'\xfe\xff', 'utf-16-be'),
  1343. ]
  1344. for bom, enc in BOMS:
  1345. if first_bytes.startswith(bom):
  1346. s = first_bytes[len(bom):].decode(enc, 'replace')
  1347. break
  1348. else:
  1349. s = first_bytes.decode('utf-8', 'replace')
  1350. return re.match(r'^\s*<', s)
  1351. def determine_protocol(info_dict):
  1352. protocol = info_dict.get('protocol')
  1353. if protocol is not None:
  1354. return protocol
  1355. url = info_dict['url']
  1356. if url.startswith('rtmp'):
  1357. return 'rtmp'
  1358. elif url.startswith('mms'):
  1359. return 'mms'
  1360. elif url.startswith('rtsp'):
  1361. return 'rtsp'
  1362. ext = determine_ext(url)
  1363. if ext == 'm3u8':
  1364. return 'm3u8'
  1365. elif ext == 'f4m':
  1366. return 'f4m'
  1367. return compat_urllib_parse_urlparse(url).scheme
  1368. def render_table(header_row, data):
  1369. """ Render a list of rows, each as a list of values """
  1370. table = [header_row] + data
  1371. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1372. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1373. return '\n'.join(format_str % tuple(row) for row in table)
  1374. def _match_one(filter_part, dct):
  1375. COMPARISON_OPERATORS = {
  1376. '<': operator.lt,
  1377. '<=': operator.le,
  1378. '>': operator.gt,
  1379. '>=': operator.ge,
  1380. '=': operator.eq,
  1381. '!=': operator.ne,
  1382. }
  1383. operator_rex = re.compile(r'''(?x)\s*
  1384. (?P<key>[a-z_]+)
  1385. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1386. (?:
  1387. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1388. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1389. )
  1390. \s*$
  1391. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1392. m = operator_rex.search(filter_part)
  1393. if m:
  1394. op = COMPARISON_OPERATORS[m.group('op')]
  1395. if m.group('strval') is not None:
  1396. if m.group('op') not in ('=', '!='):
  1397. raise ValueError(
  1398. 'Operator %s does not support string values!' % m.group('op'))
  1399. comparison_value = m.group('strval')
  1400. else:
  1401. try:
  1402. comparison_value = int(m.group('intval'))
  1403. except ValueError:
  1404. comparison_value = parse_filesize(m.group('intval'))
  1405. if comparison_value is None:
  1406. comparison_value = parse_filesize(m.group('intval') + 'B')
  1407. if comparison_value is None:
  1408. raise ValueError(
  1409. 'Invalid integer value %r in filter part %r' % (
  1410. m.group('intval'), filter_part))
  1411. actual_value = dct.get(m.group('key'))
  1412. if actual_value is None:
  1413. return m.group('none_inclusive')
  1414. return op(actual_value, comparison_value)
  1415. UNARY_OPERATORS = {
  1416. '': lambda v: v is not None,
  1417. '!': lambda v: v is None,
  1418. }
  1419. operator_rex = re.compile(r'''(?x)\s*
  1420. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1421. \s*$
  1422. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1423. m = operator_rex.search(filter_part)
  1424. if m:
  1425. op = UNARY_OPERATORS[m.group('op')]
  1426. actual_value = dct.get(m.group('key'))
  1427. return op(actual_value)
  1428. raise ValueError('Invalid filter part %r' % filter_part)
  1429. def match_str(filter_str, dct):
  1430. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1431. return all(
  1432. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1433. def match_filter_func(filter_str):
  1434. def _match_func(info_dict):
  1435. if match_str(filter_str, info_dict):
  1436. return None
  1437. else:
  1438. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1439. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1440. return _match_func
  1441. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  1442. def __init__(self, proxies=None):
  1443. # Set default handlers
  1444. for type in ('http', 'https'):
  1445. setattr(self, '%s_open' % type,
  1446. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  1447. meth(r, proxy, type))
  1448. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  1449. def proxy_open(self, req, proxy, type):
  1450. req_proxy = req.headers.get('Ytdl-request-proxy')
  1451. if req_proxy is not None:
  1452. proxy = req_proxy
  1453. del req.headers['Ytdl-request-proxy']
  1454. if proxy == '__noproxy__':
  1455. return None # No Proxy
  1456. return compat_urllib_request.ProxyHandler.proxy_open(
  1457. self, req, proxy, type)