material-preview.uts 10.6 KB
import { toStr } from "@/utils/common.uts";

export type MaterialPreviewPayload = {
        title: string
        kind: string
        url: string
        contentType: number
        unsupportedMessage: string
}

function createPreviewPayload(
        title: string,
        kind: string,
        url: string,
        contentType: number,
        unsupportedMessage: string = "该素材暂不支持预览"
): MaterialPreviewPayload {
        return {
                title: title,
                kind: kind,
                url: url,
                contentType: contentType,
                unsupportedMessage: unsupportedMessage
        };
}

export function readMaterialTitle(item: any | null): string {
        if (item == null) {
                return "";
        }
        const obj = item as UTSJSONObject;
        return (
                (obj["detailTitle"] as null | string)
                ?? (obj["materialTitle"] as null | string)
                ?? (obj["shortTitle"] as null | string)
                ?? (obj["materialName"] as null | string)
                ?? (obj["title"] as null | string)
                ?? (obj["name"] as null | string)
                ?? ""
        );
}

export function readMaterialType(item: any | null): number {
        if (item == null) {
                return -1;
        }
        const obj = item as UTSJSONObject;
        const raw = obj["contentType"];
        if (raw == null) {
                return -1;
        }
        if (typeof raw === "number") {
                return raw as number;
        }
        const parsed = parseInt(`${raw}`);
        return isNaN(parsed) ? -1 : parsed;
}

export function readMaterialCoverUrl(item: any | null): string {
        if (item == null) {
                return "";
        }
        const obj = item as UTSJSONObject;
        const candidates = [
                obj["coverUrl"],
                obj["bannerImg"],
                obj["thumbnail"],
                obj["thumbnailUrl"],
                obj["contentPicUrl"],
                obj["imageUrl"],
                obj["imgUrl"],
                obj["coverImg"],
                obj["detailUrl"]
        ];
        for (let i = 0; i < candidates.length; i++) {
                const value = candidates[i];
                if (value != null && typeof value === "string" && `${value}` !== "") {
                        return `${value}`;
                }
        }
        return "";
}

export function readMaterialPreviewUrl(item: any | null): string {
        if (item == null) {
                return "";
        }
        const obj = item as UTSJSONObject;
        const candidates = [
                obj["previewUrl"],
                obj["materialUrl"],
                obj["detailUrl"],
                obj["bodyUrl"],
                obj["contentPicUrl"],
                obj["coverUrl"],
                obj["thumbnailUrl"]
        ];
        for (let i = 0; i < candidates.length; i++) {
                const value = candidates[i];
                if (value != null && typeof value === "string" && `${value}` !== "") {
                        return `${value}`;
                }
        }
        return "";
}

function isWebUrl(url: string): boolean {
        return url.startsWith("http://") || url.startsWith("https://");
}

function getUrlWithoutQuery(url: string): string {
        let result = url.toLowerCase();
        const hashIndex = result.indexOf("#");
        if (hashIndex >= 0) {
                result = result.substring(0, hashIndex);
        }
        const queryIndex = result.indexOf("?");
        if (queryIndex >= 0) {
                result = result.substring(0, queryIndex);
        }
        return result;
}

function endsWithOneOf(url: string, suffixes: string[]): boolean {
        const normalized = getUrlWithoutQuery(url);
        for (let i = 0; i < suffixes.length; i++) {
                const suffix = suffixes[i];
                if (normalized.endsWith(suffix)) {
                        return true;
                }
        }
        return false;
}

function inferPreviewKindFromUrl(url: string): string {
        if (url == "") {
                return "unsupported";
        }
        if (endsWithOneOf(url, [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"])) {
                return "image";
        }
        if (endsWithOneOf(url, [".mp4", ".mov", ".m4v", ".webm", ".avi"])) {
                return "video";
        }
        if (isWebUrl(url) && endsWithOneOf(url, [".pdf", ".html", ".htm"])) {
                return "web";
        }
        return "unsupported";
}

function isDirectOfficeFileUrl(url: string): boolean {
        return endsWithOneOf(url, [".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"]);
}

function getUnsupportedMessage(contentType: number, previewUrl: string): string {
        if (contentType == 4 || contentType == 5) {
                if (previewUrl == "") {
                        return "Office 素材缺少预览地址";
                }
                if (isDirectOfficeFileUrl(previewUrl)) {
                        return "Office 原文件不建议直接预览,请配置在线预览地址";
                }
        }
        if (contentType == 2 && !isWebUrl(previewUrl)) {
                return "PDF 素材链接无效";
        }
        if (contentType == 1 && previewUrl == "") {
                return "视频地址不存在";
        }
        return "该素材暂不支持预览";
}

export function resolveMaterialPreviewPayload(item: any | null): MaterialPreviewPayload {
        const title = readMaterialTitle(item);
        const contentType = readMaterialType(item);
        const previewUrl = readMaterialPreviewUrl(item);
        const coverUrl = readMaterialCoverUrl(item);
        const inferredPreviewKind = inferPreviewKindFromUrl(previewUrl);
        const inferredCoverKind = inferPreviewKindFromUrl(coverUrl);

        if (contentType == 0) {
                const imageUrl = previewUrl != "" ? previewUrl : coverUrl;
                if (imageUrl != "") {
                        return createPreviewPayload(title, "image", imageUrl, contentType);
                }
                return createPreviewPayload(title, "unsupported", "", contentType, "图片地址不存在");
        }

        if (contentType == 1) {
                if (previewUrl != "") {
                        return createPreviewPayload(title, "video", previewUrl, contentType);
                }
                return createPreviewPayload(title, "unsupported", "", contentType, "视频地址不存在");
        }

        if (contentType == 2 || contentType == 3) {
                if ((inferredPreviewKind == "image" || inferredPreviewKind == "video") && previewUrl != "") {
                        return createPreviewPayload(title, inferredPreviewKind, previewUrl, contentType);
                }
                if (previewUrl != "" && isWebUrl(previewUrl)) {
                        return createPreviewPayload(title, "web", previewUrl, contentType);
                }
                if ((inferredCoverKind == "image" || inferredCoverKind == "video") && coverUrl != "") {
                        return createPreviewPayload(title, inferredCoverKind, coverUrl, contentType);
                }
                return createPreviewPayload(title, "unsupported", "", contentType, getUnsupportedMessage(contentType, previewUrl));
        }

        if (contentType == 4 || contentType == 5) {
                if ((inferredPreviewKind == "image" || inferredPreviewKind == "video") && previewUrl != "") {
                        return createPreviewPayload(title, inferredPreviewKind, previewUrl, contentType);
                }
                if (previewUrl != "" && isWebUrl(previewUrl) && !isDirectOfficeFileUrl(previewUrl)) {
                        return createPreviewPayload(title, "web", previewUrl, contentType);
                }
                if ((inferredCoverKind == "image" || inferredCoverKind == "video") && coverUrl != "") {
                        return createPreviewPayload(title, inferredCoverKind, coverUrl, contentType);
                }
                return createPreviewPayload(title, "unsupported", "", contentType, getUnsupportedMessage(contentType, previewUrl));
        }

        const inferredUrl = previewUrl != "" ? previewUrl : coverUrl;
        const inferredKind = inferPreviewKindFromUrl(inferredUrl);
        if (inferredKind != "unsupported") {
                return createPreviewPayload(title, inferredKind, inferredUrl, contentType);
        }

        return createPreviewPayload(title, "unsupported", "", contentType, getUnsupportedMessage(contentType, inferredUrl));
}

export function canPreviewMaterial(item: any | null): boolean {
        const payload = resolveMaterialPreviewPayload(item);
        return payload.kind != "unsupported" && payload.url != "";
}

export function buildMaterialPreviewRoute(item: any | null): string {
        const payload = resolveMaterialPreviewPayload(item);
        if (payload.kind == "unsupported" || payload.url == "") {
                return "";
        }
        const titleText = payload.title != "" ? payload.title : "素材预览";
        const title = encodeURIComponent(toStr(titleText));
        const url = encodeURIComponent(payload.url);
        if (payload.kind == "web") {
                return `/pages/common/webview/index?title=${title}&url=${url}`;
        }
        const kind = encodeURIComponent(payload.kind);
        return `/pages/common/materialPreview/index?title=${title}&kind=${kind}&url=${url}`;
}

export function openMaterialPreview(item: any | null, showUnsupportedToast: boolean = true): boolean {
        const payload = resolveMaterialPreviewPayload(item);
        if (payload.kind == "image" && payload.url != "") {
                uni.previewImage({
                        current: payload.url,
                        urls: [payload.url]
                });
                return true;
        }
        const route = buildMaterialPreviewRoute(item);
        if (route == "") {
                if (showUnsupportedToast) {
                        uni.showToast({
                                title: payload.unsupportedMessage,
                                icon: "none"
                        });
                }
                return false;
        }
        uni.navigateTo({ url: route });
        return true;
}

/**
 * UTSJSONObject 版本的预览解析,避免跨文件传递自定义 type 导致运行时 NoSuchMethodError
 */
export function resolvePreviewObj(item: any | null): UTSJSONObject {
        const p = resolveMaterialPreviewPayload(item);
        return {
                title: p.title,
                kind: p.kind,
                url: p.url,
                contentType: p.contentType,
                unsupportedMessage: p.unsupportedMessage
        } as UTSJSONObject;
}