-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- SyncAllLocations - Campaign
- Loading branch information
Showing
8 changed files
with
240 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
88 changes: 88 additions & 0 deletions
88
opensrp-core/src/main/java/org/smartregister/sync/wm/worker/CampaignWorker.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
package org.smartregister.sync.wm.worker | ||
|
||
import android.content.Context | ||
import androidx.work.Worker | ||
import androidx.work.WorkerParameters | ||
import com.google.gson.Gson | ||
import com.google.gson.GsonBuilder | ||
import com.google.gson.reflect.TypeToken | ||
import org.joda.time.DateTime | ||
import org.joda.time.LocalDate | ||
import org.smartregister.AllConstants | ||
import org.smartregister.CoreLibrary | ||
import org.smartregister.domain.Campaign | ||
import org.smartregister.domain.FetchStatus | ||
import org.smartregister.exception.NoHttpResponseException | ||
import org.smartregister.service.HTTPAgent | ||
import org.smartregister.util.DateTimeTypeConverter | ||
import org.smartregister.util.DateTypeConverter | ||
import org.smartregister.util.Utils | ||
import org.smartregister.util.WorkerNotificationDelegate | ||
import timber.log.Timber | ||
|
||
class CampaignWorker(context: Context, workerParams: WorkerParameters) : | ||
Worker(context, workerParams) { | ||
|
||
private val notificationDelegate = WorkerNotificationDelegate(context, TAG) | ||
|
||
override fun doWork(): Result { | ||
notificationDelegate.notify("Running \u8086") | ||
|
||
val opensrpContext = CoreLibrary.getInstance().context() | ||
val baseUrl = opensrpContext.configuration().dristhiBaseURL() | ||
val allSharedPreferences = opensrpContext.allSharedPreferences() | ||
val campaignRepository = opensrpContext.campaignRepository | ||
val httpAgent = opensrpContext.httpAgent | ||
return try { | ||
val campaignsResponse = fetchCampaigns(httpAgent, baseUrl) | ||
val allowedCampaigns = allSharedPreferences.getPreference(AllConstants.CAMPAIGNS).split(",") | ||
val campaigns = gson.fromJson<List<Campaign>>( | ||
campaignsResponse, | ||
object : TypeToken<List<Campaign?>?>() {}.type | ||
) | ||
val errors = mutableListOf<Throwable>() | ||
campaigns.filter { it.identifier != null && it.identifier in allowedCampaigns } | ||
.forEach { | ||
runCatching { campaignRepository.addOrUpdate(it)}.onFailure { e -> errors.add(e) } | ||
} | ||
if (errors.isNotEmpty()) throw Exception(errors.random()) | ||
Result.success().apply { | ||
notificationDelegate.notify("Success!!") | ||
} | ||
} catch (e: Exception) { | ||
Timber.e(e) | ||
Result.failure().apply { | ||
notificationDelegate.notify("Error: ${e.message}") | ||
} | ||
} | ||
} | ||
|
||
fun getUrl(baseUrl: String): String { | ||
val endString = "/" | ||
return "${if (baseUrl.endsWith(endString)) baseUrl.substring(0, baseUrl.lastIndexOf(endString)) else baseUrl}$CAMPAIGN_URL" | ||
} | ||
|
||
@Throws(NoHttpResponseException::class) | ||
fun fetchCampaigns(httpAgent: HTTPAgent?, baseUrl: String): String { | ||
if (httpAgent == null) { | ||
applicationContext.sendBroadcast(Utils.completeSync(FetchStatus.noConnection)) | ||
throw IllegalArgumentException("$CAMPAIGN_URL http agent is null") | ||
} | ||
val resp= httpAgent.fetch(getUrl(baseUrl)) | ||
if (resp.isFailure) { | ||
applicationContext.sendBroadcast(Utils.completeSync(FetchStatus.nothingFetched)) | ||
throw NoHttpResponseException("$CAMPAIGN_URL not returned data") | ||
} | ||
return resp.payload().toString() | ||
} | ||
|
||
companion object{ | ||
const val CAMPAIGN_URL = "/rest/campaign/" | ||
const val TAG = "CampaignWorker" | ||
val gson: Gson = GsonBuilder().registerTypeAdapter( | ||
DateTime::class.java, | ||
DateTimeTypeConverter("yyyy-MM-dd'T'HHmm") | ||
) | ||
.registerTypeAdapter(LocalDate::class.java, DateTypeConverter()).create() | ||
} | ||
} |
34 changes: 34 additions & 0 deletions
34
opensrp-core/src/main/java/org/smartregister/sync/wm/worker/SyncAllLocationsWorker.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package org.smartregister.sync.wm.worker | ||
|
||
import android.content.Context | ||
import androidx.work.Worker | ||
import androidx.work.WorkerParameters | ||
import org.smartregister.sync.helper.LocationServiceHelper | ||
import org.smartregister.util.WorkerNotificationDelegate | ||
import timber.log.Timber | ||
|
||
class SyncAllLocationsWorker(context: Context, workerParams: WorkerParameters): Worker(context, workerParams) { | ||
|
||
private val notificationDelegate = WorkerNotificationDelegate(context, TAG) | ||
|
||
override fun doWork(): Result { | ||
val locationServiceHelper = LocationServiceHelper.getInstance() | ||
|
||
return try { | ||
notificationDelegate.notify("Running \u8086") | ||
locationServiceHelper.fetchAllLocations().runCatching { } | ||
Result.success().apply { | ||
notificationDelegate.notify("Success!!") | ||
} | ||
} catch (e: Exception) { | ||
Timber.e(e) | ||
Result.failure().apply { | ||
notificationDelegate.notify("Error: ${e.message}") | ||
} | ||
} | ||
} | ||
|
||
companion object{ | ||
const val TAG = "SyncAllLocationsWorker" | ||
} | ||
} |
34 changes: 34 additions & 0 deletions
34
opensrp-core/src/main/java/org/smartregister/sync/wm/workerrequest/OneTimeWorkRequest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package org.smartregister.sync.wm.workerrequest | ||
|
||
import android.content.Context | ||
import android.os.Build | ||
import androidx.work.Constraints | ||
import androidx.work.Data | ||
import androidx.work.ListenableWorker | ||
import androidx.work.NetworkType | ||
import androidx.work.OneTimeWorkRequest | ||
import androidx.work.WorkManager | ||
import org.smartregister.sync.wm.worker.SyncAllLocationsWorker | ||
|
||
|
||
object OneTimeWorkRequest { | ||
|
||
fun runTask(context: Context, workerClass: Class<out ListenableWorker>) { | ||
val inputData: Data = Data.Builder() | ||
.putString("key", "value") | ||
.build() | ||
val constraintsBuilder = Constraints.Builder() | ||
.setRequiredNetworkType(NetworkType.UNMETERED) | ||
.setRequiresBatteryNotLow(false) | ||
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M){ | ||
constraintsBuilder.setRequiresDeviceIdle(false) | ||
} | ||
val constraints: Constraints = constraintsBuilder.build() | ||
val request = OneTimeWorkRequest.Builder(workerClass) | ||
.setInputData(inputData) | ||
.setConstraints(constraints) | ||
.build() | ||
WorkManager.getInstance(context).enqueue(request) | ||
} | ||
|
||
} |
53 changes: 53 additions & 0 deletions
53
opensrp-core/src/main/java/org/smartregister/util/WorkerUtils.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package org.smartregister.util | ||
|
||
import android.app.NotificationChannel | ||
import android.app.NotificationManager | ||
import android.content.Context | ||
import android.os.Build | ||
import androidx.core.app.NotificationCompat | ||
import androidx.core.app.NotificationManagerCompat | ||
import org.smartregister.R | ||
import kotlin.random.Random | ||
|
||
|
||
object WorkerUtils { | ||
private const val CHANNEL_ID = "org.smartregisterx" | ||
private const val CHANNEL_NAME = "OpenSRP" | ||
private const val CHANNEL_DESC = "OpenSRP Client" | ||
|
||
fun makeStatusNotification( | ||
context: Context, | ||
notificationId: Int, | ||
title: String?, | ||
message: String? | ||
) { | ||
val notificationManager = NotificationManagerCompat.from(context) | ||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { | ||
val channel = NotificationChannel( | ||
CHANNEL_ID, | ||
CHANNEL_NAME, | ||
NotificationManager.IMPORTANCE_LOW | ||
) | ||
channel.description = CHANNEL_DESC | ||
notificationManager.createNotificationChannel(channel) | ||
} | ||
val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, CHANNEL_ID) | ||
.setContentTitle(title) | ||
.setContentText(message) | ||
.setSmallIcon(R.drawable.ic_opensrp_logo) | ||
.setPriority(NotificationCompat.PRIORITY_LOW) | ||
notificationManager.notify(notificationId, builder.build()) | ||
} | ||
|
||
fun dismissNotification(context: Context, notificationId: Int){ | ||
NotificationManagerCompat.from(context).cancel(notificationId) | ||
} | ||
} | ||
|
||
class WorkerNotificationDelegate(private val context: Context, | ||
private val title: String?){ | ||
private val notificationId: Int = Random.nextInt() | ||
fun notify(message: String){ | ||
WorkerUtils.makeStatusNotification(context, notificationId, title, message) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters