1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.statementservice.domain 18 19 import androidx.work.Constraints 20 import androidx.work.ExistingPeriodicWorkPolicy 21 import androidx.work.NetworkType 22 import androidx.work.PeriodicWorkRequestBuilder 23 import androidx.work.WorkManager 24 import com.android.statementservice.domain.worker.RetryRequestWorker 25 import java.time.Duration 26 27 object DomainVerificationUtils { 28 29 private const val PERIODIC_SHORT_ID = "retry_short" 30 private const val PERIODIC_SHORT_HOURS = 24L 31 private const val PERIODIC_LONG_ID = "retry_long" 32 private const val PERIODIC_LONG_HOURS = 72L 33 34 /** 35 * In a majority of cases, the initial requests will be enough to verify domains, since they 36 * are also restricted to [NetworkType.CONNECTED], but for cases where they aren't sufficient, 37 * attempts are also made on a periodic basis. 38 * 39 * Once per 24 hours, a check of all packages is done with [NetworkType.CONNECTED]. To avoid 40 * cases where a proxy or other unusual device configuration prevents [WorkManager] from 41 * running, also schedule a 3 day task without constraints which will force the check to run. 42 * 43 * The actual logic may be skipped if a request was previously run successfully or there are no 44 * more domains that need verifying. 45 */ schedulePeriodicCheckUnlockednull46 fun schedulePeriodicCheckUnlocked(workManager: WorkManager) { 47 workManager.apply { 48 PeriodicWorkRequestBuilder<RetryRequestWorker>(Duration.ofHours(PERIODIC_SHORT_HOURS)) 49 .setConstraints( 50 Constraints.Builder() 51 .setRequiredNetworkType(NetworkType.CONNECTED) 52 .setRequiresDeviceIdle(true) 53 .build() 54 ) 55 .build() 56 .let { 57 enqueueUniquePeriodicWork( 58 PERIODIC_SHORT_ID, 59 ExistingPeriodicWorkPolicy.KEEP, it 60 ) 61 } 62 PeriodicWorkRequestBuilder<RetryRequestWorker>(Duration.ofDays(PERIODIC_LONG_HOURS)) 63 .setConstraints( 64 Constraints.Builder() 65 .setRequiresDeviceIdle(true) 66 .build() 67 ) 68 .build() 69 .let { 70 enqueueUniquePeriodicWork( 71 PERIODIC_LONG_ID, 72 ExistingPeriodicWorkPolicy.KEEP, it 73 ) 74 } 75 } 76 } 77 } 78