1 /*
2  * Copyright (C) 2014 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 package com.android.contacts.interactions;
17 
18 import android.content.AsyncTaskLoader;
19 import android.content.ContentValues;
20 import android.content.Context;
21 import android.content.pm.PackageManager;
22 import android.database.Cursor;
23 import android.database.DatabaseUtils;
24 import android.net.Uri;
25 import android.provider.CallLog.Calls;
26 import android.text.TextUtils;
27 
28 import com.google.common.annotations.VisibleForTesting;
29 
30 import com.android.contacts.common.compat.PhoneNumberUtilsCompat;
31 import com.android.contacts.common.util.PermissionsUtil;
32 
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.Comparator;
36 import java.util.List;
37 
38 public class CallLogInteractionsLoader extends AsyncTaskLoader<List<ContactInteraction>> {
39 
40     private final String[] mPhoneNumbers;
41     private final int mMaxToRetrieve;
42     private List<ContactInteraction> mData;
43 
CallLogInteractionsLoader(Context context, String[] phoneNumbers, int maxToRetrieve)44     public CallLogInteractionsLoader(Context context, String[] phoneNumbers,
45             int maxToRetrieve) {
46         super(context);
47         mPhoneNumbers = phoneNumbers;
48         mMaxToRetrieve = maxToRetrieve;
49     }
50 
51     @Override
loadInBackground()52     public List<ContactInteraction> loadInBackground() {
53         if (!PermissionsUtil.hasPhonePermissions(getContext())
54                 || !getContext().getPackageManager()
55                         .hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
56                 || mPhoneNumbers == null || mPhoneNumbers.length <= 0 || mMaxToRetrieve <= 0) {
57             return Collections.emptyList();
58         }
59 
60         final List<ContactInteraction> interactions = new ArrayList<>();
61         for (String number : mPhoneNumbers) {
62             interactions.addAll(getCallLogInteractions(number));
63         }
64         // Sort the call log interactions by date for duplicate removal
65         Collections.sort(interactions, new Comparator<ContactInteraction>() {
66             @Override
67             public int compare(ContactInteraction i1, ContactInteraction i2) {
68                 if (i2.getInteractionDate() - i1.getInteractionDate() > 0) {
69                     return 1;
70                 } else if (i2.getInteractionDate() == i1.getInteractionDate()) {
71                     return 0;
72                 } else {
73                     return -1;
74                 }
75             }
76         });
77         // Duplicates only occur because of fuzzy matching. No need to dedupe a single number.
78         if (mPhoneNumbers.length == 1) {
79             return interactions;
80         }
81         return pruneDuplicateCallLogInteractions(interactions, mMaxToRetrieve);
82     }
83 
84     /**
85      * Two different phone numbers can match the same call log entry (since phone number
86      * matching is inexact). Therefore, we need to remove duplicates. In a reasonable call log,
87      * every entry should have a distinct date. Therefore, we can assume duplicate entries are
88      * adjacent entries.
89      * @param interactions The interaction list potentially containing duplicates
90      * @return The list with duplicates removed
91      */
92     @VisibleForTesting
pruneDuplicateCallLogInteractions( List<ContactInteraction> interactions, int maxToRetrieve)93     static List<ContactInteraction> pruneDuplicateCallLogInteractions(
94             List<ContactInteraction> interactions, int maxToRetrieve) {
95         final List<ContactInteraction> subsetInteractions = new ArrayList<>();
96         for (int i = 0; i < interactions.size(); i++) {
97             if (i >= 1 && interactions.get(i).getInteractionDate() ==
98                     interactions.get(i-1).getInteractionDate()) {
99                 continue;
100             }
101             subsetInteractions.add(interactions.get(i));
102             if (subsetInteractions.size() >= maxToRetrieve) {
103                 break;
104             }
105         }
106         return subsetInteractions;
107     }
108 
getCallLogInteractions(String phoneNumber)109     private List<ContactInteraction> getCallLogInteractions(String phoneNumber) {
110         final String normalizedNumber = PhoneNumberUtilsCompat.normalizeNumber(phoneNumber);
111         // If the number contains only symbols, we can skip it
112         if (TextUtils.isEmpty(normalizedNumber)) {
113             return Collections.emptyList();
114         }
115         final Uri uri = Uri.withAppendedPath(Calls.CONTENT_FILTER_URI,
116                 Uri.encode(normalizedNumber));
117         // Append the LIMIT clause onto the ORDER BY clause. This won't cause crashes as long
118         // as we don't also set the {@link android.provider.CallLog.Calls.LIMIT_PARAM_KEY} that
119         // becomes available in KK.
120         final String orderByAndLimit = Calls.DATE + " DESC LIMIT " + mMaxToRetrieve;
121         final Cursor cursor = getContext().getContentResolver().query(uri, null, null, null,
122                 orderByAndLimit);
123         try {
124             if (cursor == null || cursor.getCount() < 1) {
125                 return Collections.emptyList();
126             }
127             cursor.moveToPosition(-1);
128             List<ContactInteraction> interactions = new ArrayList<>();
129             while (cursor.moveToNext()) {
130                 final ContentValues values = new ContentValues();
131                 DatabaseUtils.cursorRowToContentValues(cursor, values);
132                 interactions.add(new CallLogInteraction(values));
133             }
134             return interactions;
135         } finally {
136             if (cursor != null) {
137                 cursor.close();
138             }
139         }
140     }
141 
142     @Override
onStartLoading()143     protected void onStartLoading() {
144         super.onStartLoading();
145 
146         if (mData != null) {
147             deliverResult(mData);
148         }
149 
150         if (takeContentChanged() || mData == null) {
151             forceLoad();
152         }
153     }
154 
155     @Override
onStopLoading()156     protected void onStopLoading() {
157         // Attempt to cancel the current load task if possible.
158         cancelLoad();
159     }
160 
161     @Override
deliverResult(List<ContactInteraction> data)162     public void deliverResult(List<ContactInteraction> data) {
163         mData = data;
164         if (isStarted()) {
165             super.deliverResult(data);
166         }
167     }
168 
169     @Override
onReset()170     protected void onReset() {
171         super.onReset();
172 
173         // Ensure the loader is stopped
174         onStopLoading();
175         if (mData != null) {
176             mData.clear();
177         }
178     }
179 }