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.

680 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):
  413. """ tb, if given, is the original traceback (so that it can be printed out). """
  414. if not sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  415. msg = msg + u'; please report this issue on http://yt-dl.org/bug'
  416. super(ExtractorError, self).__init__(msg)
  417. self.traceback = tb
  418. self.exc_info = sys.exc_info() # preserve original exception
  419. def format_traceback(self):
  420. if self.traceback is None:
  421. return None
  422. return u''.join(traceback.format_tb(self.traceback))
  423. class DownloadError(Exception):
  424. """Download Error exception.
  425. This exception may be thrown by FileDownloader objects if they are not
  426. configured to continue on errors. They will contain the appropriate
  427. error message.
  428. """
  429. def __init__(self, msg, exc_info=None):
  430. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  431. super(DownloadError, self).__init__(msg)
  432. self.exc_info = exc_info
  433. class SameFileError(Exception):
  434. """Same File exception.
  435. This exception will be thrown by FileDownloader objects if they detect
  436. multiple files would have to be downloaded to the same file on disk.
  437. """
  438. pass
  439. class PostProcessingError(Exception):
  440. """Post Processing exception.
  441. This exception may be raised by PostProcessor's .run() method to
  442. indicate an error in the postprocessing task.
  443. """
  444. def __init__(self, msg):
  445. self.msg = msg
  446. class MaxDownloadsReached(Exception):
  447. """ --max-downloads limit has been reached. """
  448. pass
  449. class UnavailableVideoError(Exception):
  450. """Unavailable Format exception.
  451. This exception will be thrown when a video is requested
  452. in a format that is not available for that video.
  453. """
  454. pass
  455. class ContentTooShortError(Exception):
  456. """Content Too Short exception.
  457. This exception may be raised by FileDownloader objects when a file they
  458. download is too small for what the server announced first, indicating
  459. the connection was probably interrupted.
  460. """
  461. # Both in bytes
  462. downloaded = None
  463. expected = None
  464. def __init__(self, downloaded, expected):
  465. self.downloaded = downloaded
  466. self.expected = expected
  467. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  468. """Handler for HTTP requests and responses.
  469. This class, when installed with an OpenerDirector, automatically adds
  470. the standard headers to every HTTP request and handles gzipped and
  471. deflated responses from web servers. If compression is to be avoided in
  472. a particular request, the original request in the program code only has
  473. to include the HTTP header "Youtubedl-No-Compression", which will be
  474. removed before making the real request.
  475. Part of this code was copied from:
  476. http://techknack.net/python-urllib2-handlers/
  477. Andrew Rowls, the author of that code, agreed to release it to the
  478. public domain.
  479. """
  480. @staticmethod
  481. def deflate(data):
  482. try:
  483. return zlib.decompress(data, -zlib.MAX_WBITS)
  484. except zlib.error:
  485. return zlib.decompress(data)
  486. @staticmethod
  487. def addinfourl_wrapper(stream, headers, url, code):
  488. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  489. return compat_urllib_request.addinfourl(stream, headers, url, code)
  490. ret = compat_urllib_request.addinfourl(stream, headers, url)
  491. ret.code = code
  492. return ret
  493. def http_request(self, req):
  494. for h,v in std_headers.items():
  495. if h in req.headers:
  496. del req.headers[h]
  497. req.add_header(h, v)
  498. if 'Youtubedl-no-compression' in req.headers:
  499. if 'Accept-encoding' in req.headers:
  500. del req.headers['Accept-encoding']
  501. del req.headers['Youtubedl-no-compression']
  502. if 'Youtubedl-user-agent' in req.headers:
  503. if 'User-agent' in req.headers:
  504. del req.headers['User-agent']
  505. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  506. del req.headers['Youtubedl-user-agent']
  507. return req
  508. def http_response(self, req, resp):
  509. old_resp = resp
  510. # gzip
  511. if resp.headers.get('Content-encoding', '') == 'gzip':
  512. gz = gzip.GzipFile(fileobj=io.BytesIO(resp.read()), mode='r')
  513. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  514. resp.msg = old_resp.msg
  515. # deflate
  516. if resp.headers.get('Content-encoding', '') == 'deflate':
  517. gz = io.BytesIO(self.deflate(resp.read()))
  518. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  519. resp.msg = old_resp.msg
  520. return resp
  521. https_request = http_request
  522. https_response = http_response
  523. def unified_strdate(date_str):
  524. """Return a string with the date in the format YYYYMMDD"""
  525. upload_date = None
  526. #Replace commas
  527. date_str = date_str.replace(',',' ')
  528. # %z (UTC offset) is only supported in python>=3.2
  529. date_str = re.sub(r' (\+|-)[\d]*$', '', date_str)
  530. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y', '%Y-%m-%d', '%d/%m/%Y', '%Y/%m/%d %H:%M:%S']
  531. for expression in format_expressions:
  532. try:
  533. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  534. except:
  535. pass
  536. return upload_date
  537. def date_from_str(date_str):
  538. """
  539. Return a datetime object from a string in the format YYYYMMDD or
  540. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  541. today = datetime.date.today()
  542. if date_str == 'now'or date_str == 'today':
  543. return today
  544. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  545. if match is not None:
  546. sign = match.group('sign')
  547. time = int(match.group('time'))
  548. if sign == '-':
  549. time = -time
  550. unit = match.group('unit')
  551. #A bad aproximation?
  552. if unit == 'month':
  553. unit = 'day'
  554. time *= 30
  555. elif unit == 'year':
  556. unit = 'day'
  557. time *= 365
  558. unit += 's'
  559. delta = datetime.timedelta(**{unit: time})
  560. return today + delta
  561. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  562. class DateRange(object):
  563. """Represents a time interval between two dates"""
  564. def __init__(self, start=None, end=None):
  565. """start and end must be strings in the format accepted by date"""
  566. if start is not None:
  567. self.start = date_from_str(start)
  568. else:
  569. self.start = datetime.datetime.min.date()
  570. if end is not None:
  571. self.end = date_from_str(end)
  572. else:
  573. self.end = datetime.datetime.max.date()
  574. if self.start > self.end:
  575. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  576. @classmethod
  577. def day(cls, day):
  578. """Returns a range that only contains the given day"""
  579. return cls(day,day)
  580. def __contains__(self, date):
  581. """Check if the date is in the range"""
  582. if not isinstance(date, datetime.date):
  583. date = date_from_str(date)
  584. return self.start <= date <= self.end
  585. def __str__(self):
  586. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())