tokenary/Encrypted Ink/Services/SessionStorage.swift

72 lines
2.4 KiB
Swift
Raw Normal View History

2021-07-10 22:41:53 +03:00
// Copyright © 2021 Encrypted Ink. All rights reserved.
import Foundation
2021-07-10 22:54:55 +03:00
import WalletConnect
2021-07-10 22:41:53 +03:00
class SessionStorage {
2021-07-10 22:54:55 +03:00
struct Item: Codable {
let session: WCSession
2021-08-06 18:58:32 +03:00
let chainId: Int?
2021-08-01 19:42:27 +03:00
let walletId: String
2021-07-11 15:07:40 +03:00
let clientId: String
2021-07-11 14:41:04 +03:00
let sessionDetails: WCSessionRequestParam
2021-07-10 22:54:55 +03:00
}
2021-07-10 22:41:53 +03:00
static let shared = SessionStorage()
private init() {}
2021-07-10 22:54:55 +03:00
func loadAll() -> [Item] {
2021-07-11 17:38:24 +03:00
var items = Array(Defaults.storedSessions.values)
2021-07-11 16:34:25 +03:00
let wcItems = WCSessionStore.allSessions
2021-07-11 17:38:24 +03:00
let latestInteractionDates = Defaults.latestInteractionDates
let now = Date()
let oldnessThreshold: Double = 60 * 60 * 24 * 60 // 60 days
items = items.filter { item -> Bool in
guard let date = latestInteractionDates[item.clientId], now.timeIntervalSince(date) < oldnessThreshold else {
remove(clientId: item.clientId)
return false
}
if wcItems[item.session.topic] == nil {
WCSessionStore.store(item.session, peerId: item.sessionDetails.peerId, peerMeta: item.sessionDetails.peerMeta)
}
return true
2021-07-11 16:34:25 +03:00
}
2021-07-11 17:38:24 +03:00
2021-07-11 16:34:25 +03:00
return items
2021-07-10 22:54:55 +03:00
}
2021-07-11 15:07:40 +03:00
func removeAll() {
2021-07-11 17:05:20 +03:00
Defaults.storedSessions = [:]
2021-07-11 17:42:43 +03:00
Defaults.latestInteractionDates = [:]
2021-07-11 17:05:20 +03:00
}
func remove(clientId: String) {
2021-07-11 17:38:24 +03:00
Defaults.latestInteractionDates.removeValue(forKey: clientId)
2021-07-11 17:05:20 +03:00
if let item = Defaults.storedSessions.removeValue(forKey: clientId) {
WCSessionStore.clear(item.session.topic)
}
2021-07-11 15:07:40 +03:00
}
2021-08-06 18:58:32 +03:00
func add(interactor: WCInteractor, chainId: Int, walletId: String, sessionDetails: WCSessionRequestParam) {
let item = Item(session: interactor.session, chainId: chainId, walletId: walletId, clientId: interactor.clientId, sessionDetails: sessionDetails)
2021-07-11 15:26:41 +03:00
WCSessionStore.store(interactor.session, peerId: sessionDetails.peerId, peerMeta: sessionDetails.peerMeta)
2021-07-11 17:05:20 +03:00
Defaults.storedSessions[interactor.clientId] = item
2021-07-11 17:23:15 +03:00
didInteractWith(clientId: interactor.clientId)
}
func didInteractWith(clientId: String?) {
guard let clientId = clientId else { return }
Defaults.latestInteractionDates[clientId] = Date()
2021-07-10 22:54:55 +03:00
}
func shouldReconnect(interactor: WCInteractor) -> Bool {
return WCSessionStore.load(interactor.session.topic) != nil
}
2021-07-10 22:41:53 +03:00
}