network request factory working

This commit is contained in:
Odweta
2024-12-22 13:10:48 +01:00
parent e5d807b6d8
commit 99fe3a0243
4 changed files with 124 additions and 142 deletions
@@ -202,7 +202,6 @@ class Global {
var timetable: List<Day> = listOf() var timetable: List<Day> = listOf()
var lectureNotes: HashMap<Int, LectureNote> = hashMapOf() var lectureNotes: HashMap<Int, LectureNote> = hashMapOf()
var subjectNameMap: HashMap<String, String> = hashMapOf() var subjectNameMap: HashMap<String, String> = hashMapOf()
var client: OkHttpClient = OkHttpClient()
var username: String = "" var username: String = ""
var password: String = "" var password: String = ""
@@ -28,9 +28,9 @@ fun remoteLoad(ctx: Context) {
if (!global.isAPISetUp) { if (!global.isAPISetUp) {
CoroutineScope(Dispatchers.IO) CoroutineScope(Dispatchers.IO)
.launch { .launch {
Network.setupAPI() setupAPI()
global.timetableJSON = Network.getTimeTable() global.timetableJSON = networkRequestFactory.perform(NetworkRequestType.Timetable)
global.marksJSON = Network.getMarks() global.marksJSON = networkRequestFactory.perform(NetworkRequestType.Marks)
launchContinue( launchContinue(
ctx, ctx,
@@ -42,8 +42,8 @@ fun remoteLoad(ctx: Context) {
CoroutineScope(Dispatchers.IO).launch { CoroutineScope(Dispatchers.IO).launch {
launchContinue( launchContinue(
ctx, ctx,
Network.getTimeTable(), networkRequestFactory.perform(NetworkRequestType.Timetable),
Network.getMarks() networkRequestFactory.perform(NetworkRequestType.Marks)
) )
} }
} }
@@ -51,8 +51,8 @@ fun remoteLoad(ctx: Context) {
fun localLoad(ctx: Context) { fun localLoad(ctx: Context) {
global.userData = JSONObject(Util.fileToString(global.filePaths.userData)) global.userData = JSONObject(Util.fileToString(global.filePaths.userData))
global.studentId = Network.getStudentId() global.studentId = Parsing.getStudentId()
global.studentClass = Network.getStudentClass() global.studentClass = Parsing.getStudentClass()
global.apiEndPoints.marks = "${global.apiEndPoints.apiBase}/v1/students/${global.studentId}/marks/list" global.apiEndPoints.marks = "${global.apiEndPoints.apiBase}/v1/students/${global.studentId}/marks/list"
val localTimetable = JSONObject(Util.fileToString(global.filePaths.timetable)) val localTimetable = JSONObject(Util.fileToString(global.filePaths.timetable))
val localMarks = JSONObject(Util.fileToString(global.filePaths.marks)) val localMarks = JSONObject(Util.fileToString(global.filePaths.marks))
@@ -1,147 +1,106 @@
package com.odweta.solon package com.odweta.solon
import android.util.Log
import okhttp3.FormBody import okhttp3.FormBody
import okhttp3.Headers
import okhttp3.Headers.Companion.headersOf
import okhttp3.OkHttpClient
import okhttp3.Request import okhttp3.Request
import org.json.JSONException import okhttp3.Response
import org.json.JSONObject import org.json.JSONObject
import java.io.IOException
class Network { fun setupAPI() {
companion object { global.token = "NETWORK_UNREACHABLE"
fun getToken(): String { val token = networkRequestFactory.perform(NetworkRequestType.Token).getString("token")
val request = Request.Builder() if (""""error": """ !in token) {
.url(global.apiEndPoints.token) global.token = token
.header("Content-Type", "application/x-www-form-urlencoded") }
.post( if (global.token == "NETWORK_UNREACHABLE" || """"error": """ in global.token) {
FormBody.Builder() global.userData = JSONObject()
.add("grant_type", "password") global.studentId = ""
.add("username", global.username) return
.add("password", global.password) }
.add("client_id", "test_client") global.userData = networkRequestFactory.perform(NetworkRequestType.UserData)
.add("scope", "openid offline_access profile sol_api") Util.saveStringToFile(global.filePaths.userData, global.userData.toString())
.build() global.studentClass = Parsing.getStudentClass()
global.studentId = Parsing.getStudentId()
global.apiEndPoints.marks = "${global.apiEndPoints.apiBase}/v1/students/${global.studentId}/marks/list"
global.isAPISetUp = true
}
enum class NetworkRequestType {
Token,
Timetable,
Marks,
UserData
}
interface NetworkRequestInterface {
fun perform(type: NetworkRequestType): JSONObject
}
object NetworkRequestFactory: NetworkRequestInterface {
private val client: OkHttpClient = OkHttpClient()
private val responseError = JSONObject(mapOf("error" to "error"))
override fun perform(type: NetworkRequestType): JSONObject {
when (type) {
NetworkRequestType.Token -> {
val response = post(global.apiEndPoints.token, headersOf(), FormBody.Builder()
.add("grant_type", "password")
.add("username", global.username)
.add("password", global.password)
.add("client_id", "test_client")
.add("scope", "openid offline_access profile sol_api")
.build()
) )
.build()
return try { return if (response.code == 200) {
val resp = global.client.newCall(request).execute() JSONObject(mapOf("token" to JSONObject(response.body?.string().toString()).getString("access_token")))
val respString = resp.body?.string().toString()
if (JSONObject(respString).has("access_token")) {
JSONObject(respString).getString("access_token")
} else { } else {
""""error": "network"""" responseError
} }
//val respJson = respString?.let { JSONObject(it) }
//respJson.toString()
} catch (e: JSONException) {
"""{"error": "json"}"""
} catch (e: Exception) {
//e.printStackTrace()
"""{"error": "network"}"""
} }
NetworkRequestType.Timetable -> return getAPI(global.apiEndPoints.timetable)
NetworkRequestType.Marks -> return getAPI(global.apiEndPoints.marks)
NetworkRequestType.UserData -> return getAPI(global.apiEndPoints.userData)
} }
}
fun setupAPI() { private fun get(url: String, headers: Headers): Response {
global.token = "NETWORK_UNREACHABLE" val request = Request.Builder()
val token = getToken() .url(url)
if (""""error": """ !in token) { .headers(headers)
global.token = token .get()
} .build()
if (global.token == "NETWORK_UNREACHABLE" || """"error": """ in global.token) {
global.userData = JSONObject()
global.studentId = ""
return
}
global.userData = getUserData()
Util.saveStringToFile(global.filePaths.userData, global.userData.toString())
global.studentClass = getStudentClass()
global.studentId = getStudentId()
global.apiEndPoints.marks = "${global.apiEndPoints.apiBase}/v1/students/${global.studentId}/marks/list" return client.newCall(request).execute()
}
global.isAPISetUp = true private fun post(url: String, headers: Headers, body: FormBody): Response {
} val request = Request.Builder()
.url(url)
.headers(headers)
.post(body)
.build()
fun getStudentClass(): String { // TODO: move to Parsing return client.newCall(request).execute()
return if (!Parsing.userIsParent()) { }
JSONObject(
Util.fileToString(global.filePaths.userData)
).getJSONObject("class").getString("name")
} else {
// if the user is a parent, the class will be of their first child
JSONObject(
Util.fileToString(global.filePaths.userData)
).getJSONArray("children").getJSONObject(0).getString("className")
}
}
fun getStudentId(): String { // TODO: move to Parsing private fun getAPI(url: String): JSONObject {
return if (!Parsing.userIsParent()) { Log.d("debug TOKEN", global.token)
global.userData.getString("personID") val response = get(url, headersOf(
} else { "Content-Type", "application/x-www-form-urlencoded",
global.userData.getJSONArray("children") "Authorization", "Bearer ${global.token}"
.getJSONObject(0) ))
.getString("id") return if (response.code == 200) {
} JSONObject(response.body?.string().toString())
} } else {
responseError
fun getUserData(): JSONObject {
val request = Request.Builder()
.url(global.apiEndPoints.userData)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Bearer ${global.token}") // using Bearer auth token
.get()
.build()
return try {
val resp = global.client.newCall(request).execute()
val respString = resp.body?.string().toString()
JSONObject(respString)
} catch (e: JSONException) {
JSONObject("""{"error": "json"}""")
} catch (e: IOException) {
JSONObject("""{"error": "network"}""")
}
}
fun getTimeTable(): JSONObject {
val userIsParent = Parsing.userIsParent()
val url = if (!userIsParent) global.apiEndPoints.timetable
else "${global.apiEndPoints.timetable}?studentId=${global.studentId}"
val request = Request.Builder()
.url(url)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Bearer ${global.token}")
.get()
.build()
return try {
val resp = global.client.newCall(request).execute()
JSONObject(resp.body?.string().toString())
} catch (e: JSONException) {
JSONObject("""{"error": "json"}""")
} catch (e: IOException) {
JSONObject("""{"error": "network"}""")
}
}
fun getMarks(): JSONObject {
val request = Request.Builder()
.url(global.apiEndPoints.marks)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Bearer ${global.token}")
.get()
.build()
return try {
val resp = global.client.newCall(request).execute()
JSONObject(resp.body?.string().toString())
} catch (e: JSONException) {
JSONObject("""{"error": "json"}""")
} catch (e: IOException) {
JSONObject("""{"error": "network"}""")
}
} }
} }
} }
val networkRequestFactory = NetworkRequestFactory
@@ -385,5 +385,29 @@ class Parsing {
return marks return marks
} }
fun getStudentClass(): String {
return if (!userIsParent()) {
global.userData
.getJSONObject("class")
.getString("name")
} else {
// if the user is a parent, the class will be of their first child
global.userData
.getJSONArray("children")
.getJSONObject(0)
.getString("className")
}
}
fun getStudentId(): String {
return if (!userIsParent()) {
global.userData.getString("personID")
} else {
global.userData.getJSONArray("children")
.getJSONObject(0)
.getString("id")
}
}
} }
} }