aboutsummaryrefslogtreecommitdiffstats
path: root/Sources/WireguardAppIntents/GetPeers.swift
blob: 00e539910eab35ec424c92b4bc295247b655698b (plain) (blame)
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
// SPDX-License-Identifier: MIT
// Copyright © 2018-2021 WireGuard LLC. All Rights Reserved.

import Foundation
import AppIntents

@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *)
struct GetPeers: AppIntent {

    static var title = LocalizedStringResource("getPeersIntentName", table: "AppIntents")
    static var description = IntentDescription(
        LocalizedStringResource("getPeersIntentDescription", table: "AppIntents")
    )

    @Parameter(
        title: LocalizedStringResource("getPeersIntentTunnelParameterTitle", table: "AppIntents"),
        optionsProvider: TunnelsOptionsProvider()
    )
    var tunnelName: String

    @Dependency
    var tunnelsManager: TunnelsManager

    func perform() async throws -> some IntentResult & ReturnsValue<[String]> {
        guard let tunnelContainer = tunnelsManager.tunnel(named: tunnelName) else {
            throw GetPeersIntentError.wrongTunnel(name: tunnelName)
        }

        guard let tunnelConfiguration = tunnelContainer.tunnelConfiguration else {
            throw GetPeersIntentError.missingConfiguration
        }

        let publicKeys = tunnelConfiguration.peers.map { $0.publicKey.base64Key }
        return .result(value: publicKeys)
    }

    static var parameterSummary: some ParameterSummary {
        Summary("getPeersIntentSummary \(\.$tunnelName)", table: "AppIntents")
    }
}

@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *)
enum GetPeersIntentError: Swift.Error, CustomLocalizedStringResourceConvertible {
    case wrongTunnel(name: String)
    case missingConfiguration

    var localizedStringResource: LocalizedStringResource {
        switch self {
        case .wrongTunnel(let name):
            return LocalizedStringResource("wireguardAppIntentsWrongTunnelError \(name)", table: "AppIntents")
        case .missingConfiguration:
            return LocalizedStringResource("wireguardAppIntentsMissingConfigurationError", table: "AppIntents")
        }
    }
}