Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SyncWorker.kt « service « ocreader « schaal « email « java « main « src « app - github.com/schaal/ocreader.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8380fb4114bcbd7d5766e019e022c6c4d870cec7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package email.schaal.ocreader.service

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.preference.PreferenceManager
import androidx.work.*
import email.schaal.ocreader.Preferences
import email.schaal.ocreader.api.API
import email.schaal.ocreader.util.LoginError

class SyncWorker(context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) {
    companion object {
        const val KEY_SYNC_TYPE = "KEY_SYNC_TYPE"
        const val KEY_EXCEPTION = "KEY_EXCEPTION"

        fun sync(context: Context, syncType: SyncType): LiveData<WorkInfo> {
            val workManager = WorkManager.getInstance(context)
            val syncWork = OneTimeWorkRequestBuilder<SyncWorker>()
                .setInputData(workDataOf(KEY_SYNC_TYPE to syncType.action))
                .build()
            workManager.enqueue(syncWork)
            return workManager.getWorkInfoByIdLiveData(syncWork.id)
        }
    }

    override suspend fun doWork(): Result {
        val syncType: SyncType = SyncType[inputData.getString(KEY_SYNC_TYPE)] ?: SyncType.FULL_SYNC
        val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)

        if(syncType != SyncType.SYNC_CHANGES_ONLY)
            preferences.edit().putBoolean(Preferences.SYS_SYNC_RUNNING.key, true).apply()

        return try {
            API(applicationContext).sync(syncType)
            Result.success()
        } catch (e: Throwable) {
            e.printStackTrace()
            Result.failure(
                workDataOf(
                    KEY_EXCEPTION to LoginError.getError(
                        applicationContext, e).message
                )
            )
        } finally {
            preferences.edit().putBoolean(Preferences.SYS_SYNC_RUNNING.key, false).apply()
        }
    }
}