1 # -*- coding: iso-8859-1 -*- 2 """ 3 MoinMoin - PostMessage Action 4 5 @copyright: 2012 by Paul Boddie <paul@boddie.org.uk> 6 @license: GNU GPL (v2 or later), see COPYING.txt for details. 7 """ 8 9 from MoinMoin.PageEditor import PageEditor 10 from MoinSupport import * 11 from email.parser import Parser 12 13 try: 14 from cStringIO import StringIO 15 except ImportError: 16 from StringIO import StringIO 17 18 Dependencies = ['pages'] 19 20 class PostMessage: 21 22 "A posted message handler." 23 24 def __init__(self, pagename, request): 25 26 """ 27 On the page with the given 'pagename', use the given 'request' when 28 reading posted messages, modifying the Wiki. 29 """ 30 31 self.pagename = pagename 32 self.request = request 33 self.page = Page(request, pagename) 34 35 def do_action(self): 36 request = self.request 37 content_length = getHeader(request, "Content-Length", "HTTP") 38 if content_length: 39 content_length = int(content_length) 40 41 # Get the message. 42 43 message_text = StringIO(request.read(content_length)) 44 message = Parser().parse(message_text) 45 46 # Handle a single part. 47 48 if not message.is_multipart(): 49 self.handle_message_parts([message], to_replace(message)) 50 51 # Handle multiple parts. 52 53 # This can be a collection of updates, with each update potentially being a 54 # collection of alternative representations. 55 56 elif is_collection(message): 57 for part in message.get_payload(): 58 if part.is_multipart(): 59 self.handle_message_parts(part.get_payload(), to_replace(part)) 60 else: 61 self.handle_message_parts([part], to_replace(part)) 62 63 # Or it can be a collection of alternative representations for a single 64 # update. 65 66 else: 67 self.handle_message_parts(message.get_payload(), to_replace(message)) 68 69 # Default output. 70 71 writeHeaders(request, "text/plain", getMetadata(self.page), "204 No Content") 72 73 def handle_message_parts(self, parts, replace): 74 75 """ 76 Handle the given message 'parts', replacing the page content if 77 'replace' is set to a true value. 78 """ 79 80 # NOTE: Should either choose preferred content types or somehow retain them 81 # NOTE: all but present one at a time. 82 83 body = [] 84 85 for part in parts: 86 mimetype, encoding = getContentTypeAndEncoding(part.get("Content-Type")) 87 if mimetype == "text/moin": 88 body.append(part.get_payload()) 89 if replace: 90 break 91 92 if not replace: 93 body.append(self.page.get_raw_body()) 94 95 page_editor = PageEditor(self.request, self.pagename) 96 page_editor.saveText("\n\n".join(body), 0) 97 98 def is_collection(message): 99 return message.get("Update-Type") == "Collection" 100 101 def to_replace(message): 102 return message.get("Update-Action") == "replace" 103 104 # Action function. 105 106 def execute(pagename, request): 107 PostMessage(pagename, request).do_action() 108 109 # vim: tabstop=4 expandtab shiftwidth=4