blob: fdfba3b9fdb6af1d749e77f7e9143f9f5c6832c6 [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 Erfanianccca3152017-02-22 16:32:36 -080025import android.os.Build.VERSION;
26import android.os.Build.VERSION_CODES;
Eric Erfanian9779f962017-03-27 12:31:48 -070027import android.os.SystemClock;
Eric Erfanianccca3152017-02-22 16:32:36 -080028import android.provider.ContactsContract.CommonDataKinds.Phone;
29import android.provider.ContactsContract.Contacts;
30import android.provider.ContactsContract.DisplayNameSources;
31import android.support.annotation.AnyThread;
32import android.support.annotation.MainThread;
33import android.support.annotation.NonNull;
Eric Erfaniand8046e52017-04-06 09:41:50 -070034import android.support.annotation.Nullable;
Eric Erfanianccca3152017-02-22 16:32:36 -080035import android.support.annotation.WorkerThread;
Eric Erfanianea7890c2017-06-19 12:40:59 -070036import android.support.v4.content.ContextCompat;
Eric Erfanianccca3152017-02-22 16:32:36 -080037import android.support.v4.os.UserManagerCompat;
38import android.telecom.TelecomManager;
Eric Erfaniand5e47f62017-03-15 14:41:07 -070039import android.telephony.PhoneNumberUtils;
Eric Erfanianccca3152017-02-22 16:32:36 -080040import android.text.TextUtils;
41import android.util.ArrayMap;
42import android.util.ArraySet;
43import com.android.contacts.common.ContactsUtils;
44import com.android.dialer.common.Assert;
Eric Erfaniand8046e52017-04-06 09:41:50 -070045import com.android.dialer.common.concurrent.DialerExecutor;
46import com.android.dialer.common.concurrent.DialerExecutor.Worker;
47import com.android.dialer.common.concurrent.DialerExecutors;
Eric Erfanian8369df02017-05-03 10:27:13 -070048import com.android.dialer.logging.ContactLookupResult;
49import com.android.dialer.logging.ContactSource;
Eric Erfanian9779f962017-03-27 12:31:48 -070050import com.android.dialer.oem.CequintCallerIdManager;
51import com.android.dialer.oem.CequintCallerIdManager.CequintCallerIdContact;
Eric Erfanianccca3152017-02-22 16:32:36 -080052import com.android.dialer.phonenumbercache.CachedNumberLookupService;
53import com.android.dialer.phonenumbercache.CachedNumberLookupService.CachedContactInfo;
54import com.android.dialer.phonenumbercache.ContactInfo;
55import com.android.dialer.phonenumbercache.PhoneNumberCache;
56import com.android.dialer.phonenumberutil.PhoneNumberHelper;
57import com.android.dialer.util.MoreStrings;
58import com.android.incallui.CallerInfoAsyncQuery.OnQueryCompleteListener;
59import com.android.incallui.ContactsAsyncHelper.OnImageLoadCompleteListener;
60import com.android.incallui.bindings.PhoneNumberService;
61import com.android.incallui.call.DialerCall;
62import com.android.incallui.incall.protocol.ContactPhotoType;
63import java.util.Map;
64import java.util.Objects;
65import java.util.Set;
66import java.util.concurrent.ConcurrentHashMap;
67import org.json.JSONException;
68import org.json.JSONObject;
69
70/**
71 * Class responsible for querying Contact Information for DialerCall objects. Can perform
72 * asynchronous requests to the Contact Provider for information as well as respond synchronously
73 * for any data that it currently has cached from previous queries. This class always gets called
74 * from the UI thread so it does not need thread protection.
75 */
76public class ContactInfoCache implements OnImageLoadCompleteListener {
77
78 private static final String TAG = ContactInfoCache.class.getSimpleName();
79 private static final int TOKEN_UPDATE_PHOTO_FOR_CALL_STATE = 0;
80 private static ContactInfoCache sCache = null;
81 private final Context mContext;
82 private final PhoneNumberService mPhoneNumberService;
83 // Cache info map needs to be thread-safe since it could be modified by both main thread and
84 // worker thread.
Eric Erfaniand5e47f62017-03-15 14:41:07 -070085 private final ConcurrentHashMap<String, ContactCacheEntry> mInfoMap = new ConcurrentHashMap<>();
Eric Erfanianccca3152017-02-22 16:32:36 -080086 private final Map<String, Set<ContactInfoCacheCallback>> mCallBacks = new ArrayMap<>();
87 private Drawable mDefaultContactPhotoDrawable;
Eric Erfaniand5e47f62017-03-15 14:41:07 -070088 private int mQueryId;
Eric Erfaniand8046e52017-04-06 09:41:50 -070089 private final DialerExecutor<CnapInformationWrapper> cachedNumberLookupExecutor =
90 DialerExecutors.createNonUiTaskBuilder(new CachedNumberLookupWorker()).build();
91
92 private static class CachedNumberLookupWorker implements Worker<CnapInformationWrapper, Void> {
93 @Nullable
94 @Override
95 public Void doInBackground(@Nullable CnapInformationWrapper input) {
96 if (input == null) {
97 return null;
98 }
99 ContactInfo contactInfo = new ContactInfo();
100 CachedContactInfo cacheInfo = input.service.buildCachedContactInfo(contactInfo);
Eric Erfanian8369df02017-05-03 10:27:13 -0700101 cacheInfo.setSource(ContactSource.Type.SOURCE_TYPE_CNAP, "CNAP", 0);
Eric Erfaniand8046e52017-04-06 09:41:50 -0700102 contactInfo.name = input.cnapName;
103 contactInfo.number = input.number;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700104 try {
105 final JSONObject contactRows =
106 new JSONObject()
107 .put(
108 Phone.CONTENT_ITEM_TYPE,
Eric Erfanian10b34a52017-05-04 08:23:17 -0700109 new JSONObject().put(Phone.NUMBER, contactInfo.number));
Eric Erfaniand8046e52017-04-06 09:41:50 -0700110 final String jsonString =
111 new JSONObject()
112 .put(Contacts.DISPLAY_NAME, contactInfo.name)
113 .put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME)
114 .put(Contacts.CONTENT_ITEM_TYPE, contactRows)
115 .toString();
116 cacheInfo.setLookupKey(jsonString);
117 } catch (JSONException e) {
118 Log.w(TAG, "Creation of lookup key failed when caching CNAP information");
119 }
120 input.service.addContact(input.context.getApplicationContext(), cacheInfo);
121 return null;
122 }
123 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800124
125 private ContactInfoCache(Context context) {
126 mContext = context;
127 mPhoneNumberService = Bindings.get(context).newPhoneNumberService(context);
128 }
129
130 public static synchronized ContactInfoCache getInstance(Context mContext) {
131 if (sCache == null) {
132 sCache = new ContactInfoCache(mContext.getApplicationContext());
133 }
134 return sCache;
135 }
136
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700137 static ContactCacheEntry buildCacheEntryFromCall(
Eric Erfanianccca3152017-02-22 16:32:36 -0800138 Context context, DialerCall call, boolean isIncoming) {
139 final ContactCacheEntry entry = new ContactCacheEntry();
140
141 // TODO: get rid of caller info.
142 final CallerInfo info = CallerInfoUtils.buildCallerInfo(context, call);
Eric Erfanian8369df02017-05-03 10:27:13 -0700143 ContactInfoCache.populateCacheEntry(context, info, entry, call.getNumberPresentation());
Eric Erfanianccca3152017-02-22 16:32:36 -0800144 return entry;
145 }
146
147 /** Populate a cache entry from a call (which got converted into a caller info). */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700148 private static void populateCacheEntry(
Eric Erfanianccca3152017-02-22 16:32:36 -0800149 @NonNull Context context,
150 @NonNull CallerInfo info,
151 @NonNull ContactCacheEntry cce,
Eric Erfanian8369df02017-05-03 10:27:13 -0700152 int presentation) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800153 Objects.requireNonNull(info);
154 String displayName = null;
155 String displayNumber = null;
Eric Erfanianccca3152017-02-22 16:32:36 -0800156 String label = null;
157 boolean isSipCall = false;
158
159 // It appears that there is a small change in behaviour with the
160 // PhoneUtils' startGetCallerInfo whereby if we query with an
161 // empty number, we will get a valid CallerInfo object, but with
162 // fields that are all null, and the isTemporary boolean input
163 // parameter as true.
164
165 // In the past, we would see a NULL callerinfo object, but this
166 // ends up causing null pointer exceptions elsewhere down the
167 // line in other cases, so we need to make this fix instead. It
168 // appears that this was the ONLY call to PhoneUtils
169 // .getCallerInfo() that relied on a NULL CallerInfo to indicate
170 // an unknown contact.
171
172 // Currently, info.phoneNumber may actually be a SIP address, and
173 // if so, it might sometimes include the "sip:" prefix. That
174 // prefix isn't really useful to the user, though, so strip it off
175 // if present. (For any other URI scheme, though, leave the
176 // prefix alone.)
177 // TODO: It would be cleaner for CallerInfo to explicitly support
178 // SIP addresses instead of overloading the "phoneNumber" field.
179 // Then we could remove this hack, and instead ask the CallerInfo
180 // for a "user visible" form of the SIP address.
181 String number = info.phoneNumber;
182
183 if (!TextUtils.isEmpty(number)) {
184 isSipCall = PhoneNumberHelper.isUriNumber(number);
185 if (number.startsWith("sip:")) {
186 number = number.substring(4);
187 }
188 }
189
190 if (TextUtils.isEmpty(info.name)) {
191 // No valid "name" in the CallerInfo, so fall back to
192 // something else.
193 // (Typically, we promote the phone number up to the "name" slot
194 // onscreen, and possibly display a descriptive string in the
195 // "number" slot.)
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700196 if (TextUtils.isEmpty(number) && TextUtils.isEmpty(info.cnapName)) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800197 // No name *or* number! Display a generic "unknown" string
198 // (or potentially some other default based on the presentation.)
199 displayName = getPresentationString(context, presentation, info.callSubject);
200 Log.d(TAG, " ==> no name *or* number! displayName = " + displayName);
201 } else if (presentation != TelecomManager.PRESENTATION_ALLOWED) {
202 // This case should never happen since the network should never send a phone #
203 // AND a restricted presentation. However we leave it here in case of weird
204 // network behavior
205 displayName = getPresentationString(context, presentation, info.callSubject);
206 Log.d(TAG, " ==> presentation not allowed! displayName = " + displayName);
207 } else if (!TextUtils.isEmpty(info.cnapName)) {
208 // No name, but we do have a valid CNAP name, so use that.
209 displayName = info.cnapName;
210 info.name = info.cnapName;
211 displayNumber = PhoneNumberHelper.formatNumber(number, context);
212 Log.d(
213 TAG,
214 " ==> cnapName available: displayName '"
215 + displayName
216 + "', displayNumber '"
217 + displayNumber
218 + "'");
219 } else {
220 // No name; all we have is a number. This is the typical
221 // case when an incoming call doesn't match any contact,
222 // or if you manually dial an outgoing number using the
223 // dialpad.
224 displayNumber = PhoneNumberHelper.formatNumber(number, context);
225
Eric Erfanianccca3152017-02-22 16:32:36 -0800226 Log.d(
227 TAG,
228 " ==> no name; falling back to number:"
229 + " displayNumber '"
230 + Log.pii(displayNumber)
Eric Erfanianccca3152017-02-22 16:32:36 -0800231 + "'");
232 }
233 } else {
234 // We do have a valid "name" in the CallerInfo. Display that
235 // in the "name" slot, and the phone number in the "number" slot.
236 if (presentation != TelecomManager.PRESENTATION_ALLOWED) {
237 // This case should never happen since the network should never send a name
238 // AND a restricted presentation. However we leave it here in case of weird
239 // network behavior
240 displayName = getPresentationString(context, presentation, info.callSubject);
241 Log.d(
242 TAG,
243 " ==> valid name, but presentation not allowed!" + " displayName = " + displayName);
244 } else {
245 // Causes cce.namePrimary to be set as info.name below. CallCardPresenter will
246 // later determine whether to use the name or nameAlternative when presenting
247 displayName = info.name;
248 cce.nameAlternative = info.nameAlternative;
249 displayNumber = PhoneNumberHelper.formatNumber(number, context);
250 label = info.phoneLabel;
251 Log.d(
252 TAG,
253 " ==> name is present in CallerInfo: displayName '"
254 + displayName
255 + "', displayNumber '"
256 + displayNumber
257 + "'");
258 }
259 }
260
261 cce.namePrimary = displayName;
262 cce.number = displayNumber;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700263 cce.location = info.geoDescription;
Eric Erfanianccca3152017-02-22 16:32:36 -0800264 cce.label = label;
265 cce.isSipCall = isSipCall;
266 cce.userType = info.userType;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700267 cce.originalPhoneNumber = info.phoneNumber;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700268 cce.shouldShowLocation = info.shouldShowGeoDescription;
Eric Erfanianccca3152017-02-22 16:32:36 -0800269
270 if (info.contactExists) {
271 cce.contactLookupResult = ContactLookupResult.Type.LOCAL_CONTACT;
272 }
273 }
274
275 /** Gets name strings based on some special presentation modes and the associated custom label. */
276 private static String getPresentationString(
277 Context context, int presentation, String customLabel) {
278 String name = context.getString(R.string.unknown);
279 if (!TextUtils.isEmpty(customLabel)
280 && ((presentation == TelecomManager.PRESENTATION_UNKNOWN)
281 || (presentation == TelecomManager.PRESENTATION_RESTRICTED))) {
282 name = customLabel;
283 return name;
284 } else {
285 if (presentation == TelecomManager.PRESENTATION_RESTRICTED) {
286 name = PhoneNumberHelper.getDisplayNameForRestrictedNumber(context).toString();
287 } else if (presentation == TelecomManager.PRESENTATION_PAYPHONE) {
288 name = context.getString(R.string.payphone);
289 }
290 }
291 return name;
292 }
293
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700294 ContactCacheEntry getInfo(String callId) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800295 return mInfoMap.get(callId);
296 }
297
Eric Erfaniand8046e52017-04-06 09:41:50 -0700298 private static final class CnapInformationWrapper {
299 final String number;
300 final String cnapName;
301 final Context context;
302 final CachedNumberLookupService service;
303
304 CnapInformationWrapper(
305 String number, String cnapName, Context context, CachedNumberLookupService service) {
306 this.number = number;
307 this.cnapName = cnapName;
308 this.context = context;
309 this.service = service;
310 }
311 }
312
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700313 void maybeInsertCnapInformationIntoCache(
Eric Erfanianccca3152017-02-22 16:32:36 -0800314 Context context, final DialerCall call, final CallerInfo info) {
315 final CachedNumberLookupService cachedNumberLookupService =
316 PhoneNumberCache.get(context).getCachedNumberLookupService();
317 if (!UserManagerCompat.isUserUnlocked(context)) {
318 Log.i(TAG, "User locked, not inserting cnap info into cache");
319 return;
320 }
321 if (cachedNumberLookupService == null
322 || TextUtils.isEmpty(info.cnapName)
323 || mInfoMap.get(call.getId()) != null) {
324 return;
325 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800326 Log.i(TAG, "Found contact with CNAP name - inserting into cache");
Eric Erfaniand8046e52017-04-06 09:41:50 -0700327
328 cachedNumberLookupExecutor.executeParallel(
329 new CnapInformationWrapper(
330 call.getNumber(), info.cnapName, context, cachedNumberLookupService));
Eric Erfanianccca3152017-02-22 16:32:36 -0800331 }
332
333 /**
334 * Requests contact data for the DialerCall object passed in. Returns the data through callback.
335 * If callback is null, no response is made, however the query is still performed and cached.
336 *
337 * @param callback The function to call back when the call is found. Can be null.
338 */
339 @MainThread
340 public void findInfo(
341 @NonNull final DialerCall call,
342 final boolean isIncoming,
343 @NonNull ContactInfoCacheCallback callback) {
344 Assert.isMainThread();
345 Objects.requireNonNull(callback);
346
347 final String callId = call.getId();
348 final ContactCacheEntry cacheEntry = mInfoMap.get(callId);
349 Set<ContactInfoCacheCallback> callBacks = mCallBacks.get(callId);
350
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700351 // We need to force a new query if phone number has changed.
352 boolean forceQuery = needForceQuery(call, cacheEntry);
353 Log.d(TAG, "findInfo: callId = " + callId + "; forceQuery = " + forceQuery);
354
355 // If we have a previously obtained intermediate result return that now except needs
356 // force query.
357 if (cacheEntry != null && !forceQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800358 Log.d(
359 TAG,
360 "Contact lookup. In memory cache hit; lookup "
361 + (callBacks == null ? "complete" : "still running"));
362 callback.onContactInfoComplete(callId, cacheEntry);
363 // If no other callbacks are in flight, we're done.
364 if (callBacks == null) {
365 return;
366 }
367 }
368
369 // If the entry already exists, add callback
370 if (callBacks != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700371 Log.d(TAG, "Another query is in progress, add callback only.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800372 callBacks.add(callback);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700373 if (!forceQuery) {
374 Log.d(TAG, "No need to query again, just return and wait for existing query to finish");
375 return;
376 }
377 } else {
378 Log.d(TAG, "Contact lookup. In memory cache miss; searching provider.");
379 // New lookup
380 callBacks = new ArraySet<>();
381 callBacks.add(callback);
382 mCallBacks.put(callId, callBacks);
Eric Erfanianccca3152017-02-22 16:32:36 -0800383 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800384
385 /**
386 * Performs a query for caller information. Save any immediate data we get from the query. An
387 * asynchronous query may also be made for any data that we do not already have. Some queries,
388 * such as those for voicemail and emergency call information, will not perform an additional
389 * asynchronous query.
390 */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700391 final CallerInfoQueryToken queryToken = new CallerInfoQueryToken(mQueryId, callId);
392 mQueryId++;
Eric Erfanianccca3152017-02-22 16:32:36 -0800393 final CallerInfo callerInfo =
394 CallerInfoUtils.getCallerInfoForCall(
395 mContext,
396 call,
Eric Erfaniand8046e52017-04-06 09:41:50 -0700397 new DialerCallCookieWrapper(callId, call.getNumberPresentation(), call.getCnapName()),
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700398 new FindInfoCallback(isIncoming, queryToken));
Eric Erfanianccca3152017-02-22 16:32:36 -0800399
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700400 if (cacheEntry != null) {
401 // We should not override the old cache item until the new query is
402 // back. We should only update the queryId. Otherwise, we may see
403 // flicker of the name and image (old cache -> new cache before query
404 // -> new cache after query)
405 cacheEntry.queryId = queryToken.mQueryId;
406 Log.d(TAG, "There is an existing cache. Do not override until new query is back");
407 } else {
408 ContactCacheEntry initialCacheEntry =
409 updateCallerInfoInCacheOnAnyThread(
Eric Erfanian91ce7d22017-06-05 13:35:02 -0700410 callId, call.getNumberPresentation(), callerInfo, false, queryToken);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700411 sendInfoNotifications(callId, initialCacheEntry);
412 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800413 }
414
415 @AnyThread
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700416 private ContactCacheEntry updateCallerInfoInCacheOnAnyThread(
Eric Erfanianccca3152017-02-22 16:32:36 -0800417 String callId,
418 int numberPresentation,
419 CallerInfo callerInfo,
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700420 boolean didLocalLookup,
421 CallerInfoQueryToken queryToken) {
422 Log.d(
423 TAG,
424 "updateCallerInfoInCacheOnAnyThread: callId = "
425 + callId
426 + "; queryId = "
427 + queryToken.mQueryId
428 + "; didLocalLookup = "
429 + didLocalLookup);
430
Eric Erfanianccca3152017-02-22 16:32:36 -0800431 int presentationMode = numberPresentation;
432 if (callerInfo.contactExists
433 || callerInfo.isEmergencyNumber()
434 || callerInfo.isVoiceMailNumber()) {
435 presentationMode = TelecomManager.PRESENTATION_ALLOWED;
436 }
437
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700438 // We always replace the entry. The only exception is the same photo case.
Eric Erfanian8369df02017-05-03 10:27:13 -0700439 ContactCacheEntry cacheEntry = buildEntry(mContext, callerInfo, presentationMode);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700440 cacheEntry.queryId = queryToken.mQueryId;
441
442 ContactCacheEntry existingCacheEntry = mInfoMap.get(callId);
443 Log.d(TAG, "Existing cacheEntry in hashMap " + existingCacheEntry);
444
445 if (didLocalLookup) {
Eric Erfanian91ce7d22017-06-05 13:35:02 -0700446 if (cacheEntry.displayPhotoUri != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700447 // When the difference between 2 numbers is only the prefix (e.g. + or IDD),
448 // we will still trigger force query so that the number can be updated on
449 // the calling screen. We need not query the image again if the previous
450 // query already has the image to avoid flickering.
451 if (existingCacheEntry != null
452 && existingCacheEntry.displayPhotoUri != null
453 && existingCacheEntry.displayPhotoUri.equals(cacheEntry.displayPhotoUri)
454 && existingCacheEntry.photo != null) {
455 Log.d(TAG, "Same picture. Do not need start image load.");
456 cacheEntry.photo = existingCacheEntry.photo;
457 cacheEntry.photoType = existingCacheEntry.photoType;
458 return cacheEntry;
Eric Erfanianccca3152017-02-22 16:32:36 -0800459 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700460
461 Log.d(TAG, "Contact lookup. Local contact found, starting image load");
462 // Load the image with a callback to update the image state.
463 // When the load is finished, onImageLoadComplete() will be called.
464 cacheEntry.hasPendingQuery = true;
465 ContactsAsyncHelper.startObtainPhotoAsync(
466 TOKEN_UPDATE_PHOTO_FOR_CALL_STATE,
467 mContext,
468 cacheEntry.displayPhotoUri,
469 ContactInfoCache.this,
470 queryToken);
Eric Erfanianccca3152017-02-22 16:32:36 -0800471 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700472 Log.d(TAG, "put entry into map: " + cacheEntry);
473 mInfoMap.put(callId, cacheEntry);
474 } else {
475 // Don't overwrite if there is existing cache.
476 Log.d(TAG, "put entry into map if not exists: " + cacheEntry);
477 mInfoMap.putIfAbsent(callId, cacheEntry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800478 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700479 return cacheEntry;
Eric Erfanianccca3152017-02-22 16:32:36 -0800480 }
481
Eric Erfaniand8046e52017-04-06 09:41:50 -0700482 private void maybeUpdateFromCequintCallerId(
483 CallerInfo callerInfo, String cnapName, boolean isIncoming) {
Eric Erfanian9779f962017-03-27 12:31:48 -0700484 if (!CequintCallerIdManager.isCequintCallerIdEnabled(mContext)) {
485 return;
486 }
Eric Erfaniand8046e52017-04-06 09:41:50 -0700487 if (callerInfo.phoneNumber == null) {
488 return;
489 }
Eric Erfanian9779f962017-03-27 12:31:48 -0700490 CequintCallerIdContact cequintCallerIdContact =
491 CequintCallerIdManager.getCequintCallerIdContactForInCall(
Eric Erfaniand8046e52017-04-06 09:41:50 -0700492 mContext, callerInfo.phoneNumber, cnapName, isIncoming);
Eric Erfanian9779f962017-03-27 12:31:48 -0700493
Eric Erfaniand8046e52017-04-06 09:41:50 -0700494 if (cequintCallerIdContact == null) {
495 return;
496 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700497 boolean hasUpdate = false;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700498
499 if (TextUtils.isEmpty(callerInfo.name) && !TextUtils.isEmpty(cequintCallerIdContact.name)) {
Eric Erfanian9779f962017-03-27 12:31:48 -0700500 callerInfo.name = cequintCallerIdContact.name;
Eric Erfanian8369df02017-05-03 10:27:13 -0700501 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700502 }
503 if (!TextUtils.isEmpty(cequintCallerIdContact.geoDescription)) {
504 callerInfo.geoDescription = cequintCallerIdContact.geoDescription;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700505 callerInfo.shouldShowGeoDescription = true;
Eric Erfanian8369df02017-05-03 10:27:13 -0700506 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700507 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700508 // Don't overwrite photo in local contacts.
509 if (!callerInfo.contactExists
510 && callerInfo.contactDisplayPhotoUri == null
511 && cequintCallerIdContact.imageUrl != null) {
Eric Erfanian9779f962017-03-27 12:31:48 -0700512 callerInfo.contactDisplayPhotoUri = Uri.parse(cequintCallerIdContact.imageUrl);
Eric Erfanian8369df02017-05-03 10:27:13 -0700513 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700514 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700515 // Set contact to exist to avoid phone number service lookup.
516 callerInfo.contactExists = hasUpdate;
Eric Erfanian9779f962017-03-27 12:31:48 -0700517 }
518
Eric Erfanianccca3152017-02-22 16:32:36 -0800519 /**
520 * Implemented for ContactsAsyncHelper.OnImageLoadCompleteListener interface. Update contact photo
521 * when image is loaded in worker thread.
522 */
523 @WorkerThread
524 @Override
525 public void onImageLoaded(int token, Drawable photo, Bitmap photoIcon, Object cookie) {
526 Assert.isWorkerThread();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700527 CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie;
528 final String callId = myCookie.mCallId;
529 final int queryId = myCookie.mQueryId;
530 if (!isWaitingForThisQuery(callId, queryId)) {
531 return;
532 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800533 loadImage(photo, photoIcon, cookie);
534 }
535
536 private void loadImage(Drawable photo, Bitmap photoIcon, Object cookie) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700537 Log.d(TAG, "Image load complete with context: ", mContext);
Eric Erfanianccca3152017-02-22 16:32:36 -0800538 // TODO: may be nice to update the image view again once the newer one
539 // is available on contacts database.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700540 CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie;
541 final String callId = myCookie.mCallId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800542 ContactCacheEntry entry = mInfoMap.get(callId);
543
544 if (entry == null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700545 Log.e(TAG, "Image Load received for empty search entry.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800546 clearCallbacks(callId);
547 return;
548 }
549
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700550 Log.d(TAG, "setting photo for entry: ", entry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800551
552 // Conference call icons are being handled in CallCardPresenter.
553 if (photo != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700554 Log.v(TAG, "direct drawable: ", photo);
Eric Erfanianccca3152017-02-22 16:32:36 -0800555 entry.photo = photo;
556 entry.photoType = ContactPhotoType.CONTACT;
557 } else if (photoIcon != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700558 Log.v(TAG, "photo icon: ", photoIcon);
Eric Erfanianccca3152017-02-22 16:32:36 -0800559 entry.photo = new BitmapDrawable(mContext.getResources(), photoIcon);
560 entry.photoType = ContactPhotoType.CONTACT;
561 } else {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700562 Log.v(TAG, "unknown photo");
Eric Erfanianccca3152017-02-22 16:32:36 -0800563 entry.photo = null;
564 entry.photoType = ContactPhotoType.DEFAULT_PLACEHOLDER;
565 }
566 }
567
568 /**
569 * Implemented for ContactsAsyncHelper.OnImageLoadCompleteListener interface. make sure that the
570 * call state is reflected after the image is loaded.
571 */
572 @MainThread
573 @Override
574 public void onImageLoadComplete(int token, Drawable photo, Bitmap photoIcon, Object cookie) {
575 Assert.isMainThread();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700576 CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie;
577 final String callId = myCookie.mCallId;
578 final int queryId = myCookie.mQueryId;
579 if (!isWaitingForThisQuery(callId, queryId)) {
580 return;
581 }
582 sendImageNotifications(callId, mInfoMap.get(callId));
Eric Erfanianccca3152017-02-22 16:32:36 -0800583
584 clearCallbacks(callId);
585 }
586
587 /** Blows away the stored cache values. */
588 public void clearCache() {
589 mInfoMap.clear();
590 mCallBacks.clear();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700591 mQueryId = 0;
Eric Erfanianccca3152017-02-22 16:32:36 -0800592 }
593
Eric Erfanian8369df02017-05-03 10:27:13 -0700594 private ContactCacheEntry buildEntry(Context context, CallerInfo info, int presentation) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800595 final ContactCacheEntry cce = new ContactCacheEntry();
Eric Erfanian8369df02017-05-03 10:27:13 -0700596 populateCacheEntry(context, info, cce, presentation);
Eric Erfanianccca3152017-02-22 16:32:36 -0800597
598 // This will only be true for emergency numbers
599 if (info.photoResource != 0) {
Eric Erfanianea7890c2017-06-19 12:40:59 -0700600 cce.photo = ContextCompat.getDrawable(context, info.photoResource);
Eric Erfanianccca3152017-02-22 16:32:36 -0800601 } else if (info.isCachedPhotoCurrent) {
602 if (info.cachedPhoto != null) {
603 cce.photo = info.cachedPhoto;
604 cce.photoType = ContactPhotoType.CONTACT;
605 } else {
606 cce.photo = getDefaultContactPhotoDrawable();
607 cce.photoType = ContactPhotoType.DEFAULT_PLACEHOLDER;
608 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800609 } else {
610 cce.displayPhotoUri = info.contactDisplayPhotoUri;
611 cce.photo = null;
612 }
613
614 // Support any contact id in N because QuickContacts in N starts supporting enterprise
615 // contact id
616 if (info.lookupKeyOrNull != null
617 && (VERSION.SDK_INT >= VERSION_CODES.N || info.contactIdOrZero != 0)) {
618 cce.lookupUri = Contacts.getLookupUri(info.contactIdOrZero, info.lookupKeyOrNull);
619 } else {
620 Log.v(TAG, "lookup key is null or contact ID is 0 on M. Don't create a lookup uri.");
621 cce.lookupUri = null;
622 }
623
624 cce.lookupKey = info.lookupKeyOrNull;
625 cce.contactRingtoneUri = info.contactRingtoneUri;
626 if (cce.contactRingtoneUri == null || Uri.EMPTY.equals(cce.contactRingtoneUri)) {
627 cce.contactRingtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
628 }
629
630 return cce;
631 }
632
633 /** Sends the updated information to call the callbacks for the entry. */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700634 @MainThread
Eric Erfanianccca3152017-02-22 16:32:36 -0800635 private void sendInfoNotifications(String callId, ContactCacheEntry entry) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700636 Assert.isMainThread();
Eric Erfanianccca3152017-02-22 16:32:36 -0800637 final Set<ContactInfoCacheCallback> callBacks = mCallBacks.get(callId);
638 if (callBacks != null) {
639 for (ContactInfoCacheCallback callBack : callBacks) {
640 callBack.onContactInfoComplete(callId, entry);
641 }
642 }
643 }
644
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700645 @MainThread
Eric Erfanianccca3152017-02-22 16:32:36 -0800646 private void sendImageNotifications(String callId, ContactCacheEntry entry) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700647 Assert.isMainThread();
Eric Erfanianccca3152017-02-22 16:32:36 -0800648 final Set<ContactInfoCacheCallback> callBacks = mCallBacks.get(callId);
649 if (callBacks != null && entry.photo != null) {
650 for (ContactInfoCacheCallback callBack : callBacks) {
651 callBack.onImageLoadComplete(callId, entry);
652 }
653 }
654 }
655
656 private void clearCallbacks(String callId) {
657 mCallBacks.remove(callId);
658 }
659
660 public Drawable getDefaultContactPhotoDrawable() {
661 if (mDefaultContactPhotoDrawable == null) {
662 mDefaultContactPhotoDrawable =
663 mContext.getResources().getDrawable(R.drawable.img_no_image_automirrored);
664 }
665 return mDefaultContactPhotoDrawable;
666 }
667
Eric Erfanianccca3152017-02-22 16:32:36 -0800668 /** Callback interface for the contact query. */
669 public interface ContactInfoCacheCallback {
670
671 void onContactInfoComplete(String callId, ContactCacheEntry entry);
672
673 void onImageLoadComplete(String callId, ContactCacheEntry entry);
674 }
675
676 /** This is cached contact info, which should be the ONLY info used by UI. */
677 public static class ContactCacheEntry {
678
679 public String namePrimary;
680 public String nameAlternative;
681 public String number;
682 public String location;
683 public String label;
684 public Drawable photo;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700685 @ContactPhotoType int photoType;
686 boolean isSipCall;
Eric Erfanianccca3152017-02-22 16:32:36 -0800687 // Note in cache entry whether this is a pending async loading action to know whether to
688 // wait for its callback or not.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700689 boolean hasPendingQuery;
Eric Erfanianccca3152017-02-22 16:32:36 -0800690 /** This will be used for the "view" notification. */
691 public Uri contactUri;
692 /** Either a display photo or a thumbnail URI. */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700693 Uri displayPhotoUri;
Eric Erfanianccca3152017-02-22 16:32:36 -0800694
695 public Uri lookupUri; // Sent to NotificationMananger
696 public String lookupKey;
Eric Erfanian8369df02017-05-03 10:27:13 -0700697 public ContactLookupResult.Type contactLookupResult = ContactLookupResult.Type.NOT_FOUND;
Eric Erfanianccca3152017-02-22 16:32:36 -0800698 public long userType = ContactsUtils.USER_TYPE_CURRENT;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700699 Uri contactRingtoneUri;
700 /** Query id to identify the query session. */
701 int queryId;
702 /** The phone number without any changes to display to the user (ex: cnap...) */
703 String originalPhoneNumber;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700704 boolean shouldShowLocation;
Eric Erfanian9779f962017-03-27 12:31:48 -0700705
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700706 boolean isBusiness;
Eric Erfanianccca3152017-02-22 16:32:36 -0800707
708 @Override
709 public String toString() {
710 return "ContactCacheEntry{"
711 + "name='"
712 + MoreStrings.toSafeString(namePrimary)
713 + '\''
714 + ", nameAlternative='"
715 + MoreStrings.toSafeString(nameAlternative)
716 + '\''
717 + ", number='"
718 + MoreStrings.toSafeString(number)
719 + '\''
720 + ", location='"
721 + MoreStrings.toSafeString(location)
722 + '\''
723 + ", label='"
724 + label
725 + '\''
726 + ", photo="
727 + photo
728 + ", isSipCall="
729 + isSipCall
730 + ", contactUri="
731 + contactUri
732 + ", displayPhotoUri="
733 + displayPhotoUri
734 + ", contactLookupResult="
735 + contactLookupResult
736 + ", userType="
737 + userType
738 + ", contactRingtoneUri="
739 + contactRingtoneUri
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700740 + ", queryId="
741 + queryId
742 + ", originalPhoneNumber="
743 + originalPhoneNumber
Eric Erfaniand8046e52017-04-06 09:41:50 -0700744 + ", shouldShowLocation="
745 + shouldShowLocation
Eric Erfanianccca3152017-02-22 16:32:36 -0800746 + '}';
747 }
748 }
749
750 private static final class DialerCallCookieWrapper {
Eric Erfaniand8046e52017-04-06 09:41:50 -0700751 final String callId;
752 final int numberPresentation;
753 final String cnapName;
Eric Erfanianccca3152017-02-22 16:32:36 -0800754
Eric Erfaniand8046e52017-04-06 09:41:50 -0700755 DialerCallCookieWrapper(String callId, int numberPresentation, String cnapName) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800756 this.callId = callId;
757 this.numberPresentation = numberPresentation;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700758 this.cnapName = cnapName;
Eric Erfanianccca3152017-02-22 16:32:36 -0800759 }
760 }
761
762 private class FindInfoCallback implements OnQueryCompleteListener {
763
764 private final boolean mIsIncoming;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700765 private final CallerInfoQueryToken mQueryToken;
Eric Erfanianccca3152017-02-22 16:32:36 -0800766
Eric Erfaniand8046e52017-04-06 09:41:50 -0700767 FindInfoCallback(boolean isIncoming, CallerInfoQueryToken queryToken) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800768 mIsIncoming = isIncoming;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700769 mQueryToken = queryToken;
Eric Erfanianccca3152017-02-22 16:32:36 -0800770 }
771
772 @Override
773 public void onDataLoaded(int token, Object cookie, CallerInfo ci) {
774 Assert.isWorkerThread();
775 DialerCallCookieWrapper cw = (DialerCallCookieWrapper) cookie;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700776 if (!isWaitingForThisQuery(cw.callId, mQueryToken.mQueryId)) {
777 return;
778 }
Eric Erfanian9779f962017-03-27 12:31:48 -0700779 long start = SystemClock.uptimeMillis();
Eric Erfaniand8046e52017-04-06 09:41:50 -0700780 maybeUpdateFromCequintCallerId(ci, cw.cnapName, mIsIncoming);
Eric Erfanian9779f962017-03-27 12:31:48 -0700781 long time = SystemClock.uptimeMillis() - start;
782 Log.d(TAG, "Cequint Caller Id look up takes " + time + " ms.");
Eric Erfanian91ce7d22017-06-05 13:35:02 -0700783 updateCallerInfoInCacheOnAnyThread(cw.callId, cw.numberPresentation, ci, true, mQueryToken);
Eric Erfanianccca3152017-02-22 16:32:36 -0800784 }
785
786 @Override
787 public void onQueryComplete(int token, Object cookie, CallerInfo callerInfo) {
788 Assert.isMainThread();
789 DialerCallCookieWrapper cw = (DialerCallCookieWrapper) cookie;
790 String callId = cw.callId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700791 if (!isWaitingForThisQuery(cw.callId, mQueryToken.mQueryId)) {
792 return;
793 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800794 ContactCacheEntry cacheEntry = mInfoMap.get(callId);
795 // This may happen only when InCallPresenter attempt to cleanup.
796 if (cacheEntry == null) {
797 Log.w(TAG, "Contact lookup done, but cache entry is not found.");
798 clearCallbacks(callId);
799 return;
800 }
Eric Erfanian91ce7d22017-06-05 13:35:02 -0700801 // Before issuing a request for more data from other services, we only check that the
802 // contact wasn't found in the local DB. We don't check the if the cache entry already
803 // has a name because we allow overriding cnap data with data from other services.
804 if (!callerInfo.contactExists && mPhoneNumberService != null) {
805 Log.d(TAG, "Contact lookup. Local contacts miss, checking remote");
806 final PhoneNumberServiceListener listener =
807 new PhoneNumberServiceListener(callId, mQueryToken.mQueryId);
808 cacheEntry.hasPendingQuery = true;
809 mPhoneNumberService.getPhoneNumberInfo(cacheEntry.number, listener, listener, mIsIncoming);
810 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800811 sendInfoNotifications(callId, cacheEntry);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700812 if (!cacheEntry.hasPendingQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800813 if (callerInfo.contactExists) {
814 Log.d(TAG, "Contact lookup done. Local contact found, no image.");
815 } else {
816 Log.d(
817 TAG,
818 "Contact lookup done. Local contact not found and"
819 + " no remote lookup service available.");
820 }
821 clearCallbacks(callId);
822 }
823 }
824 }
825
826 class PhoneNumberServiceListener
827 implements PhoneNumberService.NumberLookupListener, PhoneNumberService.ImageLookupListener {
828
829 private final String mCallId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700830 private final int mQueryIdOfRemoteLookup;
Eric Erfanianccca3152017-02-22 16:32:36 -0800831
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700832 PhoneNumberServiceListener(String callId, int queryId) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800833 mCallId = callId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700834 mQueryIdOfRemoteLookup = queryId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800835 }
836
837 @Override
838 public void onPhoneNumberInfoComplete(final PhoneNumberService.PhoneNumberInfo info) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700839 Log.d(TAG, "PhoneNumberServiceListener.onPhoneNumberInfoComplete");
840 if (!isWaitingForThisQuery(mCallId, mQueryIdOfRemoteLookup)) {
841 return;
842 }
843
Eric Erfanianccca3152017-02-22 16:32:36 -0800844 // If we got a miss, this is the end of the lookup pipeline,
845 // so clear the callbacks and return.
846 if (info == null) {
847 Log.d(TAG, "Contact lookup done. Remote contact not found.");
848 clearCallbacks(mCallId);
849 return;
850 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800851 ContactCacheEntry entry = new ContactCacheEntry();
852 entry.namePrimary = info.getDisplayName();
853 entry.number = info.getNumber();
854 entry.contactLookupResult = info.getLookupSource();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700855 entry.isBusiness = info.isBusiness();
Eric Erfanianccca3152017-02-22 16:32:36 -0800856 final int type = info.getPhoneType();
857 final String label = info.getPhoneLabel();
858 if (type == Phone.TYPE_CUSTOM) {
859 entry.label = label;
860 } else {
861 final CharSequence typeStr = Phone.getTypeLabel(mContext.getResources(), type, label);
862 entry.label = typeStr == null ? null : typeStr.toString();
863 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700864 final ContactCacheEntry oldEntry = mInfoMap.get(mCallId);
865 if (oldEntry != null) {
866 // Location is only obtained from local lookup so persist
867 // the value for remote lookups. Once we have a name this
868 // field is no longer used; it is persisted here in case
869 // the UI is ever changed to use it.
870 entry.location = oldEntry.location;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700871 entry.shouldShowLocation = oldEntry.shouldShowLocation;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700872 // Contact specific ringtone is obtained from local lookup.
873 entry.contactRingtoneUri = oldEntry.contactRingtoneUri;
Eric Erfanian91ce7d22017-06-05 13:35:02 -0700874 entry.originalPhoneNumber = oldEntry.originalPhoneNumber;
Eric Erfanianccca3152017-02-22 16:32:36 -0800875 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700876
877 // If no image and it's a business, switch to using the default business avatar.
878 if (info.getImageUrl() == null && info.isBusiness()) {
879 Log.d(TAG, "Business has no image. Using default.");
880 entry.photo = mContext.getResources().getDrawable(R.drawable.img_business);
881 entry.photoType = ContactPhotoType.BUSINESS;
882 }
883
884 Log.d(TAG, "put entry into map: " + entry);
885 mInfoMap.put(mCallId, entry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800886 sendInfoNotifications(mCallId, entry);
887
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700888 entry.hasPendingQuery = info.getImageUrl() != null;
Eric Erfanianccca3152017-02-22 16:32:36 -0800889
890 // If there is no image then we should not expect another callback.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700891 if (!entry.hasPendingQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800892 // We're done, so clear callbacks
893 clearCallbacks(mCallId);
894 }
895 }
896
897 @Override
898 public void onImageFetchComplete(Bitmap bitmap) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700899 Log.d(TAG, "PhoneNumberServiceListener.onImageFetchComplete");
900 if (!isWaitingForThisQuery(mCallId, mQueryIdOfRemoteLookup)) {
901 return;
902 }
903 CallerInfoQueryToken queryToken = new CallerInfoQueryToken(mQueryIdOfRemoteLookup, mCallId);
904 loadImage(null, bitmap, queryToken);
905 onImageLoadComplete(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE, null, bitmap, queryToken);
906 }
907 }
908
909 private boolean needForceQuery(DialerCall call, ContactCacheEntry cacheEntry) {
910 if (call == null || call.isConferenceCall()) {
911 return false;
912 }
913
914 String newPhoneNumber = PhoneNumberUtils.stripSeparators(call.getNumber());
915 if (cacheEntry == null) {
916 // No info in the map yet so it is the 1st query
917 Log.d(TAG, "needForceQuery: first query");
918 return true;
919 }
920 String oldPhoneNumber = PhoneNumberUtils.stripSeparators(cacheEntry.originalPhoneNumber);
921
922 if (!TextUtils.equals(oldPhoneNumber, newPhoneNumber)) {
923 Log.d(TAG, "phone number has changed: " + oldPhoneNumber + " -> " + newPhoneNumber);
924 return true;
925 }
926
927 return false;
928 }
929
930 private static final class CallerInfoQueryToken {
931 final int mQueryId;
932 final String mCallId;
933
934 CallerInfoQueryToken(int queryId, String callId) {
935 mQueryId = queryId;
936 mCallId = callId;
937 }
938 }
939
940 /** Check if the queryId in the cached map is the same as the one from query result. */
941 private boolean isWaitingForThisQuery(String callId, int queryId) {
942 final ContactCacheEntry existingCacheEntry = mInfoMap.get(callId);
943 if (existingCacheEntry == null) {
944 // This might happen if lookup on background thread comes back before the initial entry is
945 // created.
946 Log.d(TAG, "Cached entry is null.");
947 return true;
948 } else {
949 int waitingQueryId = existingCacheEntry.queryId;
950 Log.d(TAG, "waitingQueryId = " + waitingQueryId + "; queryId = " + queryId);
951 return waitingQueryId == queryId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800952 }
953 }
954}