diff --git a/calsocial/models.py b/calsocial/models.py index 8c05c4a..71a8828 100644 --- a/calsocial/models.py +++ b/calsocial/models.py @@ -326,14 +326,37 @@ class Profile(db.Model): # pylint: disable=too-few-public-methods user_follow = UserFollow(follower=follower, followed=self, accepted_at=datetime.utcnow()) db.session.add(user_follow) - notification = Notification(profile=self, - actor=follower, - item=self, - action=NotificationAction.follow) + notification = self.notify(follower, self, NotificationAction.follow) + db.session.add(notification) return user_follow + def notify(self, actor, item, action): + """Notify this profile about ``action`` on ``item`` by ``actor`` + + :param actor: the actor who generated the notification + :type actor: Profile + :param item: the item ``action`` was performed on + :type item: any + :param action: the type of the action + :type action: NotificationAction, str + :raises TypeError: if ``actor`` is not a `Profile` object + :returns: the generated notification. It is already added to the database session, but + not committed + :rtype: Notification + """ + + if not isinstance(actor, Profile): + raise TypeError('actor must be a Profile instance') + + if isinstance(action, str): + action = NotificationAction[action] + + notification = Notification(profile=self, actor=actor, item=item, action=action) + + return notification + class Event(db.Model): """Database model for events @@ -426,10 +449,7 @@ class Event(db.Model): invite = Invitation(event=self, sender=inviter, invitee=invited) db.session.add(invite) - notification = Notification(profile=invited, - actor=inviter, - item=self, - action=NotificationAction.invite) + notification = invited.notify(inviter, self, NotificationAction.invite) db.session.add(notification) return invite