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()
23 return len(self
._notifications
)
26 return iter(self
._notifications
)
28 def __getitem__(self
, n
):
29 return self
._notifications
[n
]
31 def _finalise(self
, notifications
):
32 self
._data
['unread_count'] = notifications
['unread_count']
33 self
._data
['unread_count_by_type'] = notifications
['unread_count_by_type']
34 return [Notification(self
._connection
, n
) for n
in notifications
.get('notification_list', [])]
37 """Returns list of most recent notifications.
39 params
= {'per_page': 5, '_': int(round(time
.time(), 3)*1000)}
40 headers
= {'x-csrf-token': repr(self
._connection
)}
42 request
= self
._connection
.get('notifications.json', headers
=headers
, params
=params
)
44 if request
.status_code
!= 200:
45 raise Exception('status code: {0}: cannot retrieve notifications'.format(request
.status_code
))
46 return self
._finalise
(request
.json())
48 def _expand(self
, new_notifications
):
49 ids
= [notification
.id for notification
in self
._notifications
]
50 notifications
= self
._notifications
52 for n
in new_notifications
:
55 data
['unread_count'] +=1
56 data
['unread_count_by_type'][n
.type] +=1
57 notifications
.append(n
)
59 self
._notifications
= notifications
62 def _update(self
, new_notifications
):
63 ids
= [notification
.id for notification
in self
._notifications
]
64 notifications
= self
._notifications
68 if new_notifications
[len(new_notifications
)-1].id not in ids
:
71 for i
in range(len(new_notifications
)):
72 if new_notifications
[-i
].id not in ids
:
73 if new_notifications
[-i
].unread
:
74 data
['unread_count'] +=1
75 data
['unread_count_by_type'][new_notifications
[-i
].type] +=1
76 notifications
= [new_notifications
[-i
]] + notifications
77 ids
.append(new_notifications
[-i
].id)
78 self
._notifications
= notifications
80 if update
: self
.update() # if there is a gap
82 def update(self
, per_page
=5, page
=1):
83 result
= self
.get(per_page
=per_page
, page
=page
)
84 if result
: self
._update
( result
)
86 def more(self
, per_page
=5, page
=0):
87 if not page
: page
= self
.page
+ 1
89 result
= self
.get(per_page
=per_page
, page
=page
)
91 self
._expand
( result
)
93 def get(self
, per_page
=5, page
=1):
94 """Returns list of notifications.
96 params
= {'per_page': per_page
, 'page': page
}
97 headers
= {'x-csrf-token': repr(self
._connection
)}
99 request
= self
._connection
.get('notifications.json', headers
=headers
, params
=params
)
101 if request
.status_code
!= 200:
102 raise Exception('status code: {0}: cannot retreive notifications'.format(request
.status_code
))
103 return self
._finalise
(request
.json())