wallace-screen-app/utils/device.ts

41 lines
1.1 KiB
TypeScript
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.

declare const plus: any
const DEVICE_SN_STORAGE_KEY = 'wallace:screen:sn'
const DEVICE_SN_PREFIX = 'WLS-'
const normalizeNativeId = (value: unknown) => String(value || '')
.toUpperCase()
.replace(/[^A-Z0-9]/g, '')
.slice(0, 32)
const createFallbackId = () => {
const timestamp = Date.now().toString(36).toUpperCase()
const random = Math.random().toString(36).slice(2, 12).toUpperCase()
return `${timestamp}${random}`
}
/**
* APP 端优先使用 DCloud 提供的设备唯一标识 `plus.device.uuid`。
* H5、模拟器或标识不可用时,生成应用级标识并持久化,保证同一次安装期间稳定。
*/
const getNativeDeviceId = () => {
// #ifdef APP-PLUS
try {
return normalizeNativeId(plus?.device?.uuid)
} catch {
return ''
}
// #endif
return ''
}
export const getOrCreateDeviceSn = () => {
const saved = String(uni.getStorageSync(DEVICE_SN_STORAGE_KEY) || '')
if (saved) return saved
const sourceId = getNativeDeviceId() || createFallbackId()
const sn = `${DEVICE_SN_PREFIX}${sourceId}`
uni.setStorageSync(DEVICE_SN_STORAGE_KEY, sn)
return sn
}