summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/View controllers/Settings/Obfuscation/TunnelObfuscationSettingsWatchingObservableObject.swift
blob: 36be024d85c5173f9bdfb50d4299fc50e54193cb (plain)
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
//
//  TunnelObfuscationSettingsWatchingObservableObject.swift
//  MullvadVPN
//
//  Created by Andrew Bulhak on 2024-11-07.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import Foundation
import MullvadSettings

/// a generic ObservableObject that binds to obfuscation settings in TunnelManager.
/// Used as the basis for ViewModels for SwiftUI interfaces for these settings.

class TunnelObfuscationSettingsWatchingObservableObject<T: Equatable>: ObservableObject {
    let tunnelManager: TunnelManager
    let keyPath: WritableKeyPath<WireGuardObfuscationSettings, T>
    private var tunnelObserver: TunnelObserver?

    @Published var value: T

    init(tunnelManager: TunnelManager, keyPath: WritableKeyPath<WireGuardObfuscationSettings, T>) {
        self.tunnelManager = tunnelManager
        self.keyPath = keyPath
        self.value = tunnelManager.settings.wireGuardObfuscation[keyPath: keyPath]
        tunnelObserver =
            TunnelBlockObserver(didUpdateTunnelSettings: { [weak self] _, newSettings in
                guard let self else { return }
                updateValueFromSettings(newSettings.wireGuardObfuscation)
            })
    }

    private func updateValueFromSettings(_ settings: WireGuardObfuscationSettings) {
        let newValue = settings[keyPath: keyPath]
        if value != newValue {
            value = newValue
        }
    }

    // Commit the temporarily stored value upstream
    func commit() {
        var obfuscationSettings = tunnelManager.settings.wireGuardObfuscation
        obfuscationSettings[keyPath: keyPath] = value
        tunnelManager.updateSettings([.obfuscation(obfuscationSettings)])
    }
}