170 lines
7.0 KiB
JavaScript
170 lines
7.0 KiB
JavaScript
/*
|
||
Copyright (C) 2025 QuantumNous
|
||
|
||
This program is free software: you can redistribute it and/or modify
|
||
it under the terms of the GNU Affero General Public License as
|
||
published by the Free Software Foundation, either version 3 of the
|
||
License, or (at your option) any later version.
|
||
|
||
This program is distributed in the hope that it will be useful,
|
||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
GNU Affero General Public License for more details.
|
||
|
||
You should have received a copy of the GNU Affero General Public License
|
||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||
|
||
For commercial licensing, please contact support@quantumnous.com
|
||
*/
|
||
|
||
import { useContext, useEffect, useState } from 'react';
|
||
import { useTranslation } from 'react-i18next';
|
||
import { API } from '../../helpers/api';
|
||
import { normalizeLanguage } from '../../i18n/language';
|
||
import { StatusContext } from '../../context/Status';
|
||
import { UserContext } from '../../context/User';
|
||
import { toSafeHttpUrl } from '../../helpers/safeUrl';
|
||
|
||
// 同一用户的网页端开放结果缓存,避免每次顶栏重渲染都请求。
|
||
// 带 TTL:开放范围(分组/企业/黑名单)是管理员随时可改的,永不过期的缓存会
|
||
// 让"已被移出开放范围"的用户在整页刷新前一直看得到入口,点进去才被拒。
|
||
// 与后端 AccessCheckCacheTTL 取同一个 60 秒口径。
|
||
const ACCESS_CACHE_TTL = 60 * 1000;
|
||
const accessCache = new Map(); // userId -> { allowed, expires }
|
||
|
||
// 顶栏常驻,hook 的 effect 只在依赖变化时重跑:缓存过期或被清掉本身不会触发
|
||
// 任何实例重查,入口就一直停在页面加载时的判定上,直到整页刷新。这里用一个
|
||
// 模块级版本号把"该重查了"通知到每个实例:清缓存、每 60 秒一次、回到页面时各
|
||
// 推一版;缓存未过期的实例收到通知后不发请求
|
||
let accessVersion = 0;
|
||
const accessListeners = new Set();
|
||
function bumpAccessVersion() {
|
||
accessVersion += 1;
|
||
accessListeners.forEach((listener) => listener(accessVersion));
|
||
}
|
||
if (typeof document !== 'undefined') {
|
||
document.addEventListener('visibilitychange', () => {
|
||
if (document.visibilityState === 'visible') bumpAccessVersion();
|
||
});
|
||
setInterval(() => {
|
||
if (document.visibilityState === 'visible' && accessListeners.size > 0) {
|
||
bumpAccessVersion();
|
||
}
|
||
}, ACCESS_CACHE_TTL);
|
||
}
|
||
|
||
// 管理员在系统设置里改了开放范围后调用,让顶栏入口立刻重新询问后端,而不是
|
||
// 等 60 秒缓存过期
|
||
export function invalidateWeyAiAccessCache() {
|
||
accessCache.clear();
|
||
bumpAccessVersion();
|
||
}
|
||
|
||
function cachedAllowed(userId) {
|
||
const cached = userId ? accessCache.get(userId) : undefined;
|
||
return !!cached && cached.expires > Date.now() && cached.allowed === true;
|
||
}
|
||
|
||
// 只接受 http(s) 绝对地址,其他协议一律当作未配置
|
||
function trimTrailingSlash(url) {
|
||
return toSafeHttpUrl(url).replace(/\/+$/, '');
|
||
}
|
||
|
||
/**
|
||
* 顶部导航「WeyAi」入口(方案 4.7):
|
||
* - /api/status 的 weyai_web_enabled 为真且配置了 weyai_web_url 才考虑显示;
|
||
* - 已登录时按 GET /api/client/v1/web/access 的 allowed 决定;
|
||
* - 未登录时照常显示,点击由导航按 requireAuth 引导去登录。
|
||
* 返回 { visible, url },url 为 `<weyai_web_url>/sso/start?lang=<当前界面语言>`。
|
||
*
|
||
* lang 是把本站当前的界面语言交给网关:网关的启动/提示页本来按浏览器语言显示,
|
||
* 两者不一致时(系统中文、在这里选了英文)跳过去就换了语言。网关支持
|
||
* zh / zh-TW / en / ja / ko / th(与 LANGUAGE_CATALOG 同码),其余忽略并回落到
|
||
* Accept-Language;它把这个值跟着 SSO state 带到登录完成才存,所以中途跳转、
|
||
* rel="noreferrer" 都不影响。
|
||
*/
|
||
export function useWeyAiWebEntry() {
|
||
const { i18n } = useTranslation();
|
||
const [statusState] = useContext(StatusContext);
|
||
const [userState] = useContext(UserContext);
|
||
const status = statusState?.status;
|
||
const enabled =
|
||
status?.weyai_web_enabled === true || status?.weyai_web_enabled === 'true';
|
||
const baseUrl = trimTrailingSlash(status?.weyai_web_url);
|
||
const userId = userState?.user?.id || 0;
|
||
|
||
// 初值必须取缓存里的布尔结果而不是缓存条目本身:条目对象永远为真,会让
|
||
// 被拒用户在每次顶栏重挂载时先闪一下 WeyAi 入口
|
||
const [allowed, setAllowed] = useState(() => cachedAllowed(userId));
|
||
const [version, setVersion] = useState(accessVersion);
|
||
|
||
useEffect(() => {
|
||
accessListeners.add(setVersion);
|
||
return () => {
|
||
accessListeners.delete(setVersion);
|
||
};
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
if (!enabled || !baseUrl || !userId) {
|
||
setAllowed(false);
|
||
return undefined;
|
||
}
|
||
const cached = accessCache.get(userId);
|
||
if (cached && cached.expires > Date.now()) {
|
||
setAllowed(cached.allowed);
|
||
return undefined;
|
||
}
|
||
let cancelled = false;
|
||
API.get('/api/client/v1/web/access', { skipErrorHandler: true })
|
||
.then((res) => {
|
||
const body = res?.data;
|
||
const data = body && 'data' in body ? body.data : body;
|
||
const ok = body?.success !== false && data?.allowed === true;
|
||
accessCache.set(userId, {
|
||
allowed: ok,
|
||
expires: Date.now() + ACCESS_CACHE_TTL,
|
||
});
|
||
if (!cancelled) setAllowed(ok);
|
||
})
|
||
.catch(() => {
|
||
// 接口不可用(例如后端尚未部署)时不显示入口,也不缓存;下一版通知
|
||
//(60 秒、回到页面、管理员改范围)再试
|
||
if (!cancelled) setAllowed(false);
|
||
});
|
||
return () => {
|
||
cancelled = true;
|
||
};
|
||
}, [enabled, baseUrl, userId, version]);
|
||
|
||
const visible = enabled && !!baseUrl && (!userId || allowed);
|
||
const lang = normalizeLanguage(i18n.language);
|
||
return {
|
||
visible,
|
||
url: baseUrl ? `${baseUrl}/sso/start?lang=${encodeURIComponent(lang)}` : '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 桌面端下载入口(顶栏按钮 / 用户中心侧栏项共用一套判定):
|
||
* - 后台未开「桌面端下载页」→ 不显示;
|
||
* - 网页端未配置(开关/地址/密钥缺一)→ 桌面端没有独立的开放范围,登录即可用,只看下载开关;
|
||
* - 网页端已配置 → 沿用网页端开放范围(含黑名单):管理员没开放 WeyAi 的人不推送入口。
|
||
* 只对已登录用户为真;/weyai/download 本身是公开路由,未登录访客仍可直接访问。
|
||
*/
|
||
export function useWeyAiDownloadEntry() {
|
||
const [statusState] = useContext(StatusContext);
|
||
const [userState] = useContext(UserContext);
|
||
const status = statusState?.status;
|
||
const downloadEnabled =
|
||
status?.weyai_download_enabled === true ||
|
||
status?.weyai_download_enabled === 'true';
|
||
const webEnabled =
|
||
status?.weyai_web_enabled === true || status?.weyai_web_enabled === 'true';
|
||
const { visible: webVisible } = useWeyAiWebEntry();
|
||
const loggedIn = !!userState?.user?.id;
|
||
return {
|
||
visible: downloadEnabled && loggedIn && (!webEnabled || webVisible),
|
||
};
|
||
}
|