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.

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