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

import Foundation
import PIALibrary
import PIATunnel
import SwiftyBeaver
import iRate
#if PIA_DEV
import HockeySDK
16
import Firebase
17 18
import Fabric
import Crashlytics
Davide De Rosa's avatar
Davide De Rosa committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#endif

class Bootstrapper {
    static let shared = Bootstrapper()
    
    private init() {
    }
    
    private var isSimulator: Bool {
        #if arch(i386) || arch(x86_64)
            return true
        #else
            return false
        #endif
    }

    func bootstrap() {
36
        
Davide De Rosa's avatar
Davide De Rosa committed
37
        let console = ConsoleDestination()
Davide De Rosa's avatar
Davide De Rosa committed
38
        #if PIA_DEV
Davide De Rosa's avatar
Davide De Rosa committed
39
        console.minLevel = .debug
40 41 42 43 44 45 46 47 48 49 50 51
        let hockey = BITHockeyManager.shared()
        hockey.isMetricsManagerDisabled = true
        hockey.configure(withIdentifier: AppConstants.hockeyAppId)
        hockey.start()
        
        if let path = Bundle.main.url(forResource: "GoogleService-Info", withExtension: "plist"),
            let plist = NSDictionary(contentsOf: path) as? [String: Any],
            plist.count > 0 {
            FirebaseApp.configure()
            Fabric.sharedSDK().debug = true
            Fabric.with([Crashlytics.self()])
        }
Davide De Rosa's avatar
Davide De Rosa committed
52 53 54
        #else
        console.minLevel = .info
        #endif
Davide De Rosa's avatar
Davide De Rosa committed
55
        SwiftyBeaver.addDestination(console)
56 57 58 59

        // Load the database first
        Client.database = Client.Database(team: AppConstants.teamId, group: AppConstants.appGroup)

60 61 62 63 64 65
        // Check if should clean the account after delete the app and install again
        if Client.providers.accountProvider.shouldCleanAccount {
            //If first install, we need to ensure we don't have data from previous sessions in the Secure Keychain
            Client.providers.accountProvider.cleanDatabase()
        }

66 67
        AppPreferences.shared.migrate()

Davide De Rosa's avatar
Davide De Rosa committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81
        // PIALibrary
        
        guard let bundledRegionsURL = AppConstants.Regions.bundleURL else {
            fatalError("Could not find bundled regions file")
        }
        let bundledServersJSON: Data
        do {
            try bundledServersJSON = Data(contentsOf: bundledRegionsURL)
        } catch let e {
            fatalError("Could not parse bundled regions file: \(e)")
        }

        Client.environment = AppConfiguration.clientEnvironment
        Client.configuration.isDevelopment = Flags.shared.usesDevelopmentClient
82 83 84
        if let stagingUrl = AppConstants.Web.stagingEndpointURL {
            Client.configuration.setBaseURL(stagingUrl.absoluteString, for: .staging)
        }
85 86 87 88 89
        if Client.configuration.isDevelopment, let customServers = AppConstants.Servers.customServers {
            for server in customServers {
                Client.configuration.addCustomServer(server)
            }
        }
90
        
Davide De Rosa's avatar
Davide De Rosa committed
91 92 93 94 95 96 97
        Client.configuration.enablesConnectivityUpdates = true
        Client.configuration.enablesServerUpdates = true
        Client.configuration.enablesServerPings = true
        Client.configuration.bundledServersJSON = bundledServersJSON
        Client.configuration.webTimeout = AppConfiguration.ClientConfiguration.webTimeout
        Client.configuration.vpnProfileName = AppConfiguration.VPN.profileName
        Client.configuration.addVPNProfile(PIATunnelProfile(bundleIdentifier: AppConstants.Extensions.tunnelBundleIdentifier))
98
        
Davide De Rosa's avatar
Davide De Rosa committed
99 100 101
        let defaults = Client.preferences.defaults
        defaults.isPersistentConnection = true
        defaults.mace = false
Davide De Rosa's avatar
Davide De Rosa committed
102
        defaults.vpnType = PIATunnelProfile.vpnType
Davide De Rosa's avatar
Davide De Rosa committed
103 104 105
        defaults.vpnCustomConfigurations = [
            PIATunnelProfile.vpnType: AppConfiguration.VPN.piaDefaultConfigurationBuilder.build()
        ]
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
        Client.providers.accountProvider.updatePlanProductIdentifiers { [weak self] (products, error) in
            
            if let _ = error {
                self?.setDefaultPlanProducts()
            }
            
            if let products = products,
                products.count > 0 {
                for product in products {
                    if product.legacy {
                        if product.plan == .monthly {
                            Client.configuration.setPlan(.legacyMonthly, forProductIdentifier: product.identifier)
                        } else if product.plan == .yearly {
                            Client.configuration.setPlan(.legacyYearly, forProductIdentifier: product.identifier)
                        }
                    } else {
                        Client.configuration.setPlan(product.plan, forProductIdentifier: product.identifier)
                    }
                }
            }

            Client.refreshProducts()
            
        }
Davide De Rosa's avatar
Davide De Rosa committed
131

132
        if (self.isSimulator || Flags.shared.usesMockVPN) {
Davide De Rosa's avatar
Davide De Rosa committed
133 134 135 136 137 138 139 140 141 142
            Client.configuration.enablesConnectivityUpdates = false
            Client.useMockVPNProvider()
        }
        if Flags.shared.usesMockInApp {
            Client.useMockInAppProvider()
        }
        if Flags.shared.usesMockAccount {
            Client.useMockAccountProvider(AppConfiguration.Mock.accountProvider)
        }
        
143 144 145
        Client.bootstrap()
        
        // Preferences
146
        
Davide De Rosa's avatar
Davide De Rosa committed
147
        let pref = Client.preferences.editable()
148 149
        
        // as per App Store guidelines
150
        if !Flags.shared.enablesMACESetting {
Davide De Rosa's avatar
Davide De Rosa committed
151 152
            pref.mace = false
        }
153
        
Davide De Rosa's avatar
Davide De Rosa committed
154
        pref.commit()
155
        
Davide De Rosa's avatar
Davide De Rosa committed
156 157 158
        // Business objects
        
        AccountObserver.shared.start()
159 160
        //        DataCounter.shared.startCounting()
        
Davide De Rosa's avatar
Davide De Rosa committed
161 162 163 164 165 166 167 168 169 170 171 172 173
        // Third parties
        
        let rater = iRate.sharedInstance()!
        rater.usesUntilPrompt = AppConfiguration.Rating.usesUntilPrompt
        rater.eventsUntilPrompt = AppConfiguration.Rating.eventsUntilPrompt
        rater.daysUntilPrompt = AppConfiguration.Rating.daysUntilPrompt
        rater.remindPeriod = AppConfiguration.Rating.remindPeriod
        
        // Notifications
        
        let nc = NotificationCenter.default
        nc.addObserver(self, selector: #selector(reloadTheme), name: .PIAThemeDidChange, object: nil)
        nc.addObserver(self, selector: #selector(vpnStatusDidChange(notification:)), name: .PIADaemonsDidUpdateVPNStatus, object: nil)
174 175 176
        nc.addObserver(self, selector: #selector(internetUnreachable(notification:)), name: .ConnectivityDaemonDidGetUnreachable, object: nil)
        nc.addObserver(self, selector: #selector(internetReachable(notification:)), name: .ConnectivityDaemonDidGetReachable, object: nil)
        
Davide De Rosa's avatar
Davide De Rosa committed
177 178 179
        // PIALibrary (Theme)
        
        AppPreferences.shared.currentThemeCode.apply(theme: Theme.current, reload: true)
180
        
Davide De Rosa's avatar
Davide De Rosa committed
181 182 183 184
        // show walkthrough on upgrade except for logged in users
        if Client.providers.accountProvider.isLoggedIn {
            AppPreferences.shared.wasLaunched = true
        }
185

Davide De Rosa's avatar
Davide De Rosa committed
186
    }
187 188 189 190 191 192 193
    
    private func setDefaultPlanProducts() {
        Client.configuration.setPlan(.yearly, forProductIdentifier: AppConstants.InApp.yearlyProductIdentifier)
        Client.configuration.setPlan(.monthly, forProductIdentifier: AppConstants.InApp.monthlyProductIdentifier)
        Client.configuration.setPlan(.legacyYearly, forProductIdentifier: AppConstants.LegacyInApp.yearlyProductIdentifier)
        Client.configuration.setPlan(.legacyMonthly, forProductIdentifier: AppConstants.LegacyInApp.monthlyProductIdentifier)
    }
Davide De Rosa's avatar
Davide De Rosa committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211

    func dispose() {
        Client.dispose()
    }
    
    // MARK: Notifications

    @objc private func reloadTheme() {
        Theme.current.applySideMenu()
        Theme.current.applyAppearance()
    }
    
    @objc private func vpnStatusDidChange(notification: Notification) {
        guard (Client.providers.vpnProvider.vpnStatus == .connected) else {
            return
        }
        iRate.sharedInstance()!.logEvent(false)
    }
212 213 214 215 216 217 218 219 220
    
    @objc private func internetReachable(notification: Notification) {
        Macros.removeStickyNote()
    }
    
    @objc private func internetUnreachable(notification: Notification) {
        Macros.displayStickyNote(withMessage: L10n.Global.unreachable,
                                 andImage: Asset.iconWarning.image)
    }
Davide De Rosa's avatar
Davide De Rosa committed
221
}