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.

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