summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/TunnelManager/UpdateAccountDataOperation.swift
blob: 0e06dbfb6f44922f7844fdc6e9d83e21371a3da0 (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
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
//
//  UpdateAccountDataOperation.swift
//  MullvadVPN
//
//  Created by pronebird on 12/05/2022.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import Foundation
import MullvadLogging
import MullvadREST
import MullvadSettings
import MullvadTypes
import Operations

class UpdateAccountDataOperation: ResultOperation<Void>, @unchecked Sendable {
    private let logger = Logger(label: "UpdateAccountDataOperation")
    private let interactor: TunnelInteractor
    private let accountsProxy: RESTAccountHandling
    private var task: Cancellable?

    init(
        dispatchQueue: DispatchQueue,
        interactor: TunnelInteractor,
        accountsProxy: RESTAccountHandling
    ) {
        self.interactor = interactor
        self.accountsProxy = accountsProxy

        super.init(dispatchQueue: dispatchQueue)
    }

    override func main() {
        guard case let .loggedIn(accountData, _) = interactor.deviceState else {
            finish(result: .failure(InvalidDeviceStateError()))
            return
        }

        task = accountsProxy.getAccountData(
            accountNumber: accountData.number,
            retryStrategy: .default,
            completion: { result in
                self.dispatchQueue.async {
                    self.didReceiveAccountData(result: result)
                }
            }
        )
    }

    override func operationDidCancel() {
        task?.cancel()
        task = nil
    }

    private func didReceiveAccountData(result: Result<Account, Error>) {
        let result = result.inspectError { error in
            guard !error.isOperationCancellationError else { return }

            self.logger.error(
                error: error,
                message: "Failed to fetch account expiry."
            )
        }.tryMap { accountData in
            switch interactor.deviceState {
            case .loggedIn(var storedAccountData, let storedDeviceData):
                storedAccountData.expiry = accountData.expiry

                let newDeviceState = DeviceState.loggedIn(storedAccountData, storedDeviceData)

                interactor.setDeviceState(newDeviceState, persist: true)

            default:
                throw InvalidDeviceStateError()
            }
        }

        finish(result: result)
    }
}