`Connection()` object works, `diaply/client.py` partialy ported
[diaspy.git] / diaspy / conversations.py
1 #!/usr/bin/env python3
2
3
4 class Conversation:
5 """This class represents a conversation.
6
7 .. note::
8 Remember that you need to have access to the conversation.
9
10 """
11 def __init__(self, conv_id, client):
12 """
13 :param conv_id: id of the post and not the guid!
14 :type conv_id: str
15 :param client: client object used to authenticate
16 :type client: client.Client
17
18 .. note::
19 The login function of the client should be called,
20 before calling any of the post functions.
21
22 """
23 self._client = client
24 self.conv_id = conv_id
25
26 def get_data(self):
27 """ returns the plain json data representing conversation.
28 """
29 r = self._client._sessionget('conversations/{1}.json'.format(self.conv_id))
30 if r.status_code == 200:
31 return r.json()['conversation']
32 else:
33 raise Exception('wrong status code: {0}'.format(r.status_code))
34
35 def answer(self, text):
36 """ answer that conversation
37
38 :param text: text to answer.
39 :type text: str
40
41 """
42
43 data = {'message[text]': text,
44 'utf8': '✓',
45 'authenticity_token': self._client.get_token()}
46
47 r = self._client._sessionpost('conversations/{}/messages'.format(self.conv_id),
48 data=data,
49 headers={'accept': 'application/json'})
50 if r.status_code != 200:
51 raise Exception('{0}: Answer could not be posted.'
52 .format(r.status_code))
53 return r.json()
54
55 def delete(self):
56 """ delete this conversation
57 has to be implemented
58 """
59 data = {'authenticity_token': self._client.get_token()}
60
61 r = self._client._sessiondelete('conversations/{0}/visibility/'
62 .format(self.conv_id),
63 data=data,
64 headers={'accept': 'application/json'})
65
66 if r.status_code != 404:
67 raise Exception('{0}: Conversation could not be deleted.'
68 .format(r.status_code))
69
70 def get_subject(self):
71 """ return the subject of this conversation
72 """
73 return self.get_data()['subject']