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.

660 lines
22 KiB

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