copy zip file without permissions

This commit is contained in:
vishnuraghavb 2021-04-07 22:48:38 +05:30
parent 2657e5eb02
commit 1ffadd252c
2 changed files with 394 additions and 47 deletions

View file

@ -5,13 +5,12 @@
colSpan="2" colSpan="2"
rowSpan="2" rowSpan="2"
class="options-list" class="options-list"
@loaded="listViewLoad"
for="item in items" for="item in items"
> >
<v-template if="$index == 0"> <v-template if="$index == 0">
<Label class="pageTitle" :text="'db' | L" /> <Label class="pageTitle" :text="'db' | L" />
</v-template> </v-template>
<v-template if="$index == 3"> <v-template if="$index == 4">
<StackLayout class="listSpace"> </StackLayout> <StackLayout class="listSpace"> </StackLayout>
</v-template> </v-template>
<v-template> <v-template>
@ -21,19 +20,42 @@
@touch="touch($event, item.action)" @touch="touch($event, item.action)"
> >
<Label class="ico" :text="icon[item.icon]" /> <Label class="ico" :text="icon[item.icon]" />
<StackLayout col="1"> <StackLayout col="1" verticalAlignment="center">
<Label :text="item.title | L" class="info" /> <Label :text="item.title | L" class="info" />
<Label :text="item.subTitle | L" class="sub" /> <Label v-if="item.subTitle" :text="item.subTitle" class="sub" />
</StackLayout> </StackLayout>
</GridLayout> </GridLayout>
</v-template> </v-template>
</ListView> </ListView>
<GridLayout row="1" class="appbar" rows="*" columns="auto, *"> <GridLayout
<Button v-show="!toast && !backupProgress"
class="ico" row="1"
:text="icon.back" class="appbar"
@tap="$navigateBack()" rows="*"
/> columns="auto, *"
>
<Button class="ico" :text="icon.back" @tap="$navigateBack()" />
</GridLayout>
<GridLayout
v-show="toast"
row="1"
colSpan="2"
class="appbar snackBar"
columns="*"
@tap="toast = null"
>
<FlexboxLayout minHeight="48" alignItems="center">
<Label class="title msg" :text="toast" />
</FlexboxLayout>
</GridLayout>
<GridLayout
v-show="backupProgress"
row="1"
colSpan="2"
class="appbar snackBar"
columns="*"
>
<Progress :value="backupProgress" maxValue="100" />
</GridLayout> </GridLayout>
</GridLayout> </GridLayout>
</Page> </Page>
@ -47,10 +69,11 @@ import {
File, File,
Folder, Folder,
Observable, Observable,
Application,
} from "@nativescript/core"; } from "@nativescript/core";
import * as Permissions from "@nativescript-community/perms"; import * as Permissions from "@nativescript-community/perms";
import { Zip } from "@nativescript/zip"; 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 { localize } from "@nativescript/localize";
import ConfirmDialog from "../modal/ConfirmDialog.vue"; import ConfirmDialog from "../modal/ConfirmDialog.vue";
import { mapState, mapActions } from "vuex"; import { mapState, mapActions } from "vuex";
@ -60,8 +83,9 @@ import * as utils from "~/shared/utils";
export default { export default {
data() { data() {
return { return {
backupFolder: null,
backupProgress: 0, backupProgress: 0,
backupInProgress: false, toast: null,
}; };
}, },
computed: { computed: {
@ -78,17 +102,24 @@ export default {
items() { items() {
return [ return [
{}, {},
{
icon: "folder",
title: "Backup folder",
subTitle: this.backupFolder,
action: this.setBackupFolder,
},
{ {
icon: "exp", icon: "exp",
title: "expBu", title: "expBu",
subTitle: "buInfo", subTitle: localize("buInfo"),
action: this.exportCheck, action: this.exportCheck,
}, },
{ {
icon: "imp", icon: "imp",
title: "impBu", title: "impBu",
subTitle: "impInfo", subTitle: localize("impInfo"),
action: this.importCheck, // action: this.importCheck,
action: this.openZipFile,
}, },
{}, {},
]; ];
@ -104,11 +135,30 @@ export default {
onPageLoad(args) { onPageLoad(args) {
const page = args.object; const page = args.object;
page.bindingContext = new Observable(); 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 // EXPORT HANDLERS
exportCheck() { exportCheck() {
if (!this.recipes.length) { if (!this.recipes.length) {
// Toast.makeText(localize("aFBu")).show(); this.toast = localize("aFBu");
utils.timer(5, (val) => {
if (!val) this.toast = val;
});
} else { } else {
this.permissionCheck( this.permissionCheck(
this.permissionConfirmation, this.permissionConfirmation,
@ -130,28 +180,19 @@ export default {
("0" + date.getHours()).slice(-2) + ("0" + date.getHours()).slice(-2) +
("0" + date.getMinutes()).slice(-2) + ("0" + date.getMinutes()).slice(-2) +
("0" + date.getSeconds()).slice(-2); ("0" + date.getSeconds()).slice(-2);
const sdDownloadPath = Folder.fromPath(
android.os.Environment.getExternalStorageDirectory().getAbsolutePath() let filename = `EnRecipes_${formattedDate}.zip`;
).getFolder("Download").path;
let fromPath = path.join(knownFolders.documents().path, "EnRecipes"); let fromPath = path.join(knownFolders.documents().path, "EnRecipes");
let destPath = path.join( let sdcard = android.os.Environment.isExternalStorageManager();
sdDownloadPath, let destPath = path.join(this.backupFolder, filename);
`EnRecipes-Backup_${formattedDate}.zip` console.log(sdcard);
);
this.backupInProgress = true;
Zip.zip({ Zip.zip({
directory: fromPath, directory: fromPath,
archive: destPath, archive: destPath,
onProgress: (progress) => { onProgress: (progress) => (this.backupProgress = progress),
this.backupProgress = progress; }).then(() => {
}, this.showExportSummary(filename);
}).then((success) => {
// Toast.makeText(
// "Backup file successfully saved to Download folder",
// "long"
// ).show();
this.exportFiles("delete"); this.exportFiles("delete");
setTimeout((e) => (this.backupInProgress = false), 3000);
}); });
}, },
exportFiles(option) { exportFiles(option) {
@ -211,20 +252,63 @@ export default {
this.permissionCheck( this.permissionCheck(
this.permissionConfirmation, this.permissionConfirmation,
localize("reqAcc"), localize("reqAcc"),
this.openFilePicker this.openZipFile
); );
}, },
openFilePicker() { openZipFile() {
// Filepicker.create({ const ContentResolver = Application.android.nativeApp.getContentResolver();
// mode: "single",
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"], // extensions: ["zip"],
// }) // }).then((res) => this.validateZipContent(res.files[0]));
// .present()
// .then((selection) => {
// // Toast.makeText(localize("vrfy") + "...").show();
// let zipPath = selection[0];
// this.validateZipContent(zipPath);
// });
}, },
importDataToDB(data, db, zipPath) { importDataToDB(data, db, zipPath) {
switch (db) { switch (db) {
@ -315,9 +399,11 @@ export default {
}); });
}, },
validateZipContent(zipPath) { validateZipContent(zipPath) {
console.log(zipPath);
Zip.unzip({ Zip.unzip({
archive: zipPath, archive: zipPath,
overwrite: true, overwrite: true,
onProgress: (progress) => (this.backupProgress = progress),
}).then((extractedFolderPath) => { }).then((extractedFolderPath) => {
let cacheFolderPath = extractedFolderPath + "/EnRecipes"; let cacheFolderPath = extractedFolderPath + "/EnRecipes";
const EnRecipesFilePath = cacheFolderPath + "/recipes.json"; const EnRecipesFilePath = cacheFolderPath + "/recipes.json";
@ -380,6 +466,7 @@ export default {
archive: sourcePath, archive: sourcePath,
directory: dest, directory: dest,
overwrite: true, overwrite: true,
onProgress: (progress) => (this.backupProgress = progress),
}).then((res) => { }).then((res) => {
this.showImportSummary(); this.showImportSummary();
this.unlinkBrokenImages(); this.unlinkBrokenImages();
@ -399,7 +486,16 @@ export default {
)}${importedNote}${existsNote}${updatedNote}`, )}${importedNote}${existsNote}${updatedNote}`,
okButtonText: "OK", 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 // PERMISSIONS HANDLER
permissionCheck(confirmation, description, action) { permissionCheck(confirmation, description, action) {
@ -411,7 +507,6 @@ export default {
if (status === "authorized") action(); if (status === "authorized") action();
if (status !== "denied") if (status !== "denied")
ApplicationSettings.setBoolean("storagePermissionAsked", true); ApplicationSettings.setBoolean("storagePermissionAsked", true);
// else Toast.makeText(localize("dend")).show();
}); });
} }
}); });

View file

@ -1,4 +1,5 @@
import { Application, Utils } from '@nativescript/core' import { Application, AndroidApplication, Utils } from '@nativescript/core'
let timerOne
export const restartApp = () => { export const restartApp = () => {
let mStartActivity = new android.content.Intent( let mStartActivity = new android.content.Intent(
Application.android.context, Application.android.context,
@ -48,3 +49,254 @@ export const vibrate = (duration) => {
) )
if (vibratorService.hasVibrator()) vibratorService.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()
}
}
})
}