annotate messages/views.py @ 804:95b3d59913ad

Private messages refactoring: compose functionality.
author Brian Neal <bgneal@gmail.com>
date Sun, 31 Aug 2014 13:51:06 -0500
parents b3eeaefc39a8
children e966d5553955
rev   line source
bgneal@425 1 """
bgneal@425 2 Views for the messages application.
bgneal@425 3
bgneal@425 4 """
bgneal@425 5 import datetime
bgneal@679 6 import json
bgneal@425 7
bgneal@425 8 from django.contrib.auth.decorators import login_required
bgneal@428 9 from django.contrib.auth.models import User
bgneal@436 10 from django.contrib import messages as django_messages
bgneal@801 11 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
bgneal@425 12 from django.core.urlresolvers import reverse
bgneal@425 13 from django.http import HttpResponse
bgneal@425 14 from django.http import HttpResponseForbidden
bgneal@425 15 from django.http import HttpResponseNotAllowed
bgneal@425 16 from django.shortcuts import get_object_or_404
bgneal@425 17 from django.shortcuts import render
bgneal@425 18
bgneal@425 19 from messages.models import Message, Options
bgneal@425 20 from messages.forms import OptionsForm, ComposeForm
bgneal@566 21 from messages.utils import reply_subject
bgneal@436 22 from messages import MSG_BOX_LIMIT
bgneal@566 23 from core.functions import quote_message
bgneal@425 24
bgneal@425 25
bgneal@436 26 MSGS_PER_PAGE = 20 # message pagination value
bgneal@425 27
bgneal@436 28 # This must match the jQuery UI tab control
bgneal@425 29 TAB_INDICES = {
bgneal@425 30 'inbox': 0,
bgneal@425 31 'compose': 1,
bgneal@425 32 'outbox': 2,
bgneal@425 33 'trash': 3,
bgneal@425 34 'options': 4,
bgneal@425 35 }
bgneal@425 36
bgneal@425 37
bgneal@436 38 def _quota_check(box_name, count, request):
bgneal@436 39 """
bgneal@436 40 Checks the message box count against MSG_BOX_LIMIT.
bgneal@436 41 Emits a message to the user if the quota is exceeded.
bgneal@441 42
bgneal@568 43 Returns the percent used as an integer between 0-100.
bgneal@568 44
bgneal@436 45 """
bgneal@436 46 if count >= MSG_BOX_LIMIT:
bgneal@436 47 django_messages.warning(request,
bgneal@436 48 "Your %s is full. Please delete some messages." % box_name)
bgneal@436 49
bgneal@568 50 return 100 * count / MSG_BOX_LIMIT
bgneal@568 51
bgneal@436 52
bgneal@801 53 def _get_page(request, qs):
bgneal@801 54 """Paginates the given queryset and returns a page object"""
bgneal@801 55 paginator = Paginator(qs, MSGS_PER_PAGE)
bgneal@801 56 try:
bgneal@801 57 page = paginator.page(request.GET.get('page', '1'))
bgneal@801 58 except PageNotAnInteger:
bgneal@801 59 page = paginator.page(1)
bgneal@801 60 except EmptyPage:
bgneal@801 61 page = paginator.page(paginator.num_pages)
bgneal@801 62 return page
bgneal@801 63
bgneal@801 64
bgneal@425 65 @login_required
bgneal@801 66 def inbox(request):
bgneal@425 67
bgneal@801 68 msg_list = Message.objects.inbox(request.user)
bgneal@801 69 msg_count = msg_list.count()
bgneal@801 70 pct_used = _quota_check('inbox', msg_count, request)
bgneal@801 71
bgneal@801 72 page = _get_page(request, msg_list)
bgneal@801 73
bgneal@801 74 return render(request, 'messages/inbox.html', {
bgneal@801 75 'tab': 'inbox',
bgneal@801 76 'page': page,
bgneal@801 77 'inbox_pct': pct_used,
bgneal@801 78 'outbox_pct': None,
bgneal@801 79 })
bgneal@801 80
bgneal@801 81
bgneal@801 82 @login_required
bgneal@801 83 def outbox(request):
bgneal@801 84
bgneal@801 85 msg_list = Message.objects.outbox(request.user)
bgneal@801 86 msg_count = msg_list.count()
bgneal@801 87 pct_used = _quota_check('outbox', msg_count, request)
bgneal@801 88
bgneal@801 89 page = _get_page(request, msg_list)
bgneal@801 90
bgneal@801 91 return render(request, 'messages/outbox.html', {
bgneal@801 92 'tab': 'outbox',
bgneal@801 93 'page': page,
bgneal@801 94 'inbox_pct': None,
bgneal@801 95 'outbox_pct': pct_used,
bgneal@425 96 })
bgneal@425 97
bgneal@425 98
bgneal@428 99 @login_required
bgneal@802 100 def trash(request):
bgneal@802 101
bgneal@802 102 msg_list = Message.objects.trash(request.user)
bgneal@802 103
bgneal@802 104 page = _get_page(request, msg_list)
bgneal@802 105
bgneal@802 106 return render(request, 'messages/trash.html', {
bgneal@802 107 'tab': 'trash',
bgneal@802 108 'page': page,
bgneal@802 109 'inbox_pct': None,
bgneal@802 110 'outbox_pct': None,
bgneal@802 111 })
bgneal@802 112
bgneal@802 113
bgneal@802 114 @login_required
bgneal@803 115 def options(request):
bgneal@803 116 """
bgneal@803 117 This view handles the displaying and changing of private message options.
bgneal@803 118
bgneal@803 119 """
bgneal@803 120 if request.method == 'POST':
bgneal@803 121 options = Options.objects.for_user(request.user)
bgneal@803 122 form = OptionsForm(request.POST, instance=options, prefix='opts')
bgneal@803 123 if form.is_valid():
bgneal@803 124 form.save()
bgneal@803 125 django_messages.success(request, 'Options saved.')
bgneal@803 126 else:
bgneal@803 127 options = Options.objects.for_user(request.user)
bgneal@803 128 form = OptionsForm(instance=options, prefix='opts')
bgneal@803 129
bgneal@803 130 return render(request, 'messages/options.html', {
bgneal@803 131 'tab': 'options',
bgneal@803 132 'form': form,
bgneal@803 133 })
bgneal@803 134
bgneal@803 135
bgneal@803 136 @login_required
bgneal@804 137 def compose(request):
bgneal@428 138 """
bgneal@804 139 Process or prepare the compose form to create a new private message.
bgneal@428 140
bgneal@428 141 """
bgneal@804 142 if request.method == 'POST':
bgneal@804 143 compose_form = ComposeForm(request.user, request.POST)
bgneal@804 144 if compose_form.is_valid():
bgneal@804 145 compose_form.save()
bgneal@804 146 django_messages.success(request, 'Message sent.')
bgneal@804 147 compose_form = ComposeForm(request.user)
bgneal@804 148 else:
bgneal@804 149 receiver = request.GET.get('to')
bgneal@804 150 if receiver:
bgneal@804 151 form_data = {'receiver': receiver}
bgneal@804 152 compose_form = ComposeForm(request.user, initial=form_data)
bgneal@804 153 else:
bgneal@804 154 compose_form = ComposeForm(request.user)
bgneal@804 155
bgneal@804 156 _quota_check('outbox', Message.objects.outbox(request.user).count(), request)
bgneal@804 157
bgneal@804 158 return render(request, 'messages/compose.html', {
bgneal@804 159 'tab': 'compose',
bgneal@804 160 'compose_form': compose_form,
bgneal@428 161 })
bgneal@428 162
bgneal@428 163
bgneal@804 164 @login_required
bgneal@804 165 def view(request, msg_id):
bgneal@425 166 """
bgneal@425 167 This view function retrieves a message and returns it as a JSON object.
bgneal@425 168
bgneal@425 169 """
bgneal@425 170 if not request.user.is_authenticated():
bgneal@425 171 return HttpResponseForbidden()
bgneal@425 172 if request.method != 'POST':
bgneal@425 173 return HttpResponseNotAllowed(['POST'])
bgneal@425 174
bgneal@425 175 msg_id = request.POST.get('msg_id')
bgneal@425 176 msg = get_object_or_404(Message.objects.select_related(), pk=msg_id)
bgneal@425 177 if msg.sender != request.user and msg.receiver != request.user:
bgneal@425 178 return HttpResponseForbidden()
bgneal@425 179
bgneal@425 180 if msg.receiver == request.user and msg.read_date is None:
bgneal@425 181 msg.read_date = datetime.datetime.now()
bgneal@425 182 msg.save()
bgneal@425 183
bgneal@425 184 msg_dict = dict(subject=msg.subject,
bgneal@425 185 sender=msg.sender.username,
bgneal@425 186 receiver=msg.receiver.username,
bgneal@425 187 content=msg.html,
bgneal@425 188 re_subject=reply_subject(msg.subject),
bgneal@566 189 re_content=quote_message(msg.sender.username, msg.message))
bgneal@425 190
bgneal@425 191 result = json.dumps(msg_dict, ensure_ascii=False)
bgneal@425 192 return HttpResponse(result, content_type='application/json')
bgneal@425 193
bgneal@425 194
bgneal@425 195 def _only_integers(slist):
bgneal@425 196 """
bgneal@425 197 Accepts a list of strings. Returns a list of integers consisting of only
bgneal@425 198 those elements from the original list that could be converted to integers
bgneal@425 199
bgneal@425 200 """
bgneal@425 201 result = []
bgneal@425 202 for s in slist:
bgneal@425 203 try:
bgneal@425 204 n = int(s)
bgneal@425 205 except ValueError:
bgneal@425 206 pass
bgneal@425 207 else:
bgneal@425 208 result.append(n)
bgneal@425 209 return result
bgneal@425 210
bgneal@425 211
bgneal@425 212 def _delete_msgs(user, msg_ids):
bgneal@425 213 """
bgneal@425 214 Deletes the messages given by the list of msg_ids. For this to succeed, the
bgneal@425 215 user has to be either the sender or receiver on each message.
bgneal@425 216
bgneal@425 217 """
bgneal@425 218 msg_ids = _only_integers(msg_ids)
bgneal@425 219 msgs = Message.objects.filter(id__in=msg_ids)
bgneal@425 220
bgneal@425 221 for msg in msgs:
bgneal@425 222 if msg.sender == user:
bgneal@425 223 if (msg.receiver_delete_date is not None or
bgneal@425 224 msg.read_date is None):
bgneal@425 225 # Both parties deleted the message or receiver hasn't read it
bgneal@425 226 # yet, we can delete it now
bgneal@425 227 msg.delete()
bgneal@425 228 else:
bgneal@425 229 # receiver still has it in inbox
bgneal@425 230 msg.sender_delete_date = datetime.datetime.now()
bgneal@425 231 msg.save()
bgneal@425 232
bgneal@425 233 elif msg.receiver == user:
bgneal@425 234 if msg.sender_delete_date is not None:
bgneal@425 235 # both parties deleted the message, we can delete it now
bgneal@425 236 msg.delete()
bgneal@425 237 else:
bgneal@425 238 # sender still has it in the outbox
bgneal@425 239 msg.receiver_delete_date = datetime.datetime.now()
bgneal@425 240 msg.save()
bgneal@425 241
bgneal@425 242
bgneal@425 243 def _undelete_msgs(user, msg_ids):
bgneal@425 244 """
bgneal@425 245 Attempts to "undelete" the messages given by the msg_ids list.
bgneal@425 246 This will only succeed if the user is either the sender or receiver.
bgneal@425 247
bgneal@425 248 """
bgneal@425 249 msg_ids = _only_integers(msg_ids)
bgneal@425 250 msgs = Message.objects.filter(id__in=msg_ids)
bgneal@425 251 for msg in msgs:
bgneal@425 252 if msg.sender == user:
bgneal@425 253 msg.sender_delete_date = None
bgneal@425 254 msg.save()
bgneal@425 255 elif msg.receiver == user:
bgneal@425 256 msg.receiver_delete_date = None
bgneal@425 257 msg.save()
bgneal@425 258
bgneal@425 259
bgneal@425 260 def bulk(request):
bgneal@425 261 """
bgneal@425 262 This view processes messages in bulk. Arrays of message ids are expected in
bgneal@425 263 the POST query dict: inbox_ids and outbox_ids will be deleted; trash_ids will
bgneal@425 264 be undeleted.
bgneal@425 265
bgneal@425 266 """
bgneal@425 267 if not request.user.is_authenticated():
bgneal@425 268 return HttpResponseForbidden()
bgneal@425 269 if request.method != 'POST':
bgneal@425 270 return HttpResponseNotAllowed(['POST'])
bgneal@425 271
bgneal@425 272 delete_ids = []
bgneal@425 273 if 'inbox_ids' in request.POST:
bgneal@425 274 delete_ids.extend(request.POST.getlist('inbox_ids'))
bgneal@425 275 if 'outbox_ids' in request.POST:
bgneal@425 276 delete_ids.extend(request.POST.getlist('outbox_ids'))
bgneal@425 277
bgneal@425 278 if len(delete_ids):
bgneal@425 279 _delete_msgs(request.user, delete_ids)
bgneal@425 280
bgneal@425 281 if 'trash_ids' in request.POST:
bgneal@425 282 _undelete_msgs(request.user, request.POST.getlist('trash_ids'))
bgneal@425 283
bgneal@425 284 return HttpResponse('');