blob: f01bddd58dd4383cdbc3f09cccd77a6e7938d694 [file] [log] [blame]
Eric Erfanianccca3152017-02-22 16:32:36 -08001/*
2 * Copyright (C) 2013 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
17package com.android.incallui;
18
19import android.content.Context;
20import android.graphics.Bitmap;
21import android.graphics.drawable.BitmapDrawable;
22import android.graphics.drawable.Drawable;
23import android.media.RingtoneManager;
24import android.net.Uri;
Eric Erfanian9779f962017-03-27 12:31:48 -070025import android.os.SystemClock;
wangqicf61ca02017-08-31 15:32:55 -070026import android.os.Trace;
Eric Erfanianccca3152017-02-22 16:32:36 -080027import android.provider.ContactsContract.CommonDataKinds.Phone;
28import android.provider.ContactsContract.Contacts;
29import android.provider.ContactsContract.DisplayNameSources;
30import android.support.annotation.AnyThread;
31import android.support.annotation.MainThread;
32import android.support.annotation.NonNull;
Eric Erfaniand8046e52017-04-06 09:41:50 -070033import android.support.annotation.Nullable;
Eric Erfanianccca3152017-02-22 16:32:36 -080034import android.support.annotation.WorkerThread;
Eric Erfanian2ca43182017-08-31 06:57:16 -070035import android.support.v4.content.ContextCompat;
Eric Erfanianccca3152017-02-22 16:32:36 -080036import android.support.v4.os.UserManagerCompat;
37import android.telecom.TelecomManager;
Eric Erfaniand5e47f62017-03-15 14:41:07 -070038import android.telephony.PhoneNumberUtils;
Eric Erfanianccca3152017-02-22 16:32:36 -080039import android.text.TextUtils;
40import android.util.ArrayMap;
41import android.util.ArraySet;
42import com.android.contacts.common.ContactsUtils;
43import com.android.dialer.common.Assert;
Eric Erfaniand8046e52017-04-06 09:41:50 -070044import com.android.dialer.common.concurrent.DialerExecutor;
45import com.android.dialer.common.concurrent.DialerExecutor.Worker;
zachh0cd36a62017-10-31 12:04:05 -070046import com.android.dialer.common.concurrent.DialerExecutorComponent;
Eric Erfanian8369df02017-05-03 10:27:13 -070047import com.android.dialer.logging.ContactLookupResult;
48import com.android.dialer.logging.ContactSource;
Eric Erfanian9779f962017-03-27 12:31:48 -070049import com.android.dialer.oem.CequintCallerIdManager;
50import com.android.dialer.oem.CequintCallerIdManager.CequintCallerIdContact;
Eric Erfanianccca3152017-02-22 16:32:36 -080051import com.android.dialer.phonenumbercache.CachedNumberLookupService;
52import com.android.dialer.phonenumbercache.CachedNumberLookupService.CachedContactInfo;
53import com.android.dialer.phonenumbercache.ContactInfo;
54import com.android.dialer.phonenumbercache.PhoneNumberCache;
55import com.android.dialer.phonenumberutil.PhoneNumberHelper;
56import com.android.dialer.util.MoreStrings;
57import com.android.incallui.CallerInfoAsyncQuery.OnQueryCompleteListener;
58import com.android.incallui.ContactsAsyncHelper.OnImageLoadCompleteListener;
59import com.android.incallui.bindings.PhoneNumberService;
60import com.android.incallui.call.DialerCall;
61import com.android.incallui.incall.protocol.ContactPhotoType;
62import java.util.Map;
63import java.util.Objects;
64import java.util.Set;
65import java.util.concurrent.ConcurrentHashMap;
66import org.json.JSONException;
67import org.json.JSONObject;
68
69/**
70 * Class responsible for querying Contact Information for DialerCall objects. Can perform
71 * asynchronous requests to the Contact Provider for information as well as respond synchronously
72 * for any data that it currently has cached from previous queries. This class always gets called
73 * from the UI thread so it does not need thread protection.
74 */
75public class ContactInfoCache implements OnImageLoadCompleteListener {
76
77 private static final String TAG = ContactInfoCache.class.getSimpleName();
78 private static final int TOKEN_UPDATE_PHOTO_FOR_CALL_STATE = 0;
linyuh183cb712017-12-27 17:02:37 -080079 private static ContactInfoCache cache = null;
80 private final Context context;
81 private final PhoneNumberService phoneNumberService;
Eric Erfanianccca3152017-02-22 16:32:36 -080082 // Cache info map needs to be thread-safe since it could be modified by both main thread and
83 // worker thread.
linyuh183cb712017-12-27 17:02:37 -080084 private final ConcurrentHashMap<String, ContactCacheEntry> infoMap = new ConcurrentHashMap<>();
85 private final Map<String, Set<ContactInfoCacheCallback>> callBacks = new ArrayMap<>();
86 private int queryId;
zachh6a4cebd2017-10-24 17:10:06 -070087 private final DialerExecutor<CnapInformationWrapper> cachedNumberLookupExecutor;
Eric Erfaniand8046e52017-04-06 09:41:50 -070088
89 private static class CachedNumberLookupWorker implements Worker<CnapInformationWrapper, Void> {
90 @Nullable
91 @Override
92 public Void doInBackground(@Nullable CnapInformationWrapper input) {
93 if (input == null) {
94 return null;
95 }
96 ContactInfo contactInfo = new ContactInfo();
97 CachedContactInfo cacheInfo = input.service.buildCachedContactInfo(contactInfo);
Eric Erfanian8369df02017-05-03 10:27:13 -070098 cacheInfo.setSource(ContactSource.Type.SOURCE_TYPE_CNAP, "CNAP", 0);
Eric Erfaniand8046e52017-04-06 09:41:50 -070099 contactInfo.name = input.cnapName;
100 contactInfo.number = input.number;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700101 try {
102 final JSONObject contactRows =
103 new JSONObject()
104 .put(
105 Phone.CONTENT_ITEM_TYPE,
Eric Erfanian10b34a52017-05-04 08:23:17 -0700106 new JSONObject().put(Phone.NUMBER, contactInfo.number));
Eric Erfaniand8046e52017-04-06 09:41:50 -0700107 final String jsonString =
108 new JSONObject()
109 .put(Contacts.DISPLAY_NAME, contactInfo.name)
110 .put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME)
111 .put(Contacts.CONTENT_ITEM_TYPE, contactRows)
112 .toString();
113 cacheInfo.setLookupKey(jsonString);
114 } catch (JSONException e) {
115 Log.w(TAG, "Creation of lookup key failed when caching CNAP information");
116 }
117 input.service.addContact(input.context.getApplicationContext(), cacheInfo);
118 return null;
119 }
120 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800121
122 private ContactInfoCache(Context context) {
wangqicf61ca02017-08-31 15:32:55 -0700123 Trace.beginSection("ContactInfoCache constructor");
linyuh183cb712017-12-27 17:02:37 -0800124 this.context = context;
125 phoneNumberService = Bindings.get(context).newPhoneNumberService(context);
zachh6a4cebd2017-10-24 17:10:06 -0700126 cachedNumberLookupExecutor =
linyuh183cb712017-12-27 17:02:37 -0800127 DialerExecutorComponent.get(this.context)
zachh0cd36a62017-10-31 12:04:05 -0700128 .dialerExecutorFactory()
129 .createNonUiTaskBuilder(new CachedNumberLookupWorker())
130 .build();
wangqicf61ca02017-08-31 15:32:55 -0700131 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800132 }
133
134 public static synchronized ContactInfoCache getInstance(Context mContext) {
linyuh183cb712017-12-27 17:02:37 -0800135 if (cache == null) {
136 cache = new ContactInfoCache(mContext.getApplicationContext());
Eric Erfanianccca3152017-02-22 16:32:36 -0800137 }
linyuh183cb712017-12-27 17:02:37 -0800138 return cache;
Eric Erfanianccca3152017-02-22 16:32:36 -0800139 }
140
twyena40a9ef2018-05-22 17:35:59 -0700141 static ContactCacheEntry buildCacheEntryFromCall(Context context, DialerCall call) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800142 final ContactCacheEntry entry = new ContactCacheEntry();
143
144 // TODO: get rid of caller info.
145 final CallerInfo info = CallerInfoUtils.buildCallerInfo(context, call);
Eric Erfanian8369df02017-05-03 10:27:13 -0700146 ContactInfoCache.populateCacheEntry(context, info, entry, call.getNumberPresentation());
Eric Erfanianccca3152017-02-22 16:32:36 -0800147 return entry;
148 }
149
150 /** Populate a cache entry from a call (which got converted into a caller info). */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700151 private static void populateCacheEntry(
Eric Erfanianccca3152017-02-22 16:32:36 -0800152 @NonNull Context context,
153 @NonNull CallerInfo info,
154 @NonNull ContactCacheEntry cce,
Eric Erfanian8369df02017-05-03 10:27:13 -0700155 int presentation) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800156 Objects.requireNonNull(info);
157 String displayName = null;
158 String displayNumber = null;
Eric Erfanianccca3152017-02-22 16:32:36 -0800159 String label = null;
160 boolean isSipCall = false;
161
162 // It appears that there is a small change in behaviour with the
163 // PhoneUtils' startGetCallerInfo whereby if we query with an
164 // empty number, we will get a valid CallerInfo object, but with
165 // fields that are all null, and the isTemporary boolean input
166 // parameter as true.
167
168 // In the past, we would see a NULL callerinfo object, but this
169 // ends up causing null pointer exceptions elsewhere down the
170 // line in other cases, so we need to make this fix instead. It
171 // appears that this was the ONLY call to PhoneUtils
172 // .getCallerInfo() that relied on a NULL CallerInfo to indicate
173 // an unknown contact.
174
175 // Currently, info.phoneNumber may actually be a SIP address, and
176 // if so, it might sometimes include the "sip:" prefix. That
177 // prefix isn't really useful to the user, though, so strip it off
178 // if present. (For any other URI scheme, though, leave the
179 // prefix alone.)
180 // TODO: It would be cleaner for CallerInfo to explicitly support
181 // SIP addresses instead of overloading the "phoneNumber" field.
182 // Then we could remove this hack, and instead ask the CallerInfo
183 // for a "user visible" form of the SIP address.
184 String number = info.phoneNumber;
185
186 if (!TextUtils.isEmpty(number)) {
187 isSipCall = PhoneNumberHelper.isUriNumber(number);
188 if (number.startsWith("sip:")) {
189 number = number.substring(4);
190 }
191 }
192
193 if (TextUtils.isEmpty(info.name)) {
194 // No valid "name" in the CallerInfo, so fall back to
195 // something else.
196 // (Typically, we promote the phone number up to the "name" slot
197 // onscreen, and possibly display a descriptive string in the
198 // "number" slot.)
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700199 if (TextUtils.isEmpty(number) && TextUtils.isEmpty(info.cnapName)) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800200 // No name *or* number! Display a generic "unknown" string
201 // (or potentially some other default based on the presentation.)
202 displayName = getPresentationString(context, presentation, info.callSubject);
203 Log.d(TAG, " ==> no name *or* number! displayName = " + displayName);
204 } else if (presentation != TelecomManager.PRESENTATION_ALLOWED) {
205 // This case should never happen since the network should never send a phone #
206 // AND a restricted presentation. However we leave it here in case of weird
207 // network behavior
208 displayName = getPresentationString(context, presentation, info.callSubject);
209 Log.d(TAG, " ==> presentation not allowed! displayName = " + displayName);
210 } else if (!TextUtils.isEmpty(info.cnapName)) {
211 // No name, but we do have a valid CNAP name, so use that.
212 displayName = info.cnapName;
213 info.name = info.cnapName;
linyuhb06d0092018-03-01 15:05:36 -0800214 displayNumber = PhoneNumberHelper.formatNumber(context, number, info.countryIso);
Eric Erfanianccca3152017-02-22 16:32:36 -0800215 Log.d(
216 TAG,
217 " ==> cnapName available: displayName '"
218 + displayName
219 + "', displayNumber '"
220 + displayNumber
221 + "'");
222 } else {
223 // No name; all we have is a number. This is the typical
224 // case when an incoming call doesn't match any contact,
225 // or if you manually dial an outgoing number using the
226 // dialpad.
linyuhb06d0092018-03-01 15:05:36 -0800227 displayNumber = PhoneNumberHelper.formatNumber(context, number, info.countryIso);
Eric Erfanianccca3152017-02-22 16:32:36 -0800228
Eric Erfanianccca3152017-02-22 16:32:36 -0800229 Log.d(
230 TAG,
231 " ==> no name; falling back to number:"
232 + " displayNumber '"
233 + Log.pii(displayNumber)
Eric Erfanianccca3152017-02-22 16:32:36 -0800234 + "'");
235 }
236 } else {
237 // We do have a valid "name" in the CallerInfo. Display that
238 // in the "name" slot, and the phone number in the "number" slot.
239 if (presentation != TelecomManager.PRESENTATION_ALLOWED) {
240 // This case should never happen since the network should never send a name
241 // AND a restricted presentation. However we leave it here in case of weird
242 // network behavior
243 displayName = getPresentationString(context, presentation, info.callSubject);
244 Log.d(
245 TAG,
246 " ==> valid name, but presentation not allowed!" + " displayName = " + displayName);
247 } else {
248 // Causes cce.namePrimary to be set as info.name below. CallCardPresenter will
249 // later determine whether to use the name or nameAlternative when presenting
250 displayName = info.name;
251 cce.nameAlternative = info.nameAlternative;
linyuhb06d0092018-03-01 15:05:36 -0800252 displayNumber = PhoneNumberHelper.formatNumber(context, number, info.countryIso);
Eric Erfanianccca3152017-02-22 16:32:36 -0800253 label = info.phoneLabel;
254 Log.d(
255 TAG,
256 " ==> name is present in CallerInfo: displayName '"
257 + displayName
258 + "', displayNumber '"
259 + displayNumber
260 + "'");
261 }
262 }
263
264 cce.namePrimary = displayName;
265 cce.number = displayNumber;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700266 cce.location = info.geoDescription;
Eric Erfanianccca3152017-02-22 16:32:36 -0800267 cce.label = label;
268 cce.isSipCall = isSipCall;
269 cce.userType = info.userType;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700270 cce.originalPhoneNumber = info.phoneNumber;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700271 cce.shouldShowLocation = info.shouldShowGeoDescription;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700272 cce.isEmergencyNumber = info.isEmergencyNumber();
273 cce.isVoicemailNumber = info.isVoiceMailNumber();
Eric Erfanianccca3152017-02-22 16:32:36 -0800274
275 if (info.contactExists) {
wangqi262b6f22018-03-16 12:27:56 -0700276 cce.contactLookupResult = info.contactLookupResultType;
Eric Erfanianccca3152017-02-22 16:32:36 -0800277 }
278 }
279
280 /** Gets name strings based on some special presentation modes and the associated custom label. */
281 private static String getPresentationString(
282 Context context, int presentation, String customLabel) {
283 String name = context.getString(R.string.unknown);
284 if (!TextUtils.isEmpty(customLabel)
285 && ((presentation == TelecomManager.PRESENTATION_UNKNOWN)
286 || (presentation == TelecomManager.PRESENTATION_RESTRICTED))) {
287 name = customLabel;
288 return name;
289 } else {
290 if (presentation == TelecomManager.PRESENTATION_RESTRICTED) {
zachh03b13192018-01-26 10:56:46 -0800291 name = PhoneNumberHelper.getDisplayNameForRestrictedNumber(context);
Eric Erfanianccca3152017-02-22 16:32:36 -0800292 } else if (presentation == TelecomManager.PRESENTATION_PAYPHONE) {
293 name = context.getString(R.string.payphone);
294 }
295 }
296 return name;
297 }
298
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700299 ContactCacheEntry getInfo(String callId) {
linyuh183cb712017-12-27 17:02:37 -0800300 return infoMap.get(callId);
Eric Erfanianccca3152017-02-22 16:32:36 -0800301 }
302
Eric Erfaniand8046e52017-04-06 09:41:50 -0700303 private static final class CnapInformationWrapper {
304 final String number;
305 final String cnapName;
306 final Context context;
307 final CachedNumberLookupService service;
308
309 CnapInformationWrapper(
310 String number, String cnapName, Context context, CachedNumberLookupService service) {
311 this.number = number;
312 this.cnapName = cnapName;
313 this.context = context;
314 this.service = service;
315 }
316 }
317
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700318 void maybeInsertCnapInformationIntoCache(
Eric Erfanianccca3152017-02-22 16:32:36 -0800319 Context context, final DialerCall call, final CallerInfo info) {
320 final CachedNumberLookupService cachedNumberLookupService =
321 PhoneNumberCache.get(context).getCachedNumberLookupService();
322 if (!UserManagerCompat.isUserUnlocked(context)) {
323 Log.i(TAG, "User locked, not inserting cnap info into cache");
324 return;
325 }
326 if (cachedNumberLookupService == null
327 || TextUtils.isEmpty(info.cnapName)
linyuh183cb712017-12-27 17:02:37 -0800328 || infoMap.get(call.getId()) != null) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800329 return;
330 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800331 Log.i(TAG, "Found contact with CNAP name - inserting into cache");
Eric Erfaniand8046e52017-04-06 09:41:50 -0700332
333 cachedNumberLookupExecutor.executeParallel(
334 new CnapInformationWrapper(
335 call.getNumber(), info.cnapName, context, cachedNumberLookupService));
Eric Erfanianccca3152017-02-22 16:32:36 -0800336 }
337
338 /**
339 * Requests contact data for the DialerCall object passed in. Returns the data through callback.
340 * If callback is null, no response is made, however the query is still performed and cached.
341 *
342 * @param callback The function to call back when the call is found. Can be null.
343 */
344 @MainThread
345 public void findInfo(
346 @NonNull final DialerCall call,
347 final boolean isIncoming,
348 @NonNull ContactInfoCacheCallback callback) {
wangqicf61ca02017-08-31 15:32:55 -0700349 Trace.beginSection("ContactInfoCache.findInfo");
Eric Erfanianccca3152017-02-22 16:32:36 -0800350 Assert.isMainThread();
351 Objects.requireNonNull(callback);
352
wangqic8cf79e2017-10-17 09:21:00 -0700353 Trace.beginSection("prepare callback");
Eric Erfanianccca3152017-02-22 16:32:36 -0800354 final String callId = call.getId();
linyuh183cb712017-12-27 17:02:37 -0800355 final ContactCacheEntry cacheEntry = infoMap.get(callId);
356 Set<ContactInfoCacheCallback> callBacks = this.callBacks.get(callId);
Eric Erfanianccca3152017-02-22 16:32:36 -0800357
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700358 // We need to force a new query if phone number has changed.
359 boolean forceQuery = needForceQuery(call, cacheEntry);
wangqic8cf79e2017-10-17 09:21:00 -0700360 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700361 Log.d(TAG, "findInfo: callId = " + callId + "; forceQuery = " + forceQuery);
362
363 // If we have a previously obtained intermediate result return that now except needs
364 // force query.
365 if (cacheEntry != null && !forceQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800366 Log.d(
367 TAG,
368 "Contact lookup. In memory cache hit; lookup "
369 + (callBacks == null ? "complete" : "still running"));
370 callback.onContactInfoComplete(callId, cacheEntry);
371 // If no other callbacks are in flight, we're done.
372 if (callBacks == null) {
wangqicf61ca02017-08-31 15:32:55 -0700373 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800374 return;
375 }
376 }
377
378 // If the entry already exists, add callback
379 if (callBacks != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700380 Log.d(TAG, "Another query is in progress, add callback only.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800381 callBacks.add(callback);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700382 if (!forceQuery) {
383 Log.d(TAG, "No need to query again, just return and wait for existing query to finish");
wangqicf61ca02017-08-31 15:32:55 -0700384 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700385 return;
386 }
387 } else {
388 Log.d(TAG, "Contact lookup. In memory cache miss; searching provider.");
389 // New lookup
390 callBacks = new ArraySet<>();
391 callBacks.add(callback);
linyuh183cb712017-12-27 17:02:37 -0800392 this.callBacks.put(callId, callBacks);
Eric Erfanianccca3152017-02-22 16:32:36 -0800393 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800394
wangqic8cf79e2017-10-17 09:21:00 -0700395 Trace.beginSection("prepare query");
Eric Erfanianccca3152017-02-22 16:32:36 -0800396 /**
397 * Performs a query for caller information. Save any immediate data we get from the query. An
398 * asynchronous query may also be made for any data that we do not already have. Some queries,
399 * such as those for voicemail and emergency call information, will not perform an additional
400 * asynchronous query.
401 */
linyuh183cb712017-12-27 17:02:37 -0800402 final CallerInfoQueryToken queryToken = new CallerInfoQueryToken(queryId, callId);
403 queryId++;
Eric Erfanianccca3152017-02-22 16:32:36 -0800404 final CallerInfo callerInfo =
405 CallerInfoUtils.getCallerInfoForCall(
linyuh183cb712017-12-27 17:02:37 -0800406 context,
Eric Erfanianccca3152017-02-22 16:32:36 -0800407 call,
Eric Erfaniand8046e52017-04-06 09:41:50 -0700408 new DialerCallCookieWrapper(callId, call.getNumberPresentation(), call.getCnapName()),
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700409 new FindInfoCallback(isIncoming, queryToken));
wangqic8cf79e2017-10-17 09:21:00 -0700410 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800411
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700412 if (cacheEntry != null) {
413 // We should not override the old cache item until the new query is
414 // back. We should only update the queryId. Otherwise, we may see
415 // flicker of the name and image (old cache -> new cache before query
416 // -> new cache after query)
linyuh183cb712017-12-27 17:02:37 -0800417 cacheEntry.queryId = queryToken.queryId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700418 Log.d(TAG, "There is an existing cache. Do not override until new query is back");
419 } else {
420 ContactCacheEntry initialCacheEntry =
421 updateCallerInfoInCacheOnAnyThread(
Eric Erfanian2ca43182017-08-31 06:57:16 -0700422 callId, call.getNumberPresentation(), callerInfo, false, queryToken);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700423 sendInfoNotifications(callId, initialCacheEntry);
424 }
wangqicf61ca02017-08-31 15:32:55 -0700425 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800426 }
427
428 @AnyThread
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700429 private ContactCacheEntry updateCallerInfoInCacheOnAnyThread(
Eric Erfanianccca3152017-02-22 16:32:36 -0800430 String callId,
431 int numberPresentation,
432 CallerInfo callerInfo,
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700433 boolean didLocalLookup,
434 CallerInfoQueryToken queryToken) {
wangqicf61ca02017-08-31 15:32:55 -0700435 Trace.beginSection("ContactInfoCache.updateCallerInfoInCacheOnAnyThread");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700436 Log.d(
437 TAG,
438 "updateCallerInfoInCacheOnAnyThread: callId = "
439 + callId
440 + "; queryId = "
linyuh183cb712017-12-27 17:02:37 -0800441 + queryToken.queryId
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700442 + "; didLocalLookup = "
443 + didLocalLookup);
444
linyuh183cb712017-12-27 17:02:37 -0800445 ContactCacheEntry existingCacheEntry = infoMap.get(callId);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700446 Log.d(TAG, "Existing cacheEntry in hashMap " + existingCacheEntry);
447
448 // Mark it as emergency/voicemail if the cache exists and was emergency/voicemail before the
449 // number changed.
450 if (existingCacheEntry != null) {
451 if (existingCacheEntry.isEmergencyNumber) {
linyuh183cb712017-12-27 17:02:37 -0800452 callerInfo.markAsEmergency(context);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700453 } else if (existingCacheEntry.isVoicemailNumber) {
linyuh183cb712017-12-27 17:02:37 -0800454 callerInfo.markAsVoiceMail(context);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700455 }
456 }
457
Eric Erfanianccca3152017-02-22 16:32:36 -0800458 int presentationMode = numberPresentation;
459 if (callerInfo.contactExists
460 || callerInfo.isEmergencyNumber()
461 || callerInfo.isVoiceMailNumber()) {
462 presentationMode = TelecomManager.PRESENTATION_ALLOWED;
463 }
464
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700465 // We always replace the entry. The only exception is the same photo case.
linyuh183cb712017-12-27 17:02:37 -0800466 ContactCacheEntry cacheEntry = buildEntry(context, callerInfo, presentationMode);
467 cacheEntry.queryId = queryToken.queryId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700468
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700469 if (didLocalLookup) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700470 if (cacheEntry.displayPhotoUri != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700471 // When the difference between 2 numbers is only the prefix (e.g. + or IDD),
472 // we will still trigger force query so that the number can be updated on
473 // the calling screen. We need not query the image again if the previous
474 // query already has the image to avoid flickering.
475 if (existingCacheEntry != null
476 && existingCacheEntry.displayPhotoUri != null
477 && existingCacheEntry.displayPhotoUri.equals(cacheEntry.displayPhotoUri)
478 && existingCacheEntry.photo != null) {
479 Log.d(TAG, "Same picture. Do not need start image load.");
480 cacheEntry.photo = existingCacheEntry.photo;
481 cacheEntry.photoType = existingCacheEntry.photoType;
482 return cacheEntry;
Eric Erfanianccca3152017-02-22 16:32:36 -0800483 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700484
485 Log.d(TAG, "Contact lookup. Local contact found, starting image load");
486 // Load the image with a callback to update the image state.
487 // When the load is finished, onImageLoadComplete() will be called.
488 cacheEntry.hasPendingQuery = true;
489 ContactsAsyncHelper.startObtainPhotoAsync(
490 TOKEN_UPDATE_PHOTO_FOR_CALL_STATE,
linyuh183cb712017-12-27 17:02:37 -0800491 context,
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700492 cacheEntry.displayPhotoUri,
493 ContactInfoCache.this,
494 queryToken);
Eric Erfanianccca3152017-02-22 16:32:36 -0800495 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700496 Log.d(TAG, "put entry into map: " + cacheEntry);
linyuh183cb712017-12-27 17:02:37 -0800497 infoMap.put(callId, cacheEntry);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700498 } else {
499 // Don't overwrite if there is existing cache.
500 Log.d(TAG, "put entry into map if not exists: " + cacheEntry);
linyuh183cb712017-12-27 17:02:37 -0800501 infoMap.putIfAbsent(callId, cacheEntry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800502 }
wangqicf61ca02017-08-31 15:32:55 -0700503 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700504 return cacheEntry;
Eric Erfanianccca3152017-02-22 16:32:36 -0800505 }
506
Eric Erfaniand8046e52017-04-06 09:41:50 -0700507 private void maybeUpdateFromCequintCallerId(
508 CallerInfo callerInfo, String cnapName, boolean isIncoming) {
linyuh183cb712017-12-27 17:02:37 -0800509 if (!CequintCallerIdManager.isCequintCallerIdEnabled(context)) {
Eric Erfanian9779f962017-03-27 12:31:48 -0700510 return;
511 }
Eric Erfaniand8046e52017-04-06 09:41:50 -0700512 if (callerInfo.phoneNumber == null) {
513 return;
514 }
Eric Erfanian9779f962017-03-27 12:31:48 -0700515 CequintCallerIdContact cequintCallerIdContact =
linyuhfa3cd3b2018-04-26 20:21:01 -0700516 CequintCallerIdManager.getCequintCallerIdContactForCall(
linyuh183cb712017-12-27 17:02:37 -0800517 context, callerInfo.phoneNumber, cnapName, isIncoming);
Eric Erfanian9779f962017-03-27 12:31:48 -0700518
Eric Erfaniand8046e52017-04-06 09:41:50 -0700519 if (cequintCallerIdContact == null) {
520 return;
521 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700522 boolean hasUpdate = false;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700523
linyuh82953532018-04-24 16:06:06 -0700524 if (TextUtils.isEmpty(callerInfo.name) && !TextUtils.isEmpty(cequintCallerIdContact.name())) {
525 callerInfo.name = cequintCallerIdContact.name();
Eric Erfanian8369df02017-05-03 10:27:13 -0700526 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700527 }
linyuh82953532018-04-24 16:06:06 -0700528 if (!TextUtils.isEmpty(cequintCallerIdContact.geolocation())) {
529 callerInfo.geoDescription = cequintCallerIdContact.geolocation();
Eric Erfaniand8046e52017-04-06 09:41:50 -0700530 callerInfo.shouldShowGeoDescription = true;
Eric Erfanian8369df02017-05-03 10:27:13 -0700531 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700532 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700533 // Don't overwrite photo in local contacts.
534 if (!callerInfo.contactExists
535 && callerInfo.contactDisplayPhotoUri == null
linyuh82953532018-04-24 16:06:06 -0700536 && cequintCallerIdContact.photoUri() != null) {
537 callerInfo.contactDisplayPhotoUri = Uri.parse(cequintCallerIdContact.photoUri());
Eric Erfanian8369df02017-05-03 10:27:13 -0700538 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700539 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700540 // Set contact to exist to avoid phone number service lookup.
wangqid6b91d12018-01-30 16:59:03 -0800541 if (hasUpdate) {
542 callerInfo.contactExists = true;
wangqi262b6f22018-03-16 12:27:56 -0700543 callerInfo.contactLookupResultType = ContactLookupResult.Type.CEQUINT;
wangqid6b91d12018-01-30 16:59:03 -0800544 }
Eric Erfanian9779f962017-03-27 12:31:48 -0700545 }
546
Eric Erfanianccca3152017-02-22 16:32:36 -0800547 /**
548 * Implemented for ContactsAsyncHelper.OnImageLoadCompleteListener interface. Update contact photo
549 * when image is loaded in worker thread.
550 */
551 @WorkerThread
552 @Override
553 public void onImageLoaded(int token, Drawable photo, Bitmap photoIcon, Object cookie) {
554 Assert.isWorkerThread();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700555 CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie;
linyuh183cb712017-12-27 17:02:37 -0800556 final String callId = myCookie.callId;
557 final int queryId = myCookie.queryId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700558 if (!isWaitingForThisQuery(callId, queryId)) {
559 return;
560 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800561 loadImage(photo, photoIcon, cookie);
562 }
563
564 private void loadImage(Drawable photo, Bitmap photoIcon, Object cookie) {
linyuh183cb712017-12-27 17:02:37 -0800565 Log.d(TAG, "Image load complete with context: ", context);
Eric Erfanianccca3152017-02-22 16:32:36 -0800566 // TODO: may be nice to update the image view again once the newer one
567 // is available on contacts database.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700568 CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie;
linyuh183cb712017-12-27 17:02:37 -0800569 final String callId = myCookie.callId;
570 ContactCacheEntry entry = infoMap.get(callId);
Eric Erfanianccca3152017-02-22 16:32:36 -0800571
572 if (entry == null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700573 Log.e(TAG, "Image Load received for empty search entry.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800574 clearCallbacks(callId);
575 return;
576 }
577
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700578 Log.d(TAG, "setting photo for entry: ", entry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800579
580 // Conference call icons are being handled in CallCardPresenter.
581 if (photo != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700582 Log.v(TAG, "direct drawable: ", photo);
Eric Erfanianccca3152017-02-22 16:32:36 -0800583 entry.photo = photo;
584 entry.photoType = ContactPhotoType.CONTACT;
585 } else if (photoIcon != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700586 Log.v(TAG, "photo icon: ", photoIcon);
linyuh183cb712017-12-27 17:02:37 -0800587 entry.photo = new BitmapDrawable(context.getResources(), photoIcon);
Eric Erfanianccca3152017-02-22 16:32:36 -0800588 entry.photoType = ContactPhotoType.CONTACT;
589 } else {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700590 Log.v(TAG, "unknown photo");
Eric Erfanianccca3152017-02-22 16:32:36 -0800591 entry.photo = null;
592 entry.photoType = ContactPhotoType.DEFAULT_PLACEHOLDER;
593 }
594 }
595
596 /**
597 * Implemented for ContactsAsyncHelper.OnImageLoadCompleteListener interface. make sure that the
598 * call state is reflected after the image is loaded.
599 */
600 @MainThread
601 @Override
602 public void onImageLoadComplete(int token, Drawable photo, Bitmap photoIcon, Object cookie) {
603 Assert.isMainThread();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700604 CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie;
linyuh183cb712017-12-27 17:02:37 -0800605 final String callId = myCookie.callId;
606 final int queryId = myCookie.queryId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700607 if (!isWaitingForThisQuery(callId, queryId)) {
608 return;
609 }
linyuh183cb712017-12-27 17:02:37 -0800610 sendImageNotifications(callId, infoMap.get(callId));
Eric Erfanianccca3152017-02-22 16:32:36 -0800611
612 clearCallbacks(callId);
613 }
614
615 /** Blows away the stored cache values. */
616 public void clearCache() {
linyuh183cb712017-12-27 17:02:37 -0800617 infoMap.clear();
618 callBacks.clear();
619 queryId = 0;
Eric Erfanianccca3152017-02-22 16:32:36 -0800620 }
621
Eric Erfanian8369df02017-05-03 10:27:13 -0700622 private ContactCacheEntry buildEntry(Context context, CallerInfo info, int presentation) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800623 final ContactCacheEntry cce = new ContactCacheEntry();
Eric Erfanian8369df02017-05-03 10:27:13 -0700624 populateCacheEntry(context, info, cce, presentation);
Eric Erfanianccca3152017-02-22 16:32:36 -0800625
626 // This will only be true for emergency numbers
627 if (info.photoResource != 0) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700628 cce.photo = ContextCompat.getDrawable(context, info.photoResource);
Eric Erfanianccca3152017-02-22 16:32:36 -0800629 } else if (info.isCachedPhotoCurrent) {
630 if (info.cachedPhoto != null) {
631 cce.photo = info.cachedPhoto;
632 cce.photoType = ContactPhotoType.CONTACT;
633 } else {
Eric Erfanianccca3152017-02-22 16:32:36 -0800634 cce.photoType = ContactPhotoType.DEFAULT_PLACEHOLDER;
635 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800636 } else {
637 cce.displayPhotoUri = info.contactDisplayPhotoUri;
638 cce.photo = null;
639 }
640
linyuh437ae952018-03-26 12:46:18 -0700641 if (info.lookupKeyOrNull != null && info.contactIdOrZero != 0) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800642 cce.lookupUri = Contacts.getLookupUri(info.contactIdOrZero, info.lookupKeyOrNull);
643 } else {
644 Log.v(TAG, "lookup key is null or contact ID is 0 on M. Don't create a lookup uri.");
645 cce.lookupUri = null;
646 }
647
648 cce.lookupKey = info.lookupKeyOrNull;
649 cce.contactRingtoneUri = info.contactRingtoneUri;
650 if (cce.contactRingtoneUri == null || Uri.EMPTY.equals(cce.contactRingtoneUri)) {
651 cce.contactRingtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
652 }
653
654 return cce;
655 }
656
657 /** Sends the updated information to call the callbacks for the entry. */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700658 @MainThread
Eric Erfanianccca3152017-02-22 16:32:36 -0800659 private void sendInfoNotifications(String callId, ContactCacheEntry entry) {
wangqicf61ca02017-08-31 15:32:55 -0700660 Trace.beginSection("ContactInfoCache.sendInfoNotifications");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700661 Assert.isMainThread();
linyuh183cb712017-12-27 17:02:37 -0800662 final Set<ContactInfoCacheCallback> callBacks = this.callBacks.get(callId);
Eric Erfanianccca3152017-02-22 16:32:36 -0800663 if (callBacks != null) {
664 for (ContactInfoCacheCallback callBack : callBacks) {
665 callBack.onContactInfoComplete(callId, entry);
666 }
667 }
wangqicf61ca02017-08-31 15:32:55 -0700668 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800669 }
670
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700671 @MainThread
Eric Erfanianccca3152017-02-22 16:32:36 -0800672 private void sendImageNotifications(String callId, ContactCacheEntry entry) {
wangqicf61ca02017-08-31 15:32:55 -0700673 Trace.beginSection("ContactInfoCache.sendImageNotifications");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700674 Assert.isMainThread();
linyuh183cb712017-12-27 17:02:37 -0800675 final Set<ContactInfoCacheCallback> callBacks = this.callBacks.get(callId);
Eric Erfanianccca3152017-02-22 16:32:36 -0800676 if (callBacks != null && entry.photo != null) {
677 for (ContactInfoCacheCallback callBack : callBacks) {
678 callBack.onImageLoadComplete(callId, entry);
679 }
680 }
wangqicf61ca02017-08-31 15:32:55 -0700681 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800682 }
683
684 private void clearCallbacks(String callId) {
linyuh183cb712017-12-27 17:02:37 -0800685 callBacks.remove(callId);
Eric Erfanianccca3152017-02-22 16:32:36 -0800686 }
687
Eric Erfanianccca3152017-02-22 16:32:36 -0800688 /** Callback interface for the contact query. */
689 public interface ContactInfoCacheCallback {
690
691 void onContactInfoComplete(String callId, ContactCacheEntry entry);
692
693 void onImageLoadComplete(String callId, ContactCacheEntry entry);
694 }
695
696 /** This is cached contact info, which should be the ONLY info used by UI. */
697 public static class ContactCacheEntry {
698
699 public String namePrimary;
700 public String nameAlternative;
701 public String number;
702 public String location;
703 public String label;
704 public Drawable photo;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700705 @ContactPhotoType int photoType;
706 boolean isSipCall;
Eric Erfanianccca3152017-02-22 16:32:36 -0800707 // Note in cache entry whether this is a pending async loading action to know whether to
708 // wait for its callback or not.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700709 boolean hasPendingQuery;
Eric Erfanianccca3152017-02-22 16:32:36 -0800710 /** Either a display photo or a thumbnail URI. */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700711 Uri displayPhotoUri;
Eric Erfanianccca3152017-02-22 16:32:36 -0800712
713 public Uri lookupUri; // Sent to NotificationMananger
714 public String lookupKey;
Eric Erfanian8369df02017-05-03 10:27:13 -0700715 public ContactLookupResult.Type contactLookupResult = ContactLookupResult.Type.NOT_FOUND;
Eric Erfanianccca3152017-02-22 16:32:36 -0800716 public long userType = ContactsUtils.USER_TYPE_CURRENT;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700717 Uri contactRingtoneUri;
718 /** Query id to identify the query session. */
719 int queryId;
720 /** The phone number without any changes to display to the user (ex: cnap...) */
721 String originalPhoneNumber;
zachh6a4cebd2017-10-24 17:10:06 -0700722
Eric Erfaniand8046e52017-04-06 09:41:50 -0700723 boolean shouldShowLocation;
Eric Erfanian9779f962017-03-27 12:31:48 -0700724
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700725 boolean isBusiness;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700726 boolean isEmergencyNumber;
727 boolean isVoicemailNumber;
Eric Erfanianccca3152017-02-22 16:32:36 -0800728
wangqiae6c8ec2017-09-28 17:39:40 -0700729 public boolean isLocalContact() {
730 return contactLookupResult == ContactLookupResult.Type.LOCAL_CONTACT;
731 }
732
Eric Erfanianccca3152017-02-22 16:32:36 -0800733 @Override
734 public String toString() {
735 return "ContactCacheEntry{"
736 + "name='"
737 + MoreStrings.toSafeString(namePrimary)
738 + '\''
739 + ", nameAlternative='"
740 + MoreStrings.toSafeString(nameAlternative)
741 + '\''
742 + ", number='"
743 + MoreStrings.toSafeString(number)
744 + '\''
745 + ", location='"
746 + MoreStrings.toSafeString(location)
747 + '\''
748 + ", label='"
749 + label
750 + '\''
751 + ", photo="
752 + photo
753 + ", isSipCall="
754 + isSipCall
Eric Erfanianccca3152017-02-22 16:32:36 -0800755 + ", displayPhotoUri="
756 + displayPhotoUri
757 + ", contactLookupResult="
758 + contactLookupResult
759 + ", userType="
760 + userType
761 + ", contactRingtoneUri="
762 + contactRingtoneUri
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700763 + ", queryId="
764 + queryId
765 + ", originalPhoneNumber="
766 + originalPhoneNumber
Eric Erfaniand8046e52017-04-06 09:41:50 -0700767 + ", shouldShowLocation="
768 + shouldShowLocation
Eric Erfanian2ca43182017-08-31 06:57:16 -0700769 + ", isEmergencyNumber="
770 + isEmergencyNumber
771 + ", isVoicemailNumber="
772 + isVoicemailNumber
Eric Erfanianccca3152017-02-22 16:32:36 -0800773 + '}';
774 }
775 }
776
777 private static final class DialerCallCookieWrapper {
Eric Erfaniand8046e52017-04-06 09:41:50 -0700778 final String callId;
779 final int numberPresentation;
780 final String cnapName;
Eric Erfanianccca3152017-02-22 16:32:36 -0800781
Eric Erfaniand8046e52017-04-06 09:41:50 -0700782 DialerCallCookieWrapper(String callId, int numberPresentation, String cnapName) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800783 this.callId = callId;
784 this.numberPresentation = numberPresentation;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700785 this.cnapName = cnapName;
Eric Erfanianccca3152017-02-22 16:32:36 -0800786 }
787 }
788
789 private class FindInfoCallback implements OnQueryCompleteListener {
790
linyuh183cb712017-12-27 17:02:37 -0800791 private final boolean isIncoming;
792 private final CallerInfoQueryToken queryToken;
Eric Erfanianccca3152017-02-22 16:32:36 -0800793
Eric Erfaniand8046e52017-04-06 09:41:50 -0700794 FindInfoCallback(boolean isIncoming, CallerInfoQueryToken queryToken) {
linyuh183cb712017-12-27 17:02:37 -0800795 this.isIncoming = isIncoming;
796 this.queryToken = queryToken;
Eric Erfanianccca3152017-02-22 16:32:36 -0800797 }
798
799 @Override
800 public void onDataLoaded(int token, Object cookie, CallerInfo ci) {
801 Assert.isWorkerThread();
802 DialerCallCookieWrapper cw = (DialerCallCookieWrapper) cookie;
linyuh183cb712017-12-27 17:02:37 -0800803 if (!isWaitingForThisQuery(cw.callId, queryToken.queryId)) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700804 return;
805 }
Eric Erfanian9779f962017-03-27 12:31:48 -0700806 long start = SystemClock.uptimeMillis();
linyuh183cb712017-12-27 17:02:37 -0800807 maybeUpdateFromCequintCallerId(ci, cw.cnapName, isIncoming);
Eric Erfanian9779f962017-03-27 12:31:48 -0700808 long time = SystemClock.uptimeMillis() - start;
809 Log.d(TAG, "Cequint Caller Id look up takes " + time + " ms.");
linyuh183cb712017-12-27 17:02:37 -0800810 updateCallerInfoInCacheOnAnyThread(cw.callId, cw.numberPresentation, ci, true, queryToken);
Eric Erfanianccca3152017-02-22 16:32:36 -0800811 }
812
813 @Override
814 public void onQueryComplete(int token, Object cookie, CallerInfo callerInfo) {
wangqi9982f0d2017-10-11 17:46:07 -0700815 Trace.beginSection("ContactInfoCache.FindInfoCallback.onQueryComplete");
Eric Erfanianccca3152017-02-22 16:32:36 -0800816 Assert.isMainThread();
817 DialerCallCookieWrapper cw = (DialerCallCookieWrapper) cookie;
818 String callId = cw.callId;
linyuh183cb712017-12-27 17:02:37 -0800819 if (!isWaitingForThisQuery(cw.callId, queryToken.queryId)) {
wangqi9982f0d2017-10-11 17:46:07 -0700820 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700821 return;
822 }
linyuh183cb712017-12-27 17:02:37 -0800823 ContactCacheEntry cacheEntry = infoMap.get(callId);
Eric Erfanianccca3152017-02-22 16:32:36 -0800824 // This may happen only when InCallPresenter attempt to cleanup.
825 if (cacheEntry == null) {
826 Log.w(TAG, "Contact lookup done, but cache entry is not found.");
827 clearCallbacks(callId);
wangqi9982f0d2017-10-11 17:46:07 -0700828 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800829 return;
830 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700831 // Before issuing a request for more data from other services, we only check that the
832 // contact wasn't found in the local DB. We don't check the if the cache entry already
833 // has a name because we allow overriding cnap data with data from other services.
linyuh183cb712017-12-27 17:02:37 -0800834 if (!callerInfo.contactExists && phoneNumberService != null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700835 Log.d(TAG, "Contact lookup. Local contacts miss, checking remote");
836 final PhoneNumberServiceListener listener =
linyuh183cb712017-12-27 17:02:37 -0800837 new PhoneNumberServiceListener(callId, queryToken.queryId);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700838 cacheEntry.hasPendingQuery = true;
twyena40a9ef2018-05-22 17:35:59 -0700839 phoneNumberService.getPhoneNumberInfo(cacheEntry.number, listener);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700840 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800841 sendInfoNotifications(callId, cacheEntry);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700842 if (!cacheEntry.hasPendingQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800843 if (callerInfo.contactExists) {
844 Log.d(TAG, "Contact lookup done. Local contact found, no image.");
845 } else {
846 Log.d(
847 TAG,
848 "Contact lookup done. Local contact not found and"
849 + " no remote lookup service available.");
850 }
851 clearCallbacks(callId);
852 }
wangqi9982f0d2017-10-11 17:46:07 -0700853 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800854 }
855 }
856
twyena40a9ef2018-05-22 17:35:59 -0700857 class PhoneNumberServiceListener implements PhoneNumberService.NumberLookupListener {
Eric Erfanianccca3152017-02-22 16:32:36 -0800858
linyuh183cb712017-12-27 17:02:37 -0800859 private final String callId;
860 private final int queryIdOfRemoteLookup;
Eric Erfanianccca3152017-02-22 16:32:36 -0800861
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700862 PhoneNumberServiceListener(String callId, int queryId) {
linyuh183cb712017-12-27 17:02:37 -0800863 this.callId = callId;
864 queryIdOfRemoteLookup = queryId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800865 }
866
867 @Override
868 public void onPhoneNumberInfoComplete(final PhoneNumberService.PhoneNumberInfo info) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700869 Log.d(TAG, "PhoneNumberServiceListener.onPhoneNumberInfoComplete");
linyuh183cb712017-12-27 17:02:37 -0800870 if (!isWaitingForThisQuery(callId, queryIdOfRemoteLookup)) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700871 return;
872 }
873
Eric Erfanianccca3152017-02-22 16:32:36 -0800874 // If we got a miss, this is the end of the lookup pipeline,
875 // so clear the callbacks and return.
876 if (info == null) {
877 Log.d(TAG, "Contact lookup done. Remote contact not found.");
linyuh183cb712017-12-27 17:02:37 -0800878 clearCallbacks(callId);
Eric Erfanianccca3152017-02-22 16:32:36 -0800879 return;
880 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800881 ContactCacheEntry entry = new ContactCacheEntry();
882 entry.namePrimary = info.getDisplayName();
883 entry.number = info.getNumber();
884 entry.contactLookupResult = info.getLookupSource();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700885 entry.isBusiness = info.isBusiness();
Eric Erfanianccca3152017-02-22 16:32:36 -0800886 final int type = info.getPhoneType();
887 final String label = info.getPhoneLabel();
888 if (type == Phone.TYPE_CUSTOM) {
889 entry.label = label;
890 } else {
linyuh183cb712017-12-27 17:02:37 -0800891 final CharSequence typeStr = Phone.getTypeLabel(context.getResources(), type, label);
Eric Erfanianccca3152017-02-22 16:32:36 -0800892 entry.label = typeStr == null ? null : typeStr.toString();
893 }
linyuh183cb712017-12-27 17:02:37 -0800894 final ContactCacheEntry oldEntry = infoMap.get(callId);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700895 if (oldEntry != null) {
896 // Location is only obtained from local lookup so persist
897 // the value for remote lookups. Once we have a name this
898 // field is no longer used; it is persisted here in case
899 // the UI is ever changed to use it.
900 entry.location = oldEntry.location;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700901 entry.shouldShowLocation = oldEntry.shouldShowLocation;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700902 // Contact specific ringtone is obtained from local lookup.
903 entry.contactRingtoneUri = oldEntry.contactRingtoneUri;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700904 entry.originalPhoneNumber = oldEntry.originalPhoneNumber;
Eric Erfanianccca3152017-02-22 16:32:36 -0800905 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700906
907 // If no image and it's a business, switch to using the default business avatar.
908 if (info.getImageUrl() == null && info.isBusiness()) {
909 Log.d(TAG, "Business has no image. Using default.");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700910 entry.photoType = ContactPhotoType.BUSINESS;
911 }
912
913 Log.d(TAG, "put entry into map: " + entry);
linyuh183cb712017-12-27 17:02:37 -0800914 infoMap.put(callId, entry);
915 sendInfoNotifications(callId, entry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800916
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700917 entry.hasPendingQuery = info.getImageUrl() != null;
Eric Erfanianccca3152017-02-22 16:32:36 -0800918
919 // If there is no image then we should not expect another callback.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700920 if (!entry.hasPendingQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800921 // We're done, so clear callbacks
linyuh183cb712017-12-27 17:02:37 -0800922 clearCallbacks(callId);
Eric Erfanianccca3152017-02-22 16:32:36 -0800923 }
924 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700925 }
926
927 private boolean needForceQuery(DialerCall call, ContactCacheEntry cacheEntry) {
928 if (call == null || call.isConferenceCall()) {
929 return false;
930 }
931
932 String newPhoneNumber = PhoneNumberUtils.stripSeparators(call.getNumber());
933 if (cacheEntry == null) {
934 // No info in the map yet so it is the 1st query
935 Log.d(TAG, "needForceQuery: first query");
936 return true;
937 }
938 String oldPhoneNumber = PhoneNumberUtils.stripSeparators(cacheEntry.originalPhoneNumber);
939
940 if (!TextUtils.equals(oldPhoneNumber, newPhoneNumber)) {
941 Log.d(TAG, "phone number has changed: " + oldPhoneNumber + " -> " + newPhoneNumber);
942 return true;
943 }
944
945 return false;
946 }
947
948 private static final class CallerInfoQueryToken {
linyuh183cb712017-12-27 17:02:37 -0800949 final int queryId;
950 final String callId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700951
952 CallerInfoQueryToken(int queryId, String callId) {
linyuh183cb712017-12-27 17:02:37 -0800953 this.queryId = queryId;
954 this.callId = callId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700955 }
956 }
957
958 /** Check if the queryId in the cached map is the same as the one from query result. */
959 private boolean isWaitingForThisQuery(String callId, int queryId) {
linyuh183cb712017-12-27 17:02:37 -0800960 final ContactCacheEntry existingCacheEntry = infoMap.get(callId);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700961 if (existingCacheEntry == null) {
962 // This might happen if lookup on background thread comes back before the initial entry is
963 // created.
964 Log.d(TAG, "Cached entry is null.");
965 return true;
966 } else {
967 int waitingQueryId = existingCacheEntry.queryId;
968 Log.d(TAG, "waitingQueryId = " + waitingQueryId + "; queryId = " + queryId);
969 return waitingQueryId == queryId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800970 }
971 }
972}