##// END OF EJS Templates
fixed fork journal entry
fixed fork journal entry

File last commit:

r1723:64e91067 beta
r1730:ce0b4753 beta
Show More
notification.py
201 lines | 7.1 KiB | text/x-python | PythonLexer
#302 - basic notification system, models+tests
r1702 # -*- coding: utf-8 -*-
"""
rhodecode.model.notification
~~~~~~~~~~~~~~
Model for notifications
:created_on: Nov 20, 2011
:author: marcink
:copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
:license: GPLv3, see COPYING for more details.
"""
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
Notification fixes...
r1717 import os
#302 - basic notification system, models+tests
r1702 import logging
import traceback
Notification fixes...
r1717 import datetime
#302 - basic notification system, models+tests
r1702
from pylons.i18n.translation import _
- refactoring to overcome poor usage of global pylons config...
r1723 import rhodecode
Notification fixes...
r1717 from rhodecode.lib import helpers as h
#302 - basic notification system, models+tests
r1702 from rhodecode.model import BaseModel
from rhodecode.model.db import Notification, User, UserNotification
Notification system improvements...
r1712 log = logging.getLogger(__name__)
#302 - basic notification system, models+tests
r1702
notification to commit author + gardening
r1716
#302 - basic notification system, models+tests
r1702 class NotificationModel(BaseModel):
Notification system improvements...
r1712 def __get_user(self, user):
notification to commit author + gardening
r1716 if isinstance(user, basestring):
Notification system improvements...
r1712 return User.get_by_username(username=user)
else:
notification to commit author + gardening
r1716 return self._get_instance(User, user)
Notification system improvements...
r1712
def __get_notification(self, notification):
if isinstance(notification, Notification):
return notification
elif isinstance(notification, int):
return Notification.get(notification)
else:
if notification:
raise Exception('notification must be int or Instance'
' of Notification got %s' % type(notification))
notification fixes and improvements
r1703 def create(self, created_by, subject, body, recipients,
type_=Notification.TYPE_MESSAGE):
"""
Creates notification of given type
:param created_by: int, str or User instance. User who created this
notification
:param subject:
:param body:
:param recipients: list of int, str or User objects
:param type_: type of notification
"""
#235 forking page repo group selection...
r1722 from rhodecode.lib.celerylib import tasks, run_task
#302 - basic notification system, models+tests
r1702
if not getattr(recipients, '__iter__', False):
raise Exception('recipients must be a list of iterable')
Notification system improvements...
r1712 created_by_obj = self.__get_user(created_by)
#302 - basic notification system, models+tests
r1702
notification fixes and improvements
r1703 recipients_objs = []
for u in recipients:
notification to commit author + gardening
r1716 obj = self.__get_user(u)
if obj:
recipients_objs.append(obj)
Notification system improvements...
r1712 recipients_objs = set(recipients_objs)
Notification fixes...
r1717
notif = Notification.create(created_by=created_by_obj, subject=subject,
body=body, recipients=recipients_objs,
type_=type_)
# send email with notification
for rec in recipients_objs:
email_subject = NotificationModel().make_description(notif, False)
type_ = EmailNotificationModel.TYPE_CHANGESET_COMMENT
email_body = body
email_body_html = EmailNotificationModel()\
.get_email_tmpl(type_, **{'subject':subject,
'body':h.rst(body)})
#235 forking page repo group selection...
r1722 run_task(tasks.send_email, rec.email, email_subject, email_body,
Notification fixes...
r1717 email_body_html)
return notif
#302 - basic notification system, models+tests
r1702
Tests updates, Session refactoring
r1713 def delete(self, user, notification):
# we don't want to remove actual notification just the assignment
Notification system improvements...
r1712 try:
Tests updates, Session refactoring
r1713 notification = self.__get_notification(notification)
user = self.__get_user(user)
if notification and user:
Notification fixes...
r1717 obj = UserNotification.query()\
.filter(UserNotification.user == user)\
.filter(UserNotification.notification
== notification)\
.one()
Tests updates, Session refactoring
r1713 self.sa.delete(obj)
Notification system improvements...
r1712 return True
except Exception:
log.error(traceback.format_exc())
raise
#302 - basic notification system, models+tests
r1702
Tests updates, Session refactoring
r1713 def get_for_user(self, user):
user = self.__get_user(user)
return user.notifications
#302 - basic notification system, models+tests
r1702
Tests updates, Session refactoring
r1713 def get_unread_cnt_for_user(self, user):
user = self.__get_user(user)
#302 - basic notification system, models+tests
r1702 return UserNotification.query()\
Notification system improvements...
r1712 .filter(UserNotification.read == False)\
Tests updates, Session refactoring
r1713 .filter(UserNotification.user == user).count()
#302 - basic notification system, models+tests
r1702
Tests updates, Session refactoring
r1713 def get_unread_for_user(self, user):
user = self.__get_user(user)
#302 - basic notification system, models+tests
r1702 return [x.notification for x in UserNotification.query()\
Notification system improvements...
r1712 .filter(UserNotification.read == False)\
Tests updates, Session refactoring
r1713 .filter(UserNotification.user == user).all()]
Notification system improvements...
r1712
def get_user_notification(self, user, notification):
user = self.__get_user(user)
notification = self.__get_notification(notification)
return UserNotification.query()\
.filter(UserNotification.notification == notification)\
.filter(UserNotification.user == user).scalar()
Notification fixes...
r1717 def make_description(self, notification, show_age=True):
Notification system improvements...
r1712 """
Creates a human readable description based on properties
of notification object
"""
_map = {notification.TYPE_CHANGESET_COMMENT:_('commented on commit'),
notification.TYPE_MESSAGE:_('sent message'),
notification.TYPE_MENTION:_('mentioned you')}
Notification fixes...
r1717 DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
Notification system improvements...
r1712
tmpl = "%(user)s %(action)s %(when)s"
Notification fixes...
r1717 if show_age:
when = h.age(notification.created_on)
else:
DTF = lambda d: datetime.datetime.strftime(d, DATETIME_FORMAT)
when = DTF(notification.created_on)
Notification system improvements...
r1712 data = dict(user=notification.created_by_user.username,
action=_map[notification.type_],
Notification fixes...
r1717 when=when)
Notification system improvements...
r1712 return tmpl % data
Notification fixes...
r1717
class EmailNotificationModel(BaseModel):
TYPE_CHANGESET_COMMENT = 'changeset_comment'
TYPE_PASSWORD_RESET = 'passoword_link'
TYPE_REGISTRATION = 'registration'
TYPE_DEFAULT = 'default'
def __init__(self):
- refactoring to overcome poor usage of global pylons config...
r1723 self._template_root = rhodecode.CONFIG['pylons.paths']['templates'][0]
self._tmpl_lookup = rhodecode.CONFIG['pylons.app_globals'].mako_lookup
Notification fixes...
r1717
self.email_types = {
self.TYPE_CHANGESET_COMMENT:'email_templates/changeset_comment.html',
self.TYPE_PASSWORD_RESET:'email_templates/password_reset.html',
self.TYPE_REGISTRATION:'email_templates/registration.html',
self.TYPE_DEFAULT:'email_templates/default.html'
}
def get_email_tmpl(self, type_, **kwargs):
"""
return generated template for email based on given type
:param type_:
"""
- refactoring to overcome poor usage of global pylons config...
r1723
Notification fixes...
r1717 base = self.email_types.get(type_, self.TYPE_DEFAULT)
- refactoring to overcome poor usage of global pylons config...
r1723 email_template = self._tmpl_lookup.get_template(base)
Notification fixes...
r1717 # translator inject
_kwargs = {'_':_}
_kwargs.update(kwargs)
log.debug('rendering tmpl %s with kwargs %s' % (base, _kwargs))
return email_template.render(**_kwargs)