changeset 2318:062b76cf8d48

Introduce an base EventResult class for event handler return values. Make send_notification use a list of jids, instead of one. I'll remove prints tomorrow.
author Karol 'grzywacz' Nowak <grzywacz@sul.uni.lodz.pl>
date Sat, 23 Jun 2007 00:01:56 +0200
parents 02824b69a95c
children 10ec0e8d35e1
files MoinMoin/PageEditor.py MoinMoin/_tests/test_events.py MoinMoin/action/AttachFile.py MoinMoin/events/__init__.py MoinMoin/events/emailnotify.py MoinMoin/events/jabbernotify.py
diffstat 6 files changed, 89 insertions(+), 75 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/PageEditor.py	Fri Jun 22 19:00:44 2007 +0200
+++ b/MoinMoin/PageEditor.py	Sat Jun 23 00:01:56 2007 +0200
@@ -18,6 +18,11 @@
 
 import os, time, codecs, errno
 
+try:
+    set
+except:
+    from sets import Set as set
+    
 from MoinMoin import caching, config, user, wikiutil, error
 from MoinMoin.Page import Page
 from MoinMoin.widget import html
@@ -26,6 +31,7 @@
 from MoinMoin.util import filesys, timefuncs, web
 from MoinMoin.mail import sendmail
 from MoinMoin.events import PageDeletedEvent, send_event
+import MoinMoin.events.notification as notification
 
 # used for merging
 conflict_markers = ("\n---- /!\\ '''Edit conflict - other version:''' ----\n",
@@ -1043,8 +1049,16 @@
             # send notifications
             from MoinMoin import events
             e = events.PageChangedEvent(self.request, self, comment, trivial)
-            messages = events.send_event(e)
-            msg = msg + "".join(messages)
+            results = events.send_event(e)
+
+            recipients = set()
+            for result in results:
+                if isinstance(result, notification.Success):
+                    recipients.update(result.recipients)
+
+            if recipients:
+                info = _("Notifications sent to:")
+                msg = msg + "<p>%s %s</p>" % (info, ",".join(recipients))
 
             if kw.get('index', 1) and request.cfg.xapian_search:
                 from MoinMoin.search.Xapian import Index
--- a/MoinMoin/_tests/test_events.py	Fri Jun 22 19:00:44 2007 +0200
+++ b/MoinMoin/_tests/test_events.py	Sat Jun 23 00:01:56 2007 +0200
@@ -6,12 +6,12 @@
     @license: GNU GPL, see COPYING for details.
 """
 
-from MoinMoin.request.CLI import Request
 import MoinMoin.events as events
+import MoinMoin.events.notification as notification
 
 def test_get_handlers(request):
     """Test if there are any event handlers. There should be some internal ones"""
-    
+
     assert events.get_handlers(request.cfg)
 
 def test_send_event(request):
@@ -20,13 +20,14 @@
     return_string = u"test_send_event"
     
     def event_handler(event):
-        return return_string
+        return notification.Failure("Just a test")
     
     request.cfg.event_handlers = [event_handler]
     event = events.Event(request)
     
-    print "A proper event handler should be called, and an 1-element list of messages returned"
-    assert events.send_event(event)[0] == return_string
+    print "A proper event handler must be called and an 1-element list of results returned"
+    results = events.send_event(event)
+    assert issubclass(results[0].__class__, events.EventResult)
 
 def test_subscribable_events(request):
     """Test if there are any subscribable events. There should be some."""
--- a/MoinMoin/action/AttachFile.py	Fri Jun 22 19:00:44 2007 +0200
+++ b/MoinMoin/action/AttachFile.py	Sat Jun 23 00:01:56 2007 +0200
@@ -222,8 +222,16 @@
         _addLogEntry(request, 'ATTNEW', pagename, target)
         
         event = FileAttachedEvent(request, pagename, target, len(filecontent))
-        messages = send_event(event)
-        msg = "".join(messages)
+        results = events.send_event(event)    
+        
+        recipients = []
+        for result in results:
+            if isinstance(results, notification.Success):
+                recipients.append(result.recipient)
+                
+        if recipients:
+            info = _("Notifications sent to:")
+            msg = msg + "<p>%s %s</p>" % (info, ",".join(recipients))
 
         if request.cfg.xapian_search:
             from MoinMoin.search.Xapian import Index
--- a/MoinMoin/events/__init__.py	Fri Jun 22 19:00:44 2007 +0200
+++ b/MoinMoin/events/__init__.py	Sat Jun 23 00:01:56 2007 +0200
@@ -120,6 +120,10 @@
         Event.__init__(self, request)
         self.user = user
         
+class EventResult:
+    """ This is a base class for messages passed from event handlers """
+    pass
+        
 def get_handlers(cfg):
     """Create a list of available event handlers.
     
@@ -158,7 +162,7 @@
     # Try to handle the event with each available handler (for now)
     for handle in cfg.event_handlers:
         retval = handle(event)
-        if isinstance(retval, unicode):
+        if retval:
             msg.append(retval)
             
     return msg
--- a/MoinMoin/events/emailnotify.py	Fri Jun 22 19:00:44 2007 +0200
+++ b/MoinMoin/events/emailnotify.py	Sat Jun 23 00:01:56 2007 +0200
@@ -9,11 +9,16 @@
     @license: GNU GPL, see COPYING for details.
 """
 
+try:
+    set
+except:
+    from sets import Set as set
+
 from MoinMoin import user
 from MoinMoin.Page import Page
 from MoinMoin.mail import sendmail
 from MoinMoin.events import *
-from MoinMoin.events.messages import page_change_message
+import MoinMoin.events.notification as notification
 
 
 def send_notification(request, page, comment, emails, email_lang, revisions, trivial):
@@ -28,7 +33,7 @@
     @return: sendmail result
     """
     _ = request.getText
-    mailBody = page_change_message("page_changed", request, page, email_lang, 
+    mailBody = notification.page_change_message("page_changed", request, page, email_lang, 
                                    comment=comment, revisions=revisions)
 
     return sendmail.sendmail(request, emails,
@@ -53,32 +58,23 @@
     subscribers = page.getSubscribers(request, return_users=1, trivial=trivial)
     
     if subscribers:
+        recipients = set()
+        
         # get a list of old revisions, and append a diff
         revisions = page.getRevList()
 
         # send email to all subscribers
-        results = [_('Status of sending notification mails:')]
         for lang in subscribers:
             emails = [u.email for u in subscribers[lang]]
             names = [u.name for u in subscribers[lang]]
-            mailok, status = send_notification(request, page, comment, emails, lang, revisions, trivial)
-            recipients = ", ".join(names)
-            results.append(_('[%(lang)s] %(recipients)s: %(status)s') % {
-                'lang': lang, 'recipients': recipients, 'status': status})
-
-        # Return mail sent results. Ignore trivial - we don't have
-        # to lie. If mail was sent, just tell about it.
-        return '<p>\n%s\n</p> ' % '<br>'.join(results)
-
-    # No mail sent, no message.
-    return ''
+            result = send_notification(request, page, comment, emails, lang, revisions, trivial)
+            if result:
+                recipients.update(names)
+    
+        if recipients:
+            return notification.Success(recipients)
 
 
 def handle(event):
-    if not isinstance(event, PageChangedEvent):
-        return
-
-    if not event.request.cfg.mail_enabled:
-        return
-    
-    return notify_subscribers(event.request, event.page, event.comment, event.trivial)
+    if isinstance(event, PageChangedEvent) and event.request.cfg.mail_enabled:
+        return notify_subscribers(event.request, event.page, event.comment, event.trivial)
--- a/MoinMoin/events/jabbernotify.py	Fri Jun 22 19:00:44 2007 +0200
+++ b/MoinMoin/events/jabbernotify.py	Sat Jun 23 00:01:56 2007 +0200
@@ -10,13 +10,18 @@
 
 import xmlrpclib
 
+try:
+    set
+except:
+    from sets import Set as set
+    
 from MoinMoin import error
 from MoinMoin.Page import Page
 from MoinMoin.user import User, getUserList
-from MoinMoin.events.messages import page_change_message
+import MoinMoin.events.notification as notification
 
 import MoinMoin.events as ev
-
+    
 
 def handle(event):
     cfg = event.request.cfg
@@ -55,11 +60,9 @@
             server.removeJIDFromRoster(request.cfg.secret, event.jid)        
                 
     except xmlrpclib.Error, err:
-        print _("XML RPC error: "), str(err)
-        return (0, _("Notifications not sent"))
+        print _("XML RPC error: %s") % (str(err),)
     except Exception, err:
-        print _("Low-level communication error: "), str(err)
-        return (0, _("Notifications not sent"))
+        print _("Low-level communication error: $s") % (str(err),)
 
 
 def _filter_subscriber_list(event, subscribers):
@@ -92,7 +95,8 @@
     subscribers = page.getSubscribers(request, return_users=1)
     _filter_subscriber_list(event, subscribers)
     
-    page_change("attachment_added", request, page, subscribers, attach_name=event.attachment_name, attach_size=event.size)
+    return page_change("attachment_added", request, page, subscribers, \
+                       attach_name=event.attachment_name, attach_size=event.size)
 
         
 def handle_page_changed(event):
@@ -103,7 +107,8 @@
     
     subscribers = page.getSubscribers(request, return_users=1, trivial=event.trivial)    
     _filter_subscriber_list(event, subscribers)
-    page_change("page_changed", request, page, subscribers, revisions=page.getRevList(), comment=event.comment)
+    return page_change("page_changed", request, page, subscribers, \
+                       revisions=page.getRevList(), comment=event.comment)
     
 
 def handle_page_deleted(event):
@@ -115,7 +120,7 @@
     
     subscribers = page.getSubscribers(request, return_users=1)
     _filter_subscriber_list(event, subscribers)
-    page_change("page_deleted", request, page, subscribers)
+    return page_change("page_deleted", request, page, subscribers)
 
 
 def handle_user_created(event):
@@ -137,56 +142,42 @@
         # Currently send this only to super users
         # TODO: make it possible to disable this notification
         if usr.isSuperUser() and usr.jid and event_name in usr.subscribed_events:
-            jids.append(usr.jid)
-            
-    send_notification(event.request, jids, msg % (event.user.name, email))
+            send_notification(event.request, [usr.jid], msg % (event.user.name, email))
     
 
 def page_change(type, request, page, subscribers, **kwargs):
-    
+    """Sends notification about page being changed in some way"""
     _ = request.getText
     
+    # send notifications to all subscribers
     if subscribers:
-        # send notifications to all subscribers
-        results = [_('Status of sending notifications:')]
+        recipients = set()
+        
         for lang in subscribers:
             jids = [u.jid for u in subscribers[lang] if u.jid]
-            names = [u.name for u in subscribers[lang]]
-            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') % {
-                'lang': lang, 'recipients': recipients, 'status': status})
+            names = [u.name for u in subscribers[lang] if u.jid]
+            msg = notification.page_change_message(type, request, page, lang, **kwargs)
+            result = send_notification(request, jids, msg)
 
-        # 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 ''
+            if result:
+                recipients.update(names)
+        
+        if recipients:
+            return notification.Success(recipients)
 
 def send_notification(request, jids, message):
     """ Send notifications for a single language.
 
     @param comment: editor's comment given when saving the page
-    @param jids: list of Jabber IDs
-    @param message_lang: language of notification
-    @param revisions: revisions of this page (newest first!)
-    @param trivial: the change is marked as trivial
+    @param jids: an iterable of Jabber IDs to send the message to
     """
     _ = request.getText
     server = request.cfg.notification_server
     
-    for jid in jids:
-                
-        # FIXME: stops sending notifications on first error
-        try:
-            server.send_notification(request.cfg.secret, jid, message)
-        except xmlrpclib.Error, err:
-            print _("XML RPC error: "), str(err)
-            return (0, _("Notifications not sent"))
-        except Exception, err:
-            print _("Low-level communication error: "), str(err)
-            return (0, _("Notifications not sent"))
-        
-    return (1, _("Notifications sent OK"))
+    try:
+        server.send_notification(request.cfg.secret, jids, message)
+        return True
+    except xmlrpclib.Error, err:
+        print _("XML RPC error: %s") % (str(err),)
+    except Exception, err:
+        print _("Low-level communication error: %s") % (str(err),)