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