Commit | Line | Data |
---|---|---|
beaa09fb MM |
1 | import re |
2 | from diaspy.streams import Outer | |
3 | ||
4 | ||
5 | class User: | |
6 | """This class abstracts a D* user. | |
7 | This object goes around the limitations of current D* API and will | |
8 | extract user data using black magic. | |
9 | However, no chickens are harmed when you use it. | |
10 | """ | |
11 | def __init__(self, connection): | |
12 | self._connection = connection | |
13 | self.data = {} | |
141216df | 14 | self.stream = [] |
beaa09fb MM |
15 | |
16 | def __getitem__(self, key): | |
17 | return self.data[key] | |
18 | ||
19 | def _sephandle(self, handle): | |
20 | """Separate D* handle into pod pod and user. | |
21 | ||
22 | :param handle: diaspora id: user@pod.example.com | |
23 | :type handle: str | |
24 | :returns: two-tuple (pod, user) | |
25 | """ | |
26 | if re.match('^[a-zA-Z]+[a-zA-Z0-9_-]*@[a-z0-9.]+\.[a-z]+$', handle) is None: | |
27 | raise Exception('invalid handle: {0}'.format(handle)) | |
28 | handle = handle.split('@') | |
29 | pod, user = handle[1], handle[0] | |
30 | return (pod, user) | |
31 | ||
a8fdc14a MM |
32 | def _postproc(self, request): |
33 | """Makes necessary modifications to user data and | |
34 | sets up a stream. | |
35 | ||
36 | :param request: request object | |
37 | :type request: request | |
beaa09fb | 38 | """ |
141216df | 39 | if request.status_code != 200: |
a8fdc14a | 40 | raise Exception('wrong error code: {0}'.format(request.status_code)) |
141216df MM |
41 | else: |
42 | request = request.json() | |
a8fdc14a MM |
43 | data, final = request[0]['author'], {} |
44 | names = [('id', 'id'), | |
45 | ('diaspora_id', 'diaspora_id'), | |
46 | ('guid', 'guid'), | |
47 | ('name', 'diaspora_name'), | |
48 | ('avatar', 'image_urls'), | |
49 | ] | |
50 | for d, f in names: | |
51 | final[f] = data[d] | |
52 | self.data = final | |
beaa09fb MM |
53 | self.stream = Outer(self._connection, location='people/{0}.json'.format(self.data['guid'])) |
54 | ||
33a45682 | 55 | def _getbyhandle(self, diaspora_id, protocol='https'): |
beaa09fb MM |
56 | """Get user data using handle. |
57 | """ | |
58 | pod, user = self._sephandle(diaspora_id) | |
a8fdc14a MM |
59 | request = self._connection.session.get('{0}://{1}/u/{2}.json'.format(protocol, pod, user)) |
60 | self._postproc(request) | |
beaa09fb | 61 | |
33a45682 | 62 | def _getbyguid(self, guid): |
beaa09fb MM |
63 | """Get user data using guid. |
64 | """ | |
141216df | 65 | request = self._connection.get('people/{0}.json'.format(guid)) |
a8fdc14a | 66 | self._postproc(request) |
beaa09fb MM |
67 | |
68 | def fetchguid(self, guid): | |
69 | """Fetch user data using guid. | |
70 | """ | |
33a45682 | 71 | self._getbyguid(guid) |
beaa09fb MM |
72 | |
73 | def fetchhandle(self, diaspora_id, protocol='https'): | |
74 | """Fetch user data using diaspora id. | |
75 | """ | |
33a45682 | 76 | self._getbyhandle(diaspora_id, protocol) |