1 /*
2  * Copyright 2022 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 androidx.privacysandbox.ads.adservices.java.appsetid
18 
19 import android.content.Context
20 import android.os.LimitExceededException
21 import androidx.annotation.DoNotInline
22 import androidx.privacysandbox.ads.adservices.appsetid.AppSetId
23 import androidx.privacysandbox.ads.adservices.appsetid.AppSetIdManager
24 import androidx.privacysandbox.ads.adservices.java.internal.asListenableFuture
25 import com.google.common.util.concurrent.ListenableFuture
26 import kotlinx.coroutines.CoroutineScope
27 import kotlinx.coroutines.Dispatchers
28 import kotlinx.coroutines.async
29 
30 /**
31  * AppSetIdManager provides APIs for app and ad-SDKs to access appSetId for non-monetizing purpose.
32  * This class can be used by Java clients.
33  */
34 abstract class AppSetIdManagerFutures internal constructor() {
35     /**
36      * Return the AppSetId.
37      *
38      * @throws SecurityException if caller is not authorized to call this API.
39      * @throws IllegalStateException if this API is not available.
40      * @throws LimitExceededException if rate limit was reached.
41      */
getAppSetIdAsyncnull42     abstract fun getAppSetIdAsync(): ListenableFuture<AppSetId>
43 
44     private class Api33Ext4JavaImpl(private val mAppSetIdManager: AppSetIdManager) :
45         AppSetIdManagerFutures() {
46         @DoNotInline
47         override fun getAppSetIdAsync(): ListenableFuture<AppSetId> {
48             return CoroutineScope(Dispatchers.Default)
49                 .async { mAppSetIdManager.getAppSetId() }
50                 .asListenableFuture()
51         }
52     }
53 
54     companion object {
55         /**
56          * Creates [AppSetIdManagerFutures].
57          *
58          * @return AppSetIdManagerFutures object. If the device is running an incompatible build,
59          *   the value returned is null.
60          */
61         @JvmStatic
fromnull62         fun from(context: Context): AppSetIdManagerFutures? {
63             return AppSetIdManager.obtain(context)?.let { Api33Ext4JavaImpl(it) }
64         }
65     }
66 }
67