/* * Copyright 2020 The Android Open Source Project * * 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 android.app.appsearch; import static android.app.appsearch.SearchSessionUtil.safeExecute; import android.annotation.CallbackExecutor; import android.annotation.NonNull; import android.app.appsearch.aidl.AppSearchResultParcel; import android.app.appsearch.aidl.IAppSearchManager; import android.app.appsearch.aidl.IAppSearchObserverProxy; import android.app.appsearch.aidl.IAppSearchResultCallback; import android.app.appsearch.exceptions.AppSearchException; import android.app.appsearch.observer.AppSearchObserverCallback; import android.app.appsearch.observer.DocumentChangeInfo; import android.app.appsearch.observer.ObserverCallback; import android.app.appsearch.observer.ObserverSpec; import android.app.appsearch.observer.SchemaChangeInfo; import android.app.search.SearchSession; import android.compat.annotation.UnsupportedAppUsage; import android.content.AttributionSource; import android.os.Bundle; import android.os.RemoteException; import android.os.SystemClock; import android.os.UserHandle; import android.util.ArrayMap; import android.util.ArraySet; import android.util.Log; import com.android.internal.annotations.GuardedBy; import com.android.internal.util.Preconditions; import java.io.Closeable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.Executor; import java.util.function.Consumer; /** * Provides a connection to all AppSearch databases the querying application has been granted access * to. * *
This class is thread safe.
*
* @see AppSearchSession
*/
public class GlobalSearchSession implements Closeable {
private static final String TAG = "AppSearchGlobalSearchSe";
private final UserHandle mUserHandle;
private final IAppSearchManager mService;
private final AttributionSource mCallerAttributionSource;
// Management of observer callbacks. Key is observed package.
@GuardedBy("mObserverCallbacksLocked")
private final Map If the package or database doesn't exist or if the calling package doesn't have access,
* the gets will be handled as failures in an {@link AppSearchBatchResult} object in the
* callback.
*
* @param packageName the name of the package to get from
* @param databaseName the name of the database to get from
* @param request a request containing a namespace and IDs to get documents for.
* @param executor Executor on which to invoke the callback.
* @param callback Callback to receive the pending result of performing this operation. The keys
* of the returned {@link AppSearchBatchResult} are the input IDs. The values
* are the returned {@link GenericDocument}s on success, or a failed
* {@link AppSearchResult} otherwise. IDs that are not found will return a
* failed {@link AppSearchResult} with a result code of
* {@link AppSearchResult#RESULT_NOT_FOUND}. If an unexpected internal error
* occurs in the AppSearch service, {@link BatchResultCallback#onSystemError}
* will be invoked with a {@link Throwable}.
*/
public void getByDocumentId(
@NonNull String packageName,
@NonNull String databaseName,
@NonNull GetByDocumentIdRequest request,
@NonNull @CallbackExecutor Executor executor,
@NonNull BatchResultCallback Applications can be granted access to documents by specifying {@link
* SetSchemaRequest.Builder#setSchemaTypeVisibilityForPackage} when building a schema.
*
* Document access can also be granted to system UIs by specifying {@link
* SetSchemaRequest.Builder#setSchemaTypeDisplayedBySystem} when building a schema.
*
* See {@link AppSearchSession#search} for a detailed explanation on forming a query string.
*
* This method is lightweight. The heavy work will be done in {@link
* SearchResults#getNextPage}.
*
* @param queryExpression query string to search.
* @param searchSpec spec for setting document filters, adding projection, setting term match
* type, etc.
* @return a {@link SearchResults} object for retrieved matched documents.
*/
@NonNull
public SearchResults search(@NonNull String queryExpression, @NonNull SearchSpec searchSpec) {
Objects.requireNonNull(queryExpression);
Objects.requireNonNull(searchSpec);
Preconditions.checkState(!mIsClosed, "GlobalSearchSession has already been closed");
return new SearchResults(mService, mCallerAttributionSource, /*databaseName=*/null,
queryExpression, searchSpec, mUserHandle);
}
/**
* Reports that a particular document has been used from a system surface.
*
* See {@link AppSearchSession#reportUsage} for a general description of document usage, as
* well as an API that can be used by the app itself.
*
* Usage reported via this method is accounted separately from usage reported via
* {@link AppSearchSession#reportUsage} and may be accessed using the constants
* {@link SearchSpec#RANKING_STRATEGY_SYSTEM_USAGE_COUNT} and
* {@link SearchSpec#RANKING_STRATEGY_SYSTEM_USAGE_LAST_USED_TIMESTAMP}.
*
* @param request The usage reporting request.
* @param executor Executor on which to invoke the callback.
* @param callback Callback to receive errors. If the operation succeeds, the callback will be
* invoked with an {@link AppSearchResult} whose value is {@code null}. The
* callback will be invoked with an {@link AppSearchResult} of
* {@link AppSearchResult#RESULT_SECURITY_ERROR} if this API is invoked by an
* app which is not part of the system.
*/
public void reportSystemUsage(
@NonNull ReportSystemUsageRequest request,
@NonNull @CallbackExecutor Executor executor,
@NonNull Consumer If the requested package/database combination does not exist or the caller has not been
* granted access to it, then an empty GetSchemaResponse will be returned.
*
* @param packageName the package that owns the requested {@link AppSearchSchema} instances.
* @param databaseName the database that owns the requested {@link AppSearchSchema} instances.
* @return The pending {@link GetSchemaResponse} containing the schemas that the caller has
* access to or an empty GetSchemaResponse if the request package and database does not
* exist, has not set a schema or contains no schemas that are accessible to the caller.
*/
// This call hits disk; async API prevents us from treating these calls as properties.
public void getSchema(
@NonNull String packageName,
@NonNull String databaseName,
@NonNull @CallbackExecutor Executor executor,
@NonNull Consumer The observer callback is only triggered for data that changes after it is registered. No
* notification about existing data is sent as a result of registering an observer. To find out
* about existing data, you must use the {@link GlobalSearchSession#search} API.
*
* If the data owned by {@code targetPackageName} is not visible to you, the registration
* call will succeed but no notifications will be dispatched. Notifications could start flowing
* later if {@code targetPackageName} changes its schema visibility settings.
*
* If no package matching {@code targetPackageName} exists on the system, the registration
* call will succeed but no notifications will be dispatched. Notifications could start flowing
* later if {@code targetPackageName} is installed and starts indexing data.
*
* @param targetPackageName Package whose changes to monitor
* @param spec Specification of what types of changes to listen for
* @param executor Executor on which to call the {@code observer} callback methods.
* @param observer Callback to trigger when a schema or document changes
* @throws AppSearchException If an unexpected error occurs when trying to register an observer.
*/
public void registerObserverCallback(
@NonNull String targetPackageName,
@NonNull ObserverSpec spec,
@NonNull Executor executor,
@NonNull ObserverCallback observer) throws AppSearchException {
Objects.requireNonNull(targetPackageName);
Objects.requireNonNull(spec);
Objects.requireNonNull(executor);
Objects.requireNonNull(observer);
Preconditions.checkState(!mIsClosed, "GlobalSearchSession has already been closed");
synchronized (mObserverCallbacksLocked) {
IAppSearchObserverProxy stub = null;
Map If we fail to deliver change notifications, there isn't much we can do.
* The API doesn't allow the user to provide a callback to invoke on failure of
* change notification delivery. {@link SearchSessionUtil#safeExecute} already
* includes a log message. So we just do nothing.
*/
private void suppressingErrorCallback(@NonNull AppSearchResult> unused) {}
};
}
// Regardless of whether this stub was fresh or not, we have to register it again
// because the user might be supplying a different spec.
AppSearchResultParcel All instances of {@link ObserverCallback} which are registered to observe
* {@code targetPackageName} and compare equal to the provided callback using the provided
* argument's {@code ObserverCallback#equals} will be removed.
*
* If no matching observers have been registered, this method has no effect. If multiple
* matching observers have been registered, all will be removed.
*
* @param targetPackageName Package which the observers to be removed are listening to.
* @param observer Callback to unregister.
* @throws AppSearchException if an error occurs trying to remove the observer, such as a
* failure to communicate with the system service. Note that no error
* will be thrown if the provided observer doesn't match any
* registered observer.
*/
public void unregisterObserverCallback(
@NonNull String targetPackageName,
@NonNull ObserverCallback observer) throws AppSearchException {
Objects.requireNonNull(targetPackageName);
Objects.requireNonNull(observer);
Preconditions.checkState(!mIsClosed, "GlobalSearchSession has already been closed");
IAppSearchObserverProxy stub;
synchronized (mObserverCallbacksLocked) {
Map