feat: Login
This commit is contained in:
+82
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Created by sweetbread on 21.02.2025, 12:09
|
||||
* Copyright (c) 2025. All rights reserved.
|
||||
* Last modified 21.02.2025, 12:01
|
||||
*/
|
||||
|
||||
package ru.risdeveau.pixeldragon.api
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.util.Log
|
||||
import io.ktor.client.request.bearerAuth
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.client.statement.bodyAsText
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.contentType
|
||||
import org.json.JSONObject
|
||||
import ru.risdeveau.pixeldragon.accountData
|
||||
import ru.risdeveau.pixeldragon.client
|
||||
import ru.risdeveau.pixeldragon.initCheck
|
||||
import ru.risdeveau.pixeldragon.token
|
||||
import ru.risdeveau.pixeldragon.urlBase
|
||||
import splitties.init.appCtx
|
||||
|
||||
data class Me (val userId: String, val deviceId: String)
|
||||
|
||||
/**
|
||||
* This func is to validate the token
|
||||
*/
|
||||
suspend fun getMe(): Me? {
|
||||
val r = client.get("$urlBase/account/whoami") { bearerAuth(token) }
|
||||
if (r.status != HttpStatusCode.OK) {
|
||||
Log.e("getMe", r.bodyAsText())
|
||||
return null
|
||||
}
|
||||
|
||||
val json = JSONObject(r.bodyAsText())
|
||||
return Me(json.getString("user_id"), json.getString("device_id"))
|
||||
}
|
||||
|
||||
@SuppressLint("ApplySharedPref")
|
||||
suspend fun login(homeserver: String, login: String, pass: String): Boolean {
|
||||
val pinfo = appCtx.packageManager.getPackageInfo(appCtx.packageName, 0);
|
||||
|
||||
val pattern = """
|
||||
{
|
||||
"type": "m.login.password",
|
||||
"identifier": {
|
||||
"type": "m.id.user"
|
||||
},
|
||||
"initial_device_display_name": "PixelDragon Android v${pinfo.versionName}"
|
||||
}
|
||||
""".trimIndent()
|
||||
val json = JSONObject(pattern)
|
||||
json.getJSONObject("identifier").put("user", login)
|
||||
json.put("password", pass)
|
||||
|
||||
val r = try {
|
||||
client.post("https://$homeserver/_matrix/client/v3/login") {
|
||||
setBody(json.toString())
|
||||
contentType(ContentType.Application.Json)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("login", e.toString())
|
||||
return false
|
||||
}
|
||||
|
||||
if (r.status != HttpStatusCode.OK) {
|
||||
Log.e("login", r.bodyAsText())
|
||||
return false // TODO: Inform a user of error code
|
||||
}
|
||||
|
||||
val res = JSONObject(r.bodyAsText())
|
||||
val editor = accountData.edit()
|
||||
editor.putString("token", res.getString("access_token"))
|
||||
editor.putString("homeserver", res.getString("home_server"))
|
||||
editor.commit()
|
||||
|
||||
return initCheck()
|
||||
}
|
||||
Reference in New Issue
Block a user