Commit b6fdfad6 by 胡悦

feat: 新增安卓隐私协议合规管理功能

- 新增隐私同意状态管理的Vuex模块与本地存储持久化
- 添加安卓原生隐私政策弹窗配置文件androidPrivacy.json
- 限制设备信息、OAID、系统信息的获取仅在用户同意隐私协议后
- 更新WebSocket、远程日志及其他功能的初始化逻辑以适配合规要求
- 重构登录状态清除逻辑,将存储操作改为异步形式
- 清理未使用的地理位置、地图相关权限及SDK配置
- 提取设备信息工具模块,优化合规相关代码结构
1 parent 00745b41
...@@ -23,6 +23,7 @@ export default { ...@@ -23,6 +23,7 @@ export default {
onLaunch: async function () { onLaunch: async function () {
console.warn('[boot] App.onLaunch start') console.warn('[boot] App.onLaunch start')
onAppColdLaunch() onAppColdLaunch()
await this.$store.dispatch('initializePrivacyConsent')
if (isUniRuntimeBroken()) { if (isUniRuntimeBroken()) {
console.warn('[boot] App.onLaunch -> scheduleRecoverToLogin (broken)') console.warn('[boot] App.onLaunch -> scheduleRecoverToLogin (broken)')
scheduleRecoverToLogin() scheduleRecoverToLogin()
...@@ -30,7 +31,7 @@ export default { ...@@ -30,7 +31,7 @@ export default {
} }
captureLaunchEnv(this) captureLaunchEnv(this)
this.onKeep() this.onKeep()
this.setAPPVersion() await this.setAPPVersion()
setTimeout(() => { setTimeout(() => {
try { try {
plus.screen.unlockOrientation() //解除锁定屏幕方向 plus.screen.unlockOrientation() //解除锁定屏幕方向
...@@ -57,15 +58,17 @@ export default { ...@@ -57,15 +58,17 @@ export default {
// } // }
// ) // )
}, },
setAPPVersion() { async setAPPVersion() {
let version = plus.runtime.version let version = plus.runtime.version
let storageVersion = uni.$storage.get('storageVersion') let storageVersion = uni.$storage.get('storageVersion')
uni.$logger?.local?.info?.(`storageVersion ->${storageVersion}, version ->${version}`) uni.$logger?.local?.info?.(`storageVersion ->${storageVersion}, version ->${version}`)
if (storageVersion != version) { if (storageVersion != version) {
uni.$storage.rm('userInfo') await Promise.all([
uni.$storage.rm('noSignInUuid') uni.$storage.rm('userInfo'),
uni.$storage.rm('noSignInUuid')
])
} }
uni.$storage.set('storageVersion', version) await uni.$storage.set('storageVersion', version)
} }
}, },
......
{
"version": "1",
"prompt": "template",
"title": "服务协议和隐私政策",
"message": "请您务必审慎阅读、充分理解《服务协议》和《隐私政策》的各项条款。为了向您提供服务,我们可能会收集设备标识、操作日志等信息,具体收集和使用情况请查看<a href=\"https://img01.glsx.com.cn/weapp/resource/miniprogram/market-assistant/html/agreement.html\">《服务协议》</a>和<a href=\"https://img01.glsx.com.cn/weapp/resource/miniprogram/market-assistant/html/privacy.html\">《隐私政策》</a>。如您同意,请点击“同意并继续”。",
"buttonAccept": "同意并继续",
"buttonRefuse": "暂不同意",
"hrefLoader": "system",
"backToExit": "true",
"second": {
"title": "确认提示",
"message": "进入应用前,您需要先同意<a href=\"https://img01.glsx.com.cn/weapp/resource/miniprogram/market-assistant/html/agreement.html\">《服务协议》</a>和<a href=\"https://img01.glsx.com.cn/weapp/resource/miniprogram/market-assistant/html/privacy.html\">《隐私政策》</a>,否则将退出应用。",
"buttonAccept": "同意并继续",
"buttonRefuse": "退出应用"
},
"disagreeMode": {
"support": false,
"loadNativePlugins": false,
"visitorEntry": false,
"showAlways": false
}
}
...@@ -78,6 +78,7 @@ class Request { ...@@ -78,6 +78,7 @@ class Request {
currentPage = pages[pages.length - 1] currentPage = pages[pages.length - 1]
uni.$logger.local.warn(`HTTP Triggered Logout: params:${JSON.stringify(params)} method: ${params.method}->code:${code} msg:${message} currentPage:${currentPage.route}`) uni.$logger.local.warn(`HTTP Triggered Logout: params:${JSON.stringify(params)} method: ${params.method}->code:${code} msg:${message} currentPage:${currentPage.route}`)
uni.hideLoading() uni.hideLoading()
_this.clearLoginState()
if (currentPage.route != 'pages/common/login') { if (currentPage.route != 'pages/common/login') {
uni.reLaunch({ uni.reLaunch({
url: '/pages/common/login' url: '/pages/common/login'
...@@ -290,9 +291,7 @@ class Request { ...@@ -290,9 +291,7 @@ class Request {
* 跳转到登录页 * 跳转到登录页
*/ */
redirectToLogin (reject) { redirectToLogin (reject) {
uni.$storage.set('sessionId', '') this.clearLoginState()
uni.$storage.set('userInfo', {})
uni.$storage.set('noSignInUuid', '')
uni.hideLoading() uni.hideLoading()
const pages = getCurrentPages() const pages = getCurrentPages()
const currentPage = pages[pages.length - 1] const currentPage = pages[pages.length - 1]
...@@ -304,6 +303,12 @@ class Request { ...@@ -304,6 +303,12 @@ class Request {
} }
reject('登录已过期,请重新登录') reject('登录已过期,请重新登录')
} }
clearLoginState () {
uni.$storage.rm('sessionId', true)
uni.$storage.rm('userInfo', true)
uni.$storage.rm('noSignInUuid', true)
}
} }
export default new Request() export default new Request()
...@@ -33,7 +33,9 @@ ...@@ -33,7 +33,9 @@
<script type="text/ecmascript-6"> <script type="text/ecmascript-6">
import checkUpdate from "@/uni_modules/uni-upgrade-center-app/utils/check-update-nvue.js"; import checkUpdate from "@/uni_modules/uni-upgrade-center-app/utils/check-update-nvue.js";
import { getDeviceId } from '@/utils/deviceInfo'
import utils from '@/utils/utils' import utils from '@/utils/utils'
import { mapGetters } from 'vuex'
export default { export default {
name: 'SettingBox', name: 'SettingBox',
data() { data() {
...@@ -42,15 +44,29 @@ export default { ...@@ -42,15 +44,29 @@ export default {
deviceId: '' deviceId: ''
} }
}, },
computed: {
...mapGetters(['hasPrivacyConsent'])
},
watch: {
hasPrivacyConsent: {
immediate: true,
handler(agreed) {
this.deviceId = agreed ? getDeviceId() : ''
}
}
},
mounted() { mounted() {
this.version = plus?.runtime?.version || '1.0.0' this.version = plus?.runtime?.version || '1.0.0'
const {
deviceId
} = uni.getDeviceInfo()
this.deviceId = deviceId
}, },
methods: { methods: {
copyText() { copyText() {
if (!this.deviceId) {
uni.showToast({
title: '暂无可复制的APP编码',
icon: 'none'
})
return
}
uni.setClipboardData({ uni.setClipboardData({
data: this.deviceId, data: this.deviceId,
success: function() { success: function() {
...@@ -142,16 +158,18 @@ export default { ...@@ -142,16 +158,18 @@ export default {
title: '温馨提示', title: '温馨提示',
content: '是否退出当前账号?', content: '是否退出当前账号?',
confirmColor: '#347BFF', confirmColor: '#347BFF',
success(res) { success: async (res) => {
if (res.confirm) { if (res.confirm) {
try { try {
// 清除 session 和本地存储 // 清除 session 和本地存储
uni.$storage.rm("userInfo") await Promise.all([
uni.$storage.rm("sessionId") uni.$storage.rm("userInfo"),
uni.$storage.rm("noSignInUuid") uni.$storage.rm("sessionId"),
uni.$storage.rm("beisenToken") uni.$storage.rm("noSignInUuid"),
uni.$storage.rm("studyCenterPermission") uni.$storage.rm("beisenToken"),
uni.$storage.rm("boutique_YQorderSetting") uni.$storage.rm("studyCenterPermission"),
uni.$storage.rm("boutique_YQorderSetting")
])
// 跳转至登录页面 // 跳转至登录页面
uni.reLaunch({ uni.reLaunch({
......
...@@ -138,6 +138,7 @@ export default { ...@@ -138,6 +138,7 @@ export default {
beforeDestroy() { beforeDestroy() {
// 清理 FileUploadManager 资源 // 清理 FileUploadManager 资源
FileUploadManager.destroy() FileUploadManager.destroy()
this._ws?.disconnect()
}, },
provide() { provide() {
return { return {
......
...@@ -29,9 +29,7 @@ ...@@ -29,9 +29,7 @@
"Record" : {}, "Record" : {},
"VideoPlayer" : {}, "VideoPlayer" : {},
"AudioPlayer" : {}, "AudioPlayer" : {},
"SQLite" : {}, "SQLite" : {}
"Maps" : {},
"Geolocation" : {}
}, },
/* 应用发布信息 */ /* 应用发布信息 */
"distribute" : { "distribute" : {
...@@ -50,9 +48,7 @@ ...@@ -50,9 +48,7 @@
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>", "<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.RECORD_AUDIO\"/>", "<uses-permission android:name=\"android.permission.RECORD_AUDIO\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>", "<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>", "<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
"<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>"
], ],
"abiFilters" : [ "armeabi-v7a", "arm64-v8a", "x86" ], "abiFilters" : [ "armeabi-v7a", "arm64-v8a", "x86" ],
"targetSdkVersion" : 30, "targetSdkVersion" : 30,
...@@ -74,12 +70,7 @@ ...@@ -74,12 +70,7 @@
/* SDK配置 */ /* SDK配置 */
"sdkConfigs" : { "sdkConfigs" : {
"ad" : {}, "ad" : {},
"speech" : {}, "speech" : {}
"geolocation" : {
"system" : {
"__platform__" : [ "ios", "android" ]
}
}
}, },
"icons" : { "icons" : {
"android" : { "android" : {
......
...@@ -48,12 +48,12 @@ export default { ...@@ -48,12 +48,12 @@ export default {
} }
}, },
methods: { methods: {
toLogin () { async toLogin () {
if (this._bootFallbackTimer) { if (this._bootFallbackTimer) {
clearTimeout(this._bootFallbackTimer) clearTimeout(this._bootFallbackTimer)
this._bootFallbackTimer = null this._bootFallbackTimer = null
} }
uni.$storage.rm("userInfo") await uni.$storage.rm("userInfo")
uni.reLaunch({ uni.reLaunch({
url: '/pages/common/login' url: '/pages/common/login'
}) })
...@@ -75,4 +75,4 @@ export default { ...@@ -75,4 +75,4 @@ export default {
font-size: 32rpx; font-size: 32rpx;
color: #666; color: #666;
} }
</style>
\ No newline at end of file \ No newline at end of file
</style>
...@@ -104,6 +104,8 @@ ...@@ -104,6 +104,8 @@
</template> </template>
<script type="text/ecmascript-6"> <script type="text/ecmascript-6">
import { encrypt } from '@/utils/jsencrypt' import { encrypt } from '@/utils/jsencrypt'
import { getDeviceId } from '@/utils/deviceInfo'
import { mapActions, mapGetters } from 'vuex'
export default { export default {
data () { data () {
...@@ -112,7 +114,6 @@ export default { ...@@ -112,7 +114,6 @@ export default {
password: '', password: '',
showPassword: false, showPassword: false,
noSignIn: true, noSignIn: true,
readingStatus: false,
deviceId: '', deviceId: '',
dateKey: { dateKey: {
username: 0, username: 0,
...@@ -120,17 +121,33 @@ export default { ...@@ -120,17 +121,33 @@ export default {
} }
}; };
}, },
onLoad (options) { async onLoad (options) {
if (options.username) this.username = options.username if (options.username) this.username = options.username
await this.resetPrivacyConsent()
},
computed: {
...mapGetters(['hasPrivacyConsent']),
readingStatus () {
return this.hasPrivacyConsent
}
}, },
methods: { methods: {
toggleReadingStatus () { ...mapActions([
this.readingStatus = !this.readingStatus 'resetPrivacyConsent',
if (this.readingStatus && !this.deviceId) { 'setPrivacyConsent'
const { deviceId } = uni.getDeviceInfo() ]),
this.deviceId = deviceId async toggleReadingStatus () {
const agreed = await this.setPrivacyConsent(!this.hasPrivacyConsent)
if (agreed) {
this.loadDeviceId()
} else {
this.deviceId = ''
} }
}, },
loadDeviceId () {
if (!this.hasPrivacyConsent || this.deviceId) return
this.deviceId = getDeviceId()
},
copyText () { copyText () {
uni.setClipboardData({ uni.setClipboardData({
data: this.deviceId, data: this.deviceId,
...@@ -143,12 +160,12 @@ export default { ...@@ -143,12 +160,12 @@ export default {
}); });
}, },
login: uni.$throttle(async function () { login: uni.$throttle(async function () {
const { username, password, noSignIn, readingStatus } = this; const { username, password, noSignIn } = this;
try { try {
if (!username) throw '请输入账号' if (!username) throw '请输入账号'
if (!password) throw '请输入密码' if (!password) throw '请输入密码'
if (password.length < 6 || password.length > 20) throw '密码长度为 6-20 个字符' if (password.length < 6 || password.length > 20) throw '密码长度为 6-20 个字符'
if (!readingStatus) throw '请您阅读并同意《隐私协议》' if (!this.hasPrivacyConsent) throw '请您阅读并同意《隐私协议》'
uni.showLoading({ uni.showLoading({
mask: true mask: true
......
...@@ -14,6 +14,7 @@ import audio from './modules/audio' ...@@ -14,6 +14,7 @@ import audio from './modules/audio'
import update from './modules/update' import update from './modules/update'
import sys from './modules/sys' import sys from './modules/sys'
import material from './modules/material' import material from './modules/material'
import privacy from './modules/privacy'
Vue.use(Vuex) Vue.use(Vuex)
const store = new Vuex.Store({ const store = new Vuex.Store({
...@@ -23,6 +24,7 @@ const store = new Vuex.Store({ ...@@ -23,6 +24,7 @@ const store = new Vuex.Store({
update, update,
material, material,
sys, sys,
privacy,
}, },
getters getters
}) })
......
import Storage from '@/utils/cache/storage'
const storage = new Storage()
const readStoredConsent = () => {
const value = storage.get('privacyAgreed')
return value === true || value === false ? value : null
}
const readNativeConsent = () => {
// #ifdef APP-PLUS
try {
if (
typeof plus !== 'undefined' &&
plus.runtime &&
typeof plus.runtime.isAgreePrivacy === 'function'
) {
return plus.runtime.isAgreePrivacy() === true
}
} catch (error) {
console.warn('[privacy] 原生隐私同意状态读取失败', error)
}
// #endif
return null
}
const hasLegacyUserInfo = () => {
const userInfo = storage.get('userInfo')
return Boolean(
userInfo &&
(typeof userInfo !== 'object' || Object.keys(userInfo).length > 0)
)
}
const persistConsent = async (value) => {
try {
await storage.set('privacyAgreed', value)
} catch (error) {
console.warn('[privacy] 隐私同意状态持久化失败', error)
}
}
export default {
state() {
return {
privacyAgreed: false
}
},
getters: {
hasPrivacyConsent: state => state.privacyAgreed === true
},
mutations: {
SET_PRIVACY_CONSENT(state, value) {
state.privacyAgreed = value === true
}
},
actions: {
async initializePrivacyConsent({ commit }) {
// App 启动阶段同步 androidPrivacy.json 原生弹窗状态;
// 登录页会单独重置为未勾选,要求用户手动确认。
const nativeConsent = readNativeConsent()
if (nativeConsent !== null) {
commit('SET_PRIVACY_CONSENT', nativeConsent)
await persistConsent(nativeConsent)
return nativeConsent
}
const storedConsent = readStoredConsent()
if (storedConsent !== null) {
commit('SET_PRIVACY_CONSENT', storedConsent)
return storedConsent
}
// 兼容老版本:已有有效登录信息表示用户曾在登录页勾选过隐私协议。
const migratedConsent = hasLegacyUserInfo()
commit('SET_PRIVACY_CONSENT', migratedConsent)
await persistConsent(migratedConsent)
return migratedConsent
},
async setPrivacyConsent({ commit }, value) {
const agreed = value === true
commit('SET_PRIVACY_CONSENT', agreed)
await persistConsent(agreed)
if (!agreed) {
await uni.$logger?.disableRemote?.()
}
return agreed
},
resetPrivacyConsent({ dispatch }) {
return dispatch('setPrivacyConsent', false)
}
}
}
...@@ -47,5 +47,6 @@ export const STORAGE_OBJECTKEY = { ...@@ -47,5 +47,6 @@ export const STORAGE_OBJECTKEY = {
sessionId:'sessionId', sessionId:'sessionId',
typeItem: 'typeItem', typeItem: 'typeItem',
storeInfo: 'storeInfo', storeInfo: 'storeInfo',
spPhone: 'spPhone' spPhone: 'spPhone',
privacyAgreed: 'privacyAgreed'
} }
import store from '@/store'
const warnLocal = message => {
try {
const localWarn = uni.$logger?.local?.warn
if (typeof localWarn === 'function') {
localWarn.call(uni.$logger.local, message)
} else {
console.warn(message)
}
} catch (error) {
console.warn(message)
}
}
export const hasPrivacyConsent = () => Boolean(store.getters.hasPrivacyConsent)
export const getDeviceId = () => {
if (!hasPrivacyConsent()) return ''
try {
return uni.getDeviceInfo()?.deviceId || ''
} catch (error) {
warnLocal(`获取设备编码失败:${error?.message || error}`)
return ''
}
}
export const getSystemInfo = () => {
if (!hasPrivacyConsent()) return null
try {
return uni.getSystemInfoSync()
} catch (error) {
warnLocal(`获取系统信息失败:${error?.message || error}`)
return null
}
}
export const getOAID = () => {
if (!hasPrivacyConsent()) return Promise.resolve('')
return new Promise(resolve => {
try {
if (typeof plus === 'undefined' || typeof plus.device?.getOAID !== 'function') {
resolve(getDeviceId())
return
}
plus.device.getOAID({
success: e => {
resolve(hasPrivacyConsent() ? e?.oaid || '' : '')
},
fail: () => {
resolve(getDeviceId())
}
})
} catch (error) {
warnLocal(`获取OAID失败:${error?.message || error}`)
resolve(getDeviceId())
}
})
}
...@@ -5,6 +5,7 @@ const STORAGE_KEY = 'ZY_UNI_CONFIG_BACKUP' ...@@ -5,6 +5,7 @@ const STORAGE_KEY = 'ZY_UNI_CONFIG_BACKUP'
const BG_AT_KEY = 'ZY_BG_AT' const BG_AT_KEY = 'ZY_BG_AT'
const WAS_BG_KEY = 'ZY_WAS_BACKGROUND' const WAS_BG_KEY = 'ZY_WAS_BACKGROUND'
const PROCESS_START_KEY = 'ZY_PROCESS_START' const PROCESS_START_KEY = 'ZY_PROCESS_START'
const LOGIN_URL = '/pages/common/login' const LOGIN_URL = '/pages/common/login'
const BG_REINIT_WINDOW_MS = 120000 const BG_REINIT_WINDOW_MS = 120000
...@@ -225,7 +226,7 @@ export function backupUniConfigIfPresent() { ...@@ -225,7 +226,7 @@ export function backupUniConfigIfPresent() {
function clearLoginState() { function clearLoginState() {
try { try {
uni.$storage?.rm?.('userInfo') uni.$storage?.rm?.('userInfo', true)
} catch (e) {} } catch (e) {}
try { try {
uni.removeStorageSync('userInfo') uni.removeStorageSync('userInfo')
......
import sentryInit from '@/utils/sentryConfig/sentryInit' import sentryInit from '@/utils/sentryConfig/sentryInit'
import { LogLevel , RemoteExtraDataKey} from './constants' import { LogLevel , RemoteExtraDataKey} from './constants'
import { getSystemInfo, hasPrivacyConsent } from '@/utils/deviceInfo'
class RemoteLog { class RemoteLog {
sentry = null sentry = null
constructor(user) { constructor(user) {
if (!hasPrivacyConsent()) return
this.sentry = sentryInit() this.sentry = sentryInit()
this.sentry.setUser(user) this.sentry.setUser(user)
} }
isReady() {
return Boolean(this.sentry && hasPrivacyConsent())
}
debug(info) { debug(info) {
this.send(LogLevel.DEBUG, info) return this.send(LogLevel.DEBUG, info)
} }
info(info) { info(info) {
this.send(LogLevel.INFO, info) return this.send(LogLevel.INFO, info)
} }
warn(info) { warn(info) {
this.send(LogLevel.WARN, info) return this.send(LogLevel.WARN, info)
} }
error(info) { error(info) {
this.send(LogLevel.ERROR, info) return this.send(LogLevel.ERROR, info)
} }
send(level, { extra = {}, msg, tag = { key: '', value: '' } }) { send(level, { extra = {}, msg, tag = { key: '', value: '' } } = {}) {
if (!this.isReady()) return false
this.sentry.withScope(scope => { this.sentry.withScope(scope => {
if (tag && tag.key) { if (tag && tag.key) {
scope.setTag(tag.key, tag.value) scope.setTag(tag.key, tag.value)
...@@ -29,14 +38,12 @@ class RemoteLog { ...@@ -29,14 +38,12 @@ class RemoteLog {
scope.setLevel(level) scope.setLevel(level)
// 添加设备信息到 extra // 添加设备信息到 extra
try { const systemInfo = getSystemInfo()
const systemInfo = uni.getSystemInfoSync() if (systemInfo) {
scope.setExtra('device_brand', systemInfo.brand) scope.setExtra('device_brand', systemInfo.brand)
scope.setExtra('device_model', systemInfo.model) scope.setExtra('device_model', systemInfo.model)
scope.setExtra('os_version', systemInfo.system) scope.setExtra('os_version', systemInfo.system)
scope.setExtra('app_version', systemInfo.appVersion) scope.setExtra('app_version', systemInfo.appVersion)
} catch (e) {
// 忽略获取设备信息失败
} }
// 区分 Error 对象和普通消息 // 区分 Error 对象和普通消息
...@@ -46,6 +53,20 @@ class RemoteLog { ...@@ -46,6 +53,20 @@ class RemoteLog {
this.sentry.captureMessage(String(msg)) this.sentry.captureMessage(String(msg))
} }
}) })
return true
}
async close() {
const sentry = this.sentry
this.sentry = null
if (!sentry || typeof sentry.close !== 'function') return false
try {
await sentry.close(2000)
return true
} catch (error) {
console.warn('[RemoteLog] Sentry关闭失败', error)
return false
}
} }
} }
export default RemoteLog export default RemoteLog
...@@ -3,6 +3,7 @@ import LocalLog from './LocalLog' ...@@ -3,6 +3,7 @@ import LocalLog from './LocalLog'
import { LogLevel } from './constants' import { LogLevel } from './constants'
import { storageApi } from '../cache' import { storageApi } from '../cache'
import { getIp } from './util' import { getIp } from './util'
import store from '@/store'
class Logger { class Logger {
remote = null remote = null
local = null local = null
...@@ -19,10 +20,26 @@ class Logger { ...@@ -19,10 +20,26 @@ class Logger {
// 延迟初始化远程日志(Sentry),在用户同意隐私政策后调用 // 延迟初始化远程日志(Sentry),在用户同意隐私政策后调用
// overrides: 可选的用户信息覆盖,用于初始化时 userInfo 尚未完整的情况 // overrides: 可选的用户信息覆盖,用于初始化时 userInfo 尚未完整的情况
async initRemote(overrides = {}) { async initRemote(overrides = {}) {
if (this.remote) return if (!store.getters.hasPrivacyConsent) {
this.local.warn('Sentry初始化已跳过:用户未同意隐私协议')
return false
}
if (this.remote?.isReady?.()) return true
const { default: RemoteLog } = await import('./RemoteLog') const { default: RemoteLog } = await import('./RemoteLog')
const user = { ...this.getUserInfo(), ...overrides } const user = { ...this.getUserInfo(), ...overrides }
this.remote = new RemoteLog(user) this.remote = new RemoteLog(user)
if (!this.remote.isReady()) {
this.remote = null
return false
}
return true
}
async disableRemote() {
const remote = this.remote
this.remote = null
if (!remote) return false
return remote.close()
} }
debug(info) { debug(info) {
this.write(LogLevel.DEBUG, info) this.write(LogLevel.DEBUG, info)
...@@ -37,10 +54,12 @@ class Logger { ...@@ -37,10 +54,12 @@ class Logger {
this.write(LogLevel.ERROR, info) this.write(LogLevel.ERROR, info)
} }
write(level, info) { write(level, info) {
if (this.remote) { if (this.remote && store.getters.hasPrivacyConsent) {
// RemoteLog.send() 期望 { msg, extra, tag } 结构,字符串需包装 // RemoteLog.send() 期望 { msg, extra, tag } 结构,字符串需包装
const remoteInfo = typeof info === 'string' ? { msg: info } : info const remoteInfo = typeof info === 'string' ? { msg: info } : info
this.remote[level](remoteInfo) this.remote[level](remoteInfo)
} else if (this.remote) {
this.disableRemote()
} }
this.local[level](info) this.local[level](info)
} }
......
import { AudioManager, RecordDto, helpler, StrategyFactory, TimeoutService } from './index.js' import { AudioManager, RecordDto, helpler, StrategyFactory, TimeoutService } from './index.js'
import { storageApi } from '@/utils/cache' import { storageApi } from '@/utils/cache'
import utils from '@/utils/utils' import { getOAID } from '@/utils/deviceInfo'
import permision from '@/js_sdk/wa-permission/permission.js' import permision from '@/js_sdk/wa-permission/permission.js'
import store from '@/store' import store from '@/store'
...@@ -110,7 +110,7 @@ class RecordService { ...@@ -110,7 +110,7 @@ class RecordService {
async initDto() { async initDto() {
const userInfo = storageApi.getUserInfo() || {} const userInfo = storageApi.getUserInfo() || {}
const { userId, userName } = userInfo const { userId, userName } = userInfo
const machineCode = await utils.getOAID() const machineCode = await getOAID()
const dto = new RecordDto({ const dto = new RecordDto({
userId, userId,
userName, userName,
......
...@@ -2,7 +2,10 @@ ...@@ -2,7 +2,10 @@
* 提审高版本白屏排查(无 showModal,避免误报网络/WS)。 * 提审高版本白屏排查(无 showModal,避免误报网络/WS)。
* 开关:env.js REVIEW_WHITE_SCREEN_PROBE * 开关:env.js REVIEW_WHITE_SCREEN_PROBE
*/ */
import { getSystemInfo, hasPrivacyConsent } from '@/utils/deviceInfo'
const MAX_LOG = 10 const MAX_LOG = 10
const PRIVACY_NOT_AGREED_TEXT = '未同意隐私协议,未采集设备环境信息'
export function isReviewProbeEnabled() { export function isReviewProbeEnabled() {
try { try {
...@@ -13,22 +16,27 @@ export function isReviewProbeEnabled() { ...@@ -13,22 +16,27 @@ export function isReviewProbeEnabled() {
} }
function getEnvSnapshot() { function getEnvSnapshot() {
try { if (!hasPrivacyConsent()) return PRIVACY_NOT_AGREED_TEXT
const s = uni.getSystemInfoSync()
return [ const s = getSystemInfo()
s.platform, if (!s) return '获取系统信息失败'
s.system,
s.osVersion || '', return [
`model:${s.model || ''}`, s.platform,
`SDK:${s.SDKVersion || ''}`, s.system,
`app:${s.appVersion || ''}`, s.osVersion || '',
`uni:${s.uniRuntimeVersion || ''}` `model:${s.model || ''}`,
] `SDK:${s.SDKVersion || ''}`,
.filter(Boolean) `app:${s.appVersion || ''}`,
.join(' ') `uni:${s.uniRuntimeVersion || ''}`
} catch (e) { ]
return `getSystemInfoSync失败: ${e.message || e}` .filter(Boolean)
} .join(' ')
}
function getStoredOrCurrentEnv(globalData) {
if (!hasPrivacyConsent()) return PRIVACY_NOT_AGREED_TEXT
return globalData?.reviewProbeEnv || uni.getStorageSync('reviewProbeEnv') || getEnvSnapshot()
} }
function isNoiseMessage(text) { function isNoiseMessage(text) {
...@@ -83,7 +91,7 @@ export function recordReviewProbe(tag, err) { ...@@ -83,7 +91,7 @@ export function recordReviewProbe(tag, err) {
} }
const gd = ensureGlobal() const gd = ensureGlobal()
const env = gd?.reviewProbeEnv || getEnvSnapshot() const env = getStoredOrCurrentEnv(gd)
if (gd) { if (gd) {
gd.reviewProbeLogs.push(line) gd.reviewProbeLogs.push(line)
while (gd.reviewProbeLogs.length > MAX_LOG) gd.reviewProbeLogs.shift() while (gd.reviewProbeLogs.length > MAX_LOG) gd.reviewProbeLogs.shift()
...@@ -112,7 +120,7 @@ export function getReviewProbeDisplay() { ...@@ -112,7 +120,7 @@ export function getReviewProbeDisplay() {
const gd = ensureGlobal() const gd = ensureGlobal()
const raw = gd?.reviewProbeLogs?.length > 0 ? gd.reviewProbeLogs : uni.getStorageSync('reviewProbeLogs') || [] const raw = gd?.reviewProbeLogs?.length > 0 ? gd.reviewProbeLogs : uni.getStorageSync('reviewProbeLogs') || []
const logs = sanitizeProbeLogs(raw) const logs = sanitizeProbeLogs(raw)
const env = gd?.reviewProbeEnv || uni.getStorageSync('reviewProbeEnv') || getEnvSnapshot() const env = getStoredOrCurrentEnv(gd)
if (!logs.length) return '' if (!logs.length) return ''
return `【提审排查·长按可复制】\n环境: ${env}\n\n${logs.join('\n---\n')}` return `【提审排查·长按可复制】\n环境: ${env}\n\n${logs.join('\n---\n')}`
} catch (e) { } catch (e) {
......
...@@ -303,19 +303,6 @@ const refreshPageData = notRefreshOrder => { ...@@ -303,19 +303,6 @@ const refreshPageData = notRefreshOrder => {
getApp().globalDataorderListDateListScreenRefresh = true getApp().globalDataorderListDateListScreenRefresh = true
} }
const getOAID = () => {
return new Promise((resolve, reject) => {
plus.device.getOAID({
success: function (e) {
resolve(e.oaid)
},
fail: function (e) {
resolve(uni.getDeviceInfo().deviceId)
}
})
})
}
const nullValues = [undefined,'undefined',null,'null'] const nullValues = [undefined,'undefined',null,'null']
export default { export default {
...@@ -335,6 +322,5 @@ export default { ...@@ -335,6 +322,5 @@ export default {
showNoAccess, showNoAccess,
setCopyData, setCopyData,
refreshPageData, refreshPageData,
getOAID,
nullValues nullValues
} }
...@@ -3,8 +3,8 @@ import { WsTyps } from '../utils/common' ...@@ -3,8 +3,8 @@ import { WsTyps } from '../utils/common'
import CommandFactory from './CommandFactory' import CommandFactory from './CommandFactory'
import config from '@/config.js' import config from '@/config.js'
import { serializeIfObject,deepClone } from '@/utils/utils.js' import { serializeIfObject,deepClone } from '@/utils/utils.js'
import { getSystemInfo, hasPrivacyConsent } from '@/utils/deviceInfo'
// const WsTyps = common.constants.WsTyps
export class Ws { export class Ws {
wsAddress wsAddress
loginAddress loginAddress
...@@ -16,8 +16,16 @@ export class Ws { ...@@ -16,8 +16,16 @@ export class Ws {
this.wsAddress = config.SOCKET_SERVER this.wsAddress = config.SOCKET_SERVER
this.loginAddress =`${config.HTTP_SERVER}/login` this.loginAddress =`${config.HTTP_SERVER}/login`
} }
async connect() { async connect() {
const { code, data, o } = await this.login() if (!hasPrivacyConsent()) {
uni.$logger.local.warn('WS连接已跳过:用户未同意隐私协议')
return false
}
const loginResult = await this.login()
if (!loginResult) return false
const { code, data, o } = loginResult
if (code == 200) { if (code == 200) {
this.deviceId = data.id this.deviceId = data.id
this.token = data.token this.token = data.token
...@@ -28,17 +36,29 @@ export class Ws { ...@@ -28,17 +36,29 @@ export class Ws {
timeout: 5000 timeout: 5000
}) })
this.subscribe() this.subscribe()
return true
} else { } else {
uni.$logger.local.error(`登录失败 -> ${serializeIfObject({ code, data, o })}`) uni.$logger.local.error(`登录失败 -> ${serializeIfObject({ code, data, o })}`)
return false
} }
} }
async connectWhenReady() { async connectWhenReady() {
return this.connect() return this.connect()
} }
async login(retryCount = 3, retryDelay = 2000) { async login(retryCount = 3, retryDelay = 2000) {
if (!hasPrivacyConsent()) {
uni.$logger.local.warn('WS登录已跳过:用户未同意隐私协议')
return null
}
const tryLogin = async (attemptCount) => { const tryLogin = async (attemptCount) => {
try { try {
const sysInfo = uni.getSystemInfoSync() if (!hasPrivacyConsent()) {
uni.$logger.local.warn('WS登录重试已停止:用户未同意隐私协议')
return null
}
const sysInfo = getSystemInfo()
if (!sysInfo?.deviceId) { if (!sysInfo?.deviceId) {
throw new Error('未获取到系统设备信息') throw new Error('未获取到系统设备信息')
} }
...@@ -66,7 +86,9 @@ export class Ws { ...@@ -66,7 +86,9 @@ export class Ws {
for (let attempt = 1; attempt <= retryCount; attempt++) { for (let attempt = 1; attempt <= retryCount; attempt++) {
try { try {
return await tryLogin(attempt) const result = await tryLogin(attempt)
if (!result) return null
return result
} catch (err) { } catch (err) {
if (attempt === retryCount) { if (attempt === retryCount) {
uni.$logger.local.error(`登录失败(已重试${retryCount}次), 请检查网络或联系管理员! err->${serializeIfObject(err)}`) uni.$logger.local.error(`登录失败(已重试${retryCount}次), 请检查网络或联系管理员! err->${serializeIfObject(err)}`)
...@@ -77,6 +99,16 @@ export class Ws { ...@@ -77,6 +99,16 @@ export class Ws {
} }
} }
} }
disconnect() {
if (this.ws) {
if (typeof this.ws.disconnect === 'function') {
this.ws.disconnect()
} else if (typeof this.ws.close === 'function') {
this.ws.close()
}
this.ws = null
}
}
subscribe() { subscribe() {
this.ws.on(WsTyps.Connected, () => { this.ws.on(WsTyps.Connected, () => {
uni.$logger.local.warn('========WebSocket 连接成功========') uni.$logger.local.warn('========WebSocket 连接成功========')
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!