annotate messages/views.py @ 801:6bbd1473d48e

Work in progress: rework private messages.
author Brian Neal <bgneal@gmail.com>
date Sat, 30 Aug 2014 17:25:38 -0500
parents 89b240fe9297
children dbc389a409f5
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@428 100 def compose_to(request, receiver):
bgneal@428 101 """
bgneal@428 102 This function displays the base tabbed private messages view,
bgneal@428 103 and configures it to display the compose PM tab for the given
bgneal@428 104 receiver.
bgneal@428 105
bgneal@428 106 """
bgneal@428 107 user = get_object_or_404(User, username=receiver)
bgneal@428 108 tab_index = TAB_INDICES['compose']
bgneal@428 109 return render(request, 'messages/tabbed_base.html', {
bgneal@428 110 'tab': tab_index,
bgneal@428 111 'receiver': receiver,
bgneal@429 112 'unread_count': Message.objects.unread_count(request.user),
bgneal@428 113 })
bgneal@428 114
bgneal@428 115
bgneal@425 116 def trash(request):
bgneal@425 117 """
bgneal@425 118 Returns the trash for the user.
bgneal@425 119
bgneal@425 120 """
bgneal@425 121 if not request.user.is_authenticated():
bgneal@425 122 return HttpResponseForbidden()
bgneal@425 123
bgneal@425 124 msg_list = Message.objects.trash(request.user)
bgneal@425 125 paginator = Paginator(msg_list, MSGS_PER_PAGE)
bgneal@425 126 try:
bgneal@425 127 msgs = paginator.page(_get_page(request))
bgneal@566 128 except (EmptyPage, InvalidPage):
bgneal@425 129 msgs = paginator.page(paginator.num_pages)
bgneal@425 130
bgneal@425 131 return render(request, 'messages/trash_tab.html', {
bgneal@425 132 'msgs': msgs,
bgneal@429 133 'url': reverse('messages-trash'),
bgneal@425 134 })
bgneal@425 135
bgneal@425 136
bgneal@425 137 def message(request):
bgneal@425 138 """
bgneal@425 139 This view function retrieves a message and returns it as a JSON object.
bgneal@425 140
bgneal@425 141 """
bgneal@425 142 if not request.user.is_authenticated():
bgneal@425 143 return HttpResponseForbidden()
bgneal@425 144 if request.method != 'POST':
bgneal@425 145 return HttpResponseNotAllowed(['POST'])
bgneal@425 146
bgneal@425 147 msg_id = request.POST.get('msg_id')
bgneal@425 148 msg = get_object_or_404(Message.objects.select_related(), pk=msg_id)
bgneal@425 149 if msg.sender != request.user and msg.receiver != request.user:
bgneal@425 150 return HttpResponseForbidden()
bgneal@425 151
bgneal@425 152 if msg.receiver == request.user and msg.read_date is None:
bgneal@425 153 msg.read_date = datetime.datetime.now()
bgneal@425 154 msg.save()
bgneal@425 155
bgneal@425 156 msg_dict = dict(subject=msg.subject,
bgneal@425 157 sender=msg.sender.username,
bgneal@425 158 receiver=msg.receiver.username,
bgneal@425 159 content=msg.html,
bgneal@425 160 re_subject=reply_subject(msg.subject),
bgneal@566 161 re_content=quote_message(msg.sender.username, msg.message))
bgneal@425 162
bgneal@425 163 result = json.dumps(msg_dict, ensure_ascii=False)
bgneal@425 164 return HttpResponse(result, content_type='application/json')
bgneal@425 165
bgneal@425 166
bgneal@425 167 def options(request):
bgneal@425 168 """
bgneal@425 169 This view handles the displaying and changing of private message options.
bgneal@425 170
bgneal@425 171 """
bgneal@425 172 if not request.user.is_authenticated():
bgneal@425 173 return HttpResponseForbidden()
bgneal@425 174
bgneal@425 175 if request.method == "POST":
bgneal@425 176 options = Options.objects.for_user(request.user)
bgneal@425 177 form = OptionsForm(request.POST, instance=options, prefix='opts')
bgneal@425 178 if form.is_valid():
bgneal@425 179 form.save()
bgneal@436 180 django_messages.success(request, 'Options saved.')
bgneal@425 181 else:
bgneal@425 182 options = Options.objects.for_user(request.user)
bgneal@425 183 form = OptionsForm(instance=options, prefix='opts')
bgneal@425 184
bgneal@425 185 return render(request, 'messages/options_tab.html', {
bgneal@425 186 'form': form,
bgneal@425 187 })
bgneal@425 188
bgneal@425 189
bgneal@425 190 def compose(request, receiver=None):
bgneal@425 191 """
bgneal@425 192 Process or prepare the compose form to create a new private message.
bgneal@425 193
bgneal@425 194 """
bgneal@425 195 if not request.user.is_authenticated():
bgneal@425 196 return HttpResponseForbidden()
bgneal@425 197
bgneal@425 198 if request.method == "POST":
bgneal@425 199 compose_form = ComposeForm(request.user, request.POST)
bgneal@430 200
bgneal@430 201 # Is this a reply to another message?
bgneal@430 202 parent_msg_id = request.POST.get('reply_to')
bgneal@430 203 if parent_msg_id:
bgneal@430 204 parent_msg = get_object_or_404(Message, id=parent_msg_id)
bgneal@430 205 if (request.user != parent_msg.receiver and
bgneal@430 206 request.user != parent_msg.sender):
bgneal@430 207 return HttpResponseForbidden()
bgneal@430 208 else:
bgneal@430 209 parent_msg = None
bgneal@430 210
bgneal@425 211 if compose_form.is_valid():
bgneal@430 212 compose_form.save(parent_msg=parent_msg)
bgneal@436 213 django_messages.success(request, 'Message sent.')
bgneal@431 214 compose_form = ComposeForm(request.user)
bgneal@425 215 else:
bgneal@425 216 if receiver is not None:
bgneal@425 217 form_data = {'receiver': receiver}
bgneal@425 218 compose_form = ComposeForm(request.user, initial=form_data)
bgneal@425 219 else:
bgneal@425 220 compose_form = ComposeForm(request.user)
bgneal@425 221
bgneal@436 222 _quota_check('outbox', Message.objects.outbox(request.user).count(), request)
bgneal@436 223
bgneal@425 224 return render(request, 'messages/compose_tab.html', {
bgneal@425 225 'compose_form': compose_form,
bgneal@425 226 })
bgneal@425 227
bgneal@425 228
bgneal@425 229 def _only_integers(slist):
bgneal@425 230 """
bgneal@425 231 Accepts a list of strings. Returns a list of integers consisting of only
bgneal@425 232 those elements from the original list that could be converted to integers
bgneal@425 233
bgneal@425 234 """
bgneal@425 235 result = []
bgneal@425 236 for s in slist:
bgneal@425 237 try:
bgneal@425 238 n = int(s)
bgneal@425 239 except ValueError:
bgneal@425 240 pass
bgneal@425 241 else:
bgneal@425 242 result.append(n)
bgneal@425 243 return result
bgneal@425 244
bgneal@425 245
bgneal@425 246 def _delete_msgs(user, msg_ids):
bgneal@425 247 """
bgneal@425 248 Deletes the messages given by the list of msg_ids. For this to succeed, the
bgneal@425 249 user has to be either the sender or receiver on each message.
bgneal@425 250
bgneal@425 251 """
bgneal@425 252 msg_ids = _only_integers(msg_ids)
bgneal@425 253 msgs = Message.objects.filter(id__in=msg_ids)
bgneal@425 254
bgneal@425 255 for msg in msgs:
bgneal@425 256 if msg.sender == user:
bgneal@425 257 if (msg.receiver_delete_date is not None or
bgneal@425 258 msg.read_date is None):
bgneal@425 259 # Both parties deleted the message or receiver hasn't read it
bgneal@425 260 # yet, we can delete it now
bgneal@425 261 msg.delete()
bgneal@425 262 else:
bgneal@425 263 # receiver still has it in inbox
bgneal@425 264 msg.sender_delete_date = datetime.datetime.now()
bgneal@425 265 msg.save()
bgneal@425 266
bgneal@425 267 elif msg.receiver == user:
bgneal@425 268 if msg.sender_delete_date is not None:
bgneal@425 269 # both parties deleted the message, we can delete it now
bgneal@425 270 msg.delete()
bgneal@425 271 else:
bgneal@425 272 # sender still has it in the outbox
bgneal@425 273 msg.receiver_delete_date = datetime.datetime.now()
bgneal@425 274 msg.save()
bgneal@425 275
bgneal@425 276
bgneal@425 277 def _undelete_msgs(user, msg_ids):
bgneal@425 278 """
bgneal@425 279 Attempts to "undelete" the messages given by the msg_ids list.
bgneal@425 280 This will only succeed if the user is either the sender or receiver.
bgneal@425 281
bgneal@425 282 """
bgneal@425 283 msg_ids = _only_integers(msg_ids)
bgneal@425 284 msgs = Message.objects.filter(id__in=msg_ids)
bgneal@425 285 for msg in msgs:
bgneal@425 286 if msg.sender == user:
bgneal@425 287 msg.sender_delete_date = None
bgneal@425 288 msg.save()
bgneal@425 289 elif msg.receiver == user:
bgneal@425 290 msg.receiver_delete_date = None
bgneal@425 291 msg.save()
bgneal@425 292
bgneal@425 293
bgneal@425 294 def bulk(request):
bgneal@425 295 """
bgneal@425 296 This view processes messages in bulk. Arrays of message ids are expected in
bgneal@425 297 the POST query dict: inbox_ids and outbox_ids will be deleted; trash_ids will
bgneal@425 298 be undeleted.
bgneal@425 299
bgneal@425 300 """
bgneal@425 301 if not request.user.is_authenticated():
bgneal@425 302 return HttpResponseForbidden()
bgneal@425 303 if request.method != 'POST':
bgneal@425 304 return HttpResponseNotAllowed(['POST'])
bgneal@425 305
bgneal@425 306 delete_ids = []
bgneal@425 307 if 'inbox_ids' in request.POST:
bgneal@425 308 delete_ids.extend(request.POST.getlist('inbox_ids'))
bgneal@425 309 if 'outbox_ids' in request.POST:
bgneal@425 310 delete_ids.extend(request.POST.getlist('outbox_ids'))
bgneal@425 311
bgneal@425 312 if len(delete_ids):
bgneal@425 313 _delete_msgs(request.user, delete_ids)
bgneal@425 314
bgneal@425 315 if 'trash_ids' in request.POST:
bgneal@425 316 _undelete_msgs(request.user, request.POST.getlist('trash_ids'))
bgneal@425 317
bgneal@425 318 return HttpResponse('');