From 18891464654b3d1896adb0e0de5c55bcd399ab2e Mon Sep 17 00:00:00 2001 From: CYBERDEViLNL Date: Thu, 7 Mar 2019 22:21:46 +0100 Subject: [PATCH] Revert "Merge branch 'devel' into master" This wasn't my intent. Oops. --- Changelog.markdown | 41 ------------- diaspy/__init__.py | 3 +- diaspy/connection.py | 51 +++------------- diaspy/errors.py | 4 -- diaspy/models.py | 131 ++++++++-------------------------------- diaspy/notifications.py | 15 +++-- diaspy/streams.py | 116 +++++++++-------------------------- diaspy/tagFollowings.py | 50 --------------- docs/source/conf.py | 4 +- setup.py | 2 +- 10 files changed, 73 insertions(+), 344 deletions(-) delete mode 100644 diaspy/tagFollowings.py diff --git a/Changelog.markdown b/Changelog.markdown index 70c584b..8b11250 100644 --- a/Changelog.markdown +++ b/Changelog.markdown @@ -27,47 +27,6 @@ up-to-date than manual and if conflicts appear they should follow the order: ---- -#### Version `0.6.1.dev` (not final changelog for this version, still in development) - -* __upd__: `diaspy.models.Post.like()`, `diaspy.models.Post.delete_like()`, `diaspy.models.Post.reshare()` will now update data (count and likes/reshares) without doing another request. -* __upd__: Add `Comment()` to `diaspy.models.Post.comments` on `diaspy.models.Post.comment()` -* __upd__: Delete `Comment()` from `diaspy.models.Post.comments` on `diaspy.models.Post.delete_comment()` -* __upd__: Update `diaspy.models.Post._data["poll"]["participation_count"]` and `diaspy.models.Post._data["poll_participation_answer_id"]` after `diaspy.models.Post.vote_poll()` -* __upd__: Update `diaspy.models.Post._data["participation"]` on `diaspy.models.Post.subscribe()` and `diaspy.models.Post.unsubscribe()` -* __upd__: Removed `verify` keyword from `diaspy.connection.Connection` it's methods, it's now done through `**requestKwargs`. Default is still `True`. -* __upd__: `diaspy.streams.Stream._photoupload()` to more public method `diaspy.streams.Stream.photoupload()` -* __upd__: Update `diaspy.models.Notification.unread` and `diaspy.models.Notification._data['unread']` on `diasply.models.Notification.mark()` - - -* __fix__: `diaspy.models.Post.__init__()` checking on different fetch states was a mess. -* __fix__: `diaspy.streams.Asepcts.filter()` location fix. -* __fix__: Don't update `diaspy.notifications.Notifications` it's `unread_count_by_type` and `unread_count` on `diaspy.notifications.Notifications._expand()` and `diaspy.notifications.Notifications._update()` since it's already done in `diaspy.notifications.Notifications._finalize()` - - -* __new__: `diaspy.tagFollowings.TagFollowings()` which represents the tags followed by the user. -* __new__: `diaspy.models.FollowedTag()` which represents a tag followed by the user. It is used by `diaspy.tagFollowings.TagFollowings()`. -* __new__: It is now possible to give `**requestKwargs` to `diaspy.connection.Connection()` which will be used for every `request` unless directly overwritten by given the function you call different key-worded arguments. -* __new__: `diaspy.connection.Connection()` now does check if the `pod` you are connecting to has `Camo` enabled or not. Call `diaspy.connection.Connection.camo()` to receive `True` or `False`. -* __new__: `diaspy.models.Comment.authordata()` which will return all author data instead of `diaspy.models.Comment.author()` which will only return data for a certain key. -* __new__: `diaspy.streams.Public()` -* __new__: `diaspy.models.Post.fetchlikes()`. -* __new__: `diaspy.models.Post.fetchreshares()` -* __new__: `diaspy.streams.Generic.deletePostGuid()` deletes `Post` with given `guid` from the local stream object. (If you manualy update a post and find that it's been deleted, call this with the `guid` of the deleted `Post`) -* __new__: `diaspy.streams.Stream.deletephoto()` -* __new__: `diaspy.notifications.Notifications.__len__()` -* __new__: `diaspy.notifications.Notifications.data()` -* __new__: `diaspy.models.Comments.delete()` deletes comment by `id`. -* __new__: `diaspy.errors.NotificationError` - -* __rem__: `diaspy.streams.FollowedTags.get()` since it wasn’t doing anything usefull. - -* __dep__: `diaspy.streams.FollowedTags.remove()` Use `diaspy.tagFollowings.TagFollowings[“tagName”].delete()` instead. -* __dep__: `diaspy.streams.FollowedTags.add()` Use diaspy.tagFollowings.TagFollowings.follow() instead. - - ----- - - #### Version `0.6.0` In this release some bugs due to Diaspora changes where adressed, it also diff --git a/diaspy/__init__.py b/diaspy/__init__.py index aa470b6..fee78fd 100644 --- a/diaspy/__init__.py +++ b/diaspy/__init__.py @@ -8,7 +8,6 @@ import diaspy.conversations as conversations import diaspy.people as people import diaspy.notifications as notifications import diaspy.settings as settings -import diaspy.tagFollowings as tagFollowings -__version__ = '0.6.1.dev' +__version__ = '0.6.0' diff --git a/diaspy/connection.py b/diaspy/connection.py index 2c91b7e..2001c45 100644 --- a/diaspy/connection.py +++ b/diaspy/connection.py @@ -27,7 +27,7 @@ class Connection(): _userinfo_regex_2 = re.compile(r'gon.user=({.*?});gon.') _verify_SSL = True - def __init__(self, pod, username, password, schema='https', **requestsKwargs): + def __init__(self, pod, username, password, schema='https'): """ :param pod: The complete url of the diaspora pod to use. :type pod: str @@ -35,8 +35,6 @@ class Connection(): :type username: str :param password: The password used to log in. :type password: str - :param requestsKwargs: default kwargs for requests (proxy, timeout, etc) - :type requestsKwargs: keyworded arguments """ self.pod = pod self._session = requests.Session() @@ -45,24 +43,15 @@ class Connection(): self._token = '' self._diaspora_session = '' self._fetch_token_from = 'stream' - self._requests_kwargs = {'verify':self._verify_SSL} - if requestsKwargs: self._requests_kwargs.update(requestsKwargs) - - self._camo_enabled = False try: self._setlogin(username, password) except requests.exceptions.MissingSchema: self.pod = '{0}://{1}'.format(schema, self.pod) warnings.warn('schema was missing') - try: self._setlogin(username, password) except Exception as e: raise errors.LoginError('cannot create login data (caused by: {0})'.format(e)) self._cookies = self._fetchcookies() - def __bool__(self): - if self._token: return True - return False - def _fetchcookies(self): request = self.get('stream') return request.cookies @@ -75,16 +64,6 @@ class Connection(): """ return self._fetchtoken() - def requestsKwargs(self): - """Returns keyworded arguments set to use for all requests. - """ - return self._requests_kwargs - - def setRequestsKwargs(self, **requestsKwargs): - """Sets keyworded arguments that will be used for earch request. - """ - self._requests_kwargs = requestsKwargs - def get(self, string, headers={}, params={}, direct=False, **kwargs): """This method gets data from session. Performs additional checks if needed. @@ -99,8 +78,7 @@ class Connection(): """ if not direct: url = '{0}/{1}'.format(self.pod, string) else: url = string - if not kwargs: kwargs = self._requests_kwargs - return self._session.get(url, params=params, headers=headers, **kwargs) + return self._session.get(url, params=params, headers=headers, verify=self._verify_SSL, **kwargs) def tokenFrom(self, location): """Sets location for the *next* fetch of CSRF token. @@ -132,8 +110,7 @@ class Connection(): string = '{0}/{1}'.format(self.pod, string) if 'X-CSRF-Token' not in headers: headers['X-CSRF-Token'] = self.get_token() - if not kwargs: kwargs = self._requests_kwargs - request = self._session.post(string, data, headers=headers, params=params, **kwargs) + request = self._session.post(string, data, headers=headers, params=params, verify=self._verify_SSL, **kwargs) return request def put(self, string, data=None, headers={}, params={}, **kwargs): @@ -142,9 +119,8 @@ class Connection(): string = '{0}/{1}'.format(self.pod, string) if 'X-CSRF-Token' not in headers: headers['X-CSRF-Token'] = self.get_token() - if not kwargs: kwargs = self._requests_kwargs if data is not None: request = self._session.put(string, data, headers=headers, params=params, **kwargs) - else: request = self._session.put(string, headers=headers, params=params, **kwargs) + else: request = self._session.put(string, headers=headers, params=params, verify=self._verify_SSL, **kwargs) return request def delete(self, string, data = None, headers={}, **kwargs): @@ -160,18 +136,9 @@ class Connection(): string = '{0}/{1}'.format(self.pod, string) if 'X-CSRF-Token' not in headers: headers['X-CSRF-Token'] = self.get_token() - if not kwargs: kwargs = self._requests_kwargs - request = self._session.delete(string, data=data, headers=headers, **kwargs) + request = self._session.delete(string, data=data, headers=headers, verify=self._verify_SSL, **kwargs) return request - def _checkCamo(self): - response = self._session.head("{0}/camo/".format(self.pod), - **self._requests_kwargs) - if response.status_code == 200: self._camo_enabled = True - else: self._camo_enabled = False - - def camo(self): return self._camo_enabled; - def _setlogin(self, username, password): """This function is used to set data for login. @@ -191,7 +158,6 @@ class Connection(): allow_redirects=False) if request.status_code != 302: raise errors.LoginError('{0}: login failed'.format(request.status_code)) - self._checkCamo() def login(self, remember_me=1): """This function is used to log in to a pod. @@ -210,9 +176,6 @@ class Connection(): """ self.get('users/sign_out') self.token = '' - self._userdata = {} - self._diaspora_session = '' - self._camo_enabled = False def podswitch(self, pod, username, password, login=True): """Switches pod from current to another one. @@ -260,7 +223,8 @@ class Connection(): """ return self._diaspora_session - def userdata(self): return self._userdata + def userdata(self): + return self._userdata def getUserData(self): """Returns user data. @@ -277,4 +241,3 @@ class Connection(): """Sets whether there should be an error if a SSL-Certificate could not be verified. """ self._verify_SSL = verify - self._requests_kwargs.update({'verify':verify}) diff --git a/diaspy/errors.py b/diaspy/errors.py index 5aa612a..48d754a 100644 --- a/diaspy/errors.py +++ b/diaspy/errors.py @@ -72,10 +72,6 @@ class SearchError(DiaspyError): """ pass -class NotificationError(DiaspyError): - """Exception raised when something related to notifications goes wrong. - """ - pass class ConversationError(DiaspyError): """Exception raised when something related to conversations goes wrong. diff --git a/diaspy/models.py b/diaspy/models.py index 4cd0401..9468ddc 100644 --- a/diaspy/models.py +++ b/diaspy/models.py @@ -212,11 +212,8 @@ class Notification(): """ headers = {'x-csrf-token': repr(self._connection)} params = {'set_unread': json.dumps(unread)} - response = self._connection.put('notifications/{0}'.format(self['id']), params=params, headers=headers) - if response.status_code != 200: - raise errors.NotificationError('Cannot mark notification: {0}'.format(response.status_code)) + self._connection.put('notifications/{0}'.format(self['id']), params=params, headers=headers) self._data['unread'] = unread - self.unread = unread class Conversation(): @@ -428,11 +425,6 @@ class Comment(): """ return self._data['author'][key] - def authordata(self): - """Returns all author data of the comment. - """ - return self._data['author'] - class Comments(): def __init__(self, comments=[]): self._comments = comments @@ -453,12 +445,6 @@ class Comments(): def ids(self): return [c.id for c in self._comments] - def delete(self, comment_id): - for index, comment in enumerate(self._comments): - if comment.id == comment_id: - self._comments.pop(index); - break; - def add(self, comment): """ Expects Comment() object @@ -506,11 +492,16 @@ class Post(): self.guid = guid self._data = {} self.comments = Comments() - if post_data: self._setdata(post_data) - elif fetch: self._fetchdata() + if post_data: + self._data = post_data + + if fetch: self._fetchdata() if comments: if not self._data: self._fetchdata() self._fetchcomments() + else: + if not self._data: self._fetchdata() + self.comments.set_json( self.data()['interactions']['comments'] ) def __repr__(self): """Returns string containing more information then str(). @@ -522,13 +513,6 @@ class Post(): """ return self._data['text'] - def _setdata(self, data): - self._data = data - self.guid = data["guid"] - self.id = data["id"] - if not bool(self.comments) and data['interactions'].get('comments', []): - self.comments.set_json(data['interactions'].get('comments', [])) - def _fetchdata(self): """This function retrieves data of the post. @@ -539,7 +523,8 @@ class Post(): request = self._connection.get('posts/{0}.json'.format(id)) if request.status_code != 200: raise errors.PostError('{0}: could not fetch data for post: {1}'.format(request.status_code, id)) - elif request: self._setdata(request.json()); + elif request: + self._data = request.json() return self.data()['guid'] def _fetchcomments(self): @@ -555,33 +540,12 @@ class Post(): else: self.comments.set([Comment(c) for c in request.json()]) - def _fetchlikes(self): - id = self.data()['id'] - request = self._connection.get('posts/{0}/likes.json'.format(id)) - if request.status_code != 200: - raise errors.PostError('{0}: could not fetch likes for post: {1}'.format(request.status_code, id)) - json = request.json(); - if json: self._data['interactions']['likes'] = request.json(); - return self._data['interactions']['likes']; - - def _fetchreshares(self): - id = self.data()['id'] - request = self._connection.get('posts/{0}/reshares.json'.format(id)) - if request.status_code != 200: - raise errors.PostError('{0}: could not fetch likes for post: {1}'.format(request.status_code, id)) - - json = request.json(); - if json: self._data['interactions']['reshares'] = request.json(); - return self._data['interactions']['reshares']; - - def fetchlikes(self): return self._fetchlikes(); - def fetchreshares(self): return self._fetchreshares(); - def fetch(self, comments = False): """Fetches post data. """ self._fetchdata() - if comments: self._fetchcomments() + if comments: + self._fetchcomments() return self def data(self, data = None): @@ -597,7 +561,7 @@ class Post(): """ data = {'authenticity_token': repr(self._connection)} - request = self._connection.post('posts/{0}/likes'.format(self.id), + request = self._connection.post('posts/{0}/likes'.format(self.id), data=data, headers={'accept': 'application/json'}) @@ -607,8 +571,7 @@ class Post(): likes_json = request.json() if likes_json: - self._data['interactions']['likes'].insert(0, likes_json) - self._data['interactions']['likes_count'] = str(int(self._data['interactions']['likes_count'])+1) + self._data['interactions']['likes'] = [likes_json] return likes_json def reshare(self): @@ -622,11 +585,6 @@ class Post(): headers={'accept': 'application/json'}) if request.status_code != 201: raise Exception('{0}: Post could not be reshared'.format(request.status_code)) - - reshares_json = request.json() - if reshares_json: - self._data['interactions']['reshares'].insert(0, reshares_json) - self._data['interactions']['reshares_count'] = str(int(self._data['interactions']['reshares_count'])+1) return request.json() def comment(self, text): @@ -644,9 +602,7 @@ class Post(): if request.status_code != 201: raise Exception('{0}: Comment could not be posted.' .format(request.status_code)) - comment = Comment(request.json()) - self.comments.add(comment); - return comment + return Comment(request.json()) def vote_poll(self, poll_answer_id): """This function votes on a post's poll @@ -665,22 +621,13 @@ class Post(): if request.status_code != 201: raise Exception('{0}: Vote on poll failed.' .format(request.status_code)) - - data = request.json() - self._data["poll"]["participation_count"] += 1 - self._data["poll_participation_answer_id"] = data["poll_participation"]["poll_answer_id"] - - for answer in self._data["poll"]["poll_answers"]: - if answer["id"] == poll_answer_id: - answer["vote_count"] +=1; - break; - return data + return request.json() def hide(self): """ - -> PUT /share_visibilities/42 HTTP/1.1 + -> PUT /share_visibilities/42 HTTP/1.1 post_id=123 - <- HTTP/1.1 200 OK + <- HTTP/1.1 200 OK """ headers = {'x-csrf-token': repr(self._connection)} params = {'post_id': json.dumps(self.id)} @@ -691,9 +638,9 @@ class Post(): def mute(self): """ - -> POST /blocks HTTP/1.1 + -> POST /blocks HTTP/1.1 {"block":{"person_id":123}} - <- HTTP/1.1 204 No Content + <- HTTP/1.1 204 No Content """ headers = {'content-type':'application/json', 'x-csrf-token': repr(self._connection)} data = json.dumps({ 'block': { 'person_id' : self._data['author']['id'] } }) @@ -704,8 +651,8 @@ class Post(): def subscribe(self): """ - -> POST /posts/123/participation HTTP/1.1 - <- HTTP/1.1 201 Created + -> POST /posts/123/participation HTTP/1.1 + <- HTTP/1.1 201 Created """ headers = {'x-csrf-token': repr(self._connection)} data = {} @@ -715,13 +662,11 @@ class Post(): raise Exception('{0}: Failed to subscribe to post' .format(request.status_code)) - self._data.update({"participation" : True}) - def unsubscribe(self): """ - -> POST /posts/123/participation HTTP/1.1 + -> POST /posts/123/participation HTTP/1.1 _method=delete - <- HTTP/1.1 200 OK + <- HTTP/1.1 200 OK """ headers = {'x-csrf-token': repr(self._connection)} data = { "_method": "delete" } @@ -731,8 +676,6 @@ class Post(): raise Exception('{0}: Failed to unsubscribe to post' .format(request.status_code)) - self._data.update({"participation" : False}) - def report(self): """ TODO @@ -765,8 +708,6 @@ class Post(): raise errors.PostError('{0}: Comment could not be deleted' .format(request.status_code)) - self.comments.delete(comment_id) - def delete_like(self): """This function removes a like from a post """ @@ -777,32 +718,8 @@ class Post(): raise errors.PostError('{0}: Like could not be removed.' .format(request.status_code)) - self._data['interactions']['likes'].pop(0); - self._data['interactions']['likes_count'] = str(int(self._data['interactions']['likes_count'])-1) - def author(self, key='name'): """Returns author of the post. :param key: all keys available in data['author'] """ return self._data['author'][key] - -class FollowedTag(): - """This class represents a followed tag. - `diaspy.tagFollowings.TagFollowings()` uses it. - """ - def __init__(self, connection, id, name, taggings_count): - self._connection = connection - self._id, self._name, self._taggings_count = id, name, taggings_count - - def id(self): return self._id - def name(self): return self._name - def count(self): return self._taggings_count - - def delete(self): - data = {'authenticity_token': repr(self._connection)} - request = self._connection.delete('tag_followings/{0}'.format(self._id), - data=data, - headers={'accept': 'application/json'}) - if request.status_code != 204: - raise errors.TagError('{0}: Tag could not be deleted.' - .format(request.status_code)) diff --git a/diaspy/notifications.py b/diaspy/notifications.py index 877c80f..cb5b42f 100644 --- a/diaspy/notifications.py +++ b/diaspy/notifications.py @@ -19,8 +19,6 @@ class Notifications(): self._notifications = self.get() self.page = 1 - def __len__(self): return len(self._notifications); - def __iter__(self): return iter(self._notifications) @@ -32,8 +30,6 @@ class Notifications(): self._data['unread_count_by_type'] = notifications['unread_count_by_type'] return [Notification(self._connection, n) for n in notifications.get('notification_list', [])] - def data(self): return self._data; - def last(self): """Returns list of most recent notifications. """ @@ -52,10 +48,13 @@ class Notifications(): data = self._data for n in new_notifications: if n.id not in ids: + if n.unread: + data['unread_count'] +=1 + data['unread_count_by_type'][n.type] +=1 notifications.append(n) ids.append(n.id) self._notifications = notifications - self._data.update(data); + self._data = data def _update(self, new_notifications): ids = [notification.id for notification in self._notifications] @@ -68,6 +67,9 @@ class Notifications(): for i in range(len(new_notifications)): if new_notifications[-i].id not in ids: + if new_notifications[-i].unread: + data['unread_count'] +=1 + data['unread_count_by_type'][new_notifications[-i].type] +=1 notifications = [new_notifications[-i]] + notifications ids.append(new_notifications[-i].id) self._notifications = notifications @@ -82,7 +84,8 @@ class Notifications(): if not page: page = self.page + 1 self.page = page result = self.get(per_page=per_page, page=page) - if result: self._expand( result ) + if result: + self._expand( result ) def get(self, per_page=5, page=1): """Returns list of notifications. diff --git a/diaspy/streams.py b/diaspy/streams.py index c56ab60..db4d103 100644 --- a/diaspy/streams.py +++ b/diaspy/streams.py @@ -63,12 +63,6 @@ class Generic(): """ return len(self._stream) - def __bool__(self): - """Returns True if stream os filled, False if not. - """ - if self._stream: return True - return False - def _obtain(self, max_time=0, suppress=True): """Obtains stream from pod. @@ -84,17 +78,14 @@ class Generic(): params['_'] = self.latest request = self._connection.get(self._location, params=params) if request.status_code != 200: - raise errors.StreamError('wrong status code: {0}' - .format(request.status_code)) + raise errors.StreamError('wrong status code: {0}'.format(request.status_code)) posts = [] latest_time = None # Used to get the created_at from the latest posts we received. for post in request.json(): try: comments = False if post['interactions']['comments_count'] > 3: comments = True - posts.append(Post(self._connection, id=post['id'], - guid=post['guid'], fetch=False, comments=comments, - post_data=post)) + posts.append(Post(self._connection, id=post['id'], guid=post['guid'], fetch=False, comments=comments, post_data=post)) if post['created_at']: latest_time = post['created_at'] except errors.PostError: if not suppress: @@ -131,21 +122,6 @@ class Generic(): """ self._stream = [] - def deletePostGuid(self, guid): - """Deleted post from stream by guid - - :param guid: guid of the post to delete - :type guid: str - - NOTE: This affects local object only! So no request will be made to a - pod. This can be used if you tried to update a Post() and it failed then - you know the post is deleted. - """ - for index, post in enumerate(self._stream): - if post.guid == guid: - self._stream.pop(index); - break; - def purge(self): """Removes all unexistent posts from stream. """ @@ -253,9 +229,7 @@ class Stream(Generic): """ location = 'stream.json' - def post(self, text='', aspect_ids='public', photos=None, photo='', - poll_question=None, poll_answers=None, location_coords=None, - provider_display_name=''): + def post(self, text='', aspect_ids='public', photos=None, photo='', poll_question=None, poll_answers=None, location_coords=None, provider_display_name=''): """This function sends a post to an aspect. If both `photo` and `photos` are specified `photos` takes precedence. @@ -268,7 +242,7 @@ class Stream(Generic): :param photo: filename of photo to post :type photo: str - :param photos: id of photo to post (obtained from photoupload()) + :param photos: id of photo to post (obtained from _photoupload()) :type photos: int :param provider_display_name: name of provider displayed under the post @@ -287,9 +261,8 @@ class Stream(Generic): """ data = {} data['aspect_ids'] = aspect_ids - data['status_message'] = ({'text': text, - 'provider_display_name': provider_display_name}) - if photo: data['photos'] = self.photoupload(photo) + data['status_message'] = {'text': text, 'provider_display_name': provider_display_name} + if photo: data['photos'] = self._photoupload(photo) if photos: data['photos'] = photos if poll_question and poll_answers: data['poll_question'] = poll_question @@ -297,33 +270,17 @@ class Stream(Generic): if location_coords: data['location_coords'] = location_coords request = self._connection.post('status_messages', - data=json.dumps(data), - headers={'content-type': 'application/json', - 'accept': 'application/json', - 'x-csrf-token': repr(self._connection)}) + data=json.dumps(data), + headers={'content-type': 'application/json', + 'accept': 'application/json', + 'x-csrf-token': repr(self._connection)}) if request.status_code != 201: - raise Exception('{0}: Post could not be posted.' - .format(request.status_code)) + raise Exception('{0}: Post could not be posted.'.format(request.status_code)) post_json = request.json() - post = Post(self._connection, id=post_json['id'], - guid=post_json['guid'], post_data=post_json) - self._stream.insert(0, post); + post = Post(self._connection, id=post_json['id'], guid=post_json['guid'], post_data=post_json) return post - def deletephoto(self, id): - """Remove photo from the pod (if decided not needed anymore). - - :param id: photo id to delete - :type id: int - """ - data = {'authenticity_token': repr(self._connection)} - request = self._connection.delete('photos/{0}'.format(id), - data=data, - headers={'accept': 'application/json'}) - if request.status_code != 204: - raise errors.StreamError('{0}: Photo could not be deleted'.format(request.status_code)) - - def photoupload(self, filename, aspects=[]): + def _photoupload(self, filename, aspects=[]): """Uploads picture to the pod. :param filename: path to picture file @@ -349,11 +306,9 @@ class Stream(Generic): 'x-csrf-token': repr(self._connection), 'x-file-name': filename} - request = self._connection.post('photos', data=image, params=params, - headers=headers) + request = self._connection.post('photos', data=image, params=params, headers=headers) if request.status_code != 200: - raise errors.StreamError('photo cannot be uploaded: {0}' - .format(request.status_code)) + raise errors.StreamError('photo cannot be uploaded: {0}'.format(request.status_code)) return request.json()['data']['photo']['id'] @@ -417,8 +372,7 @@ class Aspects(Generic): :parameter ids: list of apsect ids :type ids: list of integers """ - self._location = 'aspects.json?a_ids[]=' + '{}'.format( - '&a_ids[]='.join(str(id) for id in ids)) + self._location = 'aspects.json?a_ids[]=' + '{}'.format('&a_ids[]='.join(ids)) self.fill() # this will create entirely new list of posts. def add(self, aspect_name, visible=0): @@ -437,8 +391,7 @@ class Aspects(Generic): request = self._connection.post('aspects', data=data) if request.status_code not in [200, 422]: - raise Exception('wrong status code: {0}' - .format(request.status_code)) + raise Exception('wrong status code: {0}'.format(request.status_code)) id = self.getAspectID(aspect_name) return Aspect(self._connection, id) @@ -461,8 +414,7 @@ class Aspects(Generic): 'authenticity_token': repr(self._connection)} request = self._connection.post('aspects/{0}'.format(id), data=data) if request.status_code not in [200, 302, 500]: - raise Exception('wrong status code: {0}: cannot remove aspect' - .format(request.status_code)) + raise Exception('wrong status code: {0}: cannot remove aspect'.format(request.status_code)) class Commented(Generic): @@ -485,34 +437,27 @@ class Mentions(Generic): _location = 'mentions.json' -class Public(Generic): - """Public stream. - """ - _location = 'public.json' - - class FollowedTags(Generic): """This stream contains all posts containing tags the user is following. """ _location = 'followed_tags.json' + def get(self): + """Returns list of followed tags. + """ + return [] + def remove(self, tag_id): """Stop following a tag. :param tag_id: tag id :type tag_id: int - - FIXME: - Deprecated, this function will be removed in next version. - Use diaspy.tagFollowings.TagFollowings[“tagName”].delete() instead. """ data = {'authenticity_token': self._connection.get_token()} - request = self._connection.delete('tag_followings/{0}' - .format(tag_id), data=data) + request = self._connection.delete('tag_followings/{0}'.format(tag_id), data=data) if request.status_code != 404: - raise Exception('wrong status code: {0}' - .format(request.status_code)) + raise Exception('wrong status code: {0}'.format(request.status_code)) def add(self, tag_name): """Follow new tag. @@ -522,10 +467,6 @@ class FollowedTags(Generic): :param tag_name: tag name :type tag_name: str :returns: int (response code) - - FIXME: - Deprecated, this function will be removed in next version. - Use diaspy.tagFollowings.TagFollowings.follow() instead. """ data = {'name': tag_name, 'authenticity_token': repr(self._connection), @@ -535,8 +476,7 @@ class FollowedTags(Generic): 'accept': 'application/json' } - request = self._connection.post('tag_followings', data=json.dumps(data), - headers=headers) + request = self._connection.post('tag_followings', data=json.dumps(data), headers=headers) if request.status_code not in [201, 403]: raise Exception('wrong error code: {0}'.format(request.status_code)) @@ -553,4 +493,6 @@ class Tag(Generic): :param tag: tag name :type tag: str """ - super().__init__(connection, 'tags/{0}.json'.format(tag), fetch) + location = 'tags/{0}.json'.format(tag) + super().__init__(connection, location.format(tag), fetch=fetch) + self._connection = connection diff --git a/diaspy/tagFollowings.py b/diaspy/tagFollowings.py deleted file mode 100644 index 65daa94..0000000 --- a/diaspy/tagFollowings.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python3 -from diaspy.models import FollowedTag -from diaspy import errors -class TagFollowings(): - """This class represents the tags followed by the user. - - Should return `dict`s in a `list` with the following keys: - `id`, `name`, `taggings_count` - """ - def __init__(self, connection, fetch=True): - self._connection = connection - self._tags = [] - if fetch: self.fetch() - - def __iter__(self): return iter(self._tags) - - def __getitem__(self, t): return self._tags[t] - - def _finalise(self, tags): - return([FollowedTag(self._connection, t['id'], t['name'], - t['taggings_count']) for t in tags]) - - def fetch(self): - """(Re-)Fetches your followed tags. - """ - self._tags = self.get() - - def follow(self, name): - """Follows a tag by given name. - - Returns FollowedTag object. - """ - data = {'authenticity_token': repr(self._connection)} - params = {'name': name} - request = self._connection.post('tag_followings', data=data, - params=params, headers={'accept': 'application/json'}) - if request.status_code != 201: - raise errors.TagError('{0}: Tag could not be followed.' - .format(request.status_code)) - result = request.json() - self._tags.append(FollowedTag(self._connection, result['id'], - result['name'], result['taggings_count'])) - return self._tags[(len(self._tags) - 1)] - - def get(self): - request = self._connection.get('tag_followings.json') - if request.status_code != 200: - raise Exception('status code: {0}: cannot retreive tag_followings' - .format(request.status_code)) - return self._finalise(request.json()) diff --git a/docs/source/conf.py b/docs/source/conf.py index d2d1fe3..3e71fe4 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -51,9 +51,9 @@ copyright = '2013, Moritz Kiefer, Marek Marecki and others' # built documents. # # The short X.Y version. -version = '0.6.1' +version = '0.6.0' # The full version, including alpha/beta/rc tags. -release = '0.6.1.dev' +release = '0.6.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/setup.py b/setup.py index e9ed179..5ed40f1 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages setup( name='diaspy-api', - version='0.6.1.dev', + version='0.6.0', author='Marek Marecki', author_email='marekjm@ozro.pw', url='https://github.com/marekjm/diaspy', -- 2.25.1