Merge branch 'master' into search
[diaspy.git] / diaspy / people.py
index 8107ab2194efdd2a94919c055cc26bed87d490bd..0f0bed135fde5e37ff715b498cf5eb9d8f564a4d 100644 (file)
@@ -1,6 +1,8 @@
 import re
 from diaspy.streams import Outer
 from diaspy.models import Aspect
+from diaspy import errors
+from diaspy import search
 
 
 class User():
@@ -11,11 +13,11 @@ class User():
 
     The parameter fetch should be either 'posts', 'data' or 'none'. By
     default it is 'posts' which means in addition to user data, stream
-    will be fetched. If user has not posted yet diaspy will not be able 
-    to extract the information from his/her posts. Since there is no official 
-    way to do it we rely on user posts. If this will be the case user 
+    will be fetched. If user has not posted yet diaspy will not be able
+    to extract the information from his/her posts. Since there is no official
+    way to do it we rely on user posts. If this will be the case user
     will be notified with appropriate exception message.
-    
+
     If fetch is 'data', only user data will be fetched. If the user is
     not found, no exception will be returned.
 
@@ -23,27 +25,34 @@ class User():
     optional parameters. GUID takes precedence over handle when fetching
     user stream. When fetching user data, handle is required.
     """
-    data = {}
-    stream = []
-
     def __init__(self, connection, guid='', handle='', fetch='posts', id=0):
         self._connection = connection
+        self.stream = []
+        self.handle = handle
+        self.guid = guid
         self.data = {
             'guid': guid,
             'handle': handle,
-            'id': id
+            'id': id,
         }
-        self._do_fetch(fetch)
+        self._fetch(fetch)
 
     def __getitem__(self, key):
         return self.data[key]
 
-    def _do_fetch(self, fetch):
+    def __str__(self):
+        return self['guid']
+
+    def __repr__(self):
+        return '{0} ({1})'.format(self['diaspora_name'], self['guid'])
+
+    def _fetch(self, fetch):
+        """Fetch user posts or data.
+        """
         if fetch == 'posts':
-            if self['handle'] and self['guid']: self.fetchguid()
-            elif self['guid'] and not self['handle']: self.fetchguid()
-            elif self['handle'] and not self['guid']: self.fetchhandle()
-        elif fetch == 'data' and len(self['handle']):
+            if self.handle and not self.guid: self.fetchhandle()
+            else: self.fetchguid()
+        elif fetch == 'data' and self.handle:
             self.fetchprofile()
 
     def _sephandle(self):
@@ -51,13 +60,19 @@ class User():
 
         :returns: two-tuple (pod, user)
         """
-        if re.match('^[a-zA-Z]+[a-zA-Z0-9_-]*@[a-z0-9.]+\.[a-z]+$', self['handle']) is None:
-            raise Exception('invalid handle: {0}'.format(self['handle']))
-        handle = self['handle'].split('@')
+        if re.match('^[a-zA-Z]+[a-zA-Z0-9_-]*@[a-z0-9.]+\.[a-z]+$', self.handle) is None:
+            raise errors.UserError('invalid handle: {0}'.format(self.handle))
+        handle = self.handle.split('@')
         pod, user = handle[1], handle[0]
         return (pod, user)
-        
-    def _finalize_data(self, data, names):
+
+    def _finalize_data(self, data):
+        names = [('id', 'id'),
+                 ('handle', 'diaspora_id'),
+                 ('guid', 'guid'),
+                 ('name', 'diaspora_name'),
+                 ('avatar', 'image_urls'),
+                 ]
         final = {}
         for d, f in names:
             final[f] = data[d]
@@ -74,14 +89,8 @@ class User():
             raise Exception('wrong error code: {0}'.format(request.status_code))
         else:
             request = request.json()
-        if not len(request): raise Exception('Cannot extract user data: no posts to analyze')
-        names = [('id', 'id'),
-                 ('diaspora_id', 'diaspora_id'),
-                 ('guid', 'guid'),
-                 ('name', 'diaspora_name'),
-                 ('avatar', 'image_urls'),
-                 ]
-        self.data = self._finalize_data(request[0]['author'], names)
+        if not len(request): raise errors.UserError('cannot extract user data: no posts to analyze')
+        self.data = self._finalize_data(request[0]['author'])
         self.stream = Outer(self._connection, location='people/{0}.json'.format(self['guid']))
 
     def fetchhandle(self, protocol='https'):
@@ -94,25 +103,8 @@ class User():
     def fetchguid(self):
         """Fetch user data and posts using guid.
         """
-        request = self._connection.get('people/{0}.json'.format(self['guid']))
+        request = self._connection.get('people/{0}.json'.format(self.guid))
         self._postproc(request)
-        
-    def fetchprofile(self, protocol='https'):
-        """Fetch user data using Diaspora handle.
-        """
-        request = self._connection.get('people.json?q={0}'.format(self['handle']))
-        if request.status_code != 200:
-            raise Exception('wrong error code: {0}'.format(request.status_code))
-        else:
-            request = request.json()
-        if len(request):
-            names = [('id', 'id'),
-                     ('handle', 'diaspora_id'),
-                     ('guid', 'guid'),
-                     ('name', 'diaspora_name'),
-                     ('avatar', 'image_urls'),
-                     ]
-            self.data = self._finalize_data(request[0], names)
 
 
 class Contacts():
@@ -164,5 +156,5 @@ class Contacts():
         request = self._connection.get('contacts.json', params=params)
         if request.status_code != 200:
             raise Exception('status code {0}: cannot get contacts'.format(request.status_code))
-        contacts = [User(self._connection, user['guid'], user['handle'], 'none', user['id']) for user in request.json()]
+        contacts = [User(self._connection, guid=user['guid'], handle=user['handle'], fetch=None, id=user['id']) for user in request.json()]
         return contacts