-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPushNotificationService.swift
More file actions
334 lines (277 loc) · 11.9 KB
/
PushNotificationService.swift
File metadata and controls
334 lines (277 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//
// PushNotificationService.swift
// DevLog
//
// Created by opfic on 7/10/25.
//
import FirebaseAuth
import Combine
import FirebaseFirestore
import FirebaseFunctions
final class PushNotificationService {
private enum FunctionName: String {
case requestPushNotificationDeletion
case undoPushNotificationDeletion
}
private let store = Firestore.firestore()
private let functions = Functions.functions(region: "asia-northeast3")
private let logger = Logger(category: "PushNotificationService")
/// 푸시 알림 On/Off 설정
func fetchPushNotificationEnabled() async throws -> Bool {
logger.info("Fetching push notification enabled status")
guard let uid = Auth.auth().currentUser?.uid else {
logger.error("User not authenticated")
throw AuthError.notAuthenticated
}
do {
let settingsRef = store.document(FirestorePath.userData(uid, document: .settings))
let doc = try await settingsRef.getDocument()
if let allowPush = doc.data()?["allowPushNotification"] as? Bool {
logger.info("Push notification enabled: \(allowPush)")
return allowPush
}
logger.error("Push notification setting not found")
throw FirestoreError.dataNotFound("allowPushNotification")
} catch {
logger.error("Failed to fetch push notification status", error: error)
throw error
}
}
/// 푸시 알림 시간 설정
func fetchPushNotificationTime() async throws -> DateComponents {
logger.info("Fetching push notification time")
guard let uid = Auth.auth().currentUser?.uid else {
logger.error("User not authenticated")
throw AuthError.notAuthenticated
}
do {
let settingsRef = store.document(FirestorePath.userData(uid, document: .settings))
let doc = try await settingsRef.getDocument()
guard let hour = doc.data()?["pushNotificationHour"] as? Int else {
throw FirestoreError.dataNotFound("pushNotificationHour")
}
guard let minute = doc.data()?["pushNotificationMinute"] as? Int else {
throw FirestoreError.dataNotFound("pushNotificationMinute")
}
return DateComponents(hour: hour, minute: minute)
} catch {
logger.error("Failed to fetch push notification time", error: error)
throw error
}
}
/// 푸시 알림 설정 업데이트
func updatePushNotificationSettings(isEnabled: Bool, components: DateComponents) async throws {
logger.info("Updating push notification settings - enabled: \(isEnabled)")
guard let uid = Auth.auth().currentUser?.uid else {
logger.error("User not authenticated")
throw AuthError.notAuthenticated
}
do {
let settingsRef = store.document(FirestorePath.userData(uid, document: .settings))
var dict: [String: Any] = ["allowPushNotification": isEnabled]
if let hour = components.hour {
dict["pushNotificationHour"] = hour
}
if let minute = components.minute {
dict["pushNotificationMinute"] = minute
}
try await settingsRef.setData(dict, merge: true)
logger.info("Successfully updated push notification settings")
} catch {
logger.error("Failed to update push notification settings", error: error)
throw error
}
}
/// 푸시 알림 기록 요청
func requestNotifications(
_ notificationQuery: PushNotificationQuery,
cursor: PushNotificationCursorDTO?
) async throws -> PushNotificationPageResponse {
do {
guard let uid = Auth.auth().currentUser?.uid else { throw AuthError.notAuthenticated }
var firestoreQuery = makeQuery(uid: uid, query: notificationQuery)
if let cursor {
firestoreQuery = firestoreQuery.start(after: [
Timestamp(date: cursor.receivedAt),
cursor.documentID
])
}
let snapshot = try await firestoreQuery
.limit(to: notificationQuery.pageSize)
.getDocuments()
let items = snapshot.documents.compactMap { makeResponse(from: $0) }
let nextCursor: PushNotificationCursorDTO? = snapshot.documents.last.map { document in
guard let receivedAt = document.data()[Key.receivedAt.rawValue] as? Timestamp else {
return nil
}
return PushNotificationCursorDTO(
receivedAt: receivedAt.dateValue(),
documentID: document.documentID
)
} ?? nil
return PushNotificationPageResponse(items: items, nextCursor: nextCursor)
} catch {
logger.error("Failed to request notifications", error: error)
throw error
}
}
func observeNotifications(
_ query: PushNotificationQuery,
limit: Int
) throws -> AnyPublisher<PushNotificationPageResponse, Error> {
guard let uid = Auth.auth().currentUser?.uid else { throw AuthError.notAuthenticated }
let subject = PassthroughSubject<PushNotificationPageResponse, Error>()
let pageLimit = max(query.pageSize, limit)
let listener = makeQuery(uid: uid, query: query)
.limit(to: pageLimit)
.addSnapshotListener { [weak self] snapshot, error in
if let error {
subject.send(completion: .failure(error))
return
}
guard let self, let snapshot else { return }
let items = snapshot.documents.compactMap { self.makeResponse(from: $0) }
let nextCursor = self.makeNextCursor(from: snapshot.documents.last)
subject.send(
PushNotificationPageResponse(
items: items,
nextCursor: nextCursor
)
)
}
return subject
.handleEvents(receiveCancel: { listener.remove() })
.eraseToAnyPublisher()
}
func observeUnreadPushCount() throws -> AnyPublisher<Int, Error> {
guard let uid = Auth.auth().currentUser?.uid else { throw AuthError.notAuthenticated }
let subject = PassthroughSubject<Int, Error>()
let listener = store.collection(FirestorePath.notifications(uid))
.whereField("isRead", isEqualTo: false)
.addSnapshotListener { snapshot, error in
if let error {
subject.send(completion: .failure(error))
return
}
guard let snapshot else { return }
let unreadPushCount = snapshot.documents.filter { document in
!(document.data()[Key.deletingAt.rawValue] is Timestamp)
}.count
subject.send(unreadPushCount)
}
return subject
.handleEvents(receiveCancel: { listener.remove() })
.eraseToAnyPublisher()
}
/// 푸시 알림 기록 삭제
func deleteNotification(_ notificationID: String) async throws {
do {
guard Auth.auth().currentUser?.uid != nil else { throw AuthError.notAuthenticated }
let function = functions.httpsCallable(FunctionName.requestPushNotificationDeletion)
_ = try await function.call(["notificationId": notificationID])
} catch {
logger.error("Failed to request notification deletion", error: error)
throw error
}
}
func undoDeleteNotification(_ notificationID: String) async throws {
do {
guard Auth.auth().currentUser?.uid != nil else { throw AuthError.notAuthenticated }
let function = functions.httpsCallable(FunctionName.undoPushNotificationDeletion)
_ = try await function.call(["notificationId": notificationID])
} catch {
logger.error("Failed to undo notification deletion", error: error)
throw error
}
}
/// 푸시 알림 읽음/안읽음 토글
func toggleNotificationRead(_ todoId: String) async throws {
logger.info("Toggling notification read for todoId: \(todoId)")
do {
guard let uid = Auth.auth().currentUser?.uid else {
logger.error("User not authenticated")
throw AuthError.notAuthenticated
}
let collection = store.collection(FirestorePath.notifications(uid))
let snapshot = try await collection.whereField("todoId", isEqualTo: todoId).getDocuments()
guard let document = snapshot.documents.first else {
logger.error("Notification not found for todoId: \(todoId)")
throw FirestoreError.dataNotFound("notification")
}
guard let currentValue = document.data()["isRead"] as? Bool else {
logger.error("isRead not found for notification: \(document.documentID)")
throw FirestoreError.dataNotFound("isRead")
}
try await document.reference.updateData(["isRead": !currentValue])
logger.info("Successfully toggled notification read")
} catch {
logger.error("Failed to toggle notification read", error: error)
throw error
}
}
}
private extension PushNotificationService {
func makeQuery(
uid: String,
query: PushNotificationQuery
) -> Query {
var firestoreQuery: Query = store.collection(FirestorePath.notifications(uid))
if let thresholdDate = query.timeFilter.thresholdDate {
firestoreQuery = firestoreQuery.whereField(
"receivedAt",
isGreaterThanOrEqualTo: Timestamp(date: thresholdDate)
)
}
if query.unreadOnly {
firestoreQuery = firestoreQuery.whereField("isRead", isEqualTo: false)
}
let isDescending = query.sortOrder == .latest
return firestoreQuery
.order(by: "receivedAt", descending: isDescending)
.order(by: FieldPath.documentID())
}
func makeNextCursor(from document: QueryDocumentSnapshot?) -> PushNotificationCursorDTO? {
guard
let document,
let receivedAt = document.data()[Key.receivedAt.rawValue] as? Timestamp else {
return nil
}
return PushNotificationCursorDTO(
receivedAt: receivedAt.dateValue(),
documentID: document.documentID
)
}
func makeResponse(from snapshot: QueryDocumentSnapshot) -> PushNotificationResponse? {
let data = snapshot.data()
if data[Key.deletingAt.rawValue] is Timestamp {
return nil
}
guard
let title = data[Key.title.rawValue] as? String,
let body = data[Key.body.rawValue] as? String,
let receivedAt = data[Key.receivedAt.rawValue] as? Timestamp,
let isRead = data[Key.isRead.rawValue] as? Bool,
let todoId = data[Key.todoId.rawValue] as? String,
let todoKind = data[Key.todoKind.rawValue] as? String else {
return nil
}
return PushNotificationResponse(
id: snapshot.documentID,
title: title,
body: body,
receivedAt: receivedAt.dateValue(),
isRead: isRead,
todoId: todoId,
todoKind: todoKind
)
}
enum Key: String {
case title
case body
case receivedAt
case isRead
case todoId
case todoKind
case deletingAt // 삭제 요청은 되었지만, 5초 유예 후 최종 삭제되기 전 상태
}
}