You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
csamsclient/foreground/src/main/java/com/gyf/csams/InitViewModel.kt

76 lines
2.6 KiB

package com.gyf.csams
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gyf.csams.util.*
import com.orhanobut.logger.Logger
import kotlinx.coroutines.launch
data class TokenVo(val token: String, val studentId: String)
class InitViewModel : ViewModel() {
/**
* 服务器网络状态是否正常,true=正常,false=不正常
*/
private val _isNetWorkWorking = MutableLiveData<Boolean>()
val isNetWorkWorking: LiveData<Boolean> = _isNetWorkWorking
/**
* token
*/
private val _token = MutableLiveData<Boolean>()
val token: LiveData<Boolean> = _token
fun checkServer() {
Logger.i("测试连接到服务端")
_isNetWorkWorking.postValue(true)
}
/**
* 查询本地是否有且只有一个用户token,如果有则自动登录
*/
fun hasOnlyUserToken(context: Context) {
viewModelScope.launch {
val db = AppDatabase.getInstance(context)
val tokenList = db?.tokenDao()?.queryAll()
if (tokenList != null && tokenList.size == 1) {
val currentToken: Token = tokenList[0]
val url = Api.buildUrl(AccountApi.LoginToken)
val action = "校验token"
Logger.i("${action}api=$url")
HttpClient.post(
url,
SimpleCallback<Boolean>(
action = action,
onSuccess = {
_token.postValue(it.body)
Logger.i("token校验结果:${it.body}")
},
onFail = { TODO("token校验失败") },
type = object : TypeToken<ApiResponse<Boolean>>() {}.type
),
jsonBody = Gson().toJson(
TokenVo(
token = currentToken.token,
studentId = currentToken.studentId
)
)
)
} else if (tokenList != null && tokenList.size > 1) {
//TODO 实现切换历史登录帐号
Logger.i("token数量大于一,需要手动登录")
_token.postValue(false)
} else {
Logger.i("本地没有任何token,跳转到登录界面")
_token.postValue(false)
}
}
}
}