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.

691 lines
23 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import errno
  4. import gzip
  5. import io
  6. import json
  7. import locale
  8. import os
  9. import re
  10. import sys
  11. import traceback
  12. import zlib
  13. import email.utils
  14. import socket
  15. import datetime
  16. try:
  17. import urllib.request as compat_urllib_request
  18. except ImportError: # Python 2
  19. import urllib2 as compat_urllib_request
  20. try:
  21. import urllib.error as compat_urllib_error
  22. except ImportError: # Python 2
  23. import urllib2 as compat_urllib_error
  24. try:
  25. import urllib.parse as compat_urllib_parse
  26. except ImportError: # Python 2
  27. import urllib as compat_urllib_parse
  28. try:
  29. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  30. except ImportError: # Python 2
  31. from urlparse import urlparse as compat_urllib_parse_urlparse
  32. try:
  33. import http.cookiejar as compat_cookiejar
  34. except ImportError: # Python 2
  35. import cookielib as compat_cookiejar
  36. try:
  37. import html.entities as compat_html_entities
  38. except ImportError: # Python 2
  39. import htmlentitydefs as compat_html_entities
  40. try:
  41. import html.parser as compat_html_parser
  42. except ImportError: # Python 2
  43. import HTMLParser as compat_html_parser
  44. try:
  45. import http.client as compat_http_client
  46. except ImportError: # Python 2
  47. import httplib as compat_http_client
  48. try:
  49. from subprocess import DEVNULL
  50. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  51. except ImportError:
  52. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  53. try:
  54. from urllib.parse import parse_qs as compat_parse_qs
  55. except ImportError: # Python 2
  56. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  57. # Python 2's version is apparently totally broken
  58. def _unquote(string, encoding='utf-8', errors='replace'):
  59. if string == '':
  60. return string
  61. res = string.split('%')
  62. if len(res) == 1:
  63. return string
  64. if encoding is None:
  65. encoding = 'utf-8'
  66. if errors is None:
  67. errors = 'replace'
  68. # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
  69. pct_sequence = b''
  70. string = res[0]
  71. for item in res[1:]:
  72. try:
  73. if not item:
  74. raise ValueError
  75. pct_sequence += item[:2].decode('hex')
  76. rest = item[2:]
  77. if not rest:
  78. # This segment was just a single percent-encoded character.
  79. # May be part of a sequence of code units, so delay decoding.
  80. # (Stored in pct_sequence).
  81. continue
  82. except ValueError:
  83. rest = '%' + item
  84. # Encountered non-percent-encoded characters. Flush the current
  85. # pct_sequence.
  86. string += pct_sequence.decode(encoding, errors) + rest
  87. pct_sequence = b''
  88. if pct_sequence:
  89. # Flush the final pct_sequence
  90. string += pct_sequence.decode(encoding, errors)
  91. return string
  92. def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  93. encoding='utf-8', errors='replace'):
  94. qs, _coerce_result = qs, unicode
  95. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  96. r = []
  97. for name_value in pairs:
  98. if not name_value and not strict_parsing:
  99. continue
  100. nv = name_value.split('=', 1)
  101. if len(nv) != 2:
  102. if strict_parsing:
  103. raise ValueError("bad query field: %r" % (name_value,))
  104. # Handle case of a control-name with no equal sign
  105. if keep_blank_values:
  106. nv.append('')
  107. else:
  108. continue
  109. if len(nv[1]) or keep_blank_values:
  110. name = nv[0].replace('+', ' ')
  111. name = _unquote(name, encoding=encoding, errors=errors)
  112. name = _coerce_result(name)
  113. value = nv[1].replace('+', ' ')
  114. value = _unquote(value, encoding=encoding, errors=errors)
  115. value = _coerce_result(value)
  116. r.append((name, value))
  117. return r
  118. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  119. encoding='utf-8', errors='replace'):
  120. parsed_result = {}
  121. pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
  122. encoding=encoding, errors=errors)
  123. for name, value in pairs:
  124. if name in parsed_result:
  125. parsed_result[name].append(value)
  126. else:
  127. parsed_result[name] = [value]
  128. return parsed_result
  129. try:
  130. compat_str = unicode # Python 2
  131. except NameError:
  132. compat_str = str
  133. try:
  134. compat_chr = unichr # Python 2
  135. except NameError:
  136. compat_chr = chr
  137. def compat_ord(c):
  138. if type(c) is int: return c
  139. else: return ord(c)
  140. # This is not clearly defined otherwise
  141. compiled_regex_type = type(re.compile(''))
  142. std_headers = {
  143. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',
  144. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  145. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  146. 'Accept-Encoding': 'gzip, deflate',
  147. 'Accept-Language': 'en-us,en;q=0.5',
  148. }
  149. def preferredencoding():
  150. """Get preferred encoding.
  151. Returns the best encoding scheme for the system, based on
  152. locale.getpreferredencoding() and some further tweaks.
  153. """
  154. try:
  155. pref = locale.getpreferredencoding()
  156. u'TEST'.encode(pref)
  157. except:
  158. pref = 'UTF-8'
  159. return pref
  160. if sys.version_info < (3,0):
  161. def compat_print(s):
  162. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  163. else:
  164. def compat_print(s):
  165. assert type(s) == type(u'')
  166. print(s)
  167. # In Python 2.x, json.dump expects a bytestream.
  168. # In Python 3.x, it writes to a character stream
  169. if sys.version_info < (3,0):
  170. def write_json_file(obj, fn):
  171. with open(fn, 'wb') as f:
  172. json.dump(obj, f)
  173. else:
  174. def write_json_file(obj, fn):
  175. with open(fn, 'w', encoding='utf-8') as f:
  176. json.dump(obj, f)
  177. def htmlentity_transform(matchobj):
  178. """Transforms an HTML entity to a character.
  179. This function receives a match object and is intended to be used with
  180. the re.sub() function.
  181. """
  182. entity = matchobj.group(1)
  183. # Known non-numeric HTML entity
  184. if entity in compat_html_entities.name2codepoint:
  185. return compat_chr(compat_html_entities.name2codepoint[entity])
  186. mobj = re.match(u'(?u)#(x?\\d+)', entity)
  187. if mobj is not None:
  188. numstr = mobj.group(1)
  189. if numstr.startswith(u'x'):
  190. base = 16
  191. numstr = u'0%s' % numstr
  192. else:
  193. base = 10
  194. return compat_chr(int(numstr, base))
  195. # Unknown entity in name, return its literal representation
  196. return (u'&%s;' % entity)
  197. compat_html_parser.locatestarttagend = re.compile(r"""<[a-zA-Z][-.a-zA-Z0-9:_]*(?:\s+(?:(?<=['"\s])[^\s/>][^\s/=>]*(?:\s*=+\s*(?:'[^']*'|"[^"]*"|(?!['"])[^>\s]*))?\s*)*)?\s*""", re.VERBOSE) # backport bugfix
  198. class AttrParser(compat_html_parser.HTMLParser):
  199. """Modified HTMLParser that isolates a tag with the specified attribute"""
  200. def __init__(self, attribute, value):
  201. self.attribute = attribute
  202. self.value = value
  203. self.result = None
  204. self.started = False
  205. self.depth = {}
  206. self.html = None
  207. self.watch_startpos = False
  208. self.error_count = 0
  209. compat_html_parser.HTMLParser.__init__(self)
  210. def error(self, message):
  211. if self.error_count > 10 or self.started:
  212. raise compat_html_parser.HTMLParseError(message, self.getpos())
  213. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  214. self.error_count += 1
  215. self.goahead(1)
  216. def loads(self, html):
  217. self.html = html
  218. self.feed(html)
  219. self.close()
  220. def handle_starttag(self, tag, attrs):
  221. attrs = dict(attrs)
  222. if self.started:
  223. self.find_startpos(None)
  224. if self.attribute in attrs and attrs[self.attribute] == self.value:
  225. self.result = [tag]
  226. self.started = True
  227. self.watch_startpos = True
  228. if self.started:
  229. if not tag in self.depth: self.depth[tag] = 0
  230. self.depth[tag] += 1
  231. def handle_endtag(self, tag):
  232. if self.started:
  233. if tag in self.depth: self.depth[tag] -= 1
  234. if self.depth[self.result[0]] == 0:
  235. self.started = False
  236. self.result.append(self.getpos())
  237. def find_startpos(self, x):
  238. """Needed to put the start position of the result (self.result[1])
  239. after the opening tag with the requested id"""
  240. if self.watch_startpos:
  241. self.watch_startpos = False
  242. self.result.append(self.getpos())
  243. handle_entityref = handle_charref = handle_data = handle_comment = \
  244. handle_decl = handle_pi = unknown_decl = find_startpos
  245. def get_result(self):
  246. if self.result is None:
  247. return None
  248. if len(self.result) != 3:
  249. return None
  250. lines = self.html.split('\n')
  251. lines = lines[self.result[1][0]-1:self.result[2][0]]
  252. lines[0] = lines[0][self.result[1][1]:]
  253. if len(lines) == 1:
  254. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  255. lines[-1] = lines[-1][:self.result[2][1]]
  256. return '\n'.join(lines).strip()
  257. # Hack for https://github.com/rg3/youtube-dl/issues/662
  258. if sys.version_info < (2, 7, 3):
  259. AttrParser.parse_endtag = (lambda self, i:
  260. i + len("</scr'+'ipt>")
  261. if self.rawdata[i:].startswith("</scr'+'ipt>")
  262. else compat_html_parser.HTMLParser.parse_endtag(self, i))
  263. def get_element_by_id(id, html):
  264. """Return the content of the tag with the specified ID in the passed HTML document"""
  265. return get_element_by_attribute("id", id, html)
  266. def get_element_by_attribute(attribute, value, html):
  267. """Return the content of the tag with the specified attribute in the passed HTML document"""
  268. parser = AttrParser(attribute, value)
  269. try:
  270. parser.loads(html)
  271. except compat_html_parser.HTMLParseError:
  272. pass
  273. return parser.get_result()
  274. def clean_html(html):
  275. """Clean an HTML snippet into a readable string"""
  276. # Newline vs <br />
  277. html = html.replace('\n', ' ')
  278. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  279. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  280. # Strip html tags
  281. html = re.sub('<.*?>', '', html)
  282. # Replace html entities
  283. html = unescapeHTML(html)
  284. return html.strip()
  285. def sanitize_open(filename, open_mode):
  286. """Try to open the given filename, and slightly tweak it if this fails.
  287. Attempts to open the given filename. If this fails, it tries to change
  288. the filename slightly, step by step, until it's either able to open it
  289. or it fails and raises a final exception, like the standard open()
  290. function.
  291. It returns the tuple (stream, definitive_file_name).
  292. """
  293. try:
  294. if filename == u'-':
  295. if sys.platform == 'win32':
  296. import msvcrt
  297. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  298. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  299. stream = open(encodeFilename(filename), open_mode)
  300. return (stream, filename)
  301. except (IOError, OSError) as err:
  302. if err.errno in (errno.EACCES,):
  303. raise
  304. # In case of error, try to remove win32 forbidden chars
  305. alt_filename = os.path.join(
  306. re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', path_part)
  307. for path_part in os.path.split(filename)
  308. )
  309. if alt_filename == filename:
  310. raise
  311. else:
  312. # An exception here should be caught in the caller
  313. stream = open(encodeFilename(filename), open_mode)
  314. return (stream, alt_filename)
  315. def timeconvert(timestr):
  316. """Convert RFC 2822 defined time string into system timestamp"""
  317. timestamp = None
  318. timetuple = email.utils.parsedate_tz(timestr)
  319. if timetuple is not None:
  320. timestamp = email.utils.mktime_tz(timetuple)
  321. return timestamp
  322. def sanitize_filename(s, restricted=False, is_id=False):
  323. """Sanitizes a string so it could be used as part of a filename.
  324. If restricted is set, use a stricter subset of allowed characters.
  325. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  326. """
  327. def replace_insane(char):
  328. if char == '?' or ord(char) < 32 or ord(char) == 127:
  329. return ''
  330. elif char == '"':
  331. return '' if restricted else '\''
  332. elif char == ':':
  333. return '_-' if restricted else ' -'
  334. elif char in '\\/|*<>':
  335. return '_'
  336. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  337. return '_'
  338. if restricted and ord(char) > 127:
  339. return '_'
  340. return char
  341. result = u''.join(map(replace_insane, s))
  342. if not is_id:
  343. while '__' in result:
  344. result = result.replace('__', '_')
  345. result = result.strip('_')
  346. # Common case of "Foreign band name - English song title"
  347. if restricted and result.startswith('-_'):
  348. result = result[2:]
  349. if not result:
  350. result = '_'
  351. return result
  352. def orderedSet(iterable):
  353. """ Remove all duplicates from the input iterable """
  354. res = []
  355. for el in iterable:
  356. if el not in res:
  357. res.append(el)
  358. return res
  359. def unescapeHTML(s):
  360. """
  361. @param s a string
  362. """
  363. assert type(s) == type(u'')
  364. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  365. return result
  366. def encodeFilename(s):
  367. """
  368. @param s The name of the file
  369. """
  370. assert type(s) == type(u'')
  371. # Python 3 has a Unicode API
  372. if sys.version_info >= (3, 0):
  373. return s
  374. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  375. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  376. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  377. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  378. return s
  379. else:
  380. encoding = sys.getfilesystemencoding()
  381. if encoding is None:
  382. encoding = 'utf-8'
  383. return s.encode(encoding, 'ignore')
  384. def decodeOption(optval):
  385. if optval is None:
  386. return optval
  387. if isinstance(optval, bytes):
  388. optval = optval.decode(preferredencoding())
  389. assert isinstance(optval, compat_str)
  390. return optval
  391. def formatSeconds(secs):
  392. if secs > 3600:
  393. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  394. elif secs > 60:
  395. return '%d:%02d' % (secs // 60, secs % 60)
  396. else:
  397. return '%d' % secs
  398. def make_HTTPS_handler(opts):
  399. if sys.version_info < (3,2):
  400. # Python's 2.x handler is very simplistic
  401. return compat_urllib_request.HTTPSHandler()
  402. else:
  403. import ssl
  404. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  405. context.set_default_verify_paths()
  406. context.verify_mode = (ssl.CERT_NONE
  407. if opts.no_check_certificate
  408. else ssl.CERT_REQUIRED)
  409. return compat_urllib_request.HTTPSHandler(context=context)
  410. class ExtractorError(Exception):
  411. """Error during info extraction."""
  412. def __init__(self, msg, tb=None, expected=False):
  413. """ tb, if given, is the original traceback (so that it can be printed out).
  414. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  415. """
  416. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  417. expected = True
  418. if not expected:
  419. msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  420. super(ExtractorError, self).__init__(msg)
  421. self.traceback = tb
  422. self.exc_info = sys.exc_info() # preserve original exception
  423. def format_traceback(self):
  424. if self.traceback is None:
  425. return None
  426. return u''.join(traceback.format_tb(self.traceback))
  427. class DownloadError(Exception):
  428. """Download Error exception.
  429. This exception may be thrown by FileDownloader objects if they are not
  430. configured to continue on errors. They will contain the appropriate
  431. error message.
  432. """
  433. def __init__(self, msg, exc_info=None):
  434. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  435. super(DownloadError, self).__init__(msg)
  436. self.exc_info = exc_info
  437. class SameFileError(Exception):
  438. """Same File exception.
  439. This exception will be thrown by FileDownloader objects if they detect
  440. multiple files would have to be downloaded to the same file on disk.
  441. """
  442. pass
  443. class PostProcessingError(Exception):
  444. """Post Processing exception.
  445. This exception may be raised by PostProcessor's .run() method to
  446. indicate an error in the postprocessing task.
  447. """
  448. def __init__(self, msg):
  449. self.msg = msg
  450. class MaxDownloadsReached(Exception):
  451. """ --max-downloads limit has been reached. """
  452. pass
  453. class UnavailableVideoError(Exception):
  454. """Unavailable Format exception.
  455. This exception will be thrown when a video is requested
  456. in a format that is not available for that video.
  457. """
  458. pass
  459. class ContentTooShortError(Exception):
  460. """Content Too Short exception.
  461. This exception may be raised by FileDownloader objects when a file they
  462. download is too small for what the server announced first, indicating
  463. the connection was probably interrupted.
  464. """
  465. # Both in bytes
  466. downloaded = None
  467. expected = None
  468. def __init__(self, downloaded, expected):
  469. self.downloaded = downloaded
  470. self.expected = expected
  471. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  472. """Handler for HTTP requests and responses.
  473. This class, when installed with an OpenerDirector, automatically adds
  474. the standard headers to every HTTP request and handles gzipped and
  475. deflated responses from web servers. If compression is to be avoided in
  476. a particular request, the original request in the program code only has
  477. to include the HTTP header "Youtubedl-No-Compression", which will be
  478. removed before making the real request.
  479. Part of this code was copied from:
  480. http://techknack.net/python-urllib2-handlers/
  481. Andrew Rowls, the author of that code, agreed to release it to the
  482. public domain.
  483. """
  484. @staticmethod
  485. def deflate(data):
  486. try:
  487. return zlib.decompress(data, -zlib.MAX_WBITS)
  488. except zlib.error:
  489. return zlib.decompress(data)
  490. @staticmethod
  491. def addinfourl_wrapper(stream, headers, url, code):
  492. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  493. return compat_urllib_request.addinfourl(stream, headers, url, code)
  494. ret = compat_urllib_request.addinfourl(stream, headers, url)
  495. ret.code = code
  496. return ret
  497. def http_request(self, req):
  498. for h,v in std_headers.items():
  499. if h in req.headers:
  500. del req.headers[h]
  501. req.add_header(h, v)
  502. if 'Youtubedl-no-compression' in req.headers:
  503. if 'Accept-encoding' in req.headers:
  504. del req.headers['Accept-encoding']
  505. del req.headers['Youtubedl-no-compression']
  506. if 'Youtubedl-user-agent' in req.headers:
  507. if 'User-agent' in req.headers:
  508. del req.headers['User-agent']
  509. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  510. del req.headers['Youtubedl-user-agent']
  511. return req
  512. def http_response(self, req, resp):
  513. old_resp = resp
  514. # gzip
  515. if resp.headers.get('Content-encoding', '') == 'gzip':
  516. gz = gzip.GzipFile(fileobj=io.BytesIO(resp.read()), mode='r')
  517. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  518. resp.msg = old_resp.msg
  519. # deflate
  520. if resp.headers.get('Content-encoding', '') == 'deflate':
  521. gz = io.BytesIO(self.deflate(resp.read()))
  522. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  523. resp.msg = old_resp.msg
  524. return resp
  525. https_request = http_request
  526. https_response = http_response
  527. def unified_strdate(date_str):
  528. """Return a string with the date in the format YYYYMMDD"""
  529. upload_date = None
  530. #Replace commas
  531. date_str = date_str.replace(',',' ')
  532. # %z (UTC offset) is only supported in python>=3.2
  533. date_str = re.sub(r' (\+|-)[\d]*$', '', date_str)
  534. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y', '%Y-%m-%d', '%d/%m/%Y', '%Y/%m/%d %H:%M:%S', '%d.%m.%Y %H:%M']
  535. for expression in format_expressions:
  536. try:
  537. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  538. except:
  539. pass
  540. return upload_date
  541. def determine_ext(url):
  542. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  543. if re.match(r'^[A-Za-z0-9]+$', guess):
  544. return guess
  545. else:
  546. return u'unknown_video'
  547. def date_from_str(date_str):
  548. """
  549. Return a datetime object from a string in the format YYYYMMDD or
  550. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  551. today = datetime.date.today()
  552. if date_str == 'now'or date_str == 'today':
  553. return today
  554. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  555. if match is not None:
  556. sign = match.group('sign')
  557. time = int(match.group('time'))
  558. if sign == '-':
  559. time = -time
  560. unit = match.group('unit')
  561. #A bad aproximation?
  562. if unit == 'month':
  563. unit = 'day'
  564. time *= 30
  565. elif unit == 'year':
  566. unit = 'day'
  567. time *= 365
  568. unit += 's'
  569. delta = datetime.timedelta(**{unit: time})
  570. return today + delta
  571. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  572. class DateRange(object):
  573. """Represents a time interval between two dates"""
  574. def __init__(self, start=None, end=None):
  575. """start and end must be strings in the format accepted by date"""
  576. if start is not None:
  577. self.start = date_from_str(start)
  578. else:
  579. self.start = datetime.datetime.min.date()
  580. if end is not None:
  581. self.end = date_from_str(end)
  582. else:
  583. self.end = datetime.datetime.max.date()
  584. if self.start > self.end:
  585. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  586. @classmethod
  587. def day(cls, day):
  588. """Returns a range that only contains the given day"""
  589. return cls(day,day)
  590. def __contains__(self, date):
  591. """Check if the date is in the range"""
  592. if not isinstance(date, datetime.date):
  593. date = date_from_str(date)
  594. return self.start <= date <= self.end
  595. def __str__(self):
  596. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())