Commit 5a00e8be authored by chenhuaqing's avatar chenhuaqing

code refactor for AuthManager

parent 0cd2a157
......@@ -4,9 +4,7 @@ import android.os.Build
import com.github.shadowsocks.Core
import com.github.shadowsocks.database.Profile
import com.github.shadowsocks.database.ProfileManager
import com.github.shadowsocks.http.FreshToken
import com.github.shadowsocks.http.HttpConfig
import com.github.shadowsocks.http.LineConfig
import com.github.shadowsocks.http.*
import com.google.gson.Gson
import com.google.gson.JsonStreamParser
import com.google.gson.reflect.TypeToken
......@@ -18,7 +16,6 @@ import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import timber.log.Timber
import java.io.File
import java.io.IOException
......@@ -78,7 +75,7 @@ object AuthManager {
MMKV.defaultMMKV().putLong("ACC_TIME", acc_time)
}
var Last_ACC_TIme:Long
var Last_ACC_TIme: Long
get() = MMKV.defaultMMKV().decodeLong("LAST_ACC_TIME", 0L)
set(last_acc_time) {
MMKV.defaultMMKV().putLong("LAST_ACC_TIME", last_acc_time)
......@@ -88,17 +85,19 @@ object AuthManager {
suspend fun initAuthProfile(profile: Profile) {
withContext(Dispatchers.IO) {
getLineConfig()?.let {
if (it.code != 200) {
return@withContext
}else if(it.code==1001){//vip过期
}
profile.host = it.data.host
profile.token = it.data.token
profile.remotePort = it.data.port
val gameId: Int = gameId?.toInt() ?: throw AuthException("游戏不存在")
val lineConfigResult = postSync<LineConfig>("/api/acc/line", LineConfigReq(gameId, area))
if (lineConfigResult.isSuccessful()) {
val lineConfig = lineConfigResult.unwrapData()
profile.host = lineConfig.host
profile.token = lineConfig.token
profile.remotePort = lineConfig.port
Timber.d("start vpn with games: ${profile.individual}, profileId: ${profile.id}, route: ${profile.route}")
ProfileManager.updateProfile(profile)
} else if (lineConfigResult.code == 1001) {
throw AuthException(lineConfigResult.error!!)
} else {
// TODO: error handling
}
}
}
......@@ -117,12 +116,17 @@ object AuthManager {
if (data.state == BaseService.State.Connected) {
data.proxy?.let { proxyInstance ->
getToken(proxyInstance.profile.token ?: "")?.let {
if (it.code == 200) {
proxyInstance.profile.token = it.data.token
configJson.addProperty("token", it.data.token)
configFile.writeText(configJson.toString())
}
val refreshTokenResult = postSync<RefreshTokenRes>(
"/api/acc/line/refresh",
RefreshTokenReq(proxyInstance.profile.token ?: "")
)
Timber.d("refreshTokenResult: $refreshTokenResult")
if (refreshTokenResult.isSuccessful()) {
proxyInstance.profile.token = refreshTokenResult.unwrapData().token
configJson.addProperty("token", proxyInstance.profile.token)
configFile.writeText(configJson.toString())
} else if (refreshTokenResult.code == 1001) {
throw AuthException(refreshTokenResult.error!!)
}
}
}
......@@ -130,51 +134,31 @@ object AuthManager {
}, 1, 1, TimeUnit.MINUTES)
}
fun getToken(token: String): FreshToken? {
val map = mapOf(Pair("token", token))
return postSync<FreshToken>("/api/acc/line/refresh", map)
}
val jsonType get() = "application/json; charset=utf-8".toMediaTypeOrNull()
private fun getLineConfig(
): LineConfig? {
val map = mutableMapOf<String, String>()
area?.let { map.put("area", it) }
gameId?.let {
map.put("gameId", it)
}
return postSync<LineConfig>("/api/acc/line", map)
}
inline fun <reified T> postSync(
url: String,
map: Map<String, String>
): T? {
params: Any
): ApiResult<T> {
val body: RequestBody = gson.toJson(params).toString().toRequestBody(jsonType)
val request = Request.Builder()
.url(HttpConfig.baseUrl + url)
.post(body)
authToken?.let {
request.addHeader("Authorization", it)
}
val call = okHttpClient.newCall(request.build())
val resultType = object : TypeToken<ApiResult<T>>() {}.type
try {
val body: RequestBody = gson.toJson(map).toString().toRequestBody(jsonType)
val request = Request.Builder()
.url(HttpConfig.baseUrl + url)
.post(body)
authToken?.let {
request.addHeader("Authorization", it)
}
val call = okHttpClient.newCall(request.build())
val response: Response = call.execute()
if (response.isSuccessful) {
call.execute().use { response ->
val string = response.body?.string()
println(string)
val type = object : TypeToken<T>() {}.type
return gson.fromJson(string, type)
return gson.fromJson(string, resultType)
}
return null
} catch (e: java.lang.Exception) {
println(e)
} catch (e: IOException) {
Timber.e(e, "AuthManager 调用接口错误")
return ApiResult(ApiError.NetworkError)
}
return null
}
private fun initSSLSocketFactory(): SSLSocketFactory {
......
package com.github.shadowsocks.http
data class FreshToken(
val code: Int,
val error:String?,
val `data`: Token
data class RefreshTokenReq(
val token: String
)
data class Token(
val token: String?
)
\ No newline at end of file
data class RefreshTokenRes(
val token: String
)
package com.github.shadowsocks.http
data class LineConfig(
val code: Int,
val `data`: Data
//data class LineConfig(
// val code: Int,
// val `data`: Data
//)
data class LineConfigReq(
val gameId: Int,
val area: String?,
)
data class Data(
data class LineConfig(
val host: String,
val method: String,
val port: Int,
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment