summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/SelectLocationController.swift
blob: 3fb22600a1e119003cf661474bbe3c5e0af54784 (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
//
//  SelectLocationController.swift
//  MullvadVPN
//
//  Created by pronebird on 02/05/2019.
//  Copyright © 2019 Mullvad VPN AB. All rights reserved.
//

import Combine
import UIKit
import os

private let kCellIdentifier = "Cell"

enum SelectLocationControllerError: Error {
    case loadRelayList(RelayCacheError)
    case getRelayConstraints(TunnelManagerError)
}

class SelectLocationController: UITableViewController {

    private let relayCache = try! RelayCache.withDefaultLocationAndEphemeralSession().get()
    private var relayList: RelayList?
    private var relayConstraints: RelayConstraints?
    private var expandedItems = [RelayLocation]()
    private var dataSource: DataSource?
    private var loadDataSubscriber: AnyCancellable?

    @IBOutlet var activityIndicator: SpinnerActivityIndicatorView!

    var selectedLocation: RelayLocation?

    // MARK: - View lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        dataSource = DataSource(
            tableView: self.tableView,
            cellProvider: { [weak self] (tableView, indexPath, item) -> UITableViewCell? in
                guard let self = self else { return nil }

                let cell = tableView.dequeueReusableCell(
                    withIdentifier: kCellIdentifier, for: indexPath) as! SelectLocationCell

                cell.accessibilityIdentifier = item.relayLocation.stringRepresentation
                cell.isDisabled = !item.hasActiveRelays()
                cell.locationLabel.text = item.displayName()
                cell.statusIndicator.isActive = item.hasActiveRelays()
                cell.showsCollapseControl = item.isCollapsibleLevel()
                cell.isExpanded = self.expandedItems.contains(item.relayLocation)
                cell.didCollapseHandler = { [weak self] (cell) in
                    self?.collapseCell(cell)
                }

                return cell
        })

        tableView.dataSource = dataSource

        addActivityIndicatorView()
        loadData()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        updateTableHeaderViewSizeIfNeeded()
    }

    // MARK: - UITableViewDelegate

    override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        return dataSource?.itemIdentifier(for: indexPath)?.hasActiveRelays() ?? false
    }

    override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
        return dataSource?.itemIdentifier(for: indexPath)?.indentationLevel() ?? 0
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let item = dataSource?.itemIdentifier(for: indexPath) else { return }

        selectedLocation = item.relayLocation

        // Return back to the main view after selecting the relay
        tableView.isUserInteractionEnabled = false

        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(250)) {
            self.performSegue(withIdentifier:
                SegueIdentifier.SelectLocation.returnToConnectWithNewRelay.rawValue, sender: self)
        }
    }

    // MARK: - Relay list handling

    private func loadData() {
        loadDataSubscriber = relayCache.read()
            .mapError { SelectLocationControllerError.loadRelayList($0) }
            .map { $0.relayList.sorted() }
            .flatMap({ (filteredRelayList) in
                TunnelManager.shared.getRelayConstraints()
                    .mapError { SelectLocationControllerError.getRelayConstraints($0) }
                    .map { (filteredRelayList, $0) }
            })
            .receive(on: DispatchQueue.main)
            .handleEvents(receiveSubscription: { [weak self] _ in
                self?.activityIndicator.startAnimating()
            }, receiveCompletion: { [weak self] _ in
                self?.activityIndicator.stopAnimating()
            }, receiveCancel: { [weak self] () in
                self?.activityIndicator.stopAnimating()
            })
            .sink(receiveCompletion: { (completion) in
                if case .failure(let error) = completion {
                    os_log(.error, "Failed to load the SelectLocation controller: %{public}s", error.localizedDescription)
                }
            }) { [weak self] (result) in
                let (relayList, constraints) = result

                self?.didReceive(relayList: relayList, relayConstraints: constraints)
            }
    }

    private func didReceive(relayList: RelayList, relayConstraints: RelayConstraints) {
        self.relayList = relayList
        self.relayConstraints = relayConstraints

        let relayLocation = relayConstraints.location.value
        expandedItems = relayLocation?.ascendants ?? []

        updateDataSource(animateDifferences: false)
        tableView.reloadData()

        updateTableViewSelection(scroll: true, animated: false)
    }

    private func computeIndexPathForSelectedLocation(relayLocation: RelayLocation) -> IndexPath? {
        guard let row = dataSource?.snapshot()
            .itemIdentifiers
            .firstIndex(where: { $0.relayLocation == relayLocation }) else {
                return nil
        }

        return IndexPath(row: row, section: 0)
    }

    // MARK: - Collapsible cells

    private func updateTableViewSelection(scroll: Bool, animated: Bool) {
        guard let relayLocation = relayConstraints?.location.value else { return }

        let indexPath = computeIndexPathForSelectedLocation(relayLocation: relayLocation)

        let scrollPosition: UITableView.ScrollPosition = scroll ? .middle : .none
        tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition)
    }

    private func updateDataSource(animateDifferences: Bool, completion: (() -> Void)? = nil) {
        let items = relayList?.intoRelayDataSourceItemList(using: { (item) -> Bool in
            return expandedItems.contains(item.relayLocation)
        }) ?? []

        var snapshot = DataSourceSnapshot()
        snapshot.appendSections([.locations])
        snapshot.appendItems(items, toSection: .locations)

        dataSource?.apply(
            snapshot,
            animatingDifferences: animateDifferences,
            completion: completion
        )
    }

    private func collapseCell(_ cell: SelectLocationCell) {
        guard let cellIndexPath = tableView.indexPath(for: cell),
            let item = dataSource?.itemIdentifier(for: cellIndexPath) else {
                return
        }

        let itemLocation = item.relayLocation

        if let index = expandedItems.firstIndex(of: itemLocation) {
            expandedItems.remove(at: index)
            cell.isExpanded = false
        } else {
            expandedItems.append(itemLocation)
            cell.isExpanded = true
        }

        updateDataSource(animateDifferences: true) {
            self.updateTableViewSelection(scroll: false, animated: true)
        }
    }

    // MARK: - UITableView header

    private func updateTableHeaderViewSizeIfNeeded() {
        guard let header = tableView.tableHeaderView else { return }

        // measure the view size
        let sizeConstraint = CGSize(
            width: tableView.bounds.width,
            height: UIView.layoutFittingCompressedSize.height
        )

        let newSize = header.systemLayoutSizeFitting(sizeConstraint)
        let oldSize = header.frame.size

        if oldSize.height != newSize.height {
            header.frame.size.height = newSize.height

            // reset the header view to force UITableView layout pass
            tableView.tableHeaderView = header
        }
    }

    // MARK: - Activity indicator

    private func addActivityIndicatorView() {
        view.addSubview(activityIndicator)

        activityIndicator.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            activityIndicator.widthAnchor.constraint(equalToConstant: 48),
            activityIndicator.heightAnchor.constraint(equalToConstant: 48),
            activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -60)
        ])
    }
}

private extension RelayList {

    typealias EvaluatorFn = (DataSourceItem) -> Bool

    /// Turn `RelayList` into a flat list of `DataSourceItem`s.
    ///
    /// - Parameters evaluator: A closure that determines if the sub-tree should be rendered when it
    ///                         returns `true`, or dropped when it returns `false`
    func intoRelayDataSourceItemList(using evaluator: EvaluatorFn) -> [DataSourceItem] {
        var items = [DataSourceItem]()

        for country in countries {
            let wrappedCountry = DataSourceItem.Country(
                countryCode: country.code,
                name: country.name,
                hasActiveRelays: country.cities.contains(where: { (city) -> Bool in
                    return city.relays.contains { (host) -> Bool in
                        return host.active
                    }
                })
            )

            let countryItem = DataSourceItem.country(wrappedCountry)
            items.append(countryItem)

            if evaluator(countryItem) {
                for city in country.cities {
                    let wrappedCity = DataSourceItem.City(
                        countryCode: country.code,
                        cityCode: city.code,
                        name: city.name,
                        hasActiveRelays: city.relays.contains(where: { $0.active })
                    )

                    let cityItem = DataSourceItem.city(wrappedCity)
                    items.append(cityItem)

                    if evaluator(cityItem) {
                        for host in city.relays {
                            let wrappedHost = DataSourceItem.Hostname(
                                countryCode: country.code,
                                cityCode: city.code,
                                hostname: host.hostname,
                                active: host.active)
                            items.append(.hostname(wrappedHost))
                        }
                    }
                }
            }
        }

        return items
    }

}

private extension RelayLocation {

    /// A list of `RelayLocation` items preceding the given one in the relay tree
    var ascendants: [RelayLocation] {
        switch self {
        case .hostname(let country, let city, _):
            return [.country(country), .city(country, city)]

        case .city(let country, _):
            return [.country(country)]

        case .country:
            return []
        }
    }

}

/// Enum describing the table view sections
private enum DataSourceSection {
    case locations
}

/// Data source type
private typealias DataSource = UITableViewDiffableDataSource<DataSourceSection, DataSourceItem>

/// Data source snapshot type
private typealias DataSourceSnapshot = NSDiffableDataSourceSnapshot<DataSourceSection, DataSourceItem>

/// A wrapper type for RelayList to be able to represent it as a flat list
private enum DataSourceItem: Hashable {

    struct Country {
        let countryCode: String
        let name: String
        let hasActiveRelays: Bool
    }

    struct City {
        let countryCode: String
        let cityCode: String
        let name: String
        let hasActiveRelays: Bool
    }

    struct Hostname {
        let countryCode: String
        let cityCode: String
        let hostname: String
        let active: Bool
    }

    case country(Country)
    case city(City)
    case hostname(Hostname)

    var relayLocation: RelayLocation {
        switch self {
        case .country(let country):
            return .country(country.countryCode)
        case .city(let city):
            return .city(city.countryCode, city.cityCode)
        case .hostname(let host):
            return .hostname(host.countryCode, host.cityCode, host.hostname)
        }
    }

    static func == (lhs: DataSourceItem, rhs: DataSourceItem) -> Bool {
        lhs.relayLocation == rhs.relayLocation
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(relayLocation)
    }

    func indentationLevel() -> Int {
        switch self {
        case .country:
            return 0
        case .city:
            return 1
        case .hostname:
            return 2
        }
    }

    func displayName() -> String {
        switch self {
        case .country(let country):
            return country.name
        case .city(let city):
            return city.name
        case .hostname(let relay):
            return relay.hostname
        }
    }

    func hasActiveRelays() -> Bool {
        switch self {
        case .country(let country):
            return country.hasActiveRelays
        case .city(let city):
            return city.hasActiveRelays
        case .hostname(let host):
            return host.active
        }
    }

    func isCollapsibleLevel() -> Bool {
        switch self {
        case .country, .city:
            return self.hasActiveRelays()
        case .hostname:
            return false
        }
    }

}