This commit is contained in:
mlogclub
2026-04-09 10:01:23 +08:00
commit efe801b8bf
707 changed files with 110595 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
import { requestJson } from "@/lib/services/http";
import type { JsonResult, WidgetConversation } from "@/lib/services/types";
/** 身份由请求头 X-External-Source / X-External-Id(及可选 X-External-Name)提供,与 GetExternalInfo 一致 */
export async function createOrMatchConversation() {
const result = await requestJson<JsonResult<WidgetConversation>>(
"/api/open/im/conversation/create_or_match",
{
method: "POST",
},
);
if (!result.data) {
throw new Error(result.message || "conversation init failed");
}
return result.data;
}
export async function closeConversation(conversationId: number) {
const result = await requestJson<JsonResult<null>>(
"/api/open/im/conversation/close",
{
method: "POST",
body: JSON.stringify({ conversationId }),
},
);
if (result.success === false) {
throw new Error(result.message || "conversation close failed");
}
}
+33
View File
@@ -0,0 +1,33 @@
import { readWidgetConfig } from "@/lib/widget/config";
import { getOrCreateExternalId } from "@/lib/widget/visitor";
export async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {
const config = readWidgetConfig();
const baseUrl = (config.apiBaseUrl || config.baseUrl).replace(/\/$/, "");
const visitorId = getOrCreateExternalId();
const externalSource = (config.externalSource ?? "web_chat").trim() || "web_chat";
const headers = new Headers(init?.headers ?? {});
if (
!headers.has("Content-Type") &&
init?.body &&
!(typeof FormData !== "undefined" && init.body instanceof FormData)
) {
headers.set("Content-Type", "application/json");
}
headers.set("X-External-Source", externalSource);
headers.set("X-External-Id", visitorId);
const externalName = (config.subject ?? "").trim();
if (externalName) {
headers.set("X-External-Name", encodeURIComponent(externalName));
}
headers.set("X-Channel-Id", config.channelId);
const response = await fetch(`${baseUrl}${path}`, {
...init,
headers,
cache: "no-store",
});
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return (await response.json()) as T;
}
+133
View File
@@ -0,0 +1,133 @@
export type WidgetMessageAssetPayload = {
assetId: string;
filename?: string;
fileSize?: number;
mimeType?: string;
url?: string;
};
export function parseMessageAssetPayload(
payload?: string,
): WidgetMessageAssetPayload | null {
if (!payload?.trim()) {
return null;
}
try {
const parsed = JSON.parse(payload) as WidgetMessageAssetPayload;
if (!parsed?.assetId?.trim()) {
return null;
}
return parsed;
} catch {
return null;
}
}
export function renderMessageHTML(message: {
messageType: string;
content: string;
payload?: string;
}) {
if (message.messageType === "html") {
return message.content;
}
const asset = parseMessageAssetPayload(message.payload);
if (message.messageType === "image") {
if (asset?.url) {
return `<p><img src="${escapeHTMLAttr(asset.url)}" alt="${escapeHTMLAttr(
asset.filename || "image",
)}"></p>`;
}
return "<p>[图片]</p>";
}
if (message.messageType === "attachment") {
if (asset?.url) {
const title = escapeHTML(asset.filename || message.content || "附件");
const meta = formatFileSize(asset.fileSize ?? 0);
const metaHTML = meta
? `<div class="im-attachment-meta">${escapeHTML(meta)}</div>`
: "";
return `<div class="im-attachment"><a href="${escapeHTMLAttr(
asset.url,
)}" target="_blank" rel="noreferrer" download="${escapeHTMLAttr(
asset.filename || "",
)}" class="im-attachment-link"><span class="im-attachment-icon" aria-hidden="true">${getAttachmentIconSVG()}</span><span class="im-attachment-content"><span class="im-attachment-title">${title}</span>${metaHTML}</span></a></div>`;
}
return `<p>${escapeHTML(message.content || "[附件]")}</p>`;
}
return `<p>${escapeHTML(message.content || "")}</p>`;
}
export function summarizeMessage(message: {
messageType: string;
content: string;
payload?: string;
}) {
if (message.messageType === "image") {
return "[图片]";
}
if (message.messageType === "attachment") {
const asset = parseMessageAssetPayload(message.payload);
return asset?.filename?.trim() ? `[附件] ${asset.filename.trim()}` : "[附件]";
}
if (message.messageType === "html") {
const text = extractTextFromHTML(message.content);
if (text.trim()) {
return text.substring(0, 100);
}
if (message.content.includes("<img")) {
return "[图片]";
}
return "[消息]";
}
return message.content?.substring(0, 100) || "[消息]";
}
function formatFileSize(size: number) {
if (!Number.isFinite(size) || size <= 0) {
return "";
}
const units = ["B", "KB", "MB", "GB"];
let value = size;
let index = 0;
while (value >= 1024 && index < units.length - 1) {
value /= 1024;
index += 1;
}
const digits = value >= 10 || index === 0 ? 0 : 1;
return `${value.toFixed(digits)} ${units[index]}`;
}
function extractTextFromHTML(html: string): string {
if (typeof document === "undefined") {
return "";
}
const div = document.createElement("div");
div.innerHTML = html;
return div.textContent || div.innerText || "";
}
function escapeHTML(value: string) {
return value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#39;")
.replaceAll("\n", "<br>");
}
function escapeHTMLAttr(value: string) {
return value
.replaceAll("&", "&amp;")
.replaceAll('"', "&quot;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;");
}
function getAttachmentIconSVG() {
return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><path d="M14 2v6h6"></path><path d="M9 15h6"></path><path d="M9 11h2"></path></svg>`;
}
+127
View File
@@ -0,0 +1,127 @@
import { requestJson } from "@/lib/services/http";
import type {
CursorResult,
JsonResult,
WidgetAsset,
WidgetMessage,
} from "@/lib/services/types";
import { generateUUID } from "@/lib/utils";
const DEFAULT_PAGE_LIMIT = 50;
function buildListQuery(
conversationId: number,
options?: { cursor?: number; limit?: number },
) {
const params = new URLSearchParams({
conversationId: String(conversationId),
});
const cursor = options?.cursor;
if (cursor !== undefined && cursor > 0) {
params.set("cursor", String(cursor));
}
const limit = options?.limit ?? DEFAULT_PAGE_LIMIT;
if (limit > 0) {
params.set("limit", String(limit));
}
return params.toString();
}
export async function fetchMessagesPage(
conversationId: number,
options?: { cursor?: number; limit?: number },
): Promise<CursorResult<WidgetMessage>> {
const qs = buildListQuery(conversationId, options);
const result = await requestJson<
JsonResult<CursorResult<WidgetMessage>>
>(`/api/open/im/message/list?${qs}`);
if (result.success === false) {
throw new Error(result.message || "加载消息失败");
}
const data = result.data;
return {
results: data?.results ?? [],
cursor: data?.cursor ?? "",
hasMore: Boolean(data?.hasMore),
};
}
/** @deprecated 使用 fetchMessagesPage;保留别名供渐进迁移 */
export async function fetchMessages(conversationId: number) {
const page = await fetchMessagesPage(conversationId);
return page.results;
}
export async function sendMessageWithPayload(
conversationId: number,
payload: {
messageType: string;
content: string;
payload?: string;
clientMsgId?: string;
},
) {
const result = await requestJson<JsonResult<WidgetMessage>>("/api/open/im/message/send", {
method: "POST",
body: JSON.stringify({
conversationId,
clientMsgId: payload.clientMsgId || `client_${generateUUID()}`,
messageType: payload.messageType,
content: payload.content,
payload: payload.payload || "",
}),
});
if (!result.data) {
throw new Error(result.message || "send message failed");
}
return result.data;
}
export async function sendMessage(conversationId: number, content: string) {
return sendMessageWithPayload(conversationId, {
messageType: "html",
content,
payload: "",
});
}
export async function markMessageRead(conversationId: number, messageId = 0) {
await requestJson<JsonResult<void>>("/api/open/im/message/read", {
method: "POST",
body: JSON.stringify({ conversationId, messageId }),
});
}
export async function uploadImage(conversationId: number, file: File) {
const formData = new FormData();
formData.set("conversationId", String(conversationId));
formData.set("file", file);
const result = await requestJson<JsonResult<WidgetAsset>>(
"/api/open/im/message/upload_image",
{
method: "POST",
body: formData,
},
);
if (!result.data) {
throw new Error(result.message || "upload image failed");
}
return result.data;
}
export async function uploadAttachment(conversationId: number, file: File) {
const formData = new FormData();
formData.set("conversationId", String(conversationId));
formData.set("file", file);
const result = await requestJson<JsonResult<WidgetAsset>>(
"/api/open/im/message/upload_attachment",
{
method: "POST",
body: formData,
},
);
if (!result.data) {
throw new Error(result.message || "upload attachment failed");
}
return result.data;
}
+37
View File
@@ -0,0 +1,37 @@
import type { WidgetMessage } from "./types";
import { summarizeMessage } from "./message-asset";
export function getNotificationBody(message: WidgetMessage): string {
return summarizeMessage(message);
}
export function showNotification(title: string, body: string, onClick?: () => void) {
if (typeof Notification === "undefined") {
return;
}
if (Notification.permission === "granted") {
const notification = new Notification(title, {
body,
icon: "/favicon.ico",
badge: "/favicon.ico",
});
if (onClick) {
notification.onclick = () => {
onClick();
notification.close();
};
}
setTimeout(() => {
notification.close();
}, 5000);
} else if (Notification.permission === "default") {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
showNotification(title, body, onClick);
}
});
}
}
+42
View File
@@ -0,0 +1,42 @@
import { readWidgetConfig } from "@/lib/widget/config";
import { getOrCreateExternalId } from "@/lib/widget/visitor";
export type RealtimeEnvelope = {
type: string;
topic?: string;
data?: {
conversationId?: number;
messageId?: number;
};
payload?: {
conversationId?: number;
messageId?: number;
};
};
export function createRealtimeConnection(onEvent: (event: RealtimeEnvelope) => void) {
const config = readWidgetConfig();
const baseUrl = (config.apiBaseUrl || config.baseUrl)
.replace(/^http/, "ws")
.replace(/\/$/, "");
const externalId = encodeURIComponent(getOrCreateExternalId());
const externalSource = encodeURIComponent(
(config.externalSource ?? "web_chat").trim() || "web_chat",
);
const externalName = (config.subject ?? "").trim();
const nameQuery =
externalName !== ""
? `&externalName=${encodeURIComponent(externalName)}`
: "";
const socket = new WebSocket(
`${baseUrl}/api/open/im/ws?externalId=${externalId}&externalSource=${externalSource}&channelId=${encodeURIComponent(config.channelId)}${nameQuery}`,
);
socket.addEventListener("message", (event) => {
try {
onEvent(JSON.parse(event.data) as RealtimeEnvelope);
} catch {
return;
}
});
return socket;
}
+81
View File
@@ -0,0 +1,81 @@
export type PageResult<T> = {
results: T[];
page?: {
page: number;
limit: number;
total: number;
};
};
export type CursorResult<T> = {
results: T[];
cursor: string;
hasMore: boolean;
};
export type JsonResult<T> = {
success?: boolean;
errorCode?: number;
code?: number;
message?: string;
data?: T;
};
export type WidgetConversation = {
id: number;
subject?: string;
status?: number;
serviceMode?: number;
currentAssigneeId?: number;
lastMessageAt?: string;
lastMessageSummary?: string;
customerUnreadCount?: number;
agentUnreadCount?: number;
customerLastReadMessageId?: number;
customerLastReadSeqNo?: number;
customerLastReadAt?: string;
agentLastReadMessageId?: number;
agentLastReadSeqNo?: number;
agentLastReadAt?: string;
};
export type WidgetMessage = {
id: number;
conversationId: number;
senderType: string;
senderName?: string;
senderAvatar?: string;
messageType: string;
content: string;
payload?: string;
seqNo?: number;
sentAt?: string;
customerRead?: boolean;
customerReadAt?: string;
agentRead?: boolean;
agentReadAt?: string;
};
export type WidgetAsset = {
id: number;
assetId: string;
provider: string;
filename: string;
fileSize: number;
mimeType: string;
status: number;
url: string;
createdAt: string;
updatedAt: string;
createUserId: number;
createUserName: string;
updateUserId: number;
updateUserName: string;
};
export type WidgetConfigResponse = {
title?: string;
subtitle?: string;
welcomeText?: string;
themeColor?: string;
};
+13
View File
@@ -0,0 +1,13 @@
import { requestJson } from "@/lib/services/http";
import type { JsonResult, WidgetConfigResponse } from "@/lib/services/types";
import { readWidgetConfig } from "@/lib/widget/config";
export async function fetchWidgetConfig() {
const config = readWidgetConfig();
const result = await requestJson<JsonResult<WidgetConfigResponse>>(
`/api/open/im/widget/config?channelId=${encodeURIComponent(config.channelId)}`,
);
return result.data ?? {};
}
export { readWidgetConfig };