changeset 2111:a3377b242e21

First try to reduce code duplication. More tomorrow after some sleep...
author Karol 'grzywacz' Nowak <grzywacz@sul.uni.lodz.pl>
date Fri, 08 Jun 2007 03:43:45 +0200
parents 1ede132a9d38
children a4d95b9d8f37
files MoinMoin/events/JabberNotification.py MoinMoin/events/messages.py
diffstat 2 files changed, 88 insertions(+), 161 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/events/JabberNotification.py	Fri Jun 08 02:41:19 2007 +0200
+++ b/MoinMoin/events/JabberNotification.py	Fri Jun 08 03:43:45 2007 +0200
@@ -13,11 +13,8 @@
 from MoinMoin.user import User, getUserList
 from MoinMoin.Page import Page
 
-from MoinMoin.events import *
-from MoinMoin.events.messages import page_changed_notification
-from MoinMoin.events.messages import file_attached_notification
-from MoinMoin.events.messages import page_deleted_notification
-
+import MoinMoin.events as ev
+from MoinMoin.events.messages import page_change_message
 
 # XML RPC Server object used to communicate with notification bot
 server = None
@@ -36,13 +33,13 @@
     if server is None:
         server = xmlrpclib.Server("http://" + cfg.bot_host)
     
-    if isinstance(event, PageChangedEvent):
+    if isinstance(event, ev.PageChangedEvent):
         return handle_page_changed(event)
-    elif isinstance(event, JabberIDSetEvent) or isinstance(event, JabberIDUnsetEvent):
+    elif isinstance(event, ev.JabberIDSetEvent) or isinstance(event, ev.JabberIDUnsetEvent):
         return handle_jid_changed(event)
-    elif isinstance(event, FileAttachedEvent):
+    elif isinstance(event, ev.FileAttachedEvent):
         return handle_file_attached(event)
-    elif isinstance(event, PageDeletedEvent):
+    elif isinstance(event, ev.PageDeletedEvent):
         return handle_page_deleted(event)
     
 
@@ -70,23 +67,43 @@
     """Handles event sent when a file is attached to a page"""
     
     request = event.request
-    pagename = event.pagename
-    size = event.size
-    attach_name = event.attachment_name
-    page = Page(request, pagename)
+    page = Page(request, event.pagename) 
+    
+    subscribers = page.getSubscribers(request, return_users=1)
+    page_change("attachment_added", request, page, subscribers, attach_name=event.attachment_name, attach_size=event.size)
+
+        
+def handle_page_changed(event):
+    """ Handles events related to page changes """
+    
+    request = event.request
+    page = event.page
+    
+    subscribers = page.getSubscribers(request, return_users=1, trivial=event.trivial)
+    page_change("page_changed", request, page, subscribers, revisions=page.getRevList(), comment=event.comment)
+    
+
+def handle_page_deleted(event):
+    """Handles event sent when a page is deleted"""
+    
+    request = event.request
+    page = event.page
+    
+    subscribers = page.getSubscribers(request, return_users=1)
+    page_change("page_deleted", request, page, subscribers)
+    
+
+def page_change(type, request, page, subscribers, **kwargs):
     
     _ = request.getText
     
-    subscribers = page.getSubscribers(request, return_users=1)
     if subscribers:
         # send notifications to all subscribers
         results = [_('Status of sending notifications:')]
-        
         for lang in subscribers:
             jids = [u.jid for u in subscribers[lang]]
             names = [u.name for u in subscribers[lang]]
-            msg = file_attached_notification(request, pagename, lang, attach_name, size)
-            print msg
+            msg = page_change_message(type, request, page, lang, **kwargs)
             jabberok, status = send_notification(request, jids, msg)
             recipients = ", ".join(names)
             results.append(_('[%(lang)s] %(recipients)s: %(status)s') % {
@@ -99,74 +116,6 @@
     # No notifications sent, no message.
     return ''
 
-        
-def handle_page_changed(event):
-    """ Handles events related to page changes """
-    
-    request = event.request
-    trivial = event.trivial
-    comment = event.comment
-    page = event.page
-    
-    _ = request.getText
-    
-    subscribers = page.getSubscribers(request, return_users=1, trivial=event.trivial)
-    if subscribers:
-        # get a list of old revisions, and append a diff
-        revisions = page.getRevList()
-        
-        # send notifications to all subscribers
-        results = [_('Status of sending notifications:')]
-        for lang in subscribers:
-            jids = [u.jid for u in subscribers[lang]]
-            names = [u.name for u in subscribers[lang]]
-            msg = page_changed_notification(request, page, comment, lang, revisions, trivial)
-            jabberok, status = send_notification(request, jids, msg)
-            recipients = ", ".join(names)
-            results.append(_('[%(lang)s] %(recipients)s: %(status)s') % {
-                'lang': lang, 'recipients': recipients, 'status': status})
-
-        # Return notifications sent results. Ignore trivial - we don't have
-        # to lie. If notification was sent, just tell about it.
-        return '<p>\n%s\n</p> ' % '<br>'.join(results)
-
-    # No notifications sent, no message.
-    return ''
-
-
-def handle_page_deleted(event):
-    """Handles event sent when a page is deleted"""
-    
-    request = event.request
-    comment = event.comment
-    page = event.page
-    
-    _ = request.getText
-    
-    subscribers = page.getSubscribers(request, return_users=1)
-    if subscribers:
-        # get a list of old revisions, and append a diff
-        revisions = page.getRevList()
-        
-        # send notifications to all subscribers
-        results = [_('Status of sending notifications:')]
-        for lang in subscribers:
-            jids = [u.jid for u in subscribers[lang]]
-            names = [u.name for u in subscribers[lang]]
-            msg = page_deleted_notification(request, page, comment, lang)
-            jabberok, status = send_notification(request, jids, msg)
-            recipients = ", ".join(names)
-            results.append(_('[%(lang)s] %(recipients)s: %(status)s') % {
-                'lang': lang, 'recipients': recipients, 'status': status})
-
-        # Return notifications sent results. Ignore trivial - we don't have
-        # to lie. If notification was sent, just tell about it.
-        return '<p>\n%s\n</p> ' % '<br>'.join(results)
-
-    # No notifications sent, no message.
-    return ''
-
-
 def send_notification(request, jids, message):
     """ Send notifications for a single language.
 
--- a/MoinMoin/events/messages.py	Fri Jun 08 02:41:19 2007 +0200
+++ b/MoinMoin/events/messages.py	Fri Jun 08 03:43:45 2007 +0200
@@ -13,92 +13,54 @@
 from MoinMoin.Page import Page
 from MoinMoin.action.AttachFile import getAttachUrl
 
-
-def page_changed_notification(request, page, comment, lang, revisions, trivial):
-    """ Prepare a page change notification text for a single language
+class UnknownChangeType:
+    pass
 
-    @param comment: editor's comment given when saving the page
-    @param lang: language of notifications
-    @param revisions: revisions of this page (newest first!)
-    @param trivial: the change is marked as trivial
-    @rtype: int
-    @return: composed string message
-    """
+def page_change_message(type, request, page, lang, **kwargs):
+    """Prepare a notification text for a page change of given type"""
+    
     _ = request.getText
     page._ = lambda s, formatted=True, r=request, l=lang: r.getText(s, formatted=formatted, lang=l)
-
-    if len(revisions) >= 2:
-        querystr = {'action': 'diff',
+    querystr = {}
+    
+    if type == "page_changed": 
+        revisions = kwargs['revisions']
+        if len(kwargs['revisions']) >= 2:
+            querystr = {'action': 'diff',
                     'rev2': str(revisions[0]),
                     'rev1': str(revisions[1])}
-    else:
-        querystr = {}
+        
+    if type == "attachment_added":
+        attachlink = request.getBaseURL() + \
+                        getAttachUrl(page.page_name, kwargs['attach_name'], request)
         
     pagelink = request.getQualifiedURL(page.url(request, querystr, relative=False))
-
-    messageBody = _("Dear Wiki user,\n\n"
+    
+    if type == "page_changed":
+        messageBody = _("Dear Wiki user,\n\n"
         'You have subscribed to a wiki page or wiki category on "%(sitename)s" for change notification.\n\n'
         "The following page has been changed by %(editor)s:\n"
         "%(pagelink)s\n\n", formatted=False) % {
             'editor': page.uid_override or user.getUserIdentification(request),
             'pagelink': pagelink,
             'sitename': page.cfg.sitename or request.getBaseURL(),
-    }
-
-    if comment:
-        messageBody = messageBody + \
-            _("The comment on the change is:\n%(comment)s\n\n", formatted=False) % {'comment': comment}
-
-    # append a diff (or append full page text if there is no diff)
-    if len(revisions) < 2:
-        messageBody = messageBody + \
-            _("New page:\n", formatted=False) + \
-            page.get_raw_body()
-    else:
-        lines = wikiutil.pagediff(request, page.page_name, revisions[1],
-                                  page.page_name, revisions[0])
-        if lines:
-            messageBody = messageBody + "%s\n%s\n" % (("-" * 78), '\n'.join(lines))
-        else:
-            messageBody = messageBody + _("No differences found!\n", formatted=False)
+        }
             
-    return messageBody
-
-def page_deleted_notification(request, page, comment, lang):
-    """ Prepare a page deletion notification text for a single language """
-    
-    _ = request.getText
-    page._ = lambda s, formatted=True, r=request, l=lang: r.getText(s, formatted=formatted, lang=l)
-    
-    pagelink = request.getQualifiedURL(page.url(request, {}, relative=False))
-    
-    messageBody = _("Dear wiki user,\n\n"
-        'You have subscribed to a wiki page "%(sitename)s" for change notification.\n\n'
-        "The following page has been deleted by %(editor)s:\n"
-        "%(pagelink)s\n\n", formatted=False) % {
-            'editor': page.uid_override or user.getUserIdentification(request),
-            'pagelink': pagelink,
-            'sitename': page.cfg.sitename or request.getBaseURL(),
-    }
-        
-    if comment:
-        messageBody = messageBody + \
-            _("The comment on the change is:\n%(comment)s", formatted=False) % {'comment': comment}
-        
-    return messageBody
-                                                                          
-
-def file_attached_notification(request, pagename, lang, attach_name, attach_size):
-    """ Prepare an attachment added notification text for a single language """
-    
-    _ = request.getText
-    page = Page(request, pagename)
-    pagelink = request.getQualifiedURL(page.url(request, {}, relative=False))
-    attachlink = request.getBaseURL() + getAttachUrl(pagename, attach_name, request)
-    
-    page._ = lambda s, formatted=True, r=request, l=lang: r.getText(s, formatted=formatted, lang=l)
-    
-    messageBody = _("Dear Wiki user,\n\n"
+        # append a diff (or append full page text if there is no diff)
+        if len(revisions) < 2:
+            messageBody = messageBody + \
+                _("New page:\n", formatted=False) + \
+                page.get_raw_body()
+        else:
+            lines = wikiutil.pagediff(request, page.page_name, revisions[1],
+                                      page.page_name, revisions[0])
+            if lines:
+                messageBody = messageBody + "%s\n%s\n" % (("-" * 78), '\n'.join(lines))
+            else:
+                messageBody = messageBody + _("No differences found!\n", formatted=False)
+                
+    elif type == "attachment_added":
+        messageBody = _("Dear Wiki user,\n\n"
         'You have subscribed to a wiki page "%(sitename)s" for change notification.\n\n'
         "An attachment has been added to the following page by %(editor)s:\n"
         "Following detailed information is available:\n"
@@ -108,10 +70,26 @@
             'editor': user.getUserIdentification(request),
             'pagelink': pagelink,
             'sitename': page.cfg.sitename or request.getBaseURL(),
-            'attach_name': attach_name,
-            'attach_size': attach_size,
+            'attach_name': kwargs['attach_name'],
+            'attach_size': kwargs['attach_size'],
             'attach_get': attachlink,
-    }
+        }
         
+    elif type == "page_deleted":
+        messageBody = _("Dear wiki user,\n\n"
+            'You have subscribed to a wiki page "%(sitename)s" for change notification.\n\n'
+            "The following page has been deleted by %(editor)s:\n"
+            "%(pagelink)s\n\n", formatted=False) % {
+                'editor': page.uid_override or user.getUserIdentification(request),
+                'pagelink': pagelink,
+                'sitename': page.cfg.sitename or request.getBaseURL(),
+        }
+    else:
+        raise UnknownChangeType()
+    
+    if 'comment' in kwargs:
+        messageBody = messageBody + \
+            _("The comment on the change is:\n%(comment)s\n\n", formatted=False) % {'comment': kwargs['comment']}
+            
     return messageBody
-
+