summaryrefslogtreecommitdiff
path: root/src/com/android/documentsui/Metrics.java
blob: 9d20fce1ee026eb0749df438e61ff56c7aade4e7 (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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
/*
 * Copyright (C) 2016 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.documentsui;

import static android.content.ContentResolver.wrap;

import static com.android.documentsui.DocumentsApplication.acquireUnstableProviderOrThrow;

import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.DocumentsContract;
import android.provider.DocumentsContract.Path;
import android.provider.DocumentsProvider;
import android.util.Log;
import android.util.StatsEvent;
import android.util.StatsLog;

import androidx.annotation.Nullable;

import com.android.documentsui.base.DocumentInfo;
import com.android.documentsui.base.Providers;
import com.android.documentsui.base.RootInfo;
import com.android.documentsui.base.State;
import com.android.documentsui.base.UserId;
import com.android.documentsui.files.LauncherActivity;
import com.android.documentsui.picker.PickResult;
import com.android.documentsui.roots.ProvidersAccess;
import com.android.documentsui.services.FileOperationService;
import com.android.documentsui.services.FileOperationService.OpType;
import com.android.documentsui.util.VersionUtils;

import java.io.FileNotFoundException;
import java.util.List;

/**
 * Methods for logging metrics.
 */
public final class Metrics {
    private static final String TAG = "Metrics";

    /**
     * Logs when DocumentsUI is started, and how. Call this when DocumentsUI first starts up.
     *
     * @param state
     * @param intent
     */
    public static void logActivityLaunch(State state, Intent intent) {
        Uri uri = intent.getData();
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_LAUNCH_REPORTED,
                toMetricsAction(state.action), false,
                sanitizeMime(intent.getType()), sanitizeRoot(uri));
    }

    /**
     * Logs when DocumentsUI are launched with {@link DocumentsContract#EXTRA_INITIAL_URI}.
     *
     * @param state used to resolve action
     * @param rootUri the resolved rootUri, or {@code null} if the provider doesn't
     *                support {@link DocumentsProvider#findDocumentPath(String, String)}
     */
    public static void logLaunchAtLocation(State state, @Nullable Uri rootUri) {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_LAUNCH_REPORTED,
                toMetricsAction(state.action), true,
                MetricConsts.MIME_UNKNOWN, sanitizeRoot(rootUri));
    }

    /**
     * Logs a root visited event in file managers. Call this when the user
     * taps on a root in {@link com.android.documentsui.sidebar.RootsFragment}.
     * @param scope
     * @param info
     */
    public static void logRootVisited(@MetricConsts.ContextScope int scope, RootInfo info) {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_ROOT_VISITED, scope, sanitizeRoot(info));
    }

    public static void logLaunchOtherApp(boolean acrossProfile) {
        DevicePolicyEventLogger.write(DevicePolicyMetricConsts.EVENT_ID_DOCSUI_LAUNCH_OTHER_APP,
                acrossProfile);
    }

    public static void logCrossProfileEmptyState(CrossProfileException e) {
        int eventId;
        if (e instanceof CrossProfileQuietModeException) {
            eventId = DevicePolicyMetricConsts.EVENT_ID_DOCSUI_EMPTY_STATE_QUIET_MODE;
        } else if (e instanceof CrossProfileNoPermissionException) {
            eventId = DevicePolicyMetricConsts.EVENT_ID_DOCSUI_EMPTY_STATE_NO_PERMISSION;
        } else {
            Log.d(TAG, "logCrossProfileEmptyState: Unexpected exception " + e);
            return;
        }
        DevicePolicyEventLogger.write(eventId, /* booleanValue= */ true);
    }

    /**
     * Logs an app visited event in file pickers. Call this when the user visits
     * on an app in the RootsFragment.
     *
     * @param info
     */
    public static void logAppVisited(ResolveInfo info) {
        DocumentsStatsLog.write(
                DocumentsStatsLog.DOCS_UI_ROOT_VISITED,
                MetricConsts.PICKER_SCOPE, sanitizeRoot(info));
    }

    /**
     * Logs file operation stats. Call this when a file operation has completed. The given
     * DocumentInfo is only used to distinguish broad categories of actions (e.g. copying from one
     * provider to another vs copying within a given provider).  No PII is logged.
     *
     * @param operationType
     * @param srcs
     * @param dst
     */
    public static void logFileOperation(
            @OpType int operationType,
            List<DocumentInfo> srcs,
            @Nullable DocumentInfo dst) {
        ProviderCounts counts = new ProviderCounts();
        countProviders(counts, srcs, dst);
        if (counts.intraProvider > 0) {
            logIntraProviderFileOps(dst.authority, operationType);
        }
        if (counts.systemProvider > 0) {
            // Log file operations on system providers.
            logInterProviderFileOps(MetricConsts.PROVIDER_SYSTEM, dst, operationType);
        }
        if (counts.externalProvider > 0) {
            // Log file operations on external providers.
            logInterProviderFileOps(MetricConsts.PROVIDER_EXTERNAL, dst, operationType);
        }
    }

    public static void logFileOperated(
            @OpType int operationType, @MetricConsts.FileOpMode int approach) {
        switch (operationType) {
            case FileOperationService.OPERATION_COPY:
                DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_FILE_OP_COPY_MOVE_MODE_REPORTED,
                        MetricConsts.FILEOP_COPY, approach);
                break;
            case FileOperationService.OPERATION_MOVE:
                DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_FILE_OP_COPY_MOVE_MODE_REPORTED,
                        MetricConsts.FILEOP_MOVE, approach);
                break;
        }
    }

    /**
     * Logs create directory operation. It is a part of file operation stats. We do not
     * differentiate between internal and external locations, all create directory operations are
     * logged under COUNT_FILEOP_SYSTEM. Call this when a create directory operation has completed.
     */
    public static void logCreateDirOperation() {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_PROVIDER_FILE_OP,
                MetricConsts.PROVIDER_SYSTEM, MetricConsts.FILEOP_CREATE_DIR);
    }

    /**
     * Logs rename file operation. It is a part of file operation stats. We do not differentiate
     * between internal and external locations, all rename operations are logged under
     * COUNT_FILEOP_SYSTEM. Call this when a rename file operation has completed.
     */
    public static void logRenameFileOperation() {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_PROVIDER_FILE_OP,
                MetricConsts.PROVIDER_SYSTEM, MetricConsts.FILEOP_RENAME);
    }

    /**
     * Logs some kind of file operation error. Call this when a file operation (e.g. copy, delete)
     * fails.
     *
     * @param operationType
     * @param failedFiles
     */
    public static void logFileOperationErrors(@OpType int operationType,
            List<DocumentInfo> failedFiles, List<Uri> failedUris) {
        ProviderCounts counts = new ProviderCounts();
        countProviders(counts, failedFiles, null);
        // TODO: Report URI errors separate from file operation errors.
        countProviders(counts, failedUris);
        @MetricConsts.FileOp int opCode = MetricConsts.FILEOP_OTHER_ERROR;
        switch (operationType) {
            case FileOperationService.OPERATION_COPY:
                opCode = MetricConsts.FILEOP_COPY_ERROR;
                break;
            case FileOperationService.OPERATION_COMPRESS:
                opCode = MetricConsts.FILEOP_COMPRESS_ERROR;
                break;
            case FileOperationService.OPERATION_EXTRACT:
                opCode = MetricConsts.FILEOP_EXTRACT_ERROR;
                break;
            case FileOperationService.OPERATION_DELETE:
                opCode = MetricConsts.FILEOP_DELETE_ERROR;
                break;
            case FileOperationService.OPERATION_MOVE:
                opCode = MetricConsts.FILEOP_MOVE_ERROR;
                break;
        }
        if (counts.systemProvider > 0) {
            DocumentsStatsLog.write(
                    DocumentsStatsLog.DOCS_UI_PROVIDER_FILE_OP,
                    MetricConsts.PROVIDER_SYSTEM, opCode);
        }
        if (counts.externalProvider > 0) {
            DocumentsStatsLog.write(
                    DocumentsStatsLog.DOCS_UI_PROVIDER_FILE_OP,
                    MetricConsts.PROVIDER_EXTERNAL, opCode);
        }
    }

    public static void logFileOperationFailure(
            Context context, @MetricConsts.SubFileOp int subFileOp, Uri docUri) {
        final String authority = docUri.getAuthority();
        switch (authority) {
            case Providers.AUTHORITY_MEDIA:
                DocumentsStatsLog.write(
                        DocumentsStatsLog.DOCS_UI_FILE_OP_FAILURE,
                        MetricConsts.AUTH_MEDIA, subFileOp);
                break;
            case Providers.AUTHORITY_STORAGE:
                logStorageFileOperationFailure(context, subFileOp, docUri);
                break;
            case Providers.AUTHORITY_DOWNLOADS:
                DocumentsStatsLog.write(
                        DocumentsStatsLog.DOCS_UI_FILE_OP_FAILURE,
                        MetricConsts.AUTH_DOWNLOADS, subFileOp);
                break;
            case Providers.AUTHORITY_MTP:
                DocumentsStatsLog.write(
                        DocumentsStatsLog.DOCS_UI_FILE_OP_FAILURE,
                        MetricConsts.AUTH_MTP, subFileOp);
                break;
            default:
                DocumentsStatsLog.write(
                        DocumentsStatsLog.DOCS_UI_FILE_OP_FAILURE,
                        MetricConsts.AUTH_OTHER, subFileOp);
                break;
        }
    }

    /**
     * Logs create directory operation error. We do not differentiate between internal and external
     * locations, all create directory errors are logged under COUNT_FILEOP_SYSTEM. Call this when a
     * create directory operation fails.
     */
    public static void logCreateDirError() {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_PROVIDER_FILE_OP,
                MetricConsts.PROVIDER_SYSTEM, MetricConsts.FILEOP_CREATE_DIR_ERROR);
    }

    /**
     * Logs rename file operation error. We do not differentiate between internal and external
     * locations, all rename errors are logged under COUNT_FILEOP_SYSTEM. Call this
     * when a rename file operation fails.
     */
    public static void logRenameFileError() {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_PROVIDER_FILE_OP,
                MetricConsts.PROVIDER_SYSTEM, MetricConsts.FILEOP_RENAME_ERROR);
    }

    /**
     * Logs the cancellation of a file operation.  Call this when a Job is canceled.
     *
     * @param operationType
     */
    public static void logFileOperationCancelled(@OpType int operationType) {
        DocumentsStatsLog.write(
                DocumentsStatsLog.DOCS_UI_FILE_OP_CANCELED, toMetricsOpType(operationType));
    }

    /**
     * Logs startup time in milliseconds.
     *
     * @param startupMs Startup time in milliseconds.
     */
    public static void logStartupMs(int startupMs) {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_STARTUP_MS, startupMs);
    }

    private static void logInterProviderFileOps(
            @MetricConsts.Provider int providerType,
            DocumentInfo dst,
            @OpType int operationType) {
        if (operationType == FileOperationService.OPERATION_DELETE) {
            DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_PROVIDER_FILE_OP,
                    providerType, MetricConsts.FILEOP_DELETE);
        } else {
            assert(dst != null);
            @MetricConsts.Provider int opProviderType = isSystemProvider(dst.authority)
                    ? MetricConsts.PROVIDER_SYSTEM : MetricConsts.PROVIDER_EXTERNAL;
            DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_PROVIDER_FILE_OP,
                    providerType, getOpCode(operationType, opProviderType));
        }
    }

    private static void logIntraProviderFileOps(String authority, @OpType int operationType) {
        @MetricConsts.Provider int providerType = isSystemProvider(authority)
                ? MetricConsts.PROVIDER_SYSTEM : MetricConsts.PROVIDER_EXTERNAL;
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_PROVIDER_FILE_OP,
                providerType, getOpCode(operationType, MetricConsts.PROVIDER_INTRA));
    }

    /**
     * Logs the action that was started by user.
     *
     * @param userAction
     */
    public static void logUserAction(@MetricConsts.UserAction int userAction) {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_USER_ACTION_REPORTED, userAction);
    }

    public static void logPickerLaunchedFrom(String packgeName) {
        DocumentsStatsLog.write(
                DocumentsStatsLog.DOCS_UI_PICKER_LAUNCHED_FROM_REPORTED, packgeName);
    }

    public static void logSearchType(int searchType) {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_SEARCH_TYPE_REPORTED, searchType);
    }

    public static void logSearchMode(boolean isKeywordSearch, boolean isChipsSearch) {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_SEARCH_MODE_REPORTED,
                getSearchMode(isKeywordSearch, isChipsSearch));
    }

    /**
     * Logs drag initiated from which app, documentsUI or another app.
     */
    public static void logDragInitiated(boolean isDragInitatedFromDocsUI) {
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_DRAG_AND_DROP_REPORTED,
                isDragInitatedFromDocsUI);
    }

    public static void logPickResult(PickResult result) {
        DocumentsStatsLog.write(
                DocumentsStatsLog.DOCS_UI_PICK_RESULT_REPORTED,
                result.getActionCount(),
                result.getDuration(),
                result.getFileCount(),
                result.isSearching(),
                result.getRoot(),
                result.getMimeType(),
                result.getRepeatedPickTimes());

        DevicePolicyEventLogger.write(DevicePolicyMetricConsts.EVENT_ID_DOCSUI_PICK_RESULT,
                result.hasCrossProfileUri());
    }

    private static void logStorageFileOperationFailure(
            Context context, @MetricConsts.SubFileOp int subFileOp, Uri docUri) {
        assert(Providers.AUTHORITY_STORAGE.equals(docUri.getAuthority()));
        boolean isInternal;
        try (ContentProviderClient client = acquireUnstableProviderOrThrow(
                context.getContentResolver(), Providers.AUTHORITY_STORAGE)) {
            final Path path = DocumentsContract.findDocumentPath(wrap(client), docUri);
            final ProvidersAccess providers = DocumentsApplication.getProvidersCache(context);
            final RootInfo root = providers.getRootOneshot(UserId.DEFAULT_USER,
                    Providers.AUTHORITY_STORAGE, path.getRootId());
            isInternal = !root.supportsEject();
        } catch (FileNotFoundException | RemoteException | RuntimeException e) {
            Log.e(TAG, "Failed to obtain its root info. Log the metrics as internal.", e);
            // It's not very likely to have an external storage so log it as internal.
            isInternal = true;
        }
        @MetricConsts.MetricsAuth final int authority = isInternal
                ? MetricConsts.AUTH_STORAGE_INTERNAL : MetricConsts.AUTH_STORAGE_EXTERNAL;
        DocumentsStatsLog.write(DocumentsStatsLog.DOCS_UI_FILE_OP_FAILURE, authority, subFileOp);
    }

    /**
     * Generates an integer identifying the given root. For privacy, this function only recognizes a
     * small set of hard-coded roots (ones provided by the system). Other roots are all grouped into
     * a single ROOT_OTHER bucket.
     */
    private static @MetricConsts.Root int sanitizeRoot(Uri uri) {
        if (uri == null || uri.getAuthority() == null || LauncherActivity.isLaunchUri(uri)) {
            return MetricConsts.ROOT_NONE;
        }
        switch (uri.getAuthority()) {
            case Providers.AUTHORITY_MEDIA:
                String rootId = getRootIdSafely(uri);
                if (rootId == null) {
                    return MetricConsts.ROOT_NONE;
                }
                switch (rootId) {
                    case Providers.ROOT_ID_AUDIO:
                        return MetricConsts.ROOT_AUDIO;
                    case Providers.ROOT_ID_IMAGES:
                        return MetricConsts.ROOT_IMAGES;
                    case Providers.ROOT_ID_VIDEOS:
                        return MetricConsts.ROOT_VIDEOS;
                    case Providers.ROOT_ID_DOCUMENTS:
                        return MetricConsts.ROOT_DOCUMENTS;
                    default:
                        return MetricConsts.ROOT_OTHER_DOCS_PROVIDER;
                }
            case Providers.AUTHORITY_STORAGE:
                rootId = getRootIdSafely(uri);
                if (rootId == null) {
                    return MetricConsts.ROOT_NONE;
                }
                if (Providers.ROOT_ID_HOME.equals(rootId)) {
                    return MetricConsts.ROOT_HOME;
                } else {
                    return MetricConsts.ROOT_DEVICE_STORAGE;
                }
            case Providers.AUTHORITY_DOWNLOADS:
                return MetricConsts.ROOT_DOWNLOADS;
            case Providers.AUTHORITY_MTP:
                return MetricConsts.ROOT_MTP;
            default:
                return MetricConsts.ROOT_OTHER_DOCS_PROVIDER;
        }
    }

    /** @see #sanitizeRoot(Uri) */
    public static @MetricConsts.Root int sanitizeRoot(RootInfo root) {
        if (root.isRecents()) {
            // Recents root is special and only identifiable via this method call. Other roots are
            // identified by URI.
            return MetricConsts.ROOT_RECENTS;
        } else {
            return sanitizeRoot(root.getUri());
        }
    }

    /** @see #sanitizeRoot(Uri) */
    public static @MetricConsts.Root int sanitizeRoot(ResolveInfo info) {
        // Log all apps under a single bucket in the roots histogram.
        return MetricConsts.ROOT_THIRD_PARTY_APP;
    }

    /**
     * Generates an int identifying a mime type. For privacy, this function only recognizes a small
     * set of hard-coded types. For any other type, this function returns "other".
     *
     * @param mimeType
     * @return
     */
    public static @MetricConsts.Mime int sanitizeMime(String mimeType) {
        if (mimeType == null) {
            return MetricConsts.MIME_NONE;
        } else if ("*/*".equals(mimeType)) {
            return MetricConsts.MIME_ANY;
        } else {
            String type = mimeType.substring(0, mimeType.indexOf('/'));
            switch (type) {
                case "application":
                    return MetricConsts.MIME_APPLICATION;
                case "audio":
                    return MetricConsts.MIME_AUDIO;
                case "image":
                    return MetricConsts.MIME_IMAGE;
                case "message":
                    return MetricConsts.MIME_MESSAGE;
                case "multipart":
                    return MetricConsts.MIME_MULTIPART;
                case "text":
                    return MetricConsts.MIME_TEXT;
                case "video":
                    return MetricConsts.MIME_VIDEO;
            }
        }
        // Bucket all other types into one bucket.
        return MetricConsts.MIME_OTHER;
    }

    private static boolean isSystemProvider(String authority) {
        switch (authority) {
            case Providers.AUTHORITY_MEDIA:
            case Providers.AUTHORITY_STORAGE:
            case Providers.AUTHORITY_DOWNLOADS:
                return true;
            default:
                return false;
        }
    }

    /**
     * @param operation
     * @param providerType
     * @return An opcode, suitable for use as histogram bucket, for the given operation/provider
     *         combination.
     */
    private static @MetricConsts.FileOp int getOpCode(
            @OpType int operation, @MetricConsts.Provider int providerType) {
        switch (operation) {
            case FileOperationService.OPERATION_COPY:
                switch (providerType) {
                    case MetricConsts.PROVIDER_INTRA:
                        return MetricConsts.FILEOP_COPY_INTRA_PROVIDER;
                    case MetricConsts.PROVIDER_SYSTEM:
                        return MetricConsts.FILEOP_COPY_SYSTEM_PROVIDER;
                    case MetricConsts.PROVIDER_EXTERNAL:
                        return MetricConsts.FILEOP_COPY_EXTERNAL_PROVIDER;
                }
            case FileOperationService.OPERATION_COMPRESS:
                switch (providerType) {
                    case MetricConsts.PROVIDER_INTRA:
                        return MetricConsts.FILEOP_COMPRESS_INTRA_PROVIDER;
                    case MetricConsts.PROVIDER_SYSTEM:
                        return MetricConsts.FILEOP_COMPRESS_SYSTEM_PROVIDER;
                    case MetricConsts.PROVIDER_EXTERNAL:
                        return MetricConsts.FILEOP_COMPRESS_EXTERNAL_PROVIDER;
                }
            case FileOperationService.OPERATION_EXTRACT:
                switch (providerType) {
                    case MetricConsts.PROVIDER_INTRA:
                        return MetricConsts.FILEOP_EXTRACT_INTRA_PROVIDER;
                    case MetricConsts.PROVIDER_SYSTEM:
                        return MetricConsts.FILEOP_EXTRACT_SYSTEM_PROVIDER;
                    case MetricConsts.PROVIDER_EXTERNAL:
                        return MetricConsts.FILEOP_EXTRACT_EXTERNAL_PROVIDER;
                }
            case FileOperationService.OPERATION_MOVE:
                switch (providerType) {
                    case MetricConsts.PROVIDER_INTRA:
                        return MetricConsts.FILEOP_MOVE_INTRA_PROVIDER;
                    case MetricConsts.PROVIDER_SYSTEM:
                        return MetricConsts.FILEOP_MOVE_SYSTEM_PROVIDER;
                    case MetricConsts.PROVIDER_EXTERNAL:
                        return MetricConsts.FILEOP_MOVE_EXTERNAL_PROVIDER;
                }
            case FileOperationService.OPERATION_DELETE:
                return MetricConsts.FILEOP_DELETE;
            default:
                Log.w(TAG, "Unrecognized operation type when logging a file operation");
                return MetricConsts.FILEOP_OTHER;
        }
    }

    /**
     * Maps FileOperationService OpType values, to MetricsOpType values.
     */
    private static @MetricConsts.FileOp int toMetricsOpType(@OpType int operation) {
        switch (operation) {
            case FileOperationService.OPERATION_COPY:
                return MetricConsts.FILEOP_COPY;
            case FileOperationService.OPERATION_MOVE:
                return MetricConsts.FILEOP_MOVE;
            case FileOperationService.OPERATION_DELETE:
                return MetricConsts.FILEOP_DELETE;
            case FileOperationService.OPERATION_UNKNOWN:
            default:
                return MetricConsts.FILEOP_UNKNOWN;
        }
    }

    private static @MetricConsts.MetricsAction int toMetricsAction(int action) {
        switch(action) {
            case State.ACTION_OPEN:
                return MetricConsts.ACTION_OPEN;
            case State.ACTION_CREATE:
                return MetricConsts.ACTION_CREATE;
            case State.ACTION_GET_CONTENT:
                return MetricConsts.ACTION_GET_CONTENT;
            case State.ACTION_OPEN_TREE:
                return MetricConsts.ACTION_OPEN_TREE;
            case State.ACTION_BROWSE:
                return MetricConsts.ACTION_BROWSE;
            case State.ACTION_PICK_COPY_DESTINATION:
                return MetricConsts.ACTION_PICK_COPY_DESTINATION;
            default:
                return MetricConsts.ACTION_OTHER;
        }
    }

    private static int getSearchMode(boolean isKeyword, boolean isChip) {
        if (isKeyword && isChip) {
            return MetricConsts.SEARCH_KEYWORD_N_CHIPS;
        } else if (isKeyword) {
            return MetricConsts.SEARCH_KEYWORD;
        } else if (isChip) {
            return MetricConsts.SEARCH_CHIPS;
        } else {
            return MetricConsts.SEARCH_UNKNOWN;
        }
    }

    /**
     * Count the given src documents and provide a tally of how many come from the same provider as
     * the dst document (if a dst is provided), how many come from system providers, and how many
     * come from external 3rd-party providers.
     */
    private static void countProviders(
            ProviderCounts counts, List<DocumentInfo> srcs, @Nullable DocumentInfo dst) {
        for (DocumentInfo doc: srcs) {
            countForAuthority(counts, doc.authority, dst);
        }
    }

    /**
     * Count the given uris and provide a tally of how many come from the same provider as
     * the dst document (if a dst is provided), how many come from system providers, and how many
     * come from external 3rd-party providers.
     */
    private static void countProviders(ProviderCounts counts, List<Uri> uris) {
        for (Uri uri: uris) {
            countForAuthority(counts, uri.getAuthority(), null);
        }
    }

    private static void countForAuthority(
            ProviderCounts counts, String authority, @Nullable DocumentInfo dst) {
        if (dst != null && authority.equals(dst.authority)) {
            counts.intraProvider++;
        } else if (isSystemProvider(authority)){
            counts.systemProvider++;
        } else {
            counts.externalProvider++;
        }
    }

    private static class ProviderCounts {
        int intraProvider;
        int systemProvider;
        int externalProvider;
    }

    private static String getRootIdSafely(Uri uri) {
        try {
            return DocumentsContract.getRootId(uri);
        } catch (IllegalArgumentException iae) {
            Log.w(TAG, "Invalid root Uri " + uri.toSafeString());
        }
        return null;
    }

    /**
     * The implementation is copied from StatsLogInternal for the DEVICE_POLICY_EVENT. This is a
     * no-op pre-R.
     */
    private static class DevicePolicyEventLogger {
        public static void write(@DevicePolicyMetricConsts.EventId int eventId,
                boolean booleanValue) {
            if (!VersionUtils.isAtLeastR()) {
                return;
            }
            final StatsEvent.Builder builder = StatsEvent.newBuilder();
            builder.setAtomId(DevicePolicyMetricConsts.ATOM_DEVICE_POLICY_EVENT);
            builder.writeInt(eventId); // eventId
            builder.writeString(null); // adminPackageName
            builder.writeInt(0); // intValue
            builder.writeBoolean(booleanValue); // booleanValue
            builder.writeLong(0); // timePeriodMs
            builder.writeByteArray(new byte[0]); // bytes

            builder.usePooledBuffer();
            StatsLog.write(builder.build());
        }
    }
}