summaryrefslogtreecommitdiff
path: root/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationSender.java
blob: 3804070d49fc93ef02051b3040f32415958b03fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*
 * Copyright (C) 2023 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 com.android.safetycenter.notifications;

import static android.os.Build.VERSION_CODES.TIRAMISU;
import static android.safetycenter.SafetyEvent.SAFETY_EVENT_TYPE_RESOLVING_ACTION_SUCCEEDED;

import static com.android.safetycenter.internaldata.SafetyCenterIds.toUserFriendlyString;

import android.annotation.IntDef;
import android.annotation.UserIdInt;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Binder;
import android.os.UserHandle;
import android.safetycenter.SafetyEvent;
import android.safetycenter.SafetySourceIssue;
import android.safetycenter.config.SafetySource;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.android.modules.utils.build.SdkLevel;
import com.android.permission.util.UserUtils;
import com.android.safetycenter.SafetyCenterFlags;
import com.android.safetycenter.SafetySourceIssueInfo;
import com.android.safetycenter.UserProfileGroup;
import com.android.safetycenter.data.SafetyCenterDataManager;
import com.android.safetycenter.internaldata.SafetyCenterIds;
import com.android.safetycenter.internaldata.SafetyCenterIssueKey;
import com.android.safetycenter.logging.SafetyCenterStatsdLogger;
import com.android.safetycenter.resources.SafetyCenterResourcesApk;

import java.io.PrintWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.time.Duration;
import java.time.Instant;
import java.util.List;

import javax.annotation.concurrent.NotThreadSafe;

/**
 * Class responsible for posting, updating and dismissing Safety Center notifications each time
 * Safety Center's issues change.
 *
 * <p>This class isn't thread safe. Thread safety must be handled by the caller.
 *
 * @hide
 */
@RequiresApi(TIRAMISU)
@NotThreadSafe
public final class SafetyCenterNotificationSender {

    private static final String TAG = "SafetyCenterNS";

    // We use a fixed notification ID because notifications are keyed by (tag, id) and it easier
    // to differentiate our notifications using the tag
    private static final int FIXED_NOTIFICATION_ID = 2345;

    private static final int NOTIFICATION_BEHAVIOR_INTERNAL_NEVER = 100;
    private static final int NOTIFICATION_BEHAVIOR_INTERNAL_DELAYED = 200;
    private static final int NOTIFICATION_BEHAVIOR_INTERNAL_IMMEDIATELY = 300;

    /**
     * Internal notification behavior {@code @IntDef} which is related to the {@code
     * SafetySourceIssue.NotificationBehavior} type introduced in Android U.
     *
     * <p>This definition is available on T+.
     *
     * <p>Unlike the U+/external {@code @IntDef}, this one has no "unspecified behavior" value. Any
     * issues which have unspecified behavior are resolved to one of these specific behaviors based
     * on their other properties.
     */
    @IntDef(
            prefix = {"NOTIFICATION_BEHAVIOR_INTERNAL"},
            value = {
                NOTIFICATION_BEHAVIOR_INTERNAL_NEVER,
                NOTIFICATION_BEHAVIOR_INTERNAL_DELAYED,
                NOTIFICATION_BEHAVIOR_INTERNAL_IMMEDIATELY
            })
    @Retention(RetentionPolicy.SOURCE)
    private @interface NotificationBehaviorInternal {}

    private final Context mContext;

    private final SafetyCenterNotificationFactory mNotificationFactory;

    private final SafetyCenterDataManager mSafetyCenterDataManager;

    private final ArrayMap<SafetyCenterIssueKey, SafetySourceIssue> mNotifiedIssues =
            new ArrayMap<>();

    private SafetyCenterNotificationSender(
            Context context,
            SafetyCenterNotificationFactory notificationFactory,
            SafetyCenterDataManager safetyCenterDataManager) {
        mContext = context;
        mNotificationFactory = notificationFactory;
        mSafetyCenterDataManager = safetyCenterDataManager;
    }

    public static SafetyCenterNotificationSender newInstance(
            Context context,
            SafetyCenterResourcesApk safetyCenterResourcesApk,
            SafetyCenterNotificationChannels notificationChannels,
            SafetyCenterDataManager dataManager) {
        return new SafetyCenterNotificationSender(
                context,
                new SafetyCenterNotificationFactory(
                        context, notificationChannels, safetyCenterResourcesApk),
                dataManager);
    }

    /**
     * Replaces an issue's notification with one displaying the success message of the {@link
     * SafetySourceIssue.Action} that resolved that issue.
     *
     * <p>The given {@link SafetyEvent} have type {@link
     * SafetyEvent#SAFETY_EVENT_TYPE_RESOLVING_ACTION_SUCCEEDED} and include issue and action IDs
     * that correspond to a {@link SafetySourceIssue} for which a notification is currently
     * displayed. Otherwise, this method has no effect.
     *
     * @param sourceId of the source which reported the issue
     * @param safetyEvent the source provided upon successful action resolution
     * @param userId to which the source, issue and notification belong
     */
    public void notifyActionSuccess(
            String sourceId, SafetyEvent safetyEvent, @UserIdInt int userId) {
        if (!SafetyCenterFlags.getNotificationsEnabled()) {
            // TODO(b/284271124): Decide what to do with existing notifications
            return;
        }

        if (safetyEvent.getType() != SAFETY_EVENT_TYPE_RESOLVING_ACTION_SUCCEEDED) {
            Log.w(TAG, "Received safety event of wrong type");
            return;
        }

        String sourceIssueId = safetyEvent.getSafetySourceIssueId();
        if (sourceIssueId == null) {
            Log.w(TAG, "Received safety event without a safety source issue id");
            return;
        }

        String sourceIssueActionId = safetyEvent.getSafetySourceIssueActionId();
        if (sourceIssueActionId == null) {
            Log.w(TAG, "Received safety event without a safety source issue action id");
            return;
        }

        SafetyCenterIssueKey issueKey =
                SafetyCenterIssueKey.newBuilder()
                        .setSafetySourceId(sourceId)
                        .setSafetySourceIssueId(sourceIssueId)
                        .setUserId(userId)
                        .build();
        SafetySourceIssue notifiedIssue = mNotifiedIssues.get(issueKey);
        if (notifiedIssue == null) {
            Log.w(TAG, "No notification for this issue");
            return;
        }

        SafetySourceIssue.Action successfulAction = null;
        for (int i = 0; i < notifiedIssue.getActions().size(); i++) {
            if (notifiedIssue.getActions().get(i).getId().equals(sourceIssueActionId)) {
                successfulAction = notifiedIssue.getActions().get(i);
            }
        }
        if (successfulAction == null) {
            Log.w(TAG, "Successful action not found");
            return;
        }

        NotificationManager notificationManager = getNotificationManagerForUser(userId);

        if (notificationManager == null) {
            return;
        }

        Notification notification =
                mNotificationFactory.newNotificationForSuccessfulAction(
                        notificationManager, notifiedIssue, successfulAction, userId);
        if (notification == null) {
            Log.w(TAG, "Could not create successful action notification");
            return;
        }
        String tag = getNotificationTag(issueKey);
        boolean wasPosted = notifyFromSystem(notificationManager, tag, notification);
        if (wasPosted) {
            // If the original issue notification was successfully replaced the key removed from
            // mNotifiedIssues to prevent the success notification from being removed by
            // cancelStaleNotifications below.
            mNotifiedIssues.remove(issueKey);
        }
    }

    /** Updates Safety Center notifications for the given {@link UserProfileGroup}. */
    public void updateNotifications(UserProfileGroup userProfileGroup) {
        updateNotifications(userProfileGroup.getProfileParentUserId());

        int[] managedProfileUserIds = userProfileGroup.getManagedProfilesUserIds();
        for (int i = 0; i < managedProfileUserIds.length; i++) {
            updateNotifications(managedProfileUserIds[i]);
        }
    }

    /**
     * Updates Safety Center notifications, usually in response to a change in the issues for the
     * given userId.
     */
    public void updateNotifications(@UserIdInt int userId) {
        if (!SafetyCenterFlags.getNotificationsEnabled()) {
            // TODO(b/284271124): Decide what to do with existing notifications
            return;
        }

        NotificationManager notificationManager = getNotificationManagerForUser(userId);

        if (notificationManager == null) {
            return;
        }

        ArrayMap<SafetyCenterIssueKey, SafetySourceIssue> issuesToNotify =
                getIssuesToNotify(userId);

        // Post or update notifications for notifiable issues. We keep track of the "fresh" issues
        // keys of those issues which were just notified because doing so allows us to cancel any
        // notifications for other, non-fresh issues.
        ArraySet<SafetyCenterIssueKey> freshIssueKeys = new ArraySet<>();
        for (int i = 0; i < issuesToNotify.size(); i++) {
            SafetyCenterIssueKey issueKey = issuesToNotify.keyAt(i);
            SafetySourceIssue issue = issuesToNotify.valueAt(i);

            boolean unchanged = issue.equals(mNotifiedIssues.get(issueKey));
            if (unchanged) {
                freshIssueKeys.add(issueKey);
                continue;
            }

            boolean wasPosted = postNotificationForIssue(notificationManager, issue, issueKey);
            if (wasPosted) {
                freshIssueKeys.add(issueKey);
            }
        }

        cancelStaleNotifications(notificationManager, userId, freshIssueKeys);
    }

    /** Cancels all notifications previously posted by this class */
    public void cancelAllNotifications() {
        // Loop in reverse index order to be able to remove entries while iterating
        for (int i = mNotifiedIssues.size() - 1; i >= 0; i--) {
            SafetyCenterIssueKey issueKey = mNotifiedIssues.keyAt(i);
            int userId = issueKey.getUserId();
            NotificationManager notificationManager = getNotificationManagerForUser(userId);
            if (notificationManager == null) {
                continue;
            }
            cancelNotificationFromSystem(notificationManager, getNotificationTag(issueKey));
            mNotifiedIssues.removeAt(i);
        }
    }

    /** Dumps state for debugging purposes. */
    public void dump(PrintWriter fout) {
        int notifiedIssuesCount = mNotifiedIssues.size();
        fout.println("NOTIFICATION SENDER (" + notifiedIssuesCount + " notified issues)");
        for (int i = 0; i < notifiedIssuesCount; i++) {
            SafetyCenterIssueKey key = mNotifiedIssues.keyAt(i);
            SafetySourceIssue issue = mNotifiedIssues.valueAt(i);
            fout.println("\t[" + i + "] " + toUserFriendlyString(key) + " -> " + issue);
        }
        fout.println();
    }

    /** Gets all the key-issue pairs for which notifications should be posted or updated now. */
    private ArrayMap<SafetyCenterIssueKey, SafetySourceIssue> getIssuesToNotify(
            @UserIdInt int userId) {
        ArrayMap<SafetyCenterIssueKey, SafetySourceIssue> result = new ArrayMap<>();
        List<SafetySourceIssueInfo> allIssuesInfo =
                mSafetyCenterDataManager.getIssuesForUser(userId);

        for (int i = 0; i < allIssuesInfo.size(); i++) {
            SafetySourceIssueInfo issueInfo = allIssuesInfo.get(i);
            SafetyCenterIssueKey issueKey = issueInfo.getSafetyCenterIssueKey();
            SafetySourceIssue issue = issueInfo.getSafetySourceIssue();

            if (!areNotificationsAllowedForSource(issueInfo.getSafetySource())) {
                continue;
            }

            if (mSafetyCenterDataManager.isNotificationDismissedNow(
                    issueKey, issue.getSeverityLevel())) {
                continue;
            }

            // Get the notification behavior for this issue which determines whether we should
            // send a notification about it now
            int behavior = getBehavior(issue, issueKey);
            if (behavior == NOTIFICATION_BEHAVIOR_INTERNAL_IMMEDIATELY) {
                result.put(issueKey, issue);
            } else if (behavior == NOTIFICATION_BEHAVIOR_INTERNAL_DELAYED) {
                if (canNotifyDelayedIssueNow(issueKey)) {
                    result.put(issueKey, issue);
                }
                // TODO(b/259094736): else handle delayed notifications using a scheduled job
            }
        }
        return result;
    }

    @NotificationBehaviorInternal
    private int getBehavior(SafetySourceIssue issue, SafetyCenterIssueKey issueKey) {
        if (SdkLevel.isAtLeastU()) {
            int notificationBehavior = issue.getNotificationBehavior();
            switch (notificationBehavior) {
                case SafetySourceIssue.NOTIFICATION_BEHAVIOR_NEVER:
                    return NOTIFICATION_BEHAVIOR_INTERNAL_NEVER;
                case SafetySourceIssue.NOTIFICATION_BEHAVIOR_DELAYED:
                    return NOTIFICATION_BEHAVIOR_INTERNAL_DELAYED;
                case SafetySourceIssue.NOTIFICATION_BEHAVIOR_IMMEDIATELY:
                    return NOTIFICATION_BEHAVIOR_INTERNAL_IMMEDIATELY;
                case SafetySourceIssue.NOTIFICATION_BEHAVIOR_UNSPECIFIED:
                    return getBehaviorForIssueWithUnspecifiedBehavior(issue, issueKey);
            }
            Log.w(
                    TAG,
                    "Unexpected SafetySourceIssue.NotificationBehavior: " + notificationBehavior);
        }
        // On Android T all issues are assumed to have "unspecified" behavior
        return getBehaviorForIssueWithUnspecifiedBehavior(issue, issueKey);
    }

    @NotificationBehaviorInternal
    private int getBehaviorForIssueWithUnspecifiedBehavior(
            SafetySourceIssue issue, SafetyCenterIssueKey issueKey) {
        String flagKey = issueKey.getSafetySourceId() + "/" + issue.getIssueTypeId();
        if (SafetyCenterFlags.getImmediateNotificationBehaviorIssues().contains(flagKey)) {
            return NOTIFICATION_BEHAVIOR_INTERNAL_IMMEDIATELY;
        } else {
            return NOTIFICATION_BEHAVIOR_INTERNAL_NEVER;
        }
    }

    private boolean areNotificationsAllowedForSource(SafetySource safetySource) {
        if (SdkLevel.isAtLeastU()) {
            if (safetySource.areNotificationsAllowed()) {
                return true;
            }
        }
        return SafetyCenterFlags.getNotificationsAllowedSourceIds().contains(safetySource.getId());
    }

    private boolean canNotifyDelayedIssueNow(SafetyCenterIssueKey issueKey) {
        Duration minNotificationsDelay = SafetyCenterFlags.getNotificationsMinDelay();
        Instant threshold = Instant.now().minus(minNotificationsDelay);
        Instant seenAt = mSafetyCenterDataManager.getIssueFirstSeenAt(issueKey);
        return seenAt != null && seenAt.isBefore(threshold);
    }

    private boolean postNotificationForIssue(
            NotificationManager notificationManager,
            SafetySourceIssue issue,
            SafetyCenterIssueKey key) {
        Notification notification =
                mNotificationFactory.newNotificationForIssue(notificationManager, issue, key);
        if (notification == null) {
            return false;
        }
        String tag = getNotificationTag(key);
        boolean wasPosted = notifyFromSystem(notificationManager, tag, notification);
        if (wasPosted) {
            mNotifiedIssues.put(key, issue);
            SafetyCenterStatsdLogger.writeNotificationPostedEvent(
                    key.getSafetySourceId(),
                    UserUtils.isManagedProfile(key.getUserId(), mContext),
                    issue.getIssueTypeId(),
                    issue.getSeverityLevel());
        }
        return wasPosted;
    }

    private void cancelStaleNotifications(
            NotificationManager notificationManager,
            @UserIdInt int userId,
            ArraySet<SafetyCenterIssueKey> freshIssueKeys) {
        // Loop in reverse index order to be able to remove entries while iterating
        for (int i = mNotifiedIssues.size() - 1; i >= 0; i--) {
            SafetyCenterIssueKey key = mNotifiedIssues.keyAt(i);
            if (key.getUserId() == userId && !freshIssueKeys.contains(key)) {
                String tag = getNotificationTag(key);
                cancelNotificationFromSystem(notificationManager, tag);
                mNotifiedIssues.removeAt(i);
            }
        }
    }

    private static String getNotificationTag(SafetyCenterIssueKey issueKey) {
        // Base 64 encoding of the issueKey proto:
        return SafetyCenterIds.encodeToString(issueKey);
    }

    /** Returns a {@link NotificationManager} which will send notifications to the given user. */
    @Nullable
    private NotificationManager getNotificationManagerForUser(@UserIdInt int userId) {
        return SafetyCenterNotificationChannels.getNotificationManagerForUser(
                mContext, UserHandle.of(userId));
    }

    /**
     * Sends a {@link Notification} from the system, dropping any calling identity. Returns {@code
     * true} if successful or {@code false} otherwise.
     *
     * <p>The recipient of the notification depends on the {@link Context} of the given {@link
     * NotificationManager}. Use {@link #getNotificationManagerForUser(int)} to send notifications
     * to a specific user.
     */
    private boolean notifyFromSystem(
            NotificationManager notificationManager,
            @Nullable String tag,
            Notification notification) {
        // This call is needed to send a notification from the system and this also grants the
        // necessary POST_NOTIFICATIONS permission.
        final long callingId = Binder.clearCallingIdentity();
        try {
            // The fixed notification ID is OK because notifications are keyed by (tag, id)
            notificationManager.notify(tag, FIXED_NOTIFICATION_ID, notification);
            return true;
        } catch (Throwable e) {
            Log.w(TAG, "Unable to send system notification", e);
            return false;
        } finally {
            Binder.restoreCallingIdentity(callingId);
        }
    }

    /**
     * Cancels a {@link Notification} from the system, dropping any calling identity.
     *
     * <p>The recipient of the notification depends on the {@link Context} of the given {@link
     * NotificationManager}. Use {@link #getNotificationManagerForUser(int)} to cancel notifications
     * sent to a specific user.
     */
    private void cancelNotificationFromSystem(
            NotificationManager notificationManager, @Nullable String tag) {
        // This call is needed to cancel a notification previously sent from the system
        final long callingId = Binder.clearCallingIdentity();
        try {
            notificationManager.cancel(tag, FIXED_NOTIFICATION_ID);
        } catch (Throwable e) {
            Log.w(TAG, "Unable to cancel system notification", e);
        } finally {
            Binder.restoreCallingIdentity(callingId);
        }
    }
}