Coverage for src/couchers/notifications/settings.py: 93%
58 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-06-01 15:07 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-06-01 15:07 +0000
1import logging
3from couchers.db import session_scope
4from couchers.models import (
5 NotificationDelivery,
6 NotificationDeliveryType,
7 NotificationPreference,
8 NotificationTopicAction,
9)
10from couchers.notifications.utils import enum_from_topic_action
11from couchers.sql import couchers_select as select
12from proto import notifications_pb2
14logger = logging.getLogger(__name__)
17def get_preference(session, user_id: int, topic_action: NotificationTopicAction) -> list[NotificationDeliveryType]:
18 """
19 Gets the user's preference from the DB or otherwise falls back to defaults
21 Must be done in session scope
23 Returns list of delivery types
24 """
25 overrides = {
26 res.delivery_type: res.deliver
27 for res in session.execute(
28 select(NotificationPreference)
29 .where(NotificationPreference.user_id == user_id)
30 .where(NotificationPreference.topic_action == topic_action)
31 )
32 .scalars()
33 .all()
34 }
35 return [dt for dt in NotificationDeliveryType if overrides.get(dt, dt in topic_action.defaults)]
38def get_topic_actions_by_delivery_type(
39 session, user_id: int, delivery_type: NotificationDeliveryType
40) -> set[NotificationTopicAction]:
41 """
42 Given push/email/digest, returns notifications that this user has enabled for that type.
43 """
44 overrides = dict(
45 session.execute(
46 select(NotificationPreference.topic_action, NotificationPreference.deliver)
47 .where(NotificationPreference.user_id == user_id)
48 .where(NotificationPreference.delivery_type == delivery_type)
49 ).all()
50 )
51 return {t for t in NotificationTopicAction if overrides.get(t, delivery_type in t.defaults)}
54def reset_preference(session, user_id, topic_action, delivery_type):
55 current_pref = session.execute(
56 select(NotificationPreference)
57 .where(NotificationPreference.user_id == user_id)
58 .where(NotificationPreference.topic_action == topic_action)
59 .where(NotificationDelivery.delivery_type == delivery_type)
60 ).scalar_one_or_none()
61 if current_pref:
62 session.delete(current_pref)
63 session.flush()
66class PreferenceNotUserEditableError(Exception):
67 pass
70def set_preference(session, user_id, topic_action: NotificationTopicAction, delivery_type, deliver):
71 if not topic_action.user_editable:
72 raise PreferenceNotUserEditableError()
73 current_pref = session.execute(
74 select(NotificationPreference)
75 .where(NotificationPreference.user_id == user_id)
76 .where(NotificationPreference.topic_action == topic_action)
77 .where(NotificationPreference.delivery_type == delivery_type)
78 ).scalar_one_or_none()
79 if current_pref:
80 current_pref.deliver = deliver
81 else:
82 session.add(
83 NotificationPreference(
84 user_id=user_id,
85 topic_action=topic_action,
86 delivery_type=delivery_type,
87 deliver=deliver,
88 )
89 )
90 session.flush()
93settings_layout = [
94 (
95 "Core Features",
96 [
97 (
98 "host_request",
99 "Host requests",
100 [
101 ("create", "Someone sends you a host request"),
102 ("accept", "Someone accepts your host request"),
103 ("confirm", "Someone confirms their host request"),
104 ("reject", "Someone declines your host request"),
105 ("cancel", "Someone cancels their host request"),
106 ("message", "Someone sends a message in a host request"),
107 ("missed_messages", "You miss messages in a host request"),
108 ],
109 ),
110 (
111 "activeness",
112 "Activity Check-in",
113 [
114 ("probe", "Check in to see if you are still hosting after a long period of inactivity"),
115 ],
116 ),
117 (
118 "chat",
119 "Messaging",
120 [
121 ("message", "Someone sends you a message"),
122 ("missed_messages", "You miss messages in a chat"),
123 ],
124 ),
125 (
126 "reference",
127 "References",
128 [
129 ("receive_hosted", "You receive a reference from someone who hosted you"),
130 ("receive_surfed", "You receive a reference from someone you hosted"),
131 ("receive_friend", "You received a reference from a friend"),
132 ("reminder_hosted", "Reminder to write a reference to someone you hosted"),
133 ("reminder_surfed", "Reminder to write a reference to someone you surfed with"),
134 ],
135 ),
136 ],
137 ),
138 (
139 "Community Features",
140 [
141 (
142 "friend_request",
143 "Friend requests",
144 [
145 ("create", "Someone sends you a friend request"),
146 ("accept", "Someone accepts your friend request"),
147 ],
148 ),
149 (
150 "event",
151 "Events",
152 [
153 ("create_approved", "An event that is approved by the moderators is created in your community"),
154 ("create_any", "A user creates any event in your community (not checked by an admin)"),
155 ("update", "An event you are attending is updated"),
156 ("comment", "Someone comments on an event you are organizing or attending"),
157 ("cancel", "An event you are attending is cancelled"),
158 ("delete", "An event you are attending is deleted"),
159 ("invite_organizer", "Someone invites you to co-organize an event"),
160 ],
161 ),
162 (
163 "discussion",
164 "Community discussions",
165 [
166 ("create", "Someone creates a discussion in one of your communities"),
167 ("comment", "Someone comments on a discussion you authored"),
168 ],
169 ),
170 (
171 "thread",
172 "Threads, Comments, & Replies",
173 [
174 ("reply", "Someone replies to your comment"),
175 ],
176 ),
177 ],
178 ),
179 (
180 "Account Settings",
181 [
182 (
183 "onboarding",
184 "Onboarding",
185 [
186 ("reminder", "Reminder to complete your profile after signing up"),
187 ],
188 ),
189 (
190 "badge",
191 "Updates to Badges on your profile",
192 [
193 ("add", "A badge is added to your account"),
194 ("remove", "A badge is removed from your account"),
195 ],
196 ),
197 (
198 "donation",
199 "Donations",
200 [
201 ("received", "Your donation is received"),
202 ],
203 ),
204 ],
205 ),
206 (
207 "Account Security",
208 [
209 (
210 "password",
211 "Password change",
212 [
213 ("change", "Your password is changed"),
214 ],
215 ),
216 (
217 "password_reset",
218 "Password reset",
219 [
220 ("start", "Password reset is initiated"),
221 ("complete", "Password reset is completed"),
222 ],
223 ),
224 (
225 "email_address",
226 "Email address change",
227 [
228 ("change", "Email change is initiated"),
229 ("verify", "Your new email is verified"),
230 ],
231 ),
232 (
233 "account_deletion",
234 "Account deletion",
235 [
236 ("start", "You initiate account deletion"),
237 ("complete", "Your account is deleted"),
238 ("recovered", "Your account is recovered (undeleted)"),
239 ],
240 ),
241 (
242 "api_key",
243 "API keys",
244 [
245 ("create", "An API key is created for your account"),
246 ],
247 ),
248 (
249 "phone_number",
250 "Phone number change",
251 [
252 ("change", "Your phone number is changed"),
253 ("verify", "Your phone number is verified"),
254 ],
255 ),
256 (
257 "birthdate",
258 "Birthdate change",
259 [
260 ("change", "Your birthdate is changed"),
261 ],
262 ),
263 (
264 "gender",
265 "Displayed gender change",
266 [
267 ("change", "The gender displayed on your profile is changed"),
268 ],
269 ),
270 (
271 "modnote",
272 "Moderator notes",
273 [
274 ("create", "You receive a moderator note"),
275 ],
276 ),
277 (
278 "verification",
279 "Verification",
280 [
281 ("sv_fail", "Strong Verification fails"),
282 ("sv_success", "Strong Verification succeeds"),
283 ],
284 ),
285 ],
286 ),
287 (
288 "Other Notifications",
289 [
290 (
291 "general",
292 "General",
293 [
294 ("new_blog_post", "We published a new blog post"),
295 ],
296 ),
297 ],
298 ),
299]
302def check_settings():
303 # check settings contain all actions+topics
304 actions_by_topic = {}
305 for t in NotificationTopicAction:
306 actions_by_topic[t.topic] = actions_by_topic.get(t.topic, []) + [t.action]
308 actions_by_topic_check = {}
310 for heading, group in settings_layout:
311 for topic, name, items in group:
312 actions = []
313 for action, description in items:
314 actions.append(action)
315 actions_by_topic_check[topic] = actions
317 for topic, actions in actions_by_topic.items():
318 assert sorted(actions) == sorted(actions_by_topic_check[topic]), (
319 f"Expected {actions} == {actions_by_topic_check[topic]} for {topic}"
320 )
321 assert sorted(actions_by_topic.keys()) == sorted(actions_by_topic_check.keys())
324check_settings()
327def get_user_setting_groups(user_id) -> list[notifications_pb2.NotificationGroup]:
328 with session_scope() as session:
329 groups = []
330 for heading, group in settings_layout:
331 topics = []
332 for topic, name, items in group:
333 actions = []
334 for action, description in items:
335 topic_action = enum_from_topic_action[topic, action]
336 delivery_types = get_preference(session, user_id, topic_action)
337 actions.append(
338 notifications_pb2.NotificationItem(
339 action=action,
340 description=description,
341 user_editable=topic_action.user_editable,
342 push=NotificationDeliveryType.push in delivery_types,
343 email=NotificationDeliveryType.email in delivery_types,
344 digest=NotificationDeliveryType.digest in delivery_types,
345 )
346 )
347 topics.append(
348 notifications_pb2.NotificationTopic(
349 topic=topic,
350 name=name,
351 items=actions,
352 )
353 )
354 groups.append(
355 notifications_pb2.NotificationGroup(
356 heading=heading,
357 topics=topics,
358 )
359 )
360 return groups