Skip to content

Commit

Permalink
Email notifications for subscribed topics, issue #37
Browse files Browse the repository at this point in the history
  • Loading branch information
Koarth committed Nov 12, 2014
1 parent 7c199c4 commit fff619e
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 3 deletions.
Binary file modified messageboard/db.sqlite3
Binary file not shown.
14 changes: 13 additions & 1 deletion messageboard/mainsite/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import datetime, timedelta
#from awesome_avatar.fields import AvatarField


Expand All @@ -11,11 +12,22 @@ class UserProfile(models.Model):
user_description = models.CharField(max_length=200, blank=True, default = "")
school = models.CharField(max_length=200, blank=True, default = "", unique=False, null=True)
timejoined = models.DateTimeField(default=timezone.now)

# Time between subscription notifications
notification_delay = models.FloatField(default=timedelta(seconds=21600).total_seconds())

# Time since being notified about a subscription
last_notified = models.DateTimeField(default=(datetime.now().replace(year=1990)))

# Subscribed topics that have been updated since last notification
notification_queue = models.ManyToManyField('Topic', related_name='users_to_notify')

#avatar = AvatarField(upload_to='avatars', width=100, height=100)

def __str__(self):
return self.user.username


class Topic(models.Model):
topic_name = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', default=timezone.now)
Expand Down
46 changes: 44 additions & 2 deletions messageboard/mainsite/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from django.core.urlresolvers import reverse
from django.utils import timezone
from mainsite.models import Topic, Message, UserProfile, Group
from datetime import datetime, timedelta
#from PIL import Image as PImage
from os.path import join as pjoin

Expand Down Expand Up @@ -120,8 +121,11 @@ def login(request):
else:
# Resend activation key
email_subject = 'Account Activation'
email_body = "Dear %s,\n\nThank you for signing up. To complete your registration, go to the link below.\
\n\nhttp://127.0.0.1:8000/mainsite/activation/%s\n\nYours,\nTeam8s" % (user.username, user.user_profile.activation_key)
email_body = "Dear %s,\n\n \
Thank you for signing up. To complete your registration, go to the link below.\n\n \
http://127.0.0.1:8000/mainsite/activation/%s\n\n\
Yours,\n\
Team8s" % (user.username, user.user_profile.activation_key)
send_mail(email_subject,
email_body,
'no-reply@messageboard.com',
Expand Down Expand Up @@ -165,6 +169,7 @@ def create_topic(request):
@login_required(login_url='/mainsite/login')
def topic(request, topicid):
if request.method == 'POST':

# Post a message to the topic.
if "POST" in request.POST:
message = Message()
Expand All @@ -173,13 +178,21 @@ def topic(request, topicid):
message.topic = current_topic
message.message_content = request.POST['message_content']
message.save()

# Hand out subscription notifications (currently synchronous)
subscribers = current_topic.subscriptions.all()
for subscriber in subscribers:
if subscriber != message.creator:
notify_subscriber(current_topic, subscriber)
return HttpResponseRedirect(reverse('mainsite:topic', args=(topicid,)))

# Edit a message.
elif "save" in request.POST:
message = get_object_or_404(Message, pk=request.POST['msgID'])
message.message_content = request.POST['message_content']
message.save()
return HttpResponseRedirect(reverse('mainsite:topic', args=(topicid,)))

# Delete a message.
elif "REMOVE" in request.POST:
message = get_object_or_404(Message, pk=request.POST['msgID'])
Expand All @@ -190,6 +203,35 @@ def topic(request, topicid):
return render(request, 'topics/topic.html', {'messages': messagelist, 'topic': this_topic})


# Helper function for subscription notifications.
# No loginrequired header is needed here, its not an actual view function.
def notify_subscriber(topic, subscriber):
profile = subscriber.user_profile

# Add a topic to the user's notification queue.
profile.notification_queue.add(topic)
profile.save()

# Check if its been long enough since the last email.
if datetime.now() > (profile.last_notified.replace(tzinfo=None) + timedelta(seconds=profile.notification_delay)):

# Start composing the email.
email_subject = 'Subscription Update!'
email_body = "Dear %s,\n\nA new message has been posted to a topic you're subscribed to!\n\n" \
% subscriber.username

# Dump all the topic links into the email.
for t in profile.notification_queue.all():
email_body += "http://127.0.0.1:8000/mainsite/messageboard/%d\n" % t.id
email_body += "\n\nYours,\nTeam8s"
send_mail(email_subject, email_body, 'no-reply@messageboard.com', [subscriber.email], fail_silently=False)

# Clear the notification queue, set the last_notified time.
profile.notification_queue.clear()
profile.last_notified = timezone.now()
profile.save()


@login_required(login_url='/mainsite/login')
def subscribe(request, topicid):
# Associate the topic and user to create a subscription
Expand Down

0 comments on commit fff619e

Please sign in to comment.