summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/PreferencesDataSource.swift
blob: 2ec34c1a6de9d9dc4c24f04a4ff2f9cf4b769f92 (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
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//
//  PreferencesDataSource.swift
//  MullvadVPN
//
//  Created by pronebird on 05/10/2021.
//  Copyright © 2021 Mullvad VPN AB. All rights reserved.
//

import UIKit

class PreferencesDataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
    private enum CellReuseIdentifiers: String, CaseIterable {
        case settingSwitch
        case dnsServer
        case addDNSServer

        var reusableViewClass: AnyClass {
            switch self {
            case .settingSwitch:
                return SettingsSwitchCell.self
            case .dnsServer:
                return SettingsDNSTextCell.self
            case .addDNSServer:
                return SettingsAddDNSEntryCell.self
            }
        }
    }

    private enum HeaderFooterReuseIdentifiers: String, CaseIterable {
        case customDNSFooter
        case spacer

        var reusableViewClass: AnyClass {
            switch self {
            case .customDNSFooter:
                return SettingsStaticTextFooterView.self
            case .spacer:
                return EmptyTableViewHeaderFooterView.self
            }
        }
    }

    private enum Section: Hashable {
        case mullvadDNS
        case customDNS
    }

    private enum Item: Hashable {
        case blockAdvertising
        case blockTracking
        case useCustomDNS
        case addDNSServer
        case dnsServer(_ uniqueID: UUID)

        static func isDNSServerItem(_ item: Item) -> Bool {
            if case .dnsServer = item {
                return true
            } else {
                return false
            }
        }
    }

    private var isEditing = false
    private var snapshot = DataSourceSnapshot<Section, Item>()

    private(set) var viewModel = PreferencesViewModel()
    private(set) var viewModelBeforeEditing = PreferencesViewModel()

    weak var delegate: PreferencesDataSourceDelegate?

    weak var tableView: UITableView? {
        didSet {
            tableView?.dataSource = self
            tableView?.delegate = self

            registerClasses()
        }
    }

    override init() {
        super.init()

        updateSnapshot()
    }

    func setEditing(_ editing: Bool, animated: Bool) {
        guard isEditing != editing else { return }

        let oldSnapshot = snapshot
        let oldDNSDomains = viewModel.customDNSDomains

        isEditing = editing

        if editing {
            viewModelBeforeEditing = viewModel
        } else {
            viewModel.sanitizeCustomDNSEntries()
        }

        updateSnapshot()

        // Reconfigure cells for items with corresponding DNS entries that were changed during sanitization.
        let itemsToReload: [Item] = oldDNSDomains.filter { oldDNSEntry in
            guard let newDNSEntry = viewModel.dnsEntry(entryIdentifier: oldDNSEntry.identifier) else { return false }

            return newDNSEntry.address != oldDNSEntry.address
        }.map { dnsEntry in
            return .dnsServer(dnsEntry.identifier)
        }

        snapshot.reconfigureItems(itemsToReload)

        if animated {
            let diffResult = oldSnapshot.difference(snapshot)
            if let tableView = tableView {
                diffResult.apply(to: tableView, animateDifferences: animated)
                reloadCustomDNSFooter()
            }
        } else {
            tableView?.reloadData()
        }

        if !editing && viewModelBeforeEditing != viewModel {
            delegate?.preferencesDataSource(self, didChangeViewModel: viewModel)
        }
    }

    func update(from dnsSettings: DNSSettings) {
        let newViewModel = PreferencesViewModel(from: dnsSettings)
        let mergedViewModel = viewModel.merged(newViewModel)

        if viewModel != mergedViewModel {
            viewModel = mergedViewModel
            updateSnapshot()
            tableView?.reloadData()
        }
    }

    // MARK: - UITableViewDataSource

    func numberOfSections(in tableView: UITableView) -> Int {
        return snapshot.numberOfSections()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let sectionIdentifier = snapshot.section(at: section) else { return 0 }

        return snapshot.numberOfItems(in: sectionIdentifier) ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = snapshot.itemForIndexPath(indexPath)!

        return dequeueCellForItem(item, in: tableView, at: indexPath)
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Disable swipe to delete when not editing the table view
        guard isEditing else { return false }

        let item = snapshot.itemForIndexPath(indexPath)

        switch item {
        case .dnsServer, .addDNSServer:
            return true
        default:
            return false
        }
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        let item = snapshot.itemForIndexPath(indexPath)

        if case .addDNSServer = item, editingStyle == .insert {
            addDNSServerEntry()
        }

        if case .dnsServer(let entryIdentifier) = item, editingStyle == .delete {
            deleteDNSServerEntry(entryIdentifier: entryIdentifier)
        }
    }

    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        let item = snapshot.itemForIndexPath(indexPath)

        switch item {
        case .dnsServer:
            return true
        default:
            return false
        }
    }

    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let sourceItem = snapshot.itemForIndexPath(sourceIndexPath)!
        let destinationItem = snapshot.itemForIndexPath(destinationIndexPath)!

        guard case .dnsServer(let sourceIdentifier) = sourceItem,
              case .dnsServer(let targetIdentifier) = destinationItem,
              let sourceIndex = viewModel.indexOfDNSEntry(entryIdentifier: sourceIdentifier),
              let destinationIndex = viewModel.indexOfDNSEntry(entryIdentifier: targetIdentifier) else { return }

        let removedEntry = viewModel.customDNSDomains.remove(at: sourceIndex)
        viewModel.customDNSDomains.insert(removedEntry, at: destinationIndex)

        updateSnapshot()
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        return false
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderFooterReuseIdentifiers.spacer.rawValue)
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let sectionIdentifier = snapshot.section(at: section)!

        switch sectionIdentifier {
        case .mullvadDNS:
            return nil

        case .customDNS:
            let reusableView = tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderFooterReuseIdentifiers.customDNSFooter.rawValue) as! SettingsStaticTextFooterView
            configureFooterView(reusableView)
            return reusableView
        }
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return UIMetrics.sectionSpacing
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        let sectionIdentifier = snapshot.section(at: section)!

        switch sectionIdentifier {
        case .mullvadDNS:
            return 0

        case .customDNS:
            switch viewModel.customDNSPrecondition {
            case .satisfied:
                return 0
            case .conflictsWithOtherSettings, .emptyDNSDomains:
                return UITableView.automaticDimension
            }
        }
    }

    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        let item = snapshot.itemForIndexPath(indexPath)

        switch item {
        case .dnsServer:
            return .delete
        case .addDNSServer:
            return .insert
        default:
            return .none
        }
    }

    func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
        guard let sectionIdentifier = snapshot.section(at: sourceIndexPath.section),
              case .customDNS = sectionIdentifier else { return sourceIndexPath }

        let items = snapshot.items(in: sectionIdentifier)

        let indexPathForFirstRow = items.first(where: Item.isDNSServerItem).flatMap { item in
            return snapshot.indexPathForItem(item)
        }

        let indexPathForLastRow = items.last(where: Item.isDNSServerItem).flatMap { item in
            return snapshot.indexPathForItem(item)
        }

        guard let indexPathForFirstRow = indexPathForFirstRow,
              let indexPathForLastRow = indexPathForLastRow else { return sourceIndexPath }

        if proposedDestinationIndexPath.section == sourceIndexPath.section {
            return min(max(proposedDestinationIndexPath, indexPathForFirstRow), indexPathForLastRow)
        } else {
            if proposedDestinationIndexPath.section > sourceIndexPath.section {
                return indexPathForLastRow
            } else {
                return indexPathForFirstRow
            }
        }
    }

    // MARK: - Private

    private func registerClasses() {
        CellReuseIdentifiers.allCases.forEach { enumCase in
            tableView?.register(enumCase.reusableViewClass, forCellReuseIdentifier: enumCase.rawValue)
        }

        HeaderFooterReuseIdentifiers.allCases.forEach { enumCase in
            tableView?.register(enumCase.reusableViewClass, forHeaderFooterViewReuseIdentifier: enumCase.rawValue)
        }
    }

    private func updateSnapshot() {
        var newSnapshot = DataSourceSnapshot<Section, Item>()
        newSnapshot.appendSections([.mullvadDNS, .customDNS])
        newSnapshot.appendItems([.blockAdvertising, .blockTracking], in: .mullvadDNS)
        newSnapshot.appendItems([.useCustomDNS], in: .customDNS)

        let dnsServerItems = viewModel.customDNSDomains.map { entry in
            return Item.dnsServer(entry.identifier)
        }
        newSnapshot.appendItems(dnsServerItems, in: .customDNS)

        if isEditing && viewModel.customDNSDomains.count < DNSSettings.maxAllowedCustomDNSDomains {
            newSnapshot.appendItems([.addDNSServer], in: .customDNS)
        }

        snapshot = newSnapshot
    }

    private func dequeueCellForItem(_ item: Item, in tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
        switch item {
        case .blockAdvertising:
            let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseIdentifiers.settingSwitch.rawValue, for: indexPath) as! SettingsSwitchCell

            cell.titleLabel.text = NSLocalizedString(
                "BLOCK_ADS_CELL_LABEL",
                tableName: "Preferences",
                value: "Block ads",
                comment: ""
            )
            cell.accessibilityHint = nil
            cell.setOn(viewModel.blockAdvertising, animated: false)
            cell.action = { [weak self] isOn in
                self?.setBlockAdvertising(isOn)
            }

            return cell

        case .blockTracking:
            let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseIdentifiers.settingSwitch.rawValue, for: indexPath) as! SettingsSwitchCell

            cell.titleLabel.text = NSLocalizedString(
                "BLOCK_TRACKERS_CELL_LABEL",
                tableName: "Preferences",
                value: "Block trackers",
                comment: ""
            )
            cell.accessibilityHint = nil
            cell.setOn(viewModel.blockTracking, animated: false)
            cell.action = { [weak self] isOn in
                self?.setBlockTracking(isOn)
            }

            return cell

        case .useCustomDNS:
            let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseIdentifiers.settingSwitch.rawValue, for: indexPath) as! SettingsSwitchCell

            cell.titleLabel.text = NSLocalizedString(
                "CUSTOM_DNS_CELL_LABEL",
                tableName: "Preferences",
                value: "Use custom DNS",
                comment: ""
            )
            cell.setEnabled(viewModel.customDNSPrecondition == .satisfied)
            cell.setOn(viewModel.effectiveEnableCustomDNS, animated: false)
            cell.action = { [weak self] isOn in
                self?.setEnableCustomDNS(isOn)
            }

            cell.accessibilityHint = viewModel.customDNSPrecondition.localizedDescription(isEditing: isEditing)

            return cell

        case .addDNSServer:
            let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseIdentifiers.addDNSServer.rawValue, for: indexPath) as! SettingsAddDNSEntryCell
            cell.titleLabel.text = NSLocalizedString(
                "ADD_CUSTOM_DNS_SERVER_CELL_LABEL",
                tableName: "Preferences",
                value: "Add a server",
                comment: ""
            )

            cell.actionHandler = { [weak self] cell in
                self?.addDNSServerEntry()
            }

            return cell

        case .dnsServer(let entryIdentifier):
            let dnsServerEntry = viewModel.dnsEntry(entryIdentifier: entryIdentifier)!

            let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseIdentifiers.dnsServer.rawValue, for: indexPath) as! SettingsDNSTextCell
            cell.textField.text = dnsServerEntry.address
            cell.isValidInput = viewModel.validateDNSDomainUserInput(dnsServerEntry.address)

            cell.onTextChange = { [weak self] cell in
                guard let self = self, let indexPath = self.tableView?.indexPath(for: cell) else { return }

                if case .dnsServer(let entryIdentifier) = self.snapshot.itemForIndexPath(indexPath) {
                    self.handleDNSEntryChange(entryIdentifier: entryIdentifier, cell: cell)
                }
            }

            cell.onReturnKey = { cell in
                cell.endEditing(false)
            }

            return cell
        }
    }

    private func setBlockAdvertising(_ isEnabled: Bool) {
        let oldViewModel = viewModel

        viewModel.setBlockAdvertising(isEnabled)

        if oldViewModel.customDNSPrecondition != viewModel.customDNSPrecondition {
            reloadCustomDNSFooter()
        }

        if !isEditing {
            delegate?.preferencesDataSource(self, didChangeViewModel: viewModel)
        }
    }

    private func setBlockTracking(_ isEnabled: Bool) {
        let oldViewModel = viewModel

        viewModel.setBlockTracking(isEnabled)

        if oldViewModel.customDNSPrecondition != viewModel.customDNSPrecondition {
            reloadCustomDNSFooter()
        }

        if !isEditing {
            delegate?.preferencesDataSource(self, didChangeViewModel: viewModel)
        }
    }

    private func setEnableCustomDNS(_ isEnabled: Bool) {
        viewModel.setEnableCustomDNS(isEnabled)

        reloadCustomDNSFooter()

        if !isEditing {
            delegate?.preferencesDataSource(self, didChangeViewModel: viewModel)
        }
    }

    private func handleDNSEntryChange(entryIdentifier: UUID, cell: SettingsDNSTextCell) {
        let string = cell.textField.text ?? ""
        let oldViewModel = viewModel

        viewModel.updateDNSEntry(entryIdentifier: entryIdentifier, newAddress: string)
        cell.isValidInput = viewModel.validateDNSDomainUserInput(string)

        if oldViewModel.customDNSPrecondition != viewModel.customDNSPrecondition {
            reloadCustomDNSFooter()
        }
    }

    private func addDNSServerEntry() {
        let oldViewModel = viewModel

        let newDNSEntry = DNSServerEntry(address: "")
        viewModel.customDNSDomains.append(newDNSEntry)

        let oldSnapshot = snapshot
        updateSnapshot()

        let diffResult = oldSnapshot.difference(snapshot)
        if let tableView = tableView {
            diffResult.apply(to: tableView, animateDifferences: true) { completed in
                if oldViewModel.customDNSPrecondition != self.viewModel.customDNSPrecondition {
                    self.reloadCustomDNSFooter()
                }

                if completed {
                    // Focus on the new entry text field.
                    let lastDNSEntry = self.snapshot.items(in: .customDNS).last { item in
                        if case .dnsServer(let entryIdentifier) = item {
                            return entryIdentifier == newDNSEntry.identifier
                        } else {
                            return false
                        }
                    }

                    if let lastDNSEntry = lastDNSEntry, let indexPath = self.snapshot.indexPathForItem(lastDNSEntry) {
                        let cell = self.tableView?.cellForRow(at: indexPath) as? SettingsDNSTextCell

                        self.tableView?.scrollToRow(at: indexPath, at: .bottom, animated: true)
                        cell?.textField.becomeFirstResponder()
                    }
                }
            }
        }
    }

    private func deleteDNSServerEntry(entryIdentifier: UUID) {
        let oldViewModel = viewModel
        let oldSnapshot = snapshot

        let entryIndex = viewModel.customDNSDomains.firstIndex { entry in
            return entry.identifier == entryIdentifier
        }

        guard let entryIndex = entryIndex else { return }

        viewModel.customDNSDomains.remove(at: entryIndex)
        updateSnapshot()

        let diffResult = oldSnapshot.difference(snapshot)

        if let tableView = tableView {
            diffResult.apply(to: tableView, animateDifferences: true) { completed in
                if oldViewModel.customDNSPrecondition != self.viewModel.customDNSPrecondition {
                    self.reloadCustomDNSFooter()
                }
            }
        }
    }

    private func reloadCustomDNSFooter() {
        let sectionIndex = snapshot.indexOfSection(.customDNS)!
        let indexPath = snapshot.indexPathForItem(.useCustomDNS)!

        // Reload footer view
        tableView?.performBatchUpdates {
            if let reusableView = tableView?.footerView(forSection: sectionIndex) as? SettingsStaticTextFooterView {
                configureFooterView(reusableView)
            }
        }

        // Reload "Use custom DNS" row
        if let cell = tableView?.cellForRow(at: indexPath) as? SettingsSwitchCell {
            cell.setEnabled(viewModel.customDNSPrecondition == .satisfied)
            cell.setOn(viewModel.effectiveEnableCustomDNS, animated: true)
        }
    }

    private func configureFooterView(_ reusableView: SettingsStaticTextFooterView) {
        let font = reusableView.titleLabel.font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize)

        reusableView.titleLabel.attributedText = viewModel.customDNSPrecondition
            .attributedLocalizedDescription(isEditing: isEditing, preferredFont: font)
    }

}