Files
CRM_Montzar/apps/web/src/lib/useOrgChat.ts
T

865 lines
26 KiB
TypeScript
Raw Normal View History

import { computed, ref, shallowRef } from 'vue';
import type { ConversationRoomDto, ConversationSessionDto } from '@mento/shared';
import { api } from '@/lib/api';
export type ChatDelivery = 'sending' | 'sent' | 'read';
2026-09-29 17:22:34 +03:30
export type ChatMediaType = 'text' | 'image' | 'voice' | 'video' | 'file';
export type ChatMessage = {
id: string;
roomId: string;
senderId: string;
content: string;
2026-09-29 17:22:34 +03:30
type: ChatMediaType;
createdAt: string;
reply: string | null;
optimistic?: boolean;
delivery?: ChatDelivery;
readAt?: string | null;
2026-09-29 17:22:34 +03:30
/** Absolute URL for media display/download */
mediaUrl?: string;
fileName?: string;
uploadProgress?: number;
localPreviewUrl?: string;
};
export type RoomLiveEvent = {
roomId: string;
preview: string;
at: string;
fromSelf: boolean;
};
const PAGE_SIZE = 50;
2026-09-29 17:22:34 +03:30
const IMAGE_MAX_EDGE = 1600;
const IMAGE_WEBP_QUALITY = 0.82;
const MAX_UPLOAD_BYTES = 40 * 1024 * 1024;
let socket: WebSocket | null = null;
let sessionCache: ConversationSessionDto | null = null;
let connectPromise: Promise<void> | null = null;
let pingTimer: ReturnType<typeof setInterval> | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
let wantSocket = false;
const status = ref<'idle' | 'connecting' | 'open' | 'closed'>('idle');
const messages = shallowRef<ChatMessage[]>([]);
const activeRoomId = ref('');
const unreadTotal = ref(0);
const pageOpen = ref(false);
type RoomListener = (event: RoomLiveEvent) => void;
const roomListeners = new Set<RoomListener>();
export function onRoomLiveEvent(listener: RoomListener) {
roomListeners.add(listener);
return () => roomListeners.delete(listener);
}
function emitRoomLive(event: RoomLiveEvent) {
for (const listener of roomListeners) {
try {
listener(event);
} catch {
// ignore listener errors
}
}
}
2026-09-29 11:56:32 +03:30
function messageTs(item: ChatMessage): number {
const t = new Date(item.createdAt).getTime();
return Number.isNaN(t) ? 0 : t;
}
function sortAsc(items: ChatMessage[]): ChatMessage[] {
return [...items].sort((a, b) => {
const d = messageTs(a) - messageTs(b);
if (d !== 0) return d;
return a.id.localeCompare(b.id);
});
}
2026-09-29 17:22:34 +03:30
function normalizeMediaType(raw: string): ChatMediaType {
const t = raw.toLowerCase().trim();
if (t === 'image' || t === 'photo' || t === 'img') return 'image';
if (t === 'voice' || t === 'audio') return 'voice';
if (t === 'video') return 'video';
if (t === 'file' || t === 'document' || t === 'attachment') return 'file';
return 'text';
}
const VIDEO_EXT_RE = /\.(mp4|webm|mov|m4v|mkv|avi|3gp|ogv)(?:\?|$)/i;
const AUDIO_EXT_RE = /\.(webm|ogg|mp3|m4a|wav|aac|opus|oga)(?:\?|$)/i;
const IMAGE_EXT_RE = /\.(jpe?g|png|gif|webp|bmp|svg|heic|heif)(?:\?|$)/i;
function looksLikeVideo(pathOrName: string): boolean {
return VIDEO_EXT_RE.test(pathOrName);
}
function inferMediaType(
declared: ChatMediaType,
content: string,
fileName?: string,
): ChatMediaType {
const probe = `${fileName || ''} ${content}`;
if (declared === 'video' || looksLikeVideo(probe)) return 'video';
if (declared === 'image') return 'image';
if (declared === 'voice') return 'voice';
if (declared === 'file' || declared === 'text') {
if (looksLikeVideo(probe)) return 'video';
if (IMAGE_EXT_RE.test(probe)) return 'image';
if (AUDIO_EXT_RE.test(probe)) return 'voice';
if (declared === 'file') return 'file';
}
return declared;
}
2026-09-29 17:22:34 +03:30
export function previewLabelForMessage(msg: Pick<ChatMessage, 'type' | 'content' | 'fileName'>) {
if (msg.type === 'image') return 'تصویر';
if (msg.type === 'voice') return 'پیام صوتی';
2026-09-29 17:22:34 +03:30
if (msg.type === 'video') return 'ویدیو';
if (msg.type === 'file') {
if (looksLikeVideo(`${msg.fileName || ''} ${msg.content}`)) return 'ویدیو';
return msg.fileName?.trim() || 'فایل';
}
2026-09-29 17:22:34 +03:30
return msg.content || 'پیام';
}
function buildChatFileUrl(value: string, downloadUrl: string): string {
const raw = String(value || '').trim();
if (!raw) return '';
if (/^(https?:\/\/|blob:|data:)/i.test(raw)) return raw;
if (!downloadUrl) return raw;
const cleanRaw = raw.replace(/^\/+/, '');
try {
const baseUrl = new URL(downloadUrl);
const basePath = baseUrl.pathname.replace(/^\/+|\/+$/g, '');
const baseParts = basePath.split('/').filter(Boolean);
const rawParts = cleanRaw.split('/').filter(Boolean);
if (basePath && cleanRaw.startsWith(`${basePath}/`)) {
return `${baseUrl.origin}/${cleanRaw}`;
}
const lastBasePart = baseParts[baseParts.length - 1];
if (lastBasePart && rawParts[0] === lastBasePart) {
const parentPath = baseParts.slice(0, -1).join('/');
return `${baseUrl.origin}/${[parentPath, cleanRaw].filter(Boolean).join('/')}`;
}
return `${downloadUrl.replace(/\/+$/, '')}/${cleanRaw}`;
} catch {
return raw;
}
}
function extractUploadedPath(result: Record<string, unknown>): string {
const nested = (result.data && typeof result.data === 'object'
? (result.data as Record<string, unknown>)
: null);
const file = (result.file && typeof result.file === 'object'
? (result.file as Record<string, unknown>)
: null);
const value =
result.path ||
result.url ||
result.file_url ||
result.fileUrl ||
nested?.path ||
nested?.url ||
nested?.file_url ||
nested?.fileUrl ||
file?.path ||
file?.url;
return String(value || '').trim();
}
function classifyFile(file: File): Exclude<ChatMediaType, 'text'> {
const mime = (file.type || '').toLowerCase();
if (mime.startsWith('image/')) return 'image';
if (mime.startsWith('audio/')) return 'voice';
if (mime.startsWith('video/')) return 'video';
return 'file';
}
/** Chat backend (Hamkar-compatible) accepts text|image|voice|file — not video. */
function wsMediaType(type: ChatMediaType): 'image' | 'voice' | 'file' | 'text' {
2026-09-29 17:22:34 +03:30
if (type === 'image') return 'image';
if (type === 'voice') return 'voice';
if (type === 'video' || type === 'file') return 'file';
return 'text';
2026-09-29 17:22:34 +03:30
}
async function compressImageIfNeeded(file: File): Promise<File> {
if (!file.type.startsWith('image/')) return file;
if (file.type === 'image/gif' || file.type === 'image/svg+xml') return file;
if (file.size < 350_000) return file;
try {
const bitmap = await createImageBitmap(file);
const ratio = Math.min(
IMAGE_MAX_EDGE / bitmap.width,
IMAGE_MAX_EDGE / bitmap.height,
1,
);
const width = Math.round(bitmap.width * ratio);
const height = Math.round(bitmap.height * ratio);
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) {
bitmap.close();
return file;
}
ctx.drawImage(bitmap, 0, 0, width, height);
bitmap.close();
const blob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob((b) => resolve(b), 'image/webp', IMAGE_WEBP_QUALITY);
});
if (!blob || blob.size >= file.size) return file;
const base = file.name.replace(/\.[^/.]+$/, '') || 'image';
return new File([blob], `${base}.webp`, {
type: 'image/webp',
lastModified: Date.now(),
});
} catch {
return file;
}
}
2026-09-29 11:56:32 +03:30
function normalizeIncoming(
raw: Record<string, unknown>,
roomFallback: string,
): ChatMessage | null {
const base =
raw.message && typeof raw.message === 'object'
? (raw.message as Record<string, unknown>)
: raw;
const declared = normalizeMediaType(String(base.type_content ?? base.type ?? 'text'));
const content = String(base.content ?? base.text ?? base.body ?? '').trim();
if (!content && !base.attachments) return null;
2026-09-29 17:22:34 +03:30
2026-09-29 11:56:32 +03:30
const id = String(base.id ?? base.message_id ?? '').trim();
const readAt = base.read_at ?? base.readAt ?? null;
2026-09-29 17:22:34 +03:30
const downloadUrl = sessionCache?.downloadUrl ?? '';
const fileName =
String(base.file_name ?? base.fileName ?? base.name ?? '').trim() ||
content.split('/').pop() ||
undefined;
const type = inferMediaType(declared, content, fileName);
2026-09-29 17:22:34 +03:30
const isMedia = type !== 'text';
const mediaUrl = isMedia ? buildChatFileUrl(content, downloadUrl) : undefined;
return {
2026-09-29 11:56:32 +03:30
id: id || `tmp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
roomId: String(base.room_id ?? raw.room_id ?? roomFallback),
senderId: String(
base.sender_id ?? base.user_id ?? base.from_user_id ?? raw.sender_id ?? '',
),
content,
2026-09-29 17:22:34 +03:30
type,
createdAt: String(
base.created_at ?? base.createdAt ?? raw.created_at ?? new Date().toISOString(),
),
reply: base.reply ? String(base.reply) : null,
readAt: readAt ? String(readAt) : null,
delivery: readAt ? 'read' : 'sent',
2026-09-29 17:22:34 +03:30
mediaUrl,
fileName,
};
}
2026-09-29 11:56:32 +03:30
function mergeMessages(incoming: ChatMessage, list: ChatMessage[]): ChatMessage[] {
const byId = list.findIndex((m) => m.id === incoming.id);
if (byId >= 0) {
const prev = list[byId];
2026-09-29 11:56:32 +03:30
const next = [...list];
next[byId] = {
...prev,
...incoming,
optimistic: false,
type:
prev.type === 'video' && (incoming.type === 'file' || incoming.type === 'text')
? 'video'
: inferMediaType(incoming.type, incoming.content, incoming.fileName || prev.fileName),
2026-09-29 17:22:34 +03:30
localPreviewUrl: incoming.localPreviewUrl ?? prev.localPreviewUrl,
mediaUrl: incoming.mediaUrl || prev.mediaUrl,
fileName: incoming.fileName || prev.fileName,
delivery:
incoming.delivery === 'read' || prev.delivery === 'read'
? 'read'
: incoming.delivery || prev.delivery || 'sent',
readAt: incoming.readAt ?? prev.readAt,
};
2026-09-29 11:56:32 +03:30
return sortAsc(next);
}
const optimisticIdx = list.findIndex(
(m) =>
m.optimistic &&
m.roomId === incoming.roomId &&
m.senderId === incoming.senderId &&
2026-09-29 17:22:34 +03:30
(m.content === incoming.content ||
(m.type === incoming.type &&
m.type !== 'text' &&
Boolean(m.localPreviewUrl))),
2026-09-29 11:56:32 +03:30
);
if (optimisticIdx >= 0) {
const prev = list[optimisticIdx];
2026-09-29 11:56:32 +03:30
const next = [...list];
next[optimisticIdx] = {
...prev,
2026-09-29 11:56:32 +03:30
...incoming,
optimistic: false,
type:
prev.type === 'video' && (incoming.type === 'file' || incoming.type === 'text')
? 'video'
: inferMediaType(incoming.type, incoming.content, incoming.fileName || prev.fileName),
localPreviewUrl: prev.localPreviewUrl,
2026-09-29 17:22:34 +03:30
uploadProgress: undefined,
mediaUrl: incoming.mediaUrl || prev.mediaUrl,
fileName: incoming.fileName || prev.fileName,
delivery: incoming.readAt ? 'read' : 'sent',
2026-09-29 11:56:32 +03:30
};
2026-09-29 17:22:34 +03:30
if (prev.localPreviewUrl?.startsWith('blob:')) {
try {
URL.revokeObjectURL(prev.localPreviewUrl);
} catch {
// ignore
}
}
2026-09-29 11:56:32 +03:30
return sortAsc(next);
}
return sortAsc([...list, incoming]);
}
function applySeenPayload(payload: Record<string, unknown>) {
const roomId = String(payload.room_id ?? '');
if (!roomId || roomId !== activeRoomId.value) return;
const myId = sessionCache?.chatUserId ?? '';
const readerId = String(payload.reader_id ?? '');
if (!readerId || readerId === myId) return;
const ids = new Set(
Array.isArray(payload.seen_message_ids)
? payload.seen_message_ids.map((id) => String(id))
: [],
);
if (!ids.size) {
messages.value = messages.value.map((m) =>
m.roomId === roomId && m.senderId === myId
? { ...m, delivery: 'read' as const, readAt: String(payload.seen_at ?? new Date().toISOString()) }
: m,
);
return;
}
const seenAt = String(payload.seen_at ?? new Date().toISOString());
messages.value = messages.value.map((m) => {
if (!ids.has(m.id)) return m;
if (m.senderId !== myId) return m;
return { ...m, delivery: 'read' as const, readAt: seenAt };
});
}
async function ensureSession(): Promise<ConversationSessionDto> {
if (sessionCache) return sessionCache;
const { data } = await api.get<ConversationSessionDto>('/conversations/session');
sessionCache = data;
return data;
}
function clearPing() {
if (pingTimer) {
clearInterval(pingTimer);
pingTimer = null;
}
}
function clearReconnect() {
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
}
function scheduleReconnect() {
if (!wantSocket || reconnectTimer) return;
reconnectTimer = setTimeout(() => {
reconnectTimer = null;
void connectSocket().catch(() => {
scheduleReconnect();
});
}, 2500);
}
function disconnectSocket() {
clearPing();
clearReconnect();
if (socket) {
socket.onmessage = null;
socket.onclose = null;
socket.onerror = null;
socket.close();
socket = null;
}
status.value = 'closed';
connectPromise = null;
}
function handleIncomingMessage(msg: ChatMessage) {
const myId = sessionCache?.chatUserId ?? '';
const fromSelf = Boolean(myId && msg.senderId === myId);
if (msg.roomId === activeRoomId.value) {
messages.value = mergeMessages(
{
...msg,
delivery: fromSelf ? msg.delivery || 'sent' : msg.delivery,
},
messages.value,
);
if (!fromSelf && pageOpen.value) {
sendRead(msg.roomId);
}
} else if (!fromSelf) {
unreadTotal.value += 1;
}
emitRoomLive({
roomId: msg.roomId,
2026-09-29 17:22:34 +03:30
preview: previewLabelForMessage(msg),
at: msg.createdAt,
fromSelf,
});
}
2026-09-29 11:56:32 +03:30
function onSocketMessage(event: MessageEvent) {
const raw = String(event.data ?? '').trim();
if (!raw || raw === 'pong' || raw === 'ping') return;
try {
const parsed = JSON.parse(raw) as Record<string, unknown>;
const type = String(parsed.type ?? parsed.event ?? '').toLowerCase();
if (type === 'pong' || type === 'ping' || type === 'typing' || type === 'read') return;
if (type === 'seen') {
applySeenPayload(parsed);
return;
}
2026-09-29 11:56:32 +03:30
const msg = normalizeIncoming(parsed, activeRoomId.value);
if (!msg) return;
handleIncomingMessage(msg);
2026-09-29 11:56:32 +03:30
} catch {
// ignore
}
}
async function connectSocket() {
wantSocket = true;
if (socket?.readyState === WebSocket.OPEN) return;
if (connectPromise) return connectPromise;
connectPromise = (async () => {
const session = await ensureSession();
if (socket?.readyState === WebSocket.OPEN) return;
disconnectSocket();
wantSocket = true;
status.value = 'connecting';
socket = new WebSocket(session.wsUrl);
await new Promise<void>((resolve, reject) => {
if (!socket) return reject(new Error('socket missing'));
const t = setTimeout(() => reject(new Error('ws timeout')), 12000);
socket.addEventListener(
'open',
() => {
clearTimeout(t);
status.value = 'open';
pingTimer = setInterval(() => {
if (socket?.readyState === WebSocket.OPEN) socket.send('ping');
}, 15000);
resolve();
},
{ once: true },
);
socket.addEventListener(
'error',
() => {
clearTimeout(t);
reject(new Error('ws error'));
},
{ once: true },
);
});
if (!socket) return;
socket.addEventListener('message', onSocketMessage);
socket.addEventListener('close', () => {
status.value = 'closed';
clearPing();
socket = null;
connectPromise = null;
if (wantSocket) scheduleReconnect();
});
})().finally(() => {
connectPromise = null;
});
return connectPromise;
}
function sendRead(roomId: string) {
if (!socket || socket.readyState !== WebSocket.OPEN || !roomId) return;
socket.send(JSON.stringify({ type: 'read', room_id: roomId }));
}
function formatUploadFailure(status: number, bodyText: string): string {
const raw = bodyText.trim();
if (raw) {
try {
const json = JSON.parse(raw) as Record<string, unknown>;
const err = String(json.error ?? json.message ?? '').trim();
const details = String(json.details ?? '').trim();
if (err && details) return `آپلود ناموفق بود: ${err} (${details})`;
if (err) return `آپلود ناموفق بود: ${err}`;
} catch {
const snippet = raw.slice(0, 160);
if (snippet) return `آپلود ناموفق بود (${status}): ${snippet}`;
}
}
if (status === 500) {
return 'آپلود ناموفق بود (۵۰۰). سرویس ذخیره‌سازی فایل (S3) روی آدرس آپلود در دسترس نیست — تنظیمات upload/download در سوپرادمین را بررسی کنید.';
}
return `آپلود ناموفق بود (${status})`;
}
2026-09-29 17:22:34 +03:30
function uploadChatFile(
uploadUrl: string,
file: File,
onProgress?: (percent: number) => void,
): Promise<string> {
return new Promise((resolve, reject) => {
if (!uploadUrl.trim()) {
reject(new Error('آدرس آپلود گفتگو تنظیم نشده است'));
return;
}
const formData = new FormData();
formData.append('file', file);
const xhr = new XMLHttpRequest();
xhr.open('POST', uploadUrl);
xhr.upload.onprogress = (event) => {
if (!event.lengthComputable) return;
onProgress?.(Math.min(99, Math.round((event.loaded / event.total) * 100)));
};
xhr.onload = () => {
if (xhr.status < 200 || xhr.status >= 300) {
reject(new Error(formatUploadFailure(xhr.status, xhr.responseText || '')));
2026-09-29 17:22:34 +03:30
return;
}
try {
const contentType = xhr.getResponseHeader('content-type') || '';
if (contentType.includes('application/json')) {
const result = JSON.parse(xhr.responseText) as Record<string, unknown>;
const path = extractUploadedPath(result);
if (!path) {
reject(new Error('پاسخ آپلود فاقد مسیر فایل است'));
return;
}
resolve(path);
return;
}
const path = xhr.responseText.trim();
if (!path) {
reject(new Error('پاسخ آپلود خالی است'));
return;
}
resolve(path);
} catch (e) {
reject(e instanceof Error ? e : new Error('پاسخ آپلود نامعتبر است'));
}
};
xhr.onerror = () => reject(new Error('خطای شبکه هنگام آپلود'));
xhr.send(formData);
});
}
export async function refreshUnreadTotal() {
try {
const { data } = await api.get<ConversationRoomDto[]>('/conversations/rooms');
unreadTotal.value = data.reduce((sum, room) => sum + (room.unreadCount || 0), 0);
return unreadTotal.value;
} catch {
return unreadTotal.value;
}
}
export function useOrgChat() {
const loadingMessages = ref(false);
async function ensureConnected() {
await connectSocket();
}
function setConversationsPageOpen(open: boolean) {
pageOpen.value = open;
}
async function loadMessages(roomId: string) {
activeRoomId.value = roomId;
loadingMessages.value = true;
try {
const session = await ensureSession();
await connectSocket();
const params = new URLSearchParams({
api_key: new URL(session.wsUrl).searchParams.get('api_key') ?? '',
room_id: roomId,
user_id: session.chatUserId,
limit: String(PAGE_SIZE),
offset: '0',
});
const url = `${session.messagesBaseUrl}/api/messages?${params.toString()}`;
const res = await fetch(url, { headers: { Accept: 'application/json' }, cache: 'no-store' });
if (!res.ok) throw new Error('messages failed');
const body = await res.json();
const list = Array.isArray(body) ? body : body?.data ?? [];
const myId = session.chatUserId;
const normalized = (list
.map((item: Record<string, unknown>) => normalizeIncoming(item, roomId))
.filter(Boolean) as ChatMessage[]).map((m) => {
if (m.senderId !== myId) return m;
return {
...m,
delivery: (m.readAt ? 'read' : 'sent') as ChatDelivery,
};
});
2026-09-29 11:56:32 +03:30
messages.value = sortAsc(normalized);
sendRead(roomId);
} finally {
loadingMessages.value = false;
}
}
async function sendText(roomId: string, text: string, reply: string | null = null) {
const trimmed = text.trim();
if (!trimmed) return;
await connectSocket();
if (!socket || socket.readyState !== WebSocket.OPEN) throw new Error('ws not open');
const session = await ensureSession();
const id = crypto.randomUUID();
const payload: Record<string, string> = {
id,
type: 'text',
room_id: roomId,
content: trimmed,
};
if (reply) payload.reply = reply;
const optimistic: ChatMessage = {
id,
roomId,
senderId: session.chatUserId,
content: trimmed,
type: 'text',
createdAt: new Date().toISOString(),
reply,
optimistic: true,
delivery: 'sending',
};
2026-09-29 11:56:32 +03:30
messages.value = mergeMessages(optimistic, messages.value);
emitRoomLive({
roomId,
preview: trimmed,
at: optimistic.createdAt,
fromSelf: true,
});
socket.send(JSON.stringify(payload));
messages.value = messages.value.map((m) =>
m.id === id ? { ...m, optimistic: false, delivery: 'sent' as const } : m,
);
}
2026-09-29 17:22:34 +03:30
async function sendMediaPath(
roomId: string,
path: string,
type: Exclude<ChatMediaType, 'text'>,
opts?: {
reply?: string | null;
fileName?: string;
localPreviewUrl?: string;
tempId?: string;
},
) {
const filePath = path.trim();
if (!filePath) return;
await connectSocket();
if (!socket || socket.readyState !== WebSocket.OPEN) throw new Error('ws not open');
const session = await ensureSession();
const id = opts?.tempId || crypto.randomUUID();
const reply = opts?.reply ?? null;
const wsType = wsMediaType(type);
const mediaUrl = buildChatFileUrl(filePath, session.downloadUrl);
const payload: Record<string, string> = {
id,
type: wsType,
room_id: roomId,
content: filePath,
};
if (reply) payload.reply = reply;
if (opts?.fileName) payload.file_name = opts.fileName;
2026-09-29 17:22:34 +03:30
const existingIdx = messages.value.findIndex((m) => m.id === id);
if (existingIdx >= 0) {
const next = [...messages.value];
next[existingIdx] = {
...next[existingIdx],
content: filePath,
type,
mediaUrl,
fileName: opts?.fileName,
uploadProgress: 100,
optimistic: false,
delivery: 'sent',
};
messages.value = next;
} else {
const optimistic: ChatMessage = {
id,
roomId,
senderId: session.chatUserId,
content: filePath,
type,
createdAt: new Date().toISOString(),
reply,
optimistic: true,
delivery: 'sending',
mediaUrl,
fileName: opts?.fileName,
localPreviewUrl: opts?.localPreviewUrl,
};
messages.value = mergeMessages(optimistic, messages.value);
}
emitRoomLive({
roomId,
preview: previewLabelForMessage({ type, content: filePath, fileName: opts?.fileName }),
at: new Date().toISOString(),
fromSelf: true,
});
socket.send(JSON.stringify(payload));
messages.value = messages.value.map((m) =>
m.id === id
? { ...m, optimistic: false, delivery: 'sent' as const, uploadProgress: undefined }
: m,
);
}
async function sendFile(
roomId: string,
file: File,
reply: string | null = null,
) {
if (!file) return;
if (file.size > MAX_UPLOAD_BYTES) {
throw new Error('حجم فایل بیش از حد مجاز است (۴۰ مگابایت)');
}
const session = await ensureSession();
if (!session.uploadUrl?.trim()) {
throw new Error(
'آدرس آپلود گفتگو خالی است. در سوپرادمین → محیط‌ها → تنظیمات گفتگو پر کنید.',
);
}
await connectSocket();
const type = classifyFile(file);
const id = crypto.randomUUID();
const localPreviewUrl = URL.createObjectURL(file);
const optimistic: ChatMessage = {
id,
roomId,
senderId: session.chatUserId,
content: '',
type,
createdAt: new Date().toISOString(),
reply,
optimistic: true,
delivery: 'sending',
fileName: file.name,
localPreviewUrl,
uploadProgress: 0,
};
messages.value = mergeMessages(optimistic, messages.value);
const setProgress = (percent: number) => {
messages.value = messages.value.map((m) =>
m.id === id ? { ...m, uploadProgress: percent } : m,
);
};
try {
setProgress(5);
const fileForUpload = type === 'image' ? await compressImageIfNeeded(file) : file;
setProgress(12);
const uploadedPath = await uploadChatFile(session.uploadUrl, fileForUpload, (p) => {
setProgress(12 + Math.round(p * 0.86));
});
setProgress(99);
await sendMediaPath(roomId, uploadedPath, type, {
reply,
fileName: file.name,
localPreviewUrl,
tempId: id,
});
} catch (e) {
messages.value = messages.value.filter((m) => m.id !== id);
if (localPreviewUrl.startsWith('blob:')) {
try {
URL.revokeObjectURL(localPreviewUrl);
} catch {
// ignore
}
}
throw e;
}
}
function clearActiveRoom() {
activeRoomId.value = '';
messages.value = [];
}
function resetSession() {
wantSocket = false;
sessionCache = null;
disconnectSocket();
messages.value = [];
activeRoomId.value = '';
}
return {
status: computed(() => status.value),
messages: computed(() => messages.value),
unreadTotal: computed(() => unreadTotal.value),
loadingMessages,
loadMessages,
sendText,
2026-09-29 17:22:34 +03:30
sendFile,
sendRead,
ensureConnected,
setConversationsPageOpen,
clearActiveRoom,
resetSession,
ensureSession,
refreshUnreadTotal,
};
}