aboutsummaryrefslogtreecommitdiffstats
path: root/Sources/WireGuardApp/UI/iOS/ViewController/SSIDOptionEditTableViewController.swift
blob: 256ff1c08433f100dae2989e8e8322abe3c596b5 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// SPDX-License-Identifier: MIT
// Copyright © 2018-2020 WireGuard LLC. All Rights Reserved.

import UIKit
import SystemConfiguration.CaptiveNetwork
import NetworkExtension

protocol SSIDOptionEditTableViewControllerDelegate: class {
    func ssidOptionSaved(option: ActivateOnDemandViewModel.OnDemandSSIDOption, ssids: [String])
}

class SSIDOptionEditTableViewController: UITableViewController {
    private enum Section {
        case ssidOption
        case selectedSSIDs
        case addSSIDs
    }

    private enum AddSSIDRow {
        case addConnectedSSID(connectedSSID: String)
        case addNewSSID
    }

    weak var delegate: SSIDOptionEditTableViewControllerDelegate?

    private var sections = [Section]()
    private var addSSIDRows = [AddSSIDRow]()

    let ssidOptionFields: [ActivateOnDemandViewModel.OnDemandSSIDOption] = [
        .anySSID,
        .onlySpecificSSIDs,
        .exceptSpecificSSIDs
    ]

    var selectedOption: ActivateOnDemandViewModel.OnDemandSSIDOption
    var selectedSSIDs: [String]
    var connectedSSID: String?

    init(option: ActivateOnDemandViewModel.OnDemandSSIDOption, ssids: [String]) {
        selectedOption = option
        selectedSSIDs = ssids
        super.init(style: .grouped)
        loadSections()
        addSSIDRows.removeAll()
        addSSIDRows.append(.addNewSSID)

        getConnectedSSID { [weak self] ssid in
            guard let self = self else { return }
            self.connectedSSID = ssid
            self.updateCurrentSSIDEntry()
            self.updateTableViewAddSSIDRows()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = tr("tunnelOnDemandSSIDViewTitle")

        tableView.estimatedRowHeight = 44
        tableView.rowHeight = UITableView.automaticDimension

        tableView.register(CheckmarkCell.self)
        tableView.register(EditableTextCell.self)
        tableView.register(TextCell.self)
        tableView.isEditing = true
        tableView.allowsSelectionDuringEditing = true
        tableView.keyboardDismissMode = .onDrag
    }

    func loadSections() {
        sections.removeAll()
        sections.append(.ssidOption)
        if selectedOption != .anySSID {
            sections.append(.selectedSSIDs)
            sections.append(.addSSIDs)
        }
    }

    func updateCurrentSSIDEntry() {
        if let connectedSSID = connectedSSID, !selectedSSIDs.contains(connectedSSID) {
            if let first = addSSIDRows.first, case .addNewSSID = first {
                addSSIDRows.insert(.addConnectedSSID(connectedSSID: connectedSSID), at: 0)
            }
        } else if let first = addSSIDRows.first, case .addConnectedSSID = first {
            addSSIDRows.removeFirst()
        }
    }

    func updateTableViewAddSSIDRows() {
        guard let addSSIDSection = sections.firstIndex(of: .addSSIDs) else { return }
        let numberOfAddSSIDRows = addSSIDRows.count
        let numberOfAddSSIDRowsInTableView = tableView.numberOfRows(inSection: addSSIDSection)
        switch (numberOfAddSSIDRowsInTableView, numberOfAddSSIDRows) {
        case (1, 2):
            tableView.insertRows(at: [IndexPath(row: 0, section: addSSIDSection)], with: .automatic)
        case (2, 1):
            tableView.deleteRows(at: [IndexPath(row: 0, section: addSSIDSection)], with: .automatic)
        default:
            break
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        delegate?.ssidOptionSaved(option: selectedOption, ssids: selectedSSIDs)
    }
}

extension SSIDOptionEditTableViewController {
    override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch sections[section] {
        case .ssidOption:
            return ssidOptionFields.count
        case .selectedSSIDs:
            return selectedSSIDs.isEmpty ? 1 : selectedSSIDs.count
        case .addSSIDs:
            return addSSIDRows.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch sections[indexPath.section] {
        case .ssidOption:
            return ssidOptionCell(for: tableView, at: indexPath)
        case .selectedSSIDs:
            if !selectedSSIDs.isEmpty {
                return selectedSSIDCell(for: tableView, at: indexPath)
            } else {
                return noSSIDsCell(for: tableView, at: indexPath)
            }
        case .addSSIDs:
            return addSSIDCell(for: tableView, at: indexPath)
        }
    }

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        switch sections[indexPath.section] {
        case .ssidOption:
            return false
        case .selectedSSIDs:
            return !selectedSSIDs.isEmpty
        case .addSSIDs:
            return true
        }
    }

    override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        switch sections[indexPath.section] {
        case .ssidOption:
            return .none
        case .selectedSSIDs:
           return .delete
        case .addSSIDs:
            return .insert
        }
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch sections[section] {
        case .ssidOption:
            return nil
        case .selectedSSIDs:
            return tr("tunnelOnDemandSectionTitleSelectedSSIDs")
        case .addSSIDs:
            return tr("tunnelOnDemandSectionTitleAddSSIDs")
        }
    }

    private func ssidOptionCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
        let field = ssidOptionFields[indexPath.row]
        let cell: CheckmarkCell = tableView.dequeueReusableCell(for: indexPath)
        cell.message = field.localizedUIString
        cell.isChecked = selectedOption == field
        cell.isEditing = false
        return cell
    }

    private func noSSIDsCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
        let cell: TextCell = tableView.dequeueReusableCell(for: indexPath)
        cell.message = tr("tunnelOnDemandNoSSIDs")
        if #available(iOS 13.0, *) {
            cell.setTextColor(.secondaryLabel)
        } else {
            cell.setTextColor(.gray)
        }
        cell.setTextAlignment(.center)
        return cell
    }

    private func selectedSSIDCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
        let cell: EditableTextCell = tableView.dequeueReusableCell(for: indexPath)
        cell.message = selectedSSIDs[indexPath.row]
        cell.placeholder = tr("tunnelOnDemandSSIDTextFieldPlaceholder")
        cell.isEditing = true
        cell.onValueBeingEdited = { [weak self, weak cell] text in
            guard let self = self, let cell = cell else { return }
            if let row = self.tableView.indexPath(for: cell)?.row {
                self.selectedSSIDs[row] = text
                self.updateCurrentSSIDEntry()
                self.updateTableViewAddSSIDRows()
            }
        }
        return cell
    }

    private func addSSIDCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
        let cell: TextCell = tableView.dequeueReusableCell(for: indexPath)
        switch addSSIDRows[indexPath.row] {
        case .addConnectedSSID:
            cell.message = tr(format: "tunnelOnDemandAddMessageAddConnectedSSID (%@)", connectedSSID!)
        case .addNewSSID:
            cell.message = tr("tunnelOnDemandAddMessageAddNewSSID")
        }
        cell.isEditing = true
        return cell
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        switch sections[indexPath.section] {
        case .ssidOption:
            assertionFailure()
        case .selectedSSIDs:
            assert(editingStyle == .delete)
            selectedSSIDs.remove(at: indexPath.row)
            if !selectedSSIDs.isEmpty {
                tableView.deleteRows(at: [indexPath], with: .automatic)
            } else {
                tableView.reloadRows(at: [indexPath], with: .automatic)
            }
            updateCurrentSSIDEntry()
            updateTableViewAddSSIDRows()
        case .addSSIDs:
            assert(editingStyle == .insert)
            let newSSID: String
            switch addSSIDRows[indexPath.row] {
            case .addConnectedSSID(let connectedSSID):
                newSSID = connectedSSID
            case .addNewSSID:
                newSSID = ""
            }
            selectedSSIDs.append(newSSID)
            loadSections()
            let selectedSSIDsSection = sections.firstIndex(of: .selectedSSIDs)!
            let indexPath = IndexPath(row: selectedSSIDs.count - 1, section: selectedSSIDsSection)
            if selectedSSIDs.count == 1 {
                tableView.reloadRows(at: [indexPath], with: .automatic)
            } else {
                tableView.insertRows(at: [indexPath], with: .automatic)
            }
            updateCurrentSSIDEntry()
            updateTableViewAddSSIDRows()
            if newSSID.isEmpty {
                if let selectedSSIDCell = tableView.cellForRow(at: indexPath) as? EditableTextCell {
                    selectedSSIDCell.beginEditing()
                }
            }
        }
    }

    private func getConnectedSSID(completionHandler: @escaping (String?) -> Void) {
        #if targetEnvironment(simulator)
        completionHandler("Simulator Wi-Fi")
        #else
        if #available(iOS 14, *) {
            NEHotspotNetwork.fetchCurrent { hotspotNetwork in
                completionHandler(hotspotNetwork?.ssid)
            }
        } else {
            if let supportedInterfaces = CNCopySupportedInterfaces() as? [CFString] {
                for interface in supportedInterfaces {
                    if let networkInfo = CNCopyCurrentNetworkInfo(interface) {
                        if let ssid = (networkInfo as NSDictionary)[kCNNetworkInfoKeySSID as String] as? String {
                            completionHandler(!ssid.isEmpty ? ssid : nil)
                            return
                        }
                    }
                }
            }

            completionHandler(nil)
        }
        #endif
    }
}

extension SSIDOptionEditTableViewController {
    override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        switch sections[indexPath.section] {
        case .ssidOption:
            return indexPath
        case .selectedSSIDs, .addSSIDs:
            return nil
        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch sections[indexPath.section] {
        case .ssidOption:
            let previousOption = selectedOption
            selectedOption = ssidOptionFields[indexPath.row]
            guard previousOption != selectedOption else {
                tableView.deselectRow(at: indexPath, animated: true)
                return
            }
            loadSections()
            if previousOption == .anySSID {
                let indexSet = IndexSet(1 ... 2)
                tableView.insertSections(indexSet, with: .fade)
            }
            if selectedOption == .anySSID {
                let indexSet = IndexSet(1 ... 2)
                tableView.deleteSections(indexSet, with: .fade)
            }
            tableView.reloadSections(IndexSet(integer: indexPath.section), with: .none)
        case .selectedSSIDs, .addSSIDs:
            assertionFailure()
        }
    }
}