| 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | |
| 4 | import time |
| 5 | |
| 6 | from diaspy.models import Notification |
| 7 | |
| 8 | |
| 9 | """This module abstracts notifications. |
| 10 | """ |
| 11 | |
| 12 | |
| 13 | class Notifications(): |
| 14 | """This class represents notifications of a user. |
| 15 | """ |
| 16 | def __init__(self, connection): |
| 17 | self._connection = connection |
| 18 | self._data = {} |
| 19 | self._notifications = self.get() |
| 20 | |
| 21 | def __iter__(self): |
| 22 | return iter(self._notifications) |
| 23 | |
| 24 | def __getitem__(self, n): |
| 25 | return self._notifications[n] |
| 26 | |
| 27 | def _finalise(self, notifications): |
| 28 | self._data['unread_count'] = notifications['unread_count'] |
| 29 | self._data['unread_count_by_type'] = notifications['unread_count_by_type'] |
| 30 | return [Notification(self._connection, n) for n in notifications.get('notification_list', [])] |
| 31 | |
| 32 | def last(self): |
| 33 | """Returns list of most recent notifications. |
| 34 | """ |
| 35 | params = {'per_page': 5, '_': int(round(time.time(), 3)*1000)} |
| 36 | headers = {'x-csrf-token': repr(self._connection)} |
| 37 | |
| 38 | request = self._connection.get('notifications.json', headers=headers, params=params) |
| 39 | |
| 40 | if request.status_code != 200: |
| 41 | raise Exception('status code: {0}: cannot retreive notifications'.format(request.status_code)) |
| 42 | return self._finalise(request.json()) |
| 43 | |
| 44 | def get(self, per_page=5, page=1): |
| 45 | """Returns list of notifications. |
| 46 | """ |
| 47 | params = {'per_page': per_page, 'page': page} |
| 48 | headers = {'x-csrf-token': repr(self._connection)} |
| 49 | |
| 50 | request = self._connection.get('notifications.json', headers=headers, params=params) |
| 51 | |
| 52 | if request.status_code != 200: |
| 53 | raise Exception('status code: {0}: cannot retreive notifications'.format(request.status_code)) |
| 54 | return self._finalise(request.json()) |