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.

363 lines
9.9 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import gzip
  4. import htmlentitydefs
  5. import HTMLParser
  6. import locale
  7. import os
  8. import re
  9. import sys
  10. import zlib
  11. import urllib2
  12. import email.utils
  13. import json
  14. try:
  15. import cStringIO as StringIO
  16. except ImportError:
  17. import StringIO
  18. std_headers = {
  19. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',
  20. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  21. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  22. 'Accept-Encoding': 'gzip, deflate',
  23. 'Accept-Language': 'en-us,en;q=0.5',
  24. }
  25. def preferredencoding():
  26. """Get preferred encoding.
  27. Returns the best encoding scheme for the system, based on
  28. locale.getpreferredencoding() and some further tweaks.
  29. """
  30. def yield_preferredencoding():
  31. try:
  32. pref = locale.getpreferredencoding()
  33. u'TEST'.encode(pref)
  34. except:
  35. pref = 'UTF-8'
  36. while True:
  37. yield pref
  38. return yield_preferredencoding().next()
  39. def htmlentity_transform(matchobj):
  40. """Transforms an HTML entity to a Unicode character.
  41. This function receives a match object and is intended to be used with
  42. the re.sub() function.
  43. """
  44. entity = matchobj.group(1)
  45. # Known non-numeric HTML entity
  46. if entity in htmlentitydefs.name2codepoint:
  47. return unichr(htmlentitydefs.name2codepoint[entity])
  48. # Unicode character
  49. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  50. if mobj is not None:
  51. numstr = mobj.group(1)
  52. if numstr.startswith(u'x'):
  53. base = 16
  54. numstr = u'0%s' % numstr
  55. else:
  56. base = 10
  57. return unichr(long(numstr, base))
  58. # Unknown entity in name, return its literal representation
  59. return (u'&%s;' % entity)
  60. HTMLParser.locatestarttagend = re.compile(r"""<[a-zA-Z][-.a-zA-Z0-9:_]*(?:\s+(?:(?<=['"\s])[^\s/>][^\s/=>]*(?:\s*=+\s*(?:'[^']*'|"[^"]*"|(?!['"])[^>\s]*))?\s*)*)?\s*""", re.VERBOSE) # backport bugfix
  61. class IDParser(HTMLParser.HTMLParser):
  62. """Modified HTMLParser that isolates a tag with the specified id"""
  63. def __init__(self, id):
  64. self.id = id
  65. self.result = None
  66. self.started = False
  67. self.depth = {}
  68. self.html = None
  69. self.watch_startpos = False
  70. self.error_count = 0
  71. HTMLParser.HTMLParser.__init__(self)
  72. def error(self, message):
  73. if self.error_count > 10 or self.started:
  74. raise HTMLParser.HTMLParseError(message, self.getpos())
  75. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  76. self.error_count += 1
  77. self.goahead(1)
  78. def loads(self, html):
  79. self.html = html
  80. self.feed(html)
  81. self.close()
  82. def handle_starttag(self, tag, attrs):
  83. attrs = dict(attrs)
  84. if self.started:
  85. self.find_startpos(None)
  86. if 'id' in attrs and attrs['id'] == self.id:
  87. self.result = [tag]
  88. self.started = True
  89. self.watch_startpos = True
  90. if self.started:
  91. if not tag in self.depth: self.depth[tag] = 0
  92. self.depth[tag] += 1
  93. def handle_endtag(self, tag):
  94. if self.started:
  95. if tag in self.depth: self.depth[tag] -= 1
  96. if self.depth[self.result[0]] == 0:
  97. self.started = False
  98. self.result.append(self.getpos())
  99. def find_startpos(self, x):
  100. """Needed to put the start position of the result (self.result[1])
  101. after the opening tag with the requested id"""
  102. if self.watch_startpos:
  103. self.watch_startpos = False
  104. self.result.append(self.getpos())
  105. handle_entityref = handle_charref = handle_data = handle_comment = \
  106. handle_decl = handle_pi = unknown_decl = find_startpos
  107. def get_result(self):
  108. if self.result == None: return None
  109. if len(self.result) != 3: return None
  110. lines = self.html.split('\n')
  111. lines = lines[self.result[1][0]-1:self.result[2][0]]
  112. lines[0] = lines[0][self.result[1][1]:]
  113. if len(lines) == 1:
  114. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  115. lines[-1] = lines[-1][:self.result[2][1]]
  116. return '\n'.join(lines).strip()
  117. def get_element_by_id(id, html):
  118. """Return the content of the tag with the specified id in the passed HTML document"""
  119. parser = IDParser(id)
  120. try:
  121. parser.loads(html)
  122. except HTMLParser.HTMLParseError:
  123. pass
  124. return parser.get_result()
  125. def clean_html(html):
  126. """Clean an HTML snippet into a readable string"""
  127. # Newline vs <br />
  128. html = html.replace('\n', ' ')
  129. html = re.sub('\s*<\s*br\s*/?\s*>\s*', '\n', html)
  130. # Strip html tags
  131. html = re.sub('<.*?>', '', html)
  132. # Replace html entities
  133. html = unescapeHTML(html)
  134. return html
  135. def sanitize_open(filename, open_mode):
  136. """Try to open the given filename, and slightly tweak it if this fails.
  137. Attempts to open the given filename. If this fails, it tries to change
  138. the filename slightly, step by step, until it's either able to open it
  139. or it fails and raises a final exception, like the standard open()
  140. function.
  141. It returns the tuple (stream, definitive_file_name).
  142. """
  143. try:
  144. if filename == u'-':
  145. if sys.platform == 'win32':
  146. import msvcrt
  147. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  148. return (sys.stdout, filename)
  149. stream = open(encodeFilename(filename), open_mode)
  150. return (stream, filename)
  151. except (IOError, OSError), err:
  152. # In case of error, try to remove win32 forbidden chars
  153. filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)
  154. # An exception here should be caught in the caller
  155. stream = open(encodeFilename(filename), open_mode)
  156. return (stream, filename)
  157. def timeconvert(timestr):
  158. """Convert RFC 2822 defined time string into system timestamp"""
  159. timestamp = None
  160. timetuple = email.utils.parsedate_tz(timestr)
  161. if timetuple is not None:
  162. timestamp = email.utils.mktime_tz(timetuple)
  163. return timestamp
  164. def sanitize_filename(s):
  165. """Sanitizes a string so it could be used as part of a filename."""
  166. def replace_insane(char):
  167. if char == '?' or ord(char) < 32 or ord(char) == 127:
  168. return ''
  169. elif char == '"':
  170. return '\''
  171. elif char == ':':
  172. return ' -'
  173. elif char in '\\/|*<>':
  174. return '-'
  175. return char
  176. result = u''.join(map(replace_insane, s))
  177. while '--' in result:
  178. result = result.replace('--', '-')
  179. return result.strip('-')
  180. def orderedSet(iterable):
  181. """ Remove all duplicates from the input iterable """
  182. res = []
  183. for el in iterable:
  184. if el not in res:
  185. res.append(el)
  186. return res
  187. def unescapeHTML(s):
  188. """
  189. @param s a string (of type unicode)
  190. """
  191. assert type(s) == type(u'')
  192. result = re.sub(ur'(?u)&(.+?);', htmlentity_transform, s)
  193. return result
  194. def encodeFilename(s):
  195. """
  196. @param s The name of the file (of type unicode)
  197. """
  198. assert type(s) == type(u'')
  199. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  200. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  201. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  202. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  203. return s
  204. else:
  205. return s.encode(sys.getfilesystemencoding(), 'ignore')
  206. class DownloadError(Exception):
  207. """Download Error exception.
  208. This exception may be thrown by FileDownloader objects if they are not
  209. configured to continue on errors. They will contain the appropriate
  210. error message.
  211. """
  212. pass
  213. class SameFileError(Exception):
  214. """Same File exception.
  215. This exception will be thrown by FileDownloader objects if they detect
  216. multiple files would have to be downloaded to the same file on disk.
  217. """
  218. pass
  219. class PostProcessingError(Exception):
  220. """Post Processing exception.
  221. This exception may be raised by PostProcessor's .run() method to
  222. indicate an error in the postprocessing task.
  223. """
  224. pass
  225. class MaxDownloadsReached(Exception):
  226. """ --max-downloads limit has been reached. """
  227. pass
  228. class UnavailableVideoError(Exception):
  229. """Unavailable Format exception.
  230. This exception will be thrown when a video is requested
  231. in a format that is not available for that video.
  232. """
  233. pass
  234. class ContentTooShortError(Exception):
  235. """Content Too Short exception.
  236. This exception may be raised by FileDownloader objects when a file they
  237. download is too small for what the server announced first, indicating
  238. the connection was probably interrupted.
  239. """
  240. # Both in bytes
  241. downloaded = None
  242. expected = None
  243. def __init__(self, downloaded, expected):
  244. self.downloaded = downloaded
  245. self.expected = expected
  246. class Trouble(Exception):
  247. """Trouble helper exception
  248. This is an exception to be handled with
  249. FileDownloader.trouble
  250. """
  251. class YoutubeDLHandler(urllib2.HTTPHandler):
  252. """Handler for HTTP requests and responses.
  253. This class, when installed with an OpenerDirector, automatically adds
  254. the standard headers to every HTTP request and handles gzipped and
  255. deflated responses from web servers. If compression is to be avoided in
  256. a particular request, the original request in the program code only has
  257. to include the HTTP header "Youtubedl-No-Compression", which will be
  258. removed before making the real request.
  259. Part of this code was copied from:
  260. http://techknack.net/python-urllib2-handlers/
  261. Andrew Rowls, the author of that code, agreed to release it to the
  262. public domain.
  263. """
  264. @staticmethod
  265. def deflate(data):
  266. try:
  267. return zlib.decompress(data, -zlib.MAX_WBITS)
  268. except zlib.error:
  269. return zlib.decompress(data)
  270. @staticmethod
  271. def addinfourl_wrapper(stream, headers, url, code):
  272. if hasattr(urllib2.addinfourl, 'getcode'):
  273. return urllib2.addinfourl(stream, headers, url, code)
  274. ret = urllib2.addinfourl(stream, headers, url)
  275. ret.code = code
  276. return ret
  277. def http_request(self, req):
  278. for h in std_headers:
  279. if h in req.headers:
  280. del req.headers[h]
  281. req.add_header(h, std_headers[h])
  282. if 'Youtubedl-no-compression' in req.headers:
  283. if 'Accept-encoding' in req.headers:
  284. del req.headers['Accept-encoding']
  285. del req.headers['Youtubedl-no-compression']
  286. return req
  287. def http_response(self, req, resp):
  288. old_resp = resp
  289. # gzip
  290. if resp.headers.get('Content-encoding', '') == 'gzip':
  291. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  292. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  293. resp.msg = old_resp.msg
  294. # deflate
  295. if resp.headers.get('Content-encoding', '') == 'deflate':
  296. gz = StringIO.StringIO(self.deflate(resp.read()))
  297. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  298. resp.msg = old_resp.msg
  299. return resp