See changes in Changelog
[diaspy.git] / diaspy / models.py
CommitLineData
88ec6cda 1#!/usr/bin/env python3
ae221396
MK
2
3
e7abf853
MM
4"""This module is only imported in other diaspy modules and
5MUST NOT import anything.
6"""
7
8
178faa46 9import json
c8438f07 10import re
178faa46 11
9896b779
MM
12from diaspy import errors
13
178faa46 14
7a818fdb
MM
15class Aspect():
16 """This class represents an aspect.
3cf4514e 17
4b7d7125
JR
18 Class can be initialized by passing either an id and/or name as
19 parameters.
20 If both are missing, an exception will be raised.
7a818fdb 21 """
4b7d7125 22 def __init__(self, connection, id=None, name=None):
7a818fdb 23 self._connection = connection
4b7d7125
JR
24 self.id, self.name = id, name
25 if id and not name:
26 self.name = self._findname()
27 elif name and not id:
28 self.id = self._findid()
29 elif not id and not name:
4b1645dc 30 raise Exception('Aspect must be initialized with either an id or name')
3cf4514e 31
e4544075
MM
32 def _findname(self):
33 """Finds name for aspect.
34 """
4b7d7125 35 name = None
e4544075
MM
36 aspects = self._connection.getUserInfo()['aspects']
37 for a in aspects:
38 if a['id'] == self.id:
39 name = a['name']
40 break
41 return name
3cf4514e 42
4b7d7125
JR
43 def _findid(self):
44 """Finds id for aspect.
45 """
46 id = None
47 aspects = self._connection.getUserInfo()['aspects']
48 for a in aspects:
49 if a['name'] == self.name:
50 id = a['id']
51 break
52 return id
7a818fdb 53
65b1f099
MM
54 def _getajax(self):
55 """Returns HTML returned when editing aspects via web UI.
488d7ff6 56 """
1513c0d9 57 start_regexp = re.compile('<ul +class=["\']contacts["\'] *>')
1513c0d9 58 ajax = self._connection.get('aspects/{0}/edit'.format(self.id)).text
08f03d26 59
1513c0d9
MM
60 begin = ajax.find(start_regexp.search(ajax).group(0))
61 end = ajax.find('</ul>')
65b1f099
MM
62 return ajax[begin:end]
63
64 def _extractusernames(self, ajax):
65 """Extracts usernames and GUIDs from ajax returned by Diaspora*.
6fd7d9c1 66 Returns list of two-tuples: (guid, diaspora_name).
65b1f099 67 """
cd18cc87 68 userline_regexp = re.compile('<a href=["\']/people/[a-z0-9]{16,16}["\']>[\w()*@. -]+</a>')
65b1f099
MM
69 return [(line[17:33], re.escape(line[35:-4])) for line in userline_regexp.findall(ajax)]
70
6fd7d9c1
MM
71 def _extractpersonids(self, ajax, usernames):
72 """Extracts `person_id`s and usernames from ajax and list of usernames.
73 Returns list of two-tuples: (username, id)
65b1f099
MM
74 """
75 personid_regexp = 'alt=["\']{0}["\'] class=["\']avatar["\'] data-person_id=["\'][0-9]+["\']'
e4544075
MM
76 personids = [re.compile(personid_regexp.format(name)).search(ajax).group(0) for guid, name in usernames]
77 for n, line in enumerate(personids):
78 i, id = -2, ''
1513c0d9 79 while line[i].isdigit():
e4544075 80 id = line[i] + id
1513c0d9 81 i -= 1
e4544075 82 personids[n] = (usernames[n][1], id)
6fd7d9c1 83 return personids
e4544075 84
6fd7d9c1
MM
85 def _defineusers(self, ajax, personids):
86 """Gets users contained in this aspect by getting users who have `delete` method.
87 """
88 method_regexp = 'data-method="delete" data-person_id="{0}"'
e4544075 89 users = []
6fd7d9c1
MM
90 for name, id in personids:
91 if re.compile(method_regexp.format(id)).search(ajax): users.append(name)
1513c0d9 92 return users
488d7ff6 93
6fd7d9c1
MM
94 def _getguids(self, users_in_aspect, usernames):
95 """Defines users contained in this aspect.
96 """
97 guids = []
98 for guid, name in usernames:
99 if name in users_in_aspect: guids.append(guid)
100 return guids
101
102 def getUsers(self):
103 """Returns list of GUIDs of users who are listed in this aspect.
104 """
105 ajax = self._getajax()
106 usernames = self._extractusernames(ajax)
107 personids = self._extractpersonids(ajax, usernames)
108 users_in_aspect = self._defineusers(ajax, personids)
109 return self._getguids(users_in_aspect, usernames)
110
7a818fdb
MM
111 def addUser(self, user_id):
112 """Add user to current aspect.
113
114 :param user_id: user to add to aspect
cd18cc87
MM
115 :type user_id: int
116 :returns: JSON from request
7a818fdb 117 """
9896b779 118 data = {'authenticity_token': repr(self._connection),
7a818fdb
MM
119 'aspect_id': self.id,
120 'person_id': user_id}
121
122 request = self._connection.post('aspect_memberships.json', data=data)
123
c5e41a94 124 if request.status_code == 400:
9896b779 125 raise errors.AspectError('duplicate record, user already exists in aspect: {0}'.format(request.status_code))
c5e41a94 126 elif request.status_code == 404:
9896b779 127 raise errors.AspectError('user not found from this pod: {0}'.format(request.status_code))
0d698df1 128 elif request.status_code != 200:
9896b779 129 raise errors.AspectError('wrong status code: {0}'.format(request.status_code))
7a818fdb
MM
130 return request.json()
131
132 def removeUser(self, user_id):
133 """Remove user from current aspect.
134
135 :param user_id: user to remove from aspect
136 :type user: int
137 """
138 data = {'authenticity_token': self._connection.get_token(),
139 'aspect_id': self.id,
140 'person_id': user_id}
7a818fdb
MM
141 request = self.connection.delete('aspect_memberships/{0}.json'.format(self.id), data=data)
142
143 if request.status_code != 200:
9896b779 144 raise errors.AspectError('cannot remove user from aspect: {0}'.format(request.status_code))
7a818fdb
MM
145 return request.json()
146
147
178faa46
MM
148class Notification():
149 """This class represents single notification.
150 """
c8438f07
MM
151 _who_regexp = re.compile(r'/people/[0-9a-z]+" class=\'hovercardable')
152 _when_regexp = re.compile(r'[0-9]{4,4}(-[0-9]{2,2}){2,2} [0-9]{2,2}(:[0-9]{2,2}){2,2} UTC')
63f1d9f1 153 _aboutid_regexp = re.compile(r'/posts/[0-9]+')
c8438f07 154
178faa46
MM
155 def __init__(self, connection, data):
156 self._connection = connection
178faa46
MM
157 self.type = list(data.keys())[0]
158 self.data = data[self.type]
159 self.id = self.data['id']
160 self.unread = self.data['unread']
161
162 def __getitem__(self, key):
c8438f07
MM
163 """Returns a key from notification data.
164 """
178faa46
MM
165 return self.data[key]
166
c8438f07
MM
167 def __str__(self):
168 """Returns notification note.
169 """
63f1d9f1 170 string = re.sub('</?[a-z]+( *[a-z_-]+=["\'][\w():.,!?#@=/\- ]*["\'])* */?>', '', self.data['note_html'])
c8438f07 171 string = string.strip().split('\n')[0]
4eb05209 172 while ' ' in string: string = string.replace(' ', ' ')
c8438f07
MM
173 return string
174
175 def __repr__(self):
176 """Returns notification note with more details.
177 """
178 return '{0}: {1}'.format(self.when(), str(self))
179
63f1d9f1
MM
180 def about(self):
181 """Returns id of post about which the notification is informing.
182 """
183 about = self._aboutid_regexp.search(self.data['note_html'])
184 if about is None: about = self.who()
185 else: about = int(about.group(0)[7:])
186 return about
187
c8438f07 188 def who(self):
19a4a78a 189 """Returns list of guids of the users who caused you to get the notification.
c8438f07 190 """
19a4a78a 191 return [who[8:24] for who in self._who_regexp.findall(self.data['note_html'])]
c8438f07
MM
192
193 def when(self):
194 """Returns UTC time as found in note_html.
b0b4c46d 195 """
19a4a78a 196 return self._when_regexp.search(self.data['note_html']).group(0)
b0b4c46d 197
178faa46
MM
198 def mark(self, unread=False):
199 """Marks notification to read/unread.
200 Marks notification to read if `unread` is False.
201 Marks notification to unread if `unread` is True.
202
203 :param unread: which state set for notification
204 :type unread: bool
205 """
fe2181b4 206 headers = {'x-csrf-token': repr(self._connection)}
178faa46 207 params = {'set_unread': json.dumps(unread)}
178faa46
MM
208 self._connection.put('notifications/{0}'.format(self['id']), params=params, headers=headers)
209 self.data['unread'] = unread
210
211
4882952f
MM
212class Conversation():
213 """This class represents a conversation.
214
215 .. note::
216 Remember that you need to have access to the conversation.
217 """
218 def __init__(self, connection, id, fetch=True):
219 """
220 :param conv_id: id of the post and not the guid!
221 :type conv_id: str
222 :param connection: connection object used to authenticate
223 :type connection: connection.Connection
224 """
225 self._connection = connection
226 self.id = id
227 self.data = {}
228 if fetch: self._fetch()
229
230 def _fetch(self):
231 """Fetches JSON data representing conversation.
232 """
233 request = self._connection.get('conversations/{}.json'.format(self.id))
234 if request.status_code == 200:
235 self.data = request.json()['conversation']
236 else:
237 raise errors.ConversationError('cannot download conversation data: {0}'.format(request.status_code))
238
239 def answer(self, text):
240 """Answer that conversation
241
242 :param text: text to answer.
243 :type text: str
244 """
245 data = {'message[text]': text,
246 'utf8': '&#x2713;',
247 'authenticity_token': repr(self._connection)}
248
249 request = self._connection.post('conversations/{}/messages'.format(self.id),
250 data=data,
251 headers={'accept': 'application/json'})
252 if request.status_code != 200:
253 raise errors.ConversationError('{0}: Answer could not be posted.'
254 .format(request.status_code))
255 return request.json()
256
257 def delete(self):
258 """Delete this conversation.
259 Has to be implemented.
260 """
261 data = {'authenticity_token': repr(self._connection)}
262
263 request = self._connection.delete('conversations/{0}/visibility/'
264 .format(self.id),
265 data=data,
266 headers={'accept': 'application/json'})
267
268 if request.status_code != 404:
269 raise errors.ConversationError('{0}: Conversation could not be deleted.'
270 .format(request.status_code))
271
272 def get_subject(self):
273 """Returns the subject of this conversation
274 """
275 return self.data['subject']
276
277
313fb305
MM
278class Comment():
279 """Represents comment on post.
280
281 Does not require Connection() object. Note that you should not manually
282 create `Comment()` objects -- they are designed to be created automatically
283 by `Post()` objects.
284 """
285 def __init__(self, data):
286 self.data = data
287
288 def __str__(self):
289 """Returns comment's text.
290 """
291 return self.data['text']
292
293 def __repr__(self):
294 """Returns comments text and author.
295 Format: AUTHOR (AUTHOR'S GUID): COMMENT
296 """
297 return '{0} ({1}): {2}'.format(self.author(), self.author('guid'), str(self))
298
299 def when(self):
300 """Returns time when the comment had been created.
301 """
302 return self.data['created_at']
303
304 def author(self, key='name'):
305 """Returns author of the comment.
306 """
307 return self.data['author'][key]
308
309
dd0a4d9f 310class Post():
ae221396
MK
311 """This class represents a post.
312
313 .. note::
314 Remember that you need to have access to the post.
ae221396 315 """
313fb305 316 def __init__(self, connection, id, fetch=True, comments=True):
a7661afd 317 """
fe2181b4
MM
318 :param id: id or guid of the post
319 :type id: str
b95ffe83
MM
320 :param connection: connection object used to authenticate
321 :type connection: connection.Connection
313fb305
MM
322 :param fetch: defines whether to fetch post's data or not
323 :type fetch: bool
324 :param comments: defines whether to fetch post's comments or not
325 :type comments: bool
a7661afd 326 """
b95ffe83 327 self._connection = connection
fe2181b4 328 self.id = id
313fb305
MM
329 self.data = {}
330 self.comments = []
331 if fetch: self._fetchdata()
332 if comments: self._fetchcomments()
8095ac8b 333
1467ec15
MM
334 def __repr__(self):
335 """Returns string containing more information then str().
336 """
75a456f4 337 return '{0} ({1}): {2}'.format(self.data['author']['name'], self.data['author']['guid'], self.data['text'])
1467ec15 338
66c3bb76
MM
339 def __str__(self):
340 """Returns text of a post.
341 """
75a456f4 342 return self.data['text']
66c3bb76 343
313fb305 344 def _fetchdata(self):
0e858bba
MM
345 """This function retrieves data of the post.
346 """
78cc478a 347 request = self._connection.get('posts/{0}.json'.format(self.id))
fe2181b4 348 if request.status_code != 200:
313fb305 349 raise errors.PostError('{0}: could not fetch data for post: {1}'.format(request.status_code, self.id))
fe2181b4
MM
350 else:
351 self.data = request.json()
a993a4b6 352
313fb305
MM
353 def _fetchcomments(self):
354 """Retireves comments for this post.
355 """
356 request = self._connection.get('posts/{0}/comments.json'.format(self.id))
357 if request.status_code != 200:
358 raise errors.PostError('{0}: could not fetch comments for post: {1}'.format(request.status_code, self.id))
359 else:
360 self.comments = [Comment(c) for c in request.json()]
361
78cc478a
MM
362 def update(self):
363 """Updates post data.
364 """
313fb305
MM
365 self._fetchdata()
366 self._fetchcomments()
78cc478a 367
a993a4b6 368 def like(self):
88ec6cda 369 """This function likes a post.
df912114 370 It abstracts the 'Like' functionality.
a993a4b6
MK
371
372 :returns: dict -- json formatted like object.
a993a4b6 373 """
fe2181b4 374 data = {'authenticity_token': repr(self._connection)}
a993a4b6 375
78cc478a 376 request = self._connection.post('posts/{0}/likes'.format(self.id),
385e7ebe
MM
377 data=data,
378 headers={'accept': 'application/json'})
a7661afd 379
fe2181b4
MM
380 if request.status_code != 201:
381 raise errors.PostError('{0}: Post could not be liked.'
382 .format(request.status_code))
383 return request.json()
a993a4b6 384
a993a4b6
MK
385 def reshare(self):
386 """This function reshares a post
a993a4b6 387 """
fe2181b4
MM
388 data = {'root_guid': self.data['guid'],
389 'authenticity_token': repr(self._connection)}
8095ac8b 390
fe2181b4 391 request = self._connection.post('reshares',
385e7ebe
MM
392 data=data,
393 headers={'accept': 'application/json'})
fe2181b4
MM
394 if request.status_code != 201:
395 raise Exception('{0}: Post could not be reshared'.format(request.status_code))
396 return request.json()
a993a4b6
MK
397
398 def comment(self, text):
399 """This function comments on a post
400
a993a4b6
MK
401 :param text: text to comment.
402 :type text: str
a993a4b6 403 """
a993a4b6 404 data = {'text': text,
fe2181b4
MM
405 'authenticity_token': repr(self._connection)}
406 request = self._connection.post('posts/{0}/comments'.format(self.id),
385e7ebe
MM
407 data=data,
408 headers={'accept': 'application/json'})
a7661afd 409
fe2181b4 410 if request.status_code != 201:
9088535d 411 raise Exception('{0}: Comment could not be posted.'
fe2181b4
MM
412 .format(request.status_code))
413 return request.json()
ae221396 414
e7abf853
MM
415 def delete(self):
416 """ This function deletes this post
417 """
418 data = {'authenticity_token': repr(self._connection)}
419 request = self._connection.delete('posts/{0}'.format(self.id),
420 data=data,
421 headers={'accept': 'application/json'})
422 if request.status_code != 204:
423 raise errors.PostError('{0}: Post could not be deleted'.format(request.status_code))
424
5e809c8b 425 def delete_comment(self, comment_id):
a993a4b6
MK
426 """This function removes a comment from a post
427
91d2d5dc
B
428 :param comment_id: id of the comment to remove.
429 :type comment_id: str
a993a4b6 430 """
fe2181b4
MM
431 data = {'authenticity_token': repr(self._connection)}
432 request = self._connection.delete('posts/{0}/comments/{1}'
433 .format(self.id,
385e7ebe
MM
434 comment_id),
435 data=data,
436 headers={'accept': 'application/json'})
a7661afd 437
fe2181b4
MM
438 if request.status_code != 204:
439 raise errors.PostError('{0}: Comment could not be deleted'
440 .format(request.status_code))
5e809c8b 441
e7abf853
MM
442 def delete_like(self):
443 """This function removes a like from a post
5e809c8b 444 """
e7abf853
MM
445 data = {'authenticity_token': self._connection.get_token()}
446
447 request = self._connection.delete('posts/{0}/likes/{1}'
448 .format(self.id,
449 self.data['interactions']
450 ['likes'][0]['id']),
451 data=data)
fe2181b4 452 if request.status_code != 204:
e7abf853
MM
453 raise errors.PostError('{0}: Like could not be removed.'
454 .format(request.status_code))
313fb305
MM
455
456 def author(self, key='name'):
457 """Returns author of the post.
458 :param key: all keys available in data['author']
459 """
460 return self.data['author'][key]