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.

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