AppPreferences.swift 7.88 KB
Newer Older
Davide De Rosa's avatar
Davide De Rosa committed
1
2
3
4
5
6
7
8
9
10
//
//  AppPreferences.swift
//  PIA VPN
//
//  Created by Davide De Rosa on 12/16/17.
//  Copyright © 2017 London Trust Media. All rights reserved.
//

import Foundation
import PIALibrary
11
import PIATunnel
Davide De Rosa's avatar
Davide De Rosa committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import SwiftyBeaver

private let log = SwiftyBeaver.self

class AppPreferences {
    private struct Entries {
        static let version = "Version"
        
        static let launched = "Launched" // discard 2.2 key and invert logic
        
        static let seenContentBlocker = "SeenContentBlocker"
        
        static let didAskToEnableNotifications = "DidAskToEnableNotifications"

        static let themeCode = "Theme" // reuse 2.2 key

        static let lastVPNConnectionStatus = "LastVPNConnectionStatus"
29
30

        static let piaSocketType = "PIASocketType"
Davide De Rosa's avatar
Davide De Rosa committed
31
32
33
34
    }

    static let shared = AppPreferences()
    
35
    private static let currentVersion = "5.0"
Davide De Rosa's avatar
Davide De Rosa committed
36
37
38
    
    private let defaults: UserDefaults

39
40
    private var isTransitioningTheme = false
    
Davide De Rosa's avatar
Davide De Rosa committed
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
    var wasLaunched: Bool {
        get {
            return defaults.bool(forKey: Entries.launched)
        }
        set {
            defaults.set(newValue, forKey: Entries.launched)
        }
    }
    
    var didSeeContentBlocker: Bool {
        get {
            return defaults.bool(forKey: Entries.seenContentBlocker)
        }
        set {
            defaults.set(newValue, forKey: Entries.seenContentBlocker)
        }
    }
    
    var didAskToEnableNotifications: Bool {
        get {
            return defaults.bool(forKey: Entries.didAskToEnableNotifications)
        }
        set {
            defaults.set(newValue, forKey: Entries.didAskToEnableNotifications)
        }
    }
    
    var currentThemeCode: ThemeCode {
        get {
            let rawCode = defaults.integer(forKey: Entries.themeCode)
            return ThemeCode(rawValue: rawCode) ?? .light
        }
        set {
            defaults.set(newValue.rawValue, forKey: Entries.themeCode)
        }
    }
    
    var lastVPNConnectionStatus: VPNStatus {
        get {
            guard let rawValue = defaults.string(forKey: Entries.lastVPNConnectionStatus) else {
                return .disconnected
            }
            return VPNStatus(rawValue: rawValue) ?? .disconnected
        }
        set {
            defaults.set(newValue.rawValue, forKey: Entries.lastVPNConnectionStatus)
        }
    }
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    
    // nil = automatic
    var piaSocketType: PIATunnelProvider.SocketType? {
        get {
            guard let rawValue = defaults.string(forKey: Entries.piaSocketType) else {
                return nil
            }
            return PIATunnelProvider.SocketType(rawValue: rawValue)
        }
        set {
            if let rawValue = newValue?.rawValue {
                defaults.set(rawValue, forKey: Entries.piaSocketType)
            } else {
                defaults.removeObject(forKey: Entries.piaSocketType)
            }
        }
    }
Davide De Rosa's avatar
Davide De Rosa committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

    private init() {
        guard let defaults = UserDefaults(suiteName: AppConstants.appGroup) else {
            fatalError("Unable to initialize app preferences")
        }
        self.defaults = defaults

        defaults.register(defaults: [
            Entries.version: AppPreferences.currentVersion,
            Entries.launched: false,
            Entries.didAskToEnableNotifications: false,
            Entries.themeCode: ThemeCode.light.rawValue
        ])
    }
    
121
    private func refreshAPIToken() {
122
        if Client.preferences.authMigrationSuccess == false {
123
124
125
126
            Client.providers.accountProvider.refreshAndLogoutUnauthorized(force: true)
        }
    }
    
Jose Blaya's avatar
Jose Blaya committed
127
128
129
130
131
132
133
134
135
136
    private func migrateAPItoV2() {
        // Migrate users from v1 to v2
        log.debug("Migration to api v2")
        //For v1 we stored the username in the plain database. We move the value to the keychain database.
        //After refresh the account, the token will be generated
        if let oldUsername = defaults.string(forKey: "LoggedUsername"),
            let _ = try? PIALibrary.Keychain(team: AppConstants.teamId,
                                             group: AppConstants.appGroup).password(for: oldUsername) {
            //User is loggedIn
            try? PIALibrary.Keychain().set(username: oldUsername)
Jose Blaya's avatar
Jose Blaya committed
137
            try? PIALibrary.Keychain().set(publicUsername: oldUsername)
Jose Blaya's avatar
Jose Blaya committed
138
139
140
141
142
            defaults.removeObject(forKey: "LoggedUsername")
            defaults.synchronize()
        }
    }
    
Davide De Rosa's avatar
Davide De Rosa committed
143
144
145
    func migrate() {
        let oldVersion = defaults.string(forKey: Entries.version)
        defaults.set(AppPreferences.currentVersion, forKey: Entries.version)
146
        
Davide De Rosa's avatar
Davide De Rosa committed
147
        guard (oldVersion == nil) else {
148
149
            if oldVersion != AppPreferences.currentVersion ||
                !Client.preferences.authMigrationSuccess { //First time for each update or if the auth token has not been updated
Jose Blaya's avatar
Jose Blaya committed
150
                migrateAPItoV2()
151
                refreshAPIToken()
Jose Blaya's avatar
Jose Blaya committed
152
            }
Davide De Rosa's avatar
Davide De Rosa committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
            return
        }

        // new install or app version < 2.1
        let oldDefaults = UserDefaults.standard
        
        // migrate username to new key
        let legacyUsername = oldDefaults.string(forKey: "Username")
        var maybeLoggedUsername = oldDefaults.string(forKey: "LoggedUsername")
        if ((legacyUsername != nil) && (maybeLoggedUsername == nil)) {
            oldDefaults.removeObject(forKey: "Username")
            maybeLoggedUsername = legacyUsername
        }
        
        // no old login means logged out or new install, no migration needed
        guard let loggedUsername = maybeLoggedUsername else {
            return
        }
        
        // otherwise, app version < 2.1 (local defaults/keychain)
        
        // it used to be here in app version <= 2.0
175
176
        let oldKeychain = PIALibrary.Keychain()
        let newKeychain = PIALibrary.Keychain(team: AppConstants.teamId, group: AppConstants.appGroup)
Davide De Rosa's avatar
Davide De Rosa committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
        
        // migrate credentials from local to shared keychain
        if let legacyPassword = try? oldKeychain.password(for: loggedUsername) {
            oldDefaults.removeObject(forKey: "Username")
            oldDefaults.removeObject(forKey: "LoggedUsername")
            oldKeychain.removePassword(for: loggedUsername)
            
            // store to new defaults/keychain
            defaults.set(loggedUsername, forKey: "LoggedUsername")
            try? newKeychain.set(password: legacyPassword, for: loggedUsername)
        }
        
        // migrate settings
        wasLaunched = !oldDefaults.bool(forKey: "FirstLaunch")
        didAskToEnableNotifications = oldDefaults.bool(forKey: Entries.didAskToEnableNotifications)
        
        // discard these, will be fetched on login
//        NSString *subscriptionExpirationDate = [oldDefaults objectForKey:@"SubscriptionExpirationDate"];
//        NSString *subscriptionPlan = [oldDefaults objectForKey:@"SubscriptionPlan"];
        oldDefaults.removeObject(forKey: "SubscriptionExpirationDate")
        oldDefaults.removeObject(forKey: "SubscriptionPlan")
Jose Blaya's avatar
Jose Blaya committed
198
199
200
        
        migrateAPItoV2()
        
Davide De Rosa's avatar
Davide De Rosa committed
201
202
203
    }

    func reset() {
204
205
        piaSocketType = nil
        transitionTheme(to: .light)
Davide De Rosa's avatar
Davide De Rosa committed
206
207
208
    }
    
//    + (void)eraseForTesting;
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

    func transitionTheme(to code: ThemeCode) {
        guard !isTransitioningTheme else {
            return
        }
        guard (code != AppPreferences.shared.currentThemeCode) else {
            return
        }
        
        AppPreferences.shared.currentThemeCode = code
        guard let window = UIApplication.shared.windows.first else {
            fatalError("No window?")
        }
        isTransitioningTheme = true
        UIView.animate(withDuration: AppConfiguration.Animations.duration, animations: {
            window.alpha = 0.0
        }, completion: { (success) in
            code.apply(theme: Theme.current, reload: true)
            
            UIView.animate(withDuration: AppConfiguration.Animations.duration) {
                window.alpha = 1.0
                self.isTransitioningTheme = false
            }
        })
    }
Davide De Rosa's avatar
Davide De Rosa committed
234
}