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.

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