blob: 67a294f971dbbbbdaa9e900b3bcc5aa5d6148807 [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;
wangqicf61ca02017-08-31 15:32:55 -070028import android.os.Trace;
Eric Erfanianccca3152017-02-22 16:32:36 -080029import android.provider.ContactsContract.CommonDataKinds.Phone;
30import android.provider.ContactsContract.Contacts;
31import android.provider.ContactsContract.DisplayNameSources;
32import android.support.annotation.AnyThread;
33import android.support.annotation.MainThread;
34import android.support.annotation.NonNull;
Eric Erfaniand8046e52017-04-06 09:41:50 -070035import android.support.annotation.Nullable;
Eric Erfanianccca3152017-02-22 16:32:36 -080036import android.support.annotation.WorkerThread;
Eric Erfanian2ca43182017-08-31 06:57:16 -070037import android.support.v4.content.ContextCompat;
Eric Erfanianccca3152017-02-22 16:32:36 -080038import android.support.v4.os.UserManagerCompat;
39import android.telecom.TelecomManager;
Eric Erfaniand5e47f62017-03-15 14:41:07 -070040import android.telephony.PhoneNumberUtils;
Eric Erfanianccca3152017-02-22 16:32:36 -080041import android.text.TextUtils;
42import android.util.ArrayMap;
43import android.util.ArraySet;
44import com.android.contacts.common.ContactsUtils;
45import com.android.dialer.common.Assert;
Eric Erfaniand8046e52017-04-06 09:41:50 -070046import com.android.dialer.common.concurrent.DialerExecutor;
47import com.android.dialer.common.concurrent.DialerExecutor.Worker;
zachh0cd36a62017-10-31 12:04:05 -070048import com.android.dialer.common.concurrent.DialerExecutorComponent;
Eric Erfanian8369df02017-05-03 10:27:13 -070049import com.android.dialer.logging.ContactLookupResult;
50import com.android.dialer.logging.ContactSource;
Eric Erfanian9779f962017-03-27 12:31:48 -070051import com.android.dialer.oem.CequintCallerIdManager;
52import com.android.dialer.oem.CequintCallerIdManager.CequintCallerIdContact;
Eric Erfanianccca3152017-02-22 16:32:36 -080053import com.android.dialer.phonenumbercache.CachedNumberLookupService;
54import com.android.dialer.phonenumbercache.CachedNumberLookupService.CachedContactInfo;
55import com.android.dialer.phonenumbercache.ContactInfo;
56import com.android.dialer.phonenumbercache.PhoneNumberCache;
57import com.android.dialer.phonenumberutil.PhoneNumberHelper;
58import com.android.dialer.util.MoreStrings;
59import com.android.incallui.CallerInfoAsyncQuery.OnQueryCompleteListener;
60import com.android.incallui.ContactsAsyncHelper.OnImageLoadCompleteListener;
61import com.android.incallui.bindings.PhoneNumberService;
62import com.android.incallui.call.DialerCall;
63import com.android.incallui.incall.protocol.ContactPhotoType;
64import java.util.Map;
65import java.util.Objects;
66import java.util.Set;
67import java.util.concurrent.ConcurrentHashMap;
68import org.json.JSONException;
69import org.json.JSONObject;
70
71/**
72 * Class responsible for querying Contact Information for DialerCall objects. Can perform
73 * asynchronous requests to the Contact Provider for information as well as respond synchronously
74 * for any data that it currently has cached from previous queries. This class always gets called
75 * from the UI thread so it does not need thread protection.
76 */
77public class ContactInfoCache implements OnImageLoadCompleteListener {
78
79 private static final String TAG = ContactInfoCache.class.getSimpleName();
80 private static final int TOKEN_UPDATE_PHOTO_FOR_CALL_STATE = 0;
81 private static ContactInfoCache sCache = null;
82 private final Context mContext;
83 private final PhoneNumberService mPhoneNumberService;
84 // Cache info map needs to be thread-safe since it could be modified by both main thread and
85 // worker thread.
Eric Erfaniand5e47f62017-03-15 14:41:07 -070086 private final ConcurrentHashMap<String, ContactCacheEntry> mInfoMap = new ConcurrentHashMap<>();
Eric Erfanianccca3152017-02-22 16:32:36 -080087 private final Map<String, Set<ContactInfoCacheCallback>> mCallBacks = new ArrayMap<>();
Eric Erfaniand5e47f62017-03-15 14:41:07 -070088 private int mQueryId;
zachh6a4cebd2017-10-24 17:10:06 -070089 private final DialerExecutor<CnapInformationWrapper> cachedNumberLookupExecutor;
Eric Erfaniand8046e52017-04-06 09:41:50 -070090
91 private static class CachedNumberLookupWorker implements Worker<CnapInformationWrapper, Void> {
92 @Nullable
93 @Override
94 public Void doInBackground(@Nullable CnapInformationWrapper input) {
95 if (input == null) {
96 return null;
97 }
98 ContactInfo contactInfo = new ContactInfo();
99 CachedContactInfo cacheInfo = input.service.buildCachedContactInfo(contactInfo);
Eric Erfanian8369df02017-05-03 10:27:13 -0700100 cacheInfo.setSource(ContactSource.Type.SOURCE_TYPE_CNAP, "CNAP", 0);
Eric Erfaniand8046e52017-04-06 09:41:50 -0700101 contactInfo.name = input.cnapName;
102 contactInfo.number = input.number;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700103 try {
104 final JSONObject contactRows =
105 new JSONObject()
106 .put(
107 Phone.CONTENT_ITEM_TYPE,
Eric Erfanian10b34a52017-05-04 08:23:17 -0700108 new JSONObject().put(Phone.NUMBER, contactInfo.number));
Eric Erfaniand8046e52017-04-06 09:41:50 -0700109 final String jsonString =
110 new JSONObject()
111 .put(Contacts.DISPLAY_NAME, contactInfo.name)
112 .put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME)
113 .put(Contacts.CONTENT_ITEM_TYPE, contactRows)
114 .toString();
115 cacheInfo.setLookupKey(jsonString);
116 } catch (JSONException e) {
117 Log.w(TAG, "Creation of lookup key failed when caching CNAP information");
118 }
119 input.service.addContact(input.context.getApplicationContext(), cacheInfo);
120 return null;
121 }
122 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800123
124 private ContactInfoCache(Context context) {
wangqicf61ca02017-08-31 15:32:55 -0700125 Trace.beginSection("ContactInfoCache constructor");
Eric Erfanianccca3152017-02-22 16:32:36 -0800126 mContext = context;
127 mPhoneNumberService = Bindings.get(context).newPhoneNumberService(context);
zachh6a4cebd2017-10-24 17:10:06 -0700128 cachedNumberLookupExecutor =
zachh0cd36a62017-10-31 12:04:05 -0700129 DialerExecutorComponent.get(mContext)
130 .dialerExecutorFactory()
131 .createNonUiTaskBuilder(new CachedNumberLookupWorker())
132 .build();
wangqicf61ca02017-08-31 15:32:55 -0700133 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800134 }
135
136 public static synchronized ContactInfoCache getInstance(Context mContext) {
137 if (sCache == null) {
138 sCache = new ContactInfoCache(mContext.getApplicationContext());
139 }
140 return sCache;
141 }
142
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700143 static ContactCacheEntry buildCacheEntryFromCall(
Eric Erfanianccca3152017-02-22 16:32:36 -0800144 Context context, DialerCall call, boolean isIncoming) {
145 final ContactCacheEntry entry = new ContactCacheEntry();
146
147 // TODO: get rid of caller info.
148 final CallerInfo info = CallerInfoUtils.buildCallerInfo(context, call);
Eric Erfanian8369df02017-05-03 10:27:13 -0700149 ContactInfoCache.populateCacheEntry(context, info, entry, call.getNumberPresentation());
Eric Erfanianccca3152017-02-22 16:32:36 -0800150 return entry;
151 }
152
153 /** Populate a cache entry from a call (which got converted into a caller info). */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700154 private static void populateCacheEntry(
Eric Erfanianccca3152017-02-22 16:32:36 -0800155 @NonNull Context context,
156 @NonNull CallerInfo info,
157 @NonNull ContactCacheEntry cce,
Eric Erfanian8369df02017-05-03 10:27:13 -0700158 int presentation) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800159 Objects.requireNonNull(info);
160 String displayName = null;
161 String displayNumber = null;
Eric Erfanianccca3152017-02-22 16:32:36 -0800162 String label = null;
163 boolean isSipCall = false;
164
165 // It appears that there is a small change in behaviour with the
166 // PhoneUtils' startGetCallerInfo whereby if we query with an
167 // empty number, we will get a valid CallerInfo object, but with
168 // fields that are all null, and the isTemporary boolean input
169 // parameter as true.
170
171 // In the past, we would see a NULL callerinfo object, but this
172 // ends up causing null pointer exceptions elsewhere down the
173 // line in other cases, so we need to make this fix instead. It
174 // appears that this was the ONLY call to PhoneUtils
175 // .getCallerInfo() that relied on a NULL CallerInfo to indicate
176 // an unknown contact.
177
178 // Currently, info.phoneNumber may actually be a SIP address, and
179 // if so, it might sometimes include the "sip:" prefix. That
180 // prefix isn't really useful to the user, though, so strip it off
181 // if present. (For any other URI scheme, though, leave the
182 // prefix alone.)
183 // TODO: It would be cleaner for CallerInfo to explicitly support
184 // SIP addresses instead of overloading the "phoneNumber" field.
185 // Then we could remove this hack, and instead ask the CallerInfo
186 // for a "user visible" form of the SIP address.
187 String number = info.phoneNumber;
188
189 if (!TextUtils.isEmpty(number)) {
190 isSipCall = PhoneNumberHelper.isUriNumber(number);
191 if (number.startsWith("sip:")) {
192 number = number.substring(4);
193 }
194 }
195
196 if (TextUtils.isEmpty(info.name)) {
197 // No valid "name" in the CallerInfo, so fall back to
198 // something else.
199 // (Typically, we promote the phone number up to the "name" slot
200 // onscreen, and possibly display a descriptive string in the
201 // "number" slot.)
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700202 if (TextUtils.isEmpty(number) && TextUtils.isEmpty(info.cnapName)) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800203 // No name *or* number! Display a generic "unknown" string
204 // (or potentially some other default based on the presentation.)
205 displayName = getPresentationString(context, presentation, info.callSubject);
206 Log.d(TAG, " ==> no name *or* number! displayName = " + displayName);
207 } else if (presentation != TelecomManager.PRESENTATION_ALLOWED) {
208 // This case should never happen since the network should never send a phone #
209 // AND a restricted presentation. However we leave it here in case of weird
210 // network behavior
211 displayName = getPresentationString(context, presentation, info.callSubject);
212 Log.d(TAG, " ==> presentation not allowed! displayName = " + displayName);
213 } else if (!TextUtils.isEmpty(info.cnapName)) {
214 // No name, but we do have a valid CNAP name, so use that.
215 displayName = info.cnapName;
216 info.name = info.cnapName;
wangqi1420a222017-09-21 09:37:40 -0700217 displayNumber = PhoneNumberHelper.formatNumber(number, info.countryIso);
Eric Erfanianccca3152017-02-22 16:32:36 -0800218 Log.d(
219 TAG,
220 " ==> cnapName available: displayName '"
221 + displayName
222 + "', displayNumber '"
223 + displayNumber
224 + "'");
225 } else {
226 // No name; all we have is a number. This is the typical
227 // case when an incoming call doesn't match any contact,
228 // or if you manually dial an outgoing number using the
229 // dialpad.
wangqi1420a222017-09-21 09:37:40 -0700230 displayNumber = PhoneNumberHelper.formatNumber(number, info.countryIso);
Eric Erfanianccca3152017-02-22 16:32:36 -0800231
Eric Erfanianccca3152017-02-22 16:32:36 -0800232 Log.d(
233 TAG,
234 " ==> no name; falling back to number:"
235 + " displayNumber '"
236 + Log.pii(displayNumber)
Eric Erfanianccca3152017-02-22 16:32:36 -0800237 + "'");
238 }
239 } else {
240 // We do have a valid "name" in the CallerInfo. Display that
241 // in the "name" slot, and the phone number in the "number" slot.
242 if (presentation != TelecomManager.PRESENTATION_ALLOWED) {
243 // This case should never happen since the network should never send a name
244 // AND a restricted presentation. However we leave it here in case of weird
245 // network behavior
246 displayName = getPresentationString(context, presentation, info.callSubject);
247 Log.d(
248 TAG,
249 " ==> valid name, but presentation not allowed!" + " displayName = " + displayName);
250 } else {
251 // Causes cce.namePrimary to be set as info.name below. CallCardPresenter will
252 // later determine whether to use the name or nameAlternative when presenting
253 displayName = info.name;
254 cce.nameAlternative = info.nameAlternative;
wangqi1420a222017-09-21 09:37:40 -0700255 displayNumber = PhoneNumberHelper.formatNumber(number, info.countryIso);
Eric Erfanianccca3152017-02-22 16:32:36 -0800256 label = info.phoneLabel;
257 Log.d(
258 TAG,
259 " ==> name is present in CallerInfo: displayName '"
260 + displayName
261 + "', displayNumber '"
262 + displayNumber
263 + "'");
264 }
265 }
266
267 cce.namePrimary = displayName;
268 cce.number = displayNumber;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700269 cce.location = info.geoDescription;
Eric Erfanianccca3152017-02-22 16:32:36 -0800270 cce.label = label;
271 cce.isSipCall = isSipCall;
272 cce.userType = info.userType;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700273 cce.originalPhoneNumber = info.phoneNumber;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700274 cce.shouldShowLocation = info.shouldShowGeoDescription;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700275 cce.isEmergencyNumber = info.isEmergencyNumber();
276 cce.isVoicemailNumber = info.isVoiceMailNumber();
Eric Erfanianccca3152017-02-22 16:32:36 -0800277
278 if (info.contactExists) {
279 cce.contactLookupResult = ContactLookupResult.Type.LOCAL_CONTACT;
280 }
281 }
282
283 /** Gets name strings based on some special presentation modes and the associated custom label. */
284 private static String getPresentationString(
285 Context context, int presentation, String customLabel) {
286 String name = context.getString(R.string.unknown);
287 if (!TextUtils.isEmpty(customLabel)
288 && ((presentation == TelecomManager.PRESENTATION_UNKNOWN)
289 || (presentation == TelecomManager.PRESENTATION_RESTRICTED))) {
290 name = customLabel;
291 return name;
292 } else {
293 if (presentation == TelecomManager.PRESENTATION_RESTRICTED) {
294 name = PhoneNumberHelper.getDisplayNameForRestrictedNumber(context).toString();
295 } else if (presentation == TelecomManager.PRESENTATION_PAYPHONE) {
296 name = context.getString(R.string.payphone);
297 }
298 }
299 return name;
300 }
301
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700302 ContactCacheEntry getInfo(String callId) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800303 return mInfoMap.get(callId);
304 }
305
Eric Erfaniand8046e52017-04-06 09:41:50 -0700306 private static final class CnapInformationWrapper {
307 final String number;
308 final String cnapName;
309 final Context context;
310 final CachedNumberLookupService service;
311
312 CnapInformationWrapper(
313 String number, String cnapName, Context context, CachedNumberLookupService service) {
314 this.number = number;
315 this.cnapName = cnapName;
316 this.context = context;
317 this.service = service;
318 }
319 }
320
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700321 void maybeInsertCnapInformationIntoCache(
Eric Erfanianccca3152017-02-22 16:32:36 -0800322 Context context, final DialerCall call, final CallerInfo info) {
323 final CachedNumberLookupService cachedNumberLookupService =
324 PhoneNumberCache.get(context).getCachedNumberLookupService();
325 if (!UserManagerCompat.isUserUnlocked(context)) {
326 Log.i(TAG, "User locked, not inserting cnap info into cache");
327 return;
328 }
329 if (cachedNumberLookupService == null
330 || TextUtils.isEmpty(info.cnapName)
331 || mInfoMap.get(call.getId()) != null) {
332 return;
333 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800334 Log.i(TAG, "Found contact with CNAP name - inserting into cache");
Eric Erfaniand8046e52017-04-06 09:41:50 -0700335
336 cachedNumberLookupExecutor.executeParallel(
337 new CnapInformationWrapper(
338 call.getNumber(), info.cnapName, context, cachedNumberLookupService));
Eric Erfanianccca3152017-02-22 16:32:36 -0800339 }
340
341 /**
342 * Requests contact data for the DialerCall object passed in. Returns the data through callback.
343 * If callback is null, no response is made, however the query is still performed and cached.
344 *
345 * @param callback The function to call back when the call is found. Can be null.
346 */
347 @MainThread
348 public void findInfo(
349 @NonNull final DialerCall call,
350 final boolean isIncoming,
351 @NonNull ContactInfoCacheCallback callback) {
wangqicf61ca02017-08-31 15:32:55 -0700352 Trace.beginSection("ContactInfoCache.findInfo");
Eric Erfanianccca3152017-02-22 16:32:36 -0800353 Assert.isMainThread();
354 Objects.requireNonNull(callback);
355
wangqic8cf79e2017-10-17 09:21:00 -0700356 Trace.beginSection("prepare callback");
Eric Erfanianccca3152017-02-22 16:32:36 -0800357 final String callId = call.getId();
358 final ContactCacheEntry cacheEntry = mInfoMap.get(callId);
359 Set<ContactInfoCacheCallback> callBacks = mCallBacks.get(callId);
360
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700361 // We need to force a new query if phone number has changed.
362 boolean forceQuery = needForceQuery(call, cacheEntry);
wangqic8cf79e2017-10-17 09:21:00 -0700363 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700364 Log.d(TAG, "findInfo: callId = " + callId + "; forceQuery = " + forceQuery);
365
366 // If we have a previously obtained intermediate result return that now except needs
367 // force query.
368 if (cacheEntry != null && !forceQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800369 Log.d(
370 TAG,
371 "Contact lookup. In memory cache hit; lookup "
372 + (callBacks == null ? "complete" : "still running"));
373 callback.onContactInfoComplete(callId, cacheEntry);
374 // If no other callbacks are in flight, we're done.
375 if (callBacks == null) {
wangqicf61ca02017-08-31 15:32:55 -0700376 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800377 return;
378 }
379 }
380
381 // If the entry already exists, add callback
382 if (callBacks != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700383 Log.d(TAG, "Another query is in progress, add callback only.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800384 callBacks.add(callback);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700385 if (!forceQuery) {
386 Log.d(TAG, "No need to query again, just return and wait for existing query to finish");
wangqicf61ca02017-08-31 15:32:55 -0700387 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700388 return;
389 }
390 } else {
391 Log.d(TAG, "Contact lookup. In memory cache miss; searching provider.");
392 // New lookup
393 callBacks = new ArraySet<>();
394 callBacks.add(callback);
395 mCallBacks.put(callId, callBacks);
Eric Erfanianccca3152017-02-22 16:32:36 -0800396 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800397
wangqic8cf79e2017-10-17 09:21:00 -0700398 Trace.beginSection("prepare query");
Eric Erfanianccca3152017-02-22 16:32:36 -0800399 /**
400 * Performs a query for caller information. Save any immediate data we get from the query. An
401 * asynchronous query may also be made for any data that we do not already have. Some queries,
402 * such as those for voicemail and emergency call information, will not perform an additional
403 * asynchronous query.
404 */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700405 final CallerInfoQueryToken queryToken = new CallerInfoQueryToken(mQueryId, callId);
406 mQueryId++;
Eric Erfanianccca3152017-02-22 16:32:36 -0800407 final CallerInfo callerInfo =
408 CallerInfoUtils.getCallerInfoForCall(
409 mContext,
410 call,
Eric Erfaniand8046e52017-04-06 09:41:50 -0700411 new DialerCallCookieWrapper(callId, call.getNumberPresentation(), call.getCnapName()),
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700412 new FindInfoCallback(isIncoming, queryToken));
wangqic8cf79e2017-10-17 09:21:00 -0700413 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800414
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700415 if (cacheEntry != null) {
416 // We should not override the old cache item until the new query is
417 // back. We should only update the queryId. Otherwise, we may see
418 // flicker of the name and image (old cache -> new cache before query
419 // -> new cache after query)
420 cacheEntry.queryId = queryToken.mQueryId;
421 Log.d(TAG, "There is an existing cache. Do not override until new query is back");
422 } else {
423 ContactCacheEntry initialCacheEntry =
424 updateCallerInfoInCacheOnAnyThread(
Eric Erfanian2ca43182017-08-31 06:57:16 -0700425 callId, call.getNumberPresentation(), callerInfo, false, queryToken);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700426 sendInfoNotifications(callId, initialCacheEntry);
427 }
wangqicf61ca02017-08-31 15:32:55 -0700428 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800429 }
430
431 @AnyThread
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700432 private ContactCacheEntry updateCallerInfoInCacheOnAnyThread(
Eric Erfanianccca3152017-02-22 16:32:36 -0800433 String callId,
434 int numberPresentation,
435 CallerInfo callerInfo,
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700436 boolean didLocalLookup,
437 CallerInfoQueryToken queryToken) {
wangqicf61ca02017-08-31 15:32:55 -0700438 Trace.beginSection("ContactInfoCache.updateCallerInfoInCacheOnAnyThread");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700439 Log.d(
440 TAG,
441 "updateCallerInfoInCacheOnAnyThread: callId = "
442 + callId
443 + "; queryId = "
444 + queryToken.mQueryId
445 + "; didLocalLookup = "
446 + didLocalLookup);
447
Eric Erfanian2ca43182017-08-31 06:57:16 -0700448 ContactCacheEntry existingCacheEntry = mInfoMap.get(callId);
449 Log.d(TAG, "Existing cacheEntry in hashMap " + existingCacheEntry);
450
451 // Mark it as emergency/voicemail if the cache exists and was emergency/voicemail before the
452 // number changed.
453 if (existingCacheEntry != null) {
454 if (existingCacheEntry.isEmergencyNumber) {
455 callerInfo.markAsEmergency(mContext);
456 } else if (existingCacheEntry.isVoicemailNumber) {
457 callerInfo.markAsVoiceMail(mContext);
458 }
459 }
460
Eric Erfanianccca3152017-02-22 16:32:36 -0800461 int presentationMode = numberPresentation;
462 if (callerInfo.contactExists
463 || callerInfo.isEmergencyNumber()
464 || callerInfo.isVoiceMailNumber()) {
465 presentationMode = TelecomManager.PRESENTATION_ALLOWED;
466 }
467
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700468 // We always replace the entry. The only exception is the same photo case.
Eric Erfanian8369df02017-05-03 10:27:13 -0700469 ContactCacheEntry cacheEntry = buildEntry(mContext, callerInfo, presentationMode);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700470 cacheEntry.queryId = queryToken.mQueryId;
471
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700472 if (didLocalLookup) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700473 if (cacheEntry.displayPhotoUri != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700474 // When the difference between 2 numbers is only the prefix (e.g. + or IDD),
475 // we will still trigger force query so that the number can be updated on
476 // the calling screen. We need not query the image again if the previous
477 // query already has the image to avoid flickering.
478 if (existingCacheEntry != null
479 && existingCacheEntry.displayPhotoUri != null
480 && existingCacheEntry.displayPhotoUri.equals(cacheEntry.displayPhotoUri)
481 && existingCacheEntry.photo != null) {
482 Log.d(TAG, "Same picture. Do not need start image load.");
483 cacheEntry.photo = existingCacheEntry.photo;
484 cacheEntry.photoType = existingCacheEntry.photoType;
485 return cacheEntry;
Eric Erfanianccca3152017-02-22 16:32:36 -0800486 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700487
488 Log.d(TAG, "Contact lookup. Local contact found, starting image load");
489 // Load the image with a callback to update the image state.
490 // When the load is finished, onImageLoadComplete() will be called.
491 cacheEntry.hasPendingQuery = true;
492 ContactsAsyncHelper.startObtainPhotoAsync(
493 TOKEN_UPDATE_PHOTO_FOR_CALL_STATE,
494 mContext,
495 cacheEntry.displayPhotoUri,
496 ContactInfoCache.this,
497 queryToken);
Eric Erfanianccca3152017-02-22 16:32:36 -0800498 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700499 Log.d(TAG, "put entry into map: " + cacheEntry);
500 mInfoMap.put(callId, cacheEntry);
501 } else {
502 // Don't overwrite if there is existing cache.
503 Log.d(TAG, "put entry into map if not exists: " + cacheEntry);
504 mInfoMap.putIfAbsent(callId, cacheEntry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800505 }
wangqicf61ca02017-08-31 15:32:55 -0700506 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700507 return cacheEntry;
Eric Erfanianccca3152017-02-22 16:32:36 -0800508 }
509
Eric Erfaniand8046e52017-04-06 09:41:50 -0700510 private void maybeUpdateFromCequintCallerId(
511 CallerInfo callerInfo, String cnapName, boolean isIncoming) {
Eric Erfanian9779f962017-03-27 12:31:48 -0700512 if (!CequintCallerIdManager.isCequintCallerIdEnabled(mContext)) {
513 return;
514 }
Eric Erfaniand8046e52017-04-06 09:41:50 -0700515 if (callerInfo.phoneNumber == null) {
516 return;
517 }
Eric Erfanian9779f962017-03-27 12:31:48 -0700518 CequintCallerIdContact cequintCallerIdContact =
519 CequintCallerIdManager.getCequintCallerIdContactForInCall(
Eric Erfaniand8046e52017-04-06 09:41:50 -0700520 mContext, callerInfo.phoneNumber, cnapName, isIncoming);
Eric Erfanian9779f962017-03-27 12:31:48 -0700521
Eric Erfaniand8046e52017-04-06 09:41:50 -0700522 if (cequintCallerIdContact == null) {
523 return;
524 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700525 boolean hasUpdate = false;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700526
527 if (TextUtils.isEmpty(callerInfo.name) && !TextUtils.isEmpty(cequintCallerIdContact.name)) {
Eric Erfanian9779f962017-03-27 12:31:48 -0700528 callerInfo.name = cequintCallerIdContact.name;
Eric Erfanian8369df02017-05-03 10:27:13 -0700529 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700530 }
531 if (!TextUtils.isEmpty(cequintCallerIdContact.geoDescription)) {
532 callerInfo.geoDescription = cequintCallerIdContact.geoDescription;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700533 callerInfo.shouldShowGeoDescription = true;
Eric Erfanian8369df02017-05-03 10:27:13 -0700534 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700535 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700536 // Don't overwrite photo in local contacts.
537 if (!callerInfo.contactExists
538 && callerInfo.contactDisplayPhotoUri == null
539 && cequintCallerIdContact.imageUrl != null) {
Eric Erfanian9779f962017-03-27 12:31:48 -0700540 callerInfo.contactDisplayPhotoUri = Uri.parse(cequintCallerIdContact.imageUrl);
Eric Erfanian8369df02017-05-03 10:27:13 -0700541 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700542 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700543 // Set contact to exist to avoid phone number service lookup.
544 callerInfo.contactExists = hasUpdate;
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;
556 final String callId = myCookie.mCallId;
557 final int queryId = myCookie.mQueryId;
558 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) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700565 Log.d(TAG, "Image load complete with context: ", mContext);
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;
569 final String callId = myCookie.mCallId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800570 ContactCacheEntry entry = mInfoMap.get(callId);
571
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);
Eric Erfanianccca3152017-02-22 16:32:36 -0800587 entry.photo = new BitmapDrawable(mContext.getResources(), photoIcon);
588 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;
605 final String callId = myCookie.mCallId;
606 final int queryId = myCookie.mQueryId;
607 if (!isWaitingForThisQuery(callId, queryId)) {
608 return;
609 }
610 sendImageNotifications(callId, mInfoMap.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() {
617 mInfoMap.clear();
618 mCallBacks.clear();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700619 mQueryId = 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
641 // Support any contact id in N because QuickContacts in N starts supporting enterprise
642 // contact id
643 if (info.lookupKeyOrNull != null
644 && (VERSION.SDK_INT >= VERSION_CODES.N || info.contactIdOrZero != 0)) {
645 cce.lookupUri = Contacts.getLookupUri(info.contactIdOrZero, info.lookupKeyOrNull);
646 } else {
647 Log.v(TAG, "lookup key is null or contact ID is 0 on M. Don't create a lookup uri.");
648 cce.lookupUri = null;
649 }
650
651 cce.lookupKey = info.lookupKeyOrNull;
652 cce.contactRingtoneUri = info.contactRingtoneUri;
653 if (cce.contactRingtoneUri == null || Uri.EMPTY.equals(cce.contactRingtoneUri)) {
654 cce.contactRingtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
655 }
656
657 return cce;
658 }
659
660 /** Sends the updated information to call the callbacks for the entry. */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700661 @MainThread
Eric Erfanianccca3152017-02-22 16:32:36 -0800662 private void sendInfoNotifications(String callId, ContactCacheEntry entry) {
wangqicf61ca02017-08-31 15:32:55 -0700663 Trace.beginSection("ContactInfoCache.sendInfoNotifications");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700664 Assert.isMainThread();
Eric Erfanianccca3152017-02-22 16:32:36 -0800665 final Set<ContactInfoCacheCallback> callBacks = mCallBacks.get(callId);
666 if (callBacks != null) {
667 for (ContactInfoCacheCallback callBack : callBacks) {
668 callBack.onContactInfoComplete(callId, entry);
669 }
670 }
wangqicf61ca02017-08-31 15:32:55 -0700671 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800672 }
673
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700674 @MainThread
Eric Erfanianccca3152017-02-22 16:32:36 -0800675 private void sendImageNotifications(String callId, ContactCacheEntry entry) {
wangqicf61ca02017-08-31 15:32:55 -0700676 Trace.beginSection("ContactInfoCache.sendImageNotifications");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700677 Assert.isMainThread();
Eric Erfanianccca3152017-02-22 16:32:36 -0800678 final Set<ContactInfoCacheCallback> callBacks = mCallBacks.get(callId);
679 if (callBacks != null && entry.photo != null) {
680 for (ContactInfoCacheCallback callBack : callBacks) {
681 callBack.onImageLoadComplete(callId, entry);
682 }
683 }
wangqicf61ca02017-08-31 15:32:55 -0700684 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800685 }
686
687 private void clearCallbacks(String callId) {
688 mCallBacks.remove(callId);
689 }
690
Eric Erfanianccca3152017-02-22 16:32:36 -0800691 /** Callback interface for the contact query. */
692 public interface ContactInfoCacheCallback {
693
694 void onContactInfoComplete(String callId, ContactCacheEntry entry);
695
696 void onImageLoadComplete(String callId, ContactCacheEntry entry);
697 }
698
699 /** This is cached contact info, which should be the ONLY info used by UI. */
700 public static class ContactCacheEntry {
701
702 public String namePrimary;
703 public String nameAlternative;
704 public String number;
705 public String location;
706 public String label;
707 public Drawable photo;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700708 @ContactPhotoType int photoType;
709 boolean isSipCall;
Eric Erfanianccca3152017-02-22 16:32:36 -0800710 // Note in cache entry whether this is a pending async loading action to know whether to
711 // wait for its callback or not.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700712 boolean hasPendingQuery;
Eric Erfanianccca3152017-02-22 16:32:36 -0800713 /** Either a display photo or a thumbnail URI. */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700714 Uri displayPhotoUri;
Eric Erfanianccca3152017-02-22 16:32:36 -0800715
716 public Uri lookupUri; // Sent to NotificationMananger
717 public String lookupKey;
Eric Erfanian8369df02017-05-03 10:27:13 -0700718 public ContactLookupResult.Type contactLookupResult = ContactLookupResult.Type.NOT_FOUND;
Eric Erfanianccca3152017-02-22 16:32:36 -0800719 public long userType = ContactsUtils.USER_TYPE_CURRENT;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700720 Uri contactRingtoneUri;
721 /** Query id to identify the query session. */
722 int queryId;
723 /** The phone number without any changes to display to the user (ex: cnap...) */
724 String originalPhoneNumber;
zachh6a4cebd2017-10-24 17:10:06 -0700725
Eric Erfaniand8046e52017-04-06 09:41:50 -0700726 boolean shouldShowLocation;
Eric Erfanian9779f962017-03-27 12:31:48 -0700727
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700728 boolean isBusiness;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700729 boolean isEmergencyNumber;
730 boolean isVoicemailNumber;
Eric Erfanianccca3152017-02-22 16:32:36 -0800731
wangqiae6c8ec2017-09-28 17:39:40 -0700732 public boolean isLocalContact() {
733 return contactLookupResult == ContactLookupResult.Type.LOCAL_CONTACT;
734 }
735
Eric Erfanianccca3152017-02-22 16:32:36 -0800736 @Override
737 public String toString() {
738 return "ContactCacheEntry{"
739 + "name='"
740 + MoreStrings.toSafeString(namePrimary)
741 + '\''
742 + ", nameAlternative='"
743 + MoreStrings.toSafeString(nameAlternative)
744 + '\''
745 + ", number='"
746 + MoreStrings.toSafeString(number)
747 + '\''
748 + ", location='"
749 + MoreStrings.toSafeString(location)
750 + '\''
751 + ", label='"
752 + label
753 + '\''
754 + ", photo="
755 + photo
756 + ", isSipCall="
757 + isSipCall
Eric Erfanianccca3152017-02-22 16:32:36 -0800758 + ", displayPhotoUri="
759 + displayPhotoUri
760 + ", contactLookupResult="
761 + contactLookupResult
762 + ", userType="
763 + userType
764 + ", contactRingtoneUri="
765 + contactRingtoneUri
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700766 + ", queryId="
767 + queryId
768 + ", originalPhoneNumber="
769 + originalPhoneNumber
Eric Erfaniand8046e52017-04-06 09:41:50 -0700770 + ", shouldShowLocation="
771 + shouldShowLocation
Eric Erfanian2ca43182017-08-31 06:57:16 -0700772 + ", isEmergencyNumber="
773 + isEmergencyNumber
774 + ", isVoicemailNumber="
775 + isVoicemailNumber
Eric Erfanianccca3152017-02-22 16:32:36 -0800776 + '}';
777 }
778 }
779
780 private static final class DialerCallCookieWrapper {
Eric Erfaniand8046e52017-04-06 09:41:50 -0700781 final String callId;
782 final int numberPresentation;
783 final String cnapName;
Eric Erfanianccca3152017-02-22 16:32:36 -0800784
Eric Erfaniand8046e52017-04-06 09:41:50 -0700785 DialerCallCookieWrapper(String callId, int numberPresentation, String cnapName) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800786 this.callId = callId;
787 this.numberPresentation = numberPresentation;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700788 this.cnapName = cnapName;
Eric Erfanianccca3152017-02-22 16:32:36 -0800789 }
790 }
791
792 private class FindInfoCallback implements OnQueryCompleteListener {
793
794 private final boolean mIsIncoming;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700795 private final CallerInfoQueryToken mQueryToken;
Eric Erfanianccca3152017-02-22 16:32:36 -0800796
Eric Erfaniand8046e52017-04-06 09:41:50 -0700797 FindInfoCallback(boolean isIncoming, CallerInfoQueryToken queryToken) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800798 mIsIncoming = isIncoming;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700799 mQueryToken = queryToken;
Eric Erfanianccca3152017-02-22 16:32:36 -0800800 }
801
802 @Override
803 public void onDataLoaded(int token, Object cookie, CallerInfo ci) {
804 Assert.isWorkerThread();
805 DialerCallCookieWrapper cw = (DialerCallCookieWrapper) cookie;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700806 if (!isWaitingForThisQuery(cw.callId, mQueryToken.mQueryId)) {
807 return;
808 }
Eric Erfanian9779f962017-03-27 12:31:48 -0700809 long start = SystemClock.uptimeMillis();
Eric Erfaniand8046e52017-04-06 09:41:50 -0700810 maybeUpdateFromCequintCallerId(ci, cw.cnapName, mIsIncoming);
Eric Erfanian9779f962017-03-27 12:31:48 -0700811 long time = SystemClock.uptimeMillis() - start;
812 Log.d(TAG, "Cequint Caller Id look up takes " + time + " ms.");
Eric Erfanian2ca43182017-08-31 06:57:16 -0700813 updateCallerInfoInCacheOnAnyThread(cw.callId, cw.numberPresentation, ci, true, mQueryToken);
Eric Erfanianccca3152017-02-22 16:32:36 -0800814 }
815
816 @Override
817 public void onQueryComplete(int token, Object cookie, CallerInfo callerInfo) {
wangqi9982f0d2017-10-11 17:46:07 -0700818 Trace.beginSection("ContactInfoCache.FindInfoCallback.onQueryComplete");
Eric Erfanianccca3152017-02-22 16:32:36 -0800819 Assert.isMainThread();
820 DialerCallCookieWrapper cw = (DialerCallCookieWrapper) cookie;
821 String callId = cw.callId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700822 if (!isWaitingForThisQuery(cw.callId, mQueryToken.mQueryId)) {
wangqi9982f0d2017-10-11 17:46:07 -0700823 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700824 return;
825 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800826 ContactCacheEntry cacheEntry = mInfoMap.get(callId);
827 // This may happen only when InCallPresenter attempt to cleanup.
828 if (cacheEntry == null) {
829 Log.w(TAG, "Contact lookup done, but cache entry is not found.");
830 clearCallbacks(callId);
wangqi9982f0d2017-10-11 17:46:07 -0700831 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800832 return;
833 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700834 // Before issuing a request for more data from other services, we only check that the
835 // contact wasn't found in the local DB. We don't check the if the cache entry already
836 // has a name because we allow overriding cnap data with data from other services.
837 if (!callerInfo.contactExists && mPhoneNumberService != null) {
838 Log.d(TAG, "Contact lookup. Local contacts miss, checking remote");
839 final PhoneNumberServiceListener listener =
840 new PhoneNumberServiceListener(callId, mQueryToken.mQueryId);
841 cacheEntry.hasPendingQuery = true;
842 mPhoneNumberService.getPhoneNumberInfo(cacheEntry.number, listener, listener, mIsIncoming);
843 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800844 sendInfoNotifications(callId, cacheEntry);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700845 if (!cacheEntry.hasPendingQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800846 if (callerInfo.contactExists) {
847 Log.d(TAG, "Contact lookup done. Local contact found, no image.");
848 } else {
849 Log.d(
850 TAG,
851 "Contact lookup done. Local contact not found and"
852 + " no remote lookup service available.");
853 }
854 clearCallbacks(callId);
855 }
wangqi9982f0d2017-10-11 17:46:07 -0700856 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800857 }
858 }
859
860 class PhoneNumberServiceListener
861 implements PhoneNumberService.NumberLookupListener, PhoneNumberService.ImageLookupListener {
862
863 private final String mCallId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700864 private final int mQueryIdOfRemoteLookup;
Eric Erfanianccca3152017-02-22 16:32:36 -0800865
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700866 PhoneNumberServiceListener(String callId, int queryId) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800867 mCallId = callId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700868 mQueryIdOfRemoteLookup = queryId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800869 }
870
871 @Override
872 public void onPhoneNumberInfoComplete(final PhoneNumberService.PhoneNumberInfo info) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700873 Log.d(TAG, "PhoneNumberServiceListener.onPhoneNumberInfoComplete");
874 if (!isWaitingForThisQuery(mCallId, mQueryIdOfRemoteLookup)) {
875 return;
876 }
877
Eric Erfanianccca3152017-02-22 16:32:36 -0800878 // If we got a miss, this is the end of the lookup pipeline,
879 // so clear the callbacks and return.
880 if (info == null) {
881 Log.d(TAG, "Contact lookup done. Remote contact not found.");
882 clearCallbacks(mCallId);
883 return;
884 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800885 ContactCacheEntry entry = new ContactCacheEntry();
886 entry.namePrimary = info.getDisplayName();
887 entry.number = info.getNumber();
888 entry.contactLookupResult = info.getLookupSource();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700889 entry.isBusiness = info.isBusiness();
Eric Erfanianccca3152017-02-22 16:32:36 -0800890 final int type = info.getPhoneType();
891 final String label = info.getPhoneLabel();
892 if (type == Phone.TYPE_CUSTOM) {
893 entry.label = label;
894 } else {
895 final CharSequence typeStr = Phone.getTypeLabel(mContext.getResources(), type, label);
896 entry.label = typeStr == null ? null : typeStr.toString();
897 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700898 final ContactCacheEntry oldEntry = mInfoMap.get(mCallId);
899 if (oldEntry != null) {
900 // Location is only obtained from local lookup so persist
901 // the value for remote lookups. Once we have a name this
902 // field is no longer used; it is persisted here in case
903 // the UI is ever changed to use it.
904 entry.location = oldEntry.location;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700905 entry.shouldShowLocation = oldEntry.shouldShowLocation;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700906 // Contact specific ringtone is obtained from local lookup.
907 entry.contactRingtoneUri = oldEntry.contactRingtoneUri;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700908 entry.originalPhoneNumber = oldEntry.originalPhoneNumber;
Eric Erfanianccca3152017-02-22 16:32:36 -0800909 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700910
911 // If no image and it's a business, switch to using the default business avatar.
912 if (info.getImageUrl() == null && info.isBusiness()) {
913 Log.d(TAG, "Business has no image. Using default.");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700914 entry.photoType = ContactPhotoType.BUSINESS;
915 }
916
917 Log.d(TAG, "put entry into map: " + entry);
918 mInfoMap.put(mCallId, entry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800919 sendInfoNotifications(mCallId, entry);
920
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700921 entry.hasPendingQuery = info.getImageUrl() != null;
Eric Erfanianccca3152017-02-22 16:32:36 -0800922
923 // If there is no image then we should not expect another callback.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700924 if (!entry.hasPendingQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800925 // We're done, so clear callbacks
926 clearCallbacks(mCallId);
927 }
928 }
929
930 @Override
931 public void onImageFetchComplete(Bitmap bitmap) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700932 Log.d(TAG, "PhoneNumberServiceListener.onImageFetchComplete");
933 if (!isWaitingForThisQuery(mCallId, mQueryIdOfRemoteLookup)) {
934 return;
935 }
936 CallerInfoQueryToken queryToken = new CallerInfoQueryToken(mQueryIdOfRemoteLookup, mCallId);
937 loadImage(null, bitmap, queryToken);
938 onImageLoadComplete(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE, null, bitmap, queryToken);
939 }
940 }
941
942 private boolean needForceQuery(DialerCall call, ContactCacheEntry cacheEntry) {
943 if (call == null || call.isConferenceCall()) {
944 return false;
945 }
946
947 String newPhoneNumber = PhoneNumberUtils.stripSeparators(call.getNumber());
948 if (cacheEntry == null) {
949 // No info in the map yet so it is the 1st query
950 Log.d(TAG, "needForceQuery: first query");
951 return true;
952 }
953 String oldPhoneNumber = PhoneNumberUtils.stripSeparators(cacheEntry.originalPhoneNumber);
954
955 if (!TextUtils.equals(oldPhoneNumber, newPhoneNumber)) {
956 Log.d(TAG, "phone number has changed: " + oldPhoneNumber + " -> " + newPhoneNumber);
957 return true;
958 }
959
960 return false;
961 }
962
963 private static final class CallerInfoQueryToken {
964 final int mQueryId;
965 final String mCallId;
966
967 CallerInfoQueryToken(int queryId, String callId) {
968 mQueryId = queryId;
969 mCallId = callId;
970 }
971 }
972
973 /** Check if the queryId in the cached map is the same as the one from query result. */
974 private boolean isWaitingForThisQuery(String callId, int queryId) {
975 final ContactCacheEntry existingCacheEntry = mInfoMap.get(callId);
976 if (existingCacheEntry == null) {
977 // This might happen if lookup on background thread comes back before the initial entry is
978 // created.
979 Log.d(TAG, "Cached entry is null.");
980 return true;
981 } else {
982 int waitingQueryId = existingCacheEntry.queryId;
983 Log.d(TAG, "waitingQueryId = " + waitingQueryId + "; queryId = " + queryId);
984 return waitingQueryId == queryId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800985 }
986 }
987}