1 /* 2 * Copyright (C) 2023 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.settings.datausage.lib 18 19 import android.content.Context 20 import android.net.NetworkTemplate 21 import android.util.Range 22 import com.android.settings.datausage.lib.NetworkCycleDataRepository.Companion.asFourWeeks 23 import com.android.settings.datausage.lib.NetworkCycleDataRepository.Companion.bucketRange 24 import com.android.settings.datausage.lib.NetworkCycleDataRepository.Companion.getCycles 25 import com.android.settings.datausage.lib.NetworkStatsRepository.Companion.Bucket 26 import com.android.settings.datausage.lib.NetworkStatsRepository.Companion.aggregate 27 import com.android.settings.datausage.lib.NetworkStatsRepository.Companion.filterTime 28 29 class NetworkCycleBucketRepository( 30 context: Context, 31 networkTemplate: NetworkTemplate, 32 private val buckets: List<Bucket>, 33 private val networkCycleDataRepository: NetworkCycleDataRepository = 34 NetworkCycleDataRepository(context, networkTemplate) 35 ) { 36 loadCyclesnull37 fun loadCycles(): List<NetworkUsageData> = 38 getCycles().map { aggregateUsage(it) }.filter { it.usage > 0 } 39 getCyclesnull40 private fun getCycles(): List<Range<Long>> = 41 networkCycleDataRepository.getPolicy()?.getCycles().orEmpty() 42 .ifEmpty { queryCyclesAsFourWeeks() } 43 queryCyclesAsFourWeeksnull44 private fun queryCyclesAsFourWeeks(): List<Range<Long>> = 45 buckets.aggregate()?.timeRange.asFourWeeks() 46 47 fun queryChartData(usageData: NetworkUsageData) = NetworkCycleChartData( 48 total = usageData, 49 dailyUsage = bucketRange( 50 startTime = usageData.startTime, 51 endTime = usageData.endTime, 52 step = NetworkCycleChartData.BUCKET_DURATION.inWholeMilliseconds, 53 ).map { aggregateUsage(it) }, 54 ) 55 aggregateUsagenull56 private fun aggregateUsage(range: Range<Long>) = NetworkUsageData( 57 startTime = range.lower, 58 endTime = range.upper, 59 usage = buckets.filterTime(range.lower, range.upper).aggregate()?.usage ?: 0, 60 ) 61 } 62