VPNAction.swift 2.02 KB
Newer Older
Davide De Rosa's avatar
Davide De Rosa committed
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
//
//  VPNAction.swift
//  PIALibrary
//
//  Created by Davide De Rosa on 12/24/17.
//  Copyright © 2017 London Trust Media. All rights reserved.
//

import Foundation

/// Command pattern for prioritized and descriptive VPN operations.
public protocol VPNAction {

    /// The priority to order this action against.
    var priority: Int { get }

    /// If `true`, this action doesn't require the VPN to be restarted.
    var canRetainConnection: Bool { get }
    
    /**
     Executes the action and potentially kills the active VPN connection.

     - Parameter callback: Returns `nil` on success.
     - Seealso: `canRetainConnection`
     */
    func execute(_ callback: SuccessLibraryCallback?)
}

class VPNActionReconnect: VPNAction, ProvidersAccess {
    let priority = 10
    
    let canRetainConnection = true
    
    func execute(_ callback: SuccessLibraryCallback?) {
        let vpn = accessedProviders.vpnProvider
        guard (vpn.vpnStatus != .disconnected) else {
            callback?(nil)
            return
        }
        vpn.reconnect(after: nil, callback)
    }
}

class VPNActionReinstall: VPNAction, ProvidersAccess {
    let priority = 20

    let canRetainConnection = true

    func execute(_ callback: SuccessLibraryCallback?) {
        let vpn = accessedProviders.vpnProvider
51
        vpn.install(force: true, { (error) in
Davide De Rosa's avatar
Davide De Rosa committed
52 53 54 55 56
            if let _ = error {
                callback?(error)
                return
            }
            callback?(nil)
57
        })
Davide De Rosa's avatar
Davide De Rosa committed
58 59 60 61 62 63 64 65 66 67
    }
}

class VPNActionDisconnectAndReinstall: VPNAction, ProvidersAccess {
    let priority = 30
    
    let canRetainConnection = false

    func execute(_ callback: SuccessLibraryCallback?) {
        let vpn = accessedProviders.vpnProvider
68
        vpn.install(force: true, { (error) in
Davide De Rosa's avatar
Davide De Rosa committed
69 70 71 72 73 74 75 76
            if let _ = error {
                callback?(error)
                return
            }
            guard (vpn.vpnStatus != .disconnected) else {
                callback?(nil)
                return
            }
77
            vpn.connect(callback)
78
        })
Davide De Rosa's avatar
Davide De Rosa committed
79 80
    }
}