/
rest.py
274 lines (248 loc) · 8.5 KB
/
rest.py
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# -*- coding: utf-8 -*-
"""
Public REST API
"""
from copy import deepcopy
from .models import Event
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import Authentication
from tastypie.authorization import Authorization
from tastypie.exceptions import NotFound
import json
from thoonk import Thoonk
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
class AbstractEventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
resource_name = 'event'
always_return_data = True
filtering = {
'created_by': ALL,
'created_at': ALL,
'action': ALL,
'parent': ALL,
'id': ALL,
'feed': ALL,
'reference': ALL
}
ordering = [
'created_by',
'created_at',
'action',
'parent',
'id',
'feed',
'reference'
]
# TODO
authentication = Authentication()
authorization = Authorization()
def __init__(self, *args, **kwargs):
self._thoonkfeeds = Thoonk(
host=settings.REDIS['host'],
port=settings.REDIS['port'],
db=settings.REDIS['db'])
super(AbstractEventResource, self).__init__(self, *args, **kwargs)
def _publish_on_thoonk(self, bundle):
"""
Notifies the corresponding Thoonk Feed of an Event instance
"""
if bundle.obj.feed is not None:
feedname = bundle.obj.feed
elif 'feed' in bundle.data:
feedname = bundle.data['feed']
else:
return
if bundle.obj.action is not None:
actionname = bundle.obj.action
elif 'action' in bundle.data:
actionname = bundle.data['action']
else:
return
feed = self._thoonkfeeds.feed(feedname)
if bundle.obj.id is not None:
eid = bundle.obj.id
elif 'id' in bundle.data:
eid = bundle.data['id']
else:
return
reference = None
if bundle.obj.reference is not None:
reference = bundle.obj.reference
elif 'reference' in bundle.data:
reference = bundle.data['reference']
parent = None
if bundle.obj.parent is not None:
parent = bundle.obj.parent
elif 'parent' in bundle.data:
parent = bundle.data['parent']
feed.publish(json.dumps({
'id': eid,
'action': actionname,
'feed': feedname,
'reference': reference,
'parent': parent
}), str(eid))
def obj_create(self, bundle, request=None, **kwargs):
"""
A Resource-specific implementation of ``obj_create``.
"""
if request and request.user.is_authenticated():
bundle.data['created_by'] = request.user.id
elif 'created_by' not in bundle.data:
bundle.data['created_by'] = -1
bundle = super(AbstractEventResource, self).obj_create(bundle, request, **kwargs)
self._publish_on_thoonk(bundle)
return bundle
def obj_update(self, bundle, request=None, **kwargs):
"""
A Resource-specific implementation of ``obj_update``.
"""
bundle = super(AbstractEventResource, self).obj_update(bundle, request, **kwargs)
self._publish_on_thoonk(bundle)
return bundle
def obj_delete(self, request=None, **kwargs):
"""
A Resource-specific implementation of ``obj_delete``.
"""
obj = kwargs.pop('_obj', None)
if not hasattr(obj, 'delete'):
try:
obj = self.obj_get(request, **kwargs)
except ObjectDoesNotExist:
raise NotFound("A model instance matching the provided arguments could not be found.")
eid = obj.id
copyobj = deepcopy(obj)
actionname = obj.action + ".delete"
obj.delete()
feed = self._thoonkfeeds.feed(obj.feed)
if feed:
feed.publish(json.dumps({
'id': eid,
'action': actionname,
'feed': obj.feed,
'reference': obj.reference,
'parent': obj.parent
}))
return copyobj
class MessageResource(AbstractEventResource):
class Meta:
queryset = Event.objects.all()
resource_name = 'message'
always_return_data = True
filtering = {
'created_by': ALL,
'created_at': ALL,
'action': ALL,
'parent': ALL,
'id': ALL,
'feed': ALL,
'reference': ALL
}
ordering = [
'created_by',
'created_at',
'action',
'parent',
'id',
'feed',
'reference'
]
# TODO
authentication = Authentication()
authorization = Authorization()
def dehydrate(self, bundle):
"""
Like data aggregated
"""
bundle.data['like_count'] = self.get_object_list(bundle.request).filter(
parent=bundle.obj.id,
action='message.like',
feed=bundle.obj.feed).count()
if bundle.request.user.is_authenticated():
bundle.data['like_user'] = self.get_object_list(bundle.request).filter(
parent=bundle.obj.id,
created_by=bundle.request.user.id,
action='message.like',
feed=bundle.obj.feed).order_by('created_at').values('id')
if len(bundle.data['like_user']) == 0:
bundle.data['like_user'] = False
else:
bundle.data['like_user'] = bundle.data['like_user'][0]['id']
else:
bundle.data['like_user'] = False
return bundle
class LikeResource(AbstractEventResource):
"""
Resource for "like" Events
"""
class Meta:
queryset = Event.objects.all()
resource_name = 'like'
always_return_data = True
filtering = {
'created_by': ALL,
'created_at': ALL,
'action': ALL,
'parent': ALL,
'id': ALL,
'feed': ALL,
'reference': ALL
}
ordering = [
'created_by',
'created_at',
'action',
'parent',
'id',
'feed',
'reference'
]
# TODO
authentication = Authentication()
authorization = Authorization()
def _get_total(self, parent, feed, action):
return Event.objects.filter(parent=parent, feed=feed, action=action).count()
def dehydrate(self, bundle):
if not bundle.obj.parent or not bundle.obj.feed or not bundle.obj.action:
return bundle
bundle.data['reference'] = self._get_total(bundle.obj.parent, bundle.obj.feed, bundle.obj.action)
return bundle
def obj_delete(self, request=None, **kwargs):
"""
A Resource-specific implementation of ``obj_delete``.
"""
obj = kwargs.pop('_obj', None)
if not hasattr(obj, 'delete'):
try:
obj = self.obj_get(request, **kwargs)
except ObjectDoesNotExist:
raise NotFound("A model instance matching the provided arguments could not be found.")
copyobj = deepcopy(obj)
actionname = obj.action + ".delete"
obj.delete()
feed = self._thoonkfeeds.feed(obj.feed)
if feed:
bundle = self.build_bundle(obj=copyobj, request=request)
bundle = self.full_dehydrate(bundle)
bundle = self.alter_detail_data_to_serialize(request, bundle)
bundle.data['action'] = actionname
response = self.create_response(request, bundle)
feed.publish(response.content)
return copyobj
def obj_create(self, bundle, request=None, **kwargs):
"""
A Resource-specific implementation of ``obj_create``.
"""
if request and request.user.is_authenticated():
bundle.data['created_by'] = request.user.id
elif 'created_by' not in bundle.data:
bundle.data['created_by'] = -1
bundle = super(AbstractEventResource, self).obj_create(bundle, request, **kwargs)
try:
bundle.data['reference'] = self._get_total(bundle.data['parent'], bundle.data['feed'], bundle.data['action'])
except:
pass
self._publish_on_thoonk(bundle)
return bundle