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.adservices.data.common; 18 19 import android.content.pm.PackageManager; 20 21 import androidx.annotation.NonNull; 22 23 import com.android.adservices.service.common.AllowLists; 24 import com.android.adservices.service.common.compat.PackageManagerCompatUtils; 25 26 import java.util.ArrayList; 27 import java.util.List; 28 import java.util.Set; 29 import java.util.stream.Collectors; 30 31 /** Contains utility functions for cleaning up data from disallowed apps. */ 32 public final class CleanupUtils { 33 34 /** 35 * Takes a list of packages which may or may not be allowed to use PPAPIs and removes all the 36 * packages that are allowed to use PPAPIs. 37 * 38 * @param packages a list of package names 39 * @param packageManager the package manager 40 * @param appAllowLists the allowlist(s) for the relevant API(s). Packages are kept if they are 41 * present in any of the listed allowlists. 42 */ removeAllowedPackages( @onNull List<String> packages, @NonNull PackageManager packageManager, @NonNull List<String> appAllowLists)43 public static void removeAllowedPackages( 44 @NonNull List<String> packages, 45 @NonNull PackageManager packageManager, 46 @NonNull List<String> appAllowLists) { 47 if (!packages.isEmpty()) { 48 Set<String> allowedPackages = 49 PackageManagerCompatUtils.getInstalledApplications(packageManager, 0).stream() 50 .map(applicationInfo -> applicationInfo.packageName) 51 .collect(Collectors.toSet()); 52 boolean allowAll = false; 53 List<String> allowedApps = new ArrayList<>(); 54 for (String appAllowList : appAllowLists) { 55 allowAll = allowAll || AllowLists.doesAllowListAllowAll(appAllowList); 56 allowedApps.addAll(AllowLists.splitAllowList(appAllowList)); 57 } 58 if (!allowAll) { 59 allowedPackages.retainAll(allowedApps); 60 } 61 62 // Packages must be both installed and allowlisted, or else they should be removed 63 packages.removeAll(allowedPackages); 64 } 65 } 66 } 67