2 from diaspy
.models
import Post
4 """Docstrings for this module are taken from:
5 https://gist.github.com/MrZYX/01c93096c30dc44caf71
7 Documentation for D* JSON API taken from:
8 http://pad.spored.de/ro/r.qWmvhSZg7rk4OQam
12 """Object representing generic stream. Used in Tag(),
13 Stream(), Activity() etc.
15 def __init__(self
, connection
, location
=''):
17 :param connection: Connection() object
18 :type connection: diaspy.connection.Connection
19 :param location: location of json
22 self
._connection
= connection
24 if location
: self
._location
= location
28 def __contains__(self
, post
):
29 """Returns True if stream contains given post.
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
36 """Provides iterable interface for stream.
38 return iter(self
._stream
)
40 def __getitem__(self
, n
):
41 """Returns n-th item in Stream.
43 return self
._stream
[n
]
46 """Returns length of the Stream.
48 return len(self
._stream
)
50 def _setlocation(self
):
51 """Sets location of the stream.
52 Location defaults to 'stream.json'
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.
60 def _setlocation(self):
61 self._location = 'foo.json'
64 :param location: url of the stream
69 self
._location
= 'stream.json'
72 """Obtains stream from pod.
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()]
80 """Removes all posts from stream.
85 """Removes all unexistent posts from stream.
88 for post
in self
._stream
:
96 if not deleted
: stream
.append(post
)
102 new_stream
= self
._obtain
()
103 ids
= [post
.post_id
for post
in self
._stream
]
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
)
111 self
._stream
= stream
114 """Fills the stream with posts.
116 self
._stream
= self
._obtain
()
119 class Outer(Generic
):
120 """Object used by diaspy.models.User to represent
121 stream of other user.
124 """Obtains stream of other user.
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()]
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.
137 def _setlocation(self
):
138 self
._location
= 'stream.json'
140 def post(self
, text
, aspect_ids
='public', photos
=None):
141 """This function sends a post to an aspect
143 :param text: Text to post.
145 :param aspect_ids: Aspect ids to send post to.
146 :type aspect_ids: str
148 :returns: diaspy.models.Post -- the Post which has been created
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
))
163 post
= Post(str(request
.json()['id']), self
._connection
)
166 def post_picture(self
, filename
):
167 """This method posts a picture to D*.
169 :param filename: Path to picture file.
172 aspects
= self
._connection
.getUserInfo()['aspects']
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']
180 data
= open(filename
, 'rb')
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
)
190 class Activity(Generic
):
191 """Stream representing user's activity.
193 def _setlocation(self
):
194 self
._location
= 'activity.json'
196 def _delid(self
, id):
197 """Deletes post with given id.
200 for p
in self
._stream
:
204 if post
is not None: post
.delete()
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.
212 :param post: post identifier
213 :type post: str, diaspy.models.Post
215 if type(post
) == str: self
._delid
(post
)
216 elif type(post
) == Post
: post
.delete()
218 raise TypeError('this method accepts only int, str or Post: {0} given')
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`
230 def _setlocation(self
):
231 self
._location
= 'aspects.json'
233 def add(self
, aspect_name
, visible
=0):
234 """This function adds a new aspect.
236 data
= {'authenticity_token': self
._connection
.get_token(),
237 'aspect[name]': aspect_name
,
238 'aspect[contacts_visible]': visible
}
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
))
244 def remove(self
, aspect_id
):
245 """This method removes an aspect.
247 data
= {'authenticity_token': self
.connection
.get_token()}
248 r
= self
.connection
.delete('aspects/{}'.format(aspect_id
),
250 if r
.status_code
!= 404:
251 raise Exception('wrong status code: {0}'.format(r
.status_code
))
254 class Commented(Generic
):
255 """This stream contains all posts
256 the user has made a comment on.
258 def _setlocation(self
):
259 self
._location
= 'commented.json'
262 class Liked(Generic
):
263 """This stream contains all posts the user liked.
265 def _setlocation(self
):
266 self
._location
= 'liked.json'
269 class Mentions(Generic
):
270 """This stream contains all posts
271 the user is mentioned in.
273 def _setlocation(self
):
274 self
._location
= 'mentions.json'
277 class FollowedTags(Generic
):
278 """This stream contains all posts
279 containing tags the user is following.
281 def _setlocation(self
):
282 self
._location
= 'followed_tags.json'
284 def remove(self
, tag_id
):
285 """Stop following a tag.
287 :param tag_id: tag id
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
))
295 def add(self
, tag_name
):
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.
300 :param tag_name: tag name
302 :returns: int (response code)
304 data
= {'name':tag_name
,
305 'authenticity_token':self
._connection
.get_token(),
307 headers
={'content-type': 'application/json',
308 'x-csrf-token': self
._connection
.get_token(),
309 'accept': 'application/json'}
311 request
= self
._connection
.post('tag_followings', data
=json
.dumps(data
), headers
=headers
)
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