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.

506 lines
16 KiB

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