Skip to content

Commit

Permalink
feat: add just and reload
Browse files Browse the repository at this point in the history
  • Loading branch information
riderx committed Nov 22, 2021
1 parent fed83c7 commit b9b17cb
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 123 deletions.
1 change: 1 addition & 0 deletions CapacitorUpdater.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ Pod::Spec.new do |s|
s.ios.deployment_target = '12.0'
s.dependency 'Capacitor'
s.dependency 'SSZipArchive'
s.dependency 'Just'
s.swift_version = '5.1'
end
145 changes: 26 additions & 119 deletions ios/Plugin/CapacitorUpdater.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import Foundation
import SSZipArchive
import Just

extension FileManager {

open func secureCopyItem(at srcURL: URL, to dstURL: URL) -> Bool {
do {
if FileManager.default.fileExists(atPath: dstURL.path) {
Expand All @@ -14,114 +15,6 @@ extension FileManager {
}
return true
}

}

class FileDownloader {


static func listFiles(url: URL)
{
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
print(directoryContents)

// if you want to filter the directory contents you can do like this:
let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
print("mp3 urls:",mp3Files)
let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
print("mp3 list:", mp3FileNames)

} catch {
print(error)
}
}

static func loadFileSync(url: URL, dest: String, completion: @escaping (String?, Error?) -> Void)
{
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

let destinationUrl = documentsUrl.appendingPathComponent(dest)

if FileManager().fileExists(atPath: destinationUrl.path)
{
print("File already exists [\(destinationUrl.path)]")
completion(destinationUrl.path, nil)
}
else if let dataFromURL = NSData(contentsOf: url)
{
if dataFromURL.write(to: destinationUrl, atomically: true)
{
print("file saved [\(destinationUrl.path)]")
completion(destinationUrl.path, nil)
}
else
{
print("error saving file")
let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
completion(destinationUrl.path, error)
}
}
else
{
let error = NSError(domain:"Error downloading file", code:1002, userInfo:nil)
completion(destinationUrl.path, error)
}
}

static func loadFileAsync(url: URL, dest: String, completion: @escaping (String?, Error?) -> Void)
{
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

let destinationUrl = documentsUrl.appendingPathComponent(dest)

if FileManager().fileExists(atPath: destinationUrl.path)
{
print("File already exists [\(destinationUrl.path)]")
completion(destinationUrl.path, nil)
}
else
{
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = session.dataTask(with: request, completionHandler:
{
data, response, error in
if error == nil
{
if let response = response as? HTTPURLResponse
{
if response.statusCode == 200
{
if let data = data
{
if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
{
completion(destinationUrl.path, error)
}
else
{
completion(destinationUrl.path, error)
}
}
else
{
completion(destinationUrl.path, error)
}
}
}
}
else
{
completion(destinationUrl.path, error)
}
})
task.resume()
}
}
}

@objc public class CapacitorUpdater: NSObject {
Expand All @@ -131,21 +24,35 @@ class FileDownloader {
return String((0..<length).map{ _ in letters.randomElement()! })
}

@objc public func updateApp(_ call: CAPPluginCall) -> Bool {
@objc public func updateApp(url: URL) -> Bool {
print(url)
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let url = URL(string: call.getString("url"))
let destZip = documentsUrl.appendingPathComponent(randomString(length: 10))
let dest = documentsUrl.appendingPathComponent(randomString(length: 10))
FileDownloader.loadFileSync(url: url!, dest: destZip) { (path, error) in
print("File downloaded to : \(path!)")
SSZipArchive.unzipFileAtPath(destZip, toDestination: dest)
let files = this.listFiles(url: dest)
for file in files {
FileManager.default.secureCopyItem(at: file], to: documentsUrl.appendingPathComponent("public"))
let publicFolder = documentsUrl.appendingPathComponent("public")
let r = Just.get(url)
if r.ok {
if (FileManager.default.createFile(atPath: destZip.absoluteString, contents: r.content, attributes: nil)) {
print("File created successfully.", destZip.absoluteString)
SSZipArchive.unzipFile(atPath: destZip.absoluteString, toDestination: dest.absoluteString)
do {
let files = try FileManager.default.contentsOfDirectory(atPath: dest.absoluteString)
print(files)
for file in files {
let urlFile = URL.init(string: file)!
FileManager.default.secureCopyItem(at: urlFile, to: publicFolder)
}
} catch {
print("Error getting zip files")
return false
}
return true
} else {
print("File not created.")
}
call.resolve(true)
} else {
print("Error downloading zip file", r.error)
}
call.resolve(false)
return false
}
}
16 changes: 12 additions & 4 deletions ios/Plugin/CapacitorUpdaterPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,17 @@ public class CapacitorUpdaterPlugin: CAPPlugin {
private let implementation = CapacitorUpdater()

@objc func updateApp(_ call: CAPPluginCall) {
let url = call.getString("url") ?? ""
call.resolve([
"done": implementation.updateApp(url)
])
let url = URL(string: call.getString("url") ?? "")

let res = implementation.updateApp(url: url!)
if (res) {
DispatchQueue.main.async {
self.bridge?.viewController?.viewDidLoad()
}
call.resolve([
"done": res
])
}
call.reject("error")
}
}

0 comments on commit b9b17cb

Please sign in to comment.