fix upload progress

This commit is contained in:
Diego Mello 2024-05-17 15:29:56 -03:00
parent 2b18d276c4
commit 0f731976c0
1 changed files with 87 additions and 100 deletions

View File

@ -9,12 +9,7 @@ import { Encryption } from '../encryption';
import { IUpload, IUser, TUploadModel } from '../../definitions';
import i18n from '../../i18n';
import database from '../database';
import FileUpload from './helpers/fileUpload';
import { IFileUpload } from './helpers/fileUpload/interfaces';
import log from './helpers/log';
import { E2E_MESSAGE_TYPE } from '../constants';
import { store } from '../store/auxStore';
import { compareServerVersion } from './helpers';
const uploadQueue: { [index: string]: StatefulPromise<FetchBlobResponse> } = {};
@ -60,11 +55,12 @@ const createUploadRecord = async ({
const db = database.active;
const uploadsCollection = db.get('uploads');
const uploadPath = getUploadPath(fileInfo.path, rid);
let uploadRecord: TUploadModel;
let uploadRecord: TUploadModel | null = null;
try {
uploadRecord = await uploadsCollection.find(uploadPath);
if (uploadRecord.id && !isForceTryAgain) {
return Alert.alert(i18n.t('FileUpload_Error'), i18n.t('Upload_in_progress'));
Alert.alert(i18n.t('FileUpload_Error'), i18n.t('Upload_in_progress'));
return [null, null];
}
} catch (error) {
try {
@ -84,6 +80,7 @@ const createUploadRecord = async ({
throw e;
}
}
return [uploadPath, uploadRecord] as const;
};
export function sendFileMessage(
@ -94,14 +91,15 @@ export function sendFileMessage(
user: Partial<Pick<IUser, 'id' | 'token'>>,
isForceTryAgain?: boolean
): Promise<FetchBlobResponse | void> {
console.log('🚀 ~ rid: string, fileInfo, tmid, server,', rid, fileInfo, tmid, server);
return new Promise(async (resolve, reject) => {
try {
const { id, token } = user;
fileInfo.rid = rid;
fileInfo.path = fileInfo.path.startsWith('file://') ? fileInfo.path.substring(7) : fileInfo.path;
await createUploadRecord({ rid, fileInfo, tmid, isForceTryAgain });
const [uploadPath, uploadRecord] = await createUploadRecord({ rid, fileInfo, tmid, isForceTryAgain });
if (!uploadPath || !uploadRecord) {
return;
}
const encryptedFileInfo = await Encryption.encryptFile(rid, fileInfo);
const { encryptedFile, getContent } = encryptedFileInfo;
@ -112,102 +110,91 @@ export function sendFileMessage(
'X-User-Id': id
};
try {
const data = [
{
name: 'file',
type: 'file',
filename: sha256(fileInfo.name || 'fileMessage'),
data: RNFetchBlob.wrap(decodeURI(encryptedFile))
}
];
const response = await RNFetchBlob.fetch('POST', `${server}/api/v1/rooms.media/${rid}`, headers, data);
const json = response.json();
let content;
if (getContent) {
content = await getContent(json.file._id, json.file.url);
const db = database.active;
const data = [
{
name: 'file',
type: 'file',
filename: sha256(fileInfo.name || 'fileMessage'),
data: RNFetchBlob.wrap(decodeURI(encryptedFile))
}
const mediaConfirm = await fetch(`${server}/api/v1/rooms.mediaConfirm/${rid}/${json.file._id}`, {
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/json'
},
body: JSON.stringify({
// msg: '', TODO: backwards compatibility
tmid,
description: fileInfo.description,
t: 'e2e',
content
})
});
console.log('🚀 ~ returnnewPromise ~ mediaConfirm :', mediaConfirm);
} catch (e) {
console.error(e);
}
];
// uploadQueue[uploadPath] = FileUpload.fetch('POST', uploadUrl, headers, formData);
uploadQueue[uploadPath] = RNFetchBlob.fetch('POST', `${server}/api/v1/rooms.media/${rid}`, headers, data);
// uploadQueue[uploadPath].uploadProgress(async (loaded: number, total: number) => {
// try {
// await db.write(async () => {
// await uploadRecord.update(u => {
// u.progress = Math.floor((loaded / total) * 100);
// });
// });
// } catch (e) {
// log(e);
// }
// });
uploadQueue[uploadPath].then(async response => {
// If response is all good...
if (response.respInfo.status >= 200 && response.respInfo.status < 400) {
try {
const json = response.json();
let content;
if (getContent) {
content = await getContent(json.file._id, json.file.url);
}
await fetch(`${server}/api/v1/rooms.mediaConfirm/${rid}/${json.file._id}`, {
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/json'
},
body: JSON.stringify({
// msg: '', TODO: backwards compatibility
tmid,
description: fileInfo.description,
t: 'e2e',
content
})
});
// uploadQueue[uploadPath].then(async response => {
// // If response is all good...
// if (response.respInfo.status >= 200 && response.respInfo.status < 400) {
// try {
// console.log('🚀 ~ returnnewPromise ~ response:', response);
// console.log('🚀 ~ returnnewPromise ~ response:', response.data);
// // if (getContent) {
// // const content = getContent(response.json().file._id, response.json().file.url);
// // console.log('🚀 ~ returnnewPromise ~ content:', content);
// // }
await db.write(async () => {
await uploadRecord.destroyPermanently();
});
resolve(response);
} catch (e) {
log(e);
}
} else {
try {
await db.write(async () => {
await uploadRecord.update(u => {
u.error = true;
});
});
} catch (e) {
log(e);
}
try {
reject(response);
} catch (e) {
reject(e);
}
}
});
// await db.write(async () => {
// await uploadRecord.destroyPermanently();
// });
// resolve(response);
// } catch (e) {
// log(e);
// }
// } else {
// try {
// await db.write(async () => {
// await uploadRecord.update(u => {
// u.error = true;
// });
// });
// } catch (e) {
// log(e);
// }
// try {
// reject(response);
// } catch (e) {
// reject(e);
// }
// }
// });
uploadQueue[uploadPath].catch(async error => {
try {
await db.write(async () => {
await uploadRecord.update(u => {
u.error = true;
});
});
} catch (e) {
log(e);
}
reject(error);
});
// uploadQueue[uploadPath].catch(async error => {
// try {
// await db.write(async () => {
// await uploadRecord.update(u => {
// u.error = true;
// });
// });
// } catch (e) {
// log(e);
// }
// reject(error);
// });
uploadQueue[uploadPath].uploadProgress(async (loaded: number, total: number) => {
try {
await db.write(async () => {
await uploadRecord.update(u => {
u.progress = Math.floor((loaded / total) * 100);
});
});
} catch (e) {
log(e);
}
});
} catch (e) {
log(e);
}