Skip to content
Repos

42 notification fix #1

open retoor wants to merge 28 commits into main from 42-notification-fix, opened WO_DevPlaceIOS

Showing 31 changed files with 1623 additions and 159 deletions Unified Split Hide whitespace Show outdated
Files
.delivered.md added +309 -0
@@ -0,0 +1,309 @@
1 # Delivered: notifications, rounds 1 to 3
2
3 Status: DELIVERED locally (step 3 of 3: .plan.md -> .implementation.md -> .delivered.md). Nothing is pushed.
4 Round 1 (fix for the broken list): plan 49fc470, implementation 7a6bcdc, release 2cf9eb4, tag `1.1.1`.
5 Round 2 (every remaining notification gap): plan 87f9336, implementation b4a6621, release 41b653d, tag `1.1.2`.
6 Round 3 (backend: unread count as `aps.badge`): plan 7d7d0e5, implementation e2e0b38, release tag `1.1.3`. Backend commits are on branch `push-unread-badge` of `../devplacepy`, not merged, not pushed, not deployed.
7
8 # Round 1
9
10 ## 1. Root cause, confirmed on a real run
11
12 Backend commit `8a48e3e` (devplacepy, 2026-11-12). I ran `../devplacepy` from its `.venv` against a throwaway data dir
13 (`DEVPLACE_DATA_DIR` and `DEVPLACE_DATABASE_URL` pointed into the scratchpad, port 10599, stopped afterwards;
14 `git status` of devplacepy is clean). I signed up through the same endpoints the app uses (`auth/signup`, `auth/token`),
15 seeded 8 notifications (4 votes on one post, 2 comments from one actor, 1 message, 1 read badge) and called
16 `GET /notifications` with the app's headers.
17
18 | Measurement | Grouping on (default) | Grouping off |
19 |---|---|---|
20 | top-level keys | `notification_groups, next_cursor, grouping` | same |
21 | `grouping` | `true` | `false` |
22 | "Today" group | `entries`: 0, `event_entries`: 4 | `entries`: 8, `event_entries`: 0 |
23 | `GET /notifications/counts` `.notifications` | 3 (unread groups) | 7 (unread rows) |
24
25 So with defaults the old app model saw zero entries per group: empty list, non-zero badge.
26
27 ## 2. What was changed (one commit each)
28
29 | Commit | File(s) | Change |
30 |---|---|---|
31 | 3b77dff | `Models/Response/NotificationEventGroup.swift` (new) | domain type + `CodingData` + `decoded`, flat object (no inner `Data`), `id` prefixed like `Notification` |
32 | 6d1014c | `NotificationGroup.swift`, `Notifications.swift` | `eventEntries` / `event_entries`, `grouping` |
33 | 9237d7e | `Package.swift`, `Tests/DevPlaceSwiftSDKTests/NotificationsDecodingTests.swift` | first test target, Swift Testing, fixtures are the real captured payloads (trimmed) |
34 | 2efb656 | `NotificationsView+ViewModel.swift` | `Row`, `rows(in:)`, grouped-aware `markAllRead`, `merged`, `mergedEventEntries`, `combined`, `deduplicated`, `applyingRead`, `markedRead` |
35 | 9fc336e | `NotificationsView.swift` | single `ForEach` over `rows(in:)`, `NotificationRow(row:)`, multiplier text for count > 1, unread from the group |
36 | 255ac8d | `Model Mocks/Notifications.swift`, `Request/API/MockDevPlaceApi.swift` | mock uses the grouped shape (counts 1,1,3), mock `openNotification` searches event groups |
37
38 Unchanged on purpose: `DevPlaceApi`, `ProdDevPlaceApi`, `AppState`, SDK request functions (endpoints and parameters did not change).
39 Server side semantics the app relies on and did not need to reimplement: `open` and `mark-read` mark the whole group read.
40
41 Design decisions:
42 - Both shapes stay supported (user can turn grouping off in the web profile), selected by the response's own `grouping` flag, not by guessing from empty arrays.
43 - Pagination: a group key can continue across the page boundary; `mergedEventEntries` folds same-key groups inside the same date label (count summed, unread OR, newest `latest` kept, actors capped at 3). Different labels stay separate, matching the backend which builds its key index per label.
44 - No new dependencies, no Combine, no comments, ViewModel imports only `Foundation`/`Observation`/SDK, `Button` stays the interaction element.
45
46 ## 3. Verification actually run on this Linux machine
47
48 1. SDK cold build with dependencies: `swift build`, 6m06s wall (KreeRequest + NIO fetch and compile). The first attempt reported
49 a compile error; that was a race (build started before `NotificationEventGroup.swift` existed), not a defect. Warm rebuild 37.6s.
50 2. `swift test` in `DevPlaceSwiftSDK`: 3 tests, 3 passed (grouped decode, ungrouped decode, counts decode) on real captured JSON.
51 3. App ViewModel logic: compiled the REAL `NotificationsView+ViewModel.swift`, `NotificationRoute.swift`, `PostDestination.swift`,
52 `Model Mocks/Notifications.swift`, `Model Mocks/User.swift` with `swiftc` (Swift 6 mode) against the SDK models, with stubs only for
53 `AppState`, `AlertMessage`, `dlog`, `DevPlaceApi` and a fake API. 20 behavior checks, all passed: grouped rows and counts,
54 unread state, `markAllRead` (API called once, every row and every `latest` read), pagination merge (labels, same-key merge, summed count,
55 unread OR, newest latest kept, actors union, cross-label separation, cursor, `grouping` preserved), ungrouped path.
56 The harness lives in the scratchpad (not in the repo; the app has no test target).
57 4. `NotificationsView.swift`, `Model Mocks/Notifications.swift`, `MockDevPlaceApi.swift`: `swiftc -parse` clean (syntax only).
58
59 ## 4. Not verified (stated, not hidden)
60
61 - `NotificationsView.swift` was NOT type-checked or run: it needs SwiftUI/UIKit, only available with Xcode. Its change is small
62 (data source swap to `rows(in:)`, `NotificationRow(row:)`, one computed `messageText`), but an Xcode build is still required.
63 - `MockDevPlaceApi.swift` change was only parsed; `Notifications.mock` itself compiled in the harness.
64 - No on-device or simulator run, no APNs.
65 - No app test target exists; adding one means editing `project.pbxproj` in Xcode.
66
67 ## 5. Gaps found in round 1 (all closed in round 2, see below)
68
69 - `NotificationType` has 7 cases; backend has 20 (`NOTIFICATION_GROUP_KEYS`). Unknown types decode to `nil` and open to no route. `Models/TypedStrings/NotificationType.swift`, routing in `NotificationsView+ViewModel.swift` `route(for:redirect:)`.
70 - `getNotifications(before:)` formats the cursor with `.iso8601` (no fractions) while `created_at` has microseconds; `DevPlaceSwiftSDK.swift` `getNotifications`. Likely the cause of the existing "duplicate IDs" log line in `deduplicated`.
71 - No app UI for the backend `grouping` and `throttling` preferences (`POST /profile/{username}/notifications/grouping|throttling`, `Profile` has no `notif_grouping_enabled` field yet).
72 - Badge now counts groups (matches the web); no code change needed.
73
74 ## 6. Release and final gates
75
76 - Version bump `1.1.0 (4)` to `1.1.1 (5)` in `project.pbxproj` (both configurations, same four lines as the previous release commit `ea5b303`), commit `2cf9eb4`, local tag `1.1.1` (the repo had no tags before).
77 - Gates over `ea5b303..HEAD`: 0 em dashes, 0 added comment lines in Swift, no tabs in content, ViewModel imports only Foundation, Observation and the SDK, `swift test` 3 of 3 passing after the final commit.
78 - Working tree clean; devplacepy untouched (clean status), throwaway backend stopped.
79
80 ## 7. What the owner must still do
81
82 1. Build in Xcode (`BuildProject`) and look at the Notifications tab once on a simulator: `NotificationsView.swift` is the only changed file never type-checked.
83 2. Push `main`-bound work and the tag `1.1.1` when satisfied (not done: outward-facing).
84 3. Decide on the gaps in section 5.
85
86 # Round 2
87
88 Status: IMPLEMENTATION (.plan.md -> .implementation.md -> .delivered.md). Plan commit: 87f9336. Round 1 is recorded in `.delivered.md` (commits 49fc470..8c8ed8f, tag 1.1.1).
89 Scope rule from the owner: ONLY notifications, ONLY this app and SDK, same branch `42-notification-fix`. No other subject
90 (for example the feed cursor, which has the same shape of problem, is NOT touched here).
91
92 ## Items (each one gets its own commit(s))
93
94 ### N1. `NotificationType` covers 7 of 20 backend types
95 Backend source of truth: `NOTIFICATION_TYPES` (19) plus `game_upkeep` from `NOTIFICATION_GROUP_KEYS` (20 total).
96 SDK has: comment, reply, mention, vote, message, issue, badge.
97 Add 13: thread, follow, level, reminder, harvest_stolen, award, quiz_attempt, battle, workspace, moderation, system,
98 ai_quota_warning, game_upkeep. Order and style as the existing file. Decode test over all 20 raw values.
99
100 ### N2. Pagination cursor loses precision (likely cause of the "duplicate IDs" log line)
101 Backend compares `created_at < before` as STRINGS. `created_at` is `2026-11-15T01:03:49.664796+00:00`.
102 The app decodes `next_cursor` to `Date` (ISO8601 decoder: millisecond precision at best) and re-encodes with `.iso8601`
103 (`2026-11-15T01:03:49Z`, no fraction, `Z` instead of `+00:00`), so the page boundary is wrong, page overlap or gap follows.
104 Fix: carry the cursor as the raw string end to end. `Notifications.nextCursor: String?`,
105 `getNotifications(before: String?)`, `DevPlaceApi.notifications(before: String?)` (+Prod, +Mock), ViewModel.
106 Transport is safe: KreeRequest `urlEncodedQueryString` rewrites `+` to `%2b` (read in the dependency source).
107 Real-path proof on the local backend: 30 microsecond-stamped notifications, page with the old encoding (expect defect)
108 and with the raw cursor (expect exact pages, no overlap, no gap).
109
110 ### N3. Routing for the other 13 types, one shared place
111 Backend `target_url` per type (grep of every `create_notification` call): `/posts/<slug>#...` (comment, reply, thread, mention, vote),
112 `/profile/<username>` (follow, badge, level), `/messages?with_uid=` (message), `/issues/<n>`, `/projects` (workspace),
113 `/reports/mine` (moderation), quiz url, farm url, others.
114 Current `route(for:redirect:)`: message -> conversation, badge -> own profile, issue -> hand built web URL, post url -> post, everything else -> nothing.
115 Change: redirect parsing moves out of the ViewModel into `NotificationRoute` (Foundation only) so the ViewModel and the push tap use ONE implementation:
116 post url -> `.post`; message -> conversation (needs user, stays in ViewModel); badge and level -> own profile;
117 any other relative `target_url` -> `.web(https://devplace.net + path)`. The hand built issue URL becomes redundant (same URL as the redirect) and is removed.
118 No in-app screens are added for other users' profiles from notifications (web fallback; deliberate, listed under decisions).
119
120 ### N4. Push tap only handles messages
121 `PushNotificationManager.handleNotificationTap` reads `userInfo["url"]` and only routes `messages?with_uid`. A tap on a comment/vote push does nothing.
122 Change: same `NotificationRoute` parsing; post -> new `AppState.pendingPostDestination`, consumed in `MainView` (`feedPost` + tab), exactly like
123 `pendingConversationUid`; other relative urls -> web via `UIApplication.shared.open`.
124 Not changed: the `aps.badge` TODO (needs backend payload change, backend is out of scope).
125
126 ### N5. No UI for the grouping and throttling preferences
127 Backend: `POST /profile/{username}/notifications/grouping` and `/throttling`, JSON `{"value": bool}` (verified: the grouping call worked with JSON in round 1),
128 `ProfileOut.notif_grouping_enabled` / `notif_throttle_enabled`. IMPORTANT backend detail: these two fields are only real when the profile
129 is requested with `?tab=notifications` and `can_manage_customization`; otherwise the server returns the constant `true`. The SDK `getProfile` already has a `tab` parameter.
130 SDK: `Profile` gets the two Bools; `setNotificationGrouping(username:enabled:token:)`, `setNotificationThrottling(...)` (JSON body per CLAUDE.md).
131 App: `DevPlaceApi` + Prod + Mock; a "Notifications" section in `SettingsView` with two `Toggle`s, ViewModel state in `SettingsView+ViewModel`.
132 Decision: server-owned preferences are NOT mirrored into `AppSettingsStore` (it is for device-local settings; a local copy would desync from the web profile).
133 They are loaded from the server when Settings appears and written through on change, with revert + alert on failure.
134 Per-type channel preferences (`notification_prefs`, 19 types x in_app/push/telegram) exist on the backend and in the SDK Profile as "type unknown".
135 They are part of the notification area, so they are in scope; see N6.
136
137 ### N6. Per-type channel preferences (`notification_prefs`)
138 Profile JSON field `notification_prefs` is `[?]` in the SDK (commented out, "type unknown"). To be captured from the real backend with `?tab=notifications`,
139 modelled with the `devplace-model-from-json` skill, and endpoint `POST /profile/{username}/notifications/...` (set per type/channel, reset) to be read
140 from `routers/profile/notifications.py`. DECISION GATE: if the shape is large (19 types x 3 channels) I build it only if the capture shows a small, stable form;
141 otherwise it is reported with exact reasons and left out. Decided after capture, recorded in `.implementation.md`.
142
143 ## Results per item
144
145 | Item | Commit(s) | Result |
146 |---|---|---|
147 | N1 types | be72901 | 20 cases (CaseIterable like PostTopic); tests prove the enum equals the backend list and unknown values decode to nil |
148 | N2 cursor | 3326b5a | MEASURED on the local backend, 60 rows inside one second: app's old encoding returned 242 rows, 25 unique, 35 of 60 unreachable and never terminated; exact raw cursor returned 60 of 60 once in 3 pages. Cursor is now a raw String through SDK, API, Prod, Mock, ViewModel. `+00:00` is safe on the wire: KreeRequest rewrites `+` to `%2b` (read in its source). The log line no longer blames the backend |
149 | N3 routing | 3b24d9f | `NotificationRoute(redirect:)` shared; badge and level -> own profile; every other relative target -> web; absolute and empty redirects never opened. 20 type rows plus 3 edge cases in the harness |
150 | N4 push tap | f66a694 | post -> `AppState.pendingPostDestination` consumed by `MainView`; other relative urls -> `UIApplication.open` |
151 | N5 settings | fd75c18, c96cabd, 26069f8, 2bf1b54 | SDK models and 5 requests, API layer, screen, Settings row. Verified on the real backend: grouping, throttling, per-type set and reset round trips, invalid type rejected (400), invalid channel rejected (422) |
152 | N6 per-type prefs | same as N5 | Decision gate passed: capture showed a small stable shape (key, label, description, in_app, push, telegram, customized) and two simple endpoints, so it was built |
153 | docs | bdbf03c | README feature list; unmodelled-field comments for `notification_prefs` removed from Profile |
154
155 Backend facts established by measurement and used in the design:
156 - `notif_grouping_enabled` and `notif_throttle_enabled` are the real values only with `?tab=notifications`; without it the server returns constant `true` (real user had grouping `false`, plain profile said `true`). Hence the dedicated `getNotificationSettings`.
157 - `customized` stays `true` after a user toggles a channel back to its default and only a reset clears it, so the optimistic update sets `customized: true` after any write and matches the server.
158 - Reset restores per-type preferences only; grouping and throttling stay as set. The button is labelled "Reset notification types".
159 - Own profile (`/profile?tab=notifications`, no username) works, used by the SDK.
160
161 Decisions: settings are server-owned and not mirrored in `AppSettingsStore` (device-local store would desync from the web profile);
162 telegram toggle is disabled with an explanatory footer until a chat is paired (as on the web); no in-app screen for other users'
163 profiles from a notification (web fallback, same as the web app link already used elsewhere).
164
165 ## Verification actually run on this Linux machine
166
167 - `swift test` (SDK): 9 tests in 3 suites, all passing (grouped, ungrouped, counts, raw cursor, 20 types + unknown, settings decode, channel wire values).
168 - Harness 1 (real `NotificationsView+ViewModel`, `NotificationRoute`, mocks compiled with `swiftc`, stubbed `DevPlaceApi`/`AppState`): 45 checks passed.
169 - Harness 2 (real `NotificationSettingsView+ViewModel`, `NotificationSettings` mock): 18 checks passed, including optimistic writes, exact request values, reset then reload, failed write alerts, reloads and reverts.
170 - Real backend (local, throwaway data dir, devplacepy untouched and clean, process stopped): cursor paging, profile tab behavior, all write endpoints.
171 - `swiftc -parse` on every changed app file: clean.
172 - Gates over 8c8ed8f..HEAD: 0 em dashes, 0 added comments, 0 tabs, no SwiftUI or Combine in notification ViewModels, no gesture recognizers.
173
174 ## Not verified here (stated, not hidden)
175
176 - Not type-checked or run (need Xcode/UIKit/SwiftUI): `NotificationSettingsView.swift`, `SettingsView.swift`, `MainView.swift`, `NotificationsView.swift` (round 1), `PushNotificationManager.swift`, `AppState.swift`.
177 - `ProdDevPlaceApi.swift` additions were parsed only. The SDK request functions compile (swift test builds the module) but were not run against a server through KreeRequest, because the SDK base URL is the constant `https://devplace.net/`; the request bodies were reproduced with curl.
178 - No simulator, device or APNs run. A push tap on a post is the least covered path.
179
180 ## Known limits left in place
181
182 - A push tap for badge or level opens the web profile, because the push payload carries only a url, not the type.
183 - Feed pagination in `AppState.loadMoreFeed` uses a Date cursor with the same shape of problem. It is not a notification and is deliberately NOT touched on this branch.
184 - `aps.badge` in the push payload (see the TODO in `PushNotificationManager`) needs a backend change.
185
186 ## Release and final gates (round 2)
187
188 - `1.1.1 (5)` to `1.1.2 (6)` in `project.pbxproj` (same four lines as before), commit 41b653d, local tag `1.1.2`. Tags present: `1.1.1`, `1.1.2`.
189 - Gate results are in the verification section above. Working tree clean, devplacepy clean, throwaway backend stopped.
190 - Branch `42-notification-fix` contains notification work only.
191
192 ## What the owner must still do
193
194 1. Build in Xcode and walk through: Notifications tab (grouped and ungrouped, load more), Settings > Notifications (toggles, reset), tap a push for a post.
195 2. Push the branch and the tags `1.1.1`, `1.1.2` when satisfied (not done: outward-facing).
196 3. Decide on the limits listed above (push tap for badge/level, `aps.badge`, and the feed cursor on its own branch).
197
198
199 Scope rule from the owner: notifications only. Backend repo `../devplacepy` may change for this one item.
200 Hard constraint from the owner: NO backend test is executed (no pytest, no `make test*`). Tests are written, not run.
201
202 ## Why
203
204 `PushNotificationManager` carries a TODO: the APNs payload has no badge number, so the app refetches counts on every received push and
205 cannot update the icon badge while backgrounded or terminated. Apple applies `aps.badge` itself, with no app code running.
206
207 ## What I read in the backend before deciding (relatable examples, per its CLAUDE.md "find the example first")
208
209 - One funnel: `utils/notifications.py` `_deliver_notification`: preference gates, insert + `clear_unread_cache`, then `if push: _schedule_push(user_uid, message, target_url)`.
210 `_schedule_push` builds the ONE shared payload `{title, message, icon, url}`. It is fire-and-forget (push/CLAUDE.md invariant: "zero cost for the request").
211 - `push/delivery.py` `notify_user` builds the body once per provider via `provider.prepare(payload)`.
212 `apns.py` `ApnsProvider.prepare` translates the shared payload into `aps.alert`, `thread-id` and custom keys `url`, `icon` (push/CLAUDE.md documents exactly this). `webpush.py` `prepare` is `json.dumps(payload)`;
213 `static/service-worker.js` reads only `url`, `title`, `message`, `icon` from it, so an extra key is ignored there.
214 - The unread number already has ONE definition: `count_unread_groups(user_uid)` (`database/notifications.py`), used by `/notifications/counts`,
215 the web badge (`jinja_unread_count`) and the relay. It counts groups, or rows when grouping is off. The iOS app sets its icon badge from that same number.
216 - A read right after the insert in the same background thread sees the new row (dataset commits per insert on the shared connection; the same function already reads before it inserts).
217 - Existing strictness precedent for payload fields: `apns._dead_before` validates `isinstance(..., (int, float))` and rejects `bool`.
218
219 ## Design (smallest diff, no second implementation)
220
221 1. Shared payload gains ONE key, `unread` (int), not `badge`: in the Notifications API `badge` already means the monochrome icon URL
222 (`service-worker.js` passes `badge: icon`), so reusing the name would confuse.
223 2. `utils/notifications.py`: `if push:` passes `count_unread_groups(user_uid)` into `_schedule_push(user_uid, message, target_url, unread)`; the payload gets `"unread": unread`.
224 Computed only when push actually fires (throttled or disabled pushes cost nothing). If in-app is off for that type there is no new row and the count is simply the current unread number, still correct.
225 `_safe_notify` payload type hint `dict[str, str]` becomes `dict[str, str | int]`.
226 3. `push/providers/apns.py`: `prepare` adds `aps.badge` when `unread` is a non-negative int (and not a bool). Missing or invalid means no `badge` key at all (iOS then leaves the badge untouched).
227 The welcome probe payload (`routers/push.py` `WELCOME_PAYLOAD`) has no `unread`, so it keeps working unchanged.
228 4. Web Push: no code change. The key rides in the encrypted JSON and is ignored by the service worker. Declared as "no change" in the four faces.
229
230 ## Four faces (DEFINITION_OF_DONE 1.5)
231
232 HTML: no change. JSON (`*Out` schemas, endpoints): no change, the number is not exposed over HTTP, only in the push body. Devii action: no change (push identity and payloads are not Devii surface, see push/CLAUDE.md "No Devii action").
233 Documentation: push/CLAUDE.md (payload spec + APNs line), utils/CLAUDE.md (funnel description), README "Push notifications" section, `docs_api/groups/push.py` intro. `events.md`: audit metadata unchanged, no change.
234
235 ## Tests (written in the existing style, NOT executed)
236
237 - `tests/unit/push.py` (pure, next to `test_apns_prepare_translates_the_shared_payload`): prepare puts `unread` into `aps.badge`; zero is kept; missing, negative, bool and non-int values produce no `badge`; the empty-payload test stays valid.
238 - `tests/unit/utils.py` (next to `test_create_mention_notifications_targets_known_users`, uses `local_db` and `_seed_user`, `monkeypatch` on `devplacepy.utils.notifications._schedule_push`):
239 single-group types count rows (1 then 2); grouped types count groups with throttling off (1 then 1) and rows with grouping off (1 then 2);
240 with in-app off for the type the pushed count is the existing unread count.
241 `create_notification` runs inline under tests (utils/CLAUDE.md), so no waiting helper is needed.
242
243 ## Gates
244
245 Done without running tests: `py_compile` on every touched Python file, `pyflakes` if present in `.venv`, import gate `from devplacepy.main import app`
246 with `DEVPLACE_DATA_DIR` and `DEVPLACE_DATABASE_URL` pointed at scratch paths (rule 10: never touch `data/`), no em dashes, no comments or docstrings, no forbidden names.
247 DEFINITION_OF_DONE gates NOT satisfied because of the owner's instruction, to be stated in the delivery: 7 (full suite), 8 (verification through the real path for the new tests), 9 (deploy and verify live).
248 Not done by me: `make test`, any pytest, deploy.
249
250 ## Git
251
252 Backend `master` is clean; the change goes on its own branch `push-unread-badge`, commits in the repo's sentence style, no push, no deploy.
253 App repo (this branch `42-notification-fix`, notification only): remove the TODO in `PushNotificationManager.swift` that this change resolves (the project allows no comments);
254 the refetch of counts on push stays because it also refreshes the tab badge. Version bump 1.1.3 (7) + tag at the end.
255
256 ## Added during implementation (owner request): indexes and field configuration
257
258 Owner instruction: check how indexes and fields are configured elsewhere and make the field I work with configured the same way.
259 The fields my change reads are `notifications.user_uid` and `notifications.read` (through `count_unread_groups`).
260 Audit of `devplacepy/database/schema.py` and `database/CLAUDE.md`:
261
262 | Check | Finding |
263 |---|---|
264 | Indexes on `notifications` | All present and already created by `init_db`: `idx_notifications_uid` (unique), `idx_notifications_user`, `idx_notifications_user_read (user_uid, read)`, `idx_notifications_user_created`, `idx_notifications_created`. Confirmed on a real table built by `init_db`. No index change needed |
265 | Plan of the unread query (`EXPLAIN QUERY PLAN`, scratch DB, not production) | The query as `dataset` emits it, bound parameters (`read = ?`): `SEARCH notifications USING INDEX idx_notifications_user_read (user_uid=? AND read=?)`. A first probe with a literal `read = 0` on a table where one user owns every row showed `SCAN`; that was a probe artifact (literal plus skewed scratch data), not the real query shape |
266 | Column configuration | GAP: `notifications` was the only table filtered and indexed on columns without a column ensure-block in `init_db` (`messages`, `push_registration`, `notification_preferences` all have one; database/CLAUDE.md makes it mandatory because `dataset` gives a lazily created table only the columns of its first insert) |
267 | Fix | Ensure-block for the 8 data columns (`uid`, `user_uid`, `type`, `message`, `related_uid`, `target_url`, `read` as bool, `created_at`), placed before the notification indexes, mirroring the `messages` block exactly. Column set taken from the real table and from the single insert site (`_deliver_notification`) |
268 | Registry test | `notifications` added to `FILTERED_COLUMNS` in `tests/unit/database/schema.py` (the existing registry, one line, same style as `messages`) |
269 | Spec | database/CLAUDE.md states the ensure-block and the serving index next to the sentence that every badge producer calls `count_unread_groups` |
270
271 ## Results per step
272
273 Backend repo `../devplacepy`, new branch `push-unread-badge` from `master` (was clean), 5 commits, no push, no deploy:
274
275 | Commit | Change |
276 |---|---|
277 | 376c6ba | `utils/notifications.py`: `_schedule_push(..., unread)`, payload key `unread`, computed with `count_unread_groups(user_uid)` only inside `if push:` after the insert; `_safe_notify` type hint widened |
278 | d815fbe | `push/providers/apns.py`: `_badge(payload)` (non-negative int, bool refused) and `aps.badge` in `prepare`; absent or invalid means no key |
279 | 2452f9e | `database/schema.py` notifications ensure-block, `tests/unit/database/schema.py` registry entry |
280 | 585fab7 | docs: `push/CLAUDE.md` (payload spec, the `unread` to `aps.badge` rule and why it is not called `badge`), `utils/CLAUDE.md`, `database/CLAUDE.md`, README push section, `docs_api/groups/push.py` intro |
281 | 6a5ed75 | tests: `tests/unit/push.py` (badge mapping, invalid values, unchanged Web Push body), `tests/unit/utils.py` (count for single types, grouped, ungrouped, in-app off) |
282
283 App repo: 9df1d6a removes the resolved TODO in `PushNotificationManager.swift` (the project allows no comments). The count refetch on a received push stays: it refreshes the tab badge.
284
285 Four faces: HTML no change, JSON no change (the number is not exposed over HTTP), Devii no change (push payloads are not Devii surface), documentation updated as above. `events.md` unchanged (audit metadata unchanged).
286
287 ## Verification actually run (static only, by instruction)
288
289 - NO backend test was executed: no pytest, no `make test*`. This was the owner's explicit instruction.
290 - `compile()` on all 7 touched Python files: ok (no `.pyc` written).
291 - `pyflakes` 4.0.3 on all 7 files: clean (`ruff` is not installed in the venv).
292 - Import gate `from devplacepy.main import app` with scratch `DEVPLACE_DATA_DIR` and `DEVPLACE_DATABASE_URL`: ok; `data/` untouched.
293 - `EXPLAIN QUERY PLAN` on a scratch SQLite copy built by `init_db`: see the audit table.
294 - Diff gates over `master..HEAD`: 0 em dashes, 0 added comment lines in Python.
295 - I did not run my own ad hoc probe of `prepare` or the funnel either, to respect the instruction literally. The behavior of the new code is therefore reasoned and statically checked, not observed.
296
297 ## DEFINITION_OF_DONE gates that are OPEN because of the instruction
298
299 - 7 Full suite green: not run. 8 Failing-first then passing for the new tests: not observed. 9 Deploy and verify live: not done.
300 - The 7 new tests and the new registry entry have never run. First run is the owner's: `make test-fast` is the cheapest pass.
301 - Whether APNs accepts the body with `aps.badge` on a real device is unverified.
302
303 ## Release and what the owner must still do (round 3)
304
305 - App: `1.1.2 (6)` to `1.1.3 (7)` (same four `project.pbxproj` lines), local tag `1.1.3`. Tags: `1.1.1`, `1.1.2`, `1.1.3`. Branch `42-notification-fix`, notification work only.
306 - Backend: branch `push-unread-badge` (5 commits on top of `master` 8b45a51). `master` untouched. No push, no merge, no deploy.
307 1. Run the backend tests yourself (nothing was executed): `make test-fast` first, then `make test`. The 7 new tests and the `FILTERED_COLUMNS` entry have never run.
308 2. Review and merge `push-unread-badge`, deploy, then send a real push to a sandbox or TestFlight build and confirm the icon badge changes with the app closed.
309 3. Build the app in Xcode and walk through the screens listed in round 2.
DevPlaceIOS.xcodeproj/project.pbxproj modified +4 -4
@@ -283,7 +283,7 @@
283 283 ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
284 284 CODE_SIGN_ENTITLEMENTS = DevPlaceIOS/DevPlaceIOS.entitlements;
285 285 CODE_SIGN_STYLE = Automatic;
286 CURRENT_PROJECT_VERSION = 4;
286 CURRENT_PROJECT_VERSION = 7;
287 287 DEVELOPMENT_TEAM = J8UL3VBQ4J;
288 288 ENABLE_PREVIEWS = YES;
289 289 GENERATE_INFOPLIST_FILE = YES;
@@ -300,7 +300,7 @@
300 300 "$(inherited)",
301 301 "@executable_path/Frameworks",
302 302 );
303 MARKETING_VERSION = 1.1.0;
303 MARKETING_VERSION = 1.1.3;
304 304 PRODUCT_BUNDLE_IDENTIFIER = wok.DevPlaceIOS;
305 305 PRODUCT_NAME = "$(TARGET_NAME)";
306 306 STRING_CATALOG_GENERATE_SYMBOLS = YES;
@@ -320,7 +320,7 @@
320 320 ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
321 321 CODE_SIGN_ENTITLEMENTS = DevPlaceIOS/DevPlaceIOS.entitlements;
322 322 CODE_SIGN_STYLE = Automatic;
323 CURRENT_PROJECT_VERSION = 4;
323 CURRENT_PROJECT_VERSION = 7;
324 324 DEVELOPMENT_TEAM = J8UL3VBQ4J;
325 325 ENABLE_PREVIEWS = YES;
326 326 GENERATE_INFOPLIST_FILE = YES;
@@ -337,7 +337,7 @@
337 337 "$(inherited)",
338 338 "@executable_path/Frameworks",
339 339 );
340 MARKETING_VERSION = 1.1.0;
340 MARKETING_VERSION = 1.1.3;
341 341 PRODUCT_BUNDLE_IDENTIFIER = wok.DevPlaceIOS;
342 342 PRODUCT_NAME = "$(TARGET_NAME)";
343 343 STRING_CATALOG_GENERATE_SYMBOLS = YES;
DevPlaceIOS/AppState/AppState.swift modified +3 -0
@@ -23,6 +23,8 @@ final class AppState {
23 23
24 24 var pendingConversationUid: String?
25 25
26 var pendingPostDestination: PostDestination?
27
26 28 func isCurrentUser(id: String) -> Bool {
27 29 currentUser?.id == id
28 30 }
@@ -87,5 +89,6 @@ final class AppState {
87 89 unreadNotificationCount = 0
88 90 unreadMessageCount = 0
89 91 pendingConversationUid = nil
92 pendingPostDestination = nil
90 93 }
91 94 }
DevPlaceIOS/Model Mocks/NotificationSettings.swift added +42 -0
@@ -0,0 +1,42 @@
1 import Foundation
2 import DevPlaceSwiftSDK
3
4 extension NotificationSettings {
5 static var mock: Self {
6 .init(
7 user: .mock,
8 groupingEnabled: true,
9 throttlingEnabled: true,
10 telegramPaired: false,
11 preferences: [
12 .init(
13 key: "comment",
14 label: "Comments",
15 description: "Someone comments on your post",
16 inApp: true,
17 push: true,
18 telegram: false,
19 customized: false,
20 ),
21 .init(
22 key: "vote",
23 label: "Upvotes",
24 description: "Someone ++'d your content",
25 inApp: true,
26 push: false,
27 telegram: false,
28 customized: true,
29 ),
30 .init(
31 key: "message",
32 label: "Direct messages",
33 description: "Someone sends you a message",
34 inApp: true,
35 push: true,
36 telegram: false,
37 customized: false,
38 ),
39 ],
40 )
41 }
42 }
DevPlaceIOS/Model Mocks/Notifications.swift modified +80 -47
@@ -7,76 +7,109 @@ extension Notifications {
7 7 groups: [
8 8 .init(
9 9 label: "Today",
10 entries: [
10 entries: [],
11 eventEntries: [
11 12 .init(
12 data: .init(
13 id: "n0",
14 type: .message,
15 message: "null_void sent you a message",
16 read: false,
17 relatedId: "u2",
18 targetUrl: "/messages?with_uid=u2",
19 createdAt: Date().addingTimeInterval(-60 * 3),
13 key: "n0",
14 count: 1,
15 unread: true,
16 actors: [.mock2],
17 latest: .init(
18 data: .init(
19 id: "n0",
20 type: .message,
21 message: "null_void sent you a message",
22 read: false,
23 relatedId: "u2",
24 targetUrl: "/messages?with_uid=u2",
25 createdAt: Date().addingTimeInterval(-60 * 3),
26 ),
27 actor: .mock2,
20 28 ),
21 actor: .mock2,
22 29 ),
23 30 .init(
24 data: .init(
25 id: "n1",
26 type: nil,
27 message: "null_void reacted 🎉 to your post \"Shipping the new build system\"",
28 read: false,
29 relatedId: "p1",
30 targetUrl: "/posts/shipping-the-new-build-system",
31 createdAt: Date().addingTimeInterval(-60 * 8),
31 key: "n1",
32 count: 1,
33 unread: true,
34 actors: [.mock2],
35 latest: .init(
36 data: .init(
37 id: "n1",
38 type: nil,
39 message: "null_void reacted 🎉 to your post \"Shipping the new build system\"",
40 read: false,
41 relatedId: "p1",
42 targetUrl: "/posts/shipping-the-new-build-system",
43 createdAt: Date().addingTimeInterval(-60 * 8),
44 ),
45 actor: .mock2,
32 46 ),
33 actor: .mock2,
34 47 ),
35 48 .init(
36 data: .init(
37 id: "n2",
38 type: .comment,
39 message: "cheeze_on_wheels commented on your post",
40 read: false,
41 relatedId: "c6",
42 targetUrl: "/posts/a-post-with-several-attachments#comment-c6",
43 createdAt: Date().addingTimeInterval(-60 * 47),
49 key: "n2",
50 count: 3,
51 unread: true,
52 actors: [.mock, .mock2],
53 latest: .init(
54 data: .init(
55 id: "n2",
56 type: .comment,
57 message: "cheeze_on_wheels commented on your post",
58 read: false,
59 relatedId: "c6",
60 targetUrl: "/posts/a-post-with-several-attachments#comment-c6",
61 createdAt: Date().addingTimeInterval(-60 * 47),
62 ),
63 actor: .mock,
44 64 ),
45 actor: .mock,
46 65 ),
47 66 ],
48 67 ),
49 68 .init(
50 69 label: "Earlier",
51 entries: [
70 entries: [],
71 eventEntries: [
52 72 .init(
53 data: .init(
54 id: "n3",
55 type: nil,
56 message: "null_void started following you",
57 read: true,
58 relatedId: "u2",
59 targetUrl: "/users/null_void",
60 createdAt: Date().addingTimeInterval(-60 * 60 * 26),
73 key: "n3",
74 count: 1,
75 unread: false,
76 actors: [.mock2],
77 latest: .init(
78 data: .init(
79 id: "n3",
80 type: nil,
81 message: "null_void started following you",
82 read: true,
83 relatedId: "u2",
84 targetUrl: "/users/null_void",
85 createdAt: Date().addingTimeInterval(-60 * 60 * 26),
86 ),
87 actor: .mock2,
61 88 ),
62 actor: .mock2,
63 89 ),
64 90 .init(
65 data: .init(
66 id: "n4",
67 type: .vote,
68 message: "cheeze_on_wheels upvoted your comment",
69 read: true,
70 relatedId: "c1",
71 targetUrl: "/posts/late-night-refactor",
72 createdAt: Date().addingTimeInterval(-60 * 60 * 24 * 4),
91 key: "n4",
92 count: 2,
93 unread: false,
94 actors: [.mock],
95 latest: .init(
96 data: .init(
97 id: "n4",
98 type: .vote,
99 message: "cheeze_on_wheels upvoted your comment",
100 read: true,
101 relatedId: "c1",
102 targetUrl: "/posts/late-night-refactor",
103 createdAt: Date().addingTimeInterval(-60 * 60 * 24 * 4),
104 ),
105 actor: .mock,
73 106 ),
74 actor: .mock,
75 107 ),
76 108 ],
77 109 ),
78 110 ],
79 111 nextCursor: nil,
112 grouping: true,
80 113 )
81 114 }
82 115 }
DevPlaceIOS/Push/PushNotificationManager.swift modified +13 -4
@@ -42,10 +42,6 @@ final class PushNotificationManager {
42 42 dlog("Failed to register for APNs: \(error)")
43 43 }
44 44
45 // TODO: The current push payload carries no badge number, so we refetch counts from the
46 // backend on every received push. Once the backend adds `aps.badge` (server-side unread
47 // count) to the payload, read it directly here and set the icon badge from it — that also
48 // lets iOS update the icon badge while the app is backgrounded/terminated, without a fetch.
49 45 func handleRemoteNotification(userInfo: [AnyHashable: Any]) async {
50 46 dlog("Received push notification payload: \(Self.prettyPrinted(userInfo))")
51 47 await AppState.shared.loadUnreadCounts(api: api)
@@ -55,6 +51,19 @@ final class PushNotificationManager {
55 51 await handleRemoteNotification(userInfo: userInfo)
56 52 if let conversationUid = Self.conversationUid(in: userInfo) {
57 53 AppState.shared.pendingConversationUid = conversationUid
54 return
55 }
56 guard let redirect = userInfo["url"] as? String,
57 let route = NotificationRoute(redirect: redirect) else {
58 return
59 }
60 switch route {
61 case .post(let destination):
62 AppState.shared.pendingPostDestination = destination
63 case .web(let url):
64 await UIApplication.shared.open(url)
65 case .conversation, .ownProfile:
66 break
58 67 }
59 68 }
60 69
DevPlaceIOS/Request/API/DevPlaceApi.swift modified +6 -1
@@ -24,11 +24,16 @@ protocol DevPlaceApi {
24 24 func sendMessage(receiverId: String, content: String, attachments: [UploadResponse]) async throws
25 25 func makeMessagesSocket(otherUserId: String) -> any MessagesSocket
26 26 func usersForMentioning(matching query: String) async throws -> UserSearch
27 func notifications(before: Date?) async throws -> Notifications
27 func notifications(before: String?) async throws -> Notifications
28 28 func openNotification(uid: String) async throws -> NotificationOpen
29 29 func notificationCounts() async throws -> NotificationCounts
30 30 func markNotificationRead(uid: String) async throws
31 31 func markAllNotificationsRead() async throws
32 func notificationSettings() async throws -> NotificationSettings
33 func setNotificationGrouping(username: String, enabled: Bool) async throws
34 func setNotificationThrottling(username: String, enabled: Bool) async throws
35 func setNotificationPreference(username: String, notificationType: String, channel: NotificationChannel, enabled: Bool) async throws
36 func resetNotificationPreferences(username: String) async throws
32 37 func registerPushDevice(deviceToken: String) async throws
33 38 func unregisterPushDevice(deviceToken: String) async throws
34 39 func vote(targetType: TargetType, targetId: String, vote: Vote) async throws
DevPlaceIOS/Request/API/MockDevPlaceApi.swift modified +28 -2
@@ -139,7 +139,7 @@ final class MockDevPlaceApi: DevPlaceApi {
139 139 return UserSearch(results: matches)
140 140 }
141 141
142 func notifications(before: Date?) async throws -> Notifications {
142 func notifications(before: String?) async throws -> Notifications {
143 143 await mockDelay(0.5)
144 144 try await refreshTokenIfNeeded()
145 145 return .mock
@@ -149,7 +149,7 @@ final class MockDevPlaceApi: DevPlaceApi {
149 149 await mockDelay(0.2)
150 150 try await refreshTokenIfNeeded()
151 151 let targetUrl = Notifications.mock.groups
152 .flatMap(\.entries)
152 .flatMap { $0.entries + $0.eventEntries.map(\.latest) }
153 153 .first { $0.data.id == uid }?
154 154 .data.targetUrl
155 155 return NotificationOpen(
@@ -174,6 +174,32 @@ final class MockDevPlaceApi: DevPlaceApi {
174 174 try await refreshTokenIfNeeded()
175 175 }
176 176
177 func notificationSettings() async throws -> NotificationSettings {
178 await mockDelay(0.5)
179 try await refreshTokenIfNeeded()
180 return .mock
181 }
182
183 func setNotificationGrouping(username: String, enabled: Bool) async throws {
184 await mockDelay(0.2)
185 try await refreshTokenIfNeeded()
186 }
187
188 func setNotificationThrottling(username: String, enabled: Bool) async throws {
189 await mockDelay(0.2)
190 try await refreshTokenIfNeeded()
191 }
192
193 func setNotificationPreference(username: String, notificationType: String, channel: NotificationChannel, enabled: Bool) async throws {
194 await mockDelay(0.2)
195 try await refreshTokenIfNeeded()
196 }
197
198 func resetNotificationPreferences(username: String) async throws {
199 await mockDelay(0.2)
200 try await refreshTokenIfNeeded()
201 }
202
177 203 func registerPushDevice(deviceToken: String) async throws {
178 204 await mockDelay(0.2)
179 205 try await refreshTokenIfNeeded()
DevPlaceIOS/Request/API/ProdDevPlaceApi.swift modified +47 -1
@@ -246,7 +246,7 @@ final class ProdDevPlaceApi: DevPlaceApi {
246 246 return try await request.searchMessageRecipients(q: query, token: token)
247 247 }
248 248
249 func notifications(before: Date?) async throws -> Notifications {
249 func notifications(before: String?) async throws -> Notifications {
250 250 guard let token = AppState.shared.token else {
251 251 throw DevPlaceError.notLoggedIn
252 252 }
@@ -286,6 +286,52 @@ final class ProdDevPlaceApi: DevPlaceApi {
286 286 try await request.markAllNotificationsRead(token: token)
287 287 }
288 288
289 func notificationSettings() async throws -> NotificationSettings {
290 guard let token = AppState.shared.token else {
291 throw DevPlaceError.notLoggedIn
292 }
293 try await refreshTokenIfNeeded()
294 return try await request.getNotificationSettings(token: token)
295 }
296
297 func setNotificationGrouping(username: String, enabled: Bool) async throws {
298 guard let token = AppState.shared.token else {
299 throw DevPlaceError.notLoggedIn
300 }
301 try await refreshTokenIfNeeded()
302 try await request.setNotificationGrouping(username: username, enabled: enabled, token: token)
303 }
304
305 func setNotificationThrottling(username: String, enabled: Bool) async throws {
306 guard let token = AppState.shared.token else {
307 throw DevPlaceError.notLoggedIn
308 }
309 try await refreshTokenIfNeeded()
310 try await request.setNotificationThrottling(username: username, enabled: enabled, token: token)
311 }
312
313 func setNotificationPreference(username: String, notificationType: String, channel: NotificationChannel, enabled: Bool) async throws {
314 guard let token = AppState.shared.token else {
315 throw DevPlaceError.notLoggedIn
316 }
317 try await refreshTokenIfNeeded()
318 try await request.setNotificationPreference(
319 username: username,
320 notificationType: notificationType,
321 channel: channel,
322 enabled: enabled,
323 token: token,
324 )
325 }
326
327 func resetNotificationPreferences(username: String) async throws {
328 guard let token = AppState.shared.token else {
329 throw DevPlaceError.notLoggedIn
330 }
331 try await refreshTokenIfNeeded()
332 try await request.resetNotificationPreferences(username: username, token: token)
333 }
334
289 335 func registerPushDevice(deviceToken: String) async throws {
290 336 guard let token = AppState.shared.token else {
291 337 throw DevPlaceError.notLoggedIn
DevPlaceIOS/UI/Navigation/NotificationRoute.swift modified +70 -0
@@ -7,3 +7,73 @@ enum NotificationRoute {
7 7 case web(URL)
8 8 case ownProfile
9 9 }
10
11 extension NotificationRoute {
12 private static let webBaseUrl = "https://devplace.net"
13 private static let notificationsPath = "/notifications"
14
15 init?(redirect: String) {
16 if let destination = Self.postDestination(fromRedirect: redirect) {
17 self = .post(destination)
18 } else if let url = Self.webUrl(fromRedirect: redirect) {
19 self = .web(url)
20 } else {
21 return nil
22 }
23 }
24
25 private static func webUrl(fromRedirect redirect: String) -> URL? {
26 guard redirect.hasPrefix("/"), redirect != notificationsPath else {
27 return nil
28 }
29 return URL(string: webBaseUrl + redirect)
30 }
31
32 private static func postDestination(fromRedirect redirect: String) -> PostDestination? {
33 guard let slug = postSlug(from: redirect) else {
34 return nil
35 }
36 let scrollToCommentId = commentUid(from: redirect).map { "comment:" + $0 }
37 return PostDestination(slug: slug, scrollToCommentId: scrollToCommentId)
38 }
39
40 private static func postSlug(from url: String) -> String? {
41 guard let components = URLComponents(string: url) else { return nil }
42 let segments = components.path.split(separator: "/").map(String.init)
43 guard let postsIndex = segments.firstIndex(of: "posts"),
44 postsIndex + 1 < segments.count else {
45 return nil
46 }
47 return segments[postsIndex + 1]
48 }
49
50 private static func commentUid(from url: String) -> String? {
51 guard let components = URLComponents(string: url) else { return nil }
52
53 if let fragment = components.fragment, let uid = commentUid(fromToken: fragment) {
54 return uid
55 }
56
57 let commentQueryNames = ["comment", "comment_id", "commentId", "comment_uid"]
58 if let value = components.queryItems?.first(where: { commentQueryNames.contains($0.name) })?.value,
59 !value.isEmpty {
60 return value
61 }
62
63 let segments = components.path.split(separator: "/").map(String.init)
64 if let commentsIndex = segments.firstIndex(of: "comments"), commentsIndex + 1 < segments.count {
65 return segments[commentsIndex + 1]
66 }
67
68 return nil
69 }
70
71 private static func commentUid(fromToken token: String) -> String? {
72 let prefixes = ["comment-", "comment_", "comment:", "comment"]
73 for prefix in prefixes where token.hasPrefix(prefix) {
74 let uid = String(token.dropFirst(prefix.count))
75 return uid.isEmpty ? nil : uid
76 }
77 return nil
78 }
79 }
DevPlaceIOS/UI/Navigation/SettingsDestination.swift modified +1 -0
@@ -1,3 +1,4 @@
1 1 enum SettingsDestination: Hashable {
2 2 case profile
3 case notifications
3 4 }
DevPlaceIOS/UI/Screens/Main/MainView.swift modified +15 -0
@@ -61,6 +61,15 @@ struct MainView: View {
61 61 selectedTab = .messages
62 62 }
63 63
64 private func openPendingPostIfNeeded() {
65 guard appState.isLoggedIn, let destination = appState.pendingPostDestination else {
66 return
67 }
68 appState.pendingPostDestination = nil
69 feedPost = destination
70 selectedTab = .postsFeed
71 }
72
64 73 @ViewBuilder private func content() -> some View {
65 74 TabView(selection: tabSelection) {
66 75 Tab(value: .postsFeed) {
@@ -131,6 +140,7 @@ struct MainView: View {
131 140 if appState.isLoggedIn {
132 141 await PushNotificationManager.shared.registerForPushNotifications(api: api)
133 142 await openPendingConversationIfNeeded()
143 openPendingPostIfNeeded()
134 144 }
135 145 }
136 146 .onChange(of: appState.isLoggedIn) { _, isLoggedIn in
@@ -138,6 +148,7 @@ struct MainView: View {
138 148 Task {
139 149 await PushNotificationManager.shared.registerForPushNotifications(api: api)
140 150 await openPendingConversationIfNeeded()
151 openPendingPostIfNeeded()
141 152 }
142 153 } else {
143 154 messagesPath = []
@@ -150,6 +161,10 @@ struct MainView: View {
150 161 await openPendingConversationIfNeeded()
151 162 }
152 163 }
164 .onChange(of: appState.pendingPostDestination) { _, destination in
165 guard destination != nil else { return }
166 openPendingPostIfNeeded()
167 }
153 168 .onChange(of: selectedTab) {
154 169 Task {
155 170 await appState.loadUnreadCounts(api: api)
DevPlaceIOS/UI/Screens/NotificationSettings/NotificationSettingsView+ViewModel.swift added +112 -0
@@ -0,0 +1,112 @@
1 import Foundation
2 import Observation
3 import DevPlaceSwiftSDK
4
5 extension NotificationSettingsView {
6 @Observable final class ViewModel {
7 let api: DevPlaceApi
8
9 var username: String?
10 var groupingEnabled = true
11 var throttlingEnabled = true
12 var telegramPaired = false
13 var preferences: [NotificationPreference] = []
14 var isLoaded = false
15 var alertMessage: AlertMessage = .none()
16
17 init(api: DevPlaceApi) {
18 self.api = api
19 }
20
21 var hasCustomizedPreferences: Bool {
22 preferences.contains { $0.customized }
23 }
24
25 func isEnabled(_ channel: NotificationChannel, in preference: NotificationPreference) -> Bool {
26 switch channel {
27 case .inApp:
28 preference.inApp
29 case .push:
30 preference.push
31 case .telegram:
32 preference.telegram
33 }
34 }
35
36 func load() async {
37 do {
38 let settings = try await api.notificationSettings()
39 username = settings.user.username
40 groupingEnabled = settings.groupingEnabled
41 throttlingEnabled = settings.throttlingEnabled
42 telegramPaired = settings.telegramPaired
43 preferences = settings.preferences
44 isLoaded = true
45 } catch {
46 alertMessage = .presentedError(error)
47 }
48 }
49
50 func setGrouping(_ enabled: Bool) async {
51 guard let username else { return }
52 groupingEnabled = enabled
53 do {
54 try await api.setNotificationGrouping(username: username, enabled: enabled)
55 } catch {
56 alertMessage = .presentedError(error)
57 await load()
58 }
59 }
60
61 func setThrottling(_ enabled: Bool) async {
62 guard let username else { return }
63 throttlingEnabled = enabled
64 do {
65 try await api.setNotificationThrottling(username: username, enabled: enabled)
66 } catch {
67 alertMessage = .presentedError(error)
68 await load()
69 }
70 }
71
72 func set(_ channel: NotificationChannel, enabled: Bool, forKey key: String) async {
73 guard let username else { return }
74 preferences = preferences.map { preference in
75 preference.key == key ? updated(preference, channel: channel, enabled: enabled) : preference
76 }
77 do {
78 try await api.setNotificationPreference(
79 username: username,
80 notificationType: key,
81 channel: channel,
82 enabled: enabled,
83 )
84 } catch {
85 alertMessage = .presentedError(error)
86 await load()
87 }
88 }
89
90 func resetPreferences() async {
91 guard let username else { return }
92 do {
93 try await api.resetNotificationPreferences(username: username)
94 } catch {
95 alertMessage = .presentedError(error)
96 }
97 await load()
98 }
99
100 private func updated(_ preference: NotificationPreference, channel: NotificationChannel, enabled: Bool) -> NotificationPreference {
101 NotificationPreference(
102 key: preference.key,
103 label: preference.label,
104 description: preference.description,
105 inApp: channel == .inApp ? enabled : preference.inApp,
106 push: channel == .push ? enabled : preference.push,
107 telegram: channel == .telegram ? enabled : preference.telegram,
108 customized: true,
109 )
110 }
111 }
112 }
DevPlaceIOS/UI/Screens/NotificationSettings/NotificationSettingsView.swift added +160 -0
@@ -0,0 +1,160 @@
1 import SwiftUI
2 import DevPlaceSwiftSDK
3
4 struct NotificationSettingsView: View {
5 @Environment(\.api) var api
6
7 var body: some View {
8 NotificationSettingsViewContent(viewModel: .init(api: api))
9 }
10 }
11
12 private struct NotificationSettingsViewContent: View {
13 @State var viewModel: NotificationSettingsView.ViewModel
14
15 @State private var resetConfirmationPresented = false
16
17 var body: some View {
18 content()
19 .screenStyle()
20 .navigationTitle(Text("Notifications"))
21 .alert($viewModel.alertMessage)
22 .task {
23 await viewModel.load()
24 }
25 }
26
27 @ViewBuilder private func content() -> some View {
28 if viewModel.isLoaded {
29 Form {
30 displaySection()
31 ForEach(viewModel.preferences) { preference in
32 preferenceSection(preference)
33 }
34 resetSection()
35 }
36 .scrollContentBackground(.hidden)
37 } else {
38 ProgressView()
39 }
40 }
41
42 @ViewBuilder private func displaySection() -> some View {
43 Section {
44 Toggle(
45 isOn: Binding(
46 get: { viewModel.groupingEnabled },
47 set: { newValue in
48 Task {
49 await viewModel.setGrouping(newValue)
50 }
51 },
52 )
53 ) {
54 Label {
55 Text("Group similar notifications")
56 } icon: {
57 Image(systemName: "rectangle.stack")
58 }
59 }
60 .tint(Color.accentColor)
61
62 Toggle(
63 isOn: Binding(
64 get: { viewModel.throttlingEnabled },
65 set: { newValue in
66 Task {
67 await viewModel.setThrottling(newValue)
68 }
69 },
70 )
71 ) {
72 Label {
73 Text("Throttle repeat alerts")
74 } icon: {
75 Image(systemName: "timer")
76 }
77 }
78 .tint(Color.accentColor)
79 } footer: {
80 Text("Grouped notifications share one entry and the badge counts groups. Throttling sends at most one push per similar event group every 5 minutes. In-app notifications are never throttled.")
81 }
82 .listRowBackground(Color.BG_1)
83 }
84
85 @ViewBuilder private func preferenceSection(_ preference: NotificationPreference) -> some View {
86 Section {
87 ForEach(NotificationChannel.allCases, id: \.self) { channel in
88 Toggle(
89 isOn: Binding(
90 get: { viewModel.isEnabled(channel, in: preference) },
91 set: { newValue in
92 Task {
93 await viewModel.set(channel, enabled: newValue, forKey: preference.key)
94 }
95 },
96 )
97 ) {
98 Text(title(for: channel))
99 }
100 .tint(Color.accentColor)
101 .disabled(channel == .telegram && !viewModel.telegramPaired)
102 }
103 } header: {
104 Text(preference.label)
105 } footer: {
106 Text(preference.description)
107 }
108 .listRowBackground(Color.BG_1)
109 }
110
111 @ViewBuilder private func resetSection() -> some View {
112 Section {
113 Button(role: .destructive) {
114 resetConfirmationPresented = true
115 } label: {
116 Label {
117 Text("Reset notification types")
118 } icon: {
119 Image(systemName: "arrow.counterclockwise")
120 }
121 }
122 .buttonStyle(.form)
123 .disabled(!viewModel.hasCustomizedPreferences)
124 .alert(
125 "Reset all notification types to their defaults?",
126 isPresented: $resetConfirmationPresented
127 ) {
128 Button(role: .cancel, action: {})
129 Button("Reset", role: .destructive) {
130 Task {
131 await viewModel.resetPreferences()
132 }
133 }
134 }
135 } footer: {
136 if !viewModel.telegramPaired {
137 Text("Telegram notifications need a paired Telegram chat. Connect Telegram from your profile on the web.")
138 }
139 }
140 .listRowBackground(Color.BG_1)
141 }
142
143 private func title(for channel: NotificationChannel) -> String {
144 switch channel {
145 case .inApp:
146 "In-app"
147 case .push:
148 "Push"
149 case .telegram:
150 "Telegram"
151 }
152 }
153 }
154
155 #Preview {
156 NavigationStack {
157 NotificationSettingsView()
158 }
159 .environment(\.api, .mock)
160 }
DevPlaceIOS/UI/Screens/Notifications/NotificationsView+ViewModel.swift modified +112 -78
@@ -14,10 +14,38 @@ extension NotificationsView {
14 14 self.api = api
15 15 }
16 16
17 struct Row: Identifiable {
18 let id: String
19 let notification: DevPlaceSwiftSDK.Notification
20 let count: Int
21 let isUnread: Bool
22 }
23
17 24 var groups: [NotificationGroup] {
18 25 notifications?.groups ?? []
19 26 }
20 27
28 func rows(in group: NotificationGroup) -> [Row] {
29 if notifications?.grouping == true {
30 return group.eventEntries.map { eventGroup in
31 Row(
32 id: eventGroup.id,
33 notification: eventGroup.latest,
34 count: eventGroup.count,
35 isUnread: eventGroup.unread,
36 )
37 }
38 }
39 return group.entries.map { entry in
40 Row(
41 id: entry.id,
42 notification: entry,
43 count: 1,
44 isUnread: !entry.data.read,
45 )
46 }
47 }
48
21 49 func load() async {
22 50 guard AppState.shared.isLoggedIn else {
23 51 notifications = nil
@@ -80,67 +108,10 @@ extension NotificationsView {
80 108 if notification.data.type == .message, let otherUser = notification.actor {
81 109 return .conversation(otherUser)
82 110 }
83 if notification.data.type == .badge {
111 if notification.data.type == .badge || notification.data.type == .level {
84 112 return .ownProfile
85 113 }
86 if notification.data.type == .issue {
87 if let url = URL(string: "https://devplace.net/issues/\(notification.data.relatedId)") {
88 return .web(url)
89 }
90 return nil
91 }
92 if let destination = postDestination(fromRedirect: redirect) {
93 return .post(destination)
94 }
95 return nil
96 }
97
98 private func postDestination(fromRedirect redirect: String) -> PostDestination? {
99 guard let slug = postSlug(from: redirect) else {
100 return nil
101 }
102 let scrollToCommentId = commentUid(from: redirect).map { "comment:" + $0 }
103 return PostDestination(slug: slug, scrollToCommentId: scrollToCommentId)
104 }
105
106 private func postSlug(from url: String) -> String? {
107 guard let components = URLComponents(string: url) else { return nil }
108 let segments = components.path.split(separator: "/").map(String.init)
109 guard let postsIndex = segments.firstIndex(of: "posts"),
110 postsIndex + 1 < segments.count else {
111 return nil
112 }
113 return segments[postsIndex + 1]
114 }
115
116 private func commentUid(from url: String) -> String? {
117 guard let components = URLComponents(string: url) else { return nil }
118
119 if let fragment = components.fragment, let uid = commentUid(fromToken: fragment) {
120 return uid
121 }
122
123 let commentQueryNames = ["comment", "comment_id", "commentId", "comment_uid"]
124 if let value = components.queryItems?.first(where: { commentQueryNames.contains($0.name) })?.value,
125 !value.isEmpty {
126 return value
127 }
128
129 let segments = components.path.split(separator: "/").map(String.init)
130 if let commentsIndex = segments.firstIndex(of: "comments"), commentsIndex + 1 < segments.count {
131 return segments[commentsIndex + 1]
132 }
133
134 return nil
135 }
136
137 private func commentUid(fromToken token: String) -> String? {
138 let prefixes = ["comment-", "comment_", "comment:", "comment"]
139 for prefix in prefixes where token.hasPrefix(prefix) {
140 let uid = String(token.dropFirst(prefix.count))
141 return uid.isEmpty ? nil : uid
142 }
143 return nil
114 return NotificationRoute(redirect: redirect)
144 115 }
145 116
146 117 func markRead(uid: String) async {
@@ -155,7 +126,9 @@ extension NotificationsView {
155 126 }
156 127
157 128 func markAllRead() async {
158 let allUids = Set(groups.flatMap { $0.entries }.map { $0.data.id })
129 let entryUids = groups.flatMap { $0.entries }.map { $0.data.id }
130 let latestUids = groups.flatMap { $0.eventEntries }.map { $0.latest.data.id }
131 let allUids = Set(entryUids + latestUids)
159 132 notifications = applyingRead(uids: allUids)
160 133 do {
161 134 try await api.markAllNotificationsRead()
@@ -173,12 +146,48 @@ extension NotificationsView {
173 146 groups[index] = NotificationGroup(
174 147 label: group.label,
175 148 entries: groups[index].entries + group.entries,
149 eventEntries: mergedEventEntries(groups[index].eventEntries, with: group.eventEntries),
176 150 )
177 151 } else {
178 152 groups.append(group)
179 153 }
180 154 }
181 return deduplicated(Notifications(groups: groups, nextCursor: older.nextCursor))
155 return deduplicated(
156 Notifications(
157 groups: groups,
158 nextCursor: older.nextCursor,
159 grouping: existing.grouping,
160 )
161 )
162 }
163
164 private func mergedEventEntries(
165 _ existing: [NotificationEventGroup],
166 with older: [NotificationEventGroup],
167 ) -> [NotificationEventGroup] {
168 var merged = existing
169 for eventGroup in older {
170 if let index = merged.firstIndex(where: { $0.key == eventGroup.key }) {
171 merged[index] = combined(merged[index], eventGroup)
172 } else {
173 merged.append(eventGroup)
174 }
175 }
176 return merged
177 }
178
179 private func combined(_ newer: NotificationEventGroup, _ older: NotificationEventGroup) -> NotificationEventGroup {
180 var actors = newer.actors
181 for actor in older.actors where actors.count < 3 && !actors.contains(where: { $0.id == actor.id }) {
182 actors.append(actor)
183 }
184 return NotificationEventGroup(
185 key: newer.key,
186 count: newer.count + older.count,
187 unread: newer.unread || older.unread,
188 actors: actors,
189 latest: newer.latest,
190 )
182 191 }
183 192
184 193 private func deduplicated(_ notifications: Notifications) -> Notifications {
@@ -193,14 +202,19 @@ extension NotificationsView {
193 202 }
194 203 return true
195 204 }
196 return NotificationGroup(label: group.label, entries: uniqueEntries)
205 return NotificationGroup(
206 label: group.label,
207 entries: uniqueEntries,
208 eventEntries: group.eventEntries,
209 )
197 210 }
198 211 if !duplicateIds.isEmpty {
199 dlog("Dropped duplicate notification IDs while loading more (backend pagination bug — report to backend team): \(duplicateIds.joined(separator: ", "))")
212 dlog("Dropped duplicate notification IDs while loading more: \(duplicateIds.joined(separator: ", "))")
200 213 }
201 214 return Notifications(
202 groups: groups.filter { !$0.entries.isEmpty },
215 groups: groups.filter { !$0.entries.isEmpty || !$0.eventEntries.isEmpty },
203 216 nextCursor: notifications.nextCursor,
217 grouping: notifications.grouping,
204 218 )
205 219 }
206 220
@@ -210,25 +224,45 @@ extension NotificationsView {
210 224 NotificationGroup(
211 225 label: group.label,
212 226 entries: group.entries.map { entry in
213 guard uids.contains(entry.data.id), !entry.data.read else {
214 return entry
227 markedRead(entry, uids: uids)
228 },
229 eventEntries: group.eventEntries.map { eventGroup in
230 guard uids.contains(eventGroup.latest.data.id) else {
231 return eventGroup
215 232 }
216 return DevPlaceSwiftSDK.Notification(
217 data: .init(
218 id: entry.data.id,
219 type: entry.data.type,
220 message: entry.data.message,
221 read: true,
222 relatedId: entry.data.relatedId,
223 targetUrl: entry.data.targetUrl,
224 createdAt: entry.data.createdAt,
225 ),
226 actor: entry.actor,
233 return NotificationEventGroup(
234 key: eventGroup.key,
235 count: eventGroup.count,
236 unread: false,
237 actors: eventGroup.actors,
238 latest: markedRead(eventGroup.latest, uids: uids),
227 239 )
228 240 },
229 241 )
230 242 }
231 return Notifications(groups: groups, nextCursor: notifications.nextCursor)
243 return Notifications(
244 groups: groups,
245 nextCursor: notifications.nextCursor,
246 grouping: notifications.grouping,
247 )
248 }
249
250 private func markedRead(_ notification: DevPlaceSwiftSDK.Notification, uids: Set<String>) -> DevPlaceSwiftSDK.Notification {
251 guard uids.contains(notification.data.id), !notification.data.read else {
252 return notification
253 }
254 return DevPlaceSwiftSDK.Notification(
255 data: .init(
256 id: notification.data.id,
257 type: notification.data.type,
258 message: notification.data.message,
259 read: true,
260 relatedId: notification.data.relatedId,
261 targetUrl: notification.data.targetUrl,
262 createdAt: notification.data.createdAt,
263 ),
264 actor: notification.actor,
265 )
232 266 }
233 267 }
234 268 }
DevPlaceIOS/UI/Screens/Notifications/NotificationsView.swift modified +18 -10
@@ -128,6 +128,7 @@ private struct NotificationsViewContent: View {
128 128 }
129 129
130 130 @ViewBuilder private func groupSection(_ group: NotificationGroup) -> some View {
131 let rows = viewModel.rows(in: group)
131 132 VStack(alignment: .leading, spacing: 8) {
132 133 Text(group.label)
133 134 .font(.headline)
@@ -135,12 +136,12 @@ private struct NotificationsViewContent: View {
135 136
136 137 BoxView(backgroundColor: .BG_1, paddingSize: .none) {
137 138 VStack(spacing: 0) {
138 ForEach(group.entries) { notification in
139 ForEach(rows) { row in
139 140 NotificationRow(
140 notification: notification,
141 row: row,
141 142 onSelect: {
142 143 Task {
143 switch await viewModel.open(notification: notification) {
144 switch await viewModel.open(notification: row.notification) {
144 145 case .post(let destination):
145 146 onOpenPost(destination)
146 147 case .conversation(let otherUser):
@@ -155,7 +156,7 @@ private struct NotificationsViewContent: View {
155 156 }
156 157 },
157 158 )
158 if notification.id != group.entries.last?.id {
159 if row.id != rows.last?.id {
159 160 Divider()
160 161 }
161 162 }
@@ -167,27 +168,27 @@ private struct NotificationsViewContent: View {
167 168 }
168 169
169 170 private struct NotificationRow: View {
170 let notification: DevPlaceSwiftSDK.Notification
171 let row: NotificationsView.ViewModel.Row
171 172 let onSelect: () -> Void
172 173
173 174 var body: some View {
174 175 Button(action: onSelect) {
175 176 HStack(alignment: .top, spacing: 10) {
176 if let user = notification.actor {
177 if let user = row.notification.actor {
177 178 UserImage(user: user)
178 179 }
179 180
180 181 VStack(alignment: .leading, spacing: 4) {
181 Text(notification.data.message)
182 Text(messageText)
182 183 .font(.subheadline)
183 184 .foregroundStyle(Color.FG_1)
184 185 .multilineTextAlignment(.leading)
185 186 .frame(maxWidth: .infinity, alignment: .leading)
186 187
187 RelativeTimeLabel(date: notification.data.createdAt)
188 RelativeTimeLabel(date: row.notification.data.createdAt)
188 189 }
189 190
190 if !notification.data.read {
191 if row.isUnread {
191 192 Circle()
192 193 .fill(Color.accentColor)
193 194 .frame(width: 8, height: 8)
@@ -195,11 +196,18 @@ private struct NotificationRow: View {
195 196 }
196 197 }
197 198 .padding(12)
198 .background(notification.data.read ? Color.clear : Color.accentColor.opacity(0.08))
199 .background(row.isUnread ? Color.accentColor.opacity(0.08) : Color.clear)
199 200 .contentShape(Rectangle())
200 201 }
201 202 .buttonStyle(.plain)
202 203 }
204
205 private var messageText: String {
206 guard row.count > 1 else {
207 return row.notification.data.message
208 }
209 return "\(row.notification.data.message) ×\(row.count)"
210 }
203 211 }
204 212
205 213 #Preview {
DevPlaceIOS/UI/Screens/Settings/SettingsView.swift modified +11 -0
@@ -34,6 +34,8 @@ private struct SettingsViewContent: View {
34 34 switch destination {
35 35 case .profile:
36 36 ProfileView()
37 case .notifications:
38 NotificationSettingsView()
37 39 }
38 40 }
39 41 .toolbar {
@@ -68,6 +70,15 @@ private struct SettingsViewContent: View {
68 70 }
69 71 }
70 72 .buttonStyle(.form)
73
74 NavigationLink(value: SettingsDestination.notifications) {
75 Label {
76 Text("Notifications")
77 } icon: {
78 Image(systemName: "bell")
79 }
80 }
81 .buttonStyle(.form)
71 82 }
72 83 }
73 84 .listRowBackground(Color.BG_1)
DevPlaceSwiftSDK/Package.swift modified +4 -1
@@ -23,6 +23,9 @@ let package = Package(
23 23 name: "DevPlaceSwiftSDK",
24 24 dependencies: ["KreeRequest"]
25 25 ),
26
26 .testTarget(
27 name: "DevPlaceSwiftSDKTests",
28 dependencies: ["DevPlaceSwiftSDK"]
29 ),
27 30 ]
28 31 )
DevPlaceSwiftSDK/Sources/DevPlaceSwiftSDK/DevPlaceSwiftSDK.swift modified +49 -2
@@ -540,9 +540,9 @@ public extension DevPlaceRequest {
540 540
541 541 // MARK: - Notifications
542 542
543 func getNotifications(before: Date? = nil, token: AuthToken) async throws -> Notifications {
543 func getNotifications(before: String? = nil, token: AuthToken) async throws -> Notifications {
544 544 var parameters: [String: String] = [:]
545 if let before { parameters["before"] = before.formatted(.iso8601) }
545 if let before { parameters["before"] = before }
546 546 let config = makeConfig(.get, path: "notifications", urlParameters: parameters, token: token)
547 547 let response: Notifications.CodingData = try await request.requestJson(config: config, apiError: ApiError.self)
548 548 return response.decoded
@@ -570,6 +570,53 @@ public extension DevPlaceRequest {
570 570 try await request.requestJson(config: config, apiError: ApiError.self)
571 571 }
572 572
573 func getNotificationSettings(token: AuthToken) async throws -> NotificationSettings {
574 let config = makeConfig(.get, path: "profile", urlParameters: ["tab": "notifications"], token: token)
575 let response: NotificationSettings.CodingData = try await request.requestJson(config: config, apiError: ApiError.self)
576 return response.decoded
577 }
578
579 func setNotificationGrouping(username: String, enabled: Bool, token: AuthToken) async throws {
580 struct Body: Encodable {
581 let value: Bool
582 }
583
584 let config = makeConfig(.post, path: "profile/\(username)/notifications/grouping", contentType: .jsonBody, token: token)
585 try await request.requestJson(config: config, json: Body(value: enabled), apiError: ApiError.self)
586 }
587
588 func setNotificationThrottling(username: String, enabled: Bool, token: AuthToken) async throws {
589 struct Body: Encodable {
590 let value: Bool
591 }
592
593 let config = makeConfig(.post, path: "profile/\(username)/notifications/throttling", contentType: .jsonBody, token: token)
594 try await request.requestJson(config: config, json: Body(value: enabled), apiError: ApiError.self)
595 }
596
597 func setNotificationPreference(
598 username: String,
599 notificationType: String,
600 channel: NotificationChannel,
601 enabled: Bool,
602 token: AuthToken,
603 ) async throws {
604 struct Body: Encodable {
605 let notification_type: String
606 let channel: String
607 let value: Bool
608 }
609
610 let config = makeConfig(.post, path: "profile/\(username)/notifications", contentType: .jsonBody, token: token)
611 let body = Body(notification_type: notificationType, channel: channel.rawValue, value: enabled)
612 try await request.requestJson(config: config, json: body, apiError: ApiError.self)
613 }
614
615 func resetNotificationPreferences(username: String, token: AuthToken) async throws {
616 let config = makeConfig(.post, path: "profile/\(username)/notifications/reset", token: token)
617 try await request.requestJson(config: config, apiError: ApiError.self)
618 }
619
573 620 // MARK: - Push
574 621
575 622 func registerPushDevice(provider: PushProvider, deviceToken: String, token: AuthToken) async throws {
DevPlaceSwiftSDK/Sources/DevPlaceSwiftSDK/Models/Response/NotificationEventGroup.swift added +44 -0
@@ -0,0 +1,44 @@
1 public struct NotificationEventGroup: Hashable, Sendable, Identifiable {
2 public var id: String { "notificationEventGroup:" + key }
3 public let key: String
4 public let count: Int
5 public let unread: Bool
6 public let actors: [User]
7 public let latest: Notification
8
9 public init(
10 key: String,
11 count: Int,
12 unread: Bool,
13 actors: [User],
14 latest: Notification,
15 ) {
16 self.key = key
17 self.count = count
18 self.unread = unread
19 self.actors = actors
20 self.latest = latest
21 }
22 }
23
24 extension NotificationEventGroup {
25 struct CodingData: Decodable {
26 let key: String
27 let count: Int
28 let unread: Bool
29 let actors: [User.CodingData]
30 let latest: Notification.CodingData
31 }
32 }
33
34 extension NotificationEventGroup.CodingData {
35 var decoded: NotificationEventGroup {
36 .init(
37 key: key,
38 count: count,
39 unread: unread,
40 actors: actors.map(\.decoded),
41 latest: latest.decoded,
42 )
43 }
44 }
DevPlaceSwiftSDK/Sources/DevPlaceSwiftSDK/Models/Response/NotificationGroup.swift modified +5 -0
@@ -1,13 +1,16 @@
1 1 public struct NotificationGroup: Hashable, Sendable {
2 2 public let label: String
3 3 public let entries: [Notification]
4 public let eventEntries: [NotificationEventGroup]
4 5
5 6 public init(
6 7 label: String,
7 8 entries: [Notification],
9 eventEntries: [NotificationEventGroup],
8 10 ) {
9 11 self.label = label
10 12 self.entries = entries
13 self.eventEntries = eventEntries
11 14 }
12 15 }
13 16
@@ -15,6 +18,7 @@ extension NotificationGroup {
15 18 struct CodingData: Decodable {
16 19 let label: String
17 20 let entries: [Notification.CodingData]
21 let event_entries: [NotificationEventGroup.CodingData]
18 22 }
19 23 }
20 24
@@ -23,6 +27,7 @@ extension NotificationGroup.CodingData {
23 27 .init(
24 28 label: label,
25 29 entries: entries.map(\.decoded),
30 eventEntries: event_entries.map(\.decoded),
26 31 )
27 32 }
28 33 }
DevPlaceSwiftSDK/Sources/DevPlaceSwiftSDK/Models/Response/NotificationPreference.swift added +54 -0
@@ -0,0 +1,54 @@
1 public struct NotificationPreference: Hashable, Sendable, Identifiable {
2 public var id: String { "notificationPreference:" + key }
3 public let key: String
4 public let label: String
5 public let description: String
6 public let inApp: Bool
7 public let push: Bool
8 public let telegram: Bool
9 public let customized: Bool
10
11 public init(
12 key: String,
13 label: String,
14 description: String,
15 inApp: Bool,
16 push: Bool,
17 telegram: Bool,
18 customized: Bool,
19 ) {
20 self.key = key
21 self.label = label
22 self.description = description
23 self.inApp = inApp
24 self.push = push
25 self.telegram = telegram
26 self.customized = customized
27 }
28 }
29
30 extension NotificationPreference {
31 struct CodingData: Decodable {
32 let key: String
33 let label: String
34 let description: String
35 let in_app: Bool
36 let push: Bool
37 let telegram: Bool
38 let customized: Bool
39 }
40 }
41
42 extension NotificationPreference.CodingData {
43 var decoded: NotificationPreference {
44 .init(
45 key: key,
46 label: label,
47 description: description,
48 inApp: in_app,
49 push: push,
50 telegram: telegram,
51 customized: customized,
52 )
53 }
54 }
DevPlaceSwiftSDK/Sources/DevPlaceSwiftSDK/Models/Response/NotificationSettings.swift added +44 -0
@@ -0,0 +1,44 @@
1 public struct NotificationSettings: Hashable, Sendable, Identifiable {
2 public var id: String { "notificationSettings:" + user.id }
3 public let user: User
4 public let groupingEnabled: Bool
5 public let throttlingEnabled: Bool
6 public let telegramPaired: Bool
7 public let preferences: [NotificationPreference]
8
9 public init(
10 user: User,
11 groupingEnabled: Bool,
12 throttlingEnabled: Bool,
13 telegramPaired: Bool,
14 preferences: [NotificationPreference],
15 ) {
16 self.user = user
17 self.groupingEnabled = groupingEnabled
18 self.throttlingEnabled = throttlingEnabled
19 self.telegramPaired = telegramPaired
20 self.preferences = preferences
21 }
22 }
23
24 extension NotificationSettings {
25 struct CodingData: Decodable {
26 let profile_user: User.CodingData
27 let notif_grouping_enabled: Bool
28 let notif_throttle_enabled: Bool
29 let notif_telegram_paired: Bool
30 let notification_prefs: [NotificationPreference.CodingData]
31 }
32 }
33
34 extension NotificationSettings.CodingData {
35 var decoded: NotificationSettings {
36 .init(
37 user: profile_user.decoded,
38 groupingEnabled: notif_grouping_enabled,
39 throttlingEnabled: notif_throttle_enabled,
40 telegramPaired: notif_telegram_paired,
41 preferences: notification_prefs.map(\.decoded),
42 )
43 }
44 }
DevPlaceSwiftSDK/Sources/DevPlaceSwiftSDK/Models/Response/Notifications.swift modified +8 -5
@@ -1,22 +1,24 @@
1 import Foundation
2
3 1 public struct Notifications: Hashable, Sendable {
4 2 public let groups: [NotificationGroup]
5 public let nextCursor: Date?
3 public let nextCursor: String?
4 public let grouping: Bool
6 5
7 6 public init(
8 7 groups: [NotificationGroup],
9 nextCursor: Date?,
8 nextCursor: String?,
9 grouping: Bool,
10 10 ) {
11 11 self.groups = groups
12 12 self.nextCursor = nextCursor
13 self.grouping = grouping
13 14 }
14 15 }
15 16
16 17 extension Notifications {
17 18 struct CodingData: Decodable {
18 19 let notification_groups: [NotificationGroup.CodingData]
19 let next_cursor: Date?
20 let next_cursor: String?
21 let grouping: Bool
20 22 }
21 23 }
22 24
@@ -25,6 +27,7 @@ extension Notifications.CodingData {
25 27 .init(
26 28 groups: notification_groups.map(\.decoded),
27 29 nextCursor: next_cursor,
30 grouping: grouping,
28 31 )
29 32 }
30 33 }
DevPlaceSwiftSDK/Sources/DevPlaceSwiftSDK/Models/Response/Profile.swift modified +0 -2
@@ -45,7 +45,6 @@ public struct Profile: Hashable, Sendable, Identifiable {
45 45 //public let people: [???] // array with null in sample - type unknown
46 46 //public let followPagination: ??? // null in sample - type unknown
47 47 //public let mediaPagination: ??? // null in sample - type unknown
48 //public let notificationPrefs: [???] // array with null in sample - type unknown
49 48
50 49 public init(
51 50 user: User,
@@ -161,7 +160,6 @@ extension Profile {
161 160 //let people: [???] // array with null in sample - type unknown
162 161 //let follow_pagination: ??? // null in sample - type unknown
163 162 //let media_pagination: ??? // null in sample - type unknown
164 //let notification_prefs: [???] // array with null in sample - type unknown
165 163 }
166 164 }
167 165
DevPlaceSwiftSDK/Sources/DevPlaceSwiftSDK/Models/TypedStrings/NotificationChannel.swift added +5 -0
@@ -0,0 +1,5 @@
1 public enum NotificationChannel: String, Hashable, Sendable, CaseIterable {
2 case inApp = "in_app"
3 case push = "push"
4 case telegram = "telegram"
5 }
DevPlaceSwiftSDK/Sources/DevPlaceSwiftSDK/Models/TypedStrings/NotificationType.swift modified +15 -2
@@ -1,9 +1,22 @@
1 public enum NotificationType: String, Hashable, Sendable {
1 public enum NotificationType: String, Hashable, Sendable, CaseIterable {
2 2 case comment = "comment"
3 3 case reply = "reply"
4 case thread = "thread"
4 5 case mention = "mention"
5 6 case vote = "vote"
7 case follow = "follow"
6 8 case message = "message"
7 case issue = "issue"
8 9 case badge = "badge"
10 case level = "level"
11 case issue = "issue"
12 case reminder = "reminder"
13 case harvestStolen = "harvest_stolen"
14 case award = "award"
15 case quizAttempt = "quiz_attempt"
16 case battle = "battle"
17 case workspace = "workspace"
18 case moderation = "moderation"
19 case system = "system"
20 case aiQuotaWarning = "ai_quota_warning"
21 case gameUpkeep = "game_upkeep"
9 22 }
DevPlaceSwiftSDK/Tests/DevPlaceSwiftSDKTests/NotificationSettingsDecodingTests.swift added +73 -0
@@ -0,0 +1,73 @@
1 import Foundation
2 import Testing
3 @testable import DevPlaceSwiftSDK
4
5 struct NotificationSettingsDecodingTests {
6 @Test func decodesSettingsFromTheNotificationsTab() throws {
7 let settings = try JSONDecoder.devPlace.decode(NotificationSettings.CodingData.self, from: Data(Fixture.settings.utf8)).decoded
8
9 #expect(settings.user.username == "fixtureuser")
10 #expect(!settings.groupingEnabled)
11 #expect(settings.throttlingEnabled)
12 #expect(!settings.telegramPaired)
13 #expect(settings.preferences.count == 2)
14
15 let comments = try #require(settings.preferences.first)
16 #expect(comments.key == "comment")
17 #expect(comments.label == "Comments")
18 #expect(comments.inApp)
19 #expect(comments.push)
20 #expect(!comments.telegram)
21 #expect(!comments.customized)
22 }
23
24 @Test func channelsMatchTheBackendWireValues() {
25 #expect(NotificationChannel.allCases.map(\.rawValue) == ["in_app", "push", "telegram"])
26 }
27 }
28
29 private enum Fixture {
30 static let settings = #"""
31 {
32 "profile_user": {
33 "uid": "01a1dcbb-e4f3-7283-b9e5-6606d3abf6a4",
34 "username": "fixtureuser",
35 "avatar_seed": null,
36 "bio": "",
37 "location": "",
38 "git_link": "",
39 "website": "",
40 "level": 1,
41 "xp": 0,
42 "xp_progress_pct": 0,
43 "xp_next_level": 100,
44 "stars": 0,
45 "created_at": "2026-11-15T01:04:23.796522+00:00",
46 "last_seen": "2026-11-15T01:18:57.645610+00:00"
47 },
48 "notif_grouping_enabled": false,
49 "notif_throttle_enabled": true,
50 "notif_telegram_paired": false,
51 "notification_prefs": [
52 {
53 "key": "comment",
54 "label": "Comments",
55 "description": "Someone comments on your post",
56 "in_app": true,
57 "push": true,
58 "telegram": false,
59 "customized": false
60 },
61 {
62 "key": "reply",
63 "label": "Replies",
64 "description": "Someone replies to your comment",
65 "in_app": true,
66 "push": true,
67 "telegram": false,
68 "customized": false
69 }
70 ]
71 }
72 """#
73 }
DevPlaceSwiftSDK/Tests/DevPlaceSwiftSDKTests/NotificationTypeTests.swift added +40 -0
@@ -0,0 +1,40 @@
1 import Testing
2 @testable import DevPlaceSwiftSDK
3
4 struct NotificationTypeTests {
5 private static let backendTypes = [
6 "comment",
7 "reply",
8 "thread",
9 "mention",
10 "vote",
11 "follow",
12 "message",
13 "badge",
14 "level",
15 "issue",
16 "reminder",
17 "harvest_stolen",
18 "award",
19 "quiz_attempt",
20 "battle",
21 "workspace",
22 "moderation",
23 "system",
24 "ai_quota_warning",
25 "game_upkeep",
26 ]
27
28 @Test(arguments: backendTypes)
29 func decodesBackendType(rawValue: String) {
30 #expect(NotificationType(rawValue: rawValue)?.rawValue == rawValue)
31 }
32
33 @Test func coversExactlyTheBackendTypes() {
34 #expect(Set(NotificationType.allCases.map(\.rawValue)) == Set(Self.backendTypes))
35 }
36
37 @Test func unknownTypeDecodesToNil() {
38 #expect(NotificationType(rawValue: "brand_new_type") == nil)
39 }
40 }
DevPlaceSwiftSDK/Tests/DevPlaceSwiftSDKTests/NotificationsDecodingTests.swift added +248 -0
@@ -0,0 +1,248 @@
1 import Foundation
2 import Testing
3 @testable import DevPlaceSwiftSDK
4
5 struct NotificationsDecodingTests {
6 @Test func decodesGroupedResponse() throws {
7 let notifications = try decode(Fixture.grouped)
8
9 #expect(notifications.grouping)
10 #expect(notifications.nextCursor == nil)
11 #expect(notifications.groups.count == 1)
12
13 let group = try #require(notifications.groups.first)
14 #expect(group.label == "Today")
15 #expect(group.entries.isEmpty)
16 #expect(group.eventEntries.count == 2)
17
18 let votes = try #require(group.eventEntries.first)
19 #expect(votes.key == "vote\u{1F}/posts/grouped-seed")
20 #expect(votes.count == 4)
21 #expect(votes.unread)
22 #expect(votes.actors.map(\.username) == ["actoruser"])
23 #expect(votes.latest.data.type == .vote)
24 #expect(votes.latest.data.message == "voter-0 upvoted your post")
25 #expect(votes.latest.actor?.username == "actoruser")
26 }
27
28 @Test func decodesUngroupedResponse() throws {
29 let notifications = try decode(Fixture.ungrouped)
30
31 #expect(!notifications.grouping)
32
33 let group = try #require(notifications.groups.first)
34 #expect(group.entries.count == 2)
35 #expect(group.eventEntries.isEmpty)
36 #expect(group.entries.first?.data.type == .vote)
37 #expect(group.entries.first?.data.read == false)
38 }
39
40 @Test func keepsNextCursorExactlyAsSent() throws {
41 let json = #"{"notification_groups":[],"next_cursor":"2026-11-14T12:00:00.123456+00:00","grouping":false}"#
42
43 let notifications = try decode(json)
44
45 #expect(notifications.nextCursor == "2026-11-14T12:00:00.123456+00:00")
46 }
47
48 @Test func decodesNotificationCounts() throws {
49 let data = Data(#"{"notifications":3,"messages":0}"#.utf8)
50 let counts = try JSONDecoder.devPlace.decode(NotificationCounts.CodingData.self, from: data).decoded
51
52 #expect(counts == NotificationCounts(notifications: 3, messages: 0))
53 }
54
55 private func decode(_ json: String) throws -> Notifications {
56 try JSONDecoder.devPlace.decode(Notifications.CodingData.self, from: Data(json.utf8)).decoded
57 }
58 }
59
60 private enum Fixture {
61 static let grouped = #"""
62 {
63 "notification_groups": [
64 {
65 "label": "Today",
66 "entries": [],
67 "event_entries": [
68 {
69 "key": "vote\u001f/posts/grouped-seed",
70 "count": 4,
71 "unread": true,
72 "actors": [
73 {
74 "uid": "01a1dcbc-12a0-7bf1-b2e6-64567a59cc51",
75 "username": "actoruser",
76 "avatar_seed": null,
77 "bio": "",
78 "location": "",
79 "git_link": "",
80 "website": "",
81 "level": 1,
82 "xp": 0,
83 "xp_progress_pct": null,
84 "xp_next_level": null,
85 "stars": 0,
86 "created_at": "2026-11-15T01:04:35.490389+00:00",
87 "last_seen": null
88 }
89 ],
90 "latest": {
91 "notification": {
92 "uid": "01a1dcbc-4a09-7de1-aa67-d82553f5a3b9",
93 "type": "vote",
94 "message": "voter-0 upvoted your post",
95 "read": false,
96 "related_uid": "01a1dcbc-12a0-7bf1-b2e6-64567a59cc51",
97 "target_url": "/posts/grouped-seed",
98 "created_at": "2026-11-15T01:03:49.664796+00:00"
99 },
100 "actor": {
101 "uid": "01a1dcbc-12a0-7bf1-b2e6-64567a59cc51",
102 "username": "actoruser",
103 "avatar_seed": null,
104 "bio": "",
105 "location": "",
106 "git_link": "",
107 "website": "",
108 "level": 1,
109 "xp": 0,
110 "xp_progress_pct": null,
111 "xp_next_level": null,
112 "stars": 0,
113 "created_at": "2026-11-15T01:04:35.490389+00:00",
114 "last_seen": null
115 },
116 "time_ago": "1m ago"
117 }
118 },
119 {
120 "key": "comment\u001f01a1dcbc-12a0-7bf1-b2e6-64567a59cc51\u001f/posts/other-post",
121 "count": 2,
122 "unread": true,
123 "actors": [
124 {
125 "uid": "01a1dcbc-12a0-7bf1-b2e6-64567a59cc51",
126 "username": "actoruser",
127 "avatar_seed": null,
128 "bio": "",
129 "location": "",
130 "git_link": "",
131 "website": "",
132 "level": 1,
133 "xp": 0,
134 "xp_progress_pct": null,
135 "xp_next_level": null,
136 "stars": 0,
137 "created_at": "2026-11-15T01:04:35.490389+00:00",
138 "last_seen": null
139 }
140 ],
141 "latest": {
142 "notification": {
143 "uid": "01a1dcbc-4a6c-7e71-8e85-31a4d14d04c7",
144 "type": "comment",
145 "message": "actoruser commented on your post",
146 "read": false,
147 "related_uid": "01a1dcbc-12a0-7bf1-b2e6-64567a59cc51",
148 "target_url": "/posts/other-post",
149 "created_at": "2026-11-15T00:54:49.664796+00:00"
150 },
151 "actor": {
152 "uid": "01a1dcbc-12a0-7bf1-b2e6-64567a59cc51",
153 "username": "actoruser",
154 "avatar_seed": null,
155 "bio": "",
156 "location": "",
157 "git_link": "",
158 "website": "",
159 "level": 1,
160 "xp": 0,
161 "xp_progress_pct": null,
162 "xp_next_level": null,
163 "stars": 0,
164 "created_at": "2026-11-15T01:04:35.490389+00:00",
165 "last_seen": null
166 },
167 "time_ago": "10m ago"
168 }
169 }
170 ]
171 }
172 ],
173 "next_cursor": null,
174 "grouping": true
175 }
176 """#
177
178 static let ungrouped = #"""
179 {
180 "notification_groups": [
181 {
182 "label": "Today",
183 "entries": [
184 {
185 "notification": {
186 "uid": "01a1dcbc-4a09-7de1-aa67-d82553f5a3b9",
187 "type": "vote",
188 "message": "voter-0 upvoted your post",
189 "read": false,
190 "related_uid": "01a1dcbc-12a0-7bf1-b2e6-64567a59cc51",
191 "target_url": "/posts/grouped-seed",
192 "created_at": "2026-11-15T01:03:49.664796+00:00"
193 },
194 "actor": {
195 "uid": "01a1dcbc-12a0-7bf1-b2e6-64567a59cc51",
196 "username": "actoruser",
197 "avatar_seed": null,
198 "bio": "",
199 "location": "",
200 "git_link": "",
201 "website": "",
202 "level": 1,
203 "xp": 0,
204 "xp_progress_pct": null,
205 "xp_next_level": null,
206 "stars": 0,
207 "created_at": "2026-11-15T01:04:35.490389+00:00",
208 "last_seen": null
209 },
210 "time_ago": "1m ago"
211 },
212 {
213 "notification": {
214 "uid": "01a1dcbc-4a6b-7cb1-8602-4c797f6911bb",
215 "type": "vote",
216 "message": "voter-1 upvoted your post",
217 "read": false,
218 "related_uid": "01a1dcbc-12a0-7bf1-b2e6-64567a59cc51",
219 "target_url": "/posts/grouped-seed",
220 "created_at": "2026-11-15T01:02:49.664796+00:00"
221 },
222 "actor": {
223 "uid": "01a1dcbc-12a0-7bf1-b2e6-64567a59cc51",
224 "username": "actoruser",
225 "avatar_seed": null,
226 "bio": "",
227 "location": "",
228 "git_link": "",
229 "website": "",
230 "level": 1,
231 "xp": 0,
232 "xp_progress_pct": null,
233 "xp_next_level": null,
234 "stars": 0,
235 "created_at": "2026-11-15T01:04:35.490389+00:00",
236 "last_seen": null
237 },
238 "time_ago": "2m ago"
239 }
240 ],
241 "event_entries": []
242 }
243 ],
244 "next_cursor": null,
245 "grouping": false
246 }
247 """#
248 }
README.md modified +3 -0
@@ -44,6 +44,9 @@ The main features are done:
44 44 * attachments
45 45 * editing comments
46 46 * notifications
47 * grouped or one per event, following the profile setting
48 * opening the related post, conversation or web page, also from a push notification
49 * settings for grouping, throttled alerts and in-app, push and Telegram delivery per notification type
47 50 * private messages
48 51
49 52 Other less frequently used features like editing own profile will be implemented later eventually.
208.1ms