Skip to content

Commit

Permalink
Merge pull request #123 from snuhcs-course/hotfix/backup
Browse files Browse the repository at this point in the history
백업 관련 핫픽스
  • Loading branch information
JH747 authored Dec 10, 2023
2 parents 66df38d + fb955e4 commit 726caa3
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 87 deletions.
37 changes: 13 additions & 24 deletions frontend/app/src/main/java/com/example/speechbuddy/AuthActivity.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package com.example.speechbuddy

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.inputmethod.InputMethodManager
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
Expand All @@ -25,7 +23,6 @@ import java.time.LocalDate
@AndroidEntryPoint
class AuthActivity : BaseActivity() {

@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)
Expand All @@ -49,7 +46,6 @@ class AuthActivity : BaseActivity() {
}
}

@RequiresApi(Build.VERSION_CODES.O)
private fun autoBackup() {
setContent {
SpeechBuddyTheme(
Expand Down Expand Up @@ -78,7 +74,6 @@ class AuthActivity : BaseActivity() {
return darkMode
}

@RequiresApi(Build.VERSION_CODES.O)
private suspend fun isBackupNecessary(): Boolean {
val autoBackup = settingsRepository.getAutoBackup().first().data
if (autoBackup == null || autoBackup == false) return false
Expand All @@ -87,23 +82,21 @@ class AuthActivity : BaseActivity() {
return true
}

@RequiresApi(Build.VERSION_CODES.O)
private fun checkPreviousAuthUser() {
lifecycleScope.launch {
authRepository.checkPreviousUser().collect {
if (it.data != null) {
val userId = it.data.first
val authToken = it.data.second
val setAuthTokenJob = sessionManager.setAuthToken(authToken)
setAuthTokenJob.join()

if (userId != GUEST_ID && sessionManager.isLogin.value != true && isBackupNecessary())
autoBackup()
sessionManager.setUserId(userId)
} else {
val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
WorkManager.getInstance(applicationContext).enqueue(request)
}
val resource = authRepository.checkPreviousUser().first()
if (resource.data != null) {
val userId = resource.data.first
val authToken = resource.data.second
val setAuthTokenJob = sessionManager.setAuthToken(authToken)
setAuthTokenJob.join()

if (userId != GUEST_ID && sessionManager.isLogin.value != true && isBackupNecessary())
autoBackup()
sessionManager.setUserId(userId)
} else {
val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
WorkManager.getInstance(applicationContext).enqueue(request)
}
}
}
Expand All @@ -121,7 +114,6 @@ class AuthActivity : BaseActivity() {
return super.dispatchTouchEvent(event)
}

@RequiresApi(Build.VERSION_CODES.O)
private fun displayBackup() {
CoroutineScope(Dispatchers.IO).launch {
settingsRepository.displayBackup().collect { result ->
Expand All @@ -139,7 +131,6 @@ class AuthActivity : BaseActivity() {
}
}

@RequiresApi(Build.VERSION_CODES.O)
private fun symbolListBackup() {
CoroutineScope(Dispatchers.IO).launch {
settingsRepository.symbolListBackup().collect { result ->
Expand All @@ -157,7 +148,6 @@ class AuthActivity : BaseActivity() {
}
}

@RequiresApi(Build.VERSION_CODES.O)
private fun favoriteSymbolBackup() {
CoroutineScope(Dispatchers.IO).launch {
settingsRepository.favoriteSymbolBackup().collect { result ->
Expand All @@ -175,7 +165,6 @@ class AuthActivity : BaseActivity() {
}
}

@RequiresApi(Build.VERSION_CODES.O)
private fun weightTableBackup() {
CoroutineScope(Dispatchers.IO).launch {
settingsRepository.weightTableBackup().collect { result ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ fun SymbolSelectionScreen(
symbol = entry,
onSelect = {
coroutineScope.launch {
val id = viewModel.selectSymbol(entry)
viewModel.selectSymbol(entry)
lazyGridState.animateScrollToItem(0)
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.example.speechbuddy.data.remote.requests.BackupWeightTableRequest
import com.example.speechbuddy.service.BackupService
import com.example.speechbuddy.utils.ResponseHandler
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import retrofit2.Response
import javax.inject.Inject
Expand All @@ -17,41 +18,34 @@ class SettingsRemoteSource @Inject constructor(
) {
suspend fun getDisplaySettings(authHeader: String): Flow<Response<SettingsBackupDto>> =
flow {
try {
val result = backupService.getDisplaySettings(authHeader)
emit(result)
} catch (e: Exception) {
emit(responseHandler.getConnectionErrorResponse())
}
val result = backupService.getDisplaySettings(authHeader)
emit(result)
}.catch {
emit(responseHandler.getConnectionErrorResponse())
}

suspend fun getSymbolList(authHeader: String): Flow<Response<SymbolListDto>> =
flow {
try {
val result = backupService.getSymbolList(authHeader)
emit(result)
} catch (e: Exception) {
emit(responseHandler.getConnectionErrorResponse())
}
val result = backupService.getSymbolList(authHeader)
emit(result)
}.catch {
emit(responseHandler.getConnectionErrorResponse())
}

suspend fun getFavoritesList(authHeader: String): Flow<Response<FavoritesListDto>> =
flow {
try {
val result = backupService.getFavoriteSymbolList(authHeader)
emit(result)
} catch (e: Exception) {
emit(responseHandler.getConnectionErrorResponse())
}
val result = backupService.getFavoriteSymbolList(authHeader)
emit(result)
}.catch {
emit(responseHandler.getConnectionErrorResponse())
}


suspend fun getWeightTable(authHeader: String): Flow<Response<BackupWeightTableRequest>> =
flow {
try {
val result = backupService.getWeightTable(authHeader)
emit(result)
} catch (e: Exception) {
emit(responseHandler.getConnectionErrorResponse())
}
val result = backupService.getWeightTable(authHeader)
emit(result)
}.catch {
emit(responseHandler.getConnectionErrorResponse())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ class BackupSettingsViewModel @Inject internal constructor(
ResponseCode.SUCCESS.value -> {
symbolListBackup()
}

ResponseCode.BAD_REQUEST.value -> {
handleNoInternetConnection()
}
ResponseCode.NO_INTERNET_CONNECTION.value -> {
handleNoInternetConnection()
}
Expand All @@ -114,7 +116,9 @@ class BackupSettingsViewModel @Inject internal constructor(
ResponseCode.SUCCESS.value -> {
favoriteSymbolBackup()
}

ResponseCode.BAD_REQUEST.value -> {
handleNoInternetConnection()
}
ResponseCode.NO_INTERNET_CONNECTION.value -> {
handleNoInternetConnection()
}
Expand All @@ -132,7 +136,9 @@ class BackupSettingsViewModel @Inject internal constructor(
ResponseCode.SUCCESS.value -> {
weightTableBackup()
}

ResponseCode.BAD_REQUEST.value -> {
handleNoInternetConnection()
}
ResponseCode.NO_INTERNET_CONNECTION.value -> {
handleNoInternetConnection()
}
Expand All @@ -148,7 +154,9 @@ class BackupSettingsViewModel @Inject internal constructor(
ResponseCode.SUCCESS.value -> {
handleSuccess()
}

ResponseCode.BAD_REQUEST.value -> {
handleNoInternetConnection()
}
ResponseCode.NO_INTERNET_CONNECTION.value -> {
handleNoInternetConnection()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,10 @@ class SymbolSelectionViewModel @Inject internal constructor(
fun clearAll() {
weightTableRepository.update(selectedSymbols)
selectedSymbols = emptyList()
getEntries()
}

fun selectSymbol(symbol: Symbol): Int {
fun selectSymbol(symbol: Symbol) {
queryInput = ""

val newSymbolItem = SymbolItem(id = selectedSymbols.size, symbol = symbol)
Expand All @@ -109,8 +110,6 @@ class SymbolSelectionViewModel @Inject internal constructor(
}

provideSuggestion(symbol)

return newSymbolItem.id
}

fun updateFavorite(symbol: Symbol, value: Boolean) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class SeedDatabaseWorker(
Expand All @@ -26,41 +25,26 @@ class SeedDatabaseWorker(
try {
val database = AppDatabase.getInstance(applicationContext)

val currentDb = database.weightRowDao().getAllWeightRows().first()
var cnt = 0
for (currentWeightRowEntity in currentDb) {
if (currentWeightRowEntity.weights.all{it == 0}){
cnt+=1 // count the rows with 0 weights
}
}
if (cnt == currentDb.size){ // if weight table is filled with 0
Log.d("create-db", "empty db->initializing db")
applicationContext.assets.open("weight_table.txt").use { inputStream ->
val weightRows = mutableListOf<WeightRowEntity>()
applicationContext.assets.open("weight_table.txt").use { inputStream ->
val weightRows = mutableListOf<WeightRowEntity>()

val inputList: MutableList<List<Int>> = ArrayList()
inputStream.bufferedReader().useLines { lines ->
lines.forEach { line ->
inputList.add(
line.split(",").mapNotNull { it.trim().toIntOrNull() })
}
}
var id = 1
for (weight in inputList) {
val weightRowEntity = WeightRowEntity(id++, weight)
weightRows.add(weightRowEntity)
val inputList: MutableList<List<Int>> = ArrayList()
inputStream.bufferedReader().useLines { lines ->
lines.forEach { line ->
inputList.add(
line.split(",").mapNotNull { it.trim().toIntOrNull() })
}

database.weightRowDao().upsertAll(weightRows)

Result.success()
}
}
else{
Log.d("create-db", "db exists")
}
var id = 1
for (weight in inputList) {
val weightRowEntity = WeightRowEntity(id++, weight)
weightRows.add(weightRowEntity)
}

database.weightRowDao().upsertAll(weightRows)

Result.success()
}

applicationContext.assets.open(SYMBOL_DATA_FILENAME).use { inputStream ->
JsonReader(inputStream.reader()).use { jsonReader ->
Expand Down

0 comments on commit 726caa3

Please sign in to comment.