-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPushNotificationService.swift
More file actions
202 lines (161 loc) · 7 KB
/
PushNotificationService.swift
File metadata and controls
202 lines (161 loc) · 7 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
//
// PushNotificationService.swift
// DevLog
//
// Created by opfic on 7/10/25.
//
import FirebaseAuth
import FirebaseFirestore
final class PushNotificationService {
private let store = Firestore.firestore()
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("users/\(uid)/userData/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 {
guard let uid = Auth.auth().currentUser?.uid else {
throw AuthError.notAuthenticated
}
let settingsRef = store.document("users/\(uid)/userData/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)
}
/// 푸시 알림 설정 업데이트
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("users/\(uid)/userData/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(
_ query: PushNotificationQuery,
cursor: PushNotificationCursorDTO?
) async throws -> PushNotificationPageResponse {
guard let uid = Auth.auth().currentUser?.uid else { throw AuthError.notAuthenticated }
var firestoreQuery: Query = store.collection("users/\(uid)/notifications")
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
firestoreQuery = firestoreQuery
.order(by: "receivedAt", descending: isDescending)
.order(by: FieldPath.documentID())
if let cursor {
firestoreQuery = firestoreQuery.start(after: [
Timestamp(date: cursor.receivedAt),
cursor.documentID
])
}
let snapshot = try await firestoreQuery
.limit(to: query.pageSize)
.getDocuments()
let items = snapshot.documents.compactMap { makeResponse(from: $0) }
let nextCursor: PushNotificationCursorDTO? = snapshot.documents.last.map { document in
guard let receivedAt = document.data()["receivedAt"] as? Timestamp else {
return nil
}
return PushNotificationCursorDTO(
receivedAt: receivedAt.dateValue(),
documentID: document.documentID
)
} ?? nil
return PushNotificationPageResponse(items: items, nextCursor: nextCursor)
}
/// 푸시 알림 기록 삭제
func deleteNotification(_ notificationID: String) async throws {
guard let uid = Auth.auth().currentUser?.uid else { throw AuthError.notAuthenticated }
let docRef = store.collection("users/\(uid)/notifications").document(notificationID)
try await docRef.delete()
}
/// 푸시 알림 읽음/안읽음 토글
func toggleNotificationRead(_ todoID: String) async throws {
logger.info("Toggling notification read for todoID: \(todoID)")
guard let uid = Auth.auth().currentUser?.uid else {
logger.error("User not authenticated")
throw AuthError.notAuthenticated
}
let collection = store.collection("users/\(uid)/notifications")
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")
}
}
private extension PushNotificationService {
func makeResponse(from snapshot: QueryDocumentSnapshot) -> PushNotificationResponse? {
let data = snapshot.data()
guard
let title = data["title"] as? String,
let body = data["body"] as? String,
let receivedAt = data["receivedAt"] as? Timestamp,
let isRead = data["isRead"] as? Bool,
let todoID = data["todoID"] as? String,
let todoKind = data["todoKind"] as? String else {
return nil
}
return PushNotificationResponse(
id: snapshot.documentID,
title: title,
body: body,
receivedAt: receivedAt.dateValue(),
isRead: isRead,
todoID: todoID,
todoKind: todoKind
)
}
}