Merge branch 'posts' into devel
[diaspy.git] / diaspy / client.py
index 7d1678da111433cbdcf346f2adbf9e9616400686..aae0681978c1d9d69c003028d9827b7b90a07889 100644 (file)
@@ -5,10 +5,9 @@ import diaspy.models
 
 
 class Client:
-    """This is the client class to connect to diaspora.
+    """This is the client class to connect to Diaspora.
 
     """
-
     def __init__(self, pod, username, password):
         """
         :param pod: The complete url of the diaspora pod to use.
@@ -17,12 +16,13 @@ class Client:
         :type username: str
         :param password: The password used to log in.
         :type password: str
-
         """
         self._token_regex = re.compile(r'content="(.*?)"\s+name="csrf-token')
         self.pod = pod
         self.session = requests.Session()
-        self._login(username, password)
+        self._post_data = {}
+        self._setlogindata(username, password)
+        self._login()
 
     def get_token(self):
         """This function gets a token needed for authentication in most cases
@@ -30,72 +30,94 @@ class Client:
         :returns: string -- token used to authenticate
 
         """
-
-        r = self.session.get(self.pod + '/stream')
+        r = self.session.get('{0}/stream'.format(self.pod))
         token = self._token_regex.search(r.text).group(1)
         return token
 
-    def _login(self, username, password):
-        """This function is used to connect to the pod and log in.
+    def _setlogindata(self, username, password):
+        """This function is used to set data for login. 
+        
         .. note::
-           This function shouldn't be called manually.
+            It should be called before _login() function.
         """
-        self._username = username
-        self._password = password
         #r = self.session.get(self.pod + '/users/sign_in')
         #token = self._token_regex.search(r.text).group(1)
-
-        data = {'user[username]': self._username,
-                'user[password]': self._password,
-                'authenticity_token': self.get_token()}
-
-        r = self.session.post(self.pod +
-                              '/users/sign_in',
-                              data=data,
+        self._username, self._password = username, password
+        self._login_data =  {
+                            'user[username]': self._username,
+                            'user[password]': self._password,
+                            'authenticity_token': self.get_token(),
+                            }
+
+    def _login(self):
+        """This function is used to connect to the pod and log in.
+        """
+        r = self.session.post('{0}/users/sign_in'.format(self.pod),
+                              data=self._login_data,
                               headers={'accept': 'application/json'})
+        
+        if r.status_code != 201: raise Exception('{0}: Login failed.'.format(r.status_code))
 
-        if r.status_code != 201:
-            raise Exception(str(r.status_code) + ': Login failed.')
-
-    def post(self, text, aspect_id='public', photos=None):
-        """This function sends a post to an aspect
-
+    def _setpostdata(self, text, aspect_id, photos):
+        """This function prepares data for posting.
         :param text: Text to post.
         :type text: str
         :param aspect_id: Aspect id to send post to.
         :type aspect_id: str
+        """
+        data = {}
+        data['aspect_id'] = aspect_id
+        data['status_message'] = {'text': text}
+        if photos: data['photos'] = photos
+        self._post_data = data
 
-        :returns: diaspy.models.Post -- the Post which has been created
+    def _post(self):
+        """Sends post to an aspect.
 
+        :returns: diaspy.models.Post -- the Post which has been created
         """
-        data = {'aspect_ids': aspect_id,
-                'status_message': {'text': text}}
-
-        if photos:
-            data['photos'] = photos
-        r = self.session.post(self.pod +
-                              "/status_messages",
-                              data=json.dumps(data),
+        r = self.session.post('{0}/status_messages'.format(self.pod),
+                              data=json.dumps(self._post_data),
                               headers={'content-type': 'application/json',
                                        'accept': 'application/json',
                                        'x-csrf-token': self.get_token()})
-        if r.status_code != 201:
-            raise Exception(str(r.status_code) + ': Post could not be posted.')
+        if r.status_code != 201: raise Exception('{0}: Post could not be posted.'.format(r.status_code))
 
         return diaspy.models.Post(str(r.json()['id']), self)
 
+    def post(self, text, aspect_id='public', photos=None):
+        """This function sends a post to an aspect
+
+        :param text: Text to post.
+        :type text: str
+        :param aspect_id: Aspect id to send post to.
+        :type aspect_id: str
+
+        :returns: diaspy.models.Post -- the Post which has been created
+        """
+        self._setpostdata(text, aspect_id, photos)
+        post = self._post()
+        self._post_data = {}
+        return post
+
     def get_user_info(self):
         """This function returns the current user's attributes.
 
         :returns: dict -- json formatted user info.
 
         """
-        r = self.session.get(self.pod + '/bookmarklet')
+        r = self.session.get('{0}/bookmarklet'.format(self.pod))
         regex = re.compile(r'window.current_user_attributes = ({.*})')
         userdata = json.loads(regex.search(r.text).group(1))
         return userdata
 
     def post_picture(self, filename):
+        """This method posts a picture to D*.
+
+        :param filename: Path to picture file.
+        :type filename: str
+        """
         aspects = self.get_user_info()['aspects']
         params = {}
         params['photo[pending]'] = 'true'
@@ -110,7 +132,7 @@ class Client:
                    'x-csrf-token': self.get_token(),
                    'x-file-name': filename}
 
-        r = self.session.post(self.pod + '/photos',
+        r = self.session.post('{0}/photos'.format(self.pod),
                               params=params, data=data, headers=headers)
 
         return r
@@ -123,17 +145,13 @@ class Client:
         """
 
         data = {'authenticity_token': self.get_token()}
-        r = self.session.get(self.pod + "/stream.json")
+        r = self.session.get('{0}/stream.json'.format(self.pod))
 
         if r.status_code != 200:
-            raise Exception('wrong status code: ' + str(r.status_code))
+            raise Exception('wrong status code: {0}'.format(r.status_code))
 
         stream = r.json()
-
-        posts = []
-
-        for post in stream:
-            posts.append(diaspy.models.Post(str(post['id']), self))
+        posts = [ diaspy.models.Post(str(post['id']), self) for post in stream ]
 
         return posts
 
@@ -145,10 +163,10 @@ class Client:
         """
 
         data = {'authenticity_token': self.get_token()}
-        r = self.session.get(self.pod + "/notifications.json")
+        r = self.session.get('{0}/notifications.json'.format(self.pod))
 
         if r.status_code != 200:
-            raise Exception('wrong status code: ' + str(r.status_code))
+            raise Exception('wrong status code: {0}'.format(r.status_code))
 
         notifications = r.json()
         return notifications
@@ -162,17 +180,13 @@ class Client:
         """
 
         data = {'authenticity_token': self.get_token()}
-        r = self.session.get(self.pod + "/mentions.json")
+        r = self.session.get('/mentions.json'.format(self.pod))
 
         if r.status_code != 200:
-            raise Exception('wrong status code: ' + str(r.status_code))
+            raise Exception('wrong status code: {0}'.format(r.status_code))
 
         mentions = r.json()
-
-        posts = []
-
-        for post in mentions:
-            posts.append(diaspy.models.Post(str(post['id']), self))
+        posts = [ diaspy.models.Post(str(post['id']), self) for post in mentions ]
 
         return posts
 
@@ -186,17 +200,13 @@ class Client:
         """
 
         data = {'authenticity_token': self.get_token()}
-        r = self.session.get(self.pod + '/tags/' + tag + '.json')
+        r = self.session.get('{0}/tags/{1}.json'.format(self.pod, tag))
 
         if r.status_code != 200:
-            raise Exception('wrong status code: ' + str(r.status_code))
+            raise Exception('wrong status code: {0}'.format(r.status_code))
 
         tagged_posts = r.json()
-
-        posts = []
-
-        for post in tagged_posts:
-            posts.append(diaspy.models.Post(str(post['id']), self))
+        posts = [ diaspy.models.Post(str(post['id']), self) for post in tagged_posts ]
 
         return posts
 
@@ -214,11 +224,11 @@ class Client:
                 'aspect_id': aspect_id,
                 'person_id': user_id}
 
-        r = self.session.post(self.pod + '/aspect_memberships.json',
+        r = self.session.post('{0}/aspect_memberships.json'.format(self.pod),
                               data=data)
 
         if r.status_code != 201:
-            raise Exception('wrong status code: ' + str(r.status_code))
+            raise Exception('wrong status code: {0}'.format(r.status_code))
         return r.json()
 
     def remove_user_from_aspect(self, user_id, aspect_id):
@@ -235,11 +245,11 @@ class Client:
                 'aspect_id': aspect_id,
                 'person_id': user_id}
 
-        r = self.session.delete(self.pod + '/aspect_memberships/42.json',
+        r = self.session.delete('{0}/aspect_memberships/42.json'.format(self.pod),
                                 data=data)
 
         if r.status_code != 200:
-            raise Exception('wrong status code: ' + str(r.status_code))
+            raise Exception('wrong status code: {0}'.format(r.status_code))
 
         return r.json()
 
@@ -251,11 +261,11 @@ class Client:
                 'aspect[name]': aspect_name,
                 'aspect[contacts_visible]': visible}
 
-        r = self.session.post(self.pod + '/aspects',
+        r = self.session.post('{0}/aspects'.format(self.pod),
                               data=data)
 
         if r.status_code != 200:
-            raise Exception('wrong status code: ' + str(r.status_code))
+            raise Exception('wrong status code: {0}'.format(r.status_code))
 
     def remove_aspect(self, aspect_id):
         """ This function adds a new aspect.
@@ -263,12 +273,11 @@ class Client:
 
         data = {'authenticity_token': self.get_token()}
 
-        r = self.session.delete(self.pod + '/aspects/' + aspect_id,
+        r = self.session.delete('{0}/aspects/{1}'.format(self.pod, aspect_id),
                                 data=data)
 
         if r.status_code != 404:
-            raise Exception('wrong status code: ' + str(r.status_code))
-
+            raise Exception('wrong status code: {0}'.format(r.status_code))
 
     def get_mailbox(self):
         """This functions returns a list of messages found in the conversation.
@@ -278,17 +287,13 @@ class Client:
         """
 
         data = {'authenticity_token': self.get_token()}
-        r = self.session.get(self.pod + "/conversations.json")
+        r = self.session.get('{0}/conversations.json'.format(self.pod))
 
         if r.status_code != 200:
-            raise Exception('wrong status code: ' + str(r.status_code))
+            raise Exception('wrong status code: {0}'.format(r.status_code))
 
         mailbox = r.json()
-
-        conversations = []
-
-        for conversation in mailbox:
-            conversations.append(diaspy.conversations.Conversation(str(conversation['conversation']['id']), self))
+        conversations = [ diaspy.conversations.Conversation(str(conversation['conversation']['id']), self) for conversation in mailbox ]
 
         return conversations
 
@@ -310,12 +315,10 @@ class Client:
                 'utf8': '✓',
                 'authenticity_token': self.get_token()}
 
-        r = self.session.post(self.pod +
-                                      '/conversations/',
-                                      data=data,
-                                      headers={'accept': 'application/json'})
+        r = self.session.post('{0}/conversations/'.format(self.pod),
+                              data=data,
+                              headers={'accept': 'application/json'})
         if r.status_code != 200:
-            raise Exception(str(r.status_code) +
-                            ': Conversation could not be started.')
+            raise Exception('{0}: Conversation could not be started.'.format(r.status_code))
 
         return r.json()