Skip to content

Commit

Permalink
fix: delete cached zip after import finished
Browse files Browse the repository at this point in the history
  • Loading branch information
farfromrefug committed Dec 19, 2024
1 parent da80ddf commit 075d8f8
Show file tree
Hide file tree
Showing 4 changed files with 233 additions and 291 deletions.
2 changes: 1 addition & 1 deletion app/android/activity.android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ let shortPress = false;
let longpressTimer;
let audioManager: android.media.AudioManager;

const SUPPORTED_KEY_CODES = [24, 25]
const SUPPORTED_KEY_CODES = [24, 25];
function handleKey(activity: androidx.appcompat.app.AppCompatActivity, keyCode: number, event: android.view.KeyEvent) {
const instance = getInstance();
// DEV_LOG && console.warn('handleKey', activity, instance, instance.shouldHandleVolumeButtons, keyCode);
Expand Down
117 changes: 28 additions & 89 deletions app/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,41 +253,11 @@ export async function getHEAD<T>(arg: any) {

export async function downloadStories(story: RemoteContent, folderId?: number) {
let progressNotificationId;
let destinationFilePath;
try {
const name = Date.now() + '';

const destinationFileName = `${name}.zip`;
const destinationFolderPath = __IOS__ ? knownFolders.temp().path : documentsService.dataFolder.path;
const androidUseContent = __ANDROID__ && destinationFolderPath.startsWith(ANDROID_CONTENT);

// let file: File;
// if (story.download.startsWith('blob:')) {
// DEV_LOG && console.log('downloadStories', 'blob', story.download);
// const destinationFilePath = path.join(knownFolders.temp().path, destinationFileName);
// if (__IOS__) {
// showSnackMessage({ text: l('downloading'), progress: -1 });
// const url = NSURL.URLWithString(story.download);
// DEV_LOG && console.log('downloadStories', 'url', url);
// const data = NSData.alloc().initWithContentsOfURL(url);
// DEV_LOG && console.log('downloadStories', 'data', data);
// await new Promise((resolve, reject) => {
// try {
// data.writeToFileAtomicallyCompletion(destinationFilePath, true, () => resolve);
// } catch (error) {
// reject(error);
// }
// });
// file = File.fromPath(destinationFilePath);
// } else {
// try {
// com.akylas.conty.FileUtils.Companion.writeURLToFile(story.download, destinationFilePath);
// } catch (e) {
// showError(e);
// }
// file = File.fromPath(destinationFilePath);
// }
// } else {
showSnackMessage({ text: l('preparing_download'), progress: -1 });
const headResult = await getHEAD(story.download);
const contentLength = headResult['content-length'] || headResult['Content-Length'];
Expand All @@ -296,49 +266,9 @@ export async function downloadStories(story: RemoteContent, folderId?: number) {
size = parseInt(headResult['content-length'] || headResult['Content-Length'], 10);
DEV_LOG && console.log('downloadStories', size);
}
// const toDownload = await Promise.all(
// stories.map(async (s) => {
// const pageContent = await (await https.request<string>({ method: 'GET', url: stories[0].download })).content.toStringAsync();
// const actualUrl = pageContent.match(/<meta http-equiv="refresh" content="0; url=(.*)">/)[1];
// const size = parseInt((await getHEAD(actualUrl))['content-length'], 10);
// return {
// ...s,
// download: actualUrl,
// size
// };
// })
// );
// DEV_LOG &&
// console.log(
// 'toDownload',
// toDownload.map((s) => ({ size: s.size, download: s.download }))
// );
// const totalSize = toDownload.reduce((acc, cur) => acc + cur.size, 0);
// const confirmed = await confirm({
// title: lc('download_stories'),
// message: lc(
// 'confirm_download_stories',
// toDownload.length,
// filesize(
// toDownload.reduce((acc, cur) => acc + cur.size, 0),
// { output: 'string' }
// )
// )
// });

// if (!confirmed) {
// return;
// }

progressNotificationId = 52346 + hashCode(story.download);
// const headers = await Promise.all(stories.map(getHEAD));

// const newContentSize = headers['content-length'];
// DEV_LOG && console.log('checkForStoryUpdate', url, storyId, workingDir, newContentSize, typeof newContentSize, lastSize !== newContentSize, Folder.exists(storyDirPath));

// if (forceReload || lastSize !== newContentSize || !Folder.exists(storyDirPath)) {
const runningRequestTag: string = story.download;
// const name = cleanFilename(story.title);

const progressNotification = ProgressNotifications.show({
id: progressNotificationId, //required
Expand Down Expand Up @@ -381,7 +311,7 @@ export async function downloadStories(story: RemoteContent, folderId?: number) {

const compressed = documentsService.supportsCompressedData;

const downloadFilePath = !compressed || androidUseContent ? path.join(knownFolders.temp().path, destinationFileName) : path.join(destinationFolderPath, destinationFileName);
const downloadFilePath = path.join(knownFolders.temp().path, destinationFileName);
const file = await getFile(
{
url: story.download,
Expand All @@ -402,29 +332,38 @@ export async function downloadStories(story: RemoteContent, folderId?: number) {
DEV_LOG && console.log('downloaded', story.download, File.exists(file.path), file.size);
if (File.exists(file.path) && file.size > 0) {
// do it on a background thread
importService.importContentFromFiles(
[
{
filePath: file.path,
id: name,
extraData: {
age: story.age,
title: story.title,
description: story.description,
createdDate: dayjs(story.created_at).valueOf(),
modifiedDate: dayjs(story.updated_at).valueOf()
}
(async () => {
try {
DEV_LOG && console.warn('about tot importContentFromFiles');
await importService.importContentFromFiles(
[
{
filePath: file.path,
id: name,
extraData: {
age: story.age,
title: story.title,
description: story.description,
createdDate: dayjs(story.created_at).valueOf(),
modifiedDate: dayjs(story.updated_at).valueOf()
}
}
],
folderId,
true
);
DEV_LOG && console.warn('aimportContentFromFiles done');
} finally {
if (file && File.exists(file.path)) {
DEV_LOG && console.log('removing downloading file', file.path);
file.remove();
}
],
folderId
);
}
})();
}
} catch (error) {
showError(error);
hideSnackMessage();
if (destinationFilePath && File.exists(destinationFilePath)) {
File.fromPath(destinationFilePath).remove();
}
} finally {
ProgressNotifications.dismiss(progressNotificationId);
}
Expand Down
21 changes: 11 additions & 10 deletions app/services/importservice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,19 @@ export class ImportService extends Observable {
nativeDatas?: { [k: string]: any };
};
}) {
// DEV_LOG && console.log('onWorkerMessage', event);
const data = event.data;
const id = data.id;
// DEV_LOG && console.log('onWorkerMessage', event);
try {
let messageData = data.messageData;
if (typeof messageData === 'string') {
try {
messageData = JSON.parse(messageData);
} catch (error) {}
}
// DEV_LOG && console.error(TAG, 'onWorkerMessage', id, data.type, id && this.messagePromises.hasOwnProperty(id), Object.keys(this.messagePromises), messageData);
// DEV_LOG && console.info('onWorkerMessage', id, data.type, id && this.messagePromises.hasOwnProperty(id), Object.keys(this.messagePromises), messageData);
if (id && this.messagePromises.hasOwnProperty(id)) {
// DEV_LOG && console.log('worker response to promise',id);
this.messagePromises[id].forEach(function (executor) {
executor.timeoutTimer && clearTimeout(executor.timeoutTimer);
// if (isError) {
Expand All @@ -64,14 +65,14 @@ export class ImportService extends Observable {
const eventData = messageData as any;
switch (data.type) {
case 'event':
DEV_LOG && console.info('worker event', documentsService.id, eventData.eventName, eventData.target, !!eventData.object, Object.keys(eventData), JSON.stringify(eventData.pack));
// DEV_LOG && console.info('worker event', documentsService.id, eventData.eventName, eventData.target, !!eventData.object, Object.keys(eventData), JSON.stringify(eventData.pack));
if (eventData.target === 'documentsService') {
if (eventData.pack) {
eventData.pack = await documentsService.packRepository.get(eventData.pack.id);
}
documentsService.notify({ ...eventData, object: eventData.object || documentsService });
} else {
DEV_LOG && console.info('notifying event from worker', documentsService.id, eventData.eventName, Object.keys(eventData));
// DEV_LOG && console.info('notifying event from worker', documentsService.id, eventData.eventName, Object.keys(eventData));
this.notify({ ...eventData });
}
break;
Expand Down Expand Up @@ -191,25 +192,25 @@ export class ImportService extends Observable {
this.worker = null;
// this.services.forEach((service) => service.stop());
}
async updateContentFromDataFolder({ showSnack = true }: { showSnack?: boolean } = {}) {
async updateContentFromDataFolder({ showSnack = true }: { showSnack?: boolean } = {}, shouldWait = false) {
this.ensureWorker();
await this.sendMessageToWorker('import_data', { showSnack }, undefined, undefined, false, 0, { db: documentsService.db.db.db });
await this.sendMessageToWorker('import_data', { showSnack }, shouldWait ? time() : undefined, undefined, false, 0, { db: documentsService.db.db.db });
}
async importContentFromFiles(files: { filePath: string; id?: string; extraData?: Partial<Pack> }[], folderId?: number) {
async importContentFromFiles(files: { filePath: string; id?: string; extraData?: Partial<Pack> }[], folderId?: number, shouldWait = false) {
DEV_LOG && console.log('importContentFromFiles', files, folderId);
this.ensureWorker();
await this.sendMessageToWorker('import_from_files', { files, folderId }, undefined, undefined, false, 0, { db: documentsService.db.db.db });
await this.sendMessageToWorker('import_from_files', { files, folderId }, shouldWait ? time() : undefined, undefined, false, 0, { db: documentsService.db.db.db });
}
// async importContentFromFile(data: { filePath: string; id?: string; extraData?; folderId?: number }) {
// DEV_LOG && console.log('importContentFromFile', JSON.stringify(data));
// this.ensureWorker();
// await this.sendMessageToWorker('import_from_file', data, undefined, undefined, false, 0, { db: documentsService.db.db.db });
// }
async deletePacks(packs: Pack[]) {
async deletePacks(packs: Pack[], shouldWait = false) {
const data = packs.map((s) => ({ id: s.id, folders: s.folders }));
DEV_LOG && console.log('deleteDocuments', JSON.stringify(data));
this.ensureWorker();
await this.sendMessageToWorker('delete_packs', data, undefined, undefined, false, 0, { db: documentsService.db.db.db });
await this.sendMessageToWorker('delete_packs', data, shouldWait ? time() : undefined, undefined, false, 0, { db: documentsService.db.db.db });
}
}
export const importService = new ImportService();
Loading

0 comments on commit 075d8f8

Please sign in to comment.