summaryrefslogtreecommitdiffstats
path: root/group_messaging/views.py
blob: c2e9af9373e1ae1971e2660411240b822af78c55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""semi-views for the `group_messaging` application
These are not really views - rather context generator
functions, to be used separately, when needed.

For example, some other application can call these
in order to render messages within the page.

Notice that :mod:`urls` module decorates all these functions
and turns them into complete views
"""
from coffin.template.loader import get_template
from django.forms import IntegerField
from django.http import HttpResponse
from django.http import HttpResponseNotAllowed
from django.http import HttpResponseForbidden
from django.utils import simplejson
from group_messaging.models import Message
from group_messaging.models import SenderList
from group_messaging.models import get_personal_group_by_user_id

class InboxView(object):
    """custom class-based view
    to be used for pjax use and for generation
    of content in the traditional way, where
    the only the :method:`get_context` would be used.
    """
    template_name = None #used only for the "GET" method
    http_method_names = ('GET', 'POST')

    def render_to_response(self, context, template_name=None):
        """like a django's shortcut, except will use
        template_name from self, if `template_name` is not given.
        Also, response is packaged as json with an html fragment
        for the pjax consumption
        """
        if template_name is None:
            template_name = self.template_name
        template = get_template(self.template_name)
        html = template.render(context)
        json = simplejson.dumps({'html': html})
        return HttpResponse(json, mimetype='application/json')
            

    def get(self, request, *args, **kwargs):
        """view function for the "GET" method"""
        context = self.get_context(request, *args, **kwargs)
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        """view function for the "POST" method"""
        pass

    def dispatch(self, request, *args, **kwargs):
        """checks that the current request method is allowed
        and calls the corresponding view function"""
        if request.method not in self.http_method_names:
            return HttpResponseNotAllowed()
        view_func = getattr(self, request.method.lower())
        return view_func(request, *args, **kwargs)

    def get_context(self, request, *args, **kwargs):
        """Returns the context dictionary for the "get"
        method only"""
        return {}

    def as_view(self):
        """returns the view function - for the urls.py"""
        def view_function(request, *args, **kwargs):
            """the actual view function"""
            if request.user.is_authenticated() and request.is_ajax():
                view_method = getattr(self, request.method.lower())
                return view_method(request, *args, **kwargs)
            else:
                return HttpResponseForbidden()

        return view_function


class NewThread(InboxView):
    """view for creation of new thread"""
    template_name = 'create_thread.html'# contains new thread form
    http_method_list = ('GET', 'POST')

    def post(self, request):
        """creates a new thread on behalf of the user
        response is blank, because on the client side we just 
        need to go back to the thread listing view whose
        content should be cached in the client'
        """
        recipient_id = IntegerField().clean(request.POST['recipient_id'])
        recipient = get_personal_group_by_user_id(recipient_id)
        Message.objects.create_thread(
                        sender=request.user,
                        recipients=[recipient],
                        text=request.POST['text']
                    )
        return HttpResponse('', mimetype='application/json')


class NewResponse(InboxView):
    """view to create a new response"""
    http_method_list = ('POST',)

    def post(self, request):
        parent_id = IntegerField().clean(request.POST['parent_id'])
        parent = Message.objects.get(id=parent_id)
        message = Message.objects.create_response(
                                        sender=request.user,
                                        text=request.POST['text'],
                                        parent=parent
                                    )
        return self.render_to_response(
            {'message': message}, template_name='stored_message.htmtl'
        )

class ThreadsList(InboxView):
    """shows list of threads for a given user"""  
    template_name = 'threads_list.html'
    http_method_list = ('GET',)

    def get_context(self, request):
        """returns thread list data"""
        threads = Message.objects.get_threads_for_user(request.user)
        threads = threads.values('id', 'headline')
        return {'threads': threads}


class SendersList(InboxView):
    """shows list of senders for a user"""
    template_name = 'senders_list.html'
    http_method_names = ('GET',)

    def get_context(self, request):
        """get data about senders for the user"""
        senders = SenderList.objects.get_senders_for_user(request.user)
        senders = senders.values('id', 'username')
        return {'senders': senders}


class ThreadDetails(InboxView):
    """shows entire thread in the unfolded form"""
    template_name = 'thread_details.html'
    http_method_names = ('GET',)

    def get_context(self, request):
        """shows individual thread"""
        thread_id = IntegerField().clean(request.GET['thread_id'])
        #todo: assert that current thread is the root
        messages = Message.objects.filter(root__id=thread_id)
        messages = messages.values('html')
        return {'messages': messages}