60 lines
1.4 KiB
TypeScript
60 lines
1.4 KiB
TypeScript
import type { AttachmentSelectorItem } from "./types";
|
|
|
|
export type MediaKind = "image" | "video" | "file";
|
|
|
|
/** 取得媒体预览地址。 */
|
|
export function getMediaPreviewURL(item: AttachmentSelectorItem): string {
|
|
return item.previewUrl || item.url;
|
|
}
|
|
|
|
/** 根据 MIME 类型和文件扩展名判断媒体类型。 */
|
|
export function getMediaKind(item: AttachmentSelectorItem): MediaKind {
|
|
const mimeType = (item.mimeType || "").toLowerCase();
|
|
if (mimeType.startsWith("video/")) {
|
|
return "video";
|
|
}
|
|
if (mimeType.startsWith("image/")) {
|
|
return "image";
|
|
}
|
|
if (mimeType) {
|
|
return "file";
|
|
}
|
|
|
|
const url = item.url.split(/[?#]/, 1)[0] || "";
|
|
if (/\.(avi|m4v|mkv|mov|mp4|mpeg|mpg|ogv|webm|wmv)$/i.test(url)) {
|
|
return "video";
|
|
}
|
|
if (/\.(pdf|docx?|xlsx?|pptx?|zip|rar|txt)$/i.test(url)) {
|
|
return "file";
|
|
}
|
|
|
|
return "image";
|
|
}
|
|
|
|
/** 取得媒体列表的缩略图地址。 */
|
|
export function getMediaThumbnailURL(item: AttachmentSelectorItem): string {
|
|
if (item.thumbnailUrl) {
|
|
return item.thumbnailUrl;
|
|
}
|
|
|
|
return getMediaKind(item) === "image" ? item.url : "";
|
|
}
|
|
|
|
/** 取得可读的文件名称。 */
|
|
export function getMediaName(item: AttachmentSelectorItem): string {
|
|
if (item.name) {
|
|
return item.name;
|
|
}
|
|
|
|
const url = item.url.split(/[?#]/, 1)[0] || "";
|
|
const fileName = url.split("/").pop();
|
|
if (!fileName) {
|
|
return "文件";
|
|
}
|
|
try {
|
|
return decodeURIComponent(fileName);
|
|
} catch {
|
|
return fileName;
|
|
}
|
|
}
|