Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
SerhiiShovkoplias committed Jul 27, 2020
1 parent d1cab0c commit 78eeb50
Show file tree
Hide file tree
Showing 14 changed files with 238 additions and 81 deletions.
8 changes: 8 additions & 0 deletions MobileWallet.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,9 @@
37B48A8324B3968F00F8A8D2 /* BPKeychainWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37B48A8224B3968F00F8A8D2 /* BPKeychainWrapper.swift */; };
37B48A8424B3968F00F8A8D2 /* BPKeychainWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37B48A8224B3968F00F8A8D2 /* BPKeychainWrapper.swift */; };
37B48A8524B3968F00F8A8D2 /* BPKeychainWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37B48A8224B3968F00F8A8D2 /* BPKeychainWrapper.swift */; };
37B5289424CB1E16008C80EB /* NetworkSpeedProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37B5289324CB1E16008C80EB /* NetworkSpeedProvider.swift */; };
37B5289524CB1E16008C80EB /* NetworkSpeedProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37B5289324CB1E16008C80EB /* NetworkSpeedProvider.swift */; };
37B5289624CB1E16008C80EB /* NetworkSpeedProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37B5289324CB1E16008C80EB /* NetworkSpeedProvider.swift */; };
37BB696B245705D20013AC4D /* RadialGradientView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37BB696A245705D20013AC4D /* RadialGradientView.swift */; };
37BB696C245705E60013AC4D /* RadialGradientView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37BB696A245705D20013AC4D /* RadialGradientView.swift */; };
37BB696D245705E70013AC4D /* RadialGradientView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37BB696A245705D20013AC4D /* RadialGradientView.swift */; };
Expand Down Expand Up @@ -769,6 +772,7 @@
37B444A8248949B800592D92 /* Checkbox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Checkbox.swift; sourceTree = "<group>"; };
37B48A7E24B3312000F8A8D2 /* PasswordVerificationViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PasswordVerificationViewController.swift; sourceTree = "<group>"; };
37B48A8224B3968F00F8A8D2 /* BPKeychainWrapper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BPKeychainWrapper.swift; sourceTree = "<group>"; };
37B5289324CB1E16008C80EB /* NetworkSpeedProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkSpeedProvider.swift; sourceTree = "<group>"; };
37BB696A245705D20013AC4D /* RadialGradientView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RadialGradientView.swift; sourceTree = "<group>"; };
37BB6973245726FB0013AC4D /* CopyableLabel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CopyableLabel.swift; sourceTree = "<group>"; };
37C8BA342480F59B005BBC05 /* WaveEmojiAnimation.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = WaveEmojiAnimation.json; sourceTree = "<group>"; };
Expand Down Expand Up @@ -972,6 +976,7 @@
37765D2524A35BA20091AE2A /* AESEncryption.swift */,
37B48A8224B3968F00F8A8D2 /* BPKeychainWrapper.swift */,
372AECAA24B4A293005CBA0F /* UserDefaultsWrapper.swift */,
37B5289324CB1E16008C80EB /* NetworkSpeedProvider.swift */,
);
path = Common;
sourceTree = "<group>";
Expand Down Expand Up @@ -2250,6 +2255,7 @@
BFF1ED9D2408111000CC9EF6 /* SendingTariViewController.swift in Sources */,
3776080924B73500008167E8 /* Backup.swift in Sources */,
00369D7D24221ACB00BAB95B /* DeepLinkManager.swift in Sources */,
37B5289424CB1E16008C80EB /* NetworkSpeedProvider.swift in Sources */,
001F6CEC2381A39300FA7002 /* CompletedTransaction.swift in Sources */,
371A0818247290C000F97713 /* TransitionLabel.swift in Sources */,
00E2BCB2236B455900C2A105 /* HomeViewFloatingPanelDelegates.swift in Sources */,
Expand Down Expand Up @@ -2287,6 +2293,7 @@
0053873124065F6C00901A68 /* SlideView.swift in Sources */,
BFE61E4924226A7E003DC99D /* NotificationManager.swift in Sources */,
37049271247EA0770034EE5D /* RestoreWalletViewController.swift in Sources */,
37B5289524CB1E16008C80EB /* NetworkSpeedProvider.swift in Sources */,
0091D4AC23ED87BE004BF7F7 /* KeyServer.swift in Sources */,
004997BC2382F5ED000A0B7D /* WalletTestDataExtension.swift in Sources */,
3723A7AC24ACD03E003382EB /* PasswordField.swift in Sources */,
Expand Down Expand Up @@ -2530,6 +2537,7 @@
0074619D239A57B000F00966 /* UIBarButtonItem.swift in Sources */,
3776080B24B75900008167E8 /* Backup.swift in Sources */,
00434A9F2477D0B000C0104F /* AppContainerLock.swift in Sources */,
37B5289624CB1E16008C80EB /* NetworkSpeedProvider.swift in Sources */,
3708D758247FF81900807D72 /* SettingsParentViewController.swift in Sources */,
37547D5824601BF600EB59CC /* UIView+GlobalFrame.swift in Sources */,
375894C724865A6A00B58816 /* VerifyPhraseViewController.swift in Sources */,
Expand Down
99 changes: 58 additions & 41 deletions MobileWallet/Backup/ICloudBackup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ class ICloudBackup: NSObject {
}

try FileManager.default.copyItem(at: fileURL, to: walletFolderURL.appendingPathComponent(fileURL.lastPathComponent))

isLastBackupFailed = false
inProgress = true
progressValue = 0.0
BackupScheduler.shared.removeSchedule()
Expand Down Expand Up @@ -338,14 +338,15 @@ extension ICloudBackup {
if let fileUploaded = fileItem?.value(forAttribute: NSMetadataUbiquitousItemIsUploadedKey) as? Bool, fileUploaded == true, fileValues.ubiquitousItemIsUploading == false {
progressValue = 0.0
inProgress = false
isLastBackupFailed = false
notifyObservers(percent: 100, completed: true, error: nil)
try cleanTempDirectory()
query.disableUpdates()
} else if let error = fileValues.ubiquitousItemUploadingError {
progressValue = 0.0
inProgress = false
isLastBackupFailed = true
notifyObservers(percent: 0, completed: false, error: error)
query.disableUpdates()
} else {
if let fileProgress = fileItem?.value(forAttribute: NSMetadataUbiquitousItemPercentUploadedKey) as? Double {
progressValue = fileProgress
Expand All @@ -355,17 +356,20 @@ extension ICloudBackup {
} catch {
isLastBackupFailed = true
inProgress = false
notifyObservers(percent: 0, completed: false, error: ICloudBackupError.uploadToICloudFailure)
notifyObservers(percent: 0, completed: false, error: ICloudBackupError.noInternetConnection)
}
}

private func notifyObservers(percent: Double, started: Bool = false, completed: Bool, error: Error?) {
observers.allObjects.forEach {
if let object = $0 as? ICloudBackupObserver {
object.onUploadProgress(percent: percent, started: started, completed: completed, error: error)
}
if completed {
self.endBackgroundBackupTask()
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.observers.allObjects.forEach {
if let object = $0 as? ICloudBackupObserver {
object.onUploadProgress(percent: percent, started: started, completed: completed, error: error)
}
if completed {
self.endBackgroundBackupTask()
}
}
}
}
Expand Down Expand Up @@ -419,28 +423,35 @@ extension ICloudBackup {
// MARK: - private methods
extension ICloudBackup {
private func syncWithICloud() {
if isInternetConnected() {
query.operationQueue?.addOperation({ [weak self] in
_ = self?.query.start()
self?.query.enableUpdates()
})
} else {
if !inProgress { return }
query.stop()
inProgress = false
if isValidBackupExists() {
notifyObservers(percent: 100, completed: true, error: ICloudBackupError.uploadToICloudFailure)
checkNetworkConnection { [weak self] (connected) in
guard let self = self else { return }
if connected {
self.query.operationQueue?.addOperation({ [weak self] in
_ = self?.query.start()
self?.query.enableUpdates()
})
} else {
if !self.inProgress { return }
self.query.stop()
self.inProgress = false
self.isLastBackupFailed = true
self.notifyObservers(percent: 0, completed: false, error: ICloudBackupError.noInternetConnection)
}
}
}

private func isInternetConnected() -> Bool {
guard let reachability = self.reachability else { return false }
switch reachability.connection {
case .wifi, .cellular:
return true
case .unavailable, .none:
return false
private func checkNetworkConnection(completion: @escaping (_ connected: Bool) -> Void) {
let speedTest = NetworkSpeedProvider()
speedTest.testSpeed { (_ speed: Float, _ error: Error?) in
if speed <= 0 || error != nil { completion(false) }

guard let reachability = self.reachability else { completion(false); return }
switch reachability.connection {
case .wifi, .cellular:
completion(true)
case .unavailable, .none:
completion(false)
}
}
}

Expand Down Expand Up @@ -505,20 +516,26 @@ extension ICloudBackup {
let folderPath = backup.folderPath
// if the last path component contains the “.icloud” extension. If yes the file is not on the device else the file is already downloaded.
if lastPathComponent.contains(".icloud") {
if !isInternetConnected() { completion(nil, ICloudBackupError.noInternetConnection) }

lastPathComponent.removeFirst()
let downloadedFilePath = folderPath + "/" + lastPathComponent.replacingOccurrences(of: ".icloud", with: "")
try FileManager.default.startDownloadingUbiquitousItem(at: backup.url)

Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
if FileManager.default.fileExists(atPath: downloadedFilePath) {
timer.invalidate()
do {
let backup = try Backup(url: URL(fileURLWithPath: downloadedFilePath))
completion(backup, nil)
} catch {
completion(nil, error)
checkNetworkConnection { (connected) in
if !connected { completion(nil, ICloudBackupError.noInternetConnection) }

lastPathComponent.removeFirst()
let downloadedFilePath = folderPath + "/" + lastPathComponent.replacingOccurrences(of: ".icloud", with: "")
do {
try FileManager.default.startDownloadingUbiquitousItem(at: backup.url)
} catch {
completion(nil, ICloudBackupError.noInternetConnection)
}

Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
if FileManager.default.fileExists(atPath: downloadedFilePath) {
timer.invalidate()
do {
let backup = try Backup(url: URL(fileURLWithPath: downloadedFilePath))
completion(backup, nil)
} catch {
completion(nil, error)
}
}
}
}
Expand Down
19 changes: 11 additions & 8 deletions MobileWallet/Common/Extensions/LAContext.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ extension LAContext {
}
}

func authenticateUser(reason: AuthenticateUserReason = .logIn, onSuccess: @escaping () -> Void) {
func authenticateUser(reason: AuthenticateUserReason = .logIn, showFailedDialog: Bool = true, onSuccess: @escaping () -> Void) {
#if targetEnvironment(simulator)
//Skip auth on simulator, quicker for development
onSuccess()
Expand All @@ -91,15 +91,14 @@ extension LAContext {
[weak self] success, error in

DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
if success {
onSuccess()
} else {
if !showFailedDialog { return }
let localizedReason = error?.localizedDescription ?? NSLocalizedString("authentication.fail.description", comment: "Authentication")
TariLogger.error("Biometrics auth failed", error: error)
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.authenticationFailedAlertOptions(reason: localizedReason, onSuccess: onSuccess)
}
self.authenticationFailedAlertOptions(reason: localizedReason, onSuccess: onSuccess)
}
}
}
Expand All @@ -125,24 +124,28 @@ extension LAContext {

private func authenticationFailedAlertOptions(reason: String, onSuccess: @escaping () -> Void) {
let alert = UIAlertController(title: NSLocalizedString("authentication.fail.title", comment: "Authentication"), message: reason, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Try again", comment: "Authentication"), style: .default, handler: { [weak self] _ in
alert.addAction(UIAlertAction(title: NSLocalizedString("authentication.try_again", comment: "Authentication"), style: .default, handler: { [weak self] _ in
guard let self = self else { return }
self.authenticateUser(onSuccess: onSuccess)
}))

alert.addAction(UIAlertAction(title: NSLocalizedString("authentication.action.open_settings", comment: "Authentication"), style: .default, handler: { [weak self] _ in
guard let self = self else { return }
self.openAppSettings()
if self.openAppSettings() {
self.authenticationFailedAlertOptions(reason: reason, onSuccess: onSuccess)
}
}))

if let topController = UIApplication.shared.topController() {
topController.present(alert, animated: true, completion: nil)
}
}

private func openAppSettings() {
private func openAppSettings() -> Bool {
if let appSettings = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(appSettings)
return true
}
return false
}
}
9 changes: 2 additions & 7 deletions MobileWallet/Common/Extensions/UIApplication+KeyWindow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,11 @@ import UIKit

extension UIApplication {
var keyWindow: UIWindow? {
return UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first
return UIApplication.shared.windows.filter({$0.isKeyWindow}).first
}

func topController() -> UIViewController? {
if var topController = UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.rootViewController {
if var topController = keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ extension UIScrollView {

func beginRefreshing() {
guard let refreshControl = refreshControl, !refreshControl.isRefreshing else { return }
let refreshControlHeight: CGFloat = 60.0 // static because if fast drag tableView refreshControl height will not correct
let refreshControlHeight: CGFloat = 70.0 // static because if fast drag tableView refreshControl height will not correct
let contentOffset = CGPoint(x: 0, y: -refreshControlHeight - contentInset.top)
refreshControl.beginRefreshing()
refreshControl.sendActions(for: .valueChanged)
Expand Down
88 changes: 88 additions & 0 deletions MobileWallet/Common/NetworkSpeedProvider.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// NetworkSpeedProvider.swift

/*
Package MobileWallet
Created by S.Shovkoplyas on 24.07.2020
Using Swift 5.0
Running on macOS 10.15
Copyright 2019 The Tari Project
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of
its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import Foundation

class NetworkSpeedProvider: NSObject {

typealias SpeedTestCompletion = (_ megabytesPerSecond: Float, _ error: Error?) -> Void

private var startTime = CFAbsoluteTime()
private var stopTime = CFAbsoluteTime()
private var bytesReceived: Float = 0
private var speedTestCompletionHandler: SpeedTestCompletion?

func testSpeed(completion: @escaping SpeedTestCompletion) {
testDownloadSpeed(withTimout: 5.0, completionHandler: completion)
}
}

extension NetworkSpeedProvider: URLSessionDataDelegate, URLSessionDelegate {
func testDownloadSpeed(withTimout timeout: TimeInterval, completionHandler: @escaping SpeedTestCompletion) {
let urlForSpeedTest = URL(string: "https://images.apple.com/v/imac-with-retina/a/images/overview/5k_image.jpg")
startTime = CFAbsoluteTimeGetCurrent()
stopTime = startTime
bytesReceived = 0
speedTestCompletionHandler = completionHandler
let configuration = URLSessionConfiguration.ephemeral
configuration.timeoutIntervalForResource = timeout
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

guard let checkedUrl = urlForSpeedTest else { return }

session.dataTask(with: checkedUrl).resume()
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
bytesReceived += Float(data.count)
stopTime = CFAbsoluteTimeGetCurrent()
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
let elapsed = (stopTime - startTime) //as? CFAbsoluteTime
let speed: Float = elapsed != 0 ? bytesReceived / (Float(CFAbsoluteTimeGetCurrent() - startTime)) / 1024.0 / 1024.0 : -1.0
// treat timeout as no error (as we're testing speed, not worried about whether we got entire resource or not
if error == nil || ((((error as NSError?)?.domain) == NSURLErrorDomain) && (error as NSError?)?.code == NSURLErrorTimedOut) {
speedTestCompletionHandler?(speed, nil)
} else {
speedTestCompletionHandler?(speed, error)
}
}
}

0 comments on commit 78eeb50

Please sign in to comment.