Skip to content
Merged
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
49 changes: 25 additions & 24 deletions app/src/main/kotlin/com/looker/droidify/work/DownloadStatsWorker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,12 @@ import io.ktor.http.HttpStatusCode
import java.io.File
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.concurrent.atomics.AtomicInt
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.concurrent.atomics.incrementAndFetch
import kotlin.time.ExperimentalTime
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext

@HiltWorker
Expand Down Expand Up @@ -78,33 +75,37 @@ class DownloadStatsWorker @AssistedInject constructor(
val fileNames = ConcurrentLinkedQueue(
generateMonthlyFileNames(lastModified)
)
val successfulResults = AtomicInt(0)
val updatedResults = AtomicInt(0)

Log.d(TAG, "Fetching ${fileNames.size} monthly files")
while (fileNames.isNotEmpty()) {
launch {
downloadSemaphores.withPermit {
val fileName = fileNames.poll() ?: return@withPermit
val target = Cache.getTemporaryFile(context)
if (downloadSemaphores.tryAcquire()) {
launch {
val fileName = fileNames.poll()
if (fileName == null) {
downloadSemaphores.release()
} else {
val target = Cache.getTemporaryFile(context)
try {
Log.i(TAG, "Downloading $fileName")
val response = downloadFile(fileName, target)
Log.i(TAG, "Downloaded $fileName with $response")

Log.i(TAG, "Downloading $fileName")
val response = downloadFile(fileName, target)
Log.i(TAG, "Downloaded $fileName with $response")

if (response is NetworkResponse.Success) {
successfulResults.incrementAndFetch()
val isModified = response.statusCode != HttpStatusCode.NotModified.value
if (isModified) {
processDownloadStats(
response = response,
fileName = fileName,
target = target
)
updatedResults.incrementAndFetch()
if (response is NetworkResponse.Success) {
val isModified =
response.statusCode != HttpStatusCode.NotModified.value
if (isModified) {
processDownloadStats(
response = response,
fileName = fileName,
target = target
)
}
}
} finally {
target.delete()
downloadSemaphores.release()
}
}
target.delete()
}
}
}
Expand Down