diff --git a/app/components/Settings/Database.vue b/app/components/Settings/Database.vue
index 91f406f9..26132fd5 100644
--- a/app/components/Settings/Database.vue
+++ b/app/components/Settings/Database.vue
@@ -5,13 +5,12 @@
colSpan="2"
rowSpan="2"
class="options-list"
- @loaded="listViewLoad"
for="item in items"
>
-
+
@@ -21,19 +20,42 @@
@touch="touch($event, item.action)"
>
-
+
-
+
-
-
+
+
+
+
+
+
+
+
+
+
@@ -47,10 +69,11 @@ import {
File,
Folder,
Observable,
+ Application,
} from "@nativescript/core";
import * as Permissions from "@nativescript-community/perms";
import { Zip } from "@nativescript/zip";
-// import * as Filepicker from "nativescript-plugin-filepicker";
+import { openFilePicker } from "@nativescript-community/ui-document-picker";
import { localize } from "@nativescript/localize";
import ConfirmDialog from "../modal/ConfirmDialog.vue";
import { mapState, mapActions } from "vuex";
@@ -60,8 +83,9 @@ import * as utils from "~/shared/utils";
export default {
data() {
return {
+ backupFolder: null,
backupProgress: 0,
- backupInProgress: false,
+ toast: null,
};
},
computed: {
@@ -78,17 +102,24 @@ export default {
items() {
return [
{},
+ {
+ icon: "folder",
+ title: "Backup folder",
+ subTitle: this.backupFolder,
+ action: this.setBackupFolder,
+ },
{
icon: "exp",
title: "expBu",
- subTitle: "buInfo",
+ subTitle: localize("buInfo"),
action: this.exportCheck,
},
{
icon: "imp",
title: "impBu",
- subTitle: "impInfo",
- action: this.importCheck,
+ subTitle: localize("impInfo"),
+ // action: this.importCheck,
+ action: this.openZipFile,
},
{},
];
@@ -104,11 +135,30 @@ export default {
onPageLoad(args) {
const page = args.object;
page.bindingContext = new Observable();
+ const downloadsFolder = Folder.fromPath(
+ android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
+ ).getFolder("Download").path;
+ this.backupFolder = ApplicationSettings.getString(
+ "backupFolder",
+ downloadsFolder
+ );
+ },
+ // BACKUP FOLDER PICKER
+ setBackupFolder() {
+ utils.pickFolder().then((res) => {
+ if (res != null) {
+ this.backupFolder = res;
+ ApplicationSettings.setString("backupFolder", this.backupFolder);
+ }
+ });
},
// EXPORT HANDLERS
exportCheck() {
if (!this.recipes.length) {
- // Toast.makeText(localize("aFBu")).show();
+ this.toast = localize("aFBu");
+ utils.timer(5, (val) => {
+ if (!val) this.toast = val;
+ });
} else {
this.permissionCheck(
this.permissionConfirmation,
@@ -130,28 +180,19 @@ export default {
("0" + date.getHours()).slice(-2) +
("0" + date.getMinutes()).slice(-2) +
("0" + date.getSeconds()).slice(-2);
- const sdDownloadPath = Folder.fromPath(
- android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
- ).getFolder("Download").path;
+
+ let filename = `EnRecipes_${formattedDate}.zip`;
let fromPath = path.join(knownFolders.documents().path, "EnRecipes");
- let destPath = path.join(
- sdDownloadPath,
- `EnRecipes-Backup_${formattedDate}.zip`
- );
- this.backupInProgress = true;
+ let sdcard = android.os.Environment.isExternalStorageManager();
+ let destPath = path.join(this.backupFolder, filename);
+ console.log(sdcard);
Zip.zip({
directory: fromPath,
archive: destPath,
- onProgress: (progress) => {
- this.backupProgress = progress;
- },
- }).then((success) => {
- // Toast.makeText(
- // "Backup file successfully saved to Download folder",
- // "long"
- // ).show();
+ onProgress: (progress) => (this.backupProgress = progress),
+ }).then(() => {
+ this.showExportSummary(filename);
this.exportFiles("delete");
- setTimeout((e) => (this.backupInProgress = false), 3000);
});
},
exportFiles(option) {
@@ -211,20 +252,63 @@ export default {
this.permissionCheck(
this.permissionConfirmation,
localize("reqAcc"),
- this.openFilePicker
+ this.openZipFile
);
},
- openFilePicker() {
- // Filepicker.create({
- // mode: "single",
+ openZipFile() {
+ const ContentResolver = Application.android.nativeApp.getContentResolver();
+
+ utils.getBackupFile().then((uri) => {
+ console.log(uri);
+ const inputStream = ContentResolver.openInputStream(uri);
+ console.log(inputStream);
+ let newFile = knownFolders.temp().getFile("test.zip");
+ console.log(newFile);
+ try {
+ const input = new java.io.BufferedInputStream(inputStream);
+ console.log(input);
+ const outputStream = new java.io.BufferedOutputStream(
+ new java.io.FileOutputStream(newFile.path)
+ );
+ console.log(outputStream);
+ let size = inputStream.available();
+ console.log(size);
+ let buffer = Array.create("byte", size);
+ input.read(buffer);
+ do {
+ outputStream.write(buffer);
+ } while (input.read(buffer) != -1);
+ } catch (e) {
+ console.log(e);
+ } finally {
+ outputStream.flush();
+ outputStream.close();
+ input.close();
+ }
+
+ // console.log(zipInputStream);
+
+ // console.log(zipInputStream);
+ // let extractedFile = new java.io.File(
+ // knownFolders.temp().path + "/tmp.zip"
+ // );
+ // if (!extractedFile.exists()) {
+ // extractedFile.mkdirs();
+ // }
+ // console.log(extractedFile);
+ // let outputStream = new java.io.OutputStream(extractedFile);
+
+ // android.os.FileUtils.copy(inputStream, outputStream);
+ // let outputStream = new java.io.FileOutputStream(extractedFile);
+ // console.log(outputStream);
+ // while ((readLen = zipInputStream.read(readBuffer)) != -1) {
+ // outputStream.write(readBuffer, 0, readLen);
+ // }
+ // console.log(outputStream, 2);
+ });
+ // openFilePicker({
// extensions: ["zip"],
- // })
- // .present()
- // .then((selection) => {
- // // Toast.makeText(localize("vrfy") + "...").show();
- // let zipPath = selection[0];
- // this.validateZipContent(zipPath);
- // });
+ // }).then((res) => this.validateZipContent(res.files[0]));
},
importDataToDB(data, db, zipPath) {
switch (db) {
@@ -315,9 +399,11 @@ export default {
});
},
validateZipContent(zipPath) {
+ console.log(zipPath);
Zip.unzip({
archive: zipPath,
overwrite: true,
+ onProgress: (progress) => (this.backupProgress = progress),
}).then((extractedFolderPath) => {
let cacheFolderPath = extractedFolderPath + "/EnRecipes";
const EnRecipesFilePath = cacheFolderPath + "/recipes.json";
@@ -380,6 +466,7 @@ export default {
archive: sourcePath,
directory: dest,
overwrite: true,
+ onProgress: (progress) => (this.backupProgress = progress),
}).then((res) => {
this.showImportSummary();
this.unlinkBrokenImages();
@@ -399,7 +486,16 @@ export default {
)}${importedNote}${existsNote}${updatedNote}`,
okButtonText: "OK",
},
- });
+ }).then(() => (this.backupProgress = 0));
+ },
+ showExportSummary(filename) {
+ this.$showModal(ConfirmDialog, {
+ props: {
+ title: "expSuc",
+ description: `Backed up to ${filename}`,
+ okButtonText: "OK",
+ },
+ }).then(() => (this.backupProgress = 0));
},
// PERMISSIONS HANDLER
permissionCheck(confirmation, description, action) {
@@ -411,7 +507,6 @@ export default {
if (status === "authorized") action();
if (status !== "denied")
ApplicationSettings.setBoolean("storagePermissionAsked", true);
- // else Toast.makeText(localize("dend")).show();
});
}
});
diff --git a/app/shared/utils.js b/app/shared/utils.js
index 11f5f0a6..b88c3d64 100644
--- a/app/shared/utils.js
+++ b/app/shared/utils.js
@@ -1,4 +1,5 @@
-import { Application, Utils } from '@nativescript/core'
+import { Application, AndroidApplication, Utils } from '@nativescript/core'
+let timerOne
export const restartApp = () => {
let mStartActivity = new android.content.Intent(
Application.android.context,
@@ -48,3 +49,254 @@ export const vibrate = (duration) => {
)
if (vibratorService.hasVibrator()) vibratorService.vibrate(duration)
}
+export const timer = (dur, callback) => {
+ clearInterval(timerOne)
+ callback(true)
+ timerOne = setInterval(() => {
+ dur--
+ callback(true)
+ if (dur == 0) {
+ callback(false)
+ clearInterval(timerOne)
+ }
+ }, 1000)
+}
+
+// FOLDER PICKER
+function callIntent(context, intent, pickerType) {
+ return new Promise((resolve, reject) => {
+ const onEvent = function(e) {
+ if (e.requestCode === pickerType) {
+ resolve(e)
+ Application.android.off(AndroidApplication.activityResultEvent, onEvent)
+ }
+ }
+ Application.android.once(AndroidApplication.activityResultEvent, onEvent)
+ context.startActivityForResult(intent, pickerType)
+ })
+}
+
+//SOURCE: https://github.com/NativeScript/nativescript-imagepicker/blob/bc9209dd7d773eb437ff812f07873c72c789d572/src/imagepicker.android.ts
+
+function getDataColumn(uri, selection, selectionArgs, isDownload) {
+ const ContentResolver = Application.android.nativeApp.getContentResolver()
+ let cursor = null
+ let filePath
+ if (isDownload) {
+ let columns = ['_display_name']
+ try {
+ cursor = ContentResolver.query(
+ uri,
+ columns,
+ selection,
+ selectionArgs,
+ null
+ )
+ if (cursor != null && cursor.moveToFirst()) {
+ let column_index = cursor.getColumnIndexOrThrow(columns[0])
+ filePath = cursor.getString(column_index)
+ if (filePath) {
+ const dl = android.os.Environment.getExternalStoragePublicDirectory(
+ android.os.Environment.DIRECTORY_DOWNLOADS
+ )
+ filePath = `${dl}/${filePath}`
+ return filePath
+ }
+ }
+ } catch (e) {
+ console.log(e)
+ } finally {
+ if (cursor) {
+ cursor.close()
+ }
+ }
+ } else {
+ let columns = [android.provider.MediaStore.MediaColumns.DATA]
+ let filePath
+
+ try {
+ cursor = ContentResolver.query(
+ uri,
+ columns,
+ selection,
+ selectionArgs,
+ null
+ )
+ if (cursor != null && cursor.moveToFirst()) {
+ let column_index = cursor.getColumnIndexOrThrow(columns[0])
+ filePath = cursor.getString(column_index)
+ if (filePath) {
+ return filePath
+ }
+ }
+ } catch (e) {
+ console.log(e)
+ } finally {
+ if (cursor) {
+ cursor.close()
+ }
+ }
+ }
+ return undefined
+}
+function getTreeUri(uri) {
+ const DocumentsContract = android.provider.DocumentsContract
+ const ContentResolver = Application.android.nativeApp.getContentResolver()
+ if (DocumentsContract.isTreeUri(uri)) {
+ let docId, id, type
+ let contentUri = null
+ if ('com.android.externalstorage.documents' === uri.getAuthority()) {
+ docId = DocumentsContract.getTreeDocumentId(uri).split(':')
+ type = docId[0]
+ id = docId[1]
+
+ if ('primary' === type.toLowerCase())
+ return android.os.Environment.getExternalStorageDirectory() + '/' + id
+ else {
+ ContentResolver.takePersistableUriPermission(
+ uri,
+ android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION |
+ android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
+ )
+ const externalMediaDirs = Application.android.context.getExternalMediaDirs()
+ if (externalMediaDirs.length > 1) {
+ let filePath = externalMediaDirs[1].getAbsolutePath()
+ filePath = filePath.substring(0, filePath.indexOf('Android')) + id
+ return filePath
+ }
+ }
+ }
+ // DownloadsProvider
+ else if (
+ 'com.android.providers.downloads.documents' === uri.getAuthority()
+ ) {
+ return getDataColumn(uri, null, null, true)
+ }
+ // MediaProvider
+ else if ('com.android.providers.media.documents' === uri.getAuthority()) {
+ docId = DocumentsContract.getTreeDocumentId(uri).split(':')
+ type = docId[0]
+ id = docId[1]
+
+ if ('image' === type)
+ contentUri =
+ android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
+ else if ('video' === type)
+ contentUri =
+ android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI
+ else if ('audio' === type)
+ contentUri =
+ android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
+
+ let selection = '_id=?'
+ let selectionArgs = [id]
+
+ return getDataColumn(contentUri, selection, selectionArgs, false)
+ }
+ }
+ return undefined
+}
+function getFileUri(uri) {
+ const DocumentsContract = android.provider.DocumentsContract
+ const ContentResolver = Application.android.nativeApp.getContentResolver()
+ if (DocumentsContract.isDocumentUri(Application.android.context, uri)) {
+ let docId, id, type
+ let contentUri = null
+ if ('com.android.externalstorage.documents' === uri.getAuthority()) {
+ docId = DocumentsContract.getDocumentId(uri).split(':')
+ type = docId[0]
+ id = docId[1]
+
+ if ('primary' === type.toLowerCase())
+ return android.os.Environment.getExternalStorageDirectory() + '/' + id
+ else {
+ ContentResolver.takePersistableUriPermission(
+ uri,
+ android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION |
+ android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
+ )
+ const externalMediaDirs = Application.android.context.getExternalMediaDirs()
+ if (externalMediaDirs.length > 1) {
+ let filePath = externalMediaDirs[1].getAbsolutePath()
+ filePath = filePath.substring(0, filePath.indexOf('Android')) + id
+ return filePath
+ }
+ }
+ }
+ // DownloadsProvider
+ else if (
+ 'com.android.providers.downloads.documents' === uri.getAuthority()
+ ) {
+ return getDataColumn(uri, null, null, true)
+ }
+ // MediaProvider
+ else if ('com.android.providers.media.documents' === uri.getAuthority()) {
+ docId = DocumentsContract.getDocumentId(uri).split(':')
+ type = docId[0]
+ id = docId[1]
+
+ if ('image' === type)
+ contentUri =
+ android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
+ else if ('video' === type)
+ contentUri =
+ android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI
+ else if ('audio' === type)
+ contentUri =
+ android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
+
+ let selection = '_id=?'
+ let selectionArgs = [id]
+
+ return getDataColumn(contentUri, selection, selectionArgs, false)
+ }
+ }
+ return undefined
+}
+
+export const pickFolder = () => {
+ const context =
+ Application.android.foregroundActivity || Application.android.startActivity
+ const DIR_CODE = Math.round(Math.random() * 10000)
+ const intent = new android.content.Intent(
+ android.content.Intent.ACTION_OPEN_DOCUMENT_TREE
+ )
+ intent.addCategory(android.content.Intent.CATEGORY_DEFAULT)
+ return callIntent(context, intent, DIR_CODE).then((res) => {
+ if (res.resultCode === android.app.Activity.RESULT_OK)
+ if (res.intent != null && res.intent.getData())
+ return getTreeUri(res.intent.getData())
+ })
+}
+
+function callBackupIntent(context, intent, pickerType) {
+ return new Promise((resolve, reject) => {
+ const onEvent = function(e) {
+ if (e.requestCode === pickerType) {
+ resolve(e)
+ Application.android.off(AndroidApplication.activityResultEvent, onEvent)
+ }
+ }
+ Application.android.once(AndroidApplication.activityResultEvent, onEvent)
+ context.startActivityForResult(intent, pickerType)
+ })
+}
+export const getBackupFile = () => {
+ const context =
+ Application.android.foregroundActivity || Application.android.startActivity
+ const DIR_CODE = Math.round(Math.random() * 10000)
+ const intent = new android.content.Intent(
+ android.content.Intent.ACTION_GET_CONTENT
+ )
+ intent.addCategory(android.content.Intent.CATEGORY_OPENABLE)
+ intent.setType('application/zip')
+ // intent.setFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ return callBackupIntent(context, intent, DIR_CODE).then((res) => {
+ if (res.resultCode === android.app.Activity.RESULT_OK) {
+ if (res.intent != null && res.intent.getData()) {
+ // return getFileUri(res.intent.getData())
+ return res.intent.getData()
+ }
+ }
+ })
+}