blob: 122cf6ce66219268f87c107b6f1ce98324c2dc06 [file] [log] [blame]
Uriel Sade298f6c02018-12-19 20:34:43 -08001/*
Uriel Saded81ddc92018-12-21 15:16:56 -08002 * Copyright (C) 2019 The Android Open Source Project
Uriel Sade298f6c02018-12-19 20:34:43 -08003 *
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 */
16package com.android.car.assist.client;
17
Uriel Saded81ddc92018-12-21 15:16:56 -080018import static android.app.Notification.Action.SEMANTIC_ACTION_MARK_AS_READ;
19import static android.app.Notification.Action.SEMANTIC_ACTION_REPLY;
Uriel Sade3703dbd2019-01-16 12:55:19 -080020import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_NOTIFICATION;
Uriel Saded81ddc92018-12-21 15:16:56 -080021
Ritwika Mitra146ed852019-05-01 10:33:06 -070022import android.annotation.Nullable;
Ritwika Mitra3eb68932019-04-29 16:40:04 -070023import android.app.ActivityManager;
Uriel Sade298f6c02018-12-19 20:34:43 -080024import android.app.Notification;
Uriel Saded81ddc92018-12-21 15:16:56 -080025import android.app.RemoteInput;
Uriel Sade298f6c02018-12-19 20:34:43 -080026import android.content.Context;
27import android.os.Bundle;
28import android.provider.Settings;
29import android.service.notification.StatusBarNotification;
30import android.util.Log;
31
32import androidx.core.app.NotificationCompat;
33
34import com.android.car.assist.CarVoiceInteractionSession;
35import com.android.internal.app.AssistUtils;
Uriel Sade3703dbd2019-01-16 12:55:19 -080036import com.android.internal.app.IVoiceActionCheckCallback;
Uriel Sade298f6c02018-12-19 20:34:43 -080037
Priyank Singh128ff292019-04-29 20:07:36 -070038import java.util.ArrayList;
Uriel Sade298f6c02018-12-19 20:34:43 -080039import java.util.Arrays;
40import java.util.Collections;
41import java.util.HashSet;
42import java.util.List;
43import java.util.Objects;
44import java.util.Set;
45import java.util.stream.Collectors;
46import java.util.stream.IntStream;
47
48/**
49 * Util class providing helper methods to interact with the current active voice service,
50 * while ensuring that the active voice service has the required permissions.
51 */
52public class CarAssistUtils {
53 public static final String TAG = "CarAssistUtils";
Uriel Saded81ddc92018-12-21 15:16:56 -080054 private static final List<Integer> REQUIRED_SEMANTIC_ACTIONS = Collections.unmodifiableList(
Uriel Sade298f6c02018-12-19 20:34:43 -080055 Arrays.asList(
Uriel Saded81ddc92018-12-21 15:16:56 -080056 SEMANTIC_ACTION_MARK_AS_READ
Uriel Sade298f6c02018-12-19 20:34:43 -080057 )
58 );
59
Ritwika Mitraaaf0c172019-01-30 08:25:03 -080060 private static final List<Integer> SUPPORTED_SEMANTIC_ACTIONS = Collections.unmodifiableList(
61 Arrays.asList(
62 SEMANTIC_ACTION_MARK_AS_READ,
63 SEMANTIC_ACTION_REPLY
64 )
65 );
Uriel Saded81ddc92018-12-21 15:16:56 -080066
Uriel Sade298f6c02018-12-19 20:34:43 -080067 private final Context mContext;
68 private final AssistUtils mAssistUtils;
Uriel Saded81ddc92018-12-21 15:16:56 -080069 private final FallbackAssistant mFallbackAssistant;
70 private final String mErrorMessage;
Uriel Sade298f6c02018-12-19 20:34:43 -080071
Uriel Sade3703dbd2019-01-16 12:55:19 -080072 /** Interface used to receive callbacks from voice action requests. */
73 public interface ActionRequestCallback {
74 /** Callback issued from a voice request on success/error. */
75 void onResult(boolean error);
76 }
77
Uriel Sade298f6c02018-12-19 20:34:43 -080078 public CarAssistUtils(Context context) {
Uriel Sade298f6c02018-12-19 20:34:43 -080079 mContext = context;
Uriel Saded81ddc92018-12-21 15:16:56 -080080 mAssistUtils = new AssistUtils(context);
Ritwika Mitra146ed852019-05-01 10:33:06 -070081 mFallbackAssistant = new FallbackAssistant(context);
Uriel Saded81ddc92018-12-21 15:16:56 -080082 mErrorMessage = context.getString(R.string.assist_action_failed_toast);
Uriel Sade298f6c02018-12-19 20:34:43 -080083 }
84
85 /**
86 * Returns true if the current active assistant has notification listener permissions.
87 */
88 public boolean assistantIsNotificationListener() {
89 final String activeComponent = mAssistUtils.getActiveServiceComponentName()
90 .flattenToString();
Ritwika Mitraac5f1512019-02-04 10:21:14 -080091 int slashIndex = activeComponent.indexOf("/");
92 final String activePackage = activeComponent.substring(0, slashIndex);
93
Ritwika Mitra3eb68932019-04-29 16:40:04 -070094 final String listeners = Settings.Secure.getStringForUser(mContext.getContentResolver(),
95 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS, ActivityManager.getCurrentUser());
Uriel Sade298f6c02018-12-19 20:34:43 -080096
Ritwika Mitraac5f1512019-02-04 10:21:14 -080097 if (listeners != null) {
98 for (String listener : Arrays.asList(listeners.split(":"))) {
99 if (listener.contains(activePackage)) {
Ritwika Mitra295d91a2019-04-26 09:55:11 -0700100 Log.d(TAG, "Active assistant has notification listener: " + listener);
Ritwika Mitraac5f1512019-02-04 10:21:14 -0800101 return true;
102 }
103 }
104 }
Ritwika Mitra295d91a2019-04-26 09:55:11 -0700105 Log.w(TAG, "No notification listeners found for assistant: " + activeComponent);
Ritwika Mitraac5f1512019-02-04 10:21:14 -0800106 return false;
Uriel Sade298f6c02018-12-19 20:34:43 -0800107 }
108
109 /**
110 * Checks whether the notification is a car-compatible messaging notification.
111 *
112 * @param sbn The notification being checked.
113 * @return true if the notification is a car-compatible messaging notification.
114 */
115 public static boolean isCarCompatibleMessagingNotification(StatusBarNotification sbn) {
116 return hasMessagingStyle(sbn)
117 && hasRequiredAssistantCallbacks(sbn)
118 && replyCallbackHasRemoteInput(sbn)
119 && assistantCallbacksShowNoUi(sbn);
120 }
121
122 /** Returns true if the semantic action provided can be supported. */
123 public static boolean isSupportedSemanticAction(int semanticAction) {
Uriel Saded81ddc92018-12-21 15:16:56 -0800124 return SUPPORTED_SEMANTIC_ACTIONS.contains(semanticAction);
Uriel Sade298f6c02018-12-19 20:34:43 -0800125 }
126
127 /**
128 * Returns true if the notification has a messaging style.
129 * <p/>
130 * This is the case if the notification in question was provided an instance of
131 * {@link Notification.MessagingStyle} (or an instance of
132 * {@link NotificationCompat.MessagingStyle} if {@link NotificationCompat} was used).
133 */
134 private static boolean hasMessagingStyle(StatusBarNotification sbn) {
135 return NotificationCompat.MessagingStyle
136 .extractMessagingStyleFromNotification(sbn.getNotification()) != null;
137 }
138
139 /**
140 * Returns true if the notification has the required Assistant callbacks to be considered
141 * a car-compatible messaging notification. The callbacks must be unambiguous, therefore false
142 * is returned if multiple callbacks exist for any semantic action that is supported.
143 */
144 private static boolean hasRequiredAssistantCallbacks(StatusBarNotification sbn) {
Priyank Singh128ff292019-04-29 20:07:36 -0700145 List<Integer> semanticActionList = getAllActions(sbn.getNotification())
146 .stream()
147 .map(NotificationCompat.Action::getSemanticAction)
Uriel Saded81ddc92018-12-21 15:16:56 -0800148 .filter(REQUIRED_SEMANTIC_ACTIONS::contains)
Uriel Sade298f6c02018-12-19 20:34:43 -0800149 .collect(Collectors.toList());
150 Set<Integer> semanticActionSet = new HashSet<>(semanticActionList);
Uriel Sade298f6c02018-12-19 20:34:43 -0800151 return semanticActionList.size() == semanticActionSet.size()
Uriel Saded81ddc92018-12-21 15:16:56 -0800152 && semanticActionSet.containsAll(REQUIRED_SEMANTIC_ACTIONS);
Uriel Sade298f6c02018-12-19 20:34:43 -0800153 }
154
Priyank Singh128ff292019-04-29 20:07:36 -0700155 /** Retrieves all visible and invisible {@link Action}s from the {@link #notification}. */
Ritwika Mitra146ed852019-05-01 10:33:06 -0700156 public static List<NotificationCompat.Action> getAllActions(Notification notification) {
Priyank Singh128ff292019-04-29 20:07:36 -0700157 List<NotificationCompat.Action> actions = new ArrayList<>();
158 actions.addAll(NotificationCompat.getInvisibleActions(notification));
159 for (int i = 0; i < NotificationCompat.getActionCount(notification); i++) {
160 actions.add(NotificationCompat.getAction(notification, i));
161 }
162 return actions;
163 }
164
Uriel Sade298f6c02018-12-19 20:34:43 -0800165 /**
Ritwika Mitra146ed852019-05-01 10:33:06 -0700166 * Retrieves the {@link NotificationCompat.Action} containing the
167 * {@link NotificationCompat.Action#SEMANTIC_ACTION_MARK_AS_READ} semantic action.
168 */
169 @Nullable
170 public static NotificationCompat.Action getMarkAsReadAction(Notification notification) {
171 for (NotificationCompat.Action action : getAllActions(notification)) {
172 if (action.getSemanticAction()
173 == NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ) {
174 return action;
175 }
176 }
177 return null;
178 }
179
180 /**
Uriel Saded81ddc92018-12-21 15:16:56 -0800181 * Returns true if the reply callback has at least one {@link RemoteInput}.
Uriel Sade298f6c02018-12-19 20:34:43 -0800182 * <p/>
183 * Precondition: There exists only one reply callback.
184 */
185 private static boolean replyCallbackHasRemoteInput(StatusBarNotification sbn) {
186 return Arrays.stream(sbn.getNotification().actions)
Uriel Saded81ddc92018-12-21 15:16:56 -0800187 .filter(action -> action.getSemanticAction() == SEMANTIC_ACTION_REPLY)
Uriel Sade298f6c02018-12-19 20:34:43 -0800188 .map(Notification.Action::getRemoteInputs)
Uriel Saded81ddc92018-12-21 15:16:56 -0800189 .filter(Objects::nonNull)
190 .anyMatch(remoteInputs -> remoteInputs.length > 0);
Uriel Sade298f6c02018-12-19 20:34:43 -0800191 }
192
193 /** Returns true if all Assistant callbacks indicate that they show no UI, false otherwise. */
194 private static boolean assistantCallbacksShowNoUi(StatusBarNotification sbn) {
195 final Notification notification = sbn.getNotification();
196 return IntStream.range(0, notification.actions.length)
197 .mapToObj(i -> NotificationCompat.getAction(notification, i))
198 .filter(Objects::nonNull)
Uriel Saded81ddc92018-12-21 15:16:56 -0800199 .filter(action -> SUPPORTED_SEMANTIC_ACTIONS.contains(action.getSemanticAction()))
Uriel Sade298f6c02018-12-19 20:34:43 -0800200 .noneMatch(NotificationCompat.Action::getShowsUserInterface);
201 }
202
203 /**
Uriel Saded81ddc92018-12-21 15:16:56 -0800204 * Requests a given action from the current active Assistant.
205 *
Ritwika Mitra146ed852019-05-01 10:33:06 -0700206 * @param sbn the notification payload to deliver to assistant
207 * @param voiceAction must be a valid {@link CarVoiceInteractionSession} VOICE_ACTION
Uriel Sade3703dbd2019-01-16 12:55:19 -0800208 * @param callback the callback to issue on success/error
Uriel Sade298f6c02018-12-19 20:34:43 -0800209 */
Ritwika Mitra146ed852019-05-01 10:33:06 -0700210 public void requestAssistantVoiceAction(StatusBarNotification sbn, String voiceAction,
Uriel Sade3703dbd2019-01-16 12:55:19 -0800211 ActionRequestCallback callback) {
Uriel Saded81ddc92018-12-21 15:16:56 -0800212 if (!isCarCompatibleMessagingNotification(sbn)) {
213 Log.w(TAG, "Assistant action requested for non-compatible notification.");
Uriel Sade3703dbd2019-01-16 12:55:19 -0800214 callback.onResult(/* error= */ true);
215 return;
216 }
217
Ritwika Mitra146ed852019-05-01 10:33:06 -0700218 switch (voiceAction) {
219 case CarVoiceInteractionSession.VOICE_ACTION_READ_NOTIFICATION:
Uriel Sade3703dbd2019-01-16 12:55:19 -0800220 readMessageNotification(sbn, callback);
221 return;
Ritwika Mitra146ed852019-05-01 10:33:06 -0700222 case CarVoiceInteractionSession.VOICE_ACTION_REPLY_NOTIFICATION:
Uriel Sade3703dbd2019-01-16 12:55:19 -0800223 replyMessageNotification(sbn, callback);
224 return;
Uriel Saded81ddc92018-12-21 15:16:56 -0800225 default:
Ritwika Mitra146ed852019-05-01 10:33:06 -0700226 Log.w(TAG, "Requested Assistant action for unsupported semantic action.");
Uriel Sade3703dbd2019-01-16 12:55:19 -0800227 callback.onResult(/* error= */ true);
228 return;
Uriel Saded81ddc92018-12-21 15:16:56 -0800229 }
Uriel Sade298f6c02018-12-19 20:34:43 -0800230 }
231
232 /**
233 * Requests a read action for the notification from the current active Assistant.
Uriel Saded81ddc92018-12-21 15:16:56 -0800234 * If the Assistant is cannot handle the request, a fallback implementation will attempt to
235 * handle it.
Uriel Sade298f6c02018-12-19 20:34:43 -0800236 *
237 * @param sbn the notification to deliver as the payload
Uriel Sade3703dbd2019-01-16 12:55:19 -0800238 * @param callback the callback to issue on success/error
Uriel Sade298f6c02018-12-19 20:34:43 -0800239 */
Uriel Sade3703dbd2019-01-16 12:55:19 -0800240 private void readMessageNotification(StatusBarNotification sbn,
241 ActionRequestCallback callback) {
242 Bundle args = BundleBuilder.buildAssistantReadBundle(sbn);
243 String action = CarVoiceInteractionSession.VOICE_ACTION_READ_NOTIFICATION;
244
245 requestAction(sbn, args, action, callback);
Uriel Sade298f6c02018-12-19 20:34:43 -0800246 }
247
248 /**
249 * Requests a reply action for the notification from the current active Assistant.
Uriel Saded81ddc92018-12-21 15:16:56 -0800250 * If the Assistant is cannot handle the request, a fallback implementation will attempt to
251 * handle it.
Uriel Sade298f6c02018-12-19 20:34:43 -0800252 *
253 * @param sbn the notification to deliver as the payload
Uriel Sade3703dbd2019-01-16 12:55:19 -0800254 * @param callback the callback to issue on success/error
Uriel Sade298f6c02018-12-19 20:34:43 -0800255 */
Uriel Sade3703dbd2019-01-16 12:55:19 -0800256 private void replyMessageNotification(StatusBarNotification sbn,
257 ActionRequestCallback callback) {
258 Bundle args = BundleBuilder.buildAssistantReplyBundle(sbn);
259 String action = CarVoiceInteractionSession.VOICE_ACTION_REPLY_NOTIFICATION;
260
261 requestAction(sbn, args, action, callback);
Uriel Sade298f6c02018-12-19 20:34:43 -0800262 }
263
Uriel Sade3703dbd2019-01-16 12:55:19 -0800264 private void requestAction(StatusBarNotification sbn, Bundle payloadArguments, String action,
265 ActionRequestCallback callback) {
266
267 if (!assistantIsNotificationListener()) {
268 Log.w(TAG, "Active Assistant does not have Notification Listener permissions.");
269 boolean success = handleFallback(sbn, action);
270 callback.onResult(!success);
271 return;
272 }
273
274 IVoiceActionCheckCallback actionCheckCallback = new IVoiceActionCheckCallback.Stub() {
275 @Override
276 public void onComplete(List<String> supportedActions) {
277 boolean success;
278 if (supportedActions != null && supportedActions.contains(action)) {
279 if (Log.isLoggable(TAG, Log.DEBUG)) {
280 Log.d(TAG, "Launching active Assistant for action: " + action);
281 }
282 success = mAssistUtils.showSessionForActiveService(payloadArguments,
283 SHOW_SOURCE_NOTIFICATION, null, null);
284 } else {
285 Log.w(TAG, "Active Assistant does not support voice action: " + action);
286 success = handleFallback(sbn, action);
287 }
288 callback.onResult(!success);
289 }
290 };
291
292 Set<String> actionSet = new HashSet<>(Collections.singletonList(action));
293 mAssistUtils.getActiveServiceSupportedActions(actionSet, actionCheckCallback);
294 }
295
296 private boolean handleFallback(StatusBarNotification sbn, String action) {
297 switch (action) {
298 case CarVoiceInteractionSession.VOICE_ACTION_READ_NOTIFICATION:
Ritwika Mitra146ed852019-05-01 10:33:06 -0700299 return mFallbackAssistant.handleReadAction(sbn);
Uriel Sade3703dbd2019-01-16 12:55:19 -0800300
301 case CarVoiceInteractionSession.VOICE_ACTION_REPLY_NOTIFICATION:
Ritwika Mitra146ed852019-05-01 10:33:06 -0700302 return mFallbackAssistant.handleErrorMessage(mErrorMessage);
Uriel Sade3703dbd2019-01-16 12:55:19 -0800303
304 default:
305 Log.w(TAG, "Requested fallback action for unsupported voice action.");
306 return false;
307 }
Uriel Sade298f6c02018-12-19 20:34:43 -0800308 }
309}