/** * App 端:通知运行时权限(Android 13+)、iOS 本地通知授权、本地推送点击跳转会话 */ // #ifdef APP-PLUS import { getToken } from './api' let pushClickRegistered = false let iosAuthAsked = false function parsePushPayload(msg) { if (!msg) return null let payload = msg.payload if (payload == null && msg.Payload != null) payload = msg.Payload if (typeof payload === 'string') { try { payload = JSON.parse(payload) } catch (e) { return null } } if (payload && typeof payload === 'object') { const cid = payload.contactId != null ? payload.contactId : payload.otherUserId if (cid != null && cid !== '') return String(cid) } return null } function navigateToChatByContactId(contactId) { const url = '/pages/chat/index?otherUserId=' + encodeURIComponent(String(contactId)) uni.navigateTo({ url, fail: () => { uni.reLaunch({ url }) } }) } function ensureAndroidPostNotifications() { try { const Build = plus.android.importClass('android.os.Build') if (Build.VERSION.SDK_INT < 33) return const main = plus.android.runtimeMainActivity() const PackageManager = plus.android.importClass('android.content.pm.PackageManager') if ( main.checkSelfPermission('android.permission.POST_NOTIFICATIONS') === PackageManager.PERMISSION_GRANTED ) { return } plus.android.requestPermissions( ['android.permission.POST_NOTIFICATIONS'], () => {}, (e) => console.warn('[notification] Android POST_NOTIFICATIONS', e && e.message) ) } catch (e) { console.warn('[notification] Android permission', e) } } function ensureIOSNotificationAuth() { if (iosAuthAsked) return iosAuthAsked = true try { const UNUserNotificationCenter = plus.ios.importClass('UNUserNotificationCenter') const center = UNUserNotificationCenter.currentNotificationCenter() const opts = 7 center.requestAuthorizationWithOptionsCompletionHandler(opts, function (granted, err) { if (err) console.warn('[notification] iOS authorization', err) }) } catch (e) { console.warn('[notification] iOS permission', e) iosAuthAsked = false } } function registerPushClick() { if (pushClickRegistered) return if (!plus.push || typeof plus.push.addEventListener !== 'function') return pushClickRegistered = true plus.push.addEventListener('click', (msg) => { if (!getToken()) return const contactId = parsePushPayload(msg) if (!contactId) return navigateToChatByContactId(contactId) }) } /** * 在已登录场景调用:申请权限 + 注册点击(幂等) */ export function setupAppNotifications() { try { if (typeof plus === 'undefined' || !plus.push) return if (plus.os.name === 'Android') ensureAndroidPostNotifications() else if (plus.os.name === 'iOS') ensureIOSNotificationAuth() registerPushClick() } catch (e) { console.warn('[notification] setup', e) } } // #endif // #ifndef APP-PLUS export function setupAppNotifications() {} // #endif