Move device token sending logic to its own component

This commit moves the device token logic to a new
PushNotificationClient, to move complexity from this specific feature
away from damusApp.swift

This commit also slightly improves the handling of device tokens, by
caching it on the client struct even if the user is using local
notifications, so that the device token can be sent to the server immediately after
switching to push notifications mode.

Signed-off-by: Daniel D’Aquino <daniel@daquino.me>
Reviewed-by: William Casarin <jb55@jb55.com>
This commit is contained in:
Daniel D’Aquino
2024-05-17 16:20:41 -07:00
parent 0a9bcb6189
commit b148fb735e
5 changed files with 73 additions and 45 deletions

View File

@@ -36,6 +36,7 @@ class DamusState: HeadlessDamusState {
let video: VideoController
let ndb: Ndb
var purple: DamusPurple
var push_notification_client: PushNotificationClient
init(pool: RelayPool, keypair: Keypair, likes: EventCounter, boosts: EventCounter, contacts: Contacts, mutelist_manager: MutelistManager, profiles: Profiles, dms: DirectMessagesModel, previews: PreviewCache, zaps: Zaps, lnurls: LNUrls, settings: UserSettingsStore, relay_filters: RelayFilters, relay_model_cache: RelayModelCache, drafts: Drafts, events: EventCache, bookmarks: BookmarksManager, postbox: PostBox, bootstrap_relays: [RelayURL], replies: ReplyCounter, wallet: WalletModel, nav: NavigationCoordinator, music: MusicController?, video: VideoController, ndb: Ndb, purple: DamusPurple? = nil, quote_reposts: EventCounter) {
self.pool = pool
@@ -68,6 +69,7 @@ class DamusState: HeadlessDamusState {
keypair: keypair
)
self.quote_reposts = quote_reposts
self.push_notification_client = PushNotificationClient(keypair: keypair, settings: settings)
}
@discardableResult

View File

@@ -0,0 +1,62 @@
//
// PushNotificationClient.swift
// damus
//
// Created by Daniel DAquino on 2024-05-17.
//
import Foundation
struct PushNotificationClient {
let keypair: Keypair
let settings: UserSettingsStore
private(set) var device_token: Data? = nil
mutating func set_device_token(new_device_token: Data) async throws {
self.device_token = new_device_token
if settings.enable_experimental_push_notifications && settings.notifications_mode == .push {
try await self.send_token()
}
}
func send_token() async throws {
guard let device_token else { return }
// Send the device token and pubkey to the server
let token = device_token.map { String(format: "%02.2hhx", $0) }.joined()
Log.info("Sending device token to server: %s", for: .push_notifications, token)
let pubkey = self.keypair.pubkey
// Send those as JSON to the server
let json: [String: Any] = ["deviceToken": token, "pubkey": pubkey.hex()]
// create post request
let url = self.settings.send_device_token_to_localhost ? Constants.DEVICE_TOKEN_RECEIVER_TEST_URL : Constants.DEVICE_TOKEN_RECEIVER_PRODUCTION_URL
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = try? JSONSerialization.data(withJSONObject: json, options: [])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
if let response = response as? HTTPURLResponse, !(200...299).contains(response.statusCode) {
print("Unexpected status code: \(response.statusCode)")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()
}
}