people.User._fetchguid() will now raise an exception when GUID is empty
[diaspy.git] / diaspy / conversations.py
1 #!/usr/bin/env python3
2
3
4 from diaspy import errors
5
6
7 class Conversation():
8 """This class represents a conversation.
9
10 .. note::
11 Remember that you need to have access to the conversation.
12 """
13 def __init__(self, connection, id, fetch=True):
14 """
15 :param conv_id: id of the post and not the guid!
16 :type conv_id: str
17 :param connection: connection object used to authenticate
18 :type connection: connection.Connection
19 """
20 self._connection = connection
21 self.id = id
22 self.data = {}
23 if fetch: self._fetch()
24
25 def _fetch(self):
26 """Fetches JSON data representing conversation.
27 """
28 request = self._connection.get('conversations/{}.json'.format(self.id))
29 if request.status_code == 200:
30 self.data = request.json()['conversation']
31 else:
32 raise errors.ConversationError('cannot download conversation data: {0}'.format(request.status_code))
33
34 def answer(self, text):
35 """Answer that conversation
36
37 :param text: text to answer.
38 :type text: str
39 """
40 data = {'message[text]': text,
41 'utf8': '✓',
42 'authenticity_token': repr(self._connection)}
43
44 request = self._connection.post('conversations/{}/messages'.format(self.id),
45 data=data,
46 headers={'accept': 'application/json'})
47 if request.status_code != 200:
48 raise errors.ConversationError('{0}: Answer could not be posted.'
49 .format(request.status_code))
50 return request.json()
51
52 def delete(self):
53 """Delete this conversation.
54 Has to be implemented.
55 """
56 data = {'authenticity_token': repr(self._connection)}
57
58 request = self._connection.delete('conversations/{0}/visibility/'
59 .format(self.id),
60 data=data,
61 headers={'accept': 'application/json'})
62
63 if request.status_code != 404:
64 raise errors.ConversationError('{0}: Conversation could not be deleted.'
65 .format(request.status_code))
66
67 def get_subject(self):
68 """Returns the subject of this conversation
69 """
70 return self.data['subject']