forked from unias/docklet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotificationmgr.py
260 lines (247 loc) · 10.4 KB
/
notificationmgr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import json
from log import logger
from model import db, Notification, NotificationGroups, User, UserNotificationPair
from userManager import administration_required, token_required
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from datetime import datetime
import env
from settings import settings
class NotificationMgr:
def __init__(self):
logger.info("Notification Manager init...")
try:
Notification.query.all()
except:
db.create_all()
try:
NotificationGroups.query.all()
except:
db.create_all()
try:
UserNotificationPair.query.all()
except:
db.create_all()
logger.info("Notification Manager init done!")
def query_user_notifications(self, user):
group_name = user.user_group
notifies = NotificationGroups.query.filter_by(group_name=group_name).all()
notifies.extend(NotificationGroups.query.filter_by(group_name='all').all())
notify_ids = [notify.notification_id for notify in notifies]
notify_ids = sorted(list(set(notify_ids)), reverse=True)
return [Notification.query.filter_by(id=notify_id).first() for notify_id in notify_ids]
def mail_notification(self, notify_id):
email_from_address = settings.get('EMAIL_FROM_ADDRESS')
if (email_from_address in ['\'\'', '\"\"', '']):
return {'success' : 'true'}
notify = Notification.query.filter_by(id=notify_id).first()
notify_groups = NotificationGroups.query.filter_by(notification_id=notify_id).all()
to_addr = []
groups = []
for group in notify_groups:
groups.append(group.group_name)
if 'all' in groups:
users = User.query.all()
for user in users:
to_addr.append(user.e_mail)
else:
for group in notify_groups:
users = User.query.filter_by(user_group=group.group_name).all()
for user in users:
to_addr.append(user.e_mail)
content = notify.content
text = '<html><h4>Dear '+ 'user' + ':</h4>' #user.username + ':</h4>'
text += '''<p> Your account in <a href='%s'>%s</a> has been recieved a notification:</p>
<p>%s</p>
<br>
<p> Note: DO NOT reply to this email!</p>
<br><br>
<p> <a href='http://docklet.unias.org'>Docklet Team</a>, SEI, PKU</p>
''' % (env.getenv("PORTAL_URL"), env.getenv("PORTAL_URL"), content)
text += '<p>'+ str(datetime.utcnow()) + '</p>'
text += '</html>'
subject = 'Docklet Notification: ' + notify.title
msg = MIMEMultipart()
textmsg = MIMEText(text,'html','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = email_from_address
msg.attach(textmsg)
s = smtplib.SMTP()
s.connect()
for address in to_addr:
try:
msg['To'] = address
s.sendmail(email_from_address, address, msg.as_string())
except Exception as e:
logger.error(e)
s.close()
return {"success": 'true'}
@administration_required
def create_notification(self, *args, **kwargs):
'''
Usage: createNotification(cur_user = 'Your current user', form = 'Post form')
Post form: {title: 'Your title', content: 'Your content', groups: "['groupA', 'groupB']"}
'''
form = kwargs['form']
notify = Notification(form['title'], form['content'])
group_names = form.getlist('groups')
db.session.add(notify)
db.session.commit()
# groups = json.loads(form['groups'])
# for group_name in groups:
if 'all' in group_names:
group_names = ['all']
for group_name in group_names:
if group_name == 'none':
continue
notify_groups = NotificationGroups(notify.id, group_name)
db.session.add(notify_groups)
db.session.commit()
if 'sendMail' in form:
self.mail_notification(notify.id)
users = User.query.all()
for user in users:
user_group = user.user_group
for group_name in group_names:
if user_group == group_name:
tempPair = UserNotificationPair(user.username, notify.id)
db.session.add(tempPair)
break;
db.session.commit()
return {"success": 'true'}
@administration_required
def list_notifications(self, *args, **kwargs):
notifies = Notification.query.all()
notify_infos = []
for notify in notifies:
if notify is None or notify.status == 'deleted':
continue
groups = NotificationGroups.query.filter_by(notification_id=notify.id).all()
notify_infos.append({
'id': notify.id,
'title': notify.title,
'content': notify.content,
'create_date': notify.create_date,
'status': notify.status,
'groups': [group.group_name for group in groups]
})
notify_infos.reverse()
return {'success': 'true', 'data': notify_infos}
@administration_required
def modify_notification(self, *args, **kwargs):
form = kwargs['form']
notify_id = form['notify_id']
notify = Notification.query.filter_by(id=notify_id).first()
notify.title = form['title']
notify.content = form['content']
notify.status = form['status']
notifies_groups = NotificationGroups.query.filter_by(notification_id=notify_id).all()
for notify_groups in notifies_groups:
db.session.delete(notify_groups)
group_names = form.getlist('groups')
if 'all' in group_names:
group_names = ['all']
for group_name in group_names:
if group_name == 'none':
continue
notify_groups = NotificationGroups(notify.id, group_name)
db.session.add(notify_groups)
db.session.commit()
if 'sendMail' in form:
self.mail_notification(notify_id)
return {"success": 'true'}
@administration_required
def delete_notification(self, *args, **kwargs):
form = kwargs['form']
notify_id = form['notify_id']
notify = Notification.query.filter_by(id=notify_id).first()
# notify.status = 'deleted'
notifies_groups = NotificationGroups.query.filter_by(notification_id=notify_id).all()
for notify_groups in notifies_groups:
db.session.delete(notify_groups)
db.session.delete(notify)
db.session.commit()
temppairs = UserNotificationPair.query.filter_by(notifyId=notify_id).all()
for temppair in temppairs:
db.session.delete(temppair)
db.session.commit()
return {"success": 'true'}
@token_required
def query_self_notification_simple_infos(self, *args, **kwargs):
user = kwargs['cur_user']
username = user.username
notifies = self.query_user_notifications(user)
notify_simple_infos = []
for notify in notifies:
if notify is None or notify.status != 'open':
continue
notifyid = notify.id
temppair = UserNotificationPair.query.filter_by(userName=username, notifyId=notifyid).first()
if temppair == None:
isRead = 0
temppair = UserNotificationPair(username, notifyid)
db.session.add(temppair)
db.session.commit()
else:
isRead = temppair.isRead
notify_simple_infos.append({
'id': notify.id,
'title': notify.title,
'create_date': notify.create_date,
'isRead': isRead
})
return {'success': 'true', 'data': notify_simple_infos}
@token_required
def query_self_notifications_infos(self, *args, **kwargs):
user = kwargs['cur_user']
username = user.username
notifies = self.query_user_notifications(user)
notify_infos = []
for notify in notifies:
if notify is None or notify.status != 'open':
continue
notifyid = notify.id
temppair = UserNotificationPair.query.filter_by(userName=username, notifyId=notifyid).first()
if temppair == None:
temppair = UserNotificationPair(username, notifyid)
db.session.add(temppair)
isRead = 1
temppair.isRead = 1
db.session.add(temppair)
db.session.commit()
notify_infos.append({
'id': notify.id,
'title': notify.title,
'content': notify.content,
'create_date': notify.create_date,
'isRead': isRead
})
return {'success': 'true', 'data': notify_infos}
@token_required
def query_notification(self, *args, **kwargs):
user = kwargs['cur_user']
form = kwargs['form']
group_name = user.user_group
notify_id = form['notify_id']
groups = NotificationGroups.query.filter_by(notification_id=notify_id).all()
if not(group_name in [group.group_name for group in groups]):
if not('all' in [group.group_name for group in groups]):
return {'success': 'false', 'reason': 'Unauthorized Action'}
notify = Notification.query.filter_by(id=notify_id).first()
notify_info = {
'id': notify.id,
'title': notify.title,
'content': notify.content,
'create_date': notify.create_date
}
usernotifypair = UserNotificationPair.query.filter_by(userName=user.username, notifyId=notify.id).first()
usernotifypair.isRead = 1
db.session.add(usernotifypair)
db.session.commit()
if notify.status != 'open':
notify_info['title'] = 'This notification is not available'
notify_info['content'] = 'Sorry, it seems that the administrator has closed this notification.'
return {'success': 'false', 'data': notify_info}
return {'success': 'true', 'data': notify_info}