Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #5

Merged
merged 3 commits into from
Jul 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ plugins {

dependencies {
implementation(project(":core:ui"))
implementation(project(":core:datastore"))
implementation(project(":core:network"))
implementation(project(":feature:auth"))
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.stslex.aproselection

import android.app.Application
import com.stslex.aproselection.core.datastore.coreDataStoreModule
import com.stslex.aproselection.core.network.di.ModuleCoreNetwork.moduleCoreNetwork
import com.stslex.aproselection.feature.auth.di.ModuleFeatureAuth.moduleFeatureAuth
import org.koin.android.ext.koin.androidContext
Expand All @@ -16,7 +17,8 @@ class SelectApplication : Application() {
androidContext(applicationContext)
modules(
moduleFeatureAuth,
moduleCoreNetwork
moduleCoreNetwork,
coreDataStoreModule
)
}
}
Expand Down
21 changes: 21 additions & 0 deletions app/src/main/java/com/stslex/aproselection/ui/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,35 @@
package com.stslex.aproselection.ui

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.lifecycle.lifecycleScope
import com.stslex.aproselection.core.datastore.AppDataStore
import com.stslex.aproselection.core.network.client.NetworkClient
import com.stslex.aproselection.core.ui.theme.AppTheme
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.koin.android.ext.android.inject

class MainActivity : ComponentActivity() {

val dataStore by inject<AppDataStore>()
val networkClient by inject<NetworkClient>()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dataStore.token
.catch {
Log.e(it.message, javaClass.simpleName, it)
}
.onEach {
if (it.isBlank()) {
networkClient.regenerateToken()
}
}
.launchIn(lifecycleScope)
setContent {
AppTheme {
InitialApp()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.stslex.aproselection

import android.content.Context
import com.stslex.aproselection.core.datastore.coreDataStoreModule
import com.stslex.aproselection.core.network.di.ModuleCoreNetwork
import com.stslex.aproselection.core.network.di.ModuleCoreNetwork.moduleCoreNetwork
import com.stslex.aproselection.feature.auth.di.ModuleFeatureAuth.moduleFeatureAuth
Expand All @@ -19,7 +20,8 @@ class DiKoinModuleTest : KoinTest {
androidContext(Mockito.mock(Context::class.java))
modules(
moduleFeatureAuth,
moduleCoreNetwork
moduleCoreNetwork,
coreDataStoreModule
)
checkModules()
}
Expand Down
1 change: 1 addition & 0 deletions core/datastore/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
10 changes: 10 additions & 0 deletions core/datastore/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
plugins {
id("aproselection.android.library")
}

android.namespace = "com.stslex.aproselection.core.datastore"

dependencies {
implementation(libs.androidx.datastore.preferences)
implementation(libs.androidx.datastore)
}
Empty file.
21 changes: 21 additions & 0 deletions core/datastore/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.stslex.aproselection.core.datastore

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.stslex.aproselection.core.datastore.test", appContext.packageName)
}
}
2 changes: 2 additions & 0 deletions core/datastore/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest />
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.stslex.aproselection.core.datastore

import kotlinx.coroutines.flow.Flow

interface AppDataStore {

val uuid: Flow<String>
val token: Flow<String>

suspend fun setUuid(uuid: String)

suspend fun setToken(token: String)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.stslex.aproselection.core.datastore

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class AppDataStoreImpl(
private val context: Context
) : AppDataStore {

companion object {
private const val DATA_STORE_KEY = "app_data_store"
private val UUID_KEY = stringPreferencesKey("UUID_KEY")
private val TOKEN_KEY = stringPreferencesKey("TOKEN_KEY")
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(DATA_STORE_KEY)
}

override val uuid: Flow<String>
get() = context.dataStore.data.map { prefs ->
prefs[UUID_KEY].orEmpty()
}

override val token: Flow<String>
get() = context.dataStore.data.map { prefs ->
prefs[TOKEN_KEY].orEmpty()
}

override suspend fun setUuid(uuid: String) {
context.dataStore.updateData { prefs ->
prefs.toMutablePreferences().apply {
set(UUID_KEY, uuid)
}
}
}


override suspend fun setToken(token: String) {
context.dataStore.updateData { prefs ->
prefs.toMutablePreferences().apply {
set(TOKEN_KEY, token)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.stslex.aproselection.core.datastore

import org.koin.core.module.dsl.bind
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.module

val coreDataStoreModule = module {
singleOf(::AppDataStoreImpl) { bind<AppDataStore>() }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.stslex.aproselection.core.datastore

import org.junit.Test

import org.junit.Assert.*

/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
1 change: 1 addition & 0 deletions core/network/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ plugins {
}

dependencies {
implementation(project(":core:datastore"))
implementation(libs.bundles.ktor)
implementation(libs.bundles.okhttp)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ interface NetworkClient {
val client: HttpClient

val apiClient: HttpClient

suspend fun regenerateToken()
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,60 @@
package com.stslex.aproselection.core.network.client

import com.stslex.aproselection.core.datastore.AppDataStore
import com.stslex.aproselection.core.network.BuildConfig
import com.stslex.aproselection.core.network.clients.auth.model.TokenResponse
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.android.Android
import io.ktor.client.plugins.ClientRequestException
import io.ktor.client.plugins.HttpResponseValidator
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.plugins.logging.DEFAULT
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.request.bearerAuth
import io.ktor.client.request.get
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.URLProtocol
import io.ktor.http.appendPathSegments
import io.ktor.http.contentType
import io.ktor.http.encodedPath
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json

class NetworkClientImpl : NetworkClient {
class NetworkClientImpl(
private val dataStore: AppDataStore
) : NetworkClient {

private val scope = CoroutineScope(SupervisorJob())
private val _token = MutableStateFlow("")
private val token = _token.asStateFlow()
private val _uuid = MutableStateFlow("")
private val uuid = _uuid.asStateFlow()

init {
dataStore.token
.onEach {
_token.emit(it)
}
.launchIn(scope)

dataStore.uuid
.onEach {
_uuid.emit(it)
}
.launchIn(scope)
}

@OptIn(ExperimentalSerializationApi::class)
override val client: HttpClient
Expand All @@ -39,6 +77,17 @@ class NetworkClientImpl : NetworkClient {
}
)
}

HttpResponseValidator {
handleResponseExceptionWithRequest { exception, request ->
val clientException = exception as? ClientRequestException
?: return@handleResponseExceptionWithRequest
val exceptionResponse = clientException.response
if (exceptionResponse.status == HttpStatusCode.Unauthorized) {
regenerateToken()
}
}
}
}

override val apiClient: HttpClient
Expand All @@ -48,8 +97,22 @@ class NetworkClientImpl : NetworkClient {
host = BuildConfig.API_SERVER_HOST
encodedPath = BuildConfig.API_VERSION
protocol = URLProtocol.HTTP
headers.append("API_KEY", BuildConfig.API_KEY)
headers.append("DEVICE_ID", "test")
headers.append("uuid", uuid.value)
contentType(ContentType.Application.Json)
}
bearerAuth(BuildConfig.API_KEY)
bearerAuth(token = token.value)
}
}

override suspend fun regenerateToken() {
val token = apiClient
.get {
url.appendPathSegments("token")
}
.body<TokenResponse>()
.token
dataStore.setToken(token)
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
package com.stslex.aproselection.core.network.clients.auth

import com.stslex.aproselection.core.network.clients.auth.model.HelloRequestModel
import com.stslex.aproselection.core.network.clients.auth.model.UserAuthResponseModel
import com.stslex.aproselection.core.network.clients.auth.model.UserAuthSendModel
import kotlinx.coroutines.flow.Flow

interface AuthNetworkClient {

suspend fun getHello(username: String): HelloRequestModel

fun auth(user: UserAuthSendModel): Flow<UserAuthResponseModel>

fun register(user: UserAuthSendModel): Flow<UserAuthResponseModel>
}
Loading
Loading