Compare commits

..

10 Commits

Author SHA1 Message Date
Elemt d5f7d1051d Dev:
1、解决微信登录和客服可能的ANR问题
2、解决抠图时可能的崩溃问题
2026-11-11 09:16:22 +08:00
Elemt 00aebd8b86 Dev:
1、解决微信登录和客服可能的ANR问题
2、解决抠图时可能的崩溃问题
2026-11-10 10:11:06 +08:00
Elemt 158b71fa5e Dev:
1、修复小程序问题
2026-11-09 18:32:20 +08:00
Elemt 738fb2fe33 Dev:
1、修改banner指示器,多张图片才展示
2、添加batiao-sdk
2026-11-03 15:27:20 +08:00
Elemt bff2d327b2 Dev:
1、修改banner图片展示
2026-11-03 13:39:22 +08:00
Elemt b52f631643 Dev:
1、添加banner功能
2026-11-02 12:01:12 +08:00
Elemt 0268068f86 Dev:
1、添加下载逻辑优化、小程序启动逻辑及解码释放
2、导航高度处理
3、一键登陆处理
2026-11-02 11:34:48 +08:00
shenzuqiang 0fb4127d7a Dev:
sync
2026-05-21 11:29:58 +08:00
shenzuqiang b06db40dc6 Dev:
1、解决vivo市场反馈,系统17下崩溃问题(初步判断加密引起,但需要升级版本重新加密上传)
2、添加客服配置加载显示
2026-05-21 10:00:08 +08:00
shenzuqiang 0b84bdb904 Dev:
1、优化部分逻辑
2、忽略网络安全策略
2026-04-28 11:33:11 +08:00
60 changed files with 2334 additions and 1239 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="21" />
<bytecodeTargetLevel target="25" />
</component>
</project>

View File

@ -3,6 +3,39 @@
<component name="deploymentTargetSelector">
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2026-11-09T09:16:20.249736600Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=Y5DELZR46DZTCI9D" />
</handle>
</Target>
</DropdownSelection>
<DialogSelection />
</SelectionState>
<SelectionState runConfigName="main">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2026-03-24T05:48:19.296324800Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=JRBI89BIE6AI5TG6" />
</handle>
</Target>
</DropdownSelection>
<DialogSelection />
</SelectionState>
<SelectionState runConfigName="unitTest">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2026-03-24T05:48:19.296324800Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=JRBI89BIE6AI5TG6" />
</handle>
</Target>
</DropdownSelection>
<DialogSelection />
</SelectionState>
<SelectionState runConfigName="androidTest">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2026-03-24T05:48:19.296324800Z">
<Target type="DEFAULT_BOOT">

View File

@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="jbr-25" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">

View File

@ -2,13 +2,26 @@ import org.gradle.kotlin.dsl.api
plugins {
id("com.android.application")
id("com.batiao.batiaosdkbuilder") version "1.0.398"
alias(libs.plugins.compose.compiler)
kotlin("plugin.serialization") version "2.3.0"
}
batiaoSdkConfig {
// 业务 API 显式挂载 SignInterceptor;全局注入会修改图片/WGT 等下载 URL。
// BatiaoUnimp 自带 SignInterceptor,不依赖全局注入。
enableHttpAuth = false
unimp = true
// 与 weiquan-android 一致,只在用户同意隐私协议后初始化。
applicationHookMethod = "initializeBatiaoAfterConsent"
sdkVersion = "1.0.398"
prop("signKey", "xn08hYoizXhZ1zHP8DVqfCm2yHxPmhil")
prop("decodeKey", "e4rOtnF8tJjtHO7ecZeJHN1rapED5ImB")
}
android {
namespace = "com.img.rabbit"
compileSdk = 36
compileSdk = 37
buildFeatures {
compose = true
@ -31,16 +44,15 @@ android {
}
composeOptions {
// 注意:Kotlin 1.8.x 以后建议检查与 Compose 编译器的版本兼容性
kotlinCompilerExtensionVersion = "1.4.8"
}
defaultConfig {
applicationId = "com.img.rabbit"
minSdk = 24
targetSdk = 36
versionCode = 1
versionName = "1.0.0"
targetSdk = 37
versionCode = 3
versionName = "1.0.3"
multiDexEnabled = true
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
@ -50,7 +62,8 @@ android {
}
ndk {
abiFilters.addAll(listOf("arm64-v8a", "x86_64", "x86", "armeabi-v7a"))
// Batiao 1.0.398 仅提供 arm64-v8a 的原生库。
abiFilters.add("arm64-v8a")
}
// 仅保留基础占位符,渠道相关的移至下方 flavor 处理
@ -163,6 +176,8 @@ tasks.withType<JavaCompile>().configureEach {
}
dependencies {
// 手动启动延后到隐私授权之后的初始化器。
implementation("androidx.startup:startup-runtime:1.2.0")
api(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar","*.aar"))))
// 基础依赖
implementation(libs.androidx.core.ktx)

View File

@ -1,9 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- 不允许依赖库重新引入读取安装列表/运行任务的权限。 -->
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:node="remove" />
<uses-permission android:name="android.permission.GET_TASKS" tools:node="remove" />
<uses-permission android:name="android.permission.REAL_GET_TASKS" tools:node="remove" />
<!-- 在Android14及以上版本读取SelectedPhotoAccess需要添加READ_MEDIA_VISUAL_USER_SELECTED权限 -->
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
<!-- 写入外部存储权限,用于保存拍照后的图片或者下载文件,主要兼容Android 13及以下版本(Android13以上高版本不需要,但低版本必须) -->
<!-- 写入外部存储权限,用于截长图保存,主要兼容Android 13及以下版本(Android13以上高版本不需要,但低版本必须) -->
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="32"
tools:ignore="ScopedStorage" />
@ -37,7 +41,7 @@
<package android:name="com.eg.android.AlipayGphone" /> <!-- 支付宝 -->
<package android:name="hk.alipay.wallet" /> <!-- AlipayHK -->
<package android:name="com.tencent.mm" />
<intent>
<intent tools:node="remove">
<action android:name="com.getui.sdk.action" />
</intent>
</queries>
@ -62,6 +66,20 @@
tools:replace="android:allowBackup,android:supportsRtl"
tools:targetApi="33">
<!-- SDK 自动初始化发生在 Application.onCreate 之前,改为同意后手动初始化。 -->
<provider android:name="com.google.mlkit.common.internal.MlKitInitProvider"
tools:node="remove" />
<provider android:name="com.getui.gtc.base.GtcProvider" tools:node="remove" />
<provider android:name=".provider.ConsentGtcProvider"
android:authorities="${applicationId}.getui.gtc.provider"
android:exported="false" />
<provider android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
tools:node="merge">
<meta-data android:name="okhttp3.internal.platform.PlatformInitializer"
tools:node="remove" />
</provider>
<activity
android:name="com.img.rabbit.MainActivity"
android:theme="@style/SplashTheme"
@ -103,6 +121,16 @@
<!--如果是小程序模式,还需要添加这行配置-->
<activity
android:name=".wxapi.AuthorizedWXEntryActivity"
android:exported="false"
android:excludeFromRecents="true"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<activity
android:name=".wxapi.AuthorizedWXPayEntryActivity"
android:exported="false"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<activity
android:name="io.dcloud.feature.payment.weixin.WXPayProcessMeadiatorActivity"
android:excludeFromRecents="true"

View File

@ -1,6 +1,5 @@
package com.img.rabbit
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
@ -8,56 +7,70 @@ import android.util.Log
import com.bumptech.glide.Glide
import com.img.rabbit.utils.NetworkMonitor
import com.g.gysdk.GYManager
import com.getui.gtc.base.util.CommonUtil.isMainProcess
import androidx.startup.AppInitializer
import com.google.mlkit.common.sdkinternal.MlKitContext
import com.github.gzuliyujiang.oaid.DeviceID
import com.github.gzuliyujiang.oaid.IGetter
import com.img.rabbit.config.Constants
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.provider.storage.PrivacyConsentStore
import com.img.rabbit.provider.ConsentGtcProvider
import com.img.rabbit.provider.utils.HeadParamUtils
import com.img.rabbit.uni.UniMPImmersiveWindow
import com.img.rabbit.utils.ChannelUtils
import com.tencent.mmkv.MMKV
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.PlatformConfig
import io.dcloud.common.util.RuningAcitvityUtil
import okhttp3.internal.platform.PlatformInitializer
import io.dcloud.feature.sdk.DCSDKInitConfig
import io.dcloud.feature.sdk.DCUniMPSDK
import io.dcloud.feature.sdk.MenuActionSheetItem
import java.lang.Exception
import java.io.File
class BaseApplication : Application() {
private val TAG = "BaseApplication"
private var batiaoInitialized = false
private var thirdPartyInitialized = false
private var uniAppInitialized = false
private var uniAppOaid: String? = null
override fun onCreate() {
super.onCreate()
// 只有是主进程时,才执行重量级初始化
if (getProcessName(this) == packageName) {
Log.i(TAG, "进行必要的SDK初始化...")
// 初始化MMKV
initMMKV()
// 非小程序进程(使用unimp 关键字 可以根据宿主的具体情况进行调整)
if (PreferenceUtil.getAgreement() && !RuningAcitvityUtil.getAppName(baseContext).contains("unimp")) {
Log.i(TAG, "已同意隐私政策,BaseApplication开始初始化SDK服务...")
initThirdParty()
initUM()
}
}
initThirdParty()
}
override fun attachBaseContext(base: Context?) {
//MultiDex.install(base)
super.attachBaseContext(base)
PrivacyConsentStore.initialize(this)
HeadParamUtils.applicationContext = this
}
/**
* 隐私同意即可初始化
*/
@Synchronized
fun initThirdParty(){
//需要在隐私框架下才能处理的逻辑
if(PreferenceUtil.getAgreement()){
if (!PrivacyConsentStore.isAccepted() || thirdPartyInitialized) return
// 独立进程也必须先检查授权;只注册其所需的窗口适配。
UniMPImmersiveWindow.register(this)
if (currentProcessName() == packageName) {
initMMKV()
AppInitializer.getInstance(this).initializeComponent(PlatformInitializer::class.java)
MlKitContext.initializeIfNeeded(this)
// 采集开关必须在任何 SDK(包括构建插件注入代码)启动前设置。
UMConfigure.enableAplCollection(false)
check(GYManager.getInstance().setSecurity(this, false)) {
"无法关闭个验扩展采集"
}
ConsentGtcProvider.initializeAfterConsent(this)
if (!batiaoInitialized) {
initializeBatiaoAfterConsent()
batiaoInitialized = true
}
Log.i(TAG, "用户已同意隐私政策,开始初始化第三方服务")
// 初始化网络状态监控
NetworkMonitor.initialize(this)
@ -65,9 +78,15 @@ class BaseApplication : Application() {
Glide.get(this)
// 初始化个推SDK
initGeTuiOneKeyLogin()
initUM()
// 初始化OAID和uni-app SDK
initOAIDAndUniAPPSdk()
}
thirdPartyInitialized = true
}
// Batiao 构建插件只向此方法注入初始化,调用前必须检查隐私协议。
private fun initializeBatiaoAfterConsent() {
}
/**
@ -114,7 +133,11 @@ class BaseApplication : Application() {
//初始化uni-app SDK
private fun initUniAPPSdk() {
if (isMainProcess(this)) {
if (PreferenceUtil.getAgreement() && currentProcessName() == packageName) {
val oaid = PreferenceUtil.getOAID()
if (uniAppInitialized && uniAppOaid == oaid) return
uniAppInitialized = true
uniAppOaid = oaid
val item = MenuActionSheetItem("关于", "gy")
val item1 = MenuActionSheetItem("获取当前页面url", "hqdqym")
val item2 = MenuActionSheetItem("跳转到宿主原生测试页面", "gotoTestPage")
@ -123,31 +146,31 @@ class BaseApplication : Application() {
sheetItems.add(item1)
sheetItems.add(item2)
val config: DCSDKInitConfig? = DCSDKInitConfig.Builder()
.setCapsule(true)
.setCapsule(false)
.setMenuDefFontSize("16px")
.setMenuDefFontColor("#ff00ff")
.setMenuDefFontWeight("normal")
.setMenuActionSheetItems(sheetItems)
.setCustomOAID(PreferenceUtil.getOAID())
.setEnableBackground(false)
.setUniMPFromRecents(true)
.build()
DCUniMPSDK.getInstance().initialize(this, config)
DCUniMPSDK.getInstance().initialize(this, config) { success ->
uniAppInitialized = success
Log.d("UniMP", "onInitFinished: $success")
}
}
}
private fun getProcessName(context: Context): String? {
private fun currentProcessName(): String? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
return getProcessName()
}
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val runningApps = am.runningAppProcesses ?: return null
for (proInfo in runningApps) {
if (proInfo.pid == android.os.Process.myPid()) {
return proInfo.processName
}
}
return null
// 旧系统只读取当前进程名,不枚举其他应用的进程。
return runCatching {
File("/proc/self/cmdline").readText().substringBefore('\u0000')
}.getOrNull()
}

View File

@ -1,7 +1,6 @@
package com.img.rabbit
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
@ -14,16 +13,22 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
@ -39,6 +44,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
@ -48,6 +54,7 @@ import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@ -58,12 +65,10 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.img.rabbit.bean.response.UniVersionEntity
import com.img.rabbit.components.GlobalToast
import com.img.rabbit.config.Constants
import com.img.rabbit.config.Constants.agreementUrl
import com.img.rabbit.config.Constants.privacyUrl
import com.img.rabbit.pages.LoadingCallback
import com.img.rabbit.pages.LoginScreen
import com.img.rabbit.pages.LoginScreenType
import com.img.rabbit.pages.MainScreen
import com.img.rabbit.pages.dialog.TipsDialog
import com.img.rabbit.pages.dialog.TipsUniMpDialog
@ -72,7 +77,6 @@ import com.img.rabbit.pages.dialog.UpdateDialog
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.utils.AppEventBus
import com.img.rabbit.utils.AppUpdate
import com.img.rabbit.utils.ChannelUtils
import com.img.rabbit.utils.FileUtils
import com.img.rabbit.utils.GlobalEvent
import com.img.rabbit.utils.GlobalEventBus
@ -85,12 +89,9 @@ import com.img.rabbit.viewmodel.GeneralViewModel
import com.img.rabbit.viewmodel.LoginViewModel
import com.img.rabbit.viewmodel.ReportViewModel
import com.img.rabbit.viewmodel.SplashViewModel
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.system.exitProcess
class MainActivity : ComponentActivity(), LoadingCallback {
private lateinit var generalViewModel: GeneralViewModel
@ -105,8 +106,26 @@ class MainActivity : ComponentActivity(), LoadingCallback {
enableEdgeToEdge()
setContent {
// 授权前仅渲染原生协议页,不创建会访问 MMKV/网络/微信的业务 ViewModel。
var consentAccepted by remember { mutableStateOf(PreferenceUtil.getAgreement()) }
if (!consentAccepted) {
splashScreen.setKeepOnScreenCondition { false }
AppTheme {
SplashScreenContent {
PrivacyPolicyScreen { accepted ->
if (accepted) {
PreferenceUtil.saveAgreement(true)
(application as BaseApplication).initThirdParty()
consentAccepted = true
} else {
finish()
}
}
}
}
return@setContent
}
val coroutineScope = rememberCoroutineScope()
var showSplash by remember { mutableStateOf(false) }
val context = LocalContext.current
val loginViewModel: LoginViewModel = viewModel()
@ -125,9 +144,11 @@ class MainActivity : ComponentActivity(), LoadingCallback {
// 下载小程序资源(在跳转指定页面时,未下载资源需要提示)
var showUniDownloadDialog by remember { mutableStateOf(false) }
var downloadUniEntity by remember { mutableStateOf<UniVersionEntity?>(null) }
var downloadUniPagePath by remember { mutableStateOf<String?>(null) }
// 小程序资源更新提示
var showUniUpdateDialog by remember { mutableStateOf(false) }
var updateUniEntity by remember { mutableStateOf<UniVersionEntity?>(null) }
var updateUniPagePath by remember { mutableStateOf<String?>(null) }
//以下为流事件收集订阅
LaunchedEffect(Unit) {
GlobalEventBus.events.collect { event ->
@ -142,11 +163,13 @@ class MainActivity : ComponentActivity(), LoadingCallback {
// 小程序资源下载提示
is GlobalEvent.ShowUniDownloadNotify -> {
downloadUniEntity = event.entity
downloadUniPagePath = event.pagePath
showUniDownloadDialog = true
}
// 小程序资源更新提示
is GlobalEvent.ShowUniUpdateNotify -> {
updateUniEntity = event.entity
updateUniPagePath = event.pagePath
showUniUpdateDialog = true
}
// 登录提示
@ -210,6 +233,8 @@ class MainActivity : ComponentActivity(), LoadingCallback {
LaunchedEffect(showUniDownloadDialog) {
if(showUniDownloadDialog) {
downloadUniEntity?.let{
val downloadVersion = it
val downloadPagePath = downloadUniPagePath
UniAppUtils.downloadReleaseWgt(
coroutineScope,
it,
@ -251,16 +276,7 @@ class MainActivity : ComponentActivity(), LoadingCallback {
onRelease = { isSuccess->
if(isSuccess){
//资源下载完成后,启动小程序到指定位置
val uniMpEntity = downloadUniEntity
if (uniMpEntity != null && UniAppUtils.isRelease(uniMpEntity.unimp_id)) {
UniAppUtils.startUniMpPage(
context = context,
uniMpId = uniMpEntity.unimp_id,
uniMpType = uniMpEntity.unimp_type,
pagePath = UniAppUtils.currentUniMpJumpPatch ?: "",
reportViewModel = reportViewModel
)
}
UniAppUtils.distributeUniMp(context, downloadVersion, reportViewModel, downloadPagePath) {}
}
},
reportViewModel = reportViewModel
@ -272,50 +288,10 @@ class MainActivity : ComponentActivity(), LoadingCallback {
AppTheme {
SplashScreenContent{
//未同意提示政策弹窗
if (!generalViewModel.agreementStatus.value){
//同意继续
PrivacyPolicyScreen(
viewModel = loginViewModel,
) { isAllowPrivacyPolicy ->
if (isAllowPrivacyPolicy) {
generalViewModel.setIsAgreement(true)
loginViewModel.setIsPolicyAgreement(true)
(applicationContext as BaseApplication).initThirdParty()
initUM()
showSplash = true
} else {
// 不同意隐私协议政策,直接退出应用
(context as MainActivity).finish()
// 强制退出应用进程
exitProcess(0)
}
}
}else{
showSplash = true
}
if(showSplash){
//val token = PreferenceUtil.getAccessToken()
// 未登录,显示登录页
//if (token.isNullOrEmpty() && loginViewModel.userConfigResult.value == null) {
if(isLogout){// 退出登录后,显示登录页
// 同意隐私协议政策,检验是否有一键登录权限
loginViewModel.oneKeyLoginForGeTuiSdk(context as Activity) { isAllowShowOneKeyScreen ->
if (isAllowShowOneKeyScreen) {
loginViewModel.loginScreenType.value = LoginScreenType.LOGIN_ONE_KEY
} else {
// 检验是否有一键登录权限失败,显示验证码登录
loginViewModel.loginScreenType.value = LoginScreenType.LOGIN_CAPTCHA
}
}
// 显示登录页
LoginScreen(generalViewModel = generalViewModel, loginViewModel = loginViewModel, isVisibilityBreak = false)
} else {
//已登录,显示主页面
MainScreen(generalViewModel = generalViewModel, loginViewModel = loginViewModel)
}
if(isLogout){
LoginScreen(generalViewModel = generalViewModel, loginViewModel = loginViewModel, isVisibilityBreak = false)
} else {
MainScreen(generalViewModel = generalViewModel, loginViewModel = loginViewModel)
}
if(showLoginDialog){
@ -352,8 +328,8 @@ class MainActivity : ComponentActivity(), LoadingCallback {
}
//UniApp更新提示
val isDownloadingWGT = mutableStateOf(false)
val progressWGTState = mutableFloatStateOf(0f)
val isDownloadingWGT = remember(showUniUpdateDialog) { mutableStateOf(false) }
val progressWGTState = remember(showUniUpdateDialog) { mutableFloatStateOf(0f) }
if(showUniUpdateDialog){
updateUniEntity?.let {
TipsUniMpDialog(
@ -366,11 +342,17 @@ class MainActivity : ComponentActivity(), LoadingCallback {
data = it,
isStartDown = isDownloadingWGT,
downProgress = progressWGTState,
reportViewModel = reportViewModel,
pagePath = updateUniPagePath,
onStatusChange = { isUpdateFinish, isCancel, data ->
if(!isUpdateFinish && !isCancel && data != null){
isDownloadingWGT.value = true
}else{
showUniUpdateDialog = false
if (isCancel) {
UniAppUtils.reportUpdateChoice(it, false, reportViewModel)
UniAppUtils.distributeUniMp(context, it, reportViewModel, updateUniPagePath) {}
}
}
}
)
@ -445,15 +427,6 @@ class MainActivity : ComponentActivity(), LoadingCallback {
}
}
/**
* 初始化友盟(同意协议的时候,进行一次初始化)
*/
private fun initUM() {
UMConfigure.preInit(applicationContext, Constants.UmengAppkey, ChannelUtils.getChannel(applicationContext))
UMConfigure.init(this, Constants.UmengAppkey, ChannelUtils.getChannel(applicationContext), UMConfigure.DEVICE_TYPE_PHONE, "")
MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
}
override fun showLoading() {
lifecycleScope.launch {
generalViewModel.setLoading(true)
@ -526,205 +499,200 @@ fun SplashScreenContent(
@Composable
private fun PrivacyPolicyScreen(viewModel: LoginViewModel, onAgreementChange: (Boolean) -> Unit) {
private fun PrivacyPolicyScreen(onAgreementChange: (Boolean) -> Unit) {
val context = LocalContext.current
Box(
modifier = Modifier.fillMaxSize()
){
BoxWithConstraints(
modifier = Modifier
.fillMaxSize()
.background(Color(0xCC000000))
.safeDrawingPadding()
.padding(horizontal = 24.dp, vertical = 24.dp),
contentAlignment = Alignment.Center
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color(0xCC000000))
.widthIn(max = 400.dp)
.fillMaxWidth()
.heightIn(max = maxHeight)
.clip(RoundedCornerShape(26.dp))
.background(Color.White)
){
Box(
Image(
painter = painterResource(id = R.mipmap.ic_privacy_policy_top_mask),
contentDescription = null,
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 38.dp, vertical = 213.dp)
.align(Alignment.Center)
.background(Color.White, shape = RoundedCornerShape(26.dp))
){
Image(
painter = painterResource(id = R.mipmap.ic_privacy_policy_top_mask),
contentDescription = null,
.fillMaxWidth()
.height(64.dp),
contentScale = ContentScale.FillBounds
)
Column(
modifier = Modifier
.fillMaxWidth()
// 内容与按钮使用同一条纵向布局,空间不足时整体滚动。
.verticalScroll(rememberScrollState())
.padding(start = 24.dp, end = 24.dp, top = 32.dp, bottom = 12.dp)
) {
Text(
text = "用户协议与隐私政策",
modifier = Modifier
.fillMaxSize(),
alignment = Alignment.TopCenter
.wrapContentSize()
.align(Alignment.CenterHorizontally),
fontWeight = FontWeight.Normal,
fontSize = 18.sp,
lineHeight = 26.sp,
textAlign = TextAlign.Center,
color = Color(0xFF1A1A1A)
)
Box(
modifier = Modifier
.fillMaxWidth()
.height(24.dp)
)
Column(
modifier = Modifier
.padding(top = 36.dp)
.align(Alignment.TopCenter)
) {
Text(
text = "用户协议与隐私政策",
modifier = Modifier
.wrapContentSize()
.align(Alignment.CenterHorizontally),
fontWeight = FontWeight.Normal,
fontSize = 18.sp,
color = Color(0xFF1A1A1A)
)
Box(
modifier = Modifier
.fillMaxWidth()
.height(24.dp)
)
val agreement = "请您务必审慎阅读、充分理解《服务协议》与《隐私政策》各条款,包括但不限于:为了更好的向您提供服务,我们需要访问您的相册、相机等。您可以阅读《隐私政策》了解详细信息。如果您同意,请点击下面同意按钮开始接受我们的服务。"
val annotatedText = buildAnnotatedString {
append(agreement)
val startIndexForService = agreement.indexOf("《服务协议》")
val startIndexPrivacy1 = agreement.indexOf("《隐私政策》")
val startIndexPrivacy2 = agreement.lastIndexOf("《隐私政策》")
val agreement = "请您务必审慎阅读、充分理解《服务协议》与《隐私政策》各条款,包括但不限于:为了更好的向您提供服务,我们需要访问您的相册、相机等。您可以阅读《隐私政策》了解详细信息。如果您同意,请点击下面同意按钮开始接受我们的服务。"
val annotatedText = buildAnnotatedString {
append(agreement)
val startIndexForService = agreement.indexOf("《服务协议》")
val startIndexPrivacy1 = agreement.indexOf("《隐私政策》")
val startIndexPrivacy2 = agreement.lastIndexOf("《隐私政策》")
val serviceLength = "《服务协议》".length
val privacyLength = "《隐私政策》".length
val serviceLength = "《服务协议》".length
val privacyLength = "《服务协议》".length
// 高亮显示 "《服务协议》"
addStyle(
style = SpanStyle(
color = Color(0xFF0066CC),
textDecoration = TextDecoration.None
),
start = startIndexForService, // "《服务协议》" 开始下标13
end = startIndexForService + serviceLength // "《服务协议》" 结束下标19
)
addStringAnnotation(
tag = "AGREEMENT",
annotation = "service_agreement",
start = startIndexForService,
end = startIndexForService + serviceLength
)
// 高亮显示 "《隐私政策》"
addStyle(
style = SpanStyle(
color = Color(0xFF0066CC),
textDecoration = TextDecoration.None
),
start = startIndexPrivacy1, // "《隐私政策》" 开始下标20
end = startIndexPrivacy1 + privacyLength // "《隐私政策》" 结束下标26
)
addStringAnnotation(
tag = "PRIVACY",
annotation = "privacy_policy",
start = startIndexPrivacy1,
end = startIndexPrivacy1 + privacyLength
)
// 高亮显示 "《隐私政策》"
addStyle(
style = SpanStyle(
color = Color(0xFF0066CC),
textDecoration = TextDecoration.None
),
start = startIndexPrivacy2, // "《隐私政策》" 开始下标
end = startIndexPrivacy2 + privacyLength // "《隐私政策》" 结束下标
)
addStringAnnotation(
tag = "PRIVACY",
annotation = "privacy_policy",
start = startIndexPrivacy2,
end = startIndexPrivacy2 + privacyLength
)
}
@Suppress("DEPRECATION")
ClickableText(
text = annotatedText,
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.align(Alignment.CenterHorizontally)
.padding(horizontal = 12.dp),
style = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
color = Color(0xFF1A1A1A)
// 高亮显示 "《服务协议》"
addStyle(
style = SpanStyle(
color = Color(0xFF0066CC),
textDecoration = TextDecoration.None
),
onClick = { offset ->
val agreementAnnotation = annotatedText.getStringAnnotations("AGREEMENT", offset, offset).firstOrNull()
val privacyAnnotation = annotatedText.getStringAnnotations("PRIVACY", offset, offset).firstOrNull()
when {
agreementAnnotation != null -> {
openAgreement(context, "服务协议", agreementUrl, false)
}
privacyAnnotation != null -> {
openAgreement(context, "隐私政策", privacyUrl, false)
}
}
}
start = startIndexForService, // "《服务协议》" 开始下标13
end = startIndexForService + serviceLength // "《服务协议》" 结束下标19
)
addStringAnnotation(
tag = "AGREEMENT",
annotation = "service_agreement",
start = startIndexForService,
end = startIndexForService + serviceLength
)
// 高亮显示 "《隐私政策》"
addStyle(
style = SpanStyle(
color = Color(0xFF0066CC),
textDecoration = TextDecoration.None
),
start = startIndexPrivacy1, // "《隐私政策》" 开始下标20
end = startIndexPrivacy1 + privacyLength // "《隐私政策》" 结束下标26
)
addStringAnnotation(
tag = "PRIVACY",
annotation = "privacy_policy",
start = startIndexPrivacy1,
end = startIndexPrivacy1 + privacyLength
)
// 高亮显示 "《隐私政策》"
addStyle(
style = SpanStyle(
color = Color(0xFF0066CC),
textDecoration = TextDecoration.None
),
start = startIndexPrivacy2, // "《隐私政策》" 开始下标
end = startIndexPrivacy2 + privacyLength // "《隐私政策》" 结束下标
)
addStringAnnotation(
tag = "PRIVACY",
annotation = "privacy_policy",
start = startIndexPrivacy2,
end = startIndexPrivacy2 + privacyLength
)
}
Column(
@Suppress("DEPRECATION")
ClickableText(
text = annotatedText,
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.align(Alignment.BottomCenter)
.align(Alignment.CenterHorizontally),
style = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
lineHeight = 20.sp,
color = Color(0xFF1A1A1A)
),
onClick = { offset ->
val agreementAnnotation = annotatedText.getStringAnnotations("AGREEMENT", offset, offset).firstOrNull()
val privacyAnnotation = annotatedText.getStringAnnotations("PRIVACY", offset, offset).firstOrNull()
when {
agreementAnnotation != null -> {
openAgreement(context, "服务协议", agreementUrl, false)
}
privacyAnnotation != null -> {
openAgreement(context, "隐私政策", privacyUrl, false)
}
}
}
)
Box(Modifier.height(24.dp))
//同意按钮,用户协议与隐私政策
Box(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.background(
Color(0xFF252525),
shape = RoundedCornerShape(359.dp),
)
.clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
onAgreementChange(true)
}
) {
//同意按钮,用户协议与隐私政策
Box(
Text(
"同意",
color = Color(0xFFC2FF43),
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth()
.wrapContentHeight()
.padding(start = 33.dp, end = 33.dp)
.background(
Color(0xFF252525),
shape = RoundedCornerShape(359.dp),
)
.clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
onAgreementChange(true)
}
) {
Text(
"同意",
color = Color(0xFFC2FF43),
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.wrapContentWidth()
.wrapContentHeight()
.padding(vertical = 12.dp)
.align(Alignment.Center)
.padding(vertical = 12.dp)
.align(Alignment.Center)
)
}
//不同按钮,意用户协议与隐私政策
Box(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.background(
Color(0x00000000),
shape = RoundedCornerShape(359.dp),
)
}
//不同按钮,意用户协议与隐私政策
Box(
.clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
onAgreementChange(false)
}
) {
Text(
"不同意",
color = Color(0xFFAAAAAA),
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth()
.wrapContentHeight()
.padding(start = 33.dp, end = 33.dp)
.background(
Color(0x00000000),
shape = RoundedCornerShape(359.dp),
)
.clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
onAgreementChange(false)
viewModel.setIsPolicyAgreement(false)
}
) {
Text(
"不同意",
color = Color(0xFFAAAAAA),
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.wrapContentWidth()
.wrapContentHeight()
.padding(vertical = 12.dp)
.align(Alignment.Center)
)
}
.padding(vertical = 12.dp)
.align(Alignment.Center)
)
}
}
}
@ -733,6 +701,15 @@ private fun PrivacyPolicyScreen(viewModel: LoginViewModel, onAgreementChange: (B
@Preview(name = "隐私弹窗-小屏", widthDp = 360, heightDp = 640, showBackground = true)
@Preview(name = "隐私弹窗-大字体", widthDp = 320, heightDp = 480, fontScale = 1.5f, showBackground = true)
@Composable
private fun PrivacyPolicyPreview() {
MaterialTheme {
PrivacyPolicyScreen(onAgreementChange = {})
}
}
@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {

View File

@ -1,14 +1,17 @@
package com.img.rabbit.bean.request
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
@Serializable
@OptIn(ExperimentalSerializationApi::class)
data class ReportRequest(
private val source: String = "android",
private val type: String,//事件类型:click error
private val key: String,
private val value: String,
private val extra: String? = null
private val extra: String? = null,
@EncodeDefault private val source: String = "android"
)
@ -18,6 +21,14 @@ object ReportType {
}
object ReportKey {
const val EVENT_CLIENT_HOME_BANNER_CLICK = "client.home.banner.click"
const val EVENT_CLIENT_OPEN_WX_UNIMP = "event_client_open_wx_unimp"
const val EVENT_CLIENT_OPEN_ALIPAY_UNIMP = "event_client_open_alipay_unimp"
const val EVENT_CLIENT_UNI_FAIL = "client.uni.fail"
const val EVENT_CLIENT_DOWNLOAD_UNIMP_ERROR = "client.download.unimp.error"
const val EVENT_CLIENT_DOWNLOAD_UNIMP_SUCCESS = "client.download.unimp.success"
const val EVENT_CLIENT_CANCEL_DOWNLOAD_UNIMP = "client.cancel.download.unimp"
const val EVENT_CLIENT_CONFIRM_DOWNLOAD_UNIMP = "client.confirm.download.unimp"
const val EVENT_CLIENT_UNI_RELEASE_WGT: String = "client.uni.release.wgt" //释放资源
const val EVENT_CLIENT_UNI_SPEC_PAGE_LOAD: String = "client.uni.page.load" //页面加载
}

View File

@ -1,10 +1,14 @@
package com.img.rabbit.bean.response
import com.google.gson.annotations.SerializedName
import com.google.gson.annotations.JsonAdapter
import kotlinx.serialization.Serializable
@Serializable
class ConfigEntity {
@SerializedName("client.banner.home") //首页轮播图
@JsonAdapter(HomeBannerListAdapter::class)
var homeBanners: List<HomeBannerEntity?>? = emptyList()
@SerializedName("client.version.upgrade") //版本更新
var versionEntity: VersionEntity? = null
@SerializedName("client.uni.version.upgrade") //小程序模拟器
@ -13,6 +17,8 @@ class ConfigEntity {
var homeIconEntity: List<UniIconEntity>? = emptyList()
@SerializedName("client.wgt.password") //WGT解压密码
var wgtPassword: String? = null
@SerializedName("client.uni.pwd") //与 WGT 密码后缀拼接的小程序密码
var uniPassword: String? = null
@SerializedName("client.uni.open") //是否开启小程序模拟器
var isUniMpOpen: Boolean? = null

View File

@ -0,0 +1,23 @@
package com.img.rabbit.bean.response
import com.google.gson.annotations.SerializedName
import kotlinx.serialization.Serializable
/** client.banner.home,与 flaunt-android 的 HomeBannerBean 字段一致。 */
@Serializable
data class HomeBannerEntity(
@SerializedName(value = "img", alternate = ["icon"])
val img: String? = null,
val url: String? = null,
val type: String? = null,
val enable: Boolean? = null,
val text: String? = null,
) {
companion object {
fun visibleItems(items: List<HomeBannerEntity?>?): List<HomeBannerEntity> =
items.orEmpty().filterNotNull().filter {
it.enable == true && !it.img.isNullOrBlank() &&
it.type in setOf("wx", "alipay", "app", "web")
}
}
}

View File

@ -0,0 +1,23 @@
package com.img.rabbit.bean.response
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import java.lang.reflect.Type
/** 后端配置兼容单个 banner 对象和 banner 数组。 */
class HomeBannerListAdapter : JsonDeserializer<List<HomeBannerEntity?>> {
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext,
): List<HomeBannerEntity?> = when {
json.isJsonObject -> listOf(context.deserialize(json, HomeBannerEntity::class.java))
json.isJsonArray -> json.asJsonArray.map { item ->
context.deserialize<HomeBannerEntity?>(item, HomeBannerEntity::class.java)
}
json.isJsonNull -> emptyList()
else -> throw JsonParseException("client.banner.home must be an object or array")
}
}

View File

@ -14,4 +14,5 @@ class UniVersionEntity(
var unimp_id: String = "",
var unimp_type: String = "",
var icon: String = "",
var urls: List<String>? = emptyList(),
)

View File

@ -18,6 +18,7 @@ class UserInfoEntity(
val name: String = "",
val phone: String = "",
val role: String = "",
val show_contact_menu: Boolean = false,
val temp: Boolean = true,
val unionid: String = "",
val user_id: String = "",

View File

@ -0,0 +1,124 @@
package com.img.rabbit.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsDraggedAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.repeatOnLifecycle
import coil3.compose.AsyncImage
import com.img.rabbit.R
import com.img.rabbit.bean.response.HomeBannerEntity
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
@Composable
fun HomeBanner(
banners: List<HomeBannerEntity>,
onClick: (HomeBannerEntity) -> Unit,
modifier: Modifier = Modifier,
) {
val fallback = painterResource(R.mipmap.ic_home_top_mask)
// 保持原顶部图片的宽高比,远程图片加载前后及兜底时布局不跳动。
val aspectRatio = fallback.intrinsicSize.width / fallback.intrinsicSize.height
if (banners.isEmpty()) {
Image(
painter = fallback,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = modifier.fillMaxWidth().aspectRatio(aspectRatio),
)
return
}
// 配置更新时重新建立页码,避免数量减少后仍访问旧页面。
key(banners) {
val count = banners.size
val pageCount = if (count > 1) Int.MAX_VALUE else 1
val startPage = if (count > 1) Int.MAX_VALUE / 2 / count * count else 0
val pagerState = rememberPagerState(initialPage = startPage) { pageCount }
val pressSource = remember { MutableInteractionSource() }
val isPressed by pressSource.collectIsPressedAsState()
val isDragged by pagerState.interactionSource.collectIsDraggedAsState()
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(pagerState, lifecycleOwner, isPressed, isDragged) {
if (count <= 1 || isPressed || isDragged) return@LaunchedEffect
lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
while (isActive) {
delay(3000)
if (!pagerState.isScrollInProgress) {
pagerState.animateScrollToPage((pagerState.currentPage + 1) % pageCount)
}
}
}
}
Box(modifier = modifier.fillMaxWidth().aspectRatio(aspectRatio)) {
HorizontalPager(
state = pagerState,
userScrollEnabled = count > 1,
modifier = Modifier.fillMaxSize(),
) { page ->
val item = banners[page % count]
AsyncImage(
model = item.img,
contentDescription = item.text,
placeholder = fallback,
error = fallback,
fallback = fallback,
// 等比缩放并居中裁切,图片比例不同时也铺满整个 banner。
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize().clickable(
interactionSource = pressSource,
indication = null,
) { onClick(item) },
)
}
if (count > 1) {
Row(
modifier = Modifier.align(Alignment.BottomCenter)
// 下方内容有 18dp 的圆角重叠区,圆点放在其上方。
.padding(bottom = 30.dp)
.background(Color.Black.copy(alpha = 0.15f), CircleShape)
.padding(horizontal = 8.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
repeat(count) { index ->
Box(
modifier = Modifier.size(6.dp).background(
if (pagerState.currentPage % count == index) Color.White else Color.White.copy(alpha = 0.45f),
CircleShape,
)
)
}
}
}
}
}
}

View File

@ -3,7 +3,7 @@ package com.img.rabbit.config
object Constants {
const val RELEASE_BASE_URL = "https://jitutu.batiao8.com" //release
const val DEBUG_BASE_URL = "https://jitutu.batiao8.com" //debug
const val LOG_REQUEST = "RabbitRequest"
const val LOG_REQUEST = "RequestLog"
const val agreementUrl = "https://jitutu.batiao8.com/static/policy-jietutu/user_android.html" //用户协议
const val privacyUrl = "https://jitutu.batiao8.com/static/policy-jietutu/provacy.html"//隐私政策

View File

@ -32,6 +32,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@ -92,6 +93,19 @@ import org.json.JSONObject
fun LoginScreen(navController: NavHostController? = null, generalViewModel: GeneralViewModel, loginViewModel: LoginViewModel, isVisibilityBreak: Boolean) {
val TAG = "Rabbit_LoginScreen"
val context = LocalContext.current
var isPreparingOneKeyLogin by remember(loginViewModel) { mutableStateOf(true) }
LaunchedEffect(loginViewModel) {
loginViewModel.setIsPolicyAgreement(false)
val activity = context as? Activity
val available = activity != null && loginViewModel.prepareOneKeyLogin(activity)
loginViewModel.loginScreenType.value = if (available) {
LoginScreenType.LOGIN_ONE_KEY
} else {
LoginScreenType.LOGIN_CAPTCHA
}
isPreparingOneKeyLogin = false
}
//关于登录的事件监听
LaunchedEffect(Unit) {
@ -104,6 +118,12 @@ fun LoginScreen(navController: NavHostController? = null, generalViewModel: Gene
loginViewModel.isLoginWxAuthor = false
}
}
is WXAuthEvent.AuthFailure -> {
if (loginViewModel.isLoginWxAuthor) {
loginViewModel.isLoginWxAuthor = false
CenterToast.show(event.message)
}
}
}
}
}
@ -150,39 +170,48 @@ fun LoginScreen(navController: NavHostController? = null, generalViewModel: Gene
.fillMaxSize()
) {
Box(modifier = Modifier.fillMaxSize()){
loginViewModel.setIsPolicyAgreement(false)
when(loginViewModel.loginScreenType.value){
LoginScreenType.LOGIN_ONE_KEY -> {
//一键登录
OneKeyLoginScreen(context, loginViewModel)
if (isPreparingOneKeyLogin) {
Column(
modifier = Modifier.align(Alignment.Center),
horizontalAlignment = Alignment.CenterHorizontally
) {
CircularProgressIndicator()
Text("正在获取本机号码…", modifier = Modifier.padding(top = 16.dp))
}
LoginScreenType.LOGIN_WX -> {
//微信登录
Box(modifier = Modifier.align(Alignment.Center).padding(bottom = 100.dp)){
WxLoginScreen(context, loginViewModel, generalViewModel)
} else {
when(loginViewModel.loginScreenType.value){
LoginScreenType.LOGIN_ONE_KEY -> {
//一键登录
OneKeyLoginScreen(context, loginViewModel)
}
LoginScreenType.LOGIN_WX -> {
//微信登录
Box(modifier = Modifier.align(Alignment.Center).padding(bottom = 100.dp)){
WxLoginScreen(context, loginViewModel, generalViewModel)
}
}
LoginScreenType.LOGIN_ALIPAY -> {
//支付宝登录
Box(modifier = Modifier.align(Alignment.Center).padding(bottom = 100.dp)){
AliPayLoginScreen(context, loginViewModel)
}
LoginScreenType.LOGIN_ALIPAY -> {
//支付宝登录
Box(modifier = Modifier.align(Alignment.Center).padding(bottom = 100.dp)){
AliPayLoginScreen(context, loginViewModel)
}
}
else -> {
//默认验证码登录
CaptchaLoginScreen(context, loginViewModel)
}
}
else -> {
//默认验证码登录
CaptchaLoginScreen(context, loginViewModel)
}
}
// 其他登录方式Bar
Column (
modifier = Modifier
.fillMaxSize()
.padding(top = 27.dp),
verticalArrangement = Arrangement.Bottom
){
OtherLoginBar(viewModel = loginViewModel)
// 其他登录方式Bar
Column (
modifier = Modifier
.fillMaxSize()
.padding(top = 27.dp),
verticalArrangement = Arrangement.Bottom
){
OtherLoginBar(viewModel = loginViewModel)
}
}
}
}
@ -316,7 +345,11 @@ private fun CaptchaLoginScreen(context: Context, viewModel: LoginViewModel) {
BasicTextField(
value = viewModel.userName.value,
onValueChange = { viewModel.setUserName(it) },
onValueChange = {
if (it.length <= 11) {
viewModel.setUserName(it)
}
},
modifier = Modifier
.fillMaxWidth()
.background(Color.Transparent)
@ -391,7 +424,7 @@ private fun CaptchaLoginScreen(context: Context, viewModel: LoginViewModel) {
singleLine = true,
maxLines = 1,
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = androidx.compose.ui.text.input.KeyboardType.Text,
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number,
imeAction = androidx.compose.ui.text.input.ImeAction.Done
),
decorationBox = { innerTextField ->
@ -599,24 +632,18 @@ private fun CaptchaLoginScreen(context: Context, viewModel: LoginViewModel) {
@SuppressLint("UseKtx", "InflateParams", "SetTextI18n")
@Composable
private fun OneKeyLoginScreen(context: Context, viewModel: LoginViewModel) {
val TAG = "Rabbit_LoginScreen_OneKeyLoginScreen"
val preLoginResult = GYManager.getInstance().preLoginResult
val phoneNumber = viewModel.oneKeyPreLogin?.number ?: ""
val operator = preLoginResult.operator//运营商,CM 移动,CT 电信,CU 联通
if (preLoginResult == null || !preLoginResult.isValid) {
LaunchedEffect(Unit) {
viewModel.loginScreenType.value = LoginScreenType.LOGIN_CAPTCHA
}
return
}
val phoneNumber = viewModel.oneKeyPreLogin?.number.orEmpty()
val operator = preLoginResult.operator
val privacyName = "《${preLoginResult.privacyName}》"
val privacyUrl = preLoginResult.privacyUrl
// 详细打印preLoginResult信息
Log.w(TAG, "=== preLoginResult 详细信息 ===")
Log.w(TAG, "preLoginResult对象: $preLoginResult")
Log.w(TAG, "operator: ${preLoginResult.operator}")
Log.w(TAG, "isValid: ${preLoginResult.isValid}")
Log.w(TAG, "privacyName: ${preLoginResult.privacyName}")
Log.w(TAG, "privacyUrl: ${preLoginResult.privacyUrl}")
Log.w(TAG, "================================")
val agreementText = "登录即认可${privacyName}、《用户协议》和《隐私政策》并使用本机号码登录"
Column(
modifier = Modifier
@ -626,15 +653,12 @@ private fun OneKeyLoginScreen(context: Context, viewModel: LoginViewModel) {
// 使用AndroidView嵌入XML布局
@Suppress("COMPOSE_APPLIER_CALL_MISMATCH")
AndroidView(
factory = { context ->
LayoutInflater.from(context).inflate(
factory = { viewContext ->
val view = LayoutInflater.from(viewContext).inflate(
R.layout.layout_one_key_login,
null,
false
) as ConstraintLayout
},
modifier = Modifier.fillMaxSize(),
update = { view ->
// 动态更新XML布局中的内容
val phoneTextView = view.findViewById<TextView>(R.id.layout_one_key_login_tv_phone)
phoneTextView.text = phoneNumber // 需要回去手机号码
@ -686,18 +710,17 @@ private fun OneKeyLoginScreen(context: Context, viewModel: LoginViewModel) {
privacyTv = agreementTextView,
viewModel = viewModel
)
// loginButton.setOnClickListener {
// // 处理登录点击
// oneKeyLogin(
// context = context,
// numberTv = phoneTextView,
// sloganTv = serviceTextView,
// loginBtn = loginButton,
// checkBox = checkbox,
// privacyTv = agreementTextView,
// viewModel = viewModel
// )
// }
view
},
modifier = Modifier.fillMaxSize(),
update = { view ->
// 只更新勾选状态,避免重绘时重复注册 SDK 登录回调。
val checkbox = view.findViewById<CheckBox>(R.id.layout_one_key_login_agreement_checkbox)
checkbox.setOnCheckedChangeListener(null)
checkbox.isChecked = viewModel.isPolicyAgreement.value
checkbox.setOnCheckedChangeListener { _, isChecked ->
viewModel.setIsPolicyAgreement(isChecked)
}
}
)
}
@ -1187,36 +1210,58 @@ private fun oneKeyLogin(
privacyTv: TextView,
viewModel: LoginViewModel,
) {
val activity = context as Activity
fun fallbackToCaptcha() {
activity.runOnUiThread {
loginBtn.isEnabled = true
if (viewModel.loginScreenType.value == LoginScreenType.LOGIN_ONE_KEY) {
viewModel.loginScreenType.value = LoginScreenType.LOGIN_CAPTCHA
CenterToast.show("一键登录暂不可用,请使用验证码登录")
}
}
}
val gyCallBack = object : GyCallBack {
override fun onSuccess(response: GYResponse?) {
loginBtn.isEnabled = true
Log.i("OneKeyLogin", "OneKeyLoginViewModel------onSuccess:$response")
try {
val jsonObject = JSONObject(response?.msg?:"{}")
val data = jsonObject.getJSONObject("data")
val token = data.getString("token")
viewModel.requestOneKeyLogin(response?.gyuid?:"", token)
} catch (e: Exception) {
e.printStackTrace()
activity.runOnUiThread {
loginBtn.isEnabled = true
if (viewModel.loginScreenType.value != LoginScreenType.LOGIN_ONE_KEY) return@runOnUiThread
try {
val data = JSONObject(response?.msg ?: "{}").getJSONObject("data")
val token = data.getString("token")
val gyuid = response?.gyuid.orEmpty()
if (token.isBlank() || gyuid.isBlank()) {
fallbackToCaptcha()
} else {
viewModel.requestOneKeyLogin(gyuid, token)
}
} catch (e: Exception) {
Log.w("OneKeyLogin", "一键登录凭证解析失败", e)
fallbackToCaptcha()
}
}
}
override fun onFailed(p0: GYResponse?) {
loginBtn.isEnabled = true
Log.e("OneKeyLogin", "OneKeyLoginViewModel------onFailed:$p0")
fallbackToCaptcha()
}
}
val eloginActivityParam = EloginActivityParam()
.setActivity(context as Activity)
.setActivity(activity)
.setNumberTextview(numberTv)
.setSloganTextview(sloganTv)
.setLoginButton(loginBtn)
.setPrivacyCheckbox(checkBox)
.setPrivacyTextview(privacyTv)
.setUiErrorListener { msg ->
loginBtn.isEnabled = true
Log.e("OneKeyLogin", "OneKeyLoginViewModel------UIErrorListener.onError:$msg")
activity.runOnUiThread {
loginBtn.isEnabled = true
if (checkBox.isChecked) {
fallbackToCaptcha()
} else {
CenterToast.show("请先同意用户协议和隐私政策")
}
}
}
.setLoginOnClickListener {
if (!checkBox.isChecked) {
@ -1226,7 +1271,12 @@ private fun oneKeyLogin(
}
// 预先注册登录回调
GYManager.getInstance().eAccountLogin(eloginActivityParam, 5000, gyCallBack)
try {
GYManager.getInstance().eAccountLogin(eloginActivityParam, 5000, gyCallBack)
} catch (e: Exception) {
Log.w("OneKeyLogin", "一键登录授权页初始化失败", e)
fallbackToCaptcha()
}
}
enum class LoginScreenType {

View File

@ -58,9 +58,31 @@ import com.img.rabbit.viewmodel.LoginViewModel
import kotlinx.coroutines.delay
// 定义底部导航的标签页
sealed class TabItem(val title: String, val router:String, val normalIconRes: Int, val selectedIconRes: Int, val normalColor: Color, val selectedColor: Color) {
object Home : TabItem("首页", "home", R.mipmap.ic_home_normal, R.mipmap.ic_home_selected, Color(0xFFAAAAAA), Color(0xFF1A1A1A))
object Mine : TabItem("我的", "mine", R.mipmap.ic_mine_normal, R.mipmap.ic_mine_selected, Color(0xFFAAAAAA), Color(0xFF1A1A1A))
sealed class TabItem(
val title: String,
val router: String,
val normalIconRes: Int,
val selectedIconRes: Int,
val normalColor: Color,
val selectedColor: Color
) {
object Home : TabItem(
"首页",
"home",
R.mipmap.ic_home_normal,
R.mipmap.ic_home_selected,
Color(0xFFAAAAAA),
Color(0xFF1A1A1A)
)
object Mine : TabItem(
"我的",
"mine",
R.mipmap.ic_mine_normal,
R.mipmap.ic_mine_selected,
Color(0xFFAAAAAA),
Color(0xFF1A1A1A)
)
}
/**
@ -72,7 +94,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
val navController = rememberNavController()
val networkStatus by generalViewModel.networkStatus.observeAsState(initial = true)
val isNavigationBarVisible by generalViewModel.isNavigationBarVisible.observeAsState(initial = true)
val tabItems = listOf( TabItem.Home, TabItem.Mine )
val tabItems = listOf(TabItem.Home, TabItem.Mine)
var selectedTab: TabItem by remember { mutableStateOf(TabItem.Home) }
generalViewModel.navController = navController
@ -84,7 +106,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
selectedTab = TabItem.Home
// 显示TabBar
generalViewModel.setNavigationBarVisible(true)
}else if(navBackStackEntry?.destination?.route == "mine"){
} else if (navBackStackEntry?.destination?.route == "mine") {
selectedTab = TabItem.Mine
// 显示TabBar
generalViewModel.setNavigationBarVisible(true)
@ -95,7 +117,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
LaunchedEffect(networkStatus) {
if (!networkStatus) {
// 网络断开时的处理
Log.w("NetworkStatus","网络断开")
Log.w("NetworkStatus", "网络断开")
//延迟500ms,确保页面初始化完成后,再跳转网络错误页面
delay(500)
@ -104,13 +126,13 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
navController.navigate("netError")
generalViewModel.setNavigationBarVisible(false)
*/
}else{
} else {
/*
if(navBackStackEntry?.destination?.route == "home"||navBackStackEntry?.destination?.route == "mine"){
generalViewModel.setNavigationBarVisible(true)
}
*/
Log.w("NetworkStatus","网络已连接")
Log.w("NetworkStatus", "网络已连接")
}
}
@ -118,11 +140,14 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
bottomBar = {
if (isNavigationBarVisible) {
Column(
modifier = Modifier.navigationBarsPadding()
modifier = Modifier
.background(Color.White)
.navigationBarsPadding()
) {
Box(modifier = Modifier.height(52.dp)) {
NavigationBar(
containerColor = Color.White,
tonalElevation = 0.dp,
contentColor = Color.Transparent
) {
tabItems.forEachIndexed { index, item ->
@ -140,12 +165,17 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
modifier = Modifier.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null
){
) {
selectedTab = tabItems[index]
}
)
},
label = { Text(item.title, color = if (selectedTab == tabItems[index]) item.selectedColor else item.normalColor) },
label = {
Text(
item.title,
color = if (selectedTab == tabItems[index]) item.selectedColor else item.normalColor
)
},
selected = selectedTab == tabItems[index],
onClick = { selectedTab = tabItems[index] },
interactionSource = remember { MutableInteractionSource() },
@ -255,15 +285,17 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
}
)
) { backStackEntry ->
val isVisibilityBreak = when(backStackEntry.arguments?.getInt("type")){
val isVisibilityBreak = when (backStackEntry.arguments?.getInt("type")) {
LoginViewModel.JumpLoginType.FROM_ADD.type -> {
// 添加账号
true
}
LoginViewModel.JumpLoginType.FROM_LOGOUT.type -> {
// 退出登录
false
}
else -> false
}
LoginScreen(
@ -296,7 +328,8 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
BindScreen(
navController = navController,
generalViewModel = generalViewModel,
bindType = backStackEntry.arguments?.getInt("type")?:BindViewModel.BindType.FROM_PHONE.type
bindType = backStackEntry.arguments?.getInt("type")
?: BindViewModel.BindType.FROM_PHONE.type
)
}
@ -305,7 +338,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
NetworkDisconnectedPage(
navController = navController,
generalViewModel = generalViewModel,
){
) {
}
}
@ -317,6 +350,7 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
TabItem.Home -> navController.navigate(ScreenRoute.Home.route) {
popUpTo(ScreenRoute.Home.route) { inclusive = true }
}
TabItem.Mine -> navController.navigate(ScreenRoute.Mine.route) {
popUpTo(ScreenRoute.Mine.route) { inclusive = true }
}

View File

@ -37,6 +37,7 @@ import com.img.rabbit.R
import com.img.rabbit.bean.response.UniVersionEntity
import com.img.rabbit.utils.UniAppUtils
import com.img.rabbit.utils.UniMpUpdate
import com.img.rabbit.viewmodel.ReportViewModel
import kotlinx.coroutines.CoroutineScope
@Composable
@ -50,6 +51,8 @@ fun TipsUniMpDialog(
data: UniVersionEntity,
isStartDown: MutableState<Boolean>,
downProgress: MutableState<Float>,
reportViewModel: ReportViewModel,
pagePath: String?,
onStatusChange: (state: Boolean, isCancel:Boolean, data: Any?) -> Unit
){
val context = LocalContext.current
@ -61,7 +64,7 @@ fun TipsUniMpDialog(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
onStatusChange(false, true, data)
if (!isStartDown.value) onStatusChange(false, true, data)
},
verticalArrangement = Arrangement.Center
){
@ -213,7 +216,8 @@ fun TipsUniMpDialog(
interactionSource = remember { MutableInteractionSource() }
) {
onStatusChange(false, false, data)
UniAppUtils.downloadWGT(context, scope, data){ uniState, filePath, progress ->
UniAppUtils.reportUpdateChoice(data, true, reportViewModel)
UniAppUtils.downloadWGT(context, scope, data, reportViewModel, pagePath){ uniState, _, progress ->
when (uniState) {
UniMpUpdate.DOWNLOAD_START -> {
//资源开始下载
@ -229,6 +233,7 @@ fun TipsUniMpDialog(
UniMpUpdate.DOWNLOAD_FAIL -> {
//资源下载失败
downProgress.value = -1f
onStatusChange(true, false, data)
Log.i("HomeScreen","DOWNLOAD_FAIL")
}
else -> {

View File

@ -32,7 +32,6 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
@ -56,15 +55,21 @@ import androidx.navigation.compose.rememberNavController
import coil3.compose.AsyncImage
import com.img.rabbit.R
import com.img.rabbit.bean.local.UIItemBean
import com.img.rabbit.bean.request.ReportKey
import com.img.rabbit.bean.request.ReportRequest
import com.img.rabbit.bean.request.ReportType
import com.img.rabbit.bean.response.HomeBannerEntity
import com.img.rabbit.bean.response.UniVersionEntity
import com.img.rabbit.components.CenterToast
import com.img.rabbit.components.HomeBanner
import com.img.rabbit.pages.LoadingCallback
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.route.ScreenRoute
import com.img.rabbit.route.HomeBannerRoutes
import com.img.rabbit.utils.GlobalEvent
import com.img.rabbit.utils.GlobalEventBus
import com.img.rabbit.utils.UniAppUtils
import com.img.rabbit.utils.UniMpUpdate
import com.img.rabbit.utils.UrlLinkUtils
import com.img.rabbit.viewmodel.GeneralViewModel
import com.img.rabbit.viewmodel.LoginViewModel
import com.img.rabbit.viewmodel.ReportViewModel
@ -72,6 +77,7 @@ import io.dcloud.feature.sdk.DCUniMPSDK
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.json.JSONObject
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import kotlin.collections.chunked
/**
@ -153,13 +159,11 @@ fun HomeScreen(
}
}
var homeIconConfig by remember { mutableStateOf(PreferenceUtil.getUserConfig()?.config?.homeIconEntity) }
var uniVersionConfig by remember { mutableStateOf(PreferenceUtil.getUserConfig()?.config?.uniVersionEntity) }
LaunchedEffect(loginViewModel.userConfigResult.value) {
if(loginViewModel.userConfigResult.value != null){
homeIconConfig = PreferenceUtil.getUserConfig()?.config?.homeIconEntity
uniVersionConfig = PreferenceUtil.getUserConfig()?.config?.uniVersionEntity
}
val userConfig = loginViewModel.userConfig.value?.config
val homeIconConfig = userConfig?.homeIconEntity
val uniVersionConfig = userConfig?.uniVersionEntity
val homeBanners = remember(userConfig?.homeBanners) {
HomeBannerEntity.visibleItems(userConfig?.homeBanners)
}
Column(
@ -177,13 +181,59 @@ fun HomeScreen(
shape = RoundedCornerShape(topStart = 18.dp, topEnd = 18.dp)
)
){
// 顶部mask
item {
Image(
painter = painterResource(id = R.mipmap.ic_home_top_mask),
contentDescription = null,
contentScale = ContentScale.FillWidth,
modifier = Modifier.fillMaxWidth()
// 顶部轮播,无配置和加载失败时使用原顶部图片兜底。
item(key = "home_banner") {
HomeBanner(
banners = homeBanners,
onClick = { banner ->
val type = banner.type.orEmpty()
val url = banner.url.orEmpty()
reportViewModel.requestReport(ReportRequest(
type = ReportType.CLICK,
key = ReportKey.EVENT_CLIENT_HOME_BANNER_CLICK,
value = type,
extra = url,
))
when (type) {
"wx", "alipay" -> {
if (loginViewModel.requiredLogin()) {
val version = uniVersionConfig?.firstOrNull { it.unimp_type == type }
if (version == null) {
CenterToast.show("功能暂不可用,请稍后重试")
} else {
dealUniMpDownloadLaunch(
context, scope, version, progressPair,
reportViewModel, loadingCallback,
pagePath = url.takeIf { it.isNotBlank() },
itemName = banner.text?.takeIf { it.isNotBlank() } ?: "home",
)
}
}
}
"web" -> {
if (url.isNotBlank()) {
if (url.toHttpUrlOrNull() != null) {
UrlLinkUtils.openAgreement(context, banner.text.orEmpty(), url)
} else {
CenterToast.show("链接暂不可用")
}
}
}
"app" -> {
if (url.isNotBlank()) {
val route = HomeBannerRoutes.resolve(url)
if (route == null) {
CenterToast.show("功能暂不可用,请稍后重试")
} else {
generalViewModel.setNavigationBarVisible(
route == ScreenRoute.Home.route || route == ScreenRoute.Mine.route
)
navController.navigate(route) { launchSingleTop = true }
}
}
}
}
},
)
Column(
modifier = Modifier
@ -199,7 +249,7 @@ fun HomeScreen(
}
// 当配置开启模拟器时,展示模拟器部分
if(PreferenceUtil.getUserConfig()?.config?.isUniMpOpen?:false){
if(userConfig?.isUniMpOpen == true){
//模拟器部分,大于9时,每排展示3个,否则每排展示4个
val columnsCount = if((homeIconConfig?.size?:0) >= 9){ 3 }else{ 4 }
val rows = homeIconConfig?.chunked(columnsCount)?:emptyList()
@ -269,7 +319,7 @@ fun HomeScreen(
)
//下载完成前显示
if((progressPair[uniMpId]?:0f) > 0f && (progressPair[uniMpId]?:0f) < 1f){
if((progressPair[uniMpId]?:-1f) >= 0f && (progressPair[uniMpId]?:-1f) < 1f){
Box(
modifier = Modifier
.fillMaxWidth()
@ -343,7 +393,7 @@ fun HomeScreen(
)
//下载完成前显示
if((progressPair[uniMpId]?:0f) > 0f && (progressPair[uniMpId]?:0f) < 1f){
if((progressPair[uniMpId]?:-1f) >= 0f && (progressPair[uniMpId]?:-1f) < 1f){
Box(
modifier = Modifier
.fillMaxWidth()
@ -406,23 +456,16 @@ fun HomeScreen(
}
val uniVersion =
PreferenceUtil.getUserConfig()?.config?.uniVersionEntity?.firstOrNull { it.unimp_type == item.type }
uniVersionConfig?.firstOrNull { it.unimp_type == item.type }
if(uniVersion == null){
CenterToast.show("无可用资源...")
return@clickable
}
val uniMpId = uniVersion.unimp_id
UniAppUtils.currentUniMpJumpPatch = item.url
val wgtExists = UniAppUtils.wgtIsExists(uniMpId)
if(!wgtExists){
//是否下载
scope.launch {
GlobalEventBus.emit(
GlobalEvent.ShowUniDownloadNotify(uniVersion))
}
}else {
UniAppUtils.startUniMpPage(context = context, uniMpId = uniMpId, uniMpType = item.type, pagePath = item.url, reportViewModel = reportViewModel)
}
dealUniMpDownloadLaunch(
context, scope, uniVersion, progressPair,
reportViewModel, loadingCallback,
pagePath = item.url, itemName = item.text
)
}
) {
Column {
@ -765,17 +808,32 @@ private fun dealUniMpDownloadLaunch(
uniMp: UniVersionEntity,
progressPair: SnapshotStateMap<String, Float>,
reportViewModel: ReportViewModel,
loadingCallback: LoadingCallback?){
loadingCallback: LoadingCallback?,
pagePath: String? = null,
itemName: String = "",
){
val TAG = "Rabbit_HomeScreen_download"
val uniMpId = uniMp.unimp_id
UniAppUtils.reportOpen(uniMp, itemName.ifEmpty { if (uniMp.unimp_type == "wx") "微信模拟器" else "小宝模拟器" }, reportViewModel)
if (UniAppUtils.isBusy(uniMpId)) {
CenterToast.show("请等待模拟器更新完毕!")
return
}
if (UniAppUtils.showRunningUniMp(uniMpId, pagePath)) return
// 处理点击事件,微信模拟器
if (UniAppUtils.isDownloadUniMp(uniMp)) {
if (pagePath != null) {
scope.launch { GlobalEventBus.emit(GlobalEvent.ShowUniDownloadNotify(uniMp, pagePath)) }
return
}
//没有下载或者强制更新(更新释放新版本并启动)
UniAppUtils.downloadWGT(
context,
scope,
uniMp
uniMp,
reportViewModel,
pagePath
) { uniState, _, progress ->
progressPair[uniMpId]
?: mutableMapOf<String, Float>().apply { put(uniMpId, 0f) }
@ -818,15 +876,14 @@ private fun dealUniMpDownloadLaunch(
}
} else if (UniAppUtils.isUpdate(uniMp)) {
// 提示更新(1、更新释放新版本并启动;2、直接启动现有版本)
UniAppUtils.currentUpdateUniMp = uniMp
scope.launch {
GlobalEventBus.emit(
GlobalEvent.ShowUniUpdateNotify(uniMp))
GlobalEvent.ShowUniUpdateNotify(uniMp, pagePath))
}
} else {
loadingCallback?.showLoading()
//启动uni小程序(1、直接启动;2、释放并启动)
UniAppUtils.distributeUniMp(context, uniMp, reportViewModel) {
UniAppUtils.distributeUniMp(context, uniMp, reportViewModel, pagePath) {
loadingCallback?.hideLoading()
}
}

View File

@ -22,10 +22,8 @@ import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
@ -57,7 +55,6 @@ import com.img.rabbit.utils.GlobalEventBus
import com.img.rabbit.viewmodel.GeneralViewModel
import com.img.rabbit.viewmodel.LoginViewModel
import com.img.rabbit.viewmodel.MineViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
@ -75,7 +72,7 @@ fun MineScreen(
val context = LocalContext.current
val scope = rememberCoroutineScope()
//用户数据
var userInfo by remember { mutableStateOf(PreferenceUtil.getUserInfo()) }
val userInfo by loginViewModel.userInfo
// 获取当前路由状态
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
@ -92,15 +89,6 @@ fun MineScreen(
}
}
LaunchedEffect(loginViewModel.userInfoResult.value) {
if(loginViewModel.userInfoResult.value != null){
// 等待200ms,确保用户配置已经刷新
delay(200)
userInfo = PreferenceUtil.getUserInfo()
}
}
Box(
modifier = Modifier
.fillMaxSize()
@ -402,62 +390,60 @@ fun MineScreen(
Color(0x4DBBBBBB)
)
)
Row(
modifier = Modifier
.fillMaxWidth()
.height(52.dp)
.clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
if (!generalViewModel.api.isWXAppInstalled) {
CenterToast.show("未安装微信客户端")
}else if(userInfo != null){
viewModel.requestServiceLink(generalViewModel.api)
}
},
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.mipmap.ic_mine_service),
contentDescription = null,
contentScale = ContentScale.FillWidth,
if(userInfo?.show_contact_menu == true){
Row(
modifier = Modifier
.wrapContentSize()
.padding(start = 12.dp)
)
Box(
modifier = Modifier.weight(1f)
){
Text(
text = "在线客服",
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
color = Color(0xFF1A1A1A),
.fillMaxWidth()
.height(52.dp)
.clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
viewModel.requestServiceLink(generalViewModel.api)
},
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.mipmap.ic_mine_service),
contentDescription = null,
contentScale = ContentScale.FillWidth,
modifier = Modifier
.wrapContentSize()
.padding(start = 8.dp)
.padding(start = 12.dp)
)
Box(
modifier = Modifier.weight(1f)
){
Text(
text = "在线客服",
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
color = Color(0xFF1A1A1A),
modifier = Modifier
.wrapContentSize()
.padding(start = 8.dp)
)
}
Image(
painter = painterResource(id = R.mipmap.ic_arrow_right),
contentDescription = null,
contentScale = ContentScale.FillWidth,
modifier = Modifier
.wrapContentSize()
.padding(end = 12.dp) // 改为end padding
)
}
Image(
painter = painterResource(id = R.mipmap.ic_arrow_right),
contentDescription = null,
contentScale = ContentScale.FillWidth,
Box(
modifier = Modifier
.wrapContentSize()
.padding(end = 12.dp) // 改为end padding
.fillMaxWidth()
.height(0.5.dp)
.padding(horizontal = 12.dp)
.background(
Color(0x4DBBBBBB)
)
)
}
Box(
modifier = Modifier
.fillMaxWidth()
.height(0.5.dp)
.padding(horizontal = 12.dp)
.background(
Color(0x4DBBBBBB)
)
)
Row(
modifier = Modifier
.fillMaxWidth()

View File

@ -78,7 +78,6 @@ import coil3.compose.AsyncImage
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale
import com.img.rabbit.R
import com.img.rabbit.bean.local.ClothingBean
import com.img.rabbit.bean.local.HairstyleBean
@ -102,7 +101,10 @@ import java.util.Date
import java.util.Locale
import com.img.rabbit.utils.PhotoCutter
import com.img.rabbit.viewmodel.CutoutViewModel
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
// 建议的状态数据结构
@ -146,8 +148,10 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
val coroutineScope = rememberCoroutineScope()
// 抠图加载中状态
val isLoading = remember { mutableStateOf(false) }
var isSaving by remember { mutableStateOf(false) }
var recordedImage by remember { mutableStateOf<Bitmap?>(null) }
val widthParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("width") ?: 23f
val widthParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("width") ?: 25f
val heightParam = navController.previousBackStackEntry?.savedStateHandle?.get<Float>("height") ?: 35f
//显示服装和发型
@ -188,7 +192,7 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
// 当前选中的发型
val selectedHairstyle = remember { mutableStateOf(hairstyleForFemales.getOrNull(0)) }
// 当前选中的尺寸
val selectedSize = remember { mutableStateOf(resizes.first { it.width == widthParam && it.height == heightParam }) }
val selectedSize = remember { mutableStateOf(resizes.firstOrNull { it.width == widthParam && it.height == heightParam } ?: resizes.first()) }
val storagePermissionState = rememberPermissionState(
@ -207,6 +211,8 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
) { uri ->
uri?.let {
selectedImageUri.value = it
cutoutResultBitmap.value = null
recordedImage = null
isLoading.value = true
// 执行抠图操作
if(isLoadingCutoutMethodFromService){
@ -290,54 +296,47 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
.navigationBarsPadding()
) {
TitleBar(navController = navController, paddingValues = it, title = "", showSave = true){
// 保存图片
if (isSaving) return@TitleBar
if (isLoading.value || cutoutResultBitmap.value == null) {
CenterToast.show("请等待抠图完成后再保存")
return@TitleBar
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && !storagePermissionState.status.isGranted) {
storagePermissionState.launchPermissionRequest()
return@TitleBar
}
// Receiving the result does not mean Compose has recorded the new canvas yet.
if (recordedImage !== cutoutResultBitmap.value || graphicsLayer.isReleased ||
graphicsLayer.size.width <= 0 || graphicsLayer.size.height <= 0) {
CenterToast.show("图片尚未绘制完成,请稍后保存")
return@TitleBar
}
isSaving = true
coroutineScope.launch {
// 从 Layer 捕获 Bitmap
val bitmap = graphicsLayer.toImageBitmap().asAndroidBitmap()
// 保存图片到系统相册(图片已按比例裁剪)
/*
saveCanvasToGallery(context, bitmap, ExportFormat.JPG){fileName, isSuccess ->
val tips = if(isSuccess){ "已保存为: $fileName" }else{ "保存失败" }
CenterToast.show(tips)
}
*/
/*
// 保存图片到系统相册(指定尺寸,如果targetWidth与targetHeight比原始值小太多会导致图片模糊)
saveCanvasToGallery(context, bitmap, ExportFormat.JPG, selectedSize.value.width.toInt(), selectedSize.value.height.toInt()){fileName, isSuccess ->
if(isSuccess){
Toast.makeText(context, "已保存为: $fileName", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show()
}
}
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// 保存图片到系统相册(图片已按比例裁剪)
saveCanvasToGallery(context, bitmap, ExportFormat.JPG){fileName, isSuccess ->
val tips = if(isSuccess){ "已保存为: $fileName" }else{ "保存失败" }
CenterToast.show(tips)
}
}else{
when {
// 情况 A:已获得权限
storagePermissionState.status.isGranted -> {
// 保存图片到系统相册(图片已按比例裁剪)
saveCanvasToGallery(context, bitmap, ExportFormat.JPG){fileName, isSuccess ->
val tips = if(isSuccess){ "已保存为: $fileName" }else{ "保存失败" }
CenterToast.show(tips)
try {
val bitmap = graphicsLayer.toImageBitmap().asAndroidBitmap()
try {
val result = withContext(Dispatchers.IO) {
var result: Pair<String, Boolean> = "" to false
saveCanvasToGallery(context, bitmap, ExportFormat.JPG) { filename, success ->
result = filename to success
}
result
}
// 情况 B:需要向用户解释(之前拒绝过,但未勾选“不再询问”)
storagePermissionState.status.shouldShowRationale -> {
storagePermissionState.launchPermissionRequest()
}
// 情况 C:从未请求过权限或已被彻底拒绝
else -> {
storagePermissionState.launchPermissionRequest()
}
CenterToast.show(if (result.second) "已保存为: ${result.first}" else "保存失败,请重试")
} finally {
bitmap.recycle()
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e("CutoutScreen", "保存抠图结果失败", e)
CenterToast.show("保存失败,请稍后重试")
} catch (e: OutOfMemoryError) {
Log.e("CutoutScreen", "保存图片时内存不足", e)
CenterToast.show("内存不足,请稍后重试")
} finally {
isSaving = false
}
}
}
@ -398,6 +397,7 @@ fun CutoutScreen(navController: NavController, viewModel: CutoutViewModel = view
graphicsLayer.record {
this@drawWithContent.drawContent()
}
recordedImage = cutoutResultBitmap.value
drawLayer(graphicsLayer)
}
.clipToBounds()

View File

@ -197,7 +197,7 @@ fun AccountBindScreen(navController: NavHostController, viewModel: AccountBindVi
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
//TODO 跳转绑定或解绑微信
// 跳转绑定或解绑微信
if (userInfo?.weixinAppId.isNullOrEmpty()) {
navController.navigate("bind?type=${BindViewModel.BindType.FROM_WX.type}")
} else {

View File

@ -98,6 +98,12 @@ fun BindScreen(navController: NavHostController, viewModel: BindViewModel = view
viewModel.isBindWxAuthor = false
}
}
is WXAuthEvent.AuthFailure -> {
if (viewModel.isBindWxAuthor) {
viewModel.isBindWxAuthor = false
CenterToast.show(event.message)
}
}
}
}
}

View File

@ -0,0 +1,58 @@
package com.img.rabbit.provider
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.pm.ProviderInfo
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import com.getui.gtc.base.GtcProvider
import com.img.rabbit.provider.storage.PrivacyConsentStore
/** 保留个推的进程通信地址,但在授权前不创建 SDK Provider。 */
class ConsentGtcProvider : ContentProvider() {
private var delegate: ContentProvider? = null
private lateinit var providerInfo: ProviderInfo
override fun attachInfo(context: Context, info: ProviderInfo) {
providerInfo = info
super.attachInfo(context, info)
}
override fun onCreate(): Boolean = true
@Synchronized
private fun initialize(): ContentProvider? {
if (!PrivacyConsentStore.isAccepted()) return null
return delegate ?: GtcProvider().also {
it.attachInfo(requireNotNull(context), providerInfo)
delegate = it
}
}
override fun call(method: String, arg: String?, extras: Bundle?): Bundle? {
val provider = initialize() ?: return null
return if (method == INITIALIZE) Bundle() else provider.call(method, arg, extras)
}
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
override fun getType(uri: Uri): String? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
override fun update(uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<out String>?): Int = 0
companion object {
private const val INITIALIZE = "rabbit.initializeAfterConsent"
fun initializeAfterConsent(context: Context) {
if (!PrivacyConsentStore.isAccepted()) return
context.contentResolver.call(
Uri.parse("content://${context.packageName}.getui.gtc.provider"),
INITIALIZE, null, null
)
}
}
}

View File

@ -2,14 +2,16 @@
package com.img.rabbit.provider.api
import android.util.Log
import com.batiao.batiaosdk.SignInterceptor
import com.img.rabbit.BuildConfig
import com.img.rabbit.config.Constants
import com.img.rabbit.provider.utils.HeaderInterceptor
import com.img.rabbit.provider.utils.RequestInterceptor
import com.img.rabbit.provider.utils.ResponseInterceptor
import com.img.rabbit.provider.utils.getUnsafeOkHttpClient
import com.img.rabbit.viewmodel.`interface`.ServiceVo
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
@ -33,12 +35,14 @@ object ApiManager {
}
if (!::retrofit.isInitialized) {
val client = OkHttpClient().newBuilder()
// 仅业务 API 使用 Batiao 签名和解密,资源下载保持原始 URL。
val client = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.addInterceptor(RequestInterceptor())
.addInterceptor(HeaderInterceptor())
.addDebugRequestLogging()
.addInterceptor(SignInterceptor)
.build()
retrofit = Retrofit.Builder()
@ -54,8 +58,9 @@ object ApiManager {
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.addInterceptor(HeaderInterceptor())
.addInterceptor(RequestInterceptor())
.addInterceptor(ResponseInterceptor())
.addDebugRequestLogging()
.addInterceptor(SignInterceptor)
.build()
unsafeRetrofit = Retrofit.Builder()
@ -70,6 +75,19 @@ object ApiManager {
}
}
private fun OkHttpClient.Builder.addDebugRequestLogging(): OkHttpClient.Builder = apply {
if (BuildConfig.DEBUG) {
// 放在签名拦截器外侧,以记录 SDK 解密后的响应。
addInterceptor(HttpLoggingInterceptor { message ->
message.chunked(1000).forEach { chunk ->
Log.d(Constants.LOG_REQUEST, chunk)
}
}.apply {
level = HttpLoggingInterceptor.Level.BODY
})
}
}
// 添加重新初始化方法,用于在baseUrl改变时调用
fun reinitialize() {
// 重置所有实例,使其在下一次访问时重新初始化

View File

@ -1,18 +1,13 @@
package com.img.rabbit.provider.storage
import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.img.rabbit.bean.local.UniMpVersionBean
import com.img.rabbit.bean.response.UserConfigEntity
import com.img.rabbit.bean.response.LoginInfoEntity
import com.img.rabbit.bean.response.UserInfoEntity
import com.img.rabbit.provider.utils.HeadParamUtils.applicationContext
import com.img.rabbit.utils.MMKVUtils
import com.img.rabbit.utils.MMKVUtils.mmkv
import com.img.rabbit.utils.appwalle.ChannelReader
import kotlinx.serialization.json.Json
import org.json.JSONObject
/**
* SharedPreferences工具类,用于简化数据持久化操作
@ -27,7 +22,6 @@ object PreferenceUtil {
private const val KEY_USER_CONFIG = "user_config"
private const val KEY_WX_CODE = "wx_code"
private const val KEY_USER_INFO = "user_info"
private const val KEY_AGREEMENT = "agreement"
private const val KEY_WGT_VERSION = "uni_wgt_version"
@ -38,7 +32,7 @@ object PreferenceUtil {
// Gson实例
private val gson: Gson = GsonBuilder().create()
private val gson: Gson by lazy { GsonBuilder().create() }
/**
@ -74,11 +68,11 @@ object PreferenceUtil {
fun saveAgreement(agreement: Boolean) {
mmkv.putBoolean(KEY_AGREEMENT, agreement)
PrivacyConsentStore.setAccepted(agreement)
}
fun getAgreement(): Boolean {
return mmkv.decodeBool(KEY_AGREEMENT, false)
return PrivacyConsentStore.isAccepted()
}
fun saveUserConfig(config: UserConfigEntity?) {
@ -137,7 +131,7 @@ object PreferenceUtil {
fun saveUserInfo(userInfoEntity: UserInfoEntity?) {
if(userInfoEntity == null){
mmkv.encode(KEY_USER_INFO, gson.toJson("{}"))
mmkv.remove(KEY_USER_INFO)
}else{
mmkv.encode(KEY_USER_INFO, gson.toJson(userInfoEntity))
}
@ -145,7 +139,8 @@ object PreferenceUtil {
fun getUserInfo(): UserInfoEntity? {
return try {
gson.fromJson(mmkv.decodeString(KEY_USER_INFO, "{}"), UserInfoEntity::class.java)
gson.fromJson(mmkv.decodeString(KEY_USER_INFO, null), UserInfoEntity::class.java)
?.takeIf { !it.user_id.isNullOrBlank() }
}catch (e: Exception){
null
}
@ -213,5 +208,6 @@ object PreferenceUtil {
*/
fun clearAll() {
mmkv.clearAll()
PrivacyConsentStore.setAccepted(false)
}
}

View File

@ -0,0 +1,22 @@
package com.img.rabbit.provider.storage
import android.content.Context
import android.content.SharedPreferences
/** 协议判断不能依赖尚未获准初始化的 MMKV 或其他 SDK。 */
object PrivacyConsentStore {
private lateinit var preferences: SharedPreferences
fun initialize(context: Context) {
preferences = context.getSharedPreferences("privacy_consent", Context.MODE_PRIVATE)
}
fun isAccepted(): Boolean = preferences.getBoolean("accepted", false)
fun setAccepted(accepted: Boolean) {
// 在启动小程序等独立进程前落盘,保证它们读取到明确的授权状态。
check(preferences.edit().putBoolean("accepted", accepted).commit()) {
"无法保存隐私协议状态"
}
}
}

View File

@ -3,15 +3,9 @@ package com.img.rabbit.provider.utils
import android.content.Context
import android.content.pm.PackageManager
import com.img.rabbit.R
import okhttp3.internal.platform.ContextAwarePlatform
import okhttp3.internal.platform.Platform
object HeadParamUtils {
var applicationContext: Context?
get() = (Platform.get() as? ContextAwarePlatform)?.applicationContext
set(value) {
(Platform.get() as? ContextAwarePlatform)?.applicationContext = value
}
var applicationContext: Context? = null
fun getAppVersionName(): String? {
return try {

View File

@ -1,11 +1,9 @@
package com.img.rabbit.provider.utils
import android.util.Log
import com.github.gzuliyujiang.oaid.DeviceIdentifier
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.BuildConfig
import com.img.rabbit.config.Constants
import com.img.rabbit.config.Constants.LOG_REQUEST
import com.img.rabbit.provider.utils.HeadParamUtils.applicationContext
import com.img.rabbit.provider.utils.HeadParamUtils.getAppVersionName
import com.img.rabbit.utils.ChannelUtils
@ -33,22 +31,6 @@ class HeaderInterceptor : Interceptor {
mBuilder.header("x-click-id", "${ChannelUtils.getBdVid(applicationContext)}")
mBuilder.header("x-app-id", Constants.AppId)
val stringBuilder = StringBuilder()
stringBuilder.append("-------------> 📤 header start<-------------\n")
stringBuilder.append("│ x-token = $accessToken\n")
stringBuilder.append("│ x-version = ${getAppVersionName()}\n")
stringBuilder.append("│ x-device-id = ${DeviceIdentifier.getAndroidID(applicationContext)}\n")
stringBuilder.append("│ x-mobile-brand = ${android.os.Build.BRAND}\n")
stringBuilder.append("│ x-mobile-model = ${android.os.Build.MODEL}\n")
stringBuilder.append("│ x-base-version = ${getAppVersionName()}\n")
stringBuilder.append("│ x-channel = ${ChannelUtils.getChannel(applicationContext)}\n")
stringBuilder.append("│ x-click-id = ${ChannelUtils.getBdVid(applicationContext)}\n")
stringBuilder.append("│ x-package = ${BuildConfig.APPLICATION_ID}\n")
stringBuilder.append("-------------> header end <-------------")
Log.i(LOG_REQUEST, stringBuilder.toString())
val request = mBuilder
.method(original.method, original.body)
.build()

View File

@ -1,85 +1,26 @@
package com.img.rabbit.provider.utils
import android.text.TextUtils
import android.util.Log
import com.img.rabbit.BuildConfig
import com.img.rabbit.config.Constants
import com.img.rabbit.utils.AESpkcs7paddingUtil
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import org.json.JSONObject
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException
/**
* 解密数据
*/
/** 签名和解密由 Batiao SDK 处理,此处仅保留业务接口的 HTTP 400 兼容。 */
class ResponseInterceptor : Interceptor {
private val TAG = "Decode"
private val baseUrl = (if (BuildConfig.DEBUG) Constants.DEBUG_BASE_URL else Constants.RELEASE_BASE_URL).toHttpUrl()
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val url = request.url
val apiPath = String.format("%s", url)
val baseUrl = if (BuildConfig.DEBUG) {
Constants.DEBUG_BASE_URL
} else {
Constants.RELEASE_BASE_URL
}
//如果请求的不是服务端的接口则不用加密
if (!apiPath.startsWith(baseUrl)) {
return chain.proceed(request)
}
val response = chain.proceed(request)
var charset = Charset.forName("UTF-8")
val contentType = response.header("Content-Type")
if (contentType != null && contentType.contains("application/json")) {
val responseBody = response.body
val source = responseBody.source()
source.request(Long.MAX_VALUE)
val buffer = source.buffer
val mediaType = responseBody.contentType()
if (mediaType != null) {
try {
charset = mediaType.charset(Charset.forName("UTF-8"))
} catch (e: UnsupportedCharsetException) {
e.printStackTrace()
}
}
val respBody = buffer.clone().readString(charset!!)
Log.w(TAG, "response=${respBody}")
if (TextUtils.isEmpty(respBody)) {
val responseCode = if (response.code == 400) 200 else response.code //兼容某些接口400的情况
return response.newBuilder().code(responseCode).body(responseBody).build()
}
val isEncrypt = JSONObject(respBody).optBoolean("encrypt")
Log.w(TAG, "是否需要解密:$isEncrypt")
if (!isEncrypt) { //如果不需要加密 直接返回
Log.w(TAG, "response=${response.body}")
val responseCode = if (response.code == 400) 200 else response.code //兼容某些接口400的情况
return response.newBuilder().code(responseCode).body(responseBody).build()
}
val decrybody = JSONObject(respBody).optString("data")
Log.w(TAG, "Json解析后的字符串为---->$decrybody")
var decryString: String?
try {
decryString = AESpkcs7paddingUtil.decryptNormal(decrybody, Constants.AESDecrypt)
Log.w("ResponseInterceptor", "解密后返回的字符串为---->$decryString")
//这里可以通过code处理token过去过期的情况
//val decCode = JSONObject(decryString).optInt("code")
//返回新创建的response
val responseCode = if (response.code == 400 && decrybody != null) 200 else response.code //兼容某些接口400的情况
return response.newBuilder().code(responseCode).body(decryString.toResponseBody("text/plain".toMediaType())).build()
} catch (e: Exception) {
e.printStackTrace()
}
val isBackend = request.url.scheme == baseUrl.scheme &&
request.url.host == baseUrl.host && request.url.port == baseUrl.port
return if (isBackend && response.code == 400 &&
response.header("Content-Type").orEmpty().contains("application/json", ignoreCase = true)
) {
response.newBuilder().code(200).build()
} else {
response
}
return response
}
}

View File

@ -0,0 +1,15 @@
package com.img.rabbit.route
/** 仅允许跳转宿主已注册的原生页面,未知配置不传给 NavController。 */
internal object HomeBannerRoutes {
private val routes = setOf(
ScreenRoute.Home.route, ScreenRoute.Mine.route,
ScreenRoute.Cutout.route, ScreenRoute.Resize.route, ScreenRoute.Format.route,
ScreenRoute.CameraGuide.route, ScreenRoute.LongImage.route,
ScreenRoute.Feedback.route, ScreenRoute.Login.route, ScreenRoute.Setting.route,
ScreenRoute.BindAccount.route, ScreenRoute.ManagerAccount.route,
ScreenRoute.AboutMine.route, ScreenRoute.DeleteAccount.route,
)
fun resolve(route: String?): String? = route?.takeIf { it in routes }
}

View File

@ -11,21 +11,30 @@ import com.img.rabbit.R;
import io.dcloud.feature.sdk.Interface.IDCUniMPAppSplashView;
public class UniMPAlipaySplashView implements IDCUniMPAppSplashView {
FrameLayout splashView;
private FrameLayout splashView;
private UniMPSplashWindow splashWindow;
@Override
public View getSplashView(Context context, String appid, String s1, String s2) {
if (splashWindow != null) splashWindow.close();
splashView = new FrameLayout(context);
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(R.mipmap.ic_launch_alipay_unimp);
splashView.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
splashWindow = new UniMPSplashWindow(context, splashView, true);
return splashView;
}
@Override
public void onCloseSplash(ViewGroup rootView) {
if(rootView != null)
if (splashWindow != null) {
splashWindow.close();
splashWindow = null;
}
if (rootView != null && splashView != null) {
rootView.removeView(splashView);
}
splashView = null;
}
}

View File

@ -0,0 +1,95 @@
package com.img.rabbit.uni
import android.app.Activity
import android.app.Application
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver
import android.view.Window
import android.view.WindowManager
import io.dcloud.feature.sdk.DCUniMPActivity
/** 在各 UniMP 进程中维持底部沉浸,覆盖启动图关闭、页面切换和后台返回。 */
@Suppress("DEPRECATION")
object UniMPImmersiveWindow {
fun register(application: Application) {
application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
private val controllers = mutableMapOf<Activity, Controller>()
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
// 包含 DCUniMPActivity0..4 和 DCUniMPTopActivity0..4;不改宿主及支付等页面。
if (activity is DCUniMPActivity) {
controllers[activity] = Controller(activity.window)
}
}
override fun onActivityResumed(activity: Activity) {
controllers[activity]?.apply()
}
override fun onActivityDestroyed(activity: Activity) {
controllers.remove(activity)?.close()
}
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
})
}
internal fun apply(window: Window) {
val flags = window.attributes.flags
if (flags and WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS == 0) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
}
if (flags and WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION != 0) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
}
if (window.navigationBarColor != Color.TRANSPARENT) window.navigationBarColor = Color.TRANSPARENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && window.navigationBarDividerColor != Color.TRANSPARENT) {
window.navigationBarDividerColor = Color.TRANSPARENT
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && window.isNavigationBarContrastEnforced) {
window.isNavigationBarContrastEnforced = false
}
// 只让内容延伸至导航栏下方。保留 SDK 的状态栏、图标颜色和 adjustResize 输入法处理;
// 不隐藏系统手势条,也不消费键盘或状态栏的 WindowInsets。
val decor = window.decorView
val visibility = decor.systemUiVisibility or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
if (decor.systemUiVisibility != visibility) decor.systemUiVisibility = visibility
}
private class Controller(private val window: Window) :
ViewTreeObserver.OnGlobalLayoutListener, ViewTreeObserver.OnWindowFocusChangeListener {
private val decor = window.decorView
private val observer = decor.viewTreeObserver
init {
observer.addOnGlobalLayoutListener(this)
observer.addOnWindowFocusChangeListener(this)
apply()
}
fun apply() = UniMPImmersiveWindow.apply(window)
override fun onGlobalLayout() = apply()
override fun onWindowFocusChanged(hasFocus: Boolean) {
if (hasFocus) apply()
}
fun close() {
// 未附着时注册的 ViewTreeObserver 会合并到附着后的 observer。
val activeObserver = if (observer.isAlive) observer else decor.viewTreeObserver
if (activeObserver.isAlive) {
activeObserver.removeOnGlobalLayoutListener(this)
activeObserver.removeOnWindowFocusChangeListener(this)
}
}
}
}

View File

@ -0,0 +1,125 @@
package com.img.rabbit.uni
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Color
import android.os.Build
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager
import androidx.core.view.WindowCompat
import io.dcloud.feature.sdk.DCUniMPActivity
/** 启动图期间设置导航图标明暗,关闭后交由 UniMP 正文的沉浸控制器接管。 */
@Suppress("DEPRECATION")
class UniMPSplashWindow(
context: Context,
private val splashView: View,
private val darkNavigationIcons: Boolean,
) :
View.OnAttachStateChangeListener, ViewTreeObserver.OnGlobalLayoutListener {
private val activity = findActivity(context)
private val window = activity?.window
private val originalNavigationBarColor = window?.navigationBarColor
private val originalSystemUiVisibility = window?.decorView?.systemUiVisibility ?: 0
private val originalWindowFlags = window?.attributes?.flags ?: 0
private val originalDividerColor = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) window?.navigationBarDividerColor else null
private val originalContrastEnforced = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) window?.isNavigationBarContrastEnforced else null
private val insetsController = window?.let { WindowCompat.getInsetsController(it, it.decorView) }
private val originalLightNavigationBars = insetsController?.isAppearanceLightNavigationBars ?: false
private var observer: ViewTreeObserver? = null
private var closed = false
private val reapply = Runnable { applyTransparentNavigationBar() }
init {
splashView.addOnAttachStateChangeListener(this)
applyTransparentNavigationBar()
if (splashView.isAttachedToWindow) onViewAttachedToWindow(splashView)
}
override fun onViewAttachedToWindow(view: View) {
if (closed) return
observer?.takeIf { it.isAlive }?.removeOnGlobalLayoutListener(this)
observer = view.viewTreeObserver.also { it.addOnGlobalLayoutListener(this) }
applyTransparentNavigationBar()
// SDK 初始化窗口时可能覆盖导航栏配置,启动阶段短暂补设。
view.removeCallbacks(reapply)
for (attempt in 1..10) view.postDelayed(reapply, attempt * 50L)
}
override fun onGlobalLayout() = applyTransparentNavigationBar()
override fun onViewDetachedFromWindow(view: View) = close()
private fun applyTransparentNavigationBar() {
val window = window ?: return
if (closed) return
val flags = window.attributes.flags
if (flags and WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS == 0) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
}
if (flags and WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION != 0) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
}
if (window.navigationBarColor != Color.TRANSPARENT) window.navigationBarColor = Color.TRANSPARENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && window.navigationBarDividerColor != Color.TRANSPARENT) {
window.navigationBarDividerColor = Color.TRANSPARENT
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && window.isNavigationBarContrastEnforced) {
window.isNavigationBarContrastEnforced = false
}
val decor = window.decorView
val visibility = decor.systemUiVisibility or LAYOUT_FLAGS
if (decor.systemUiVisibility != visibility) decor.systemUiVisibility = visibility
// 微信启动图为深色、支付宝为白色,分别使用浅色和深色导航按键。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && insetsController != null &&
insetsController.isAppearanceLightNavigationBars != darkNavigationIcons) {
insetsController.isAppearanceLightNavigationBars = darkNavigationIcons
}
}
fun close() {
if (closed) return
closed = true
// 先取消启动图监听及延时任务,正文由独立的沉浸控制器维护。
splashView.removeCallbacks(reapply)
splashView.removeOnAttachStateChangeListener(this)
observer?.takeIf { it.isAlive }?.removeOnGlobalLayoutListener(this)
observer = null
val window = window ?: return
window.decorView.systemUiVisibility =
(window.decorView.systemUiVisibility and LAYOUT_FLAGS.inv()) or
(originalSystemUiVisibility and LAYOUT_FLAGS)
window.setFlags(originalWindowFlags and WINDOW_FLAGS, WINDOW_FLAGS)
originalNavigationBarColor?.let { window.navigationBarColor = it }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
originalDividerColor?.let { window.navigationBarDividerColor = it }
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
originalContrastEnforced?.let { window.isNavigationBarContrastEnforced = it }
}
insetsController?.isAppearanceLightNavigationBars = originalLightNavigationBars
// 启动图关闭时立即接续底部沉浸,避免恢复窗口后先露出一帧安全区底色。
if (activity is DCUniMPActivity) UniMPImmersiveWindow.apply(window)
}
private companion object {
const val LAYOUT_FLAGS = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
const val WINDOW_FLAGS = WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS or
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
fun findActivity(context: Context): Activity? {
var current = context
while (current is ContextWrapper) {
if (current is Activity) return current
val base = current.baseContext
if (base === current) break
current = base
}
return null
}
}
}

View File

@ -12,21 +12,30 @@ import com.img.rabbit.R;
import io.dcloud.feature.sdk.Interface.IDCUniMPAppSplashView;
public class UniMPWxSplashView implements IDCUniMPAppSplashView {
FrameLayout splashView;
private FrameLayout splashView;
private UniMPSplashWindow splashWindow;
@Override
public View getSplashView(Context context, String appid, String s1, String s2) {
if (splashWindow != null) splashWindow.close();
splashView = new FrameLayout(context);
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(R.mipmap.ic_launch_wx_unimp);
splashView.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
splashWindow = new UniMPSplashWindow(context, splashView, false);
return splashView;
}
@Override
public void onCloseSplash(ViewGroup rootView) {
if(rootView != null)
if (splashWindow != null) {
splashWindow.close();
splashWindow = null;
}
if (rootView != null && splashView != null) {
rootView.removeView(splashView);
}
splashView = null;
}
}

View File

@ -13,7 +13,7 @@ object AppEventBus {
)
val events = _events.asSharedFlow()
*/
private val _events = MutableSharedFlow<Any>()
private val _events = MutableSharedFlow<Any>(extraBufferCapacity = 16)
val events = _events.asSharedFlow()
suspend fun post(event: UniMpWXPayEvent) {
@ -27,6 +27,9 @@ object AppEventBus {
suspend fun post(event: WXAuthEvent) {
_events.emit(event)
}
// Callback Activities must close even when a subscriber is temporarily busy.
fun tryPost(event: WXAuthEvent): Boolean = _events.tryEmit(event)
}
/**
@ -53,6 +56,7 @@ sealed class LoginBindEvent {
*/
sealed class WXAuthEvent {
data class AuthResult(val code: String, val authType: Int) : WXAuthEvent()
data class AuthFailure(val message: String) : WXAuthEvent()
}
/**
@ -68,8 +72,8 @@ sealed class UniMpWXPayEvent {
sealed class GlobalEvent {
object ShowAppUpdateNotify : GlobalEvent()
object ShowLoginNotify : GlobalEvent()
data class ShowUniDownloadNotify(val entity: UniVersionEntity) : GlobalEvent()
data class ShowUniUpdateNotify(val entity: UniVersionEntity) : GlobalEvent()
data class ShowUniDownloadNotify(val entity: UniVersionEntity, val pagePath: String? = null) : GlobalEvent()
data class ShowUniUpdateNotify(val entity: UniVersionEntity, val pagePath: String? = null) : GlobalEvent()
}
object GlobalEventBus {

View File

@ -4,6 +4,7 @@ import android.content.Context
import android.content.pm.PackageManager
import android.text.TextUtils
import com.alibaba.fastjson.JSON
import com.batiao.batiaosdk.PackageSpliter
import com.bytedance.hume.readapk.HumeSDK
import com.img.rabbit.BuildConfig
import com.img.rabbit.utils.appwalle.ChannelReader
@ -37,7 +38,8 @@ object ChannelUtils {
if (!TextUtils.isEmpty(juliang)) {
return juliang
}
return channel(context)
// 保留 Rabbit 的渠道命名和 manifest 兜底,优先读取 Batiao 分包渠道。
return PackageSpliter.getBatiaoChannel(channel(context))
}
private fun channel(context: Context): String {

View File

@ -0,0 +1,12 @@
package com.img.rabbit.utils
/** Choose the sampling factor before allocating pixels, including for very large camera images. */
internal fun imageSampleSize(width: Int, height: Int, maxDimension: Int): Int {
require(maxDimension > 0)
var sampleSize = 1
val longestSide = maxOf(width, height).toLong()
while ((longestSide + sampleSize - 1) / sampleSize > maxDimension) {
sampleSize *= 2
}
return sampleSize
}

View File

@ -205,10 +205,19 @@ object ImageUtils {
* @param uri 图片URI
* @return Bitmap对象,如果获取失败则返回null
*/
fun getBitmapFromUri(context: Context, uri: Uri): Bitmap? {
fun getBitmapFromUri(context: Context, uri: Uri, maxDimension: Int? = null): Bitmap? {
return try {
val options = BitmapFactory.Options()
if (maxDimension != null) {
options.inJustDecodeBounds = true
context.contentResolver.openInputStream(uri)?.use {
BitmapFactory.decodeStream(it, null, options)
}
options.inSampleSize = imageSampleSize(options.outWidth, options.outHeight, maxDimension)
options.inJustDecodeBounds = false
}
context.contentResolver.openInputStream(uri)?.use { inputStream ->
BitmapFactory.decodeStream(inputStream)
BitmapFactory.decodeStream(inputStream, null, options)
}
} catch (e: Exception) {
Log.e("ImageUtils", "从URI获取Bitmap失败", e)

View File

@ -1,12 +1,14 @@
package com.img.rabbit.utils
import android.graphics.*
import android.util.Log
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.segmentation.Segmentation
import com.google.mlkit.vision.segmentation.selfie.SelfieSegmenterOptions
import androidx.core.graphics.createBitmap
import androidx.compose.ui.geometry.Offset
import java.util.concurrent.Executors
// 变换状态模型
data class TransformState(
@ -18,6 +20,7 @@ data class TransformState(
object PhotoCutter {
private val executor = Executors.newSingleThreadExecutor()
fun cutPureHead(sourceBitmap: Bitmap, callback: (Bitmap?) -> Unit) {
// 1. 配置分割器:单图模式
@ -25,29 +28,42 @@ object PhotoCutter {
.setDetectorMode(SelfieSegmenterOptions.SINGLE_IMAGE_MODE)
.build()
val segmenter = Segmentation.getClient(options)
val image = InputImage.fromBitmap(sourceBitmap, 0)
// 2. 开始处理
segmenter.process(image)
.addOnSuccessListener { mask ->
val resultBitmap = generateTransparentBitmap(sourceBitmap, mask.buffer)
callback(resultBitmap)
}
.addOnFailureListener {
callback(null)
try {
val image = InputImage.fromBitmap(sourceBitmap, 0)
// Mask conversion belongs off the UI thread; exceptions here are asynchronous.
segmenter.process(image).addOnCompleteListener(executor) { task ->
val result = try {
val mask = task.result
generateTransparentBitmap(sourceBitmap, mask.buffer, mask.width, mask.height)
} catch (e: Exception) {
Log.e("PhotoCutter", "本地抠图失败", e)
null
} finally {
segmenter.close()
}
callback(result)
}
} catch (e: Exception) {
segmenter.close()
throw e
}
}
private fun generateTransparentBitmap(
source: Bitmap,
maskBuffer: java.nio.ByteBuffer,
maskWidth: Int,
maskHeight: Int,
): Bitmap {
val width = source.width
val height = source.height
val result = createBitmap(width, height)
// 将掩码缓冲区重置
maskBuffer.rewind()
require(maskWidth > 0 && maskHeight > 0 &&
maskBuffer.remaining().toLong() >= maskWidth.toLong() * maskHeight * 4) {
"无效的人像掩码"
}
// 逐像素处理
val pixels = IntArray(width * height)
@ -55,7 +71,9 @@ object PhotoCutter {
for (i in 0 until width * height) {
// 获取当前像素的人像概率(0.0 ~ 1.0)
val confidence = maskBuffer.float
val maskX = (i % width).toLong() * maskWidth / width
val maskY = (i / width).toLong() * maskHeight / height
val confidence = maskBuffer.getFloat(((maskY * maskWidth + maskX) * 4).toInt())
// 如果置信度低于 0.5,认为该像素是背景,设为完全透明
if (confidence < 0.5) {
@ -63,6 +81,7 @@ object PhotoCutter {
}
}
val result = createBitmap(width, height)
result.setPixels(pixels, 0, width, 0, 0, width, height)
return result
}

View File

@ -1,8 +1,10 @@
package com.img.rabbit.utils
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.webkit.MimeTypeMap
import com.batiao.batiaosdk.unimp.BatiaoUnimp
import com.github.gzuliyujiang.oaid.DeviceIdentifier
import com.img.rabbit.BuildConfig
import com.img.rabbit.bean.request.ReportKey
@ -23,403 +25,328 @@ import io.dcloud.feature.sdk.DCUniMPSDK
import io.dcloud.feature.sdk.Interface.IUniMP
import io.dcloud.feature.unimp.config.UniMPOpenConfiguration
import io.dcloud.feature.unimp.config.UniMPReleaseConfiguration
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import kotlinx.serialization.json.Json
import java.io.File
import kotlin.jvm.java
import java.util.Locale
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
/**
* UniApp工具类
* 小程序运行路径:/data/user/0/com.img.rabbit/files/apps/(一般/data/data/com.img.rabbit/files/apps/)
*/
/** UniMP 的下载、解压、启动及事件上报入口。 */
object UniAppUtils {
private const val TAG = "UniAppUtils"
/**
* 所有运行的UniMp小程序实体
*/
private val mainHandler = Handler(Looper.getMainLooper())
private val releaseExecutor = Executors.newSingleThreadExecutor()
private val downloader = UniMpDownloader()
private val downloading = ConcurrentHashMap.newKeySet<String>()
private val releasing = ConcurrentHashMap.newKeySet<String>()
private val _uniMpFlow = MutableStateFlow<Map<String?, IUniMP?>>(emptyMap())
val uniMpFlow = _uniMpFlow.asStateFlow()
fun updateUniMp(id: String?, mp: IUniMP?) {
val currentMap = _uniMpFlow.value.toMutableMap()
currentMap[id] = mp
_uniMpFlow.value = currentMap
_uniMpFlow.update { it + (id to mp) }
}
//当前正在更新的小程序
var currentUpdateUniMp: UniVersionEntity? = null
//仅当跳转指定小程序时,才需要跳转指定位置
var currentUniMpJumpPatch: String? = null
private fun getWgtName(uniMpId: String): String{
return String.format("%s.wgt", uniMpId)
//return String.format("%s.zip", uniMpId)
private fun getWgtFile(uniMpId: String): File {
require(uniMpId.matches(Regex("[A-Za-z0-9_-]+"))) { "无效的小程序 ID" }
val directory = FileUtils.instance?.cacheUniAppDir ?: File(checkNotNull(applicationContext).cacheDir, "uniApp")
return File(directory, "$uniMpId.wgt")
}
private fun getWgtFile(uniMpId: String): File{
val wgtName = getWgtName(uniMpId)
return File(FileUtils.instance?.cacheUniAppDir?.absolutePath, wgtName)
}
/**
*获取当前前台运行的UniMp小程序实体
*/
fun getCurrentUniMp(): IUniMP?{
return uniMpFlow.value.filter { it.value?.isRunning == true }.values.firstOrNull()
//return uniMpPair.filter { it.value?.isRunning == true }.values.firstOrNull()
}
/**
* 是否存在更新
*/
fun isUpdate(uniVersion: UniVersionEntity): Boolean{
return checkUpdate(uniVersion, PreferenceUtil.getWgtVersion(uniVersion.unimp_id)?:"0.0.0")
}
fun getCurrentUniMp(): IUniMP? = uniMpFlow.value.values.firstOrNull { it?.isRunning == true }
/**
* 是否强制更新
*/
private fun isUpdateForce(uniVersion: UniVersionEntity): Boolean{
return checkUpdate(uniVersion, PreferenceUtil.getWgtVersion(uniVersion.unimp_id)?:"0.0.0") && uniVersion.force
}
fun isUpdate(uniVersion: UniVersionEntity): Boolean = UniMpPolicy.isNewer(
uniVersion.version, PreferenceUtil.getWgtVersion(uniVersion.unimp_id) ?: "0.0.0"
)
/**
* 是否需要下载(强制更新或者不存在wgt文件)
*/
fun isDownloadUniMp(uniVersion: UniVersionEntity): Boolean{
val wgtFile = getWgtFile(uniVersion.unimp_id)
return isUpdateForce(uniVersion) || !(FileUtils.instance?.fileIsExists(wgtFile) == true && FileUtils.getFileSize(wgtFile) > 0)
}
fun isDownloadUniMp(uniVersion: UniVersionEntity): Boolean =
UniMpPolicy.requiresDownload(uniVersion.force, wgtIsExists(uniVersion.unimp_id))
fun wgtIsExists(uniMpId: String): Boolean{
val wgtFile = getWgtFile(uniMpId)
//判断wgt是否下载
return FileUtils.instance?.fileIsExists(wgtFile) == true && FileUtils.getFileSize(wgtFile) > 0
}
fun wgtIsExists(uniMpId: String): Boolean = runCatching {
getWgtFile(uniMpId).let { it.isFile && it.length() > 0 }
}.getOrDefault(false)
fun isRelease(uniMpId: String): Boolean{
return DCUniMPSDK.getInstance().isExistsApp(uniMpId)
}
fun isRelease(uniMpId: String): Boolean = DCUniMPSDK.getInstance().isExistsApp(uniMpId)
/**
* 检查更新
*/
private fun checkUpdate(uniVersion: UniVersionEntity, currentVersion: String): Boolean {
val version = uniVersion.version
if(version.isEmpty())return false
fun isBusy(uniMpId: String): Boolean = uniMpId in downloading || uniMpId in releasing
val newVersions = version.split(".")
val originVersions = currentVersion.split(".")
if(newVersions.size != 3 || originVersions.size != 3)return false
for (i in 0..2) {
val newVal = newVersions[i].toIntOrNull() ?: 0
val oldVal = originVersions[i].toIntOrNull() ?: 0
if (newVal > oldVal) {
return true
} else if (newVal < oldVal) {
return false
}
}
return false
}
/**
* 分发uniMP(下载、更新与启动)
*/
fun distributeUniMp(context: Context, uniVersion: UniVersionEntity,reportViewModel: ReportViewModel, onResult:(loading: Boolean) -> Unit){
val isExists = DCUniMPSDK.getInstance().isExistsApp(uniVersion.unimp_id)
if(isExists){
//资源已释放,直接启动
startUniMp(context, uniVersion, onResult)
}else{
//资源未释放,先释放后启动
releaseWgt(uniVersion,reportViewModel){ isSuccess, versionEntity ->
if(isSuccess){
startUniMp(context, versionEntity, onResult)
}else{
onResult(false)
}
}
/** 已运行的小程序直接显示,通过 jump 事件跳转,避免再次 openUniMP。 */
fun showRunningUniMp(uniMpId: String, pagePath: String?): Boolean {
if (isBusy(uniMpId)) return false
return try {
val mp = _uniMpFlow.value[uniMpId] ?: return false
refreshUniMpHeaders()
if ((mp.isRuning || mp.isRunning) && mp.showUniMP()) {
mp.sendUniMPEvent("jump", pagePath)
true
} else false
} catch (e: Exception) {
Log.w(TAG, "恢复小程序失败,将重新启动: $uniMpId", e)
updateUniMp(uniMpId, null)
false
}
}
private fun startUniMp(context: Context, uniVersion: UniVersionEntity, onResult:(loading: Boolean) -> Unit){
val uniMp = _uniMpFlow.value[uniVersion.unimp_id]//uniMpPair[uniVersion.unimp_id]
if(uniMp?.isRuning == true){
uniMp.showUniMP()
}else{
val configuration = getUniMPOpenConfiguration()
if(uniVersion.unimp_type == "wx"){
configuration.splashClass = UniMPWxSplashView::class.java
}else if("alipay" == uniVersion.unimp_type){
configuration.splashClass = UniMPAlipaySplashView::class.java
}
updateUniMp(uniVersion.unimp_id, DCUniMPSDK.getInstance().openUniMP(context, uniVersion.unimp_id, configuration))
}
onResult(false)
fun reportOpen(version: UniVersionEntity, itemName: String, reportViewModel: ReportViewModel) {
report(reportViewModel, ReportType.CLICK,
if (version.unimp_type == "wx") ReportKey.EVENT_CLIENT_OPEN_WX_UNIMP else ReportKey.EVENT_CLIENT_OPEN_ALIPAY_UNIMP,
itemName, "")
}
/**
* 启动小程序并直达指定页面
*/
fun startUniMpPage(context: Context, uniMpId: String, uniMpType: String, pagePath: String, reportViewModel: ReportViewModel){
if(!isRelease(uniMpId)){
releaseWgt(uniMpId,reportViewModel){
if(it){
// 启动直达页面
startUniMpToPage(context, uniMpId, uniMpType, pagePath)
}
}
}else {
val uniMp = _uniMpFlow.value[uniMpId]
if(uniMp?.isRuning == true){
uniMp.showUniMP()
}
// 启动直达页面
startUniMpToPage(context, uniMpId, uniMpType, pagePath)
}
}
private fun startUniMpToPage(context: Context, uniMpId: String, uniMpType: String, pagePath: String){
// 启动直达页面
val configuration = getUniMPOpenConfiguration()
if(uniMpType == "wx"){
configuration.splashClass = UniMPWxSplashView::class.java
}else if("alipay" == uniMpType){
configuration.splashClass = UniMPAlipaySplashView::class.java
}
configuration.path = pagePath
updateUniMp(uniMpId, DCUniMPSDK.getInstance().openUniMP(context, uniMpId, configuration))
fun reportUpdateChoice(version: UniVersionEntity, confirmed: Boolean, reportViewModel: ReportViewModel) {
report(reportViewModel, ReportType.CLICK,
if (confirmed) ReportKey.EVENT_CLIENT_CONFIRM_DOWNLOAD_UNIMP else ReportKey.EVENT_CLIENT_CANCEL_DOWNLOAD_UNIMP,
"", Json.encodeToString(version))
}
private fun releaseWgt(versionEntity: UniVersionEntity, reportViewModel: ReportViewModel, onReleaseWgt: (isSuccess: Boolean, versionEntity: UniVersionEntity) -> Unit) {
releaseWgt(versionEntity.unimp_id,reportViewModel){ isSuccess ->
if(isSuccess){
onReleaseWgt(true, versionEntity)
}else{
onReleaseWgt(false, versionEntity)
}
}
}
//释放资源
private fun releaseWgt(uniMpId: String, reportViewModel: ReportViewModel, onReleaseWgt: (isSuccess: Boolean) -> Unit) {
val appBasePath = DCUniMPSDK.getInstance().getAppBasePath(applicationContext)
val deleteSuccess = File(appBasePath, uniMpId).deleteRecursively()
if(deleteSuccess){
val wgtFile = getWgtFile(uniMpId)
val uniMPReleaseConfiguration = UniMPReleaseConfiguration().apply {
wgtPath = wgtFile.path
password = PreferenceUtil.getUserConfig()?.config?.wgtPassword//"6462"////没有密码可以不写
}
DCUniMPSDK.getInstance().releaseWgtToRunPath(uniMpId, uniMPReleaseConfiguration) { code, _ ->
if (code == 1) {
//释放wgt完成
onReleaseWgt(true)
} else {
//释放wgt失败
CenterToast.show("加载失败,请重试或联系客服!")
onReleaseWgt(false)
File(appBasePath, uniMpId).deleteRecursively()
//事件提交
reportViewModel.requestReport(
ReportRequest(
ReportType.ERROR,
ReportKey.EVENT_CLIENT_UNI_RELEASE_WGT,
uniMpId,
"释放资源失败"
)
)
}
}
}else{
CenterToast.show("加载失败,请重试或联系客服!")
}
}
/**
* 下载wgt文件
*/
fun downloadWGT(context: Context,scope: CoroutineScope, uniVersion: UniVersionEntity, reportViewModel: ReportViewModel = ReportViewModel(), onProgress:(state: UniMpUpdate, filePath: String?, progress: Float?) -> Unit) {
val wgtFile = getWgtFile(uniVersion.unimp_id)
onProgress(UniMpUpdate.DOWNLOAD_START, wgtFile.path, 0f)
downloadUniMp(scope, uniVersion){uniState, filePath, progress ->
onProgress(uniState, filePath, progress)
if(uniState == UniMpUpdate.DOWNLOAD_FINISH){
distributeUniMp(context, uniVersion,reportViewModel) { _ ->}
}
}
}
/**
* 下载并释放资源(但不会启动)
*/
fun downloadReleaseWgt(scope: CoroutineScope, uniVersion: UniVersionEntity,reportViewModel: ReportViewModel, onProgress:(state: UniMpUpdate, progress: Float?) -> Unit,onRelease:(isSuccess: Boolean) -> Unit){
val uniMpId = uniVersion.unimp_id
onProgress(UniMpUpdate.DOWNLOAD_START, 0f)
downloadUniMp(scope, uniVersion){uniState, _, progress ->
onProgress(UniMpUpdate.DOWNLOAD_LOADING, progress)
if(uniState == UniMpUpdate.DOWNLOAD_FINISH){
onProgress(UniMpUpdate.DOWNLOAD_FINISH, 1f)
releaseWgt(uniMpId,reportViewModel){ isSuccess ->
if(isSuccess){
onRelease(true)
}else{
onRelease(false)
}
}
}else if(uniState == UniMpUpdate.DOWNLOAD_FAIL){
onProgress(UniMpUpdate.DOWNLOAD_FAIL, -1f)
}
}
}
//下载资源
private fun downloadUniMp(
scope: CoroutineScope,
fun distributeUniMp(
context: Context,
uniVersion: UniVersionEntity,
onProgress:(state:UniMpUpdate,filePath: String?, progress: Float) -> Unit
) {
val extension = MimeTypeMap.getFileExtensionFromUrl(uniVersion.url)
if(extension != "zip" && extension != "wgt"){
CenterToast.show("资源文件格式不被支持...")
onProgress(UniMpUpdate.DOWNLOAD_FAIL, null, -1f)
reportViewModel: ReportViewModel,
pagePath: String? = null,
onResult: (loading: Boolean) -> Unit,
) = onMain {
if (isBusy(uniVersion.unimp_id)) {
CenterToast.show("请等待模拟器更新完毕!")
onResult(false)
} else if (showRunningUniMp(uniVersion.unimp_id, pagePath)) {
onResult(false)
} else if (isRelease(uniVersion.unimp_id)) {
openUniMp(context, uniVersion.unimp_id, uniVersion.unimp_type, pagePath, reportViewModel, onResult)
} else {
releaseWgt(uniVersion.unimp_id, reportViewModel) { success ->
if (success) {
openUniMp(context, uniVersion.unimp_id, uniVersion.unimp_type, pagePath, reportViewModel, onResult)
} else onResult(false)
}
}
}
fun startUniMpPage(context: Context, uniMpId: String, uniMpType: String, pagePath: String, reportViewModel: ReportViewModel) {
distributeUniMp(context, UniVersionEntity(unimp_id = uniMpId, unimp_type = uniMpType), reportViewModel, pagePath) {}
}
private fun openUniMp(
context: Context,
uniMpId: String,
uniMpType: String,
pagePath: String?,
reportViewModel: ReportViewModel,
onResult: (Boolean) -> Unit,
) = onMain {
try {
val mp = DCUniMPSDK.getInstance().openUniMP(context, uniMpId, getUniMPOpenConfiguration(uniMpType, pagePath))
if (mp == null) {
startupFailure(uniMpId, "上报原因:启动小程序失败", reportViewModel)
} else {
updateUniMp(uniMpId, mp)
}
} catch (e: Exception) {
Log.e(TAG, "启动小程序异常: $uniMpId", e)
startupFailure(uniMpId, "上报原因:启动小程序异常,${e.message.orEmpty()}", reportViewModel)
} finally {
onResult(false)
}
}
private fun startupFailure(uniMpId: String, reason: String, reportViewModel: ReportViewModel) {
updateUniMp(uniMpId, null)
runCatching { getWgtFile(uniMpId).delete() }
report(reportViewModel, ReportType.ERROR, ReportKey.EVENT_CLIENT_UNI_FAIL, uniMpId, reason)
CenterToast.show("加载失败,请重试或联系客服!")
}
private fun releaseWgt(uniMpId: String, reportViewModel: ReportViewModel, onRelease: (Boolean) -> Unit) {
if (!releasing.add(uniMpId)) {
onMain {
CenterToast.show("请等待模拟器更新完毕!")
onRelease(false)
}
return
}
val uniMpId = uniVersion.unimp_id
val wgtName = getWgtName(uniMpId)
val path = FileUtils.instance?.cacheUniAppDir?.absolutePath?:""
//先删除旧文件
val oldFile = File(path, wgtName)
if(oldFile.exists()){
oldFile.delete()
}
onProgress(UniMpUpdate.DOWNLOAD_LOADING, null, 0.0f)
scope.launch {
val isAvailable = isFileDownloadable(uniVersion.url)
if(!isAvailable){
onProgress(UniMpUpdate.DOWNLOAD_FAIL, null, -1f)
}else{
UpdateUtils.download(
scope = scope,
url = uniVersion.url,
filePath = path,
fileName = wgtName,
onProgress = {progress->
if(progress.toFloat()/100f>0.1f) {
onProgress(
UniMpUpdate.DOWNLOAD_LOADING,
null,
progress.toFloat() / 100f
)
}
},
onFinish = {isSuccess, filePath ->
if(isSuccess){
PreferenceUtil.saveWgtVersion(uniMpId, uniVersion.version)
onProgress(UniMpUpdate.DOWNLOAD_FINISH, filePath, 1f)
}else{
onProgress(UniMpUpdate.DOWNLOAD_FAIL, filePath, -1f)
CenterToast.show("下载失败...")
releaseExecutor.execute {
try {
val wgtFile = getWgtFile(uniMpId)
check(wgtFile.isFile && wgtFile.length() > 0) { "资源包不存在或为空" }
val config = PreferenceUtil.getUserConfig()?.config
val releaseConfig = UniMPReleaseConfiguration().apply {
wgtPath = wgtFile.absolutePath
password = UniMpPolicy.releasePassword(config?.wgtPassword, config?.uniPassword)
}
DCUniMPSDK.getInstance().releaseWgtToRunPath(uniMpId, releaseConfig) { code, args ->
if (code == 1) {
onMain {
releasing.remove(uniMpId)
onRelease(true)
}
} else {
releaseFailure(uniMpId, "SDK 释放失败提示。错误码: $code, 原因提示: $args", reportViewModel, onRelease)
}
)
}
} catch (e: Exception) {
releaseFailure(uniMpId, "释放小程序资源包异常: ${e.message.orEmpty()}", reportViewModel, onRelease)
}
}
}
private fun getUniMPOpenConfiguration(): UniMPOpenConfiguration{
val stringBuilder = StringBuilder()
stringBuilder.append("-------------> 📤 header start<-------------\n")
stringBuilder.append("│ x-token = ${PreferenceUtil.getXToken()}\n")
stringBuilder.append("│ x-version = ${getAppVersionName()}\n")
stringBuilder.append("│ x-platform = android\n")
stringBuilder.append("│ x-device-id = ${DeviceIdentifier.getAndroidID(applicationContext)}\n")
stringBuilder.append("│ x-mobile-brand = ${android.os.Build.BRAND}\n")
stringBuilder.append("│ x-mobile-model = ${android.os.Build.MODEL}\n")
stringBuilder.append("│ x-channel = ${ChannelUtils.getChannel(applicationContext)}\n")
stringBuilder.append("│ x-package = ${BuildConfig.APPLICATION_ID}\n")
stringBuilder.append("│ x-click-id = ${ChannelUtils.getBdVid(applicationContext)}\n")
stringBuilder.append("│ host = ${Constants.RELEASE_BASE_URL}\n")
stringBuilder.append("│ decrypt = ${Constants.AESDecrypt}\n")
stringBuilder.append("│ decrypt = ${Constants.Signature}\n")
stringBuilder.append("│ isCombo = ok\n")
stringBuilder.append("-------------> header end <-------------")
Log.i("UniAppUtils", stringBuilder.toString())
private fun releaseFailure(uniMpId: String, reason: String, reportViewModel: ReportViewModel, onRelease: (Boolean) -> Unit) {
releaseExecutor.execute {
runCatching {
getWgtFile(uniMpId).delete()
val basePath = DCUniMPSDK.getInstance().getAppBasePath(applicationContext)
File(basePath, uniMpId).deleteRecursively()
}.onFailure { Log.w(TAG, "清理失败的小程序资源异常", it) }
onMain {
releasing.remove(uniMpId)
updateUniMp(uniMpId, null)
Log.e(TAG, reason)
report(reportViewModel, ReportType.ERROR, ReportKey.EVENT_CLIENT_UNI_RELEASE_WGT, uniMpId, reason)
CenterToast.show("加载失败,请重试或联系客服!")
onRelease(false)
}
}
}
return UniMPOpenConfiguration().apply {
extraData.put("x-token", PreferenceUtil.getXToken()?:"")
extraData.put("x-version", getAppVersionName()?:"")
extraData.put("x-platform", "android")
extraData.put("x-device-id", DeviceIdentifier.getAndroidID(applicationContext))
extraData.put("x-mobile-brand", android.os.Build.BRAND)
extraData.put("x-mobile-model", android.os.Build.MODEL)
extraData.put("x-channel", ChannelUtils.getChannel(applicationContext))
extraData.put("x-package", BuildConfig.APPLICATION_ID)
extraData.put("x-click-id",ChannelUtils.getBdVid(applicationContext))
extraData.put("host", "${Constants.RELEASE_BASE_URL}/")
/** 新包下载完成后始终重新释放,避免仍启动旧的运行目录。 */
fun downloadWGT(
context: Context,
scope: CoroutineScope,
uniVersion: UniVersionEntity,
reportViewModel: ReportViewModel,
pagePath: String? = null,
onProgress: (state: UniMpUpdate, filePath: String?, progress: Float?) -> Unit,
) {
downloadUniMp(scope, uniVersion, reportViewModel, onProgress) {
releaseWgt(uniVersion.unimp_id, reportViewModel) { success ->
if (success) openUniMp(context, uniVersion.unimp_id, uniVersion.unimp_type, pagePath, reportViewModel) {}
}
}
}
fun downloadReleaseWgt(
scope: CoroutineScope,
uniVersion: UniVersionEntity,
reportViewModel: ReportViewModel,
onProgress: (state: UniMpUpdate, progress: Float?) -> Unit,
onRelease: (Boolean) -> Unit,
) {
downloadUniMp(scope, uniVersion, reportViewModel, { state, _, progress ->
onProgress(state, progress)
if (state == UniMpUpdate.DOWNLOAD_FAIL) onRelease(false)
}) {
releaseWgt(uniVersion.unimp_id, reportViewModel, onRelease)
}
}
private fun downloadUniMp(
scope: CoroutineScope,
version: UniVersionEntity,
reportViewModel: ReportViewModel,
onProgress: (UniMpUpdate, String?, Float?) -> Unit,
onDownloaded: () -> Unit,
) = onMain {
val id = version.unimp_id
if (id in releasing || !downloading.add(id)) {
CenterToast.show("请等待模拟器更新完毕!")
return@onMain
}
scope.launch(Dispatchers.Main.immediate, start = CoroutineStart.UNDISPATCHED) {
var failureReported = false
var downloadCompleted = false
try {
onProgress(UniMpUpdate.DOWNLOAD_START, null, 0f)
val file = getWgtFile(id)
val result = downloader.download(UniMpPolicy.downloadUrls(version), file,
onProgress = { progress -> withContext(Dispatchers.Main) { onProgress(UniMpUpdate.DOWNLOAD_LOADING, null, progress) } },
onFailure = { url, elapsed, reason ->
failureReported = true
report(reportViewModel, ReportType.ERROR, ReportKey.EVENT_CLIENT_DOWNLOAD_UNIMP_ERROR, reason,
"下载地址:$url 持续时间:${elapsed / 1000f}秒 上报原因:$reason")
})
downloadCompleted = true
PreferenceUtil.saveWgtVersion(id, version.version)
val time = String.format(Locale.CHINA, "%.2f", result.elapsedMillis / 1000.0)
report(reportViewModel, ReportType.CLICK, ReportKey.EVENT_CLIENT_DOWNLOAD_UNIMP_SUCCESS, "下载时间:${time}s",
"下载地址:${result.url} 持续时间:${time}秒 上报原因:下载完成。")
} catch (e: CancellationException) {
withContext(NonCancellable + Dispatchers.Main) { onProgress(UniMpUpdate.DOWNLOAD_FAIL, null, -1f) }
throw e
} catch (e: Exception) {
Log.e(TAG, "下载小程序失败: $id", e)
if (!failureReported || downloadCompleted) {
report(reportViewModel, ReportType.ERROR, ReportKey.EVENT_CLIENT_DOWNLOAD_UNIMP_ERROR, e.message.orEmpty(), "处理小程序资源包失败: $id,${e.message.orEmpty()}")
}
CenterToast.show("打开失败,请重试或联系客服")
onProgress(UniMpUpdate.DOWNLOAD_FAIL, null, -1f)
return@launch
} finally {
downloading.remove(id)
}
onProgress(UniMpUpdate.DOWNLOAD_FINISH, getWgtFile(id).path, 1f)
onDownloaded()
}
}
private fun getUniMPOpenConfiguration(uniType: String, pagePath: String?): UniMPOpenConfiguration =
UniMPOpenConfiguration().apply {
path = pagePath
splashClass = if (uniType == "alipay") UniMPAlipaySplashView::class.java else UniMPWxSplashView::class.java
// 同时保留 extraData,兼容尚未使用 Batiao 网络桥接的旧版小程序。
refreshUniMpHeaders().forEach { (key, value) -> extraData.put(key, value) }
extraData.put("host", "${Constants.RELEASE_BASE_URL.trimEnd('/')}/")
extraData.put("decrypt", Constants.AESDecrypt)
extraData.put("encrypt", Constants.Signature)
extraData.put("isCombo", "ok")
}
private fun refreshUniMpHeaders(): Map<String, String> {
val headers = linkedMapOf(
"x-token" to PreferenceUtil.getXToken().orEmpty(),
"x-version" to getAppVersionName().orEmpty(),
"x-platform" to "android",
"x-device-id" to DeviceIdentifier.getAndroidID(applicationContext).orEmpty(),
"x-mobile-brand" to android.os.Build.BRAND,
"x-mobile-model" to android.os.Build.MODEL,
"x-channel" to ChannelUtils.getChannel(applicationContext),
"x-package" to BuildConfig.APPLICATION_ID,
"x-click-id" to ChannelUtils.getBdVid(applicationContext).orEmpty(),
"x-base-version" to getAppVersionName().orEmpty(),
"x-app-id" to Constants.AppId,
)
BatiaoUnimp.setHeaders(headers)
return headers
}
/**
* 拉起微信小程序来支付
*/
fun startUniPay(api: IWXAPI, weixinMpOriId: String, outTradeNo: String) {
//isStartComboPay = true
val req = WXLaunchMiniProgram.Req()
req.userName = weixinMpOriId // 填小程序原始id
req.path = "pages/index/index?outTradeNo=$outTradeNo" //拉起小程序页面的可带参路径,不填默认拉起小程序首页,对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar"。
req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE// 可选打开 开发版,体验版和正式版
api.sendReq(req)
}
private val okHttpClient: OkHttpClient by lazy {
OkHttpClient.Builder()
// 如果需要,可以在这里配置超时、缓存等
// .connectTimeout(15, TimeUnit.SECONDS)
.build()
}
suspend fun isFileDownloadable(url: String): Boolean = withContext(Dispatchers.IO) {
val request = Request.Builder().url(url).build()
try {
okHttpClient.newCall(request).execute().use { response ->
val body = response.body
val fileSize = body.contentLength()
// 下载文件小于1KB,需要判断Url是否可靠
if (fileSize < 1024) {
return@withContext response.isSuccessful
} else {
return@withContext true
}
}
} catch (e: Exception) {
e.printStackTrace()
val request = WXLaunchMiniProgram.Req().apply {
userName = weixinMpOriId
path = "pages/index/index?outTradeNo=$outTradeNo"
miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE
}
return@withContext false
api.sendReq(request)
}
private fun report(viewModel: ReportViewModel, type: String, key: String, value: String, extra: String) {
viewModel.requestReport(ReportRequest(type = type, key = key, value = value, extra = extra))
}
private fun onMain(action: () -> Unit) {
if (Looper.myLooper() == Looper.getMainLooper()) action() else mainHandler.post { action() }
}
}
enum class UniMpUpdate{
enum class UniMpUpdate {
DOWNLOAD_START,
DOWNLOAD_LOADING,
DOWNLOAD_FINISH,
DOWNLOAD_FAIL
DOWNLOAD_FAIL,
}

View File

@ -0,0 +1,206 @@
package com.img.rabbit.utils
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
import java.util.concurrent.TimeUnit
/** 每个小程序独立下载;按 urls 顺序重试,重试期间展示进度不回退。 */
internal class UniMpDownloader(
private val client: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.callTimeout(60, TimeUnit.SECONDS)
.build(),
) {
data class Result(val url: String, val elapsedMillis: Long)
suspend fun download(
urls: List<String>,
destination: File,
onProgress: suspend (Float) -> Unit,
onFailure: suspend (url: String, elapsedMillis: Long, reason: String) -> Unit,
): Result = withContext(Dispatchers.IO) {
val started = System.nanoTime()
val temporary = File(destination.parentFile, "${destination.nameWithoutExtension}_cache.wgt")
val progressMutex = Mutex()
var maximumProgress = 0
var lastError: Exception = IOException("url为空!")
try {
for (url in urls.ifEmpty { listOf("") }) {
currentCoroutineContext().ensureActive()
val attemptStarted = System.nanoTime()
try {
val directory = destination.parentFile ?: throw IOException("下载目录不存在")
if (!directory.isDirectory && !directory.mkdirs()) throw IOException("无法创建下载目录")
if (temporary.exists() && !temporary.delete()) throw IOException("无法清理下载缓存")
if (url.isBlank()) throw IOException("url为空!")
downloadUrl(url, temporary, attemptStarted) { current, total ->
val percent = if (total > 0) (current * 100 / total).coerceIn(0, 99).toInt() else 0
progressMutex.withLock {
if (percent > maximumProgress) {
maximumProgress = percent
onProgress(percent / 100f)
}
}
}
currentCoroutineContext().ensureActive()
if (temporary.length() == 0L) throw IOException("资源包为空")
// 仅完整下载的包才能替换正式 wgt,SDK 要求文件名为 unimp_id.wgt。
if (destination.exists() && !destination.delete()) throw IOException("无法替换资源包")
if (!temporary.renameTo(destination)) throw IOException("复制资源包失败")
return@withContext Result(url, elapsedMillis(started))
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
currentCoroutineContext().ensureActive()
lastError = e
onFailure(url, elapsedMillis(attemptStarted), e.message?.takeIf { it.isNotBlank() } ?: "Url连接错误")
}
}
throw lastError
} finally {
temporary.delete()
}
}
private suspend fun downloadUrl(
url: String,
file: File,
started: Long,
onProgress: suspend (Long, Long) -> Unit,
) {
var rangedSize = 0L
request(Request.Builder().url(url).header("Accept-Encoding", "identity").build()) { response ->
if (!response.isSuccessful) throw IOException("HTTP ${response.code}: ${response.message}")
val total = response.body.contentLength()
if (total > CHUNK_SIZE && response.header("Accept-Ranges").equals("bytes", ignoreCase = true)) {
rangedSize = total
} else {
var received = 0L
var lastProgressTime = 0L
response.body.byteStream().use { input ->
file.outputStream().use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
checkActive(started)
val count = input.read(buffer)
if (count == -1) break
output.write(buffer, 0, count)
received += count
val now = elapsedMillis(started)
if (now - lastProgressTime >= 500) {
onProgress(received, total)
lastProgressTime = now
}
}
}
}
if (total >= 0 && received != total) throw IOException("资源包长度不匹配: $received/$total")
onProgress(received, total)
}
}
if (rangedSize > 0) downloadChunks(url, file, rangedSize, started, onProgress)
}
private suspend fun downloadChunks(
url: String,
file: File,
total: Long,
started: Long,
onProgress: suspend (Long, Long) -> Unit,
) = coroutineScope {
RandomAccessFile(file, "rw").use { it.setLength(total) }
val permits = Semaphore(MAX_THREADS)
val progressMutex = Mutex()
var received = 0L
var lastProgressTime = 0L
(0L until total step CHUNK_SIZE).map { start ->
async {
permits.withPermit {
val end = minOf(start + CHUNK_SIZE - 1, total - 1)
val request = Request.Builder().url(url)
.header("Accept-Encoding", "identity")
.header("Range", "bytes=$start-$end").build()
request(request) { response ->
if (response.code != 206 || response.header("Content-Range") != "bytes $start-$end/$total") {
throw IOException("无效的分块响应: HTTP ${response.code}")
}
var chunkSize = 0L
response.body.byteStream().use { input ->
RandomAccessFile(file, "rw").use { output ->
output.seek(start)
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
checkActive(started)
val count = input.read(buffer)
if (count == -1) break
chunkSize += count
if (chunkSize > end - start + 1) throw IOException("分块长度超出范围")
output.write(buffer, 0, count)
progressMutex.withLock {
received += count
val now = elapsedMillis(started)
if (now - lastProgressTime >= 500) {
onProgress(received, total)
lastProgressTime = now
}
}
}
}
}
if (chunkSize != end - start + 1) throw IOException("分块数据不完整")
}
}
}
}.awaitAll()
onProgress(received, total)
}
private suspend fun <T> request(request: Request, block: suspend (Response) -> T): T = coroutineScope {
val call = client.newCall(request)
// 取消页面任务或某个分块失败时,及时终止其余网络请求。
val cancellation = launch(start = CoroutineStart.UNDISPATCHED) {
try {
awaitCancellation()
} finally {
call.cancel()
}
}
try {
call.execute().use { block(it) }
} finally {
cancellation.cancel()
}
}
private suspend fun checkActive(started: Long) {
currentCoroutineContext().ensureActive()
if (elapsedMillis(started) > 60_000) throw IOException("超时下载")
}
private fun elapsedMillis(started: Long) = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)
private companion object {
const val CHUNK_SIZE = 10 * 1024 * 1024L
const val MAX_THREADS = 8
}
}

View File

@ -0,0 +1,27 @@
package com.img.rabbit.utils
import com.img.rabbit.bean.response.UniVersionEntity
/** 与 weiquan-android 的资源配置、强更和密码规则保持一致。 */
internal object UniMpPolicy {
fun releasePassword(wgtPassword: String?, uniPassword: String?): String? {
val prefix = wgtPassword.orEmpty().let { if (it.length > 10) it.substring(10) else it }
return (prefix + uniPassword.orEmpty()).takeIf { it.isNotEmpty() }
}
fun downloadUrls(version: UniVersionEntity): List<String> =
version.urls?.takeIf { it.isNotEmpty() } ?: listOf(version.url)
fun requiresDownload(force: Boolean, hasPackage: Boolean): Boolean = force || !hasPackage
fun isNewer(version: String, installedVersion: String): Boolean {
val newer = version.split('.')
val installed = installedVersion.split('.')
if (newer.size != 3 || installed.size != 3) return false
for (i in 0..2) {
val comparison = (newer[i].toIntOrNull() ?: 0).compareTo(installed[i].toIntOrNull() ?: 0)
if (comparison != 0) return comparison > 0
}
return false
}
}

View File

@ -0,0 +1,13 @@
package com.img.rabbit.utils
import com.tencent.mm.opensdk.modelbase.BaseResp
internal fun wechatAuthResult(errorCode: Int, code: String?): WXAuthEvent = when {
errorCode == BaseResp.ErrCode.ERR_OK && !code.isNullOrBlank() ->
WXAuthEvent.AuthResult(code, authType = 0)
errorCode == BaseResp.ErrCode.ERR_USER_CANCEL ->
WXAuthEvent.AuthFailure("已取消微信授权")
errorCode == BaseResp.ErrCode.ERR_AUTH_DENIED ->
WXAuthEvent.AuthFailure("微信授权被拒绝,请重试")
else -> WXAuthEvent.AuthFailure("微信授权失败,请重试")
}

View File

@ -0,0 +1,46 @@
package com.img.rabbit.utils
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/** SDK calls may synchronously query WeChat's ContentProvider. Keep them off the UI thread. */
object WechatRequests {
suspend fun authorize(api: IWXAPI, state: String): String? = execute {
if (!api.isWXAppInstalled) return@execute "您没有安装微信客户端,请先下载安装"
val request = SendAuth.Req().apply {
scope = "snsapi_userinfo"
this.state = state
}
if (api.sendReq(request)) null else "无法打开微信授权,请重试"
}
suspend fun customerService(api: IWXAPI, corpId: String?, url: String?): String? = execute {
if (!api.isWXAppInstalled) return@execute "未安装微信客户端"
if (api.wxAppSupportAPI < Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
return@execute "当前微信版本不支持在线客服,请升级微信"
}
if (corpId.isNullOrBlank() || url.isNullOrBlank()) {
return@execute "客服信息暂不可用,请稍后重试"
}
val request = WXOpenCustomerServiceChat.Req().apply {
this.corpId = corpId
this.url = url
}
if (api.sendReq(request)) null else "无法打开微信客服,请重试"
}
private suspend fun execute(block: () -> String?): String? = withContext(Dispatchers.IO) {
try {
block()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
"微信暂时无法响应,请稍后重试"
}
}
}

View File

@ -39,7 +39,6 @@ class AccountBindViewModel : BaseViewModel() {
if(wechatCode.isEmpty()){
return
}
PreferenceUtil.saveWxCode(wechatCode)
// 调用 API 获取数据
val jsonWx = JsonObject()

View File

@ -5,6 +5,9 @@ import android.content.Context
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import com.img.rabbit.utils.WechatRequests
import kotlinx.coroutines.launch
import com.g.gysdk.GYManager
import com.g.gysdk.GYResponse
import com.g.gysdk.GyCallBack
@ -18,7 +21,6 @@ import com.img.rabbit.pages.screen.mine.setting.BindScreenType
import com.img.rabbit.provider.api.ApiManager
import com.img.rabbit.provider.api.ResultVo
import com.img.rabbit.provider.storage.PreferenceUtil
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import kotlinx.serialization.json.Json
import okhttp3.RequestBody.Companion.toRequestBody
@ -27,6 +29,7 @@ class BindViewModel : BaseViewModel() {
private val TAG = "BindViewModel"
private val ONEKEY_TAG = "BindViewModel_OneKey"
var isBindWxAuthor = false
private var isLaunchingWechat = false
val bindScreenType = mutableStateOf(BindScreenType.BIND_NORMAL)
// 登录状态
val bindState = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
@ -59,6 +62,10 @@ class BindViewModel : BaseViewModel() {
fun oneKeyLoginForGeTuiSdk(activity: Activity, onShowOneKeyScreen:(Boolean)->Unit) {
if (!PreferenceUtil.getAgreement()) {
onShowOneKeyScreen(false)
return
}
// 初始化 SDK
GYManager.getInstance().init(GyConfig.with(activity.applicationContext).callBack(object : GyCallBack {
override fun onSuccess(response: GYResponse?) {
@ -206,15 +213,20 @@ class BindViewModel : BaseViewModel() {
//获取微信授权
private fun doWechatAuth(context: Context, wxApi: IWXAPI) {
if (!wxApi.isWXAppInstalled) {
CenterToast.show("您没有安装微信客户端,请先下载安装")
return
}
if (isLaunchingWechat) return
isLaunchingWechat = true
isBindWxAuthor = true
val req = SendAuth.Req()
req.scope = "snsapi_userinfo" // 只能填 snsapi_userinfo
req.state = context.packageName + Math.random() * 1000 + "_phone"
wxApi.sendReq(req)
val state = context.packageName + java.util.UUID.randomUUID().toString()
viewModelScope.launch {
try {
WechatRequests.authorize(wxApi, state)?.let { message ->
isBindWxAuthor = false
CenterToast.show(message)
}
} finally {
isLaunchingWechat = false
}
}
}
/**

View File

@ -2,8 +2,8 @@ package com.img.rabbit.viewmodel
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
@ -13,8 +13,12 @@ import com.img.rabbit.utils.DownUtils
import com.img.rabbit.utils.FileUtils
import com.img.rabbit.utils.ImageUtils
import com.img.rabbit.utils.PhotoCutter
import com.img.rabbit.utils.imageSampleSize
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody
@ -24,6 +28,9 @@ import kotlin.text.ifEmpty
class CutoutViewModel : BaseViewModel() {
companion object {
private const val MAX_IMAGE_DIMENSION = 2048
}
private val targetPath = FileUtils.instance?.cacheImageDir?.absolutePath?:""
private val targetFileName = "cutoutCache.png"
// 错误状态
@ -32,40 +39,51 @@ class CutoutViewModel : BaseViewModel() {
// 本地抠图
fun cutoutImageFromLocal(context: Context, uri: Uri, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
// 执行抠图操作
Thread {
viewModelScope.launch(Dispatchers.IO) {
try {
val originalBitmap = ImageUtils.getBitmapFromUri(context, uri)
originalBitmap?.let { bitmap ->
val bitmap = ImageUtils.getBitmapFromUri(context, uri, MAX_IMAGE_DIMENSION)
?: throw IOException("无法获取图片")
try {
PhotoCutter.cutPureHead(bitmap) { croppedBitmap ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
context.mainExecutor.execute {
onResult(true, croppedBitmap)
}
}
bitmap.recycle()
deliverResult(croppedBitmap, onResult)
}
} catch (e: Exception) {
bitmap.recycle()
throw e
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e("CutoutScreen", "抠图失败: ${e.message}")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
context.mainExecutor.execute {
onResult(false, null)
}
}
Log.e("CutoutViewModel", "本地抠图失败", e)
deliverResult(null, onResult)
}
}.start()
}
}
private fun deliverResult(bitmap: Bitmap?, onResult: (Boolean, Bitmap?) -> Unit) {
viewModelScope.launch(Dispatchers.Main) {
onResult(bitmap != null, bitmap)
}
}
//服务器抠图
fun cutoutImageFromService(context: Context, uri: Uri, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
mLaunch {
// Always report failure so the screen can fall back to local segmentation, even offline.
viewModelScope.launch(Dispatchers.IO) {
try {
// 1. 获取并压缩图片为 PNG (.png/jpg/jpeg 只支持这三种格式,当前选择使用PNG)
val bitmap = ImageUtils.getBitmapFromUri(context, uri) ?: throw IOException("无法获取图片")
val outputStream = java.io.ByteArrayOutputStream()
// PNG 是无损的,质量参数 100 即可
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
val compressedBytes = outputStream.toByteArray()
bitmap.recycle()
val bitmap = ImageUtils.getBitmapFromUri(context, uri, MAX_IMAGE_DIMENSION) ?: throw IOException("无法获取图片")
val compressedBytes = try {
java.io.ByteArrayOutputStream().use { outputStream ->
if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)) {
throw IOException("图片编码失败")
}
outputStream.toByteArray()
}
} finally {
bitmap.recycle()
}
// 2. MediaType 修改为 image/png
val requestFile = compressedBytes.toRequestBody("image/png".toMediaTypeOrNull(),0,compressedBytes.size)
@ -79,43 +97,56 @@ class CutoutViewModel : BaseViewModel() {
val response = ApiManager.serviceVo.cutoutImage(filePart)
if (response.status) {
Log.i("CutoutViewModel", "抠图成功: ${response.data}")
val resultUrl = Uri.decode(response.data.toString())
// 将 http 替换为 https
//val resultUrl = resultUrl.replace("http://", "https://")
Log.i("CutoutViewModel", "服务端抠图完成")
// Preserve percent-encoding in signed download URLs.
val resultUrl = response.data as? String ?: throw IOException("抠图结果地址无效")
saveUrlToCache(resultUrl, onResult)
} else {
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "抠图失败" })
onResult(false, null)
withContext(Dispatchers.Main) {
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "抠图失败" })
}
deliverResult(null, onResult)
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { // 捕获更广泛的异常
e.printStackTrace()
Log.e("CutoutViewModel", "服务请求异常: ${e.message}")
onResult(false, null)
Log.e("CutoutViewModel", "服务请求异常", e)
deliverResult(null, onResult)
}
}
}
private fun saveUrlToCache(url: String, onResult: (isSuccess: Boolean, croppedBitmap: Bitmap?) -> Unit) {
try {
val targetFile = File(targetPath,targetFileName)
if(targetFile.exists()){
targetFile.delete()
}
viewModelScope.launch(Dispatchers.IO) {
viewModelScope.launch(Dispatchers.IO) {
try {
require(url.toHttpUrlOrNull() != null) { "抠图结果地址无效" }
val targetFile = File(targetPath, targetFileName)
if (targetFile.exists()) {
targetFile.delete()
}
DownUtils.getInstance()
.initUrl(url, null)
.setFilePath(targetPath)
.setFileName(targetFileName)
.setDownCallBack(object : DownUtils.DownCallBack {
override fun success(file: File) {
// 3. 下载成功后,将文件解析为 Bitmap 并回调给 UI
val bitmap = android.graphics.BitmapFactory.decodeFile(file.absolutePath)
onResult(true, bitmap)
viewModelScope.launch(Dispatchers.IO) {
val bitmap = try {
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(file.absolutePath, options)
options.inSampleSize = imageSampleSize(options.outWidth, options.outHeight, MAX_IMAGE_DIMENSION)
options.inJustDecodeBounds = false
BitmapFactory.decodeFile(file.absolutePath, options)
} catch (e: Exception) {
Log.e("CutoutViewModel", "抠图结果读取失败", e)
null
}
deliverResult(bitmap, onResult)
}
}
override fun fail(str: String) {
onResult(false, null)
deliverResult(null, onResult)
}
override fun progress(position: Long) {
@ -127,14 +158,16 @@ class CutoutViewModel : BaseViewModel() {
}
override fun cancel() {
onResult(false, null)
deliverResult(null, onResult)
}
})
.down()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e("CutoutViewModel", "抠图结果下载失败", e)
deliverResult(null, onResult)
}
}catch (e: Exception){
e.printStackTrace()
onResult(false, null)
}
}
}

View File

@ -65,9 +65,9 @@ class FeedbackViewModel : BaseViewModel() {
fun uploadImage(context: Context, uri: Uri) {
mLaunch {
try {
val compressedUri = ImageUtils.imageCompressToUri(context, uri) ?: throw IOException("无法压缩图片")
val requestFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), compressedUri)
val filePart = MultipartBody.Part.createFormData("file", uri.lastPathSegment, requestFile)
val compressedUri:ByteArray = ImageUtils.imageCompressToUri(context, uri) ?: throw IOException("无法压缩图片")
val requestFile:RequestBody = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), compressedUri)
val filePart:MultipartBody.Part = MultipartBody.Part.createFormData("file", uri.lastPathSegment, requestFile)
val response = ApiManager.serviceVo.upload(filePart, "feedback")
if (response.status) {
val updateFile = FileManagerBean(response.data, uri)

View File

@ -97,6 +97,7 @@ class GeneralViewModel: BaseViewModel(){
}
private fun initWXApi(context: Context) {
if (!PreferenceUtil.getAgreement()) return
api = WXAPIFactory.createWXAPI(context, Constants.WxAppId, true)
api.registerApp(Constants.WxAppId)
@ -118,6 +119,10 @@ class GeneralViewModel: BaseViewModel(){
override fun onCleared() {
super.onCleared()
connectivityManager.unregisterNetworkCallback(networkCallback)
if (::receiver.isInitialized && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
HeadParamUtils.applicationContext?.unregisterReceiver(receiver)
}
if (::api.isInitialized) api.detach()
}
@OptIn(DelicateCoroutinesApi::class)

View File

@ -35,8 +35,13 @@ import com.img.rabbit.utils.GlobalEventBus
import com.img.rabbit.utils.LoginBindEvent
import com.img.rabbit.utils.MMKVUtils
import com.img.rabbit.utils.StringUtils
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.img.rabbit.utils.WechatRequests
import com.tencent.mm.opensdk.openapi.IWXAPI
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.resume
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@ -49,6 +54,7 @@ class LoginViewModel : BaseViewModel() {
private val ONEKEY_TAG = "OneKeyLoginViewModel"
var isLoginWxAuthor = false
private var isLaunchingWechat = false
val authInfoForAlipay: MutableState<String> = mutableStateOf("")
val loginScreenType = mutableStateOf(LoginScreenType.LOGIN_NORMAL)
@ -78,8 +84,12 @@ class LoginViewModel : BaseViewModel() {
val loginResult = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
// 用户配置获取结果
val userConfigResult = mutableStateOf<ResultVo<UserConfigEntity>?>(null)
// 用户信息获取结果
val userInfoResult = mutableStateOf<ResultVo<UserInfoEntity>?>(null)
// 保留最新配置供首页观察;userConfigResult 作为请求完成事件会被 Activity 清空。
private val _userConfig = mutableStateOf(PreferenceUtil.getUserConfig())
val userConfig: State<UserConfigEntity?> = _userConfig
// 页面直接观察用户数据,缓存只用于首次加载。
private val _userInfo = mutableStateOf(PreferenceUtil.getUserInfo())
val userInfo: State<UserInfoEntity?> = _userInfo
// 错误状态
val errorState = mutableStateOf<ErrorBean?>(null)
@ -108,6 +118,7 @@ class LoginViewModel : BaseViewModel() {
PreferenceUtil.saveXToken(response.data.token)
PreferenceUtil.setTimeDiff(response.data.nowtime.toLong() - System.currentTimeMillis() / 1000)
PreferenceUtil.saveUserConfig(response.data)
_userConfig.value = response.data
userConfigResult.value = response
if(isInitConfig){
@ -130,91 +141,55 @@ class LoginViewModel : BaseViewModel() {
}
}
fun oneKeyLoginForGeTuiSdk(activity: Activity, onShowOneKeyScreen:(Boolean)->Unit) {
// 初始化 SDK
GYManager.getInstance().init(GyConfig.with(activity.applicationContext).callBack(object : GyCallBack {
override fun onSuccess(response: GYResponse?) {
/** 登录页进入时优先预取本机号码;失败、超时或结果无效时交由页面回退。 */
suspend fun prepareOneKeyLogin(activity: Activity): Boolean = withContext(Dispatchers.Main.immediate) {
oneKeyPreLogin = null
isGYUIDValid.value = false
if (!PreferenceUtil.getAgreement()) return@withContext false
try {
withTimeoutOrNull(12_000L) {
val manager = GYManager.getInstance()
awaitGyResponse { callback ->
manager.init(GyConfig.with(activity.applicationContext).callBack(callback).build())
} ?: return@withTimeoutOrNull false
isGYUIDValid.value = true
Log.i(ONEKEY_TAG, "--->初始化: onSuccess")
//预登录(提高拉起速度,可选但推荐)
GYManager.getInstance().ePreLogin(/* timeout = */ 8000, /* gyCallBack = */ object : GyCallBack {
override fun onSuccess(response: GYResponse?) {
Log.i(ONEKEY_TAG, "--->预登录: onSuccess--->${response}")
val preLoginData = response?.msg
if (!preLoginData.isNullOrEmpty()) {
try {
val json = Json { ignoreUnknownKeys = true }
oneKeyPreLogin =
json.decodeFromString<OnekeyPreLogin>(preLoginData)
// 打印解析后的详细数据
Log.i(ONEKEY_TAG, "=== 预登录数据解析结果 ===")
Log.i(ONEKEY_TAG, "流程ID: ${oneKeyPreLogin?.process_id}")
Log.i(ONEKEY_TAG, "运营商类型: ${oneKeyPreLogin?.operatorType}")
Log.i(ONEKEY_TAG, "客户端类型: ${oneKeyPreLogin?.clienttype}")
Log.i(ONEKEY_TAG, "访问码: ${oneKeyPreLogin?.accessCode}")
Log.i(ONEKEY_TAG, "手机号: ${oneKeyPreLogin?.number}")
Log.i(ONEKEY_TAG, "过期时间: ${oneKeyPreLogin?.expiredTime}")
Log.i(ONEKEY_TAG, "错误码: ${oneKeyPreLogin?.errorCode}")
Log.i(ONEKEY_TAG, "错误描述: ${oneKeyPreLogin?.errorDesc}")
Log.i(ONEKEY_TAG, "耗时: ${oneKeyPreLogin?.costTime}ms")
Log.i(ONEKEY_TAG, "================================")
// 根据解析结果决定是否继续(根据errorCode判断)
if (oneKeyPreLogin?.errorCode == 0) {
oneKeyLoginValid(onShowOneKeyScreen = onShowOneKeyScreen)
} else {
onShowOneKeyScreen(false)
Log.e(ONEKEY_TAG, "预登录校验失败: ${oneKeyPreLogin?.errorDesc}")
}
} catch (e: Exception) {
Log.e(ONEKEY_TAG, "JSON解析失败: ${e.message}")
Log.e(ONEKEY_TAG, "原始数据: $preLoginData")
// 解析失败时继续执行原逻辑
onShowOneKeyScreen(false)
}
}
}
override fun onFailed(response: GYResponse?) {
onShowOneKeyScreen(false)
Log.i(ONEKEY_TAG, "--->预登录: onFailed--->${response}")
}
})
}
override fun onFailed(response: GYResponse?) {
onShowOneKeyScreen(false)
Log.i(ONEKEY_TAG, "--->初始化: onFailed--->${response}")
}
}).build())
}
private fun oneKeyLoginValid(onShowOneKeyScreen:(Boolean)->Unit) {
if (GYManager.getInstance().isPreLoginResultValid) {
//预登录有效,启动登录授权页
onShowOneKeyScreen(true)
Log.i(ONEKEY_TAG, "--->预登录校验有效A: onSuccess")
} else {
//考虑到是用户在等待,建议超时8s以上,至少设置5s以上
GYManager.getInstance().ePreLogin(5000, object : GyCallBack {
override fun onSuccess(response: GYResponse?) {
//预登录成功,启动登录授权页
onShowOneKeyScreen(true)
Log.i(ONEKEY_TAG, "--->预登录校验有效B: onSuccess--->${response}")
val response = awaitGyResponse { callback -> manager.ePreLogin(8000, callback) }
?: return@withTimeoutOrNull false
val data = response.msg?.takeIf { it.isNotBlank() }
?: return@withTimeoutOrNull false
val result = Json { ignoreUnknownKeys = true }.decodeFromString<OnekeyPreLogin>(data)
if (result.errorCode != 0 || result.number.isBlank() ||
!manager.isPreLoginResultValid || manager.preLoginResult == null) {
return@withTimeoutOrNull false
}
override fun onFailed(response: GYResponse?) {
//预登录失败,提示用户稍后重试
onShowOneKeyScreen(false)
Log.i(ONEKEY_TAG, "--->预登录校验有效B: onFailed--->${response}")
}
})
oneKeyPreLogin = result
true
} ?: false
} catch (e: CancellationException) {
// 页面退出时取消等待,不让迟到的 SDK 回调切换后续页面。
throw e
} catch (e: Exception) {
Log.w(ONEKEY_TAG, "一键登录准备失败,回退验证码登录", e)
false
}
}
private suspend fun awaitGyResponse(start: (GyCallBack) -> Unit): GYResponse? =
suspendCancellableCoroutine { continuation ->
val completed = AtomicBoolean(false)
fun complete(response: GYResponse?) {
if (completed.compareAndSet(false, true) && continuation.isActive) {
continuation.resume(response)
}
}
start(object : GyCallBack {
override fun onSuccess(response: GYResponse?) = complete(response)
override fun onFailed(response: GYResponse?) = complete(null)
})
}
fun requestOneKeyLogin(gyuid: String, token: String) {
// 调用 API 获取数据
val jsonOneKey = JsonObject()
@ -269,15 +244,20 @@ class LoginViewModel : BaseViewModel() {
fun authorWechat(context: Context, wxApi:IWXAPI) {
if (isPolicyAgreement.value) {
if (!wxApi.isWXAppInstalled) {
CenterToast.show("您没有安装微信客户端,请先下载安装")
return
}
if (isLaunchingWechat) return
isLaunchingWechat = true
isLoginWxAuthor = true
val req = SendAuth.Req()
req.scope = "snsapi_userinfo" // 只能填 snsapi_userinfo
req.state = context.packageName + Math.random() * 1000 + "_phone"
wxApi.sendReq(req)
val state = context.packageName + java.util.UUID.randomUUID().toString()
viewModelScope.launch {
try {
WechatRequests.authorize(wxApi, state)?.let { message ->
isLoginWxAuthor = false
CenterToast.show(message)
}
} finally {
isLaunchingWechat = false
}
}
}else{
CenterToast.show("请先同意用户协议和隐私政策")
}
@ -412,12 +392,18 @@ class LoginViewModel : BaseViewModel() {
}
fun requestUserInfo(){
PreferenceUtil.saveUserInfo(null)
val currentUserId = _userConfig.value?.user_id
if (!currentUserId.isNullOrBlank() && _userInfo.value?.user_id != currentUserId) {
PreferenceUtil.saveUserInfo(null)
_userInfo.value = null
}
mLaunch {
val response = ApiManager.serviceVo.userInfo()
// 切换账号后,忽略旧账号尚未完成的请求。
if (currentUserId != _userConfig.value?.user_id) return@mLaunch
if(response.status){
PreferenceUtil.saveUserInfo(response.data)
userInfoResult.value = response
_userInfo.value = response.data
}
}
}
@ -432,6 +418,7 @@ class LoginViewModel : BaseViewModel() {
val response = ApiManager.serviceVo.logout()
if (response.status) {
PreferenceUtil.clearLogin()
_userInfo.value = null
AppEventBus.post( LoginBindEvent.Login(userId = null, loginType = PreferenceUtil.getLoginType(), isLogin = false, data = null) )
} else {
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "退出登录失败" })

View File

@ -1,30 +1,43 @@
package com.img.rabbit.viewmodel
import com.img.rabbit.bean.response.ServiceWxLinkEntity
import android.util.Log
import androidx.lifecycle.viewModelScope
import com.img.rabbit.components.CenterToast
import com.img.rabbit.utils.WechatRequests
import com.img.rabbit.provider.api.ApiManager
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat
import com.tencent.mm.opensdk.openapi.IWXAPI
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MineViewModel : BaseViewModel() {
private val TAG = "MineViewModel"
private var isOpeningService = false
//请求客服连接
fun requestServiceLink(api: IWXAPI){
mLaunch {
val response = ApiManager.serviceVo.wxService()
if (response.status) {
contactClientService(response.data, api)
if (isOpeningService) return
isOpeningService = true
viewModelScope.launch {
try {
val message = withContext(Dispatchers.IO) {
if (!api.isWXAppInstalled) return@withContext "未安装微信客户端"
val response = ApiManager.serviceVo.wxService()
if (!response.status) {
return@withContext "暂时无法获取客服信息,请稍后重试"
}
val data = response.data
WechatRequests.customerService(api, data?.corpid, data?.address)
}
message?.let { CenterToast.show(it) }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e("MineViewModel", "打开微信客服失败", e)
CenterToast.show("打开客服失败,请检查网络后重试")
} finally {
isOpeningService = false
}
}
}
private fun contactClientService(data: ServiceWxLinkEntity, api: IWXAPI) {
if (api.wxAppSupportAPI >= Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
val req = WXOpenCustomerServiceChat.Req()
req.corpId = data.corpid
req.url = data.address
api.sendReq(req)
}
}
}

View File

@ -1,20 +1,31 @@
package com.img.rabbit.viewmodel
import android.util.Log
import androidx.lifecycle.viewModelScope
import com.img.rabbit.bean.request.ReportRequest
import com.img.rabbit.provider.api.ApiManager
import kotlinx.serialization.json.Json
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
class ReportViewModel : BaseViewModel() {
private val TAG = "ReportViewModel"
//请求客服连接
fun requestReport(requst: ReportRequest){
mLaunch {
val requstJson = Json.encodeToString(requst)
val response = ApiManager.serviceVo.report(requstJson.toRequestBody())
Log.i(TAG, "requestReport: ${response.data}")
fun requestReport(request: ReportRequest){
viewModelScope.launch(Dispatchers.IO) {
try {
val body = Json.encodeToString(request)
.toRequestBody("application/json; charset=utf-8".toMediaType())
ApiManager.serviceVo.report(body)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
// 上报失败不干扰下载重试和启动界面。
Log.w(TAG, "事件上报失败", e)
}
}
}
}

View File

@ -1,41 +1,61 @@
@file:OptIn(DelicateCoroutinesApi::class)
package com.img.rabbit.wxapi
import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.img.rabbit.utils.AppEventBus
import com.img.rabbit.utils.WXAuthEvent
import com.img.rabbit.utils.wechatAuthResult
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.umeng.socialize.weixin.view.WXCallbackActivity
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class WXEntryActivity : WXCallbackActivity() {
class WXEntryActivity : WechatConsentActivity() {
override val callbackClassName = "com.img.rabbit.wxapi.AuthorizedWXEntryActivity"
}
class AuthorizedWXEntryActivity : WXCallbackActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
try {
// The SDK dispatches handleIntent/onResp synchronously.
super.onCreate(savedInstanceState)
} catch (e: Exception) {
Log.e("WXEntryActivity", "微信回调处理失败", e)
AppEventBus.tryPost(WXAuthEvent.AuthFailure("微信授权失败,请重试"))
} finally {
// Invalid intents may not invoke onResp at all.
finish()
}
}
override fun onNewIntent(intent: Intent) {
try {
super.onNewIntent(intent)
} catch (e: Exception) {
Log.e("WXEntryActivity", "微信回调处理失败", e)
AppEventBus.tryPost(WXAuthEvent.AuthFailure("微信授权失败,请重试"))
} finally {
finish()
}
}
override fun onResp(resp: BaseResp?) {
if (resp?.type == ConstantsAPI.COMMAND_SENDAUTH) {
when (resp.errCode) {
BaseResp.ErrCode.ERR_OK -> {
val authResp = resp as SendAuth.Resp
//val wxState = WxBean(code = authResp.code,state = authResp.state)
GlobalScope.launch {
//GlobalStateManager(this@WXEntryActivity).storeGlobalWxAuthorization(authResp.code)
AppEventBus.post(
WXAuthEvent.AuthResult(
code = authResp.code,
authType = 0
)
)
finish()
}
try {
if (resp?.type == ConstantsAPI.COMMAND_SENDAUTH) {
val event = wechatAuthResult(resp.errCode, (resp as? SendAuth.Resp)?.code)
if (!AppEventBus.tryPost(event)) {
Log.w("WXEntryActivity", "微信授权结果未能投递")
}
else -> {}
} else {
super.onResp(resp)
}
} catch (e: Exception) {
Log.e("WXEntryActivity", "微信授权回调异常", e)
AppEventBus.tryPost(WXAuthEvent.AuthFailure("微信授权失败,请重试"))
} finally {
finish()
}
}
}

View File

@ -10,7 +10,11 @@ import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import io.dcloud.feature.payment.weixin.AbsWXPayCallbackActivity
class WXPayEntryActivity : AbsWXPayCallbackActivity() {
class WXPayEntryActivity : WechatConsentActivity() {
override val callbackClassName = "com.img.rabbit.wxapi.AuthorizedWXPayEntryActivity"
}
class AuthorizedWXPayEntryActivity : AbsWXPayCallbackActivity() {
//val scope = CoroutineScope(Dispatchers.Main)
private lateinit var generalViewModel: GeneralViewModel
override fun onCreate(savedInstanceState: Bundle?) {

View File

@ -0,0 +1,28 @@
package com.img.rabbit.wxapi
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.img.rabbit.provider.storage.PrivacyConsentStore
/** 外部回调先经过原生 Activity,避免 SDK 父类在未授权时执行 onCreate。 */
abstract class WechatConsentActivity : Activity() {
protected abstract val callbackClassName: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dispatch(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
dispatch(intent)
}
private fun dispatch(callback: Intent) {
if (PrivacyConsentStore.isAccepted()) {
startActivity(Intent(callback).setClassName(this, callbackClassName))
}
finish()
}
}

View File

@ -6,6 +6,7 @@
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<exclude domain="sharedpref" path="privacy_consent.xml" />
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>

View File

@ -5,11 +5,15 @@
-->
<data-extraction-rules>
<cloud-backup>
<exclude domain="sharedpref" path="privacy_consent.xml" />
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<device-transfer>
<exclude domain="sharedpref" path="privacy_consent.xml" />
</device-transfer>
<!--
<device-transfer>
<include .../>

View File

@ -1,7 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">enrichgw.10010.com</domain>
<domain includeSubdomains="true">aliyuncs.com</domain>
</domain-config>
<base-config cleartextTrafficPermitted="true" />
<!-- <domain-config cleartextTrafficPermitted="true">-->
<!-- <domain includeSubdomains="true">enrichgw.10010.com</domain>-->
<!-- <domain includeSubdomains="true">aliyuncs.com</domain>-->
<!-- <domain includeSubdomains="true">home.batiao8.com</domain>-->
<!-- </domain-config>-->
</network-security-config>

View File

@ -1,5 +1,23 @@
pluginManagement {
repositories {
maven {
name = "batiao"
url = uri("http://proxy.local:7777/repository/maven-releases/")
isAllowInsecureProtocol = true
content { includeGroup("com.batiao") }
credentials {
val local = java.util.Properties().apply {
val propertiesFile = file("local.properties")
if (propertiesFile.exists()) propertiesFile.inputStream().use { load(it) }
}
username = providers.gradleProperty("BATIAO_MAVEN_USERNAME")
.orElse(providers.environmentVariable("BATIAO_MAVEN_USERNAME"))
.orNull ?: local.getProperty("BATIAO_MAVEN_USERNAME")
password = providers.gradleProperty("BATIAO_MAVEN_PASSWORD")
.orElse(providers.environmentVariable("BATIAO_MAVEN_PASSWORD"))
.orNull ?: local.getProperty("BATIAO_MAVEN_PASSWORD")
}
}
google {
content {
includeGroupByRegex("com\\.android.*")
@ -14,11 +32,36 @@ pluginManagement {
mavenCentral()
gradlePluginPortal()
}
resolutionStrategy {
eachPlugin {
if (requested.id.id == "com.batiao.batiaosdkbuilder") {
useModule("com.batiao:batiao-sdk-builder:${requested.version}")
}
}
}
}
@Suppress("UnstableApiUsage")
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
maven {
name = "batiao"
url = uri("http://proxy.local:7777/repository/maven-releases/")
isAllowInsecureProtocol = true
content { includeGroup("com.batiao") }
credentials {
val local = java.util.Properties().apply {
val propertiesFile = file("local.properties")
if (propertiesFile.exists()) propertiesFile.inputStream().use { load(it) }
}
username = providers.gradleProperty("BATIAO_MAVEN_USERNAME")
.orElse(providers.environmentVariable("BATIAO_MAVEN_USERNAME"))
.orNull ?: local.getProperty("BATIAO_MAVEN_USERNAME")
password = providers.gradleProperty("BATIAO_MAVEN_PASSWORD")
.orElse(providers.environmentVariable("BATIAO_MAVEN_PASSWORD"))
.orNull ?: local.getProperty("BATIAO_MAVEN_PASSWORD")
}
}
google()
mavenCentral()
flatDir {