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.

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