Skip to content

Commit

Permalink
chore: refine code
Browse files Browse the repository at this point in the history
  • Loading branch information
klxiaoniu committed Sep 17, 2024
1 parent 5ad7393 commit 2376e57
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 57 deletions.
2 changes: 1 addition & 1 deletion settings.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
rootProject.name = "FuTalk"
rootProject.name = "FzuHelper"

include(":androidApp")
include(":shared")
Expand Down
2 changes: 1 addition & 1 deletion shared/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import org.jetbrains.kotlin.gradle.dsl.KotlinVersion
val appyx_version = "2.0.0-alpha09"
val koin_version = "3.5.0"
val koin_compose_version = "1.1.0"
val ktor_version = "2.3.5"
val ktor_version = "2.3.12"
val serialization_version = "1.6.2"
val markdown_version = "0.10.0"
val sqlDelightVersion = "2.0.1"
Expand Down
34 changes: 17 additions & 17 deletions shared/src/commonMain/kotlin/di/koinAction.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ import kotlinx.datetime.plus
import kotlinx.serialization.json.Json
import org.koin.core.module.Module
import org.koin.dsl.module
import repository.ClassScheduleRepository
import repository.EmptyHouseRepository
import repository.FeedbackRepository
import repository.JwchRepository
import repository.LoginRepository
import repository.ManageRepository
import repository.ModifierInformationRepository
Expand Down Expand Up @@ -79,35 +79,35 @@ import kotlin.time.toDuration
/**
* 对教务处client的相关处理
*
* @property classScheduleRepository ClassScheduleRepository 有关
* @property jwchRepository JwchRepository 有关
* @property kVaultAction UndergraduateKValueAction
* @property toast Toast 用于提示的toast
* @property client HttpClient? 用于储存可用的教务处client
* @property userSchoolId String? 储存可用的学生id
* @property upDataTime Instant client更新时间
* @property updateTime Instant client更新时间
* @constructor
*/
class ClassSchedule(
private val classScheduleRepository: ClassScheduleRepository,
class Jwch(
private val jwchRepository: JwchRepository,
private val kVaultAction: UndergraduateKValueAction,
val toast: Toast,
) {
private var client: HttpClient? = null
private var userSchoolId: String? = null
private var upDataTime = Clock.System.now().plus(-50, DateTimeUnit.MINUTE)
private var updateTime = Clock.System.now().plus(-50, DateTimeUnit.MINUTE)

@OptIn(ExperimentalCoroutinesApi::class)
/** 获取可用于教务处请求的 client和学生id 如果失败则会返回Pair(null,null) */
suspend fun getClassScheduleClient(): Pair<HttpClient?, String?> {
if (client == null || Clock.System.now() - upDataTime > 20.toDuration(DurationUnit.MINUTES)) {
suspend fun getJwchClient(): Pair<HttpClient?, String?> {
if (client == null || Clock.System.now() - updateTime > 20.toDuration(DurationUnit.MINUTES)) {
val newClient =
HttpClient() {
HttpClient {
install(ContentNegotiation) { json() }
install(HttpCookies) {}
install(HttpRedirect) { checkHttpMethod = false }
configureForPlatform()
}
classScheduleRepository.apply {
jwchRepository.apply {
val userName = kVaultAction.schoolUserName.currentValue.value
val password = kVaultAction.schoolPassword.currentValue.value
if (userName == null || password == null) {
Expand Down Expand Up @@ -138,7 +138,7 @@ class ClassSchedule(
val url = it.call.request.url.toString()
client = newClient
userSchoolId = url.split("id=")[1].split("&")[0]
upDateClientTime()
updateClientTime()
}
.catch {
client = null
Expand All @@ -152,9 +152,9 @@ class ClassSchedule(
return Pair(client, userSchoolId)
}

/** Up date client time 更新client更新时间 */
private fun upDateClientTime() {
upDataTime = Clock.System.now()
/** Update client time 更新client更新时间 */
private fun updateClientTime() {
updateTime = Clock.System.now()
}

/**
Expand All @@ -179,7 +179,7 @@ class ClassSchedule(
install(HttpRedirect) { checkHttpMethod = false }
configureForPlatform()
}
classScheduleRepository.apply {
jwchRepository.apply {
var id = ""
var num = ""
newClient.apply {
Expand Down Expand Up @@ -322,7 +322,7 @@ fun appModule(rootAction: RootAction, systemAction: SystemAction, navigator: Nav
single { rootAction }
single { ThemeKValueAction(get()) }
single { UndergraduateKValueAction(get()) }
single { ClassSchedule(get(), get(), get()) }
single { Jwch(get(), get(), get()) }
single { systemAction }
single { navigator }
single {
Expand Down Expand Up @@ -418,7 +418,7 @@ fun Module.repositoryList() {
single { ManageRepository(get()) }
single { RibbonRepository(get()) }
single { EmptyHouseRepository(get()) }
single { ClassScheduleRepository() }
single { JwchRepository() }
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import util.math.parseInt
*
* @property charSet Charset 设置教务处常用的编码方式
*/
class ClassScheduleRepository {
class JwchRepository {
private val charSet = Charset.forName("GB2312")

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import configureForPlatform
import dao.Dao
import dao.UndergraduateKValueAction
import dev.icerock.moko.mvvm.viewmodel.ViewModel
import di.ClassSchedule
import di.Jwch
import di.ShareClient
import di.database
import io.ktor.client.HttpClient
Expand All @@ -29,7 +29,7 @@ import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.retry
import kotlinx.coroutines.flow.stateIn
import repository.ClassScheduleRepository
import repository.JwchRepository
import repository.WeekData
import util.flow.actionWithLabel
import util.flow.catchWithMassage
Expand All @@ -47,8 +47,8 @@ import util.network.resetWithoutLog
* 课程功能的相关功能
*
* @property kValueAction UndergraduateKValueAction
* @property classScheduleRepository ClassScheduleRepository
* @property classSchedule ClassSchedule
* @property jwchRepository JwchRepository
* @property jwch Jwch
* @property dao Dao
* @property shareClient ShareClient
* @property classScheduleUiState ClassScheduleUiState 用于渲染的开始年月日
Expand All @@ -68,8 +68,8 @@ import util.network.resetWithoutLog
@OptIn(ExperimentalCoroutinesApi::class)
class ClassScheduleViewModel(
private val kValueAction: UndergraduateKValueAction,
private val classScheduleRepository: ClassScheduleRepository,
private val classSchedule: ClassSchedule,
private val jwchRepository: JwchRepository,
private val jwch: Jwch,
private val dao: Dao,
private val shareClient: ShareClient,
) : ViewModel() {
Expand Down Expand Up @@ -164,7 +164,7 @@ class ClassScheduleViewModel(
/** 初始化会更新更新当前学期 */
init {
viewModelScope.launchInDefault {
classScheduleRepository.apply {
jwchRepository.apply {
shareClient.client.apply {
getWeek()
.map {
Expand Down Expand Up @@ -213,8 +213,8 @@ class ClassScheduleViewModel(
fun refreshClassData() {
viewModelScope.launchInDefault {
refreshState.logicIfNotLoading {
classScheduleRepository.apply {
val studentData = classSchedule.getClassScheduleClient()
jwchRepository.apply {
val studentData = jwch.getJwchClient()
val client =
studentData.first
?: run {
Expand Down Expand Up @@ -279,7 +279,7 @@ class ClassScheduleViewModel(
*/
@OptIn(ExperimentalCoroutinesApi::class)
private suspend fun HttpClient.getCourseFromNetwork(id: String) {
with(classScheduleRepository) {
with(jwchRepository) {
with(this@getCourseFromNetwork) {
getCourseStateHTML(id)
.catchWithMassage { label, throwable ->
Expand Down Expand Up @@ -340,7 +340,7 @@ class ClassScheduleViewModel(
.map { it.yearOptionsName }
.forEach { yearOptionsName ->
yearOptionsName.let { xq ->
with(classScheduleRepository) {
with(jwchRepository) {
this@getOtherCourseFromNetwork.getCourseStateHTML(id)
.flatMapConcat { stateHtml -> getCourses(xq, stateHtml) }
.flatMapConcat {
Expand All @@ -364,7 +364,7 @@ class ClassScheduleViewModel(
viewModelScope.launchInDefault {
refreshExamState.logicIfNotLoading {
val xq = kValueAction.currentXq.currentValue.value
val studentData = classSchedule.getClassScheduleClient()
val studentData = jwch.getJwchClient()
val client =
studentData.first
?: run {
Expand All @@ -384,7 +384,7 @@ class ClassScheduleViewModel(
return@logicIfNotLoading
}
with(client) {
with(classScheduleRepository) {
with(jwchRepository) {
getExamStateHTML(id)
.map {
return@map (parseExamsHTML(it))
Expand All @@ -407,7 +407,7 @@ class ClassScheduleViewModel(
fun changeCurrentYear(newValue: String) {
viewModelScope.launchInDefault {
selectYear.emit(newValue)
classScheduleRepository.apply {
jwchRepository.apply {
val client =
HttpClient() {
install(ContentNegotiation) { json() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package ui.compose.Setting

import dao.UndergraduateKValueAction
import dev.icerock.moko.mvvm.viewmodel.ViewModel
import di.ClassSchedule
import di.Jwch
import kotlinx.coroutines.flow.MutableStateFlow
import util.flow.launchInDefault
import util.flow.launchInIO
Expand All @@ -16,13 +16,13 @@ import util.network.resetWithoutLog
* 设置的逻辑
*
* @property kValueAction UndergraduateKValueAction
* @property classSchedule ClassSchedule
* @property jwch Jwch
* @property signInStatus MutableStateFlow<NetworkResult<String>>
* @constructor
*/
class SettingViewModel(
val kValueAction: UndergraduateKValueAction,
val classSchedule: ClassSchedule,
val jwch: Jwch,
) : ViewModel() {
val signInStatus = MutableStateFlow<NetworkResult<String>>(NetworkResult.UnSend())

Expand All @@ -35,16 +35,16 @@ class SettingViewModel(
fun verifyTheAccount(userName: String, password: String, loginType: Int) {
viewModelScope.launchInDefault {
signInStatus.logicIfNotLoading {
classSchedule.verifyYourAccount(
jwch.verifyYourAccount(
userName,
password,
failAction = {
when (it) {
ClassSchedule.VerifyYourAccountError.ValidationFailed -> {
Jwch.VerifyYourAccountError.ValidationFailed -> {
signInStatus.resetWithoutLog(networkError("验证失败,请稍后重试", "验证失败"))
}

ClassSchedule.VerifyYourAccountError.LoginFailed -> {
Jwch.VerifyYourAccountError.LoginFailed -> {
signInStatus.resetWithoutLog(networkError("登录失败,请稍后重试", ""))
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import com.multiplatform.webview.web.WebView
import com.multiplatform.webview.web.rememberWebViewNavigator
import com.multiplatform.webview.web.rememberWebViewState
import config.JWCH_BASE_URL
import kotlin.jvm.Transient
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import org.koin.compose.koinInject
Expand All @@ -26,6 +25,7 @@ import util.compose.ParentPaddingControl
import util.compose.defaultSelfPaddingControl
import util.compose.parentSystemControl
import util.network.CollectWithContentInBox
import kotlin.jvm.Transient

class UndergraduateWebViewVoyagerScreen(
val url: String,
Expand All @@ -48,20 +48,13 @@ fun OwnWebViewScreen(start: String, parentPaddingControl: ParentPaddingControl)
val viewModel: UndergraduateWebViewViewModel = koinInject()
val clientState = viewModel.clientState.collectAsState()
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) { viewModel.getClassScheduleClient() }
LaunchedEffect(Unit) { viewModel.getJwchClient() }
var url = start
val isLoadingCookie = remember { mutableStateOf(true) }
clientState.CollectWithContentInBox(
success = {
url = start.replace("{id}", it.id)
val state =
rememberWebViewState(
url,
mapOf(
"User-Agent" to
"Mozilla/5.0 (Linux; Android 9; ELE-AL00 Build/HUAWEIELE-AL0001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.83 Mobile Safari/537.36 T7/11.15 baiduboxapp/11.15.5.10 (Baidu; P1 9)"
),
)
val state = rememberWebViewState(url)
LaunchedEffect(state) {
snapshotFlow { state.loadingState }
.filter { it is LoadingState.Initializing }
Expand Down Expand Up @@ -94,7 +87,7 @@ fun OwnWebViewScreen(start: String, parentPaddingControl: ParentPaddingControl)
error = {
ErrorText(
text = "加载失败",
onClick = { scope.launch { viewModel.getClassScheduleClient() } },
onClick = { scope.launch { viewModel.getJwchClient() } },
boxModifier = Modifier.fillMaxSize(),
)
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package ui.compose.UndergraduateWebView
import config.JWCH_BASE_URL
import dev.icerock.moko.mvvm.flow.CMutableStateFlow
import dev.icerock.moko.mvvm.viewmodel.ViewModel
import di.ClassSchedule
import di.Jwch
import io.ktor.client.plugins.cookies.cookies
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand All @@ -13,25 +13,25 @@ import util.network.NetworkResult
import util.network.logicIfNotLoading
import util.network.resetWithLog

class UndergraduateWebViewViewModel(val classSchedule: ClassSchedule) : ViewModel() {
class UndergraduateWebViewViewModel(val jwch: Jwch) : ViewModel() {
private val _clientState =
CMutableStateFlow(MutableStateFlow<NetworkResult<IdWithCookie>>(NetworkResult.UnSend()))
val clientState = _clientState.asStateFlow()

fun getClassScheduleClient() {
fun getJwchClient() {
viewModelScope.launchInIO {
_clientState.logicIfNotLoading {
val client = classSchedule.getClassScheduleClient()
val client = jwch.getJwchClient()
if (client.first == null || client.second == null) {
_clientState.resetWithLog(
"getClassScheduleClient",
"getJwchClient",
NetworkResult.Error(Throwable("获取教务处信息失败"), Throwable()),
)
} else {
val cookie = client.first!!.cookies(JWCH_BASE_URL)
val id = client.second!!
_clientState.resetWithLog(
"getClassScheduleClient",
"getJwchClient",
NetworkResult.Success(
IdWithCookie(id, cookie.map { cookieItem -> CookieUtil.transform(cookieItem) })
),
Expand Down

0 comments on commit 2376e57

Please sign in to comment.