Skip to content

Commit

Permalink
Fix issue: #97, #96, #78
Browse files Browse the repository at this point in the history
  • Loading branch information
soowon-kang committed Dec 6, 2020
1 parent 10c36ed commit 95b4f13
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ class SurveyCollector(
val timestamp = System.currentTimeMillis()

if (intent?.action == ACTION_SCHEDULE) {
Log.d(javaClass, "schedule broadcast received: id: ${intent.getLongExtra(EXTRA_SURVEY_ID, 0)}, timestamp: $timestamp")
handleSchedule(intent.getLongExtra(EXTRA_SURVEY_ID, 0), timestamp, null)
}
}
Expand All @@ -58,19 +59,31 @@ class SurveyCollector(
override fun isAvailable(): Boolean = configurations.isNotEmpty()

override fun getDescription(): Array<Description> = arrayOf(
R.string.collector_survey_info_base_date with formatDateTime(context, baseScheduleDate)
R.string.collector_survey_info_base_date with formatDateTime(context, this.baseScheduleDate)
)

override val permissions: List<String> = listOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)

override val setupIntent: Intent? = Intent(context, SurveySettingActivity::class.java)
override val setupIntent: Intent = Intent(context, SurveySettingActivity::class.java)

private val schedulingIntent by lazy {
PendingIntent.getBroadcast(
context, REQUEST_CODE_ACTION_SCHEDULE,
Intent(ACTION_SCHEDULE),
PendingIntent.FLAG_UPDATE_CURRENT
)
}

private val alarmManager by lazy {
context.getSystemService<AlarmManager>()!!
}

override suspend fun onStart() {
if (baseScheduleDate < 0) {
baseScheduleDate = System.currentTimeMillis()
if (this.baseScheduleDate < 0) {
this.baseScheduleDate = System.currentTimeMillis()
}

EventBus.register(this)
Expand All @@ -79,39 +92,26 @@ class SurveyCollector(
addAction(ACTION_EMPTY)
})

val timestamp = System.currentTimeMillis()
handleSchedule(0, timestamp, null)
handleSchedule(0, System.currentTimeMillis(), null)
}

override suspend fun onStop() {
EventBus.unregister(this)
context.safeUnregisterReceiver(receiver)

val alarmManager = context.getSystemService<AlarmManager>() ?: return

val triggerIntent = PendingIntent.getBroadcast(
context, REQUEST_CODE_ACTION_SCHEDULE,
Intent(ACTION_SCHEDULE),
PendingIntent.FLAG_NO_CREATE
)

if (triggerIntent != null) {
alarmManager.cancel(triggerIntent)
}
}

override suspend fun count(): Long = dataRepository.count<SurveyEntity>()

override suspend fun flush(entities: Collection<SurveyEntity>) {
dataRepository.remove(entities)
recordsUploaded += entities.size
this.recordsUploaded += entities.size
}

override suspend fun list(limit: Long): Collection<SurveyEntity> = dataRepository.find(0, limit)

@Subscribe(threadMode = ThreadMode.BACKGROUND)
fun onEvent(event: Event) {
val events = configurations.flatMap { setting ->
val events = this.configurations.flatMap { setting ->
(setting.survey.intraDaySchedule as? EventSchedule)?.let {
it.eventsTrigger + it.eventsCancel
} ?: listOf()
Expand Down Expand Up @@ -165,13 +165,15 @@ class SurveyCollector(

if (dateCurrent + DAYS_MARGIN_FOR_SCHEDULE < dateFrom) return

val dateTo = if (survey.timeTo.isNone()) {
var dateTo: LocalDate = if (survey.timeTo.isNone()) {
dateFrom + DAYS_SCHEDULE
} else {
dateBase + survey.timeTo
}

if (dateTo < dateCurrent) return
if (dateTo < dateCurrent) {
dateTo = dateCurrent + DAYS_MARGIN_FOR_SCHEDULE
}

val scheduledDates = scheduleInterDay(
dateFrom, dateTo, interDaySchedule
Expand Down Expand Up @@ -245,8 +247,6 @@ class SurveyCollector(
order(InternalSurveyEntity_.intendedTriggerTime)
}

val alarmManager = context.getSystemService<AlarmManager>() ?: return

if (upcomingSchedule == null) {
val triggerIntent = PendingIntent.getBroadcast(
context, REQUEST_CODE_ACTION_SCHEDULE,
Expand Down Expand Up @@ -280,6 +280,8 @@ class SurveyCollector(
showIntent,
triggerIntent
)

Log.d(javaClass, "timer(): upcomingSchedule; id: ${upcomingSchedule.id}, alarm at: ${upcomingSchedule.intendedTriggerTime}")
}
}

Expand All @@ -300,12 +302,14 @@ class SurveyCollector(
}

val updateEntity = entity.copy(actualTriggerTime = timestamp)
put(updateEntity) // temporary entity that will be notified but not be responded yet.
put(updateEntity, isStatUpdates = false) // temporary entity that will be notified but not be responded yet.

responses.forEach {
put(it, isStatUpdates = false)
}

Log.d(javaClass, "trigger() at: $timestamp")

NotificationRepository.notifySurvey(
context = context,
timestamp = timestamp,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,17 @@ import kaist.iclab.abclogger.ui.base.BaseViewModel
import kaist.iclab.abclogger.collector.survey.*
import kaist.iclab.abclogger.commons.AbcError
import kaist.iclab.abclogger.commons.EntityError
import kaist.iclab.abclogger.core.AuthRepository
import kaist.iclab.abclogger.core.EventBus
import kaist.iclab.abclogger.core.Log
import kaist.iclab.abclogger.grpc.proto.DatumProtos.Survey.getDefaultInstance
import kaist.iclab.abclogger.structure.survey.Survey
import kaist.iclab.abclogger.ui.State
import kaist.iclab.abclogger.ui.survey.list.SurveyPagingSource
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import java.util.*

class SurveyViewModel(
private val dataRepository: DataRepository,
Expand Down Expand Up @@ -54,7 +58,8 @@ class SurveyViewModel(
}

suspend fun listAnswered() : Flow<PagingData<InternalSurveyEntity>> {
prepareSync(System.currentTimeMillis())
val curTime = System.currentTimeMillis()
prepareSync(curTime)

return Pager(PagingConfig(10)) {
SurveyPagingSource(dataRepository) {
Expand Down Expand Up @@ -88,7 +93,7 @@ class SurveyViewModel(
return Pager(PagingConfig(10)) {
SurveyPagingSource(dataRepository) {
greater(InternalSurveyEntity_.actualTriggerTime, 0)
equal(InternalSurveyEntity_.isTransferredToSync, false)
//equal(InternalSurveyEntity_.isTransferredToSync, false)
less(InternalSurveyEntity_.timeoutUntil, curTime)
equal(
InternalSurveyEntity_.timeoutAction,
Expand Down Expand Up @@ -121,8 +126,23 @@ class SurveyViewModel(
responses.forEach { dataRepository.put(it) }

val answeredSurveyEntity = toSurveyEntity(updatedSurvey, responses)
answeredSurveyEntity.apply {
utcOffset = TimeZone.getDefault().rawOffset / 1000
groupName = AuthRepository.groupName
email = AuthRepository.email
instanceId = AuthRepository.instanceId
source = AuthRepository.source
deviceManufacturer = AuthRepository.deviceManufacturer
deviceModel = AuthRepository.deviceModel
deviceVersion = AuthRepository.deviceVersion
deviceOs = AuthRepository.deviceOs
appId = AuthRepository.appId
appVersion = AuthRepository.appVersion
}
//val answeredSurveyEntity = getDefaultInstance()
dataRepository.put(answeredSurveyEntity)
EventBus.post(answeredSurveyEntity)
Log.d(javaClass, answeredSurveyEntity)
saveStatusChannel.send(State.Success(Unit))
} catch (e: Exception) {
saveStatusChannel.send(State.Failure(AbcError.wrap(e)))
Expand All @@ -131,6 +151,8 @@ class SurveyViewModel(

private suspend fun prepareSync(timestamp: Long) = withContext(ioContext) {
try {
saveStatusChannel.send(State.Loading)

val expiredEntities = dataRepository.find<InternalSurveyEntity> {
greater(InternalSurveyEntity_.actualTriggerTime, 0)
equal(InternalSurveyEntity_.isTransferredToSync, false)
Expand All @@ -146,9 +168,27 @@ class SurveyViewModel(
toSurveyEntity(survey, responses)
}
expiredEntities.forEach {
it.apply {
utcOffset = TimeZone.getDefault().rawOffset / 1000
groupName = AuthRepository.groupName
email = AuthRepository.email
instanceId = AuthRepository.instanceId
source = AuthRepository.source
deviceManufacturer = AuthRepository.deviceManufacturer
deviceModel = AuthRepository.deviceModel
deviceVersion = AuthRepository.deviceVersion
deviceOs = AuthRepository.deviceOs
appId = AuthRepository.appId
appVersion = AuthRepository.appVersion
}
dataRepository.put(it)
EventBus.post(it)
Log.d(javaClass, it)
}
} catch (e: Exception) { }
saveStatusChannel.send(State.Success(Unit))
} catch (e: Exception) {
saveStatusChannel.send(State.Failure(AbcError.wrap(e)))
}
}

/**
Expand Down Expand Up @@ -182,8 +222,9 @@ class SurveyViewModel(
answer = response.answer.main + response.answer.other
)
}
)/*.apply {
id = survey.id // error: ID is higher or equal to internal ID sequence: 1 (vs. 1). Use ID 0 (zero) to insert new entities.
instanceId = survey.id.toString() // instanceId is uuid for each participant defined by AuthRepository.
}*/
).apply {
this.timestamp = System.currentTimeMillis()
//id = survey.id // error: ID is higher or equal to internal ID sequence: 1 (vs. 1). Use ID 0 (zero) to insert new entities.
//instanceId = survey.id.toString() // instanceId is uuid for each participant defined by AuthRepository.
}
}

0 comments on commit 95b4f13

Please sign in to comment.