-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
SyncWorker.kt
582 lines (547 loc) · 21 KB
/
SyncWorker.kt
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/*
* VoIP.ms SMS
* Copyright (C) 2017-2021 Michael Kourlas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kourlas.voipms_sms.sms.workers
import android.app.ForegroundServiceStartNotAllowedException
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.ForegroundInfo
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.OutOfQuotaPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import com.squareup.moshi.JsonClass
import com.squareup.moshi.JsonDataException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.ensureActive
import net.kourlas.voipms_sms.R
import net.kourlas.voipms_sms.database.Database
import net.kourlas.voipms_sms.network.NetworkManager
import net.kourlas.voipms_sms.notifications.Notifications
import net.kourlas.voipms_sms.preferences.accountConfigured
import net.kourlas.voipms_sms.preferences.didsConfigured
import net.kourlas.voipms_sms.preferences.getDids
import net.kourlas.voipms_sms.preferences.getEmail
import net.kourlas.voipms_sms.preferences.getPassword
import net.kourlas.voipms_sms.preferences.getRetrieveDeletedMessages
import net.kourlas.voipms_sms.preferences.getRetrieveOnlyRecentMessages
import net.kourlas.voipms_sms.preferences.getStartDate
import net.kourlas.voipms_sms.preferences.getSyncInterval
import net.kourlas.voipms_sms.sms.ConversationId
import net.kourlas.voipms_sms.utils.httpPostWithMultipartFormData
import net.kourlas.voipms_sms.utils.logException
import net.kourlas.voipms_sms.utils.toBoolean
import net.kourlas.voipms_sms.utils.validatePhoneNumber
import java.io.IOException
import java.net.URLEncoder
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import java.util.concurrent.TimeUnit
import kotlin.math.ceil
/**
* Worker used to synchronize the database with VoIP.ms.
*/
class SyncWorker(context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
private var error: String? = null
private var progress: Int = 0
override suspend fun doWork(): Result {
try {
// Perform database synchronization.
handleSync()
return if (error == null) {
Result.success()
} else {
Log.w("tag", error ?: "")
Result.failure()
}
} finally {
// Send a broadcast indicating that the database has been
// synchronized or an attempt has been made to synchronize it.
val syncCompleteBroadcastIntent = Intent(
applicationContext.getString(
R.string.sync_complete_action
)
)
syncCompleteBroadcastIntent.putExtra(
applicationContext.getString(
R.string.sync_complete_error
), error
)
if (!inputData.getBoolean(
applicationContext.getString(
R.string.sync_force_recent
), false
)
) {
syncCompleteBroadcastIntent.putExtra(
applicationContext.getString(
R.string.sync_complete_full
), true
)
}
syncCompleteBroadcastIntent.setPackage(
applicationContext.packageName
)
applicationContext.sendBroadcast(syncCompleteBroadcastIntent)
}
}
override suspend fun getForegroundInfo(): ForegroundInfo {
val notification = Notifications.getInstance(applicationContext)
.getSyncDatabaseNotification(id, progress)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ForegroundInfo(
Notifications.SYNC_DATABASE_NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
)
} else {
ForegroundInfo(
Notifications.SYNC_DATABASE_NOTIFICATION_ID,
notification
)
}
}
/**
* Perform synchronization.
*/
private suspend fun handleSync() {
try {
val forceRecent = inputData.getBoolean(
applicationContext.getString(R.string.sync_force_recent), false
)
// Terminate quietly if it is impossible to sync due to account
// configuration, unless it is a full sync.
if (!accountConfigured(applicationContext)) {
if (!forceRecent) {
error = applicationContext.getString(
R.string.sync_error_account
)
}
return
}
if (!didsConfigured(applicationContext)) {
if (!forceRecent) {
error = applicationContext.getString(
R.string.sync_error_dids
)
}
return
}
// Terminate if no network connection is available.
if (!NetworkManager.getInstance().isNetworkConnectionAvailable(
applicationContext
)
) {
error = applicationContext.getString(
R.string.sync_error_network
)
return
}
// Retrieve all messages from VoIP.ms, or only those messages
// dated after the most recent message stored locally
val retrieveOnlyRecentMessages =
forceRecent || getRetrieveOnlyRecentMessages(applicationContext)
// Retrieve messages from VoIP.ms that were deleted locally
val retrieveDeletedMessages =
!forceRecent && getRetrieveDeletedMessages(applicationContext)
// Process retrieval requests separately
val retrievalRequests = createRetrievalRequests(
retrieveOnlyRecentMessages
)
processRequests(retrievalRequests, retrieveDeletedMessages)
} catch (e: CancellationException) {
// We need to propagate the exception from processRequests
error = applicationContext.getString(R.string.sync_error_cancelled)
throw e
} catch (e: Exception) {
logException(e)
error = applicationContext.getString(
R.string.sync_error_unknown
)
}
}
/**
* Generates a set of requests for retrieving messages from VoIP.ms.
*
* @param retrieveOnlyRecentMessages Whether or not the constructed
* retrieval requests should date back to the most recent message or the
* message retrieval start date.
*/
private suspend fun createRetrievalRequests(
retrieveOnlyRecentMessages: Boolean
): List<RetrievalRequest> {
val retrievalRequests = mutableListOf<RetrievalRequest>()
val dids = getDids(applicationContext, onlyRetrieveMessages = true)
val encodedDids = dids.map { URLEncoder.encode(it, "UTF-8") }
// Get number of days between now and the message retrieval start
// date or when the most recent message was received, as appropriate;
// note that EDT is used throughout because the VoIP.ms API only works
// with EDT
val mostRecentMessage = Database.getInstance(applicationContext)
.getMessageMostRecent(dids)
val thenCalendar = Calendar.getInstance(
TimeZone.getTimeZone("America/New_York"), Locale.US
)
thenCalendar.time = if (mostRecentMessage == null
|| !retrieveOnlyRecentMessages
) {
getStartDate(applicationContext)
} else {
mostRecentMessage.date
}
thenCalendar.set(Calendar.HOUR_OF_DAY, 0)
thenCalendar.set(Calendar.MINUTE, 0)
thenCalendar.set(Calendar.SECOND, 0)
thenCalendar.set(Calendar.MILLISECOND, 0)
val then = thenCalendar.time
val nowCalendar = Calendar.getInstance(
TimeZone.getTimeZone("America/New_York"), Locale.US
)
nowCalendar.time = Date()
nowCalendar.set(Calendar.HOUR_OF_DAY, 0)
nowCalendar.set(Calendar.MINUTE, 0)
nowCalendar.set(Calendar.SECOND, 0)
nowCalendar.set(Calendar.MILLISECOND, 0)
val now = nowCalendar.time
val daysDifference = ceil(
((now.time - then.time) / (1000 * 60 * 60 * 24)).toDouble()
)
.toLong()
// Split this number into 90 day periods (which is approximately the
// maximum supported by the VoIP.ms API); note that the first period
// is intentionally the oldest
var daysRemaining = daysDifference
val periods = mutableListOf<Pair<Date, Date>>()
while (daysRemaining > 90L) {
val last = if (periods.isEmpty()) then else periods.last().second
val calendar = Calendar.getInstance(
TimeZone.getTimeZone("America/New_York"), Locale.US
)
calendar.time = last
calendar.add(Calendar.DAY_OF_YEAR, 90)
periods.add(Pair(last, calendar.time))
daysRemaining -= 90L
}
if (periods.isEmpty()) {
periods.add(Pair(then, now))
} else {
periods.add(Pair(periods.last().second, now))
}
// Create VoIP.ms API retrieval request for each of these periods
// and for each DID
val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.US)
sdf.timeZone = TimeZone.getTimeZone("America/New_York")
for (period in periods) {
encodedDids
.map {
mapOf(
"api_username" to getEmail(applicationContext),
"api_password" to getPassword(applicationContext),
"method" to "getMMS",
"did" to it,
"limit" to "1000000",
"from" to sdf.format(period.first),
"to" to sdf.format(period.second),
"timezone" to "-5",
"all_messages" to "1",
) // -5 corresponds to EDT
}
.mapTo(retrievalRequests) {
RetrievalRequest(it, period)
}
}
return retrievalRequests
}
/**
* Processes the specified requests using the VoIP.ms API.
*
* @param retrievalRequests The retrieval requests to process.
* @param retrieveDeletedMessages If true, messages are retrieved from
* VoIP.ms even after being deleted locally.
*/
private suspend fun processRequests(
retrievalRequests: List<RetrievalRequest>,
retrieveDeletedMessages: Boolean
) = coroutineScope {
val incomingMessages = mutableListOf<IncomingMessage>()
for (i in retrievalRequests.indices) {
ensureActive()
val nextIncomingMessages = processRetrievalRequest(
retrievalRequests[i]
)
if (nextIncomingMessages != null) {
incomingMessages.addAll(nextIncomingMessages)
} else {
return@coroutineScope
}
progress = ((i + 1) * 100) / retrievalRequests.size
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
setForeground(getForegroundInfo())
} else {
try {
setForeground(getForegroundInfo())
} catch (_: ForegroundServiceStartNotAllowedException) {
// Do nothing -- this is expected if the app is running in
// the background.
}
}
}
// Add new messages from the server
val newConversationIds: Set<ConversationId>
try {
newConversationIds = Database.getInstance(
applicationContext
)
.insertMessagesVoipMsApi(
incomingMessages,
retrieveDeletedMessages
)
} catch (e: Exception) {
logException(e)
error = applicationContext.getString(
R.string.sync_error_database
)
return@coroutineScope
}
// Show notifications for new messages
if (newConversationIds.isNotEmpty()) {
Notifications.getInstance(applicationContext).showNotifications(
newConversationIds
)
}
}
@JsonClass(generateAdapter = true)
data class MessageResponse(
val date: String,
val id: String,
val type: String,
val did: String,
val contact: String,
val message: String?,
val col_media1: String?,
val col_media2: String?,
val col_media3: String?,
)
@JsonClass(generateAdapter = true)
data class MessagesResponse(
val status: String,
val sms: List<MessageResponse>?
)
/**
* Processes the specified retrieval request using the VoIP.ms API.
*
* @return Null if the request failed.
*/
private suspend fun processRetrievalRequest(
request: RetrievalRequest
): List<IncomingMessage>? {
val response = sendRequestWithVoipMsApi(request) ?: return null
// Extract messages from the VoIP.ms API response
val incomingMessages = mutableListOf<IncomingMessage>()
if (response.status != "success" && response.status != "no_sms") {
error = when (response.status) {
"invalid_credentials" -> applicationContext.getString(
R.string.sync_error_api_error_invalid_credentials
)
else -> applicationContext.getString(
R.string.sync_error_api_error,
response.status
)
}
return null
}
if (response.status != "no_sms") {
for (message in response.sms ?: emptyList()) {
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
sdf.timeZone = TimeZone.getTimeZone("America/New_York")
try {
if (message.message == null
&& message.col_media1 == null
&& message.col_media2 == null
&& message.col_media3 == null
) {
// This message is malformed.
continue
}
val incomingMessage = IncomingMessage(
message.id.toLong(),
sdf.parse(message.date) ?: throw Exception(
"Failed to parse date ${message.date}"
),
toBoolean(message.type),
message.did,
message.contact,
message.message,
message.col_media1,
message.col_media2,
message.col_media3
)
incomingMessages.add(incomingMessage)
} catch (e: Exception) {
logException(e)
error = applicationContext.getString(
R.string.sync_error_api_parse
)
return null
}
}
}
return incomingMessages
}
/**
* Performs a GET request using the specified url and parses the response
* as JSON.
*/
private suspend fun sendRequestWithVoipMsApi(
request: RetrievalRequest
): MessagesResponse? {
try {
repeat(3) {
try {
return httpPostWithMultipartFormData(
applicationContext,
"https://voip.ms/api/v1/rest.php",
request.formData
)
} catch (e: IOException) {
// Try again...
}
}
error = applicationContext.getString(
R.string.sync_error_api_request
)
return null
} catch (e: JsonDataException) {
logException(e)
error = applicationContext.getString(R.string.sync_error_api_parse)
return null
} catch (e: Exception) {
logException(e)
error = applicationContext.getString(R.string.sync_error_unknown)
return null
}
}
/**
* A message received from the VoIP.ms API.
*
* @param voipId The VoIP.ms ID associated with the message.
* @param date The date that the message was received.
* @param isIncoming Whether or not the message was received or sent by the
* DID associated with the message.
* @param did The DID associated with the message.
* @param contact The contact associated with the message.
* @param text The text of the message.
* @param media1 The URI to the first media associated with the message.
* @param media2 The URI to the second media associated with the message.
* @param media3 The URI to the third media associated with the message.
*/
data class IncomingMessage(
val voipId: Long,
val date: Date,
val isIncoming: Boolean,
val did: String,
val contact: String,
val text: String?,
val media1: String?,
val media2: String?,
val media3: String?
) {
init {
validatePhoneNumber(did)
validatePhoneNumber(contact)
}
}
/**
* A request to the VoIP.ms API to retrieve the messages from the specified
* period using the specified URL.
*/
data class RetrievalRequest(
val formData: Map<String, String>,
private val period: Pair<Date, Date>
)
companion object {
/**
* Synchronize the database with VoIP.ms.
*
* @param customPeriod A custom period for synchronization, in
* fractions of a day. If not provided, the system configuration will
* be used.
* @param scheduleOnly Do not perform synchronization immediately.
*/
fun performFullSynchronization(
context: Context,
customPeriod: Double? = null,
scheduleOnly: Boolean = false
) {
val delayInterval = (
(customPeriod ?: getSyncInterval(context))
* (24 * 60 * 60 * 1000)).toLong()
if (delayInterval != 0L) {
val workRequest = PeriodicWorkRequestBuilder<SyncWorker>(
delayInterval,
TimeUnit.MILLISECONDS
)
if (scheduleOnly) {
workRequest.setInitialDelay(
delayInterval,
TimeUnit.MILLISECONDS
)
}
val work = workRequest.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
context.getString(R.string.sync_work_id),
ExistingPeriodicWorkPolicy.UPDATE,
work
)
} else if (!scheduleOnly) {
val work = OneTimeWorkRequestBuilder<SyncWorker>().build()
WorkManager.getInstance(context)
.enqueueUniqueWork(
context.getString(R.string.sync_work_id),
ExistingWorkPolicy.REPLACE, work
)
}
}
/**
* Check VoIP.ms for new messages.
*/
fun performPartialSynchronization(context: Context) {
val work = OneTimeWorkRequestBuilder<SyncWorker>().setInputData(
workDataOf(
context.getString(R.string.sync_force_recent) to true
)
).setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
context.getString(R.string.sync_partial_work_id),
ExistingWorkPolicy.KEEP, work
)
}
}
}