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.

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