This repository has been archived by the owner on Jun 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 439
/
PushManager.swift
202 lines (169 loc) · 6.53 KB
/
PushManager.swift
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
//
// PushManager.swift
// Rocket.Chat
//
// Created by Gradler Kim on 2017. 1. 23..
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
import UserNotifications
final class PushManager {
static let delegate = UserNotificationCenterDelegate()
static let kDeviceTokenKey = "deviceToken"
static let kPushIdentifierKey = "pushIdentifier"
static func updatePushToken() {
guard let deviceToken = getDeviceToken() else { return }
guard let userIdentifier = AuthManager.isAuthenticated()?.userId else { return }
let request = [
"msg": "method",
"method": "raix:push-update",
"params": [[
"id": getOrCreatePushId(),
"userId": userIdentifier,
"token": ["apn": deviceToken],
"appName": Bundle.main.bundleIdentifier ?? "main",
"metadata": [:]
]]
] as [String: Any]
SocketManager.send(request)
}
static func updateUser(_ userIdentifier: String) {
let request = [
"msg": "method",
"method": "raix:push-setuser",
"userId": userIdentifier,
"params": [getOrCreatePushId()]
] as [String: Any]
SocketManager.send(request)
}
fileprivate static func getOrCreatePushId() -> String {
guard let pushId = UserDefaults.group.string(forKey: kPushIdentifierKey) else {
let randomId = UUID().uuidString.replacingOccurrences(of: "-", with: "")
UserDefaults.group.set(randomId, forKey: kPushIdentifierKey)
return randomId
}
return pushId
}
static func getDeviceToken() -> String? {
guard let deviceToken = UserDefaults.group.string(forKey: kDeviceTokenKey) else {
return nil
}
return deviceToken
}
}
// MARK: Handle Notifications
struct PushNotification {
let host: URL
let username: String
let roomId: String
let roomType: SubscriptionType
init?(raw: [AnyHashable: Any]) {
guard
let json = JSON(parseJSON: (raw["ejson"] as? String) ?? "").dictionary,
let hostString = json["host"]?.string,
let host = URL(string: hostString),
let username = json["sender"]?["username"].string,
let roomType = json["type"]?.string,
let roomId = json["rid"]?.string
else {
return nil
}
self.host = host
self.username = username
self.roomId = roomId
self.roomType = SubscriptionType(rawValue: roomType) ?? .group
}
}
// MARK: Categories
extension UNNotificationAction {
static var reply: UNNotificationAction {
return UNTextInputNotificationAction(
identifier: "REPLY",
title: localized("notifications.action.reply"),
options: .authenticationRequired
)
}
}
extension UNNotificationCategory {
static var message: UNNotificationCategory {
return UNNotificationCategory(
identifier: "MESSAGE",
actions: [.reply],
intentIdentifiers: [],
options: []
)
}
static var messageNoReply: UNNotificationCategory {
return UNNotificationCategory(
identifier: "REPLY",
actions: [.reply],
intentIdentifiers: [],
options: []
)
}
}
extension PushManager {
static func setupNotificationCenter() {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = PushManager.delegate
notificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { (_, _) in }
notificationCenter.setNotificationCategories([.message, .messageNoReply])
}
@discardableResult
static func handleNotification(raw: [AnyHashable: Any], reply: String? = nil) -> Bool {
guard let notification = PushNotification(raw: raw) else { return false }
return handleNotification(notification, reply: reply)
}
@discardableResult
static func handleNotification(_ notification: PushNotification, reply: String? = nil) -> Bool {
guard let index = DatabaseManager.serverIndexForUrl(notification.host) else {
return false
}
// side effect: needed for Subscription.notificationSubscription()
AppManager.initialRoomId = notification.roomId
if index != DatabaseManager.selectedIndex {
AppManager.changeSelectedServer(index: index)
} else {
if let auth = AuthManager.isAuthenticated() {
let openSubscription = MainSplitViewController.chatViewController?.subscription
if let subscription = Subscription.notificationSubscription(auth: auth), subscription != openSubscription {
AppManager.open(room: subscription, animated: false)
}
}
}
guard let realm = DatabaseManager.databaseInstace(index: index) else {
return false
}
if let reply = reply {
let appendage = notification.roomType == .directMessage ? "" : " @\(notification.username)"
let message = "\(reply)\(appendage)"
let backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
API.current(realm: realm)?.fetch(PostMessageRequest(roomId: notification.roomId, text: message)) { response in
switch response {
case .resource:
UIApplication.shared.endBackgroundTask(backgroundTask)
case .error:
Alert.defaultError.present()
}
}
}
return true
}
}
final class UserNotificationCenterDelegate: NSObject, UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if SocketManager.isConnected() {
completionHandler([])
return
}
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
PushManager.handleNotification(
raw: response.notification.request.content.userInfo,
reply: (response as? UNTextInputNotificationResponse)?.userText
)
}
}