Files
xbcr/static/js/map-utils.js

459 lines
23 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ========== 通用确认弹窗(替换 window.confirm) ==========
// 为什么不用 confirm:原生壳是 Android WebView,WebView 默认不弹 JS 原生对话框
// (Chromium 需要宿主实现 onJsConfirm,未实现时 confirm 直接返回 false,用户点不到"确认")。
// 这里用页面内弹窗,行为一致但任何环境都能用。
let _appConfirmResolve = null;
function appConfirm(message, opts) {
const o = opts || {};
const modal = document.getElementById("app-confirm-modal");
const titleEl = document.getElementById("app-confirm-title");
const textEl = document.getElementById("app-confirm-text");
const okBtn = document.getElementById("app-confirm-ok");
const cancelBtn = document.getElementById("app-confirm-cancel");
if (!modal || !textEl) { // 极老页面兜底
return Promise.resolve(window.confirm ? window.confirm(message) : true);
}
titleEl.textContent = o.title || "确认操作";
// 支持换行(保留 \n 的排版)
textEl.innerHTML = String(message || "")
.split("\n")
.map(line => escHtml(line))
.join("<br/>");
okBtn.textContent = o.okText || "确认";
cancelBtn.textContent = o.cancelText || "取消";
okBtn.classList.toggle("danger", !!o.danger);
return new Promise(resolve => {
_appConfirmResolve = resolve;
const finish = (val) => {
modal.classList.remove("show");
okBtn.onclick = null;
cancelBtn.onclick = null;
modal.onclick = null;
_appConfirmResolve = null;
resolve(val);
};
okBtn.onclick = (e) => { e.stopPropagation(); finish(true); };
cancelBtn.onclick = (e) => { e.stopPropagation(); finish(false); };
modal.onclick = (e) => { if (e.target === modal) finish(false); };
modal.classList.add("show");
});
}
function appConfirmClose() {
if (_appConfirmResolve) {
const r = _appConfirmResolve;
_appConfirmResolve = null;
document.getElementById("app-confirm-modal").classList.remove("show");
r(false);
}
}
function mapSnapshotNow() {
return renderedMapSnapshot
? renderedMapSnapshot.serverTime + (performance.now() - renderedMapSnapshot.receivedAt) / 1000
: Date.now() / 1000;
}
function updateMapFreshnessBadge() {
const el = document.getElementById("update-time");
if (!el) return;
const stamp = Number(renderedMapSnapshot?.fetched_at);
if (renderedMapSnapshot && Number.isFinite(stamp) && renderedMapSnapshot.fetched_at !== null) {
el.textContent = new Date(stamp * 1000).toLocaleTimeString('zh-CN', {
timeZone: 'Asia/Shanghai', hour: '2-digit', minute: '2-digit'
});
const expired = mapSnapshotNow() >= Number(renderedMapSnapshot.expires_at);
el.classList.toggle("stale", expired || mapRefreshFailed);
} else if (mapRefreshFailed) {
el.textContent = "更新失败";
el.classList.add("stale");
}
el.onclick = showFreshnessDetail;
el.style.cursor = "pointer";
}
function updateTime() {
if (renderedMapSnapshot) { updateMapFreshnessBadge(); return; }
// Compatibility for a server without snapshot metadata; never show client time.
apiFetch(`/api/map/freshness?type=${encodeURIComponent(currentType)}`, { cache: "no-store" })
.then(r => r.json())
.then(result => {
if (result.rtn_code !== 0 || !result.data?.latest) return;
const el = document.getElementById("update-time");
if (!el) return;
el.textContent = String(result.data.latest).slice(11, 16);
el.classList.toggle("stale", result.data.status === "stale" || result.data.stale_seconds >= 60);
el.onclick = showFreshnessDetail;
el.style.cursor = "pointer";
})
.catch(() => {});
}
function showFreshnessDetail() {
if (renderedMapSnapshot && renderedMapSnapshot.fetched_at !== null) {
const seconds = Math.max(0, Math.floor(mapSnapshotNow() - renderedMapSnapshot.fetched_at));
const when = new Date(renderedMapSnapshot.fetched_at * 1000).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai' });
const age = seconds < 60 ? `${seconds} 秒前` : `${Math.floor(seconds / 60)} 分钟前`;
showToast(`车辆数据更新于 ${when}(${age})${mapRefreshFailed ? ',更新暂时失败,正在自动重试' : ''}`);
return;
}
showToast(mapRefreshFailed ? "地图数据暂时不可用,正在自动重试" : "正在获取最新车辆数据");
}
function showToast(msg) {
const t = document.getElementById("toast");
t.textContent = msg;
t.classList.add("show");
setTimeout(() => t.classList.remove("show"), 2500);
}
// ========== 抓包工具下载 ==========
// 安装包是 Windows exe,任何手机/平板都跑不了;微信、QQ、支付宝等内置
// WebView 还会直接拦截 exe 下载。这两类情况都改为提示复制链接到电脑浏览器。
const CAPTURE_TOOL_PATH = "/download/capture-tool.exe";
// 鸿蒙 UA 有两种:老版 HarmonyOS + Android 兼容层,新版纯 OpenHarmony/ArkWeb;
// 微信鸿蒙版仍带 MicroMessenger,但部分版本 UA 精简后只剩 HarmonyOS。
function detectHarmony() {
const ua = navigator.userAgent || "";
return /OpenHarmony|HarmonyOS|ArkWeb|HMSCore/i.test(ua);
}
function detectMobile() {
const ua = navigator.userAgent || "";
const touchPoints = navigator.maxTouchPoints || 0;
// iPadOS 13+ 默认「请求桌面网站」,UA 伪装成 macOS;
// 靠触点数区分真正的 Mac(0)与 iPad(>1)
if (/Macintosh/.test(ua) && touchPoints > 1) return "iPad";
// 鸿蒙平板也常带 Tablet,先于手机判断
if (/OpenHarmony|HarmonyOS|ArkWeb/.test(ua)) {
return /Tablet/i.test(ua) ? "鸿蒙平板" : "鸿蒙手机";
}
if (/iPhone|iPod/.test(ua)) return "iPhone";
if (/iPad/.test(ua)) return "iPad";
if (/Android/.test(ua)) return /Tablet/i.test(ua) ? "安卓平板" : "安卓手机";
// 兜底:UA 明确标了 Mobile 但没给出具体平台
if (/Mobile/i.test(ua)) return "手机";
return null;
}
// 返回需要拦截的"环境名",null 表示可以直接下载
function detectInAppBrowser() {
const ua = navigator.userAgent || "";
// 原生壳优先判断:它是最外层容器,UA 里可能同时带 Android
if (/xbniu-native/i.test(ua)) return "APP";
if (/MicroMessenger/i.test(ua)) return detectHarmony() ? "鸿蒙微信" : "微信";
if (/\bQQ\/|QQBrowser/i.test(ua)) return "QQ";
if (/AlipayClient/i.test(ua)) return "支付宝";
if (/DingTalk/i.test(ua)) return "钉钉";
if (/Weibo/i.test(ua)) return "微博";
if (/aweme|ByteDance/i.test(ua)) return "抖音";
return null;
}
function captureToolUrl() {
return new URL(CAPTURE_TOOL_PATH, window.location.href).href;
}
// 返回 true 时放行 <a download> 的原生下载
function onDownloadCaptureTool(event) {
const app = detectInAppBrowser();
const mobile = app ? null : detectMobile(); // 内嵌环境优先,文案更具体
if (!app && !mobile) return true;
if (event) event.preventDefault();
showDownloadTipModal(app, mobile);
return false;
}
function showDownloadTipModal(appName, mobileName) {
const title = document.getElementById("download-tip-title");
const desc = document.getElementById("download-tip-desc");
const hint = document.getElementById("download-tip-hint");
title.textContent = "请在电脑上下载安装";
if (appName) {
desc.textContent = `${appName}内无法直接下载安装包。请复制下面的链接,在电脑浏览器中打开下载。`;
hint.textContent = "安装包为 Windows 程序,手机端下载后无法运行。";
} else {
// 普通移动端浏览器:能下载但装了也用不了,引导去电脑
desc.textContent = `当前是${mobileName || "移动设备"},安装包为 Windows 程序,在此设备上无法运行。请复制下面的链接,在电脑浏览器中打开下载。`;
hint.textContent = "";
}
hint.style.display = hint.textContent ? "block" : "none";
document.getElementById("download-tip-link").value = captureToolUrl();
document.getElementById("download-tip-modal").classList.add("show");
}
function closeDownloadTipModal() {
document.getElementById("download-tip-modal").classList.remove("show");
}
// ========== 数据导出(CSV 直链,1 小时有效) ==========
// 流程:POST /api/export/create(登录态)→ 拿到免登录直链。
// UA 复用 detectInAppBrowser:微信/QQ/支付宝/钉钉/微博/抖音/原生壳内无法直接下载,
// 弹「复制链接到外部浏览器」提示;普通浏览器直接触发下载。
function closeExportTipModal() {
document.getElementById("export-tip-modal").classList.remove("show");
}
async function copyExportLink() {
const url = document.getElementById("export-tip-link").value;
const input = document.getElementById("export-tip-link");
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(url);
showToast("链接已复制,请在浏览器中打开");
return;
}
throw new Error("clipboard unavailable");
} catch (e) {
try {
input.removeAttribute("readonly");
input.select();
document.execCommand("copy");
input.setAttribute("readonly", "");
showToast("链接已复制,请在浏览器中打开");
} catch (e2) {
showToast("复制失败,请长按链接手动复制");
}
}
}
async function exportHistoryCsv() {
if (!authToken) { showToast("请先登录"); return; }
showToast("正在生成导出链接...");
try {
const resp = await apiFetch("/api/export/create", {
method: "POST",
headers: { "Content-Type": "application/json",
"Authorization": `Bearer ${authToken}` },
body: JSON.stringify({ type: "history_csv" })
});
const data = await resp.json();
if (data.rtn_code !== 0) {
showToast(data.message || "生成导出链接失败");
return;
}
const url = new URL(data.data.url, window.location.href).href;
const app = detectInAppBrowser();
if (app) {
// 微信/原生壳等内嵌环境:给直链,复制到外部浏览器下载(直链免登录,1小时有效)
document.getElementById("export-tip-desc").textContent =
`${app}内无法直接下载文件。请复制下面的链接到系统浏览器打开(免登录,${data.data.ttl_hours} 小时内有效)。`;
document.getElementById("export-tip-link").value = url;
document.getElementById("export-tip-modal").classList.add("show");
return;
}
// 普通浏览器:直接下载,同时保留直链以便换浏览器使用
const a = document.createElement("a");
a.href = url;
a.download = "";
document.body.appendChild(a);
a.click();
a.remove();
showToast(`已开始下载(直链 ${data.data.ttl_hours} 小时内有效)`);
} catch (err) {
showToast("导出失败,请重试");
}
}
async function copyDownloadLink() {
const url = captureToolUrl();
const input = document.getElementById("download-tip-link");
// 微信等 WebView 常禁用 navigator.clipboard(非安全上下文或权限拒绝),
// 回退到选中 + execCommand 的老办法
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(url);
showToast("链接已复制");
return;
}
throw new Error("clipboard unavailable");
} catch (e) {
try {
input.removeAttribute("readonly");
input.select();
input.setSelectionRange(0, url.length);
const ok = document.execCommand("copy");
input.setAttribute("readonly", "readonly");
showToast(ok ? "链接已复制" : "复制失败,请长按链接手动复制");
} catch (e2) {
showToast("复制失败,请长按链接手动复制");
}
}
}
// 底层异常转用户提示:网关/错误页返回 HTML 时 resp.json() 会抛
// "Unexpected token '<' ... is not valid JSON",直接展示既难懂又含 token 字样易引起误解
function friendlyError(e) {
const msg = (e && e.message) || "";
if (/Unexpected token|is not valid JSON|JSON\.parse/i.test(msg)) {
return "服务响应异常,请稍后重试";
}
return msg || "网络错误,请重试";
}
// ========== Token失效弹窗 ==========
// 仅在真正检测到微信凭据失效时调用;带冷却时间,避免轮询/刷新反复打扰
let _credInvalidLastShownAt = 0;
const CRED_INVALID_MODAL_COOLDOWN = 10 * 60 * 1000; // 10 分钟内不重复弹出
function notifyCredentialInvalid(message) {
const modal = document.getElementById("token-expired-modal");
if (!modal || modal.classList.contains("show")) return;
if (Date.now() - _credInvalidLastShownAt < CRED_INVALID_MODAL_COOLDOWN) return;
_credInvalidLastShownAt = Date.now();
showTokenExpiredModal(null, message);
}
function showTokenExpiredModal(customTitle, customDesc) {
document.getElementById("token-expired-title").textContent = customTitle || "token已失效,请重新登录";
document.getElementById("token-expired-desc").textContent = customDesc || "您的微信凭据已过期,请重新抓包获取最新的 Token ID(及 AccessToken)";
document.getElementById("token-expired-modal").classList.add("show");
// 预填当前用户已有的token信息
loadExpiredTokenFields();
}
function closeTokenExpiredModal() {
document.getElementById("token-expired-modal").classList.remove("show");
document.getElementById("expired-tip").textContent = "";
}
async function loadExpiredTokenFields() {
if (!authToken) return;
try {
const resp = await apiFetch("/api/auth/profile", {
headers: { "Authorization": `Bearer ${authToken}` }
});
const data = await resp.json();
if (data.rtn_code === 0 && data.data) {
document.getElementById("expired-token-id").value = data.data.token_id || "";
document.getElementById("expired-signature").value = data.data.token || "";
}
} catch (e) { /* ignore */ }
}
async function saveExpiredToken() {
if (!authToken) {
document.getElementById("expired-tip").textContent = "请先登录";
return;
}
const token_id = document.getElementById("expired-token-id").value.trim();
const access_token = document.getElementById("expired-signature").value.trim();
const tip = document.getElementById("expired-tip");
if (!token_id) {
tip.textContent = "Token ID 必填;AccessToken 选填";
return;
}
tip.textContent = "验证中...";
try {
const verifyResp = await apiFetch("/api/auth/verify_token", {
method: "POST",
headers: { "Content-Type": "application/json",
"Authorization": `Bearer ${authToken}` },
body: JSON.stringify({ access_token, token_id })
});
const verifyData = await verifyResp.json();
if (!verifyData.valid) {
tip.textContent = verifyData.message || "凭据验证失败,请检查 Token ID 是否正确";
return;
}
} catch (err) {
tip.textContent = "验证失败";
return;
}
try {
const resp = await apiFetch("/api/auth/save_token", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${authToken}`
},
body: JSON.stringify({ access_token, token_id })
});
const data = await resp.json();
if (data.rtn_code === 0) {
tip.textContent = "";
closeTokenExpiredModal();
showToast("凭证已更新 ✓");
} else {
tip.textContent = data.message || "保存失败";
}
} catch (err) {
tip.textContent = "保存失败";
}
}
// ================= 版本号 & 更新说明 =================
const VERSION_TAG = "v1.7.0-preview";
const VERSION_LOGS = [
{ v: "v1.7.0 预览", items: ["新增附近列表、车型与电量筛选、校园地点搜索和常用地点", "完善定位失败引导、订阅编辑与执行结果、历史订单筛选和分页", "统一车辆状态,支持5位和8位车牌,增加浅色、深色和跟随系统"] },
{ v: "v1.6.0", items: [
"新增用车设置:可独立开启或关闭邮件提醒,并多选到期前 10、5、3、2、1 分钟及到期时提醒",
"支持实时调整用车到期时间,当前订单也会立即按新时长更新;默认 19 分钟,月卡前 20 分钟免费并预留 1 分钟容错",
"新增自动还车开关;关闭后到期邮件只提醒手动还车,不再显示已自动还车或自动还车失败",
"共享用车按实际骑行人的到期与自动还车设置执行,车主和骑行人分别按各自设置接收美化后的 HTML 邮件及一键还车入口",
"修复共享车主重复显示订单横幅,并修复普通/共享车辆已锁车但接口响应异常时误报还车失败的问题"
] },
{ v: "v1.5.0", items: [
"新增共享电动车自定义昵称"
] },
{ v: "v1.4.0", items: [
"支持多设备同时登录:同一账号可在多台设备/多个浏览器同时在线,不再相互顶下线",
"个人中心新增“登录设备管理”:可查看当前账号各登录设备(记录系统/浏览器与最近活跃),随时下线其它设备或一键下线其它所有设备",
"统一个人中心/凭证/设备管理的深浅色模式适配"
] },
{ v: "v1.3.0", items: [
"新增「共享电动车」功能:向车主申请共享其电动车;接受后可设置每天可用次数、是否需要车主持有优惠卡、优惠卡剩余次数下限(低于则不能用)",
"开锁时可选择“用自己的账号”或“用共享者的账号”(附实时可用次数;今日次数用完的共享者默认隐藏)",
"用车横幅区分“共享中/使用XX的车中”,车主与被共享者都能还车",
"个人中心新增“共享电动车”入口,双Tab管理(可使用的/我共享的),双方都可解绑"
] },
{ v: "v1.2.0", items: [
"修复远程扫码被拦截:开锁上报车辆附近随机位置",
"请求头对齐当前版本微信环境"
] }
];
// 右下角版本徽标始终跟随 VERSION_TAG,避免与更新说明不一致
(function () {
var b = document.getElementById("version-badge");
if (b) b.textContent = VERSION_TAG;
})();
let versionModalInited = false;
let versionAutoTries = 0;
function openVersionModal() {
if (!versionModalInited) {
const el = document.getElementById("version-content");
el.innerHTML = VERSION_LOGS.map(l =>
`<h4>${l.v}</h4><ul>${l.items.map(i => `<li>${i}</li>`).join("")}</ul>`
).join("");
versionModalInited = true;
}
// 记录已查看当前版本,避免每次打开都弹
try { localStorage.setItem("version_seen", VERSION_TAG); } catch (e) {}
document.getElementById("version-modal").classList.add("show");
}
function closeVersionModal() {
document.getElementById("version-modal").classList.remove("show");
}
// 新版本/首次打开自动弹当前版本更新说明(每版本每浏览器只自动弹一次)
function maybeAutoShowVersion() {
// Update notes are available from Settings; first visits stay focused on finding a bike.
}
async function previewLogin(button) {
button = button || document.querySelector("[data-preview-demo]") || document.getElementById("auth-btn");
await doLogin("demo@preview.local", "preview123", document.getElementById("gate-tip"), button);
if (currentUser?.email === "demo@preview.local" && typeof SettingsPages !== "undefined") SettingsPages.close();
}
async function createPreviewSession() {
return AppAPI.run("preview-session", null, async () => {
try {
let result = null;
const saved = localStorage.getItem("xbniu_preview_live_token");
if (saved) {
const status = await (await apiFetch("/api/auth/status", {headers:{Authorization:`Bearer ${saved}`}})).json();
if (status.data?.logged_in) result = {rtn_code:0,data:{token:saved,email:status.data.email}};
}
if (!result) result = await (await apiFetch("/api/preview/session", {method:"POST"})).json();
if (result.rtn_code !== 0) throw new Error(result.message || "创建失败");
if (currentUser?.email !== result.data.email) resetMapForAccount();
authToken = result.data.token; currentUser = {email:result.data.email}; localStorage.setItem("auth_token",authToken);
localStorage.setItem("xbniu_preview_live_token", authToken);
updateAuthButton(); hideLoginGate(); closeAllModals(); clearRentalState(); hideOrderBanner();
currentOrder = null;
if (map) loadMapData(currentType, false);
showToast("独立测试账号已创建,请填写微信凭证后测试真实接口");
openSettingsPage(); openAuthModal();
} catch (error) { showToast(error.message || "创建失败,请重试"); }
});
}