Merge branch 'streams' into people
[diaspy.git] / diaspy / streams.py
1 import json
2 from diaspy.models import Post
3
4 """Docstrings for this module are taken from:
5 https://gist.github.com/MrZYX/01c93096c30dc44caf71
6
7 Documentation for D* JSON API taken from:
8 http://pad.spored.de/ro/r.qWmvhSZg7rk4OQam
9 """
10
11 class Generic:
12 """Object representing generic stream. Used in Tag(),
13 Stream(), Activity() etc.
14 """
15 def __init__(self, connection, location=''):
16 """
17 :param connection: Connection() object
18 :type connection: diaspy.connection.Connection
19 :param location: location of json
20 :type location: str
21 """
22 self._connection = connection
23 self._setlocation()
24 if location: self._location = location
25 self._stream = []
26 self.fill()
27
28 def __contains__(self, post):
29 """Returns True if stream contains given post.
30 """
31 if type(post) is not Post:
32 raise TypeError('stream can contain only posts: checked for {0}'.format(type(post)))
33 return post in self._stream
34
35 def __iter__(self):
36 """Provides iterable interface for stream.
37 """
38 return iter(self._stream)
39
40 def __getitem__(self, n):
41 """Returns n-th item in Stream.
42 """
43 return self._stream[n]
44
45 def __len__(self):
46 """Returns length of the Stream.
47 """
48 return len(self._stream)
49
50 def _setlocation(self):
51 """Sets location of the stream.
52 Location defaults to 'stream.json'
53
54 NOTICE: inheriting objects should override this method
55 and set their own value to the `location`.
56 However, it is possible to override default location by
57 passing the desired one to the constructor.
58 For example:
59
60 def _setlocation(self):
61 self._location = 'foo.json'
62
63
64 :param location: url of the stream
65 :type location: str
66
67 :returns: str
68 """
69 self._location = 'stream.json'
70
71 def _obtain(self):
72 """Obtains stream from pod.
73 """
74 request = self._connection.get(self._location)
75 if request.status_code != 200:
76 raise Exception('wrong status code: {0}'.format(request.status_code))
77 return [Post(str(post['id']), self._connection) for post in request.json()]
78
79 def clear(self):
80 """Removes all posts from stream.
81 """
82 self._stream = []
83
84 def purge(self):
85 """Removes all unexistent posts from stream.
86 """
87 stream = []
88 for post in self._stream:
89 deleted = False
90 try:
91 post.get_data()
92 stream.append(post)
93 except Exception:
94 deleted = True
95 finally:
96 if not deleted: stream.append(post)
97 self._stream = stream
98
99 def update(self):
100 """Updates stream.
101 """
102 new_stream = self._obtain()
103 ids = [post.post_id for post in self._stream]
104
105 stream = self._stream
106 for i in range(len(new_stream)):
107 if new_stream[-i].post_id not in ids:
108 stream = [new_stream[-i]] + stream
109 ids.append(new_stream[-i].post_id)
110
111 self._stream = stream
112
113 def fill(self):
114 """Fills the stream with posts.
115 """
116 self._stream = self._obtain()
117
118
119 class Outer(Generic):
120 """Object used by diaspy.models.User to represent
121 stream of other user.
122 """
123 def _obtain(self):
124 """Obtains stream of other user.
125 """
126 request = self._connection.get(self._location)
127 if request.status_code != 200:
128 raise Exception('wrong status code: {0}'.format(request.status_code))
129 return [Post(str(post['id']), self._connection) for post in request.json()]
130
131
132 class Stream(Generic):
133 """The main stream containing the combined posts of the
134 followed users and tags and the community spotlights posts
135 if the user enabled those.
136 """
137 def _setlocation(self):
138 self._location = 'stream.json'
139
140 def post(self, text, aspect_ids='public', photos=None):
141 """This function sends a post to an aspect
142
143 :param text: Text to post.
144 :type text: str
145 :param aspect_ids: Aspect ids to send post to.
146 :type aspect_ids: str
147
148 :returns: diaspy.models.Post -- the Post which has been created
149 """
150 data = {}
151 data['aspect_ids'] = aspect_ids
152 data['status_message'] = {'text': text}
153 if photos: data['photos'] = photos
154 request = self._connection.post('status_messages',
155 data=json.dumps(data),
156 headers={'content-type': 'application/json',
157 'accept': 'application/json',
158 'x-csrf-token': self._connection.get_token()})
159 if request.status_code != 201:
160 raise Exception('{0}: Post could not be posted.'.format(
161 request.status_code))
162
163 post = Post(str(request.json()['id']), self._connection)
164 return post
165
166 def post_picture(self, filename):
167 """This method posts a picture to D*.
168
169 :param filename: Path to picture file.
170 :type filename: str
171 """
172 aspects = self._connection.getUserInfo()['aspects']
173 params = {}
174 params['photo[pending]'] = 'true'
175 params['set_profile_image'] = ''
176 params['qqfile'] = filename
177 for i, aspect in enumerate(aspects):
178 params['photo[aspect_ids][%d]' % (i)] = aspect['id']
179
180 data = open(filename, 'rb')
181
182 headers = {'content-type': 'application/octet-stream',
183 'x-csrf-token': self._connection.get_token(),
184 'x-file-name': filename}
185 request = self._connection.post('photos', params=params, data=data, headers=headers)
186 data.close()
187 return request
188
189
190 class Activity(Generic):
191 """Stream representing user's activity.
192 """
193 def _setlocation(self):
194 self._location = 'activity.json'
195
196 def _delid(self, id):
197 """Deletes post with given id.
198 """
199 post = None
200 for p in self._stream:
201 if p['id'] == id:
202 post = p
203 break
204 if post is not None: post.delete()
205
206 def delete(self, post):
207 """Deletes post from users activity.
208 `post` can be either post id or Post()
209 object which will be identified and deleted.
210 After deleting post the stream will be filled.
211
212 :param post: post identifier
213 :type post: str, diaspy.models.Post
214 """
215 if type(post) == str: self._delid(post)
216 elif type(post) == Post: post.delete()
217 else:
218 raise TypeError('this method accepts only int, str or Post: {0} given')
219 self.fill()
220
221
222 class Aspects(Generic):
223 """This stream contains the posts filtered by
224 the specified aspect IDs. You can choose the aspect IDs with
225 the parameter `aspect_ids` which value should be
226 a comma seperated list of aspect IDs.
227 If the parameter is ommitted all aspects are assumed.
228 An example call would be `aspects.json?aspect_ids=23,5,42`
229 """
230 def _setlocation(self):
231 self._location = 'aspects.json'
232
233 def add(self, aspect_name, visible=0):
234 """This function adds a new aspect.
235 """
236 data = {'authenticity_token': self._connection.get_token(),
237 'aspect[name]': aspect_name,
238 'aspect[contacts_visible]': visible}
239
240 r = self._connection.post('aspects', data=data)
241 if r.status_code != 200:
242 raise Exception('wrong status code: {0}'.format(r.status_code))
243
244 def remove(self, aspect_id):
245 """This method removes an aspect.
246 """
247 data = {'authenticity_token': self.connection.get_token()}
248 r = self.connection.delete('aspects/{}'.format(aspect_id),
249 data=data)
250 if r.status_code != 404:
251 raise Exception('wrong status code: {0}'.format(r.status_code))
252
253
254 class Commented(Generic):
255 """This stream contains all posts
256 the user has made a comment on.
257 """
258 def _setlocation(self):
259 self._location = 'commented.json'
260
261
262 class Liked(Generic):
263 """This stream contains all posts the user liked.
264 """
265 def _setlocation(self):
266 self._location = 'liked.json'
267
268
269 class Mentions(Generic):
270 """This stream contains all posts
271 the user is mentioned in.
272 """
273 def _setlocation(self):
274 self._location = 'mentions.json'
275
276
277 class FollowedTags(Generic):
278 """This stream contains all posts
279 containing tags the user is following.
280 """
281 def _setlocation(self):
282 self._location = 'followed_tags.json'
283
284 def remove(self, tag_id):
285 """Stop following a tag.
286
287 :param tag_id: tag id
288 :type tag_id: int
289 """
290 data = {'authenticity_token':self._connection.get_token()}
291 request = self._connection.delete('tag_followings/{0}'.format(tag_id), data=data)
292 if request.status_code != 404:
293 raise Exception('wrong status code: {0}'.format(request.status_code))
294
295 def add(self, tag_name):
296 """Follow new tag.
297 Error code 403 is accepted because pods respod with it when request
298 is sent to follow a tag that a user already follows.
299
300 :param tag_name: tag name
301 :type tag_name: str
302 :returns: int (response code)
303 """
304 data = {'name':tag_name,
305 'authenticity_token':self._connection.get_token(),
306 }
307 headers={'content-type': 'application/json',
308 'x-csrf-token': self._connection.get_token(),
309 'accept': 'application/json'}
310
311 request = self._connection.post('tag_followings', data=json.dumps(data), headers=headers)
312
313 if request.status_code not in [201, 403]:
314 raise Exception('wrong error code: {0}'.format(request.status_code))
315 return request.status_code