aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuard/WireGuard/ZipArchive/ZipExporter.swift
blob: f875e1b83e9de184d222a2c8b0b4bd0768b3a3a7 (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
// SPDX-License-Identifier: MIT
// Copyright © 2018 WireGuard LLC. All Rights Reserved.

import UIKit

enum ZipExporterError: WireGuardAppError {
    case noTunnelsToExport

    func alertText() -> (String, String)? {
        switch (self) {
        case .noTunnelsToExport:
            return ("Nothing to export", "There are no tunnels to export")
        }
    }
}

class ZipExporter {
    static func exportConfigFiles(tunnelConfigurations: [TunnelConfiguration], to url: URL,
                                  completion: @escaping (WireGuardAppError?) -> Void) {

        guard (!tunnelConfigurations.isEmpty) else {
            completion(ZipExporterError.noTunnelsToExport)
            return
        }
        DispatchQueue.global(qos: .userInitiated).async {
            var inputsToArchiver: [(fileName: String, contents: Data)] = []
            var lastTunnelName: String = ""
            for tunnelConfiguration in tunnelConfigurations {
                if let contents = WgQuickConfigFileWriter.writeConfigFile(from: tunnelConfiguration) {
                    let name = tunnelConfiguration.interface.name
                    if (name.isEmpty || name == lastTunnelName) { continue }
                    inputsToArchiver.append((fileName: "\(name).conf", contents: contents))
                    lastTunnelName = name
                }
            }
            do {
                try ZipArchive.archive(inputs: inputsToArchiver, to: url)
            } catch (let error as WireGuardAppError) {
                DispatchQueue.main.async { completion(error) }
                return
            } catch {
                fatalError()
            }
            DispatchQueue.main.async { completion(nil) }
        }
    }
}