Передача транспортного сервера в контекст, в базу, и в кэш

This commit is contained in:
RoyceDa
2026-03-29 14:58:52 +02:00
parent 61e83bdd43
commit 2f2a0b5376
2 changed files with 94 additions and 15 deletions

View File

@@ -53,6 +53,7 @@ export function useAttachment(attachment: Attachment, parentMessage: MessageProp
} }
const calcDownloadStatus = async () => { const calcDownloadStatus = async () => {
console.info("ds", attachment);
if (downloadStatus == DownloadStatus.DOWNLOADED) { if (downloadStatus == DownloadStatus.DOWNLOADED) {
return; return;
} }
@@ -142,6 +143,7 @@ export function useAttachment(attachment: Attachment, parentMessage: MessageProp
return; return;
} }
setDownloadStatus(DownloadStatus.DECRYPTING); setDownloadStatus(DownloadStatus.DECRYPTING);
console.info("decoding with key " + parentMessage.chacha_key_plain);
//console.info("Decrypted attachment ", Buffer.from(keyPlain, 'binary').toString('hex')); //console.info("Decrypted attachment ", Buffer.from(keyPlain, 'binary').toString('hex'));
const decrypted = await decodeWithPassword(parentMessage.chacha_key_plain, downloadedBlob); const decrypted = await decodeWithPassword(parentMessage.chacha_key_plain, downloadedBlob);
setDownloadTag(""); setDownloadTag("");

View File

@@ -9,7 +9,7 @@ import { useDialogsList } from "../DialogListProvider/useDialogsList";
import { useDatabase } from "../DatabaseProvider/useDatabase"; import { useDatabase } from "../DatabaseProvider/useDatabase";
import { useConsoleLogger } from "@/app/hooks/useConsoleLogger"; import { useConsoleLogger } from "@/app/hooks/useConsoleLogger";
import { useDialogsCache } from "../DialogProvider/useDialogsCache"; import { useDialogsCache } from "../DialogProvider/useDialogsCache";
import { DialogContext } from "../DialogProvider/DialogProvider"; import { AttachmentMeta, DialogContext } from "../DialogProvider/DialogProvider";
import { useTransportServer } from "../TransportProvider/useTransportServer"; import { useTransportServer } from "../TransportProvider/useTransportServer";
import { usePublicKey } from "../AccountProvider/usePublicKey"; import { usePublicKey } from "../AccountProvider/usePublicKey";
@@ -17,7 +17,7 @@ export function usePrepareAttachment() {
const intervalsRef = useRef<NodeJS.Timeout>(null); const intervalsRef = useRef<NodeJS.Timeout>(null);
const {uploadFile} = useTransport(); const {uploadFile} = useTransport();
const {updateDialog} = useDialogsList(); const {updateDialog} = useDialogsList();
const {runQuery} = useDatabase(); const {runQuery, getQuery} = useDatabase();
const {info} = useConsoleLogger('usePrepareAttachment'); const {info} = useConsoleLogger('usePrepareAttachment');
const {getDialogCache} = useDialogsCache(); const {getDialogCache} = useDialogsCache();
const context = useContext(DialogContext); const context = useContext(DialogContext);
@@ -37,6 +37,79 @@ export function usePrepareAttachment() {
} }
} }
/**
* Обновляет транспортный сервер в кэше, чтобы поддерживать его в актуальном состоянии после загрузки
*/
const updateAttachmentTransportInCache = (dialog: string, message_id : string, attachment: Attachment) => {
const dialogCache = getDialogCache(dialog);
if(dialogCache == null){
return;
}
for(let i = 0; i < dialogCache.length; i++){
if(dialogCache[i].message_id == message_id){
for(let j = 0; j < dialogCache[i].attachments.length; j++){
if(dialogCache[i].attachments[j].id == attachment.id){
dialogCache[i].attachments[j].transport = attachment.transport;
}
}
}
}
}
/**
* Обновляет транспорт в базе после загрузки вложения (нам нужно сохранить транспорт)
*/
const updateAttachmentTransportInDatabase = async (message_id : string, attachment: Attachment) => {
let message = await getQuery(`SELECT attachments FROM messages WHERE message_id = ?`, [message_id]);
console.info(message)
if(!message){
return;
}
if(message.attachments == '[]'){
return;
}
let meta : AttachmentMeta[] = JSON.parse(message.attachments);
for(let i = 0; i < meta.length; i++){
if(meta[i].id == attachment.id){
meta[i].transport = attachment.transport;
}
}
await runQuery(`UPDATE messages SET attachments = ? WHERE message_id = ?`, [JSON.stringify(meta), message_id]);
}
/**
* Обновляет вложение в стейте сообщений
*/
const updateAttachmentTransportInContext = (message_id: string, attachment : Attachment) => {
if(context == null || !context){
/**
* Если этот диалог сейчас не открыт
*/
return;
}
context.setMessages((prev) => {
return prev.map((value) => {
if(value.message_id != message_id){
return value;
}
for(let i = 0; i < value.attachments.length; i++){
if(value.attachments[i].id != attachment.id){
return value;
}
value.attachments[i].transport = attachment.transport;
return value;
}
return value;
})
});
}
const updateTransportAfterUploading = async (dialog: string, message_id : string, attachment: Attachment) => {
updateAttachmentTransportInCache(dialog, message_id, attachment);
updateAttachmentTransportInDatabase(message_id, attachment);
updateAttachmentTransportInContext(message_id, attachment);
}
/** /**
* Обновляет временную метку в сообщении, пока вложения отправляются, * Обновляет временную метку в сообщении, пока вложения отправляются,
* потому что если этого не делать, то сообщение может быть помечено как * потому что если этого не делать, то сообщение может быть помечено как
@@ -103,7 +176,9 @@ export function usePrepareAttachment() {
if(attachment.type == AttachmentType.MESSAGES){ if(attachment.type == AttachmentType.MESSAGES){
let reply : MessageReply[] = JSON.parse(attachment.blob) let reply : MessageReply[] = JSON.parse(attachment.blob)
for(let j = 0; j < reply.length; j++){ for(let j = 0; j < reply.length; j++){
reply[j].attachments = await prepareAttachmentsToSend(message_id, dialog, password, reply[j].attachments, true); for(let k = 0; k < reply[j].attachments.length; k++){
reply[j].attachments[k].blob = "";
}
} }
prepared.push({ prepared.push({
...attachment, ...attachment,
@@ -119,16 +194,16 @@ export function usePrepareAttachment() {
const blurhash = await base64ImageToBlurhash(attachment.blob); const blurhash = await base64ImageToBlurhash(attachment.blob);
attachment.preview = blurhash; attachment.preview = blurhash;
} }
if(rePrepared && (attachment.encoding.encoded_for == dialog || attachment.encoding.encoder == dialog)){ // if(rePrepared && (attachment.encoding.encoded_for == dialog || attachment.encoding.encoder == dialog)){
/** // /**
* Это пересланное сообщение и оно уже закодировано для этого диалога, или закодировано отправителем, значит не нужно его кодировать и загружать заново // * Это пересланное сообщение и оно уже закодировано для этого диалога, или закодировано отправителем, значит не нужно его кодировать и загружать заново
*/ // */
prepared.push({ // prepared.push({
...attachment, // ...attachment,
blob: "" // blob: ""
}); // });
continue; // continue;
} // }
doTimestampUpdateImMessageWhileAttachmentsSend(message_id, dialog); doTimestampUpdateImMessageWhileAttachmentsSend(message_id, dialog);
const content = await encodeWithPassword(password, attachment.blob); const content = await encodeWithPassword(password, attachment.blob);
const upid = attachment.id; const upid = attachment.id;
@@ -139,7 +214,7 @@ export function usePrepareAttachment() {
if(intervalsRef.current != null){ if(intervalsRef.current != null){
clearInterval(intervalsRef.current); clearInterval(intervalsRef.current);
} }
prepared.push({ const preparedAttachment : Attachment = {
...attachment, ...attachment,
transport: { transport: {
transport_server: transportServer || "", transport_server: transportServer || "",
@@ -151,7 +226,9 @@ export function usePrepareAttachment() {
}, },
preview: attachment.preview, preview: attachment.preview,
blob: "" blob: ""
}); };
await updateTransportAfterUploading(dialog, message_id, preparedAttachment);
prepared.push(preparedAttachment);
} }
return prepared; return prepared;
}catch(e){ }catch(e){