changeset 801:1f8976e01c3a

fix wrong import, make more use of MimeType class
author Thomas Waldmann <tw AT waldmann-edv DOT de>
date Fri, 19 May 2006 20:18:45 +0200
parents 3d50c51878b7
children 7b2e550c9660
files MoinMoin/Xapian.py MoinMoin/action/AttachFile.py MoinMoin/wikiutil.py
diffstat 3 files changed, 69 insertions(+), 85 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/Xapian.py	Fri May 19 19:17:12 2006 +0200
+++ b/MoinMoin/Xapian.py	Fri May 19 20:18:45 2006 +0200
@@ -12,7 +12,7 @@
 
 from MoinMoin.support.xapwrap import document as xapdoc
 from MoinMoin.support.xapwrap import index as xapidx
-from MoinMoin.parser.wiki import Parser as WikiParser
+from MoinMoin.parser.text_moin_wiki import Parser as WikiParser
 
 from MoinMoin.Page import Page
 from MoinMoin import config, wikiutil
@@ -397,29 +397,21 @@
     def contentfilter(self, filename):
         """ Get a filter for content of filename and return unicode content. """
         request = self.request
-        mt2mn = wikiutil.mimetype2modulename
-        mimetype, encoding = wikiutil.guess_type(filename)
-        if mimetype is None:
-            mimetype = 'application/octet-stream'
-        try:
-            _filter = mt2mn(mimetype)
-            execute = wikiutil.importPlugin(request.cfg, 'filter', _filter)
-        except wikiutil.PluginMissingError:
+        mt = wikiutil.MimeType(filename=filename)
+        for modulename in mt.module_name():
             try:
-                _filter = mt2mn(mimetype.split("/", 1)[0])
-                execute = wikiutil.importPlugin(request.cfg, 'filter', _filter)
+                execute = wikiutil.importPlugin(request.cfg, 'filter', modulename)
             except wikiutil.PluginMissingError:
-                try:
-                    _filter = mt2mn('application/octet-stream')
-                    execute = wikiutil.importPlugin(request.cfg, 'filter', _filter)
-                except wikiutil.PluginMissingError:
-                    raise ImportError("Cannot load filter %s" % _filter)
+                pass
+        else:
+            raise "Cannot load filter for mimetype." # XXX
         try:
             data = execute(self, filename)
-            if debug: request.log("Filter %s returned %d characters for file %s" % (_filter, len(data), filename))
+            if debug:
+                request.log("Filter %s returned %d characters for file %s" % (modulename, len(data), filename))
         except (OSError, IOError), err:
             data = ''
-            request.log("Filter %s threw error '%s' for file %s" % (_filter, str(err), filename))
+            request.log("Filter %s threw error '%s' for file %s" % (modulename, str(err), filename))
         return mimetype, data
    
     def test(self, request):
--- a/MoinMoin/action/AttachFile.py	Fri May 19 19:17:12 2006 +0200
+++ b/MoinMoin/action/AttachFile.py	Fri May 19 20:18:45 2006 +0200
@@ -633,16 +633,14 @@
     import shutil
 
     filename, fpath = _access_file(pagename, request)
-    if not filename: return # error msg already sent in _access_file
+    if not filename:
+        return # error msg already sent in _access_file
 
-    # get mimetype
-    type, enc = wikiutil.guess_type(filename)
-    if not type:
-        type = "application/octet-stream"
+    mt = wikiutil.MimeType(filename=filename)
 
     # send header
     request.http_headers([
-        "Content-Type: %s" % type,
+        "Content-Type: %s" % mt.content_type(),
         "Content-Length: %d" % os.path.getsize(fpath),
         # TODO: fix the encoding here, plain 8 bit is not allowed according to the RFCs
         # There is no solution that is compatible to IE except stripping non-ascii chars
@@ -766,24 +764,23 @@
 
     request.write('<h2>' + _("Attachment '%(filename)s'") % {'filename': filename} + '</h2>')
 
-    type, enc = wikiutil.guess_type(filename)
-    if type:
-        if type[:5] == 'image':
-            timestamp = htdocs_access(request) and "?%s" % time.time() or ''
-            request.write('<img src="%s%s" alt="%s">' % (
-                getAttachUrl(pagename, filename, request, escaped=1), timestamp, wikiutil.escape(filename, 1)))
-            return
-        elif type[:4] == 'text':
-            # TODO: should use formatter here!
-            request.write("<pre>")
-            # Try to decode file contents. It may return junk, but we
-            # don't have enough information on attachments.
-            content = open(fpath, 'r').read()
-            content = wikiutil.decodeUnknownInput(content)
-            content = wikiutil.escape(content)
-            request.write(content)
-            request.write("</pre>")
-            return
+    mt = wikiutil.MimeType(filename=filename)
+    if mt.major == 'image':
+        timestamp = htdocs_access(request) and "?%s" % time.time() or ''
+        request.write('<img src="%s%s" alt="%s">' % (
+            getAttachUrl(pagename, filename, request, escaped=1), timestamp, wikiutil.escape(filename, 1)))
+        return
+    elif mt.major == 'text':
+        # TODO: should use formatter here!
+        request.write("<pre>")
+        # Try to decode file contents. It may return junk, but we
+        # don't have enough information on attachments.
+        content = open(fpath, 'r').read()
+        content = wikiutil.decodeUnknownInput(content)
+        content = wikiutil.escape(content)
+        request.write(content)
+        request.write("</pre>")
+        return
 
     package = packages.ZipPackage(request, fpath)
     if package.isPackage():
--- a/MoinMoin/wikiutil.py	Fri May 19 19:17:12 2006 +0200
+++ b/MoinMoin/wikiutil.py	Fri May 19 20:18:45 2006 +0200
@@ -24,35 +24,6 @@
 CHILD_PREFIX_LEN = len(CHILD_PREFIX)
 
 #############################################################################
-### mimetype support
-#############################################################################
-import mimetypes
-guess_type = mimetypes.guess_type
-guess_extension = mimetypes.guess_extension
-
-_our_types = {
- # OpenOffice 2.x & others
- '.odt': 'application/vnd.oasis.opendocument.text',
- '.ods': 'application/vnd.oasis.opendocument.spreadsheet',
- '.odp': 'application/vnd.oasis.opendocument.presentation',
- '.odg': 'application/vnd.oasis.opendocument.graphics',
- '.odc': 'application/vnd.oasis.opendocument.chart',
- '.odf': 'application/vnd.oasis.opendocument.formula',
- '.odb': 'application/vnd.oasis.opendocument.database',
- '.odi': 'application/vnd.oasis.opendocument.image',
- '.odm': 'application/vnd.oasis.opendocument.text-master',
- '.ott': 'application/vnd.oasis.opendocument.text-template',
- '.ots': 'application/vnd.oasis.opendocument.spreadsheet-template',
- '.otp': 'application/vnd.oasis.opendocument.presentation-template',
- '.otg': 'application/vnd.oasis.opendocument.graphics-template',
-}
-[mimetypes.add_type(mimetype, ext, True) for ext, mimetype in _our_types.items()]
-
-def mimetype2modulename(mimetype):
-    """ convert an original mimetype to a string usable as python module name """
-    return mimetype.replace("/", "_").replace("-","_").replace(".", "_")
-
-#############################################################################
 ### Getting data from user/Sending data to user
 #############################################################################
 
@@ -790,33 +761,57 @@
     else:
         return u'["%s"]' % pagename
 
+#############################################################################
+### mimetype support
+#############################################################################
+import mimetypes
+
+MIMETYPES_MORE = {
+ # OpenOffice 2.x & other open document stuff
+ '.odt': 'application/vnd.oasis.opendocument.text',
+ '.ods': 'application/vnd.oasis.opendocument.spreadsheet',
+ '.odp': 'application/vnd.oasis.opendocument.presentation',
+ '.odg': 'application/vnd.oasis.opendocument.graphics',
+ '.odc': 'application/vnd.oasis.opendocument.chart',
+ '.odf': 'application/vnd.oasis.opendocument.formula',
+ '.odb': 'application/vnd.oasis.opendocument.database',
+ '.odi': 'application/vnd.oasis.opendocument.image',
+ '.odm': 'application/vnd.oasis.opendocument.text-master',
+ '.ott': 'application/vnd.oasis.opendocument.text-template',
+ '.ots': 'application/vnd.oasis.opendocument.spreadsheet-template',
+ '.otp': 'application/vnd.oasis.opendocument.presentation-template',
+ '.otg': 'application/vnd.oasis.opendocument.graphics-template',
+}
+[mimetypes.add_type(mimetype, ext, True) for ext, mimetype in MIMETYPES_MORE.items()]
+
+MIMETYPES_sanitize_mapping = {
+    # this stuff is text, but got application/* for unknown reasons
+    ('application', 'docbook+xml'): ('text', 'docbook'),
+    ('application', 'x-latex'): ('text', 'latex'),
+    ('application', 'x-tex'): ('text', 'tex'),
+    ('application', 'javascript'): ('text', 'javascript'),
+}
+
+MIMETYPES_spoil_mapping = {} # inverse mapping of above
+for key, value in MIMETYPES_sanitize_mapping.items():
+    MIMETYPES_spoil_mapping[value] = key
+
+
 # mimetype stuff ------------------------------------------------------------
 class MimeType(object):
     """ represents a mimetype like text/plain """
-    sanitize_mapping = {
-        # this stuff is text, but got application/* for unknown reasons
-        ('application', 'docbook+xml'): ('text', 'docbook'),
-        ('application', 'x-latex'): ('text', 'latex'),
-        ('application', 'x-tex'): ('text', 'tex'),
-        ('application', 'javascript'): ('text', 'javascript'),
-    }
-    spoil_mapping = {} # inverse mapping of above
     
     def __init__(self, mimestr=None, filename=None):
         self.major = self.minor = None # sanitized mime type and subtype
         self.params = {} # parameters like "charset" or others
         self.charset = None # this stays None until we know for sure!
 
-        for key, value in self.sanitize_mapping.items():
-            self.spoil_mapping[value] = key
-
         if mimestr:
             self.parse_mimetype(mimestr)
         elif filename:
             self.parse_filename(filename)
     
     def parse_filename(self, filename):
-        import mimetypes
         mtype, encoding = mimetypes.guess_type()
         if mtype is None:
             mtype = 'application/octet-stream'
@@ -873,13 +868,13 @@
             readable text, we will return some text/* mimetype, not application/*,
             because we need text/plain as fallback and not application/octet-stream.
         """
-        self.major, self.minor = self.sanitize_mapping.get((self.major, self.minor), (self.major, self.minor))
+        self.major, self.minor = MIMETYPES_sanitize_mapping.get((self.major, self.minor), (self.major, self.minor))
 
     def spoil(self):
         """ this returns something conformant to /etc/mime.type or IANA as a string,
             kind of inverse operation of sanitize(), but doesn't change self
         """
-        major, minor = self.spoil_mapping.get((self.major, self.minor), (self.major, self.minor))
+        major, minor = MIMETYPES_spoil_mapping.get((self.major, self.minor), (self.major, self.minor))
         return self.content_type(major, minor)
 
     def content_type(self, major=None, minor=None, charset=None, params=None):