99 lines
3.2 KiB
TypeScript
99 lines
3.2 KiB
TypeScript
import { AlertController, LoadingController } from "@ionic/angular";
|
|
import { WSItem } from "../ws-item";
|
|
import { StoragehubService } from "src/app/storagehub.service";
|
|
import { Directory, Filesystem } from "@capacitor/filesystem";
|
|
import { FileOpener } from "@awesome-cordova-plugins/file-opener/ngx";
|
|
import { App } from '@capacitor/app';
|
|
import { isPlatform } from '@ionic/angular';
|
|
import { presentConnectionAlert } from "src/app/_helper/utils";
|
|
|
|
|
|
export class OpenFile {
|
|
|
|
pluginListener: any;
|
|
|
|
item: WSItem;
|
|
|
|
constructor(item: WSItem) {
|
|
this.item = item;
|
|
if (isPlatform("android")) {
|
|
App.addListener('resume', () => {
|
|
Filesystem.deleteFile(
|
|
{
|
|
path: item.getTitle(),
|
|
directory: Directory.Data
|
|
}).then(() => console.log("file deleted"));
|
|
this.pluginListener?.remove();
|
|
}).then((handler) => this.pluginListener = handler);
|
|
}
|
|
}
|
|
|
|
async open(storageHub: StoragehubService, fileOpener: FileOpener, loadingCtrl: LoadingController, alertCtrl: AlertController) {
|
|
const size = this.item.item.content?.size;
|
|
if (!size || size / 1000000 > 20) {
|
|
this.presentAlert(alertCtrl);
|
|
return;
|
|
}
|
|
|
|
this.showLoading(loadingCtrl);
|
|
storageHub.downloadFile(this.item.item.id).then(obs => obs.subscribe({
|
|
next: async blob => {
|
|
const base64 = await this.blobToBase64(blob) as string;
|
|
const fileWrited = await Filesystem.writeFile({
|
|
path: this.item.getTitle(),
|
|
data: base64,
|
|
directory: Directory.Data
|
|
});
|
|
|
|
const mimeType = this.item.item.content?.mimeType;
|
|
fileOpener.open(fileWrited.uri, mimeType ? mimeType : "application/octet-stream").then(() => {
|
|
loadingCtrl.dismiss();
|
|
if (isPlatform("ios"))
|
|
Filesystem.deleteFile(
|
|
{
|
|
path: this.item.getTitle(),
|
|
directory: Directory.Data
|
|
});
|
|
|
|
})
|
|
|
|
},
|
|
error: (err) => {
|
|
loadingCtrl.dismiss();
|
|
this.pluginListener?.remove();
|
|
presentConnectionAlert(err, alertCtrl);
|
|
}
|
|
}))
|
|
}
|
|
|
|
|
|
async presentAlert(alertCtrl: AlertController) {
|
|
const alert = await alertCtrl.create({
|
|
header: 'Alert',
|
|
message: 'File too big to be opeend here!',
|
|
buttons: ['OK'],
|
|
});
|
|
|
|
await alert.present();
|
|
}
|
|
|
|
async showLoading(loadingCtrl: LoadingController) {
|
|
const loading = await loadingCtrl.create({
|
|
message: 'Loading...',
|
|
duration: 20000,
|
|
spinner: 'circles',
|
|
});
|
|
|
|
loading.present();
|
|
return loading;
|
|
}
|
|
|
|
|
|
blobToBase64(blob: Blob) {
|
|
return new Promise((resolve, _) => {
|
|
const reader = new FileReader();
|
|
reader.onloadend = () => resolve(reader.result);
|
|
reader.readAsDataURL(blob);
|
|
});
|
|
}
|
|
} |