From fe54bd0b627bead56483755a529b35c810479423 Mon Sep 17 00:00:00 2001 From: tianfeng <769204422@qq.com> Date: Thu, 21 Aug 2025 16:48:48 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Eapp=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/appConnectionManager.js | 74 ++++++++++++ src/utils/useOptimizedAppConnection.js | 155 +++++++++++++++++++++++++ src/views/HostCenterView.vue | 148 ++++++++++++++--------- 3 files changed, 324 insertions(+), 53 deletions(-) create mode 100644 src/utils/appConnectionManager.js create mode 100644 src/utils/useOptimizedAppConnection.js diff --git a/src/utils/appConnectionManager.js b/src/utils/appConnectionManager.js new file mode 100644 index 0000000..16a4b67 --- /dev/null +++ b/src/utils/appConnectionManager.js @@ -0,0 +1,74 @@ +// APP连接状态管理器 +class AppConnectionManager { + constructor() { + this.connected = false + this.connecting = false + this.headerInfo = null + this.connectionPromise = null + this.lastConnectTime = null + this.connectionTimeout = 5 * 60 * 1000 // 5分钟超时重连 + } + + // 检查是否需要重新连接 + needsReconnect() { + if (!this.connected) return true + if (!this.lastConnectTime) return true + + const now = Date.now() + return (now - this.lastConnectTime) > this.connectionTimeout + } + + // 获取连接状态 + isConnected() { + return this.connected && !this.needsReconnect() + } + + // 获取头部信息 + getHeaderInfo() { + return this.headerInfo + } + + // 设置连接状态 + setConnected(headerInfo = null) { + this.connected = true + this.connecting = false + this.headerInfo = headerInfo + this.lastConnectTime = Date.now() + this.connectionPromise = null + console.debug('✅ APP连接状态已更新') + } + + // 设置连接中状态 + setConnecting(promise) { + this.connecting = true + this.connectionPromise = promise + } + + // 重置连接状态 + reset() { + this.connected = false + this.connecting = false + this.headerInfo = null + this.connectionPromise = null + this.lastConnectTime = null + console.debug('🔄 APP连接状态已重置') + } + + // 获取当前连接Promise + getConnectionPromise() { + return this.connectionPromise + } + + // 是否正在连接中 + isConnecting() { + return this.connecting + } +} + +// 创建全局实例 +export const appConnectionManager = new AppConnectionManager() + +// 导出便捷方法 +export const isAppConnected = () => appConnectionManager.isConnected() +export const getAppHeaderInfo = () => appConnectionManager.getHeaderInfo() +export const resetAppConnection = () => appConnectionManager.reset() diff --git a/src/utils/useOptimizedAppConnection.js b/src/utils/useOptimizedAppConnection.js new file mode 100644 index 0000000..0a3d2d3 --- /dev/null +++ b/src/utils/useOptimizedAppConnection.js @@ -0,0 +1,155 @@ +import { appConnectionManager, isAppConnected, getAppHeaderInfo } from './appConnectionManager.js' +import { connectApplication, parseAccessOrigin, parseHeader, setHttpHeaders, isInApp } from './appBridge.js' + +/** + * 优化的APP连接工具 + * 避免重复连接,提升性能 + */ +export const useOptimizedAppConnection = () => { + // 优化的连接方法 + const connectToAppOptimized = async (router, options = {}) => { + const { + fetchDataCallback = null, + onConnectionSuccess = null, + onConnectionFailed = null + } = options + + console.group('🔗 Optimized APP Connection') + console.debug('🚀 Starting connection check...') + + // 检查是否在APP环境中 + if (!isInApp()) { + console.debug('🌐 Browser environment - skipping APP connection') + if (fetchDataCallback) { + await fetchDataCallback() + } + console.groupEnd() + return { success: true, fromCache: false } + } + + // 检查是否已经连接且有效 + if (isAppConnected()) { + console.debug('✅ Using existing valid connection') + const headerInfo = getAppHeaderInfo() + + if (fetchDataCallback) { + await fetchDataCallback() + } + if (onConnectionSuccess) { + onConnectionSuccess(headerInfo) + } + + console.groupEnd() + return { success: true, fromCache: true, headerInfo } + } + + // 检查是否有进行中的连接 + if (appConnectionManager.isConnecting()) { + console.debug('⏳ Waiting for existing connection...') + try { + await appConnectionManager.getConnectionPromise() + const headerInfo = getAppHeaderInfo() + + if (fetchDataCallback) { + await fetchDataCallback() + } + if (onConnectionSuccess) { + onConnectionSuccess(headerInfo) + } + + console.groupEnd() + return { success: true, fromCache: true, headerInfo } + } catch (error) { + console.error('❌ Existing connection failed:', error) + if (onConnectionFailed) { + onConnectionFailed(error) + } + console.groupEnd() + return { success: false, error } + } + } + + // 建立新连接 + console.debug('📱 Establishing new APP connection...') + const connectionPromise = new Promise((resolve, reject) => { + connectApplication(async (access) => { + try { + const result = parseAccessOrigin(access) + + if (result.success) { + const headerInfo = parseHeader(result.data) + await setHttpHeaders(headerInfo) + + // 更新连接状态 + appConnectionManager.setConnected(headerInfo) + + console.debug('🎉 New connection established') + + if (fetchDataCallback) { + await fetchDataCallback() + } + if (onConnectionSuccess) { + onConnectionSuccess(headerInfo) + } + + resolve({ success: true, fromCache: false, headerInfo }) + } else { + console.error('❌ Failed to parse access:', result.error) + appConnectionManager.reset() + + if (router) { + router.push({ path: '/not_app', query: { message: result.error }}) + } + if (onConnectionFailed) { + onConnectionFailed(new Error(result.error)) + } + + reject(new Error(result.error)) + } + } catch (error) { + console.error('❌ Connection process failed:', error) + appConnectionManager.reset() + + if (onConnectionFailed) { + onConnectionFailed(error) + } + + reject(error) + } + }) + }) + + appConnectionManager.setConnecting(connectionPromise) + + try { + const result = await connectionPromise + console.groupEnd() + return result + } catch (error) { + console.groupEnd() + return { success: false, error } + } + } + + // 重置连接 + const resetConnection = () => { + appConnectionManager.reset() + } + + // 检查连接状态 + const checkConnectionStatus = () => { + return { + isConnected: isAppConnected(), + isConnecting: appConnectionManager.isConnecting(), + headerInfo: getAppHeaderInfo() + } + } + + return { + connectToAppOptimized, + resetConnection, + checkConnectionStatus, + isAppConnected, + getAppHeaderInfo + } +} diff --git a/src/views/HostCenterView.vue b/src/views/HostCenterView.vue index 42f3f9f..a6630b3 100644 --- a/src/views/HostCenterView.vue +++ b/src/views/HostCenterView.vue @@ -130,6 +130,7 @@ import { useRouter } from 'vue-router' import MobileHeader from '../components/MobileHeader.vue' import { getBankBalance, getUserIdentity, getTeamEntry, getTeamMemberWorkStatistics } from '../api/wallet.js' import { connectApplication, parseAccessOrigin, parseHeader, setHttpHeaders, isInApp } from '../utils/appBridge.js' +import { appConnectionManager, isAppConnected, getAppHeaderInfo } from '../utils/appConnectionManager.js' import {getUserId, setUserInfo} from '../utils/userStore.js' import {showError} from "@/utils/toast.js"; @@ -143,19 +144,15 @@ const headerInfo = ref({}) const userProfile = ref(null) const identityChecked = ref(false) -// 连接APP并获取认证信息 +// 连接APP并获取认证信息(优化版) const connectToApp = async () => { - console.group('🔗 APP Connection Process') - console.debug('🚀 Starting APP connection...') + console.group('🔗 APP Connection Process (Optimized)') + console.debug('🚀 Starting optimized APP connection...') + // 检查是否在APP环境中 if (!isInApp()) { console.warn('⚠️ Not running in APP environment') console.debug('🌐 Browser environment detected') - console.debug('📱 APP Bridge objects:') - console.debug(' - window.app:', !!window.app) - console.debug(' - window.webkit:', !!window.webkit) - - // 非APP环境,直接执行后续逻辑 appConnected.value = true console.debug('✅ Skipping APP connection, proceeding with team entry') await fetchTeamEntry() @@ -163,49 +160,98 @@ const connectToApp = async () => { return } - console.debug('📱 APP environment detected') - console.debug('🔍 Checking APP bridge availability:') - console.debug(' - window.app:', !!window.app) - console.debug(' - window.webkit:', !!window.webkit) + // 检查是否已经连接且未过期 + if (isAppConnected()) { + console.debug('✅ APP already connected and valid') + appConnected.value = true - connectApplication(async (access) => { - const result = parseAccessOrigin(access) - - if (result.success) { - // 解析头部信息 - headerInfo.value = parseHeader(result.data) - - // 设置HTTP请求头 - console.debug('🔧 Setting HTTP headers...') - await setHttpHeaders(headerInfo.value) - - // 标记连接成功 - appConnected.value = true - - console.debug('🎉 APP connection established successfully') - - // 连接成功后获取团队信息和银行余额 - console.debug('📊 Fetching team entry and bank balance...') - const teamEntryResult = await fetchTeamEntry() - console.debug('✅ Team entry fetched') - if (teamEntryResult != null) { - await fetchBankBalance() - console.debug('✅ Bank balance fetch initiated') - - await fetchWorkStatistics() - console.debug('✅ Work statistics fetch initiated') - } - } else { - console.error('❌ Failed to parse access origin:', result.error) - console.debug('🔄 Redirecting to error page...') - // 可以显示错误提示或跳转到错误页面 - router.push({ path: '/not_app', query: { message: result.error }}) + // 使用缓存的头部信息 + const cachedHeaderInfo = getAppHeaderInfo() + if (cachedHeaderInfo) { + headerInfo.value = cachedHeaderInfo + console.debug('🔧 Using cached HTTP headers') } + console.debug('📊 Fetching data with existing connection...') + const teamEntryResult = await fetchTeamEntry() + if (teamEntryResult != null) { + await fetchBankBalance() + await fetchWorkStatistics() + } console.groupEnd() + return + } + + // 检查是否有正在进行的连接 + if (appConnectionManager.isConnecting()) { + console.debug('⏳ Connection already in progress, waiting...') + try { + await appConnectionManager.getConnectionPromise() + appConnected.value = true + console.debug('✅ Connected via existing process') + console.groupEnd() + return + } catch (error) { + console.error('❌ Failed to wait for existing connection:', error) + } + } + + console.debug('📱 APP environment detected, establishing new connection') + + // 创建新的连接Promise + const connectionPromise = new Promise((resolve, reject) => { + connectApplication(async (access) => { + try { + const result = parseAccessOrigin(access) + + if (result.success) { + // 解析头部信息 + headerInfo.value = parseHeader(result.data) + + // 设置HTTP请求头 + console.debug('🔧 Setting HTTP headers...') + await setHttpHeaders(headerInfo.value) + + // 标记连接成功 + appConnected.value = true + appConnectionManager.setConnected(headerInfo.value) + + console.debug('🎉 APP connection established successfully') + + // 连接成功后获取团队信息和银行余额 + console.debug('📊 Fetching team entry and bank balance...') + const teamEntryResult = await fetchTeamEntry() + if (teamEntryResult != null) { + await fetchBankBalance() + await fetchWorkStatistics() + } + + resolve() + } else { + console.error('❌ Failed to parse access origin:', result.error) + appConnectionManager.reset() + router.push({ path: '/not_app', query: { message: result.error }}) + reject(new Error(result.error)) + } + } catch (error) { + console.error('❌ Connection process failed:', error) + appConnectionManager.reset() + reject(error) + } + }) }) - console.debug('⏳ Waiting for APP response...') + // 设置连接状态 + appConnectionManager.setConnecting(connectionPromise) + + try { + await connectionPromise + console.debug('✅ Connection completed successfully') + } catch (error) { + console.error('❌ Connection failed:', error) + } + + console.groupEnd() } // 获取银行余额 @@ -405,16 +451,12 @@ const transfer = () => { router.push('/transfer') } -// 页面加载时先连接APP,然后获取数据 +// 页面加载时优化连接逻辑 onMounted(async () => { - // 先连接APP获取认证信息 - await connectToApp() + console.debug('📄 HostCenterView mounted') - // 如果不是APP环境,直接获取数据 - if (!isInApp()) { - await fetchBankBalance() - await fetchWorkStatistics() - } + // 优化的APP连接,只在必要时才连接 + await connectToApp() })