PageRenderTime 22ms CodeModel.GetById 14ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/jchat/views.py

http://django-jchat.googlecode.com/
Python | 144 lines | 131 code | 3 blank | 10 comment | 0 complexity | 2f26211b6a5803fafdfdcd7623c9330c MD5 | raw file
  1# -*- encoding: UTF-8 -*-
  2'''
  3Chat application views, some are tests... some are not
  4@author: Federico C??ceres <fede.caceres@gmail.com>
  5'''
  6from datetime import datetime
  7
  8from django.http import HttpResponse, Http404
  9from django.shortcuts import render_to_response
 10from django.contrib.auth.decorators import login_required
 11from django.template import RequestContext
 12from django.contrib.auth.models import User 
 13
 14from models import Room, Message
 15
 16@login_required
 17def send(request):
 18    '''
 19    Expects the following POST parameters:
 20    chat_room_id
 21    message
 22    '''
 23    p = request.POST
 24    r = Room.objects.get(id=int(p['chat_room_id']))
 25    r.say(request.user, p['message'])
 26    return HttpResponse('')
 27
 28@login_required
 29def sync(request):
 30    '''Return last message id
 31
 32    EXPECTS the following POST parameters:
 33    id
 34    '''
 35    if request.method != 'POST':
 36        raise Http404
 37    post = request.POST
 38
 39    if not post.get('id', None):
 40        raise Http404
 41
 42    r = Room.objects.get(id=post['id'])
 43    
 44    lmid = r.last_message_id()    
 45    
 46    return HttpResponse(jsonify({'last_message_id':lmid}))
 47
 48@login_required
 49def receive(request):
 50    '''
 51    Returned serialized data
 52    
 53    EXPECTS the following POST parameters:
 54    id
 55    offset
 56    
 57    This could be useful:
 58    @see: http://www.djangosnippets.org/snippets/622/
 59    '''
 60    if request.method != 'POST':
 61        raise Http404
 62    post = request.POST
 63
 64    if not post.get('id', None) or not post.get('offset', None):
 65        raise Http404
 66    
 67    try:
 68        room_id = int(post['id'])
 69    except:
 70        raise Http404
 71
 72    try:
 73        offset = int(post['offset'])
 74    except:
 75        offset = 0
 76    
 77    r = Room.objects.get(id=room_id)
 78
 79    m = r.messages(offset)
 80
 81    
 82    return HttpResponse(jsonify(m, ['id','author','message','type']))
 83
 84
 85@login_required
 86def join(request):
 87    '''
 88    Expects the following POST parameters:
 89    chat_room_id
 90    message
 91    '''
 92    p = request.POST
 93    r = Room.objects.get(id=int(p['chat_room_id']))
 94    r.join(request.user)
 95    return HttpResponse('')
 96
 97
 98@login_required
 99def leave(request):
100    '''
101    Expects the following POST parameters:
102    chat_room_id
103    message
104    '''
105    p = request.POST
106    r = Room.objects.get(id=int(p['chat_room_id']))
107    r.leave(request.user)
108    return HttpResponse('')
109
110
111@login_required
112def test(request):
113    '''Test the chat application'''
114    
115    u = User.objects.get(id=1) # always attach to first user id
116    r = Room.objects.get_or_create(u)
117
118    return render_to_response('chat/chat.html', {'js': ['/media/js/mg/chat.js'], 'chat_id':r.pk}, context_instance=RequestContext(request))
119
120
121def jsonify(object, fields=None, to_dict=False):
122    '''Simple convert model to json'''
123    try:
124        import json
125    except:
126        import django.utils.simplejson as json
127 
128    out = []
129    if type(object) not in [dict,list,tuple] :
130        for i in object:
131            tmp = {}
132            if fields:
133                for field in fields:
134                    tmp[field] = unicode(i.__getattribute__(field))
135            else:
136                for attr, value in i.__dict__.iteritems():
137                    tmp[attr] = value
138            out.append(tmp)
139    else:
140        out = object
141    if to_dict:
142        return out
143    else:
144        return json.dumps(out)