Skip to content

Commit

Permalink
fix: save and download issue
Browse files Browse the repository at this point in the history
  • Loading branch information
riderx committed Jun 25, 2022
1 parent 6ea750f commit d325ec9
Show file tree
Hide file tree
Showing 5 changed files with 104 additions and 30 deletions.
9 changes: 4 additions & 5 deletions ios/Plugin/CapacitorUpdater.swift
Original file line number Diff line number Diff line change
Expand Up @@ -414,12 +414,11 @@ extension CustomError: LocalizedError {
public func getVersionInfo(folder: String = VersionInfo.VERSION_BUILTIN) -> VersionInfo {
print("\(self.TAG) Getting info for [\(folder)]")
if(VersionInfo.VERSION_BUILTIN == folder) {
// (version: String, status: VersionStatus, downloaded: Date, name: String)
return VersionInfo(folder: folder, versionName: "", status: VersionStatus.SUCCESS)
}
do {
let result: VersionInfo = try UserDefaults.standard.getObject(forKey: "\(folder)\(self.INFO_SUFFIX)", castTo: VersionInfo.self)
print("\(self.TAG) Returning info [\(folder)]", result)
let result: VersionInfo = try UserDefaults.standard.getObj(forKey: "\(folder)\(self.INFO_SUFFIX)", castTo: VersionInfo.self)
print("\(self.TAG) Returning info [\(folder)]", result.toString())
return result
} catch {
print("\(self.TAG) Failed to parse version info for [\(folder)]", error.localizedDescription)
Expand Down Expand Up @@ -448,12 +447,12 @@ extension CustomError: LocalizedError {
}
if(info == nil) {
print("\(self.TAG) Removing info for folder [\(folder)]")
UserDefaults.standard.removeObject(forKey: "\(folder)\(INFO_SUFFIX)")
UserDefaults.standard.removeObject(forKey: "\(folder)\(self.INFO_SUFFIX)")
} else {
let update = info!.setFolder(folder: folder)
print("\(self.TAG) Storing info for folder [\(folder)]", update.toString())
do {
try UserDefaults.standard.setObject(update.toString(), forKey: "\(folder)\(self.INFO_SUFFIX)")
try UserDefaults.standard.setObj(update, forKey: "\(folder)\(self.INFO_SUFFIX)")
} catch {
print("\(self.TAG) Failed to save version info for [\(folder)]", error.localizedDescription)
}
Expand Down
45 changes: 30 additions & 15 deletions ios/Plugin/CapacitorUpdaterPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin {
}

@objc func notifyDownload(folder: String, percent: Int) {
let version = self.implementation.getVersionInfo(folder: folder).toJSON()
self.notifyListeners("download", data: ["percent": percent, "version": version])
let version = self.implementation.getVersionInfo(folder: folder)
self.notifyListeners("download", data: ["percent": percent, "version": version.toJSON()])
}

@objc func getId(_ call: CAPPluginCall) {
Expand All @@ -88,14 +88,21 @@ public class CapacitorUpdaterPlugin: CAPPlugin {
}

@objc func download(_ call: CAPPluginCall) {
let url = URL(string: call.getString("url") ?? "")
let versionName: String = call.getString("versionName") ?? ""
guard let urlString = call.getString("url") else {
print("\(self.implementation.TAG) Download called without url")
call.reject("Download called without folder")
return
}
guard let versionName = call.getString("versionName") else {
print("\(self.implementation.TAG) Download called without versionName")
call.reject("Download called without versionName")
return
}
let url = URL(string: urlString)
print("\(self.implementation.TAG) Downloading \(url!)")
do {
let res = try implementation.download(url: url!, versionName: versionName)
call.resolve([
"version": res
])
call.resolve(res.toJSON())
} catch {
call.reject("download failed", error.localizedDescription)
}
Expand Down Expand Up @@ -124,12 +131,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin {

@objc func next(_ call: CAPPluginCall) {
guard let folder = call.getString("folder") else {
print("\(self.implementation.TAG) Next call version missing")
call.reject("Next called without version")
print("\(self.implementation.TAG) Next called without folder")
call.reject("Next called without folder")
return
}
guard let versionName = call.getString("versionName") else {
print("\(self.implementation.TAG) Next call versionName missing")
print("\(self.implementation.TAG) Next called without versionName")
call.reject("Next called without versionName")
return
}
Expand All @@ -147,8 +154,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin {

@objc func set(_ call: CAPPluginCall) {
guard let folder = call.getString("folder") else {
print("\(self.implementation.TAG) Set called without version")
call.reject("Next call version missing")
print("\(self.implementation.TAG) Set called without folder")
call.reject("Set called without folder")
return
}
let res = implementation.set(folder: folder)
Expand All @@ -162,7 +169,11 @@ public class CapacitorUpdaterPlugin: CAPPlugin {
}

@objc func delete(_ call: CAPPluginCall) {
let folder = call.getString("folder") ?? ""
guard let folder = call.getString("folder") else {
print("\(self.implementation.TAG) Delete called without version")
call.reject("Delete called without folder")
return
}
let res = implementation.delete(folder: folder)
if (res) {
call.resolve()
Expand All @@ -173,8 +184,12 @@ public class CapacitorUpdaterPlugin: CAPPlugin {

@objc func list(_ call: CAPPluginCall) {
let res = implementation.list()
var resArr: [[String: String]] = []
for v in res {
resArr.append(v.toJSON())
}
call.resolve([
"versions": res
"versions": resArr
])
}

Expand Down Expand Up @@ -368,7 +383,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin {
print("\(self.implementation.TAG) Did you forget to call 'notifyAppReady()' in your Capacitor App code?")

self.notifyListeners("updateFailed", data: [
"version": current
"version": current.toJSON()
])
self.implementation.sendStats(action: "revert", version: current);
if (!fallback.isBuiltin() && !(fallback == current)) {
Expand Down
72 changes: 65 additions & 7 deletions ios/Plugin/ObjectPreferences.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,22 @@
import Foundation

protocol ObjectSavable {
func setObject<Object>(_ object: Object, forKey: String) throws where Object: Encodable
func getObject<Object>(forKey: String, castTo type: Object.Type) throws -> Object where Object: Decodable
func setObj<Object>(_ object: Object, forKey: String) throws where Object: Encodable
func getObj<Object>(forKey: String, castTo type: Object.Type) throws -> Object where Object: Decodable
}

enum ObjectSavableError: String, LocalizedError {
case unableToEncode = "Unable to encode object into data"
case noValue = "No data object found for the given key"
case unableToDecode = "Unable to decode object into given type"

var errorDescription: String? {
rawValue
}
}

extension UserDefaults: ObjectSavable {
func setObject<Object>(_ object: Object, forKey: String) throws where Object: Encodable {
func setObj<Object>(_ object: Object, forKey: String) throws where Object: Encodable {
let encoder = JSONEncoder()
do {
let data = try encoder.encode(object)
Expand All @@ -32,9 +32,11 @@ extension UserDefaults: ObjectSavable {
throw ObjectSavableError.unableToEncode
}
}

func getObject<Object>(forKey: String, castTo type: Object.Type) throws -> Object where Object: Decodable {

func getObj<Object>(forKey: String, castTo type: Object.Type) throws -> Object where Object: Decodable {
print("forKey", forKey)
guard let data = data(forKey: forKey) else { throw ObjectSavableError.noValue }
print("data", data)
let decoder = JSONDecoder()
do {
let object = try decoder.decode(type, from: data)
Expand All @@ -43,4 +45,60 @@ extension UserDefaults: ObjectSavable {
throw ObjectSavableError.unableToDecode
}
}
}
}

//
//// MARK: - Methods
//public extension UserDefaults {
// /// SwifterSwift: get object from UserDefaults by using subscript.
// ///
// /// - Parameter key: key in the current user's defaults database.
// subscript(key: String) -> Any? {
// get {
// return object(forKey: key)
// }
// set {
// set(newValue, forKey: key)
// }
// }
//
// /// SwifterSwift: Float from UserDefaults.
// ///
// /// - Parameter key: key to find float for.
// /// - Returns: Float object for key (if exists).
// func float(forKey key: String) -> Float? {
// return object(forKey: key) as? Float
// }
//
// /// SwifterSwift: Date from UserDefaults.
// ///
// /// - Parameter key: key to find date for.
// /// - Returns: Date object for key (if exists).
// func date(forKey key: String) -> Date? {
// return object(forKey: key) as? Date
// }
//
// /// SwifterSwift: Retrieves a Codable object from UserDefaults.
// ///
// /// - Parameters:
// /// - type: Class that conforms to the Codable protocol.
// /// - key: Identifier of the object.
// /// - decoder: Custom JSONDecoder instance. Defaults to `JSONDecoder()`.
// /// - Returns: Codable object for key (if exists).
// func object<T: Codable>(_ type: T.Type, with key: String, usingDecoder decoder: JSONDecoder = JSONDecoder()) -> T? {
// guard let data = value(forKey: key) as? Data else { return nil }
// return try? decoder.decode(type.self, from: data)
// }
//
// /// SwifterSwift: Allows storing of Codable objects to UserDefaults.
// ///
// /// - Parameters:
// /// - object: Codable object to store.
// /// - key: Identifier of the object.
// /// - encoder: Custom JSONEncoder instance. Defaults to `JSONEncoder()`.
// func set<T: Codable>(object: T, forKey key: String, usingEncoder encoder: JSONEncoder = JSONEncoder()) {
// let data = try? encoder.encode(object)
// set(data, forKey: key)
// }
//}
//
6 changes: 4 additions & 2 deletions ios/Plugin/VersionInfo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import Foundation


@objc public class VersionInfo: NSObject, Decodable {
@objc public class VersionInfo: NSObject, Decodable, Encodable {
public static let VERSION_BUILTIN: String = "builtin"
public static let VERSION_UNKNOWN: String = "unknown"
public static let DOWNLOADED_BUILTIN: String = "1970-01-01T00:00:00.000Z"
Expand All @@ -13,10 +13,12 @@ import Foundation
private let status: VersionStatus

convenience init(folder: String, versionName: String, status: VersionStatus, downloaded: Date) {
print("downloaded", downloaded.iso8601withFractionalSeconds)
self.init(folder: folder, versionName: versionName, status: status, downloaded: downloaded.iso8601withFractionalSeconds)
}

init(folder: String, versionName: String, status: VersionStatus, downloaded: String = VersionInfo.DOWNLOADED_BUILTIN) {
print("downloaded", downloaded)
self.downloaded = downloaded.trim()
self.folder = folder
self.versionName = versionName
Expand Down Expand Up @@ -89,6 +91,6 @@ import Foundation
}

public func toString() -> String {
return "{ downloaded: \"\(self.getDownloaded())\", folder: \"\(self.getFolder())\", versionName: \"\(self.getVersionName())\", status: \"\(self.getStatus())\"}"
return "{ \"downloaded\": \"\(self.getDownloaded())\", \"folder\": \"\(self.getFolder())\", \"versionName\": \"\(self.getVersionName())\", \"status\": \"\(self.getStatus())\"}"
}
}
2 changes: 1 addition & 1 deletion ios/Plugin/VersionStatus.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func ==(lhs:LocalizedString, rhs:LocalizedString) -> Bool {
return lhs.v == rhs.v
}

enum VersionStatus: LocalizedString, Decodable {
enum VersionStatus: LocalizedString, Decodable, Encodable {
case SUCCESS = "success"
case ERROR = "error"
case PENDING = "pending"
Expand Down

0 comments on commit d325ec9

Please sign in to comment.