forked from openlabs/nereid-activity-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
activity_stream.py
241 lines (200 loc) · 6.78 KB
/
activity_stream.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
# -*- coding: utf-8 -*-
"""
activity_stream
Activity Stream module.
:copyright: (c) 2013-2014 by Openlabs Technologies & Consulting (P) Limited
:license: GPLv3, see LICENSE for more details.
"""
from trytond.model import ModelSQL, ModelView, fields
from trytond.pool import Pool, PoolMeta
from trytond.exceptions import UserError
from nereid import request, jsonify, login_required
__all__ = ['NereidUser', 'Activity', 'ActivityAllowedModel']
__metaclass__ = PoolMeta
class NereidUser:
"Nereid User"
__name__ = 'nereid.user'
activities = fields.One2Many(
'nereid.activity', 'actor', 'Activities'
)
def _json(self):
"""
Serialize the actor alone and return a dictionary. This is separated
so that other modules can easily modify the behavior independent of
this modules.
"""
return {
"url": None,
"objectType": self.__name__,
"id": self.id,
"displayName": self.display_name,
}
class Activity(ModelSQL, ModelView):
'''
Nereid user activity
The model stores activities (verb) performed by nereid users (actor). The
field names and data structure is inspired by the activity stream json
specification 1.0 http://activitystrea.ms/specs/json/1.0/
'''
__name__ = 'nereid.activity'
actor = fields.Many2One(
'nereid.user', 'Actor', required=True, select=True
)
verb = fields.Char("Verb", required=True, select=True)
object_ = fields.Reference(
"Object", selection='models_get', select=True, required=True,
)
target = fields.Reference(
"Target", selection='models_get', select=True,
)
score = fields.Function(
fields.Integer('Score'), 'get_score'
)
event_time = fields.Function(
fields.Char('Event Time'), 'get_event_time'
)
@classmethod
def __setup__(cls):
super(Activity, cls).__setup__()
cls._order = [('create_date', 'DESC')]
@classmethod
def get_event_time(cls, records, name):
"""
Returns event time of current activity
"""
res = {}
for record in records:
res[record.id] = str(record.create_date)
return res
def get_score(self, name):
"""
Returns an integer score which could be used for sorting the activities
by external system like caches, which may not be able to sort on the
date
This score is based on the create date of the activity.
:param name: name of field.
:return: Integer Score.
"""
return int(self.create_date.strftime('%s'))
@classmethod
def models_get(cls):
'''
Return valid models where activity stream could have valid objects
and targets.
'''
ActivityAllowedModel = Pool().get('nereid.activity.allowed_model')
activity_allowed_models = ActivityAllowedModel.search([])
res = [(None, '')]
for allowed_model in activity_allowed_models:
res.append((allowed_model.model.model, allowed_model.name))
return res
def serialize(self):
'''
Return a JSON Seralizable dictionary that could be stored in a
cache and sent by XHR.
If additional information needs to be passed with the serialized data,
a subclass could get the returned dictionary and inject properties
anywhere in the dictionary (to be JSON object). This is respected by
the JSON Activity Streams 1.0 spec.
'''
if not self.search([('id', '=', self.id)], count=True):
return None
if not self.object_:
# When the object_ which caused the activity is no more
# the value will be False
return None
response_json = {
"published": self.create_date.isoformat(),
"actor": self.actor._json(),
"verb": self.verb,
}
try:
self.object_.rec_name
except UserError:
# The record may not exist anymore which results in
# a read error
return None
else:
response_json["object"] = self.object_._json()
if self.target:
try:
self.target.rec_name
except UserError:
# The record may not exist anymore which results in
# a read error
return None
else:
response_json["target"] = self.target._json()
return response_json
@classmethod
def get_activity_stream_domain(cls):
'''
Returns the domain to get activity stream
'''
return [
('actor', '=', request.nereid_user.id)
]
@classmethod
def get_public_stream_domain(cls):
"""
Returns the domain for public stream
"""
return [
('id', '=', None)
]
@classmethod
def public_stream(cls):
'''
Returns activity stream for public user
'''
offset = request.args.get('offset', 0, int)
limit = request.args.get('limit', 100, int)
activities = cls.search(
cls.get_public_stream_domain(), limit=limit, offset=offset,
)
items = filter(
None, map(lambda activity: activity.serialize(), activities)
)
return jsonify({
'totalItems': len(items),
'items': items,
})
@classmethod
@login_required
def stream(cls):
'''
Return JSON Serialized Activity Stream to XHR.
As defined by the activity stream json specification 1.0
http://activitystrea.ms/specs/json/1.0/
'''
offset = request.args.get('offset', 0, int)
limit = request.args.get('limit', 100, int)
activities = cls.search(
cls.get_activity_stream_domain(),
limit=limit, offset=offset,
)
items = filter(
None, map(lambda activity: activity.serialize(), activities)
)
return jsonify({
'totalItems': len(items),
'items': items,
})
class ActivityAllowedModel(ModelSQL, ModelView):
'''
Nereid activity allowed model
The model stores name (name) and model (ir.model) as list of allowed model
in activty.
'''
__name__ = 'nereid.activity.allowed_model'
name = fields.Char("Name", required=True, select=True)
model = fields.Many2One('ir.model', 'Model', required=True, select=True)
@classmethod
def __setup__(cls):
super(ActivityAllowedModel, cls).__setup__()
cls._sql_constraints += [
('unique_model', 'UNIQUE(model)',
'Name is already used.'),
('unique_name', 'UNIQUE(name)',
'Model is already used.'),
]