Skip to content

Commit

Permalink
Refactor data request
Browse files Browse the repository at this point in the history
  • Loading branch information
ya0211 committed Mar 12, 2023
1 parent a63a32a commit f22f50d
Show file tree
Hide file tree
Showing 8 changed files with 171 additions and 181 deletions.
104 changes: 34 additions & 70 deletions app/src/main/kotlin/com/sanmer/mrepo/provider/repo/RepoProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import com.sanmer.mrepo.data.CloudManager
import com.sanmer.mrepo.data.RepoManger
import com.sanmer.mrepo.data.database.entity.Repo
import com.sanmer.mrepo.data.json.OnlineModule
import com.sanmer.mrepo.data.json.Update
import com.sanmer.mrepo.utils.expansion.runRequest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
Expand All @@ -16,7 +16,7 @@ object RepoProvider {
private val coroutineScope = CoroutineScope(Dispatchers.IO)

@Synchronized
fun getRepoAll() = coroutineScope.launch(Dispatchers.IO) {
fun getRepoAll() = coroutineScope.launch {
if (Status.Cloud.isLoading) {
Timber.w("getRepo is already loading!")
return@launch
Expand All @@ -40,90 +40,54 @@ object RepoProvider {
}
}

suspend fun getRepo(repo: Repo) = if (repo.enable) {
getRepo(repo.url).onSuccess {
suspend fun getRepo(repo: Repo) = withContext(Dispatchers.IO) {
if (!repo.enable) {
return@withContext Result.failure(RuntimeException("${repo.name} is disabled!"))
}

runRequest {
val api = RepoService.create(repo.url)
return@runRequest api.getModules().execute()
}.onSuccess {
CloudManager.updateById(
id = repo.id,
value = it.copy(repoId = repo.id)
)

RepoManger.update(repo.copy(
name = it.name,
size = it.modules.size,
timestamp = it.timestamp
))
RepoManger.update(
repo.copy(
name = it.name,
size = it.modules.size,
timestamp = it.timestamp
)
)
}.onFailure {
Timber.e("getRepo: ${it.message}")
}
} else {
Result.failure(RuntimeException("${repo.name} is disabled!"))
}

private suspend fun getRepo(repoUrl: String) = withContext(Dispatchers.IO) {
try {
val api = RepoService.create(repoUrl)
val response = api.getModules().execute()

if (response.isSuccessful) {
val data = response.body()
return@withContext if (data != null) {
Result.success(data)
}else {
Result.failure(NullPointerException("The data is null!"))
}
} else {
val errorBody = response.errorBody()
val error = errorBody?.string()

return@withContext Result.failure(RuntimeException(error))
}
} catch (e: Exception) {
return@withContext Result.failure(e)
suspend fun getUpdate(module: OnlineModule) = withContext(Dispatchers.IO) {
if (module.repoId.isEmpty()) {
return@withContext Result.failure(NoSuchElementException("The repoId is empty!"))
}
}

suspend fun getUpdate(module: OnlineModule): Result<List<Update?>> {
if (module.repoId.isEmpty()) {
return Result.failure(NoSuchElementException("The repoId is empty!"))
} else {
val result = module.repoId.map { id ->
val repo = RepoManger.getById(id)!!
getUpdate(
repo = repo,
id = module.id
).onFailure {
Timber.d("getUpdate: ${it.message}")
}
}
val result = module.repoId.map { id ->
val repo = RepoManger.getById(id)!!

return if (result.all { it.isFailure }) {
Result.failure(result.first().exceptionOrNull()!!)
} else {
Result.success(result.map { it.getOrNull() })
runRequest {
val api = RepoService.create(repo.url)
api.getUpdate(module.id).execute()
}.onSuccess {
return@map Result.success(it.copy(repoId = repo.id))
}.onFailure {
Timber.d("getUpdate: ${it.message}")
}
}
}

private suspend fun getUpdate(repo: Repo, id: String) = withContext(Dispatchers.IO) {
try {
val api = RepoService.create(repo.url)
val response = api.getUpdate(id).execute()

if (response.isSuccessful) {
val data = response.body()
return@withContext if (data != null) {
Result.success(data.copy(repoId = repo.id))
}else {
Result.failure(NullPointerException("The data is null!"))
}
} else {
val errorBody = response.errorBody()
val error = errorBody?.string()

return@withContext Result.failure(RuntimeException(error))
}
} catch (e: Exception) {
return@withContext Result.failure(e)
return@withContext if (result.all { it.isFailure }) {
Result.failure(result.first().exceptionOrNull()!!)
} else {
Result.success(result.map { it.getOrNull() })
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import com.sanmer.mrepo.data.json.Update
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.create
import retrofit2.http.GET
import retrofit2.http.Path
import timber.log.Timber
Expand All @@ -25,7 +26,7 @@ interface RepoService {
.baseUrl(repoUrl)
.addConverterFactory(MoshiConverterFactory.create())
.build()
.create(RepoService::class.java)
.create()
}
}
}
Original file line number Diff line number Diff line change
@@ -1,27 +1,17 @@
package com.sanmer.mrepo.provider.spdx

import com.sanmer.mrepo.utils.expansion.runRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object LicenseProvider {
private val api by lazy { SpdxService.create() }

suspend fun getLicense(id: String) = withContext(Dispatchers.IO) {
try {
val response = api.getLicense(id).execute()

if (response.isSuccessful) {
val data = response.body()
return@withContext if (data != null) {
Result.success(data)
}else {
Result.failure(NullPointerException("The data is null!"))
}
} else {
return@withContext Result.failure(RuntimeException("The specified key does not exist!"))
}
} catch (e: Exception) {
return@withContext Result.failure(e)
runRequest {
api.getLicense(id).execute()
}.onFailure {
return@withContext Result.failure(RuntimeException("The specified key does not exist!"))
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.sanmer.mrepo.data.json.License
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.create
import retrofit2.http.GET
import retrofit2.http.Path

Expand All @@ -18,7 +19,7 @@ interface SpdxService {
.baseUrl(Const.SPDX_URL)
.addConverterFactory(MoshiConverterFactory.create())
.build()
.create(SpdxService::class.java)
.create()
}
}
}
29 changes: 17 additions & 12 deletions app/src/main/kotlin/com/sanmer/mrepo/service/DownloadService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ import com.sanmer.mrepo.utils.NotificationUtils
import com.sanmer.mrepo.utils.expansion.parcelable
import com.sanmer.mrepo.utils.expansion.toFile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import timber.log.Timber

class DownloadService : LifecycleService() {
val context by lazy { this }

private data class DownloadItem(
val id: Int = System.currentTimeMillis().toInt(),
val value: Module,
Expand Down Expand Up @@ -78,7 +79,7 @@ class DownloadService : LifecycleService() {

private fun downloader(
item: DownloadItem
) {
) = lifecycleScope.launch {
val module = item.value
val notificationId = item.id
val notificationIdFinish = notificationId + 1
Expand All @@ -87,7 +88,7 @@ class DownloadService : LifecycleService() {
Timber.d("download to ${path.absolutePath}")

val notification = NotificationUtils
.buildNotification(this, Const.CHANNEL_ID_DOWNLOAD)
.buildNotification(context, Const.CHANNEL_ID_DOWNLOAD)
.setContentTitle(module.name)
.setContentIntent(NotificationUtils.getActivity(MainActivity::class))
.setProgress(0, 0 , false)
Expand Down Expand Up @@ -121,7 +122,7 @@ class DownloadService : LifecycleService() {
)

if (item.install) {
InstallActivity.start(context = this, path = path)
InstallActivity.start(context = context, path = path)
}
}

Expand All @@ -138,18 +139,22 @@ class DownloadService : LifecycleService() {

HttpUtils.downloader(
url = module.url,
path = path,
out = path,
onProgress = {
broadcast(it, module)
progressFlow.value = (it * 100).toInt()
},
onSucceeded = succeeded,
onFailed = failed,
onFinished = {
list.remove(item)
stopIt()
}
)
).onSuccess {
succeeded()

list.remove(item)
stopIt()
}.onFailure {
failed(it.message)

list.remove(item)
stopIt()
}
}

private fun setForeground() {
Expand Down
Loading

0 comments on commit f22f50d

Please sign in to comment.