Implement broadcasts and print them in tests (no real check for now)
This commit is contained in:
14 files changed
+213
-45
No files matched your search
@@ -27,9 +27,6 @@ android {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
testOptions {
|
||||
unitTests.includeAndroidResources = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -3,4 +3,7 @@ package eu.depau.etchdroid
|
||||
object AppBuildConfig {
|
||||
@JvmField
|
||||
var TEST_BUILD = false
|
||||
|
||||
@JvmField
|
||||
var USE_LOCAL_BROADCASTS = true
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package eu.depau.etchdroid.broadcasts
|
||||
|
||||
object BroadcastExtras {
|
||||
const val UPDATE_DTO = "eu.depau.etchdroid.broadcast.extras.UPDATE_DTO"
|
||||
}
|
||||
@@ -7,7 +7,7 @@ object JobProgressUpdateBroadcast {
|
||||
const val ACTION = "eu.depau.etchdroid.broadcast.JOB_PROGRESS_UPDATE"
|
||||
|
||||
fun getIntent(dto: JobProgressUpdateBroadcastDTO) = Intent().apply {
|
||||
action = this@JobProgressUpdateBroadcast.ACTION
|
||||
action = ACTION
|
||||
dto.writeToIntent(this)
|
||||
}
|
||||
}
|
||||
+11
-7
@@ -1,26 +1,30 @@
|
||||
package eu.depau.etchdroid.broadcasts.dto
|
||||
|
||||
import android.content.Intent
|
||||
import eu.depau.etchdroid.broadcasts.BroadcastExtras
|
||||
import eu.depau.etchdroid.utils.worker.enums.RateUnit
|
||||
import java.io.Serializable
|
||||
|
||||
|
||||
data class JobProgressUpdateBroadcastDTO(
|
||||
val jobId: Long,
|
||||
val indefinite: Boolean,
|
||||
val showProgressBar: Boolean,
|
||||
val completed: Boolean,
|
||||
val indefinite: Boolean = false,
|
||||
val showProgressBar: Boolean = true,
|
||||
val completed: Boolean = false,
|
||||
val step: Int? = null,
|
||||
val percentage: Double? = null,
|
||||
val rate: Double? = null,
|
||||
val rateUnit: RateUnit? = null,
|
||||
val currentMessage: String? = null,
|
||||
val error: Exception? = null
|
||||
val error: Throwable? = null
|
||||
) : Serializable {
|
||||
fun writeToIntent(intent: Intent) {
|
||||
intent.putExtra(BroadcastExtras.UPDATE_DTO, this)
|
||||
intent.putExtra(EXTRA, this)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA = "eu.depau.etchdroid.broadcast.extras.UPDATE_DTO"
|
||||
|
||||
fun readFromIntent(intent: Intent) =
|
||||
intent.getSerializableExtra(BroadcastExtras.UPDATE_DTO)!! as JobProgressUpdateBroadcastDTO
|
||||
intent.getSerializableExtra(EXTRA)!! as JobProgressUpdateBroadcastDTO
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
package eu.depau.etchdroid.db.repository
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.Query
|
||||
import androidx.room.*
|
||||
import eu.depau.etchdroid.db.entity.Job
|
||||
|
||||
@Dao
|
||||
@@ -20,6 +17,9 @@ interface JobRepository {
|
||||
@Insert
|
||||
fun insertAll(vararg jobs: Job)
|
||||
|
||||
@Update
|
||||
fun update(job: Job)
|
||||
|
||||
@Delete
|
||||
fun delete(job: Job)
|
||||
}
|
||||
@@ -16,10 +16,10 @@ class JobIntentHandler(
|
||||
) : AbstractJobProgressSender() {
|
||||
|
||||
private val jobId = jobDTO.jobId
|
||||
private val broadcastForwarder = ProgressBroadcastForwarder(jobId, context)
|
||||
private val svcNotificationHandler = JobServiceNotificationHandler(context)
|
||||
private val notification = svcNotificationHandler.build()
|
||||
private lateinit var job: Job
|
||||
private val broadcastForwarder = ProgressBroadcastForwarder(jobId, context)
|
||||
|
||||
init {
|
||||
assert(jobId >= 0) { "Invalid jobId (jobId < 0)" }
|
||||
@@ -27,8 +27,10 @@ class JobIntentHandler(
|
||||
|
||||
fun handle() = context.runForeground(jobId.toInt(), notification, true) {
|
||||
val db = EtchDroidDatabase.getDatabase(context)
|
||||
job = db.jobRepository().getById(jobId)
|
||||
assert(!job.completed) { "Job $jobId already completed" }
|
||||
|
||||
job = db.jobRepository().getById(jobId).also {
|
||||
assert(!it.completed) { "Job $jobId already completed" }
|
||||
}
|
||||
|
||||
job.attachAndRun { procedure ->
|
||||
procedure.forEachAction { index, action, worker ->
|
||||
@@ -36,6 +38,9 @@ class JobIntentHandler(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
job.completed = true
|
||||
db.jobRepository().update(job)
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,31 +1,37 @@
|
||||
package eu.depau.etchdroid.services.job
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager
|
||||
import eu.depau.etchdroid.AppBuildConfig
|
||||
import eu.depau.etchdroid.R
|
||||
import eu.depau.etchdroid.broadcasts.JobProgressUpdateBroadcast
|
||||
import eu.depau.etchdroid.broadcasts.dto.JobProgressUpdateBroadcastDTO
|
||||
import eu.depau.etchdroid.db.EtchDroidDatabase
|
||||
import eu.depau.etchdroid.utils.job.IJobProgressListener
|
||||
import eu.depau.etchdroid.utils.worker.IWorkerProgressListener
|
||||
import eu.depau.etchdroid.utils.worker.dto.ProgressUpdateDTO
|
||||
|
||||
// TODO: implement class stubs
|
||||
|
||||
/**
|
||||
* This class is subscribed to IAsyncWorker+IWorkerProgressSender events by the worker service.
|
||||
* It is aware of the current JobProcedure (in fact, it retrieves it by ID from the database).
|
||||
* It is aware of the current JobProcedure.
|
||||
*
|
||||
* It tracks
|
||||
* It receives the job progress and forwards it to the rest of the app.
|
||||
*/
|
||||
class ProgressBroadcastForwarder(
|
||||
private val jobId: Long, private val context: Context
|
||||
) : IJobProgressListener, IWorkerProgressListener {
|
||||
|
||||
private val db = EtchDroidDatabase.getDatabase(context)
|
||||
private val jobEntity = db.jobRepository().getById(jobId)
|
||||
private val job = db.jobRepository().getById(jobId)
|
||||
private val procedure = job.jobProcedure
|
||||
|
||||
private val totalProgressWeights = jobEntity.jobProcedure.map { it.progressWeight }.sum()
|
||||
private val totalProgressWeights = job.jobProcedure.map { it.progressWeight }.sum()
|
||||
|
||||
private var currentActionIdx: Int? = null
|
||||
private var prevActionsProgressWeight: Double? = null
|
||||
|
||||
|
||||
private fun assertProcedureStarted() {
|
||||
if (currentActionIdx == null || prevActionsProgressWeight == null) {
|
||||
throw IllegalStateException("Call to a .on*() method without a call to .onProcedureStart()")
|
||||
@@ -33,19 +39,45 @@ class ProgressBroadcastForwarder(
|
||||
}
|
||||
|
||||
|
||||
private fun sendBroadcast(dto: JobProgressUpdateBroadcastDTO) {
|
||||
val intent = JobProgressUpdateBroadcast.getIntent(dto)
|
||||
|
||||
when {
|
||||
AppBuildConfig.USE_LOCAL_BROADCASTS ->
|
||||
LocalBroadcastManager
|
||||
.getInstance(context.applicationContext)
|
||||
.sendBroadcast(intent)
|
||||
else ->
|
||||
context
|
||||
.sendBroadcast(intent.apply { `package` = context.packageName })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called by the worker service to notify the forwarder that the currently referenced procedure
|
||||
* is starting.
|
||||
*/
|
||||
override fun onProcedureStart(startActionIndex: Int) {
|
||||
currentActionIdx = startActionIndex
|
||||
prevActionsProgressWeight = jobEntity.jobProcedure
|
||||
prevActionsProgressWeight = job.jobProcedure
|
||||
.subList(0, currentActionIdx!!)
|
||||
.map { it.progressWeight }
|
||||
.sum()
|
||||
|
||||
println("-> onProcedureStart job $jobId, startAt $startActionIndex, " +
|
||||
val isCheckpoint = currentActionIdx!! > 0
|
||||
val messageResId = if (isCheckpoint) R.string.resuming_job else R.string.starting_job
|
||||
|
||||
Log.d(TAG, "-> onProcedureStart job $jobId, startAt $startActionIndex, " +
|
||||
"currentAction $currentActionIdx, prevProgress: $prevActionsProgressWeight")
|
||||
//context.getString(R.string.starting_job)
|
||||
val dto = JobProgressUpdateBroadcastDTO(
|
||||
jobId = jobId,
|
||||
indefinite = true,
|
||||
step = currentActionIdx!!,
|
||||
currentMessage = context.getString(messageResId)
|
||||
)
|
||||
sendBroadcast(dto)
|
||||
}
|
||||
|
||||
|
||||
@@ -55,8 +87,20 @@ class ProgressBroadcastForwarder(
|
||||
*/
|
||||
override fun onProcedureDone() {
|
||||
assertProcedureStarted()
|
||||
// TODO: stub
|
||||
println("-> onProcedureDone job $jobId action $currentActionIdx")
|
||||
|
||||
Log.d(TAG, "-> onProcedureDone job $jobId action $currentActionIdx")
|
||||
|
||||
// Ensure no more updates are sent after the procedure is done
|
||||
currentActionIdx = null
|
||||
|
||||
val dto = JobProgressUpdateBroadcastDTO(
|
||||
jobId = jobId,
|
||||
showProgressBar = false,
|
||||
percentage = 100.0,
|
||||
completed = true,
|
||||
currentMessage = context.getString(R.string.done)
|
||||
)
|
||||
sendBroadcast(dto)
|
||||
}
|
||||
|
||||
|
||||
@@ -67,8 +111,19 @@ class ProgressBroadcastForwarder(
|
||||
override fun onProcedureError(error: Throwable) {
|
||||
assertProcedureStarted()
|
||||
// TODO: stub
|
||||
println("-> onProcedureError job $jobId action $currentActionIdx")
|
||||
error.printStackTrace()
|
||||
Log.d(TAG, "-> onProcedureError job $jobId action $currentActionIdx")
|
||||
|
||||
// Ensure no more updates are sent after the procedure failed
|
||||
currentActionIdx = null
|
||||
|
||||
val dto = JobProgressUpdateBroadcastDTO(
|
||||
jobId = jobId,
|
||||
showProgressBar = false,
|
||||
completed = true,
|
||||
currentMessage = context.getString(R.string.job_failed),
|
||||
error = error
|
||||
)
|
||||
sendBroadcast(dto)
|
||||
}
|
||||
|
||||
|
||||
@@ -80,8 +135,25 @@ class ProgressBroadcastForwarder(
|
||||
*/
|
||||
override fun onWorkerProgress(dto: ProgressUpdateDTO) {
|
||||
assertProcedureStarted()
|
||||
// TODO: stub
|
||||
println(" -> onWorkerProgress job $jobId action $currentActionIdx dto $dto")
|
||||
|
||||
val currentActionWeight = procedure[currentActionIdx!!].progressWeight
|
||||
val indefinite = dto.progress == null
|
||||
val progress: Double? =
|
||||
if (!indefinite)
|
||||
prevActionsProgressWeight!! + dto.progress!!.toDouble() * currentActionWeight
|
||||
else
|
||||
null
|
||||
|
||||
Log.d(TAG, " -> onWorkerProgress job $jobId action $currentActionIdx dto $dto")
|
||||
|
||||
val broadcastDTO = JobProgressUpdateBroadcastDTO(
|
||||
jobId = jobId,
|
||||
showProgressBar = true,
|
||||
indefinite = indefinite,
|
||||
percentage = if (!indefinite) progress!!.toDouble() / totalProgressWeights * 100 else null,
|
||||
step = currentActionIdx!!
|
||||
)
|
||||
sendBroadcast(broadcastDTO)
|
||||
}
|
||||
|
||||
|
||||
@@ -93,10 +165,17 @@ class ProgressBroadcastForwarder(
|
||||
override fun onActionStart(actionIndex: Int) {
|
||||
assertProcedureStarted()
|
||||
currentActionIdx = actionIndex
|
||||
prevActionsProgressWeight = prevActionsProgressWeight!!.plus(jobEntity.jobProcedure[actionIndex].progressWeight)
|
||||
|
||||
// TODO: stub
|
||||
println(" -> onActionStart job $jobId action $currentActionIdx")
|
||||
Log.d(TAG, " -> onActionStart job $jobId action $currentActionIdx")
|
||||
|
||||
val dto = JobProgressUpdateBroadcastDTO(
|
||||
jobId = jobId,
|
||||
showProgressBar = true,
|
||||
indefinite = false,
|
||||
percentage = prevActionsProgressWeight!!.toDouble() / totalProgressWeights * 100,
|
||||
step = currentActionIdx!!
|
||||
)
|
||||
sendBroadcast(dto)
|
||||
}
|
||||
|
||||
|
||||
@@ -108,7 +187,14 @@ class ProgressBroadcastForwarder(
|
||||
*/
|
||||
override fun onActionDone() {
|
||||
assertProcedureStarted()
|
||||
// TODO: stub
|
||||
println(" -> onActionDone job $jobId action $currentActionIdx")
|
||||
prevActionsProgressWeight = prevActionsProgressWeight!!.plus(job.jobProcedure[currentActionIdx!!].progressWeight)
|
||||
|
||||
Log.d(TAG, " -> onActionDone job $jobId action $currentActionIdx")
|
||||
|
||||
// We don't really need to broadcast this event
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TAG = ".s.j.PrgBcastFw"
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,23 @@
|
||||
package eu.depau.etchdroid.utils.worker.dto
|
||||
|
||||
import android.os.Parcel
|
||||
import eu.depau.etchdroid.utils.StringResBuilder
|
||||
import eu.depau.etchdroid.utils.worker.enums.RateUnit
|
||||
import eu.depau.kotlet.android.parcelable.*
|
||||
|
||||
data class ProgressUpdateDTO(
|
||||
val progress: Double?,
|
||||
val rate: Double?,
|
||||
val rateUnit: RateUnit?
|
||||
val rateUnit: RateUnit?,
|
||||
val message: StringResBuilder? = null
|
||||
) : KotletParcelable {
|
||||
constructor(parcel: Parcel) : this(
|
||||
progress = parcel.readNullable { parcel.readDouble() },
|
||||
rate = parcel.readNullable { parcel.readDouble() },
|
||||
rateUnit = parcel.readNullable { parcel.readEnum<RateUnit>() }
|
||||
rateUnit = parcel.readNullable { parcel.readEnum<RateUnit>() },
|
||||
message = parcel.readNullable {
|
||||
(parcel.readParcelable(StringResBuilder::class.java.classLoader) as StringResBuilder?)!!
|
||||
}
|
||||
)
|
||||
|
||||
override fun writeToParcel(parcel: Parcel, flags: Int) {
|
||||
@@ -20,6 +25,7 @@ data class ProgressUpdateDTO(
|
||||
writeNullable(progress) { writeDouble(it) }
|
||||
writeNullable(rate) { writeDouble(it) }
|
||||
writeNullable(rateUnit) { writeEnum(rateUnit) }
|
||||
writeNullable(message) { writeParcelable(message, flags) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -158,5 +158,9 @@
|
||||
<string name="notif_channel_job_result_name">Job outcome</string>
|
||||
<string name="notif_channel_job_result_desc">Used to show a completed job outcome</string>
|
||||
<string name="notif_starting_job">Starting job...</string>
|
||||
<string name="starting_job">Starting job...</string>
|
||||
<string name="resuming_job">Resuming from checkpoint...</string>
|
||||
<string name="done">Done.</string>
|
||||
<string name="job_failed">Job failed.</string>
|
||||
|
||||
</resources>
|
||||
@@ -0,0 +1,14 @@
|
||||
package android.util;
|
||||
|
||||
public class Log {
|
||||
public static int d(java.lang.String tag, java.lang.String message) {
|
||||
System.out.println(String.format("[DEBUG] %s: %s", tag, message));
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int d(java.lang.String tag, java.lang.String message, java.lang.Throwable throwable) {
|
||||
d(tag, message);
|
||||
throwable.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package eu.depau.etchdroid.broadcasts
|
||||
|
||||
import android.content.Intent
|
||||
import eu.depau.etchdroid.broadcasts.dto.JobProgressUpdateBroadcastDTO
|
||||
import org.mockito.Mockito
|
||||
import org.mockito.Mockito.any
|
||||
import org.mockito.Mockito.mock
|
||||
import java.io.Serializable
|
||||
|
||||
/**
|
||||
* Mock reimplementation that shadows the original in order to return mock intents
|
||||
*/
|
||||
object JobProgressUpdateBroadcast {
|
||||
const val ACTION = "eu.depau.etchdroid.broadcast.JOB_PROGRESS_UPDATE"
|
||||
|
||||
fun getIntent(dto: JobProgressUpdateBroadcastDTO) = mock(Intent::class.java).apply {
|
||||
action = ACTION
|
||||
|
||||
// Simulate intent put/get extra logic
|
||||
val extras = mutableMapOf<String, Serializable>()
|
||||
|
||||
Mockito
|
||||
.`when`(this.putExtra(any(), any(Serializable::class.java)))
|
||||
.thenAnswer {
|
||||
val extra = it.arguments[0] as String
|
||||
val serializable = it.arguments[1] as Serializable
|
||||
extras[extra] = serializable
|
||||
this
|
||||
}
|
||||
|
||||
Mockito
|
||||
.`when`(this.getSerializableExtra(any()))
|
||||
.thenAnswer {
|
||||
val extra = it.arguments[0] as String
|
||||
extras[extra]
|
||||
}
|
||||
|
||||
|
||||
dto.writeToIntent(this)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@ package eu.depau.etchdroid.services
|
||||
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import eu.depau.etchdroid.AppBuildConfig
|
||||
import eu.depau.etchdroid.broadcasts.dto.JobProgressUpdateBroadcastDTO
|
||||
import eu.depau.etchdroid.db.EtchDroidDatabase
|
||||
import eu.depau.etchdroid.db.entity.Job
|
||||
import eu.depau.etchdroid.db.repository.JobRepository
|
||||
@@ -31,6 +33,8 @@ internal class JobIntentHandlerTest {
|
||||
fun setUp() {
|
||||
// Used by JobServiceNotificationHandler to avoid building real notifications when testing
|
||||
AppBuildConfig.TEST_BUILD = true
|
||||
// Make sure the app uses Context to send broadcasts, so it's mocked
|
||||
AppBuildConfig.USE_LOCAL_BROADCASTS = false
|
||||
|
||||
// Mock eu.depau.etchdroid.services.job.JobService
|
||||
mockService = mock(JobService::class.java)
|
||||
@@ -103,6 +107,14 @@ internal class JobIntentHandlerTest {
|
||||
.`when`(jobRepo!!.getById(jobId))
|
||||
.thenReturn(job)
|
||||
|
||||
Mockito
|
||||
.`when`(mockService!!.sendBroadcast(any()))
|
||||
.thenAnswer {
|
||||
val intent = it.arguments[0] as Intent
|
||||
println("))) BROADCAST ((( ${intent.getSerializableExtra(JobProgressUpdateBroadcastDTO.EXTRA)}")
|
||||
Unit
|
||||
}
|
||||
|
||||
// Pass it to the intent handler
|
||||
val intentHandler = JobIntentHandler(mockService!!, JobServiceIntentDTO(jobId))
|
||||
intentHandler.handle()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package eu.depau.etchdroid.testutils.worker
|
||||
|
||||
import android.util.Log
|
||||
import eu.depau.etchdroid.utils.worker.enums.RateUnit
|
||||
import eu.depau.etchdroid.utils.worker.impl.AbstractAutoProgressAsyncWorker
|
||||
|
||||
@@ -16,7 +17,7 @@ open class MockJobWorker(val startAt: Int, val steps: Int) : AbstractAutoProgres
|
||||
*/
|
||||
override fun runStep(): Boolean {
|
||||
counter++
|
||||
println(" -- Worker counts $counter/$steps")
|
||||
Log.d(".t.MockJobWorkr", " -- Worker counts $counter/$steps")
|
||||
progressUpdate(1)
|
||||
Thread.sleep(sleepTime)
|
||||
return counter < steps
|
||||
|
||||
Reference in new issue
Block a user