-
Notifications
You must be signed in to change notification settings - Fork 415
/
NetworkProtectionStatusViewModel.swift
643 lines (545 loc) · 21.9 KB
/
NetworkProtectionStatusViewModel.swift
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//
// NetworkProtectionStatusViewModel.swift
// DuckDuckGo
//
// Copyright © 2023 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Combine
import NetworkProtection
import WidgetKit
import BrowserServicesKit
import Core
import Subscription
import TipKit
struct NetworkProtectionLocationStatusModel {
enum LocationIcon {
case defaultIcon
case emoji(String)
}
let title: String
let icon: LocationIcon
let isNearest: Bool
init(selectedLocation: VPNSettings.SelectedLocation) {
switch selectedLocation {
case .nearest:
title = UserText.netPPreferredLocationNearest
icon = .defaultIcon
isNearest = true
case .location(let location):
let countryLabelsModel = NetworkProtectionVPNCountryLabelsModel(country: location.country, useFullCountryName: true)
if let city = location.city {
let formattedCityAndCountry = UserText.netPVPNSettingsLocationSubtitleFormattedCityAndCountry(
city: city,
country: countryLabelsModel.title
)
title = "\(countryLabelsModel.emoji) \(formattedCityAndCountry)"
} else {
title = "\(countryLabelsModel.emoji) \(countryLabelsModel.title)"
}
icon = .emoji(countryLabelsModel.emoji)
isNearest = false
}
}
static func formattedLocation(city: String, country: String) -> String {
let countryLabelsModel = NetworkProtectionVPNCountryLabelsModel(country: country, useFullCountryName: true)
let city = "\(countryLabelsModel.emoji) \(city)"
return UserText.netPVPNSettingsLocationSubtitleFormattedCityAndCountry(city: city, country: countryLabelsModel.title)
}
}
final class NetworkProtectionStatusViewModel: ObservableObject {
enum Constants {
static let defaultDownloadVolume = "0 KB"
static let defaultUploadVolume = "0 KB"
}
private static var dateFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.zeroFormattingBehavior = .pad
return formatter
}()
private static var snoozeRemainingDateFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.minute, .second]
formatter.zeroFormattingBehavior = .pad
return formatter
}()
private let byteCountFormatter: ByteCountFormatter = {
let formatter = ByteCountFormatter()
formatter.allowsNonnumericFormatting = false
formatter.allowedUnits = [.useKB, .useMB, .useGB]
return formatter
}()
private let tunnelController: (TunnelController & TunnelSessionProvider)
private let statusObserver: ConnectionStatusObserver
private let serverInfoObserver: ConnectionServerInfoObserver
private let errorObserver: ConnectionErrorObserver
private var cancellables: Set<AnyCancellable> = []
// MARK: - Tips
@Published
var showAddWidgetEducationView: Bool = false
@Published
var vpnEnabledTips: TipGrouping = {
if #available(iOS 18.0, *) {
return TipGroup(.ordered) {
VPNChangeLocationTip()
VPNUseSnoozeTip()
VPNAddWidgetTip()
}
} else if #available(iOS 17.0, *) {
return LegacyTipGroup(.ordered) {
VPNChangeLocationTip()
VPNUseSnoozeTip()
VPNAddWidgetTip()
}
} else {
return EmptyTipGroup()
}
}()
// MARK: Error
struct ErrorItem {
let title: String
let message: String
}
@Published public var error: ErrorItem? {
didSet {
shouldShowError = error != nil
}
}
@Published public var shouldShowError: Bool = false
// MARK: Header
@Published public var statusImageID: String
@Published public var headerTitle: String
// MARK: Toggle Item
@Published public var isNetPEnabled = false {
didSet {
if #available(iOS 17.0, *) {
if isNetPEnabled {
VPNChangeLocationTip.donateVPNConnectedEvent()
}
VPNUseSnoozeTip.vpnEnabled = isNetPEnabled
VPNAddWidgetTip.vpnEnabled = isNetPEnabled
}
}
}
@Published public var isSnoozing = false {
didSet {
snoozeRequestPending = false
}
}
@Published public var snoozeRequestPending = false
@Published public var statusMessage: String
@Published public var shouldDisableToggle: Bool = false
// MARK: Location
private let settings: VPNSettings
@Published public var preferredLocation: NetworkProtectionLocationStatusModel
// MARK: Connection Details
@Published public var hasServerInfo: Bool = false
@Published public var location: String?
@Published public var ipAddress: String?
@Published public var dnsSettings: NetworkProtectionDNSSettings
@Published public var uploadTotal: String?
@Published public var downloadTotal: String?
private var throughputUpdateTimer: Timer?
@Published public var animationsOn: Bool = false
public let usesUnifiedFeedbackForm: Bool
public init(tunnelController: (TunnelController & TunnelSessionProvider),
settings: VPNSettings,
statusObserver: ConnectionStatusObserver,
serverInfoObserver: ConnectionServerInfoObserver,
errorObserver: ConnectionErrorObserver = ConnectionErrorObserverThroughSession(),
locationListRepository: NetworkProtectionLocationListRepository,
usesUnifiedFeedbackForm: Bool) {
self.tunnelController = tunnelController
self.settings = settings
self.statusObserver = statusObserver
self.serverInfoObserver = serverInfoObserver
self.errorObserver = errorObserver
self.usesUnifiedFeedbackForm = usesUnifiedFeedbackForm
statusMessage = Self.message(for: statusObserver.recentValue)
self.headerTitle = Self.titleText(status: statusObserver.recentValue)
self.statusImageID = Self.statusImageID(connected: statusObserver.recentValue.isConnected)
self.preferredLocation = NetworkProtectionLocationStatusModel(selectedLocation: settings.selectedLocation)
self.dnsSettings = settings.dnsSettings
updateViewModel(withStatus: statusObserver.recentValue)
setUpIsConnectedStatePublishers()
setUpToggledStatePublisher()
setUpStatusMessagePublishers()
setUpDisableTogglePublisher()
setUpServerInfoPublishers()
setUpLocationPublishers()
setUpDNSSettingsPublisher()
setUpThroughputRefreshTimer()
setUpErrorPublishers()
// Prefetching this now for snappy load times on the locations screens
Task {
_ = try? await locationListRepository.fetchLocationList()
}
}
private func setUpIsConnectedStatePublishers() {
statusObserver.publisher.receive(on: DispatchQueue.main).sink { [weak self] status in
self?.updateViewModel(withStatus: status)
}
.store(in: &cancellables)
}
private func setUpToggledStatePublisher() {
statusObserver.publisher
.receive(on: DispatchQueue.main)
.sink { [weak self] status in
switch status {
case .connected:
self?.isNetPEnabled = true
case .connecting:
self?.isNetPEnabled = true
self?.resetConnectionInformation()
default:
self?.isNetPEnabled = false
self?.resetConnectionInformation()
}
}
.store(in: &cancellables)
statusObserver.publisher
.map {
switch $0 {
case .snoozing:
return true
default:
return false
}
}
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
.assign(to: \.isSnoozing, onWeaklyHeld: self)
.store(in: &cancellables)
}
private func setUpStatusMessagePublishers() {
statusObserver.publisher
.removeDuplicates()
.flatMap(maxPublishers: .max(1)) { status in
// As soon as the connection status changes, we should update the status message
var statusUpdatePublishers = [Just(Self.message(for: status)).eraseToAnyPublisher()]
switch status {
case .connected(let connectedDate):
// In the case that the status is connected, we should then provide timed updates
// If we rely on the timed updates alone, there will be a delay to the initial update
statusUpdatePublishers.append(Self.timedConnectedStatusMessagePublisher(forConnectedDate: connectedDate))
case .snoozing:
let timingStore = NetworkProtectionSnoozeTimingStore(userDefaults: .networkProtectionGroupDefaults)
guard let endDate = timingStore.activeTiming?.endDate else {
break
}
statusUpdatePublishers = [Just(Self.snoozeDurationRemainingMessage(for: endDate, currentDate: Date())).eraseToAnyPublisher()]
statusUpdatePublishers.append(Self.timedSnoozeDurationRemainingMessagePublisher(forSnoozeEndDate: endDate))
default:
break
}
return statusUpdatePublishers.publisher
}
.switchToLatest()
.receive(on: DispatchQueue.main)
.assign(to: \.statusMessage, onWeaklyHeld: self)
.store(in: &cancellables)
}
private func setUpDisableTogglePublisher() {
let isLoadingPublisher = statusObserver.publisher.map { $0.isLoading }
isLoadingPublisher
.receive(on: DispatchQueue.main)
.assign(to: \.shouldDisableToggle, onWeaklyHeld: self)
.store(in: &cancellables)
// Set up a delayed publisher to fire just once that reenables the toggle
// Each event cancels the previous delayed publisher
$shouldDisableToggle
.filter { $0 }
.map { _ -> AnyPublisher<Bool, Never> in
Just(false).delay(for: 2.0, scheduler: DispatchQueue.main).eraseToAnyPublisher()
}
.switchToLatest()
.assign(to: \.shouldDisableToggle, onWeaklyHeld: self)
.store(in: &cancellables)
}
private func setUpServerInfoPublishers() {
serverInfoObserver.publisher
.map { serverInfo in
guard let attributes = serverInfo.serverLocation else {
return nil
}
return NetworkProtectionLocationStatusModel.formattedLocation(
city: attributes.city,
country: attributes.country
)
}
.receive(on: DispatchQueue.main)
.assign(to: \.location, onWeaklyHeld: self)
.store(in: &cancellables)
serverInfoObserver.publisher
.map(\.serverAddress)
.receive(on: DispatchQueue.main)
.assign(to: \.ipAddress, onWeaklyHeld: self)
.store(in: &cancellables)
serverInfoObserver.publisher
.map {
$0.serverAddress != nil || $0.serverLocation != nil
}
.receive(on: DispatchQueue.main)
.assign(to: \.hasServerInfo, onWeaklyHeld: self)
.store(in: &cancellables)
}
private func updateViewModel(withStatus connectionStatus: ConnectionStatus) {
self.headerTitle = Self.titleText(status: connectionStatus)
self.statusImageID = Self.statusImageID(connected: connectionStatus.isConnected)
if !connectionStatus.isConnected {
self.uploadTotal = nil
self.downloadTotal = nil
self.throughputUpdateTimer?.invalidate()
self.throughputUpdateTimer = nil
} else {
self.setUpThroughputRefreshTimer()
}
switch connectionStatus {
case .connected:
self.isNetPEnabled = true
case .connecting:
self.isNetPEnabled = true
self.resetConnectionInformation()
default:
self.isNetPEnabled = false
self.resetConnectionInformation()
}
}
private func setUpErrorPublishers() {
guard AppDependencyProvider.shared.internalUserDecider.isInternalUser else {
return
}
errorObserver.publisher
.map { errorMessage in
guard let errorMessage else {
return nil
}
return ErrorItem(title: "Failed to Connect", message: errorMessage)
}
.receive(on: DispatchQueue.main)
.assign(to: \.error, onWeaklyHeld: self)
.store(in: &cancellables)
}
private func setUpLocationPublishers() {
settings.selectedLocationPublisher
.receive(on: DispatchQueue.main)
.map(NetworkProtectionLocationStatusModel.init(selectedLocation:))
.assign(to: \.preferredLocation, onWeaklyHeld: self)
.store(in: &cancellables)
}
private func setUpDNSSettingsPublisher() {
settings.dnsSettingsPublisher
.receive(on: DispatchQueue.main)
.assign(to: \.dnsSettings, onWeaklyHeld: self)
.store(in: &cancellables)
}
private func setUpThroughputRefreshTimer() {
if let throughputUpdateTimer, throughputUpdateTimer.isValid {
// Prevent the timer from being set up multiple times
return
}
Task {
// Refresh as soon as the timer is set up, rather than waiting for 1 second:
await self.refreshDataVolumeTotals()
}
throughputUpdateTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
guard let strongSelf = self else { return }
Task {
await strongSelf.refreshDataVolumeTotals()
}
}
}
private func refreshDataVolumeTotals() async {
guard let activeSession = await tunnelController.activeSession() else {
return
}
let data: ExtensionMessageString? = try? await activeSession.sendProviderMessage(.getDataVolume)
guard let data else {
return
}
let bytes = data.value.components(separatedBy: ",")
guard let receivedString = bytes.first, let sentString = bytes.last,
let received = Int64(receivedString), let sent = Int64(sentString) else {
return
}
await updateBandwidthCounts(sent: sent, received: received)
}
@MainActor
private func updateBandwidthCounts(sent: Int64, received: Int64) {
self.uploadTotal = byteCountFormatter.string(fromByteCount: sent)
self.downloadTotal = byteCountFormatter.string(fromByteCount: received)
}
@MainActor
func didToggleNetP(to enabled: Bool) async {
shouldDisableToggle = true
// This is to prevent weird looking animations on navigating to the screen.
// It makes sense as animations should mostly only happen when a user has interacted.
animationsOn = true
if enabled {
if isSnoozing {
await cancelSnooze()
} else {
await enableNetP()
}
} else {
await disableNetP()
}
WidgetCenter.shared.reloadTimelines(ofKind: "VPNStatusWidget")
}
@MainActor
private func enableNetP() async {
await tunnelController.start()
}
@MainActor
private func disableNetP() async {
await tunnelController.stop()
}
@MainActor
func startSnooze() async {
guard !snoozeRequestPending, let activeSession = await tunnelController.activeSession() else {
return
}
let defaultDuration: TimeInterval = .minutes(20)
snoozeRequestPending = true
try? await activeSession.sendProviderMessage(.startSnooze(defaultDuration))
DailyPixel.fire(pixel: .networkProtectionSnoozeEnabledFromStatusMenu)
if #available(iOS 17.0, *) {
await VPNSnoozeLiveActivityManager().start(endDate: Date().addingTimeInterval(defaultDuration))
}
}
@MainActor
func cancelSnooze() async {
guard !snoozeRequestPending, let activeSession = await tunnelController.activeSession() else {
return
}
snoozeRequestPending = true
try? await activeSession.sendProviderMessage(.cancelSnooze)
DailyPixel.fire(pixel: .networkProtectionSnoozeDisabledFromStatusMenu)
if #available(iOS 17.0, *) {
await VPNSnoozeLiveActivityManager().endSnoozeActivity()
}
}
private class func titleText(status: ConnectionStatus) -> String {
switch status {
case .connected: return UserText.netPStatusHeaderTitleOn
case .snoozing: return UserText.netPStatusHeaderTitleSnoozed
case .notConfigured, .disconnected, .disconnecting, .connecting, .reasserting: return UserText.netPStatusHeaderTitleOff
}
}
private class func statusImageID(connected isConnected: Bool) -> String {
isConnected ? "VPN" : "VPNDisabled"
}
private static func timedConnectedStatusMessagePublisher(forConnectedDate connectedDate: Date) -> AnyPublisher<String, Never> {
Timer.publish(every: .seconds(1), on: .main, in: .default)
.autoconnect()
.map {
Self.connectedMessage(for: connectedDate, currentDate: $0)
}
.eraseToAnyPublisher()
}
private static func timedSnoozeDurationRemainingMessagePublisher(forSnoozeEndDate snoozeEndDate: Date) -> AnyPublisher<String, Never> {
Timer.publish(every: .seconds(1), on: .main, in: .default)
.autoconnect()
.map {
Self.snoozeDurationRemainingMessage(for: snoozeEndDate, currentDate: $0)
}
.eraseToAnyPublisher()
}
private static func message(for status: ConnectionStatus) -> String {
switch status {
case .disconnected, .notConfigured:
return UserText.netPStatusDisconnected
case .disconnecting:
return UserText.netPStatusDisconnecting
case .connected(connectedDate: let connectedDate):
return connectedMessage(for: connectedDate)
case .connecting, .reasserting:
return UserText.netPStatusConnecting
case .snoozing:
return UserText.netPStatusPaused
}
}
private static func connectedMessage(for connectedDate: Date, currentDate: Date = Date()) -> String {
let timeLapsedInterval = currentDate.timeIntervalSince(connectedDate)
let timeLapsed = Self.dateFormatter.string(from: timeLapsedInterval) ?? "00:00:00"
return UserText.netPStatusConnected(since: timeLapsed)
}
private static func snoozeDurationRemainingMessage(for snoozeEndDate: Date, currentDate: Date = Date()) -> String {
if snoozeEndDate <= currentDate {
return UserText.netPCellSnoozing
}
let timeRemainingInterval = snoozeEndDate.timeIntervalSince(currentDate)
let timeRemaining = Self.snoozeRemainingDateFormatter.string(from: timeRemainingInterval) ?? "00:00"
return UserText.netPStatusSnoozing(until: timeRemaining)
}
private func resetConnectionInformation() {
self.location = nil
self.ipAddress = nil
self.uploadTotal = nil
self.downloadTotal = nil
}
// MARK: - UI Events handling
@available(iOS 17.0, *)
func snoozeActionHandler(action: Tips.Action) {
if action.id == VPNUseSnoozeTip.ActionIdentifiers.learnMore.rawValue {
let url = URL(string: "https://duckduckgo.com/duckduckgo-help-pages/privacy-pro/vpn/troubleshooting/")!
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
@available(iOS 17.0, *)
@MainActor
func widgetActionHandler(action: Tips.Action) {
if action.id == VPNAddWidgetTip.ActionIdentifiers.addWidget.rawValue {
showAddWidgetEducationView = true
(vpnEnabledTips.currentTip as? VPNAddWidgetTip)?.invalidate(reason: .actionPerformed)
}
}
/// The user opened the VPN locations view
///
func handleUserOpenedVPNLocations() {
if #available(iOS 17.0, *) {
Task { @MainActor in
(vpnEnabledTips.currentTip as? VPNChangeLocationTip)?.invalidate(reason: .actionPerformed)
}
}
}
}
private extension ConnectionStatus {
var isConnected: Bool {
switch self {
case .connected:
return true
default:
return false
}
}
var isSnoozing: Bool {
switch self {
case .snoozing:
return true
default:
return false
}
}
var isLoading: Bool {
switch self {
case .connecting, .reasserting, .disconnecting:
return true
default:
return false
}
}
}