6 from diaspy
.models
import Notification
9 """This module abstracts notifications.
13 class Notifications():
14 """This class represents notifications of a user.
16 def __init__(self
, connection
):
17 self
._connection
= connection
19 self
._notifications
= self
.get()
22 def __len__(self
): return len(self
._notifications
);
25 return iter(self
._notifications
)
27 def __getitem__(self
, n
):
28 return self
._notifications
[n
]
30 def _finalise(self
, notifications
):
31 self
._data
['unread_count'] = notifications
['unread_count']
32 self
._data
['unread_count_by_type'] = notifications
['unread_count_by_type']
33 return [Notification(self
._connection
, n
) for n
in notifications
.get('notification_list', [])]
35 def data(self
): return self
._data
;
38 """Returns list of most recent notifications.
40 params
= {'per_page': 5, '_': int(round(time
.time(), 3)*1000)}
41 headers
= {'x-csrf-token': repr(self
._connection
)}
43 request
= self
._connection
.get('notifications.json', headers
=headers
, params
=params
)
45 if request
.status_code
!= 200:
46 raise Exception('status code: {0}: cannot retreive notifications'.format(request
.status_code
))
47 return self
._finalise
(request
.json())
49 def _expand(self
, new_notifications
):
50 ids
= [notification
.id for notification
in self
._notifications
]
51 notifications
= self
._notifications
53 for n
in new_notifications
:
55 notifications
.append(n
)
57 self
._notifications
= notifications
58 self
._data
.update(data
);
60 def _update(self
, new_notifications
):
61 ids
= [notification
.id for notification
in self
._notifications
]
62 notifications
= self
._notifications
66 if new_notifications
[len(new_notifications
)-1].id not in ids
:
69 for i
in range(len(new_notifications
)):
70 if new_notifications
[-i
].id not in ids
:
71 notifications
= [new_notifications
[-i
]] + notifications
72 ids
.append(new_notifications
[-i
].id)
73 self
._notifications
= notifications
75 if update
: self
.update() # if there is a gap
77 def update(self
, per_page
=5, page
=1):
78 result
= self
.get(per_page
=per_page
, page
=page
)
79 if result
: self
._update
( result
)
81 def more(self
, per_page
=5, page
=0):
82 if not page
: page
= self
.page
+ 1
84 result
= self
.get(per_page
=per_page
, page
=page
)
85 if result
: self
._expand
( result
)
87 def get(self
, per_page
=5, page
=1):
88 """Returns list of notifications.
90 params
= {'per_page': per_page
, 'page': page
}
91 headers
= {'x-csrf-token': repr(self
._connection
)}
93 request
= self
._connection
.get('notifications.json', headers
=headers
, params
=params
)
95 if request
.status_code
!= 200:
96 raise Exception('status code: {0}: cannot retreive notifications'.format(request
.status_code
))
97 return self
._finalise
(request
.json())