changeset 2638:6e84127a1860

Finally all known bugs fixed, OOB is used to send links with jabber. More... Changed the way notifications are called. Notification data is now stored in dicts, instead of separate arguments. This helps extensibility if more extensions like OOB Data are to be added in the future. Also fixed some previously missed bugs.
author Karol 'grzywacz' Nowak <grzywacz@sul.uni.lodz.pl>
date Sun, 05 Aug 2007 22:46:04 +0200
parents edf9a449fe9d
children 117e1bee2444
files MoinMoin/events/__init__.py MoinMoin/events/emailnotify.py MoinMoin/events/jabbernotify.py MoinMoin/events/notification.py jabberbot/commands.py jabberbot/xmlrpcbot.py jabberbot/xmppbot.py
diffstat 7 files changed, 95 insertions(+), 63 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/events/__init__.py	Fri Aug 03 17:25:27 2007 +0200
+++ b/MoinMoin/events/__init__.py	Sun Aug 05 22:46:04 2007 +0200
@@ -115,11 +115,11 @@
     description = _(u"""A new attachment has been added""")
     req_superuser = False
 
-    def __init__(self, request, pagename, name, size):
+    def __init__(self, request, pagename, filename, size):
         PageEvent.__init__(self, request)
         self.request = request
         self.pagename = pagename
-        self.name = name
+        self.filename = filename
         self.size = size
 
 
--- a/MoinMoin/events/emailnotify.py	Fri Aug 03 17:25:27 2007 +0200
+++ b/MoinMoin/events/emailnotify.py	Sun Aug 05 22:46:04 2007 +0200
@@ -14,6 +14,8 @@
 from MoinMoin.mail import sendmail
 from MoinMoin.support.python_compatibility import set
 from MoinMoin.user import User, getUserList
+from MoinMoin.action.AttachFile import getAttachUrl
+
 import MoinMoin.events as ev
 import MoinMoin.events.notification as notification
 
@@ -63,7 +65,6 @@
     @return: message, indicating success or errors.
 
     """
-    _ = request.getText
     subscribers = page.getSubscribers(request, return_users=1, trivial=trivial)
     mail_from = page.cfg.mail_from
 
@@ -117,7 +118,6 @@
     """Sends an email to super users that have subscribed to this event type"""
 
     names = set()
-    _ = event.request.getText
     event_name = event.name
     from_address = event.request.cfg.mail_from
     request = event.request
@@ -125,19 +125,28 @@
 
     subscribers = page.getSubscribers(request, return_users=1)
     notification.filter_subscriber_list(event, subscribers, False)
-    data = notification.attachment_added(request, event.pagename, event.name, event.size)
+    recipients = []
+
+    for lang in subscribers:
+        recipients.extend(subscribers[lang])
+
+    attachlink = request.getBaseURL() + getAttachUrl(event.pagename, event.filename, request)
+    pagelink = request.getQualifiedURL(page.url(request, {}, relative=False))
 
     for lang in subscribers:
         emails = []
+        _ = lambda text: request.getText(text, lang=lang, formatted=False)
 
-        for usr in subscribers[lang]:
-            if usr.email and event_name in usr.email_subscribed_events:
-                emails.append(usr.email)
-            else:
-                continue
+        links = _("Attachment link: %(attach)s\n" \
+                  "Page link: %(page)s\n") % {'attach': attachlink, 'page': pagelink}
 
-            if send_notification(request, from_address, emails, data):
-                names.update(usr.name)
+        data = notification.attachment_added(request, _, event.pagename, event.filename, event.size)
+        data['body'] = data['body'] + links
+
+        emails = [usr.email for usr in subscribers[lang]]
+
+        if send_notification(request, from_address, emails, data):
+            names.update(recipients)
 
     return notification.Success(names)
 
--- a/MoinMoin/events/jabbernotify.py	Fri Aug 03 17:25:27 2007 +0200
+++ b/MoinMoin/events/jabbernotify.py	Sun Aug 05 22:46:04 2007 +0200
@@ -14,6 +14,8 @@
 from MoinMoin.Page import Page
 from MoinMoin.user import User, getUserList
 from MoinMoin.support.python_compatibility import set
+from MoinMoin.action.AttachFile import getAttachUrl
+
 import MoinMoin.events.notification as notification
 import MoinMoin.events as ev
 
@@ -69,22 +71,26 @@
     request = event.request
     page = Page(request, event.pagename)
     event_name = event.name
-
     subscribers = page.getSubscribers(request, return_users=1)
     notification.filter_subscriber_list(event, subscribers, True)
+    recipients = []
+
+    for lang in subscribers:
+        recipients.extend(subscribers[lang])
+
+    attachlink = request.getBaseURL() + getAttachUrl(event.pagename, event.filename, request)
+    pagelink = request.getQualifiedURL(page.url(request, {}, relative=False))
 
     for lang in subscribers.keys():
-        jids = []
-        data = notification.attachment_added(request, event.pagename, event.name, event.size)
+        _ = lambda text: request.getText(text, lang=lang, formatted=False)
+        data = notification.attachment_added(request, _, event.pagename, event.filename, event.size)
+        links = [{'url': attachlink, 'description': _("Attachment link")},
+                  {'url': pagelink, 'description': _("Page link")}]
 
-        for usr in subscribers[lang]:
-            if usr.jid and event_name in usr.jabber_subscribed_events:
-                jids.append(usr.jid)
-            else:
-                continue
+        jids = [usr.jid for usr in subscribers[lang]]
 
-            if send_notification(request, jids, data['body'], data['subject']):
-                names.update(usr.name)
+        if send_notification(request, jids, data['body'], data['subject'], links):
+            names.update(recipients)
 
     return notification.Success(names)
 
@@ -157,7 +163,9 @@
             jids = [u.jid for u in subscribers[lang] if u.jid]
             names = [u.name for u in subscribers[lang] if u.jid]
             msg = notification.page_change_message(change_type, request, page, lang, **kwargs)
-            result = send_notification(request, jids, msg)
+            page_url = request.getQualifiedURL(page.url(request, relative=False))
+            url = {'url': page_url, 'description': _("Changed page")}
+            result = send_notification(request, jids, msg, _("Page changed"), [url])
 
             if result:
                 recipients.update(names)
@@ -172,11 +180,15 @@
     @param message: message text
     @param subject: subject of the message, makes little sense for chats
     @param url_list: a list of dicts containing URLs and their descriptions
+    @type url_list: list
 
     """
     _ = request.getText
     server = request.cfg.notification_server
 
+    if type(url_list) != list:
+        raise ValueError("url_list must be of type list!")
+
     try:
         cmd_data = {'text': message, 'subject': subject, 'url_list': url_list}
         server.send_notification(request.cfg.secret, jids, cmd_data)
--- a/MoinMoin/events/notification.py	Fri Aug 03 17:25:27 2007 +0200
+++ b/MoinMoin/events/notification.py	Sun Aug 05 22:46:04 2007 +0200
@@ -46,6 +46,17 @@
     """ Used to signal an invalid page change event """
     pass
 
+def page_link(request, page, querystr):
+    """Create an absolute url to a given page with optional action
+
+    @param page: a page to link to
+    @type page: MoinMoin.Page.Page
+    @param querystr: a dict passed to wikiutil.makeQueryString
+
+    """
+    query = wikiutil.makeQueryString(querystr, True)
+    return request.getQualifiedURL(page.url(request, query, relative=False))
+
 def page_change_message(msgtype, request, page, lang, **kwargs):
     """Prepare a notification text for a page change of given type
 
@@ -70,15 +81,14 @@
                     'rev2': str(revisions[0]),
                     'rev1': str(revisions[1])}
 
-    pagelink = request.getQualifiedURL(page.url(request, querystr, relative=False))
+    pagelink = page_link(request, page, querystr)
 
     if msgtype == "page_changed":
         msg_body = _("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) % {
+        'The "%(pagename)s" page has been changed by %(editor)s:\n\n', formatted=False) % {
+            'pagename': page.page_name,
             'editor': page.uid_override or user.getUserIdentification(request),
-            'pagelink': pagelink,
             'sitename': page.cfg.sitename or request.getBaseURL(),
         }
 
@@ -98,20 +108,19 @@
     elif msgtype == "page_deleted":
         msg_body = _("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) % {
+            'The page "%(pagename)" has been deleted by %(editor)s:\n\n', formatted=False) % {
+                'pagename': page.page_name,
                 'editor': page.uid_override or user.getUserIdentification(request),
-                'pagelink': pagelink,
                 'sitename': page.cfg.sitename or request.getBaseURL(),
         }
 
     elif msgtype == "page_renamed":
         msg_body = _("Dear wiki user,\n\n"
             'You have subscribed to a wiki page "%(sitename)s" for change notification.\n\n'
-            "The following page has been renamed from %(oldname)s by %(editor)s:\n"
-            "%(pagelink)s\n\n", formatted=False) % {
+            'The page "%(pagename)" has been renamed from %(oldname)s by %(editor)s:\n',
+            formatted=False) % {
                 'editor': page.uid_override or user.getUserIdentification(request),
-                'pagelink': pagelink,
+                'pagename': page.page_name,
                 'sitename': page.cfg.sitename or request.getBaseURL(),
                 'oldname': kwargs['old_name']
         }
@@ -120,7 +129,8 @@
 
     if 'comment' in kwargs and kwargs['comment']:
         msg_body = msg_body + \
-            _("The comment on the change is:\n%(comment)s", formatted=False) % {'comment': kwargs['comment']}
+            _("The comment on the change is:\n%(comment)s",
+              formatted=False) % {'comment': kwargs['comment']}
 
     return msg_body
 
@@ -141,17 +151,14 @@
 
     return {'subject': subject, 'body': body}
 
-def attachment_added(request, page_name, attach_name, attach_size):
+def attachment_added(request, _, page_name, attach_name, attach_size):
     """Formats a message used to notify about new attachments
 
+    @param _: a gettext function
     @return: a dict containing message body and subject
-    """
-    from MoinMoin.action.AttachFile import getAttachUrl
 
-    _ = request.getText
+    """
     page = Page(request, page_name)
-    attachlink = request.getBaseURL() + getAttachUrl(page_name, attach_name, request)
-    pagelink = request.getQualifiedURL(page.url(request, {}, relative=False))
 
     subject = _("New attachment added to page %(pagename)s on %(sitename)s") % {
                 'pagename': page_name,
@@ -163,14 +170,11 @@
     "An attachment has been added to that page by %(editor)s. "
     "Following detailed information is available:\n\n"
     "Attachment name: %(attach_name)s\n"
-    "Attachment size: %(attach_size)s\n"
-    "Download link: %(attach_get)s", formatted=False) % {
+    "Attachment size: %(attach_size)s\n") % {
         'editor': user.getUserIdentification(request),
-        'pagelink': pagelink,
         'page_name': page_name,
         'attach_name': attach_name,
         'attach_size': attach_size,
-        'attach_get': attachlink,
     }
 
     return {'body': body, 'subject': subject}
--- a/jabberbot/commands.py	Fri Aug 03 17:25:27 2007 +0200
+++ b/jabberbot/commands.py	Sun Aug 05 22:46:04 2007 +0200
@@ -42,12 +42,15 @@
         """Translate the message using a provided gettext function
 
         @param gettext_func: a unary gettext function
-        @return: translated message
+        @return: translated message and subject
+        @rtype: tuple
         """
         if self.notification.has_key('data'):
-            return gettext_func(self.notification['text']) % self.notification['data']
+            msg =  gettext_func(self.notification['text']) % self.notification['data']
         else:
-            return gettext_func(self.notification['text'])
+            msg = gettext_func(self.notification['text'])
+
+        return (msg, gettext_func(self.notification.get('subject', '')))
 
 class AddJIDToRosterCommand:
     """Class representing a request to add a new jid to roster"""
--- a/jabberbot/xmlrpcbot.py	Fri Aug 03 17:25:27 2007 +0200
+++ b/jabberbot/xmlrpcbot.py	Sun Aug 05 22:46:04 2007 +0200
@@ -306,10 +306,15 @@
     def send_notification(self, jids, notification):
         """Instructs the XMPP component to send a notification
 
+        The notification dict has following entries:
+        'text' - notification text (REQUIRED)
+        'subject' - notification subject
+        'url_list' - a list of dicts describing attached URLs
+
         @param jids: a list of JIDs to send a message to (bare JIDs)
         @type jids: a list of str or unicode
-        @param text: a message body
-        @type text: unicode
+        @param notification: dictionary with notification data
+        @type notification: dict
 
         """
         command = cmd.NotificationCommand(jids, notification, async=True)
--- a/jabberbot/xmppbot.py	Fri Aug 03 17:25:27 2007 +0200
+++ b/jabberbot/xmppbot.py	Sun Aug 05 22:46:04 2007 +0200
@@ -256,29 +256,32 @@
         """
         # Handle normal notifications
         if isinstance(command, cmd.NotificationCommand):
+            cmd_data = command.notification
+
             for recipient in command.jids:
                 jid = JID(recipient)
                 jid_text = jid.bare().as_utf8()
 
-                _ = self.get_text(jid_text)
-                text = command.notification['text']
+                text = cmd_data['text']
+                subject = cmd_data.get('subject', '')
+                msg_data = command.notification
 
                 if isinstance(command, cmd.NotificationCommandI18n):
                     # Translate&interpolate the message with data
-                    gettext_func = self.get_text(recipient)
-                    text = command.translate(gettext_func)
+                    gettext_func = self.get_text(jid_text)
+                    text, subject = command.translate(gettext_func)
+                    msg_data = {'text': text, 'subject': subject,
+                                'url_list': cmd_data.get('url_list', [])}
 
                 # Check if contact is DoNotDisturb.
                 # If so, queue the message for delayed delivery.
-                try:
-                    contact = self.contacts[jid_text]
+                contact = self.contacts.get(jid_text, '')
+                if contact:
                     if command.async and contact.is_dnd() and not ignore_dnd:
                         contact.messages.append(command)
                         return
-                except KeyError:
-                    pass
 
-                self.send_message(jid, command.notification, command.msg_type)
+                self.send_message(jid, msg_data, command.msg_type)
 
             return
 
@@ -369,11 +372,7 @@
         @type jid: pyxmpp.jid.JID
 
         """
-        if data.has_key('subject'):
-            subject = data['subject']
-        else:
-            subject = ''
-
+        subject = data.get('subject', '')
         message = Message(to_jid=jid, body=data['text'], stanza_type=msg_type, subject=subject)
 
         if data.has_key('url_list'):