Err, it was kinda stupid to return anything about *deleted* stuff,
[diaspy.git] / diaspy / models.py
1 #!/usr/bin/env python3
2
3
4 """This module is only imported in other diaspy modules and
5 MUST NOT import anything.
6 """
7
8
9 import json
10 import re
11
12 from diaspy import errors
13
14
15 class Aspect():
16 """This class represents an aspect.
17
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.
21 """
22 def __init__(self, connection, id=None, name=None):
23 self._connection = connection
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:
30 raise Exception('Aspect must be initialized with either an id or name')
31
32 def _findname(self):
33 """Finds name for aspect.
34 """
35 name = None
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
42
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
53
54 def _getajax(self):
55 """Returns HTML returned when editing aspects via web UI.
56 """
57 start_regexp = re.compile('<ul +class=["\']contacts["\'] *>')
58 ajax = self._connection.get('aspects/{0}/edit'.format(self.id)).text
59
60 begin = ajax.find(start_regexp.search(ajax).group(0))
61 end = ajax.find('</ul>')
62 return ajax[begin:end]
63
64 def _extractusernames(self, ajax):
65 """Extracts usernames and GUIDs from ajax returned by Diaspora*.
66 Returns list of two-tuples: (guid, diaspora_name).
67 """
68 userline_regexp = re.compile('<a href=["\']/people/[a-z0-9]{16,16}["\']>[\w()*@. -]+</a>')
69 return [(line[17:33], re.escape(line[35:-4])) for line in userline_regexp.findall(ajax)]
70
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)
74 """
75 personid_regexp = 'alt=["\']{0}["\'] class=["\']avatar["\'] data-person_id=["\'][0-9]+["\']'
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, ''
79 while line[i].isdigit():
80 id = line[i] + id
81 i -= 1
82 personids[n] = (usernames[n][1], id)
83 return personids
84
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}"'
89 users = []
90 for name, id in personids:
91 if re.compile(method_regexp.format(id)).search(ajax): users.append(name)
92 return users
93
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
111 def addUser(self, user_id):
112 """Add user to current aspect.
113
114 :param user_id: user to add to aspect
115 :type user_id: int
116 :returns: JSON from request
117 """
118 data = {'authenticity_token': repr(self._connection),
119 'aspect_id': self.id,
120 'person_id': user_id}
121
122 request = self._connection.post('aspect_memberships.json', data=data)
123
124 if request.status_code == 400:
125 raise errors.AspectError('duplicate record, user already exists in aspect: {0}'.format(request.status_code))
126 elif request.status_code == 404:
127 raise errors.AspectError('user not found from this pod: {0}'.format(request.status_code))
128 elif request.status_code != 200:
129 raise errors.AspectError('wrong status code: {0}'.format(request.status_code))
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}
141 request = self.connection.delete('aspect_memberships/{0}.json'.format(self.id), data=data)
142
143 if request.status_code != 200:
144 raise errors.AspectError('cannot remove user from aspect: {0}'.format(request.status_code))
145 return request.json()
146
147
148 class Notification():
149 """This class represents single notification.
150 """
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')
153 _aboutid_regexp = re.compile(r'/posts/[0-9]+')
154
155 def __init__(self, connection, data):
156 self._connection = connection
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):
163 """Returns a key from notification data.
164 """
165 return self.data[key]
166
167 def __str__(self):
168 """Returns notification note.
169 """
170 string = re.sub('</?[a-z]+( *[a-z_-]+=["\'][\w():.,!?#@=/\- ]*["\'])* */?>', '', self.data['note_html'])
171 string = string.strip().split('\n')[0]
172 while ' ' in string: string = string.replace(' ', ' ')
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
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
188 def who(self):
189 """Returns list of guids of the users who caused you to get the notification.
190 """
191 return [who[8:24] for who in self._who_regexp.findall(self.data['note_html'])]
192
193 def when(self):
194 """Returns UTC time as found in note_html.
195 """
196 return self._when_regexp.search(self.data['note_html']).group(0)
197
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 """
206 headers = {'x-csrf-token': repr(self._connection)}
207 params = {'set_unread': json.dumps(unread)}
208 self._connection.put('notifications/{0}'.format(self['id']), params=params, headers=headers)
209 self.data['unread'] = unread
210
211
212 class Comment():
213 """Represents comment on post.
214
215 Does not require Connection() object. Note that you should not manually
216 create `Comment()` objects -- they are designed to be created automatically
217 by `Post()` objects.
218 """
219 def __init__(self, data):
220 self.data = data
221
222 def __str__(self):
223 """Returns comment's text.
224 """
225 return self.data['text']
226
227 def __repr__(self):
228 """Returns comments text and author.
229 Format: AUTHOR (AUTHOR'S GUID): COMMENT
230 """
231 return '{0} ({1}): {2}'.format(self.author(), self.author('guid'), str(self))
232
233 def when(self):
234 """Returns time when the comment had been created.
235 """
236 return self.data['created_at']
237
238 def author(self, key='name'):
239 """Returns author of the comment.
240 """
241 return self.data['author'][key]
242
243
244 class Post():
245 """This class represents a post.
246
247 .. note::
248 Remember that you need to have access to the post.
249 """
250 def __init__(self, connection, id, fetch=True, comments=True):
251 """
252 :param id: id or guid of the post
253 :type id: str
254 :param connection: connection object used to authenticate
255 :type connection: connection.Connection
256 :param fetch: defines whether to fetch post's data or not
257 :type fetch: bool
258 :param comments: defines whether to fetch post's comments or not
259 :type comments: bool
260 """
261 self._connection = connection
262 self.id = id
263 self.data = {}
264 self.comments = []
265 if fetch: self._fetchdata()
266 if comments: self._fetchcomments()
267
268 def __repr__(self):
269 """Returns string containing more information then str().
270 """
271 return '{0} ({1}): {2}'.format(self.data['author']['name'], self.data['author']['guid'], self.data['text'])
272
273 def __str__(self):
274 """Returns text of a post.
275 """
276 return self.data['text']
277
278 def _fetchdata(self):
279 """This function retrieves data of the post.
280 """
281 request = self._connection.get('posts/{0}.json'.format(self.id))
282 if request.status_code != 200:
283 raise errors.PostError('{0}: could not fetch data for post: {1}'.format(request.status_code, self.id))
284 else:
285 self.data = request.json()
286
287 def _fetchcomments(self):
288 """Retireves comments for this post.
289 """
290 request = self._connection.get('posts/{0}/comments.json'.format(self.id))
291 if request.status_code != 200:
292 raise errors.PostError('{0}: could not fetch comments for post: {1}'.format(request.status_code, self.id))
293 else:
294 self.comments = [Comment(c) for c in request.json()]
295
296 def update(self):
297 """Updates post data.
298 """
299 self._fetchdata()
300 self._fetchcomments()
301
302 def like(self):
303 """This function likes a post.
304 It abstracts the 'Like' functionality.
305
306 :returns: dict -- json formatted like object.
307 """
308 data = {'authenticity_token': repr(self._connection)}
309
310 request = self._connection.post('posts/{0}/likes'.format(self.id),
311 data=data,
312 headers={'accept': 'application/json'})
313
314 if request.status_code != 201:
315 raise errors.PostError('{0}: Post could not be liked.'
316 .format(request.status_code))
317 return request.json()
318
319 def reshare(self):
320 """This function reshares a post
321 """
322 data = {'root_guid': self.data['guid'],
323 'authenticity_token': repr(self._connection)}
324
325 request = self._connection.post('reshares',
326 data=data,
327 headers={'accept': 'application/json'})
328 if request.status_code != 201:
329 raise Exception('{0}: Post could not be reshared'.format(request.status_code))
330 return request.json()
331
332 def comment(self, text):
333 """This function comments on a post
334
335 :param text: text to comment.
336 :type text: str
337 """
338 data = {'text': text,
339 'authenticity_token': repr(self._connection)}
340 request = self._connection.post('posts/{0}/comments'.format(self.id),
341 data=data,
342 headers={'accept': 'application/json'})
343
344 if request.status_code != 201:
345 raise Exception('{0}: Comment could not be posted.'
346 .format(request.status_code))
347 return request.json()
348
349 def delete(self):
350 """ This function deletes this post
351 """
352 data = {'authenticity_token': repr(self._connection)}
353 request = self._connection.delete('posts/{0}'.format(self.id),
354 data=data,
355 headers={'accept': 'application/json'})
356 if request.status_code != 204:
357 raise errors.PostError('{0}: Post could not be deleted'.format(request.status_code))
358
359 def delete_comment(self, comment_id):
360 """This function removes a comment from a post
361
362 :param comment_id: id of the comment to remove.
363 :type comment_id: str
364 """
365 data = {'authenticity_token': repr(self._connection)}
366 request = self._connection.delete('posts/{0}/comments/{1}'
367 .format(self.id,
368 comment_id),
369 data=data,
370 headers={'accept': 'application/json'})
371
372 if request.status_code != 204:
373 raise errors.PostError('{0}: Comment could not be deleted'
374 .format(request.status_code))
375
376 def delete_like(self):
377 """This function removes a like from a post
378 """
379 data = {'authenticity_token': self._connection.get_token()}
380
381 request = self._connection.delete('posts/{0}/likes/{1}'
382 .format(self.id,
383 self.data['interactions']
384 ['likes'][0]['id']),
385 data=data)
386 if request.status_code != 204:
387 raise errors.PostError('{0}: Like could not be removed.'
388 .format(request.status_code))
389
390 def author(self, key='name'):
391 """Returns author of the post.
392 :param key: all keys available in data['author']
393 """
394 return self.data['author'][key]