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 lectureNotes: HashMap<Int, LectureNote> = hashMapOf()
var subjectNameMap: HashMap<String, String> = hashMapOf()
var client: OkHttpClient = OkHttpClient()
var username: String = ""
var password: String = ""
@@ -28,9 +28,9 @@ fun remoteLoad(ctx: Context) {
if (!global.isAPISetUp) {
CoroutineScope(Dispatchers.IO)
.launch {
Network.setupAPI()
global.timetableJSON = Network.getTimeTable()
global.marksJSON = Network.getMarks()
setupAPI()
global.timetableJSON = networkRequestFactory.perform(NetworkRequestType.Timetable)
global.marksJSON = networkRequestFactory.perform(NetworkRequestType.Marks)
launchContinue(
ctx,
@@ -42,8 +42,8 @@ fun remoteLoad(ctx: Context) {
CoroutineScope(Dispatchers.IO).launch {
launchContinue(
ctx,
Network.getTimeTable(),
Network.getMarks()
networkRequestFactory.perform(NetworkRequestType.Timetable),
networkRequestFactory.perform(NetworkRequestType.Marks)
)
}
}
@@ -51,8 +51,8 @@ fun remoteLoad(ctx: Context) {
fun localLoad(ctx: Context) {
global.userData = JSONObject(Util.fileToString(global.filePaths.userData))
global.studentId = Network.getStudentId()
global.studentClass = Network.getStudentClass()
global.studentId = Parsing.getStudentId()
global.studentClass = Parsing.getStudentClass()
global.apiEndPoints.marks = "${global.apiEndPoints.apiBase}/v1/students/${global.studentId}/marks/list"
val localTimetable = JSONObject(Util.fileToString(global.filePaths.timetable))
val localMarks = JSONObject(Util.fileToString(global.filePaths.marks))
@@ -1,49 +1,17 @@
package com.odweta.solon
import android.util.Log
import okhttp3.FormBody
import okhttp3.Headers
import okhttp3.Headers.Companion.headersOf
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONException
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException
class Network {
companion object {
fun getToken(): String {
val request = Request.Builder()
.url(global.apiEndPoints.token)
.header("Content-Type", "application/x-www-form-urlencoded")
.post(
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 {
val resp = global.client.newCall(request).execute()
val respString = resp.body?.string().toString()
if (JSONObject(respString).has("access_token")) {
JSONObject(respString).getString("access_token")
} else {
""""error": "network""""
}
//val respJson = respString?.let { JSONObject(it) }
//respJson.toString()
} catch (e: JSONException) {
"""{"error": "json"}"""
} catch (e: Exception) {
//e.printStackTrace()
"""{"error": "network"}"""
}
}
fun setupAPI() {
fun setupAPI() {
global.token = "NETWORK_UNREACHABLE"
val token = getToken()
val token = networkRequestFactory.perform(NetworkRequestType.Token).getString("token")
if (""""error": """ !in token) {
global.token = token
}
@@ -52,96 +20,87 @@ class Network {
global.studentId = ""
return
}
global.userData = getUserData()
global.userData = networkRequestFactory.perform(NetworkRequestType.UserData)
Util.saveStringToFile(global.filePaths.userData, global.userData.toString())
global.studentClass = getStudentClass()
global.studentId = getStudentId()
global.studentClass = Parsing.getStudentClass()
global.studentId = Parsing.getStudentId()
global.apiEndPoints.marks = "${global.apiEndPoints.apiBase}/v1/students/${global.studentId}/marks/list"
global.isAPISetUp = true
}
}
fun getStudentClass(): String { // TODO: move to Parsing
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")
}
}
enum class NetworkRequestType {
Token,
Timetable,
Marks,
UserData
}
fun getStudentId(): String { // TODO: move to Parsing
return if (!Parsing.userIsParent()) {
global.userData.getString("personID")
} else {
global.userData.getJSONArray("children")
.getJSONObject(0)
.getString("id")
}
}
interface NetworkRequestInterface {
fun perform(type: NetworkRequestType): JSONObject
}
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()
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()
)
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"}""")
return if (response.code == 200) {
JSONObject(mapOf("token" to JSONObject(response.body?.string().toString()).getString("access_token")))
} else {
responseError
}
}
NetworkRequestType.Timetable -> return getAPI(global.apiEndPoints.timetable)
NetworkRequestType.Marks -> return getAPI(global.apiEndPoints.marks)
NetworkRequestType.UserData -> return getAPI(global.apiEndPoints.userData)
}
}
fun getTimeTable(): JSONObject {
val userIsParent = Parsing.userIsParent()
val url = if (!userIsParent) global.apiEndPoints.timetable
else "${global.apiEndPoints.timetable}?studentId=${global.studentId}"
private fun get(url: String, headers: Headers): Response {
val request = Request.Builder()
.url(url)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Bearer ${global.token}")
.headers(headers)
.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"}""")
}
return client.newCall(request).execute()
}
fun getMarks(): JSONObject {
private fun post(url: String, headers: Headers, body: FormBody): Response {
val request = Request.Builder()
.url(global.apiEndPoints.marks)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Bearer ${global.token}")
.get()
.url(url)
.headers(headers)
.post(body)
.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"}""")
return client.newCall(request).execute()
}
private fun getAPI(url: String): JSONObject {
Log.d("debug TOKEN", global.token)
val response = get(url, headersOf(
"Content-Type", "application/x-www-form-urlencoded",
"Authorization", "Bearer ${global.token}"
))
return if (response.code == 200) {
JSONObject(response.body?.string().toString())
} else {
responseError
}
}
}
val networkRequestFactory = NetworkRequestFactory
@@ -385,5 +385,29 @@ class Parsing {
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")
}
}
}
}