Skip to content

Commit

Permalink
feat: make unzip and copy step
Browse files Browse the repository at this point in the history
  • Loading branch information
riderx committed Oct 29, 2021
1 parent bc39255 commit bd45727
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 59 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Android:
- restart app

Apple:
- unzip downloaded file in background
- unzip downloaded file in background with `SSZipArchive`
- copy new file in public folder
- restart app

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,57 +103,39 @@ public Boolean remove(String target) throws JSONException {
return true;
}

// Use thread to copy assets to a temporary directory in background
// public class DownloadandCopy extends AsyncTask<Void, Void, String> {
// @Override protected String doInBackground(Void... params) {
// this.downloadFile(url, folderName)
// }
// @Override protected void onPostExecute(String result) {
// this.copyAssets(source, 'public')
// }
// }


private void unzip(final PluginCall call) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
private void unzip(String source, String dest) {
File zipFile = new File(source);
File targetDirectory = new File(dest);
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(new FileInputStream(zipFile)));
try {
ZipEntry ze;
int count;
byte[] buffer = new byte[8192];
while ((ze = zis.getNextEntry()) != null) {
File file = new File(targetDirectory, ze.getName());
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Failed to ensure directory: " +
dir.getAbsolutePath());
if (ze.isDirectory())
continue;
FileOutputStream fout = new FileOutputStream(file);
try {
File zipFile = new File(new URI(call.getString("zipFile")));
File targetDirectory = new File(new URI(call.getString("targetDirectory")));
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(new FileInputStream(zipFile)));
try {
ZipEntry ze;
int count;
byte[] buffer = new byte[8192];
while ((ze = zis.getNextEntry()) != null) {
File file = new File(targetDirectory, ze.getName());
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Failed to ensure directory: " +
dir.getAbsolutePath());
if (ze.isDirectory())
continue;
FileOutputStream fout = new FileOutputStream(file);
try {
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally {
fout.close();
}
}
} finally {
zis.close();
call.resolve();
}
} catch (Exception e) {
call.reject("An error occurred when trying to unzip package. " + e.getMessage());
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally {
fout.close();
}

return null;
}
}.execute();
} catch (Exception e) {
Log.e(TAG, "unzip error", e);
return false;
} finally {
zis.close();
return true;
}
}

private Boolean downloadFile(String url, String dest) throws JSONException {
Expand Down Expand Up @@ -183,9 +165,12 @@ private Boolean downloadFile(String url, String dest) throws JSONException {
public Boolean updateApp(String url) {
Log.i("updateApp", url);
try {
String folderNameZip = this.generateFolderName();
String folderName = this.generateFolderName();
Boolean downloaded = this.downloadFile(url, folderName);
if(!downloaded) return false;
Boolean unziped = this.unzip(folderNameZip, folderName);
if(!unziped) return false;
Boolean copied = this.copyAssets(source, "public");
if(!copied) return false;
return true;
Expand Down
50 changes: 39 additions & 11 deletions ios/Plugin/CapacitorUpdater.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,32 @@ extension FileManager {
}

class FileDownloader {

static func loadFileSync(url: URL, completion: @escaping (String?, Error?) -> Void)


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(url.lastPathComponent)
let destinationUrl = documentsUrl.appendingPathComponent(dest)

if FileManager().fileExists(atPath: destinationUrl.path)
{
Expand Down Expand Up @@ -107,17 +127,25 @@ class FileDownloader {
@objc public class CapacitorUpdater: NSObject {

@objc private func randomString(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map{ _ in letters.randomElement()! })
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map{ _ in letters.randomElement()! })
}

@objc public func updateApp(_ url: String) -> Bool {
@objc public func updateApp(_ call: CAPPluginCall) -> Bool {
print(url)
let url = URL(string: url)
let dest = randomString(length: 10)
FileDownloader.loadFileAsync(url: url!, dest: dest) { (path, error) in
print("PDF File downloaded to : \(path!)")
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"))
}
call.resolve(true)
}
return false
call.resolve(false)
}
}

0 comments on commit bd45727

Please sign in to comment.