]> git.openstreetmap.org Git - osqa.git/blobdiff - forum/subscriptions.py
Allow for missing content types
[osqa.git] / forum / subscriptions.py
index 4c5725650994f45c2dbc9d8579fc5db812c2884f..fad24a5c95fa3a16e38548263f8407e0e39c3e1f 100644 (file)
-import os\r
-import re\r
-import datetime\r
-from forum.models import User, Question, Comment, QuestionSubscription, SubscriptionSettings, Answer\r
-from forum.models.user import activity_record\r
-from forum.utils.mail import send_email\r
-from forum.views.readers import question_view\r
-from django.utils.translation import ugettext as _\r
-from django.conf import settings\r
-from django.db.models import Q, F\r
-from django.db.models.signals import post_save\r
-from django.contrib.contenttypes.models import ContentType\r
-import const\r
-\r
-def create_subscription_if_not_exists(question, user):\r
-    try:\r
-        subscription = QuestionSubscription.objects.get(question=question, user=user)\r
-    except:\r
-        subscription = QuestionSubscription(question=question, user=user)\r
-        subscription.save()\r
-\r
-def apply_default_filters(queryset, excluded_id):\r
-    return queryset.values('email', 'username').exclude(id=excluded_id)\r
-\r
-def create_recipients_dict(usr_list):\r
-    return [(s['username'], s['email'], {'username': s['username']}) for s in usr_list]\r
-\r
-def question_posted(instance, created, **kwargs):\r
-    if not created: return\r
-\r
-    question = instance\r
-\r
-    subscribers = User.objects.values('email', 'username').filter(\r
-            Q(subscription_settings__enable_notifications=True, subscription_settings__new_question='i') |\r
-            (Q(subscription_settings__new_question_watched_tags='i') &\r
-              Q(marked_tags__name__in=question.tagnames.split(' ')) &\r
-              Q(tag_selections__reason='good'))\r
-    ).exclude(id=question.author.id).distinct()\r
-\r
-    recipients = create_recipients_dict(subscribers)\r
-\r
-    send_email(settings.EMAIL_SUBJECT_PREFIX + _("New question on %(app_name)s") % dict(app_name=settings.APP_SHORT_NAME),\r
-               recipients, "notifications/newquestion.html", {\r
-        'question': question,\r
-    })\r
-\r
-    if question.author.subscription_settings.questions_asked:\r
-        subscription = QuestionSubscription(question=question, user=question.author)\r
-        subscription.save()\r
-\r
-    new_subscribers = User.objects.filter(\r
-            Q(subscription_settings__all_questions=True) |\r
-            Q(subscription_settings__all_questions_watched_tags=True,\r
-                    marked_tags__name__in=question.tagnames.split(' '),\r
-                    tag_selections__reason='good'))\r
-\r
-    for user in new_subscribers:\r
-        create_subscription_if_not_exists(question, user)\r
-\r
-#post_save.connect(question_posted, sender=Question)\r
-\r
-\r
-def answer_posted(instance, created, **kwargs):\r
-    if not created: return\r
-\r
-    answer = instance\r
-    question = answer.question\r
-\r
-    subscribers = question.subscribers.values('email', 'username').filter(\r
-            subscription_settings__enable_notifications=True,\r
-            subscription_settings__notify_answers=True,\r
-            subscription_settings__subscribed_questions='i'\r
-    ).exclude(id=answer.author.id).distinct()\r
-    recipients = create_recipients_dict(subscribers)\r
-\r
-    send_email(settings.EMAIL_SUBJECT_PREFIX + _("New answer to '%(question_title)s'") % dict(question_title=question.title),\r
-               recipients, "notifications/newanswer.html", {\r
-        'question': question,\r
-        'answer': answer\r
-    })\r
-\r
-    if answer.author.subscription_settings.questions_answered:\r
-        create_subscription_if_not_exists(question, answer.author)\r
-\r
-post_save.connect(answer_posted, sender=Answer)\r
-\r
-\r
-def comment_posted(sender, instance, **kwargs):\r
-    comment = instance.content_object\r
-    post = comment.content_object\r
-\r
-    if post.__class__ == Question:\r
-        question = post\r
-    else:\r
-        question = post.question\r
-\r
-    subscribers = question.subscribers.values('email', 'username')\r
-\r
-    q_filter = Q(subscription_settings__notify_comments=True) | Q(subscription_settings__notify_comments_own_post=True, id=post.author.id)\r
-\r
-    inreply = re.search('@\w+', comment.comment)\r
-    if inreply is not None:\r
-        q_filter = q_filter | Q(subscription_settings__notify_reply_to_comments=True,\r
-                                username__istartswith=inreply.group(0)[1:],\r
-                                comments__object_id=post.id,\r
-                                comments__content_type=ContentType.objects.get_for_model(post.__class__)\r
-                                )\r
-\r
-    subscribers = subscribers.filter(\r
-            q_filter, subscription_settings__subscribed_questions='i', subscription_settings__enable_notifications=True \r
-    ).exclude(id=comment.user.id).distinct()\r
-\r
-    recipients = create_recipients_dict(subscribers)\r
-\r
-    send_email(settings.EMAIL_SUBJECT_PREFIX + _("New comment on %(question_title)s") % dict(question_title=question.title),\r
-               recipients, "notifications/newcomment.html", {\r
-                'comment': comment,\r
-                'post': post,\r
-                'question': question,\r
-    })\r
-\r
-    if comment.user.subscription_settings.questions_commented:\r
-        create_subscription_if_not_exists(question, comment.user)\r
-\r
-activity_record.connect(comment_posted, sender=const.TYPE_ACTIVITY_COMMENT_QUESTION, weak=False)\r
-activity_record.connect(comment_posted, sender=const.TYPE_ACTIVITY_COMMENT_ANSWER, weak=False)\r
-\r
-\r
-def answer_accepted(instance, created, **kwargs):\r
-    if not created and 'accepted' in instance.get_dirty_fields() and instance.accepted:\r
-        question = instance.question\r
-\r
-        subscribers = question.subscribers.values('email', 'username').filter(\r
-                subscription_settings__enable_notifications=True,\r
-                subscription_settings__notify_accepted=True,\r
-                subscription_settings__subscribed_questions='i'\r
-        ).exclude(id=instance.accepted_by.id).distinct()\r
-        recipients = create_recipients_dict(subscribers)\r
-\r
-        send_email(settings.EMAIL_SUBJECT_PREFIX + _("An answer to '%(question_title)s' was accepted") % dict(question_title=question.title),\r
-                   recipients, "notifications/answeraccepted.html", {\r
-            'question': question,\r
-            'answer': instance\r
-        })\r
-\r
-post_save.connect(answer_accepted, sender=Answer)\r
-\r
-\r
-def member_joined(sender, instance, created, **kwargs):\r
-    if not created:\r
-        return\r
-        \r
-    subscribers = User.objects.values('email', 'username').filter(\r
-            subscription_settings__enable_notifications=True,\r
-            subscription_settings__member_joins='i'\r
-    ).exclude(id=instance.id).distinct()\r
-\r
-    recipients = create_recipients_dict(subscribers)\r
-\r
-    send_email(settings.EMAIL_SUBJECT_PREFIX + _("%(username)s is a new member on %(app_name)s") % dict(username=instance.username, app_name=settings.APP_SHORT_NAME),\r
-               recipients, "notifications/newmember.html", {\r
-        'newmember': instance,\r
-    })\r
-\r
-    sub_settings = SubscriptionSettings(user=instance)\r
-    sub_settings.save()\r
-\r
-post_save.connect(member_joined, sender=User, weak=False)\r
-\r
-def question_viewed(instance, user, **kwargs):\r
-    if not user.is_authenticated():\r
-        return\r
-        \r
-    try:\r
-        subscription = QuestionSubscription.objects.get(question=instance, user=user)\r
-        subscription.last_view = datetime.datetime.now()\r
-        subscription.save()\r
-    except:\r
-        if user.subscription_settings.questions_viewed:\r
-            subscription = QuestionSubscription(question=instance, user=user)\r
-            subscription.save()\r
-\r
-question_view.connect(question_viewed)\r
-\r
-#todo: this stuff goes temporarily here\r
-from forum.models import Award, Answer\r
-\r
-def notify_award_message(instance, created, **kwargs):\r
-    if created:\r
-        user = instance.user\r
-\r
-        msg = (u"Congratulations, you have received a badge '%s'. " \\r
-                + u"Check out <a href=\"%s\">your profile</a>.") \\r
-                % (instance.badge.name, user.get_profile_url())\r
-\r
-        user.message_set.create(message=msg)\r
-\r
-post_save.connect(notify_award_message, sender=Award)\r
-\r
-#todo: translate this\r
-record_answer_event_re = re.compile("You have received (a|\d+) .*new response.*")\r
-def record_answer_event(instance, created, **kwargs):\r
-    if created:\r
-        q_author = instance.question.author\r
-        found_match = False\r
-        #print 'going through %d messages' % q_author.message_set.all().count()\r
-        for m in q_author.message_set.all():\r
-            #print m.message\r
-            match = record_answer_event_re.search(m.message)\r
-            if match:\r
-                found_match = True\r
-                try:\r
-                    cnt = int(match.group(1))\r
-                except:\r
-                    cnt = 1\r
-                m.message = u"You have received %d <a href=\"%s?sort=responses\">new responses</a>."\\r
-                            % (cnt+1, q_author.get_profile_url())\r
-\r
-                m.save()\r
-                break\r
-        if not found_match:\r
-            msg = u"You have received a <a href=\"%s?sort=responses\">new response</a>."\\r
-                    % q_author.get_profile_url()\r
-\r
-            q_author.message_set.create(message=msg)\r
-\r
-post_save.connect(record_answer_event, sender=Answer)
\ No newline at end of file
+import os
+import re
+import datetime
+import logging
+from forum.models import User, Question, Comment, QuestionSubscription, SubscriptionSettings, Answer
+from forum.utils.mail import send_template_email
+from django.utils.translation import ugettext as _
+from forum.actions import AskAction, AnswerAction, CommentAction, AcceptAnswerAction, UserJoinsAction, QuestionViewAction
+from forum import settings
+from django.db.models import Q, F
+
+def create_subscription_if_not_exists(question, user):
+    try:
+        subscription = QuestionSubscription.objects.get(question=question, user=user)
+        return subscription
+    except QuestionSubscription.MultipleObjectsReturned:
+        pass
+    except QuestionSubscription.DoesNotExist:
+        subscription = QuestionSubscription(question=question, user=user)
+        subscription.save()
+        return subscription
+    except Exception, e:
+        logging.error(e)
+
+    return False
+
+def filter_subscribers(subscribers):
+    subscribers = subscribers.exclude(is_active=False)
+
+    if settings.DONT_NOTIFY_UNVALIDATED:
+        return subscribers.exclude(email_isvalid=False)
+    else:
+        return subscribers
+
+def question_posted(action, new):
+    question = action.node
+
+    if not question.is_notifiable:
+        return
+
+    subscribers = User.objects.filter(
+            Q(subscription_settings__enable_notifications=True, subscription_settings__new_question='i') |
+            (Q(subscription_settings__new_question_watched_tags='i') &
+              Q(marked_tags__name__in=question.tagnames.split(' ')) &
+              Q(tag_selections__reason='good'))
+    ).exclude(id=question.author.id).distinct()
+
+    subscribers = filter_subscribers(subscribers)
+
+    send_template_email(subscribers, "notifications/newquestion.html", {'question': question})
+
+    subscription = QuestionSubscription(question=question, user=question.author)
+    subscription.save()
+
+    new_subscribers = User.objects.filter(
+            Q(subscription_settings__all_questions=True) |
+            Q(subscription_settings__all_questions_watched_tags=True,
+                    marked_tags__name__in=question.tagnames.split(' '),
+                    tag_selections__reason='good'))
+
+    for user in new_subscribers:
+        create_subscription_if_not_exists(question, user)
+
+AskAction.hook(question_posted)
+
+
+def answer_posted(action, new):
+    answer = action.node
+    question = answer.question
+
+    logging.error("Answer posted: %s" % str(answer.is_notifiable))
+
+    if not answer.is_notifiable or not question.is_notifiable:
+        return
+
+    subscribers = question.subscribers.filter(
+            subscription_settings__enable_notifications=True,
+            subscription_settings__notify_answers=True,
+            subscription_settings__subscribed_questions='i'
+    ).exclude(id=answer.author.id).distinct()
+
+    subscribers = filter_subscribers(subscribers)
+
+    send_template_email(subscribers, "notifications/newanswer.html", {'answer': answer})
+
+    create_subscription_if_not_exists(question, answer.author)
+
+AnswerAction.hook(answer_posted)
+
+
+def comment_posted(action, new):
+    comment = action.node
+    post = comment.parent
+
+    if not comment.is_notifiable or not post.is_notifiable:
+        return
+
+    if post.__class__ == Question:
+        question = post
+    else:
+        question = post.question
+
+    q_filter = Q(subscription_settings__notify_comments=True) | Q(subscription_settings__notify_comments_own_post=True, id=post.author.id)
+
+    inreply = re.search('@\w+', comment.comment)
+    if inreply is not None:
+        q_filter = q_filter | Q(subscription_settings__notify_reply_to_comments=True,
+                                username__istartswith=inreply.group(0)[1:],
+                                nodes__parent=post, nodes__node_type="comment")
+
+    subscribers = question.subscribers.filter(
+            q_filter, subscription_settings__subscribed_questions='i', subscription_settings__enable_notifications=True
+    ).exclude(id=comment.user.id).distinct()
+
+    subscribers = filter_subscribers(subscribers)
+
+
+    send_template_email(subscribers, "notifications/newcomment.html", {'comment': comment})
+
+    create_subscription_if_not_exists(question, comment.user)
+
+CommentAction.hook(comment_posted)
+
+
+def answer_accepted(action, new):
+    question = action.node.question
+
+    if not question.is_notifiable:
+        return
+
+    subscribers = question.subscribers.filter(
+            subscription_settings__enable_notifications=True,
+            subscription_settings__subscribed_questions='i'
+    ).exclude(id=action.node.nstate.accepted.by.id).distinct()
+    
+    subscribers = filter_subscribers(subscribers)
+
+    send_template_email(subscribers, "notifications/answeraccepted.html", {'answer': action.node})
+
+AcceptAnswerAction.hook(answer_accepted)
+
+
+def member_joined(action, new):
+    subscribers = User.objects.filter(
+            subscription_settings__enable_notifications=True,
+            subscription_settings__member_joins='i'
+    ).exclude(id=action.user.id).distinct()
+
+    subscribers = filter_subscribers(subscribers)
+
+    send_template_email(subscribers, "notifications/newmember.html", {'newmember': action.user})
+
+UserJoinsAction.hook(member_joined)
+
+def question_viewed(action, new):
+    if not action.viewuser.is_authenticated():
+        return
+
+    try:
+        subscription = QuestionSubscription.objects.get(question=action.node, user=action.viewuser)
+        subscription.last_view = datetime.datetime.now()
+        subscription.save()
+    except:
+        if action.viewuser.subscription_settings.questions_viewed:
+            subscription = QuestionSubscription(question=action.node, user=action.viewuser)
+            subscription.save()
+
+QuestionViewAction.hook(question_viewed)
+
+
+#todo: translate this
+#record_answer_event_re = re.compile("You have received (a|\d+) .*new response.*")
+#def record_answer_event(instance, created, **kwargs):
+#    if created:
+#        q_author = instance.question.author
+#        found_match = False
+#        #print 'going through %d messages' % q_author.message_set.all().count()
+#        for m in q_author.message_set.all():
+##            #print m.message
+# #           match = record_answer_event_re.search(m.message)
+#            if match:
+#                found_match = True
+#                try:
+#                    cnt = int(match.group(1))
+#                except:
+#                    cnt = 1
+##                m.message = u"You have received %d <a href=\"%s?sort=responses\">new responses</a>."\
+# #                           % (cnt+1, q_author.get_profile_url())
+#
+#                m.save()
+#                break
+#        if not found_match:
+#            msg = u"You have received a <a href=\"%s?sort=responses\">new response</a>."\
+#                    % q_author.get_profile_url()
+#
+#            q_author.message_set.create(message=msg)
+#
+#post_save.connect(record_answer_event, sender=Answer)