blob: 2735461b2dea69290c7309d501e45e974f918325 [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;
48import com.android.dialer.common.concurrent.DialerExecutors;
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 =
129 DialerExecutors.createNonUiTaskBuilder(mContext, new CachedNumberLookupWorker()).build();
wangqicf61ca02017-08-31 15:32:55 -0700130 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800131 }
132
133 public static synchronized ContactInfoCache getInstance(Context mContext) {
134 if (sCache == null) {
135 sCache = new ContactInfoCache(mContext.getApplicationContext());
136 }
137 return sCache;
138 }
139
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700140 static ContactCacheEntry buildCacheEntryFromCall(
Eric Erfanianccca3152017-02-22 16:32:36 -0800141 Context context, DialerCall call, boolean isIncoming) {
142 final ContactCacheEntry entry = new ContactCacheEntry();
143
144 // TODO: get rid of caller info.
145 final CallerInfo info = CallerInfoUtils.buildCallerInfo(context, call);
Eric Erfanian8369df02017-05-03 10:27:13 -0700146 ContactInfoCache.populateCacheEntry(context, info, entry, call.getNumberPresentation());
Eric Erfanianccca3152017-02-22 16:32:36 -0800147 return entry;
148 }
149
150 /** Populate a cache entry from a call (which got converted into a caller info). */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700151 private static void populateCacheEntry(
Eric Erfanianccca3152017-02-22 16:32:36 -0800152 @NonNull Context context,
153 @NonNull CallerInfo info,
154 @NonNull ContactCacheEntry cce,
Eric Erfanian8369df02017-05-03 10:27:13 -0700155 int presentation) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800156 Objects.requireNonNull(info);
157 String displayName = null;
158 String displayNumber = null;
Eric Erfanianccca3152017-02-22 16:32:36 -0800159 String label = null;
160 boolean isSipCall = false;
161
162 // It appears that there is a small change in behaviour with the
163 // PhoneUtils' startGetCallerInfo whereby if we query with an
164 // empty number, we will get a valid CallerInfo object, but with
165 // fields that are all null, and the isTemporary boolean input
166 // parameter as true.
167
168 // In the past, we would see a NULL callerinfo object, but this
169 // ends up causing null pointer exceptions elsewhere down the
170 // line in other cases, so we need to make this fix instead. It
171 // appears that this was the ONLY call to PhoneUtils
172 // .getCallerInfo() that relied on a NULL CallerInfo to indicate
173 // an unknown contact.
174
175 // Currently, info.phoneNumber may actually be a SIP address, and
176 // if so, it might sometimes include the "sip:" prefix. That
177 // prefix isn't really useful to the user, though, so strip it off
178 // if present. (For any other URI scheme, though, leave the
179 // prefix alone.)
180 // TODO: It would be cleaner for CallerInfo to explicitly support
181 // SIP addresses instead of overloading the "phoneNumber" field.
182 // Then we could remove this hack, and instead ask the CallerInfo
183 // for a "user visible" form of the SIP address.
184 String number = info.phoneNumber;
185
186 if (!TextUtils.isEmpty(number)) {
187 isSipCall = PhoneNumberHelper.isUriNumber(number);
188 if (number.startsWith("sip:")) {
189 number = number.substring(4);
190 }
191 }
192
193 if (TextUtils.isEmpty(info.name)) {
194 // No valid "name" in the CallerInfo, so fall back to
195 // something else.
196 // (Typically, we promote the phone number up to the "name" slot
197 // onscreen, and possibly display a descriptive string in the
198 // "number" slot.)
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700199 if (TextUtils.isEmpty(number) && TextUtils.isEmpty(info.cnapName)) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800200 // No name *or* number! Display a generic "unknown" string
201 // (or potentially some other default based on the presentation.)
202 displayName = getPresentationString(context, presentation, info.callSubject);
203 Log.d(TAG, " ==> no name *or* number! displayName = " + displayName);
204 } else if (presentation != TelecomManager.PRESENTATION_ALLOWED) {
205 // This case should never happen since the network should never send a phone #
206 // AND a restricted presentation. However we leave it here in case of weird
207 // network behavior
208 displayName = getPresentationString(context, presentation, info.callSubject);
209 Log.d(TAG, " ==> presentation not allowed! displayName = " + displayName);
210 } else if (!TextUtils.isEmpty(info.cnapName)) {
211 // No name, but we do have a valid CNAP name, so use that.
212 displayName = info.cnapName;
213 info.name = info.cnapName;
wangqi1420a222017-09-21 09:37:40 -0700214 displayNumber = PhoneNumberHelper.formatNumber(number, info.countryIso);
Eric Erfanianccca3152017-02-22 16:32:36 -0800215 Log.d(
216 TAG,
217 " ==> cnapName available: displayName '"
218 + displayName
219 + "', displayNumber '"
220 + displayNumber
221 + "'");
222 } else {
223 // No name; all we have is a number. This is the typical
224 // case when an incoming call doesn't match any contact,
225 // or if you manually dial an outgoing number using the
226 // dialpad.
wangqi1420a222017-09-21 09:37:40 -0700227 displayNumber = PhoneNumberHelper.formatNumber(number, info.countryIso);
Eric Erfanianccca3152017-02-22 16:32:36 -0800228
Eric Erfanianccca3152017-02-22 16:32:36 -0800229 Log.d(
230 TAG,
231 " ==> no name; falling back to number:"
232 + " displayNumber '"
233 + Log.pii(displayNumber)
Eric Erfanianccca3152017-02-22 16:32:36 -0800234 + "'");
235 }
236 } else {
237 // We do have a valid "name" in the CallerInfo. Display that
238 // in the "name" slot, and the phone number in the "number" slot.
239 if (presentation != TelecomManager.PRESENTATION_ALLOWED) {
240 // This case should never happen since the network should never send a name
241 // AND a restricted presentation. However we leave it here in case of weird
242 // network behavior
243 displayName = getPresentationString(context, presentation, info.callSubject);
244 Log.d(
245 TAG,
246 " ==> valid name, but presentation not allowed!" + " displayName = " + displayName);
247 } else {
248 // Causes cce.namePrimary to be set as info.name below. CallCardPresenter will
249 // later determine whether to use the name or nameAlternative when presenting
250 displayName = info.name;
251 cce.nameAlternative = info.nameAlternative;
wangqi1420a222017-09-21 09:37:40 -0700252 displayNumber = PhoneNumberHelper.formatNumber(number, info.countryIso);
Eric Erfanianccca3152017-02-22 16:32:36 -0800253 label = info.phoneLabel;
254 Log.d(
255 TAG,
256 " ==> name is present in CallerInfo: displayName '"
257 + displayName
258 + "', displayNumber '"
259 + displayNumber
260 + "'");
261 }
262 }
263
264 cce.namePrimary = displayName;
265 cce.number = displayNumber;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700266 cce.location = info.geoDescription;
Eric Erfanianccca3152017-02-22 16:32:36 -0800267 cce.label = label;
268 cce.isSipCall = isSipCall;
269 cce.userType = info.userType;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700270 cce.originalPhoneNumber = info.phoneNumber;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700271 cce.shouldShowLocation = info.shouldShowGeoDescription;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700272 cce.isEmergencyNumber = info.isEmergencyNumber();
273 cce.isVoicemailNumber = info.isVoiceMailNumber();
Eric Erfanianccca3152017-02-22 16:32:36 -0800274
275 if (info.contactExists) {
276 cce.contactLookupResult = ContactLookupResult.Type.LOCAL_CONTACT;
277 }
278 }
279
280 /** Gets name strings based on some special presentation modes and the associated custom label. */
281 private static String getPresentationString(
282 Context context, int presentation, String customLabel) {
283 String name = context.getString(R.string.unknown);
284 if (!TextUtils.isEmpty(customLabel)
285 && ((presentation == TelecomManager.PRESENTATION_UNKNOWN)
286 || (presentation == TelecomManager.PRESENTATION_RESTRICTED))) {
287 name = customLabel;
288 return name;
289 } else {
290 if (presentation == TelecomManager.PRESENTATION_RESTRICTED) {
291 name = PhoneNumberHelper.getDisplayNameForRestrictedNumber(context).toString();
292 } else if (presentation == TelecomManager.PRESENTATION_PAYPHONE) {
293 name = context.getString(R.string.payphone);
294 }
295 }
296 return name;
297 }
298
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700299 ContactCacheEntry getInfo(String callId) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800300 return mInfoMap.get(callId);
301 }
302
Eric Erfaniand8046e52017-04-06 09:41:50 -0700303 private static final class CnapInformationWrapper {
304 final String number;
305 final String cnapName;
306 final Context context;
307 final CachedNumberLookupService service;
308
309 CnapInformationWrapper(
310 String number, String cnapName, Context context, CachedNumberLookupService service) {
311 this.number = number;
312 this.cnapName = cnapName;
313 this.context = context;
314 this.service = service;
315 }
316 }
317
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700318 void maybeInsertCnapInformationIntoCache(
Eric Erfanianccca3152017-02-22 16:32:36 -0800319 Context context, final DialerCall call, final CallerInfo info) {
320 final CachedNumberLookupService cachedNumberLookupService =
321 PhoneNumberCache.get(context).getCachedNumberLookupService();
322 if (!UserManagerCompat.isUserUnlocked(context)) {
323 Log.i(TAG, "User locked, not inserting cnap info into cache");
324 return;
325 }
326 if (cachedNumberLookupService == null
327 || TextUtils.isEmpty(info.cnapName)
328 || mInfoMap.get(call.getId()) != null) {
329 return;
330 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800331 Log.i(TAG, "Found contact with CNAP name - inserting into cache");
Eric Erfaniand8046e52017-04-06 09:41:50 -0700332
333 cachedNumberLookupExecutor.executeParallel(
334 new CnapInformationWrapper(
335 call.getNumber(), info.cnapName, context, cachedNumberLookupService));
Eric Erfanianccca3152017-02-22 16:32:36 -0800336 }
337
338 /**
339 * Requests contact data for the DialerCall object passed in. Returns the data through callback.
340 * If callback is null, no response is made, however the query is still performed and cached.
341 *
342 * @param callback The function to call back when the call is found. Can be null.
343 */
344 @MainThread
345 public void findInfo(
346 @NonNull final DialerCall call,
347 final boolean isIncoming,
348 @NonNull ContactInfoCacheCallback callback) {
wangqicf61ca02017-08-31 15:32:55 -0700349 Trace.beginSection("ContactInfoCache.findInfo");
Eric Erfanianccca3152017-02-22 16:32:36 -0800350 Assert.isMainThread();
351 Objects.requireNonNull(callback);
352
wangqic8cf79e2017-10-17 09:21:00 -0700353 Trace.beginSection("prepare callback");
Eric Erfanianccca3152017-02-22 16:32:36 -0800354 final String callId = call.getId();
355 final ContactCacheEntry cacheEntry = mInfoMap.get(callId);
356 Set<ContactInfoCacheCallback> callBacks = mCallBacks.get(callId);
357
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700358 // We need to force a new query if phone number has changed.
359 boolean forceQuery = needForceQuery(call, cacheEntry);
wangqic8cf79e2017-10-17 09:21:00 -0700360 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700361 Log.d(TAG, "findInfo: callId = " + callId + "; forceQuery = " + forceQuery);
362
363 // If we have a previously obtained intermediate result return that now except needs
364 // force query.
365 if (cacheEntry != null && !forceQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800366 Log.d(
367 TAG,
368 "Contact lookup. In memory cache hit; lookup "
369 + (callBacks == null ? "complete" : "still running"));
370 callback.onContactInfoComplete(callId, cacheEntry);
371 // If no other callbacks are in flight, we're done.
372 if (callBacks == null) {
wangqicf61ca02017-08-31 15:32:55 -0700373 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800374 return;
375 }
376 }
377
378 // If the entry already exists, add callback
379 if (callBacks != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700380 Log.d(TAG, "Another query is in progress, add callback only.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800381 callBacks.add(callback);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700382 if (!forceQuery) {
383 Log.d(TAG, "No need to query again, just return and wait for existing query to finish");
wangqicf61ca02017-08-31 15:32:55 -0700384 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700385 return;
386 }
387 } else {
388 Log.d(TAG, "Contact lookup. In memory cache miss; searching provider.");
389 // New lookup
390 callBacks = new ArraySet<>();
391 callBacks.add(callback);
392 mCallBacks.put(callId, callBacks);
Eric Erfanianccca3152017-02-22 16:32:36 -0800393 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800394
wangqic8cf79e2017-10-17 09:21:00 -0700395 Trace.beginSection("prepare query");
Eric Erfanianccca3152017-02-22 16:32:36 -0800396 /**
397 * Performs a query for caller information. Save any immediate data we get from the query. An
398 * asynchronous query may also be made for any data that we do not already have. Some queries,
399 * such as those for voicemail and emergency call information, will not perform an additional
400 * asynchronous query.
401 */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700402 final CallerInfoQueryToken queryToken = new CallerInfoQueryToken(mQueryId, callId);
403 mQueryId++;
Eric Erfanianccca3152017-02-22 16:32:36 -0800404 final CallerInfo callerInfo =
405 CallerInfoUtils.getCallerInfoForCall(
406 mContext,
407 call,
Eric Erfaniand8046e52017-04-06 09:41:50 -0700408 new DialerCallCookieWrapper(callId, call.getNumberPresentation(), call.getCnapName()),
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700409 new FindInfoCallback(isIncoming, queryToken));
wangqic8cf79e2017-10-17 09:21:00 -0700410 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800411
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700412 if (cacheEntry != null) {
413 // We should not override the old cache item until the new query is
414 // back. We should only update the queryId. Otherwise, we may see
415 // flicker of the name and image (old cache -> new cache before query
416 // -> new cache after query)
417 cacheEntry.queryId = queryToken.mQueryId;
418 Log.d(TAG, "There is an existing cache. Do not override until new query is back");
419 } else {
420 ContactCacheEntry initialCacheEntry =
421 updateCallerInfoInCacheOnAnyThread(
Eric Erfanian2ca43182017-08-31 06:57:16 -0700422 callId, call.getNumberPresentation(), callerInfo, false, queryToken);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700423 sendInfoNotifications(callId, initialCacheEntry);
424 }
wangqicf61ca02017-08-31 15:32:55 -0700425 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800426 }
427
428 @AnyThread
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700429 private ContactCacheEntry updateCallerInfoInCacheOnAnyThread(
Eric Erfanianccca3152017-02-22 16:32:36 -0800430 String callId,
431 int numberPresentation,
432 CallerInfo callerInfo,
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700433 boolean didLocalLookup,
434 CallerInfoQueryToken queryToken) {
wangqicf61ca02017-08-31 15:32:55 -0700435 Trace.beginSection("ContactInfoCache.updateCallerInfoInCacheOnAnyThread");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700436 Log.d(
437 TAG,
438 "updateCallerInfoInCacheOnAnyThread: callId = "
439 + callId
440 + "; queryId = "
441 + queryToken.mQueryId
442 + "; didLocalLookup = "
443 + didLocalLookup);
444
Eric Erfanian2ca43182017-08-31 06:57:16 -0700445 ContactCacheEntry existingCacheEntry = mInfoMap.get(callId);
446 Log.d(TAG, "Existing cacheEntry in hashMap " + existingCacheEntry);
447
448 // Mark it as emergency/voicemail if the cache exists and was emergency/voicemail before the
449 // number changed.
450 if (existingCacheEntry != null) {
451 if (existingCacheEntry.isEmergencyNumber) {
452 callerInfo.markAsEmergency(mContext);
453 } else if (existingCacheEntry.isVoicemailNumber) {
454 callerInfo.markAsVoiceMail(mContext);
455 }
456 }
457
Eric Erfanianccca3152017-02-22 16:32:36 -0800458 int presentationMode = numberPresentation;
459 if (callerInfo.contactExists
460 || callerInfo.isEmergencyNumber()
461 || callerInfo.isVoiceMailNumber()) {
462 presentationMode = TelecomManager.PRESENTATION_ALLOWED;
463 }
464
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700465 // We always replace the entry. The only exception is the same photo case.
Eric Erfanian8369df02017-05-03 10:27:13 -0700466 ContactCacheEntry cacheEntry = buildEntry(mContext, callerInfo, presentationMode);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700467 cacheEntry.queryId = queryToken.mQueryId;
468
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700469 if (didLocalLookup) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700470 if (cacheEntry.displayPhotoUri != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700471 // When the difference between 2 numbers is only the prefix (e.g. + or IDD),
472 // we will still trigger force query so that the number can be updated on
473 // the calling screen. We need not query the image again if the previous
474 // query already has the image to avoid flickering.
475 if (existingCacheEntry != null
476 && existingCacheEntry.displayPhotoUri != null
477 && existingCacheEntry.displayPhotoUri.equals(cacheEntry.displayPhotoUri)
478 && existingCacheEntry.photo != null) {
479 Log.d(TAG, "Same picture. Do not need start image load.");
480 cacheEntry.photo = existingCacheEntry.photo;
481 cacheEntry.photoType = existingCacheEntry.photoType;
482 return cacheEntry;
Eric Erfanianccca3152017-02-22 16:32:36 -0800483 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700484
485 Log.d(TAG, "Contact lookup. Local contact found, starting image load");
486 // Load the image with a callback to update the image state.
487 // When the load is finished, onImageLoadComplete() will be called.
488 cacheEntry.hasPendingQuery = true;
489 ContactsAsyncHelper.startObtainPhotoAsync(
490 TOKEN_UPDATE_PHOTO_FOR_CALL_STATE,
491 mContext,
492 cacheEntry.displayPhotoUri,
493 ContactInfoCache.this,
494 queryToken);
Eric Erfanianccca3152017-02-22 16:32:36 -0800495 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700496 Log.d(TAG, "put entry into map: " + cacheEntry);
497 mInfoMap.put(callId, cacheEntry);
498 } else {
499 // Don't overwrite if there is existing cache.
500 Log.d(TAG, "put entry into map if not exists: " + cacheEntry);
501 mInfoMap.putIfAbsent(callId, cacheEntry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800502 }
wangqicf61ca02017-08-31 15:32:55 -0700503 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700504 return cacheEntry;
Eric Erfanianccca3152017-02-22 16:32:36 -0800505 }
506
Eric Erfaniand8046e52017-04-06 09:41:50 -0700507 private void maybeUpdateFromCequintCallerId(
508 CallerInfo callerInfo, String cnapName, boolean isIncoming) {
Eric Erfanian9779f962017-03-27 12:31:48 -0700509 if (!CequintCallerIdManager.isCequintCallerIdEnabled(mContext)) {
510 return;
511 }
Eric Erfaniand8046e52017-04-06 09:41:50 -0700512 if (callerInfo.phoneNumber == null) {
513 return;
514 }
Eric Erfanian9779f962017-03-27 12:31:48 -0700515 CequintCallerIdContact cequintCallerIdContact =
516 CequintCallerIdManager.getCequintCallerIdContactForInCall(
Eric Erfaniand8046e52017-04-06 09:41:50 -0700517 mContext, callerInfo.phoneNumber, cnapName, isIncoming);
Eric Erfanian9779f962017-03-27 12:31:48 -0700518
Eric Erfaniand8046e52017-04-06 09:41:50 -0700519 if (cequintCallerIdContact == null) {
520 return;
521 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700522 boolean hasUpdate = false;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700523
524 if (TextUtils.isEmpty(callerInfo.name) && !TextUtils.isEmpty(cequintCallerIdContact.name)) {
Eric Erfanian9779f962017-03-27 12:31:48 -0700525 callerInfo.name = cequintCallerIdContact.name;
Eric Erfanian8369df02017-05-03 10:27:13 -0700526 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700527 }
528 if (!TextUtils.isEmpty(cequintCallerIdContact.geoDescription)) {
529 callerInfo.geoDescription = cequintCallerIdContact.geoDescription;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700530 callerInfo.shouldShowGeoDescription = true;
Eric Erfanian8369df02017-05-03 10:27:13 -0700531 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700532 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700533 // Don't overwrite photo in local contacts.
534 if (!callerInfo.contactExists
535 && callerInfo.contactDisplayPhotoUri == null
536 && cequintCallerIdContact.imageUrl != null) {
Eric Erfanian9779f962017-03-27 12:31:48 -0700537 callerInfo.contactDisplayPhotoUri = Uri.parse(cequintCallerIdContact.imageUrl);
Eric Erfanian8369df02017-05-03 10:27:13 -0700538 hasUpdate = true;
Eric Erfanian9779f962017-03-27 12:31:48 -0700539 }
Eric Erfanian8369df02017-05-03 10:27:13 -0700540 // Set contact to exist to avoid phone number service lookup.
541 callerInfo.contactExists = hasUpdate;
Eric Erfanian9779f962017-03-27 12:31:48 -0700542 }
543
Eric Erfanianccca3152017-02-22 16:32:36 -0800544 /**
545 * Implemented for ContactsAsyncHelper.OnImageLoadCompleteListener interface. Update contact photo
546 * when image is loaded in worker thread.
547 */
548 @WorkerThread
549 @Override
550 public void onImageLoaded(int token, Drawable photo, Bitmap photoIcon, Object cookie) {
551 Assert.isWorkerThread();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700552 CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie;
553 final String callId = myCookie.mCallId;
554 final int queryId = myCookie.mQueryId;
555 if (!isWaitingForThisQuery(callId, queryId)) {
556 return;
557 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800558 loadImage(photo, photoIcon, cookie);
559 }
560
561 private void loadImage(Drawable photo, Bitmap photoIcon, Object cookie) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700562 Log.d(TAG, "Image load complete with context: ", mContext);
Eric Erfanianccca3152017-02-22 16:32:36 -0800563 // TODO: may be nice to update the image view again once the newer one
564 // is available on contacts database.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700565 CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie;
566 final String callId = myCookie.mCallId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800567 ContactCacheEntry entry = mInfoMap.get(callId);
568
569 if (entry == null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700570 Log.e(TAG, "Image Load received for empty search entry.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800571 clearCallbacks(callId);
572 return;
573 }
574
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700575 Log.d(TAG, "setting photo for entry: ", entry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800576
577 // Conference call icons are being handled in CallCardPresenter.
578 if (photo != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700579 Log.v(TAG, "direct drawable: ", photo);
Eric Erfanianccca3152017-02-22 16:32:36 -0800580 entry.photo = photo;
581 entry.photoType = ContactPhotoType.CONTACT;
582 } else if (photoIcon != null) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700583 Log.v(TAG, "photo icon: ", photoIcon);
Eric Erfanianccca3152017-02-22 16:32:36 -0800584 entry.photo = new BitmapDrawable(mContext.getResources(), photoIcon);
585 entry.photoType = ContactPhotoType.CONTACT;
586 } else {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700587 Log.v(TAG, "unknown photo");
Eric Erfanianccca3152017-02-22 16:32:36 -0800588 entry.photo = null;
589 entry.photoType = ContactPhotoType.DEFAULT_PLACEHOLDER;
590 }
591 }
592
593 /**
594 * Implemented for ContactsAsyncHelper.OnImageLoadCompleteListener interface. make sure that the
595 * call state is reflected after the image is loaded.
596 */
597 @MainThread
598 @Override
599 public void onImageLoadComplete(int token, Drawable photo, Bitmap photoIcon, Object cookie) {
600 Assert.isMainThread();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700601 CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie;
602 final String callId = myCookie.mCallId;
603 final int queryId = myCookie.mQueryId;
604 if (!isWaitingForThisQuery(callId, queryId)) {
605 return;
606 }
607 sendImageNotifications(callId, mInfoMap.get(callId));
Eric Erfanianccca3152017-02-22 16:32:36 -0800608
609 clearCallbacks(callId);
610 }
611
612 /** Blows away the stored cache values. */
613 public void clearCache() {
614 mInfoMap.clear();
615 mCallBacks.clear();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700616 mQueryId = 0;
Eric Erfanianccca3152017-02-22 16:32:36 -0800617 }
618
Eric Erfanian8369df02017-05-03 10:27:13 -0700619 private ContactCacheEntry buildEntry(Context context, CallerInfo info, int presentation) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800620 final ContactCacheEntry cce = new ContactCacheEntry();
Eric Erfanian8369df02017-05-03 10:27:13 -0700621 populateCacheEntry(context, info, cce, presentation);
Eric Erfanianccca3152017-02-22 16:32:36 -0800622
623 // This will only be true for emergency numbers
624 if (info.photoResource != 0) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700625 cce.photo = ContextCompat.getDrawable(context, info.photoResource);
Eric Erfanianccca3152017-02-22 16:32:36 -0800626 } else if (info.isCachedPhotoCurrent) {
627 if (info.cachedPhoto != null) {
628 cce.photo = info.cachedPhoto;
629 cce.photoType = ContactPhotoType.CONTACT;
630 } else {
Eric Erfanianccca3152017-02-22 16:32:36 -0800631 cce.photoType = ContactPhotoType.DEFAULT_PLACEHOLDER;
632 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800633 } else {
634 cce.displayPhotoUri = info.contactDisplayPhotoUri;
635 cce.photo = null;
636 }
637
638 // Support any contact id in N because QuickContacts in N starts supporting enterprise
639 // contact id
640 if (info.lookupKeyOrNull != null
641 && (VERSION.SDK_INT >= VERSION_CODES.N || info.contactIdOrZero != 0)) {
642 cce.lookupUri = Contacts.getLookupUri(info.contactIdOrZero, info.lookupKeyOrNull);
643 } else {
644 Log.v(TAG, "lookup key is null or contact ID is 0 on M. Don't create a lookup uri.");
645 cce.lookupUri = null;
646 }
647
648 cce.lookupKey = info.lookupKeyOrNull;
649 cce.contactRingtoneUri = info.contactRingtoneUri;
650 if (cce.contactRingtoneUri == null || Uri.EMPTY.equals(cce.contactRingtoneUri)) {
651 cce.contactRingtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
652 }
653
654 return cce;
655 }
656
657 /** Sends the updated information to call the callbacks for the entry. */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700658 @MainThread
Eric Erfanianccca3152017-02-22 16:32:36 -0800659 private void sendInfoNotifications(String callId, ContactCacheEntry entry) {
wangqicf61ca02017-08-31 15:32:55 -0700660 Trace.beginSection("ContactInfoCache.sendInfoNotifications");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700661 Assert.isMainThread();
Eric Erfanianccca3152017-02-22 16:32:36 -0800662 final Set<ContactInfoCacheCallback> callBacks = mCallBacks.get(callId);
663 if (callBacks != null) {
664 for (ContactInfoCacheCallback callBack : callBacks) {
665 callBack.onContactInfoComplete(callId, entry);
666 }
667 }
wangqicf61ca02017-08-31 15:32:55 -0700668 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800669 }
670
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700671 @MainThread
Eric Erfanianccca3152017-02-22 16:32:36 -0800672 private void sendImageNotifications(String callId, ContactCacheEntry entry) {
wangqicf61ca02017-08-31 15:32:55 -0700673 Trace.beginSection("ContactInfoCache.sendImageNotifications");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700674 Assert.isMainThread();
Eric Erfanianccca3152017-02-22 16:32:36 -0800675 final Set<ContactInfoCacheCallback> callBacks = mCallBacks.get(callId);
676 if (callBacks != null && entry.photo != null) {
677 for (ContactInfoCacheCallback callBack : callBacks) {
678 callBack.onImageLoadComplete(callId, entry);
679 }
680 }
wangqicf61ca02017-08-31 15:32:55 -0700681 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800682 }
683
684 private void clearCallbacks(String callId) {
685 mCallBacks.remove(callId);
686 }
687
Eric Erfanianccca3152017-02-22 16:32:36 -0800688 /** Callback interface for the contact query. */
689 public interface ContactInfoCacheCallback {
690
691 void onContactInfoComplete(String callId, ContactCacheEntry entry);
692
693 void onImageLoadComplete(String callId, ContactCacheEntry entry);
694 }
695
696 /** This is cached contact info, which should be the ONLY info used by UI. */
697 public static class ContactCacheEntry {
698
699 public String namePrimary;
700 public String nameAlternative;
701 public String number;
702 public String location;
703 public String label;
704 public Drawable photo;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700705 @ContactPhotoType int photoType;
706 boolean isSipCall;
Eric Erfanianccca3152017-02-22 16:32:36 -0800707 // Note in cache entry whether this is a pending async loading action to know whether to
708 // wait for its callback or not.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700709 boolean hasPendingQuery;
Eric Erfanianccca3152017-02-22 16:32:36 -0800710 /** Either a display photo or a thumbnail URI. */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700711 Uri displayPhotoUri;
Eric Erfanianccca3152017-02-22 16:32:36 -0800712
713 public Uri lookupUri; // Sent to NotificationMananger
714 public String lookupKey;
Eric Erfanian8369df02017-05-03 10:27:13 -0700715 public ContactLookupResult.Type contactLookupResult = ContactLookupResult.Type.NOT_FOUND;
Eric Erfanianccca3152017-02-22 16:32:36 -0800716 public long userType = ContactsUtils.USER_TYPE_CURRENT;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700717 Uri contactRingtoneUri;
718 /** Query id to identify the query session. */
719 int queryId;
720 /** The phone number without any changes to display to the user (ex: cnap...) */
721 String originalPhoneNumber;
zachh6a4cebd2017-10-24 17:10:06 -0700722
Eric Erfaniand8046e52017-04-06 09:41:50 -0700723 boolean shouldShowLocation;
Eric Erfanian9779f962017-03-27 12:31:48 -0700724
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700725 boolean isBusiness;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700726 boolean isEmergencyNumber;
727 boolean isVoicemailNumber;
Eric Erfanianccca3152017-02-22 16:32:36 -0800728
wangqiae6c8ec2017-09-28 17:39:40 -0700729 public boolean isLocalContact() {
730 return contactLookupResult == ContactLookupResult.Type.LOCAL_CONTACT;
731 }
732
Eric Erfanianccca3152017-02-22 16:32:36 -0800733 @Override
734 public String toString() {
735 return "ContactCacheEntry{"
736 + "name='"
737 + MoreStrings.toSafeString(namePrimary)
738 + '\''
739 + ", nameAlternative='"
740 + MoreStrings.toSafeString(nameAlternative)
741 + '\''
742 + ", number='"
743 + MoreStrings.toSafeString(number)
744 + '\''
745 + ", location='"
746 + MoreStrings.toSafeString(location)
747 + '\''
748 + ", label='"
749 + label
750 + '\''
751 + ", photo="
752 + photo
753 + ", isSipCall="
754 + isSipCall
Eric Erfanianccca3152017-02-22 16:32:36 -0800755 + ", displayPhotoUri="
756 + displayPhotoUri
757 + ", contactLookupResult="
758 + contactLookupResult
759 + ", userType="
760 + userType
761 + ", contactRingtoneUri="
762 + contactRingtoneUri
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700763 + ", queryId="
764 + queryId
765 + ", originalPhoneNumber="
766 + originalPhoneNumber
Eric Erfaniand8046e52017-04-06 09:41:50 -0700767 + ", shouldShowLocation="
768 + shouldShowLocation
Eric Erfanian2ca43182017-08-31 06:57:16 -0700769 + ", isEmergencyNumber="
770 + isEmergencyNumber
771 + ", isVoicemailNumber="
772 + isVoicemailNumber
Eric Erfanianccca3152017-02-22 16:32:36 -0800773 + '}';
774 }
775 }
776
777 private static final class DialerCallCookieWrapper {
Eric Erfaniand8046e52017-04-06 09:41:50 -0700778 final String callId;
779 final int numberPresentation;
780 final String cnapName;
Eric Erfanianccca3152017-02-22 16:32:36 -0800781
Eric Erfaniand8046e52017-04-06 09:41:50 -0700782 DialerCallCookieWrapper(String callId, int numberPresentation, String cnapName) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800783 this.callId = callId;
784 this.numberPresentation = numberPresentation;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700785 this.cnapName = cnapName;
Eric Erfanianccca3152017-02-22 16:32:36 -0800786 }
787 }
788
789 private class FindInfoCallback implements OnQueryCompleteListener {
790
791 private final boolean mIsIncoming;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700792 private final CallerInfoQueryToken mQueryToken;
Eric Erfanianccca3152017-02-22 16:32:36 -0800793
Eric Erfaniand8046e52017-04-06 09:41:50 -0700794 FindInfoCallback(boolean isIncoming, CallerInfoQueryToken queryToken) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800795 mIsIncoming = isIncoming;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700796 mQueryToken = queryToken;
Eric Erfanianccca3152017-02-22 16:32:36 -0800797 }
798
799 @Override
800 public void onDataLoaded(int token, Object cookie, CallerInfo ci) {
801 Assert.isWorkerThread();
802 DialerCallCookieWrapper cw = (DialerCallCookieWrapper) cookie;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700803 if (!isWaitingForThisQuery(cw.callId, mQueryToken.mQueryId)) {
804 return;
805 }
Eric Erfanian9779f962017-03-27 12:31:48 -0700806 long start = SystemClock.uptimeMillis();
Eric Erfaniand8046e52017-04-06 09:41:50 -0700807 maybeUpdateFromCequintCallerId(ci, cw.cnapName, mIsIncoming);
Eric Erfanian9779f962017-03-27 12:31:48 -0700808 long time = SystemClock.uptimeMillis() - start;
809 Log.d(TAG, "Cequint Caller Id look up takes " + time + " ms.");
Eric Erfanian2ca43182017-08-31 06:57:16 -0700810 updateCallerInfoInCacheOnAnyThread(cw.callId, cw.numberPresentation, ci, true, mQueryToken);
Eric Erfanianccca3152017-02-22 16:32:36 -0800811 }
812
813 @Override
814 public void onQueryComplete(int token, Object cookie, CallerInfo callerInfo) {
wangqi9982f0d2017-10-11 17:46:07 -0700815 Trace.beginSection("ContactInfoCache.FindInfoCallback.onQueryComplete");
Eric Erfanianccca3152017-02-22 16:32:36 -0800816 Assert.isMainThread();
817 DialerCallCookieWrapper cw = (DialerCallCookieWrapper) cookie;
818 String callId = cw.callId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700819 if (!isWaitingForThisQuery(cw.callId, mQueryToken.mQueryId)) {
wangqi9982f0d2017-10-11 17:46:07 -0700820 Trace.endSection();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700821 return;
822 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800823 ContactCacheEntry cacheEntry = mInfoMap.get(callId);
824 // This may happen only when InCallPresenter attempt to cleanup.
825 if (cacheEntry == null) {
826 Log.w(TAG, "Contact lookup done, but cache entry is not found.");
827 clearCallbacks(callId);
wangqi9982f0d2017-10-11 17:46:07 -0700828 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800829 return;
830 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700831 // Before issuing a request for more data from other services, we only check that the
832 // contact wasn't found in the local DB. We don't check the if the cache entry already
833 // has a name because we allow overriding cnap data with data from other services.
834 if (!callerInfo.contactExists && mPhoneNumberService != null) {
835 Log.d(TAG, "Contact lookup. Local contacts miss, checking remote");
836 final PhoneNumberServiceListener listener =
837 new PhoneNumberServiceListener(callId, mQueryToken.mQueryId);
838 cacheEntry.hasPendingQuery = true;
839 mPhoneNumberService.getPhoneNumberInfo(cacheEntry.number, listener, listener, mIsIncoming);
840 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800841 sendInfoNotifications(callId, cacheEntry);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700842 if (!cacheEntry.hasPendingQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800843 if (callerInfo.contactExists) {
844 Log.d(TAG, "Contact lookup done. Local contact found, no image.");
845 } else {
846 Log.d(
847 TAG,
848 "Contact lookup done. Local contact not found and"
849 + " no remote lookup service available.");
850 }
851 clearCallbacks(callId);
852 }
wangqi9982f0d2017-10-11 17:46:07 -0700853 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800854 }
855 }
856
857 class PhoneNumberServiceListener
858 implements PhoneNumberService.NumberLookupListener, PhoneNumberService.ImageLookupListener {
859
860 private final String mCallId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700861 private final int mQueryIdOfRemoteLookup;
Eric Erfanianccca3152017-02-22 16:32:36 -0800862
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700863 PhoneNumberServiceListener(String callId, int queryId) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800864 mCallId = callId;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700865 mQueryIdOfRemoteLookup = queryId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800866 }
867
868 @Override
869 public void onPhoneNumberInfoComplete(final PhoneNumberService.PhoneNumberInfo info) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700870 Log.d(TAG, "PhoneNumberServiceListener.onPhoneNumberInfoComplete");
871 if (!isWaitingForThisQuery(mCallId, mQueryIdOfRemoteLookup)) {
872 return;
873 }
874
Eric Erfanianccca3152017-02-22 16:32:36 -0800875 // If we got a miss, this is the end of the lookup pipeline,
876 // so clear the callbacks and return.
877 if (info == null) {
878 Log.d(TAG, "Contact lookup done. Remote contact not found.");
879 clearCallbacks(mCallId);
880 return;
881 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800882 ContactCacheEntry entry = new ContactCacheEntry();
883 entry.namePrimary = info.getDisplayName();
884 entry.number = info.getNumber();
885 entry.contactLookupResult = info.getLookupSource();
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700886 entry.isBusiness = info.isBusiness();
Eric Erfanianccca3152017-02-22 16:32:36 -0800887 final int type = info.getPhoneType();
888 final String label = info.getPhoneLabel();
889 if (type == Phone.TYPE_CUSTOM) {
890 entry.label = label;
891 } else {
892 final CharSequence typeStr = Phone.getTypeLabel(mContext.getResources(), type, label);
893 entry.label = typeStr == null ? null : typeStr.toString();
894 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700895 final ContactCacheEntry oldEntry = mInfoMap.get(mCallId);
896 if (oldEntry != null) {
897 // Location is only obtained from local lookup so persist
898 // the value for remote lookups. Once we have a name this
899 // field is no longer used; it is persisted here in case
900 // the UI is ever changed to use it.
901 entry.location = oldEntry.location;
Eric Erfaniand8046e52017-04-06 09:41:50 -0700902 entry.shouldShowLocation = oldEntry.shouldShowLocation;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700903 // Contact specific ringtone is obtained from local lookup.
904 entry.contactRingtoneUri = oldEntry.contactRingtoneUri;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700905 entry.originalPhoneNumber = oldEntry.originalPhoneNumber;
Eric Erfanianccca3152017-02-22 16:32:36 -0800906 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700907
908 // If no image and it's a business, switch to using the default business avatar.
909 if (info.getImageUrl() == null && info.isBusiness()) {
910 Log.d(TAG, "Business has no image. Using default.");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700911 entry.photoType = ContactPhotoType.BUSINESS;
912 }
913
914 Log.d(TAG, "put entry into map: " + entry);
915 mInfoMap.put(mCallId, entry);
Eric Erfanianccca3152017-02-22 16:32:36 -0800916 sendInfoNotifications(mCallId, entry);
917
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700918 entry.hasPendingQuery = info.getImageUrl() != null;
Eric Erfanianccca3152017-02-22 16:32:36 -0800919
920 // If there is no image then we should not expect another callback.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700921 if (!entry.hasPendingQuery) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800922 // We're done, so clear callbacks
923 clearCallbacks(mCallId);
924 }
925 }
926
927 @Override
928 public void onImageFetchComplete(Bitmap bitmap) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700929 Log.d(TAG, "PhoneNumberServiceListener.onImageFetchComplete");
930 if (!isWaitingForThisQuery(mCallId, mQueryIdOfRemoteLookup)) {
931 return;
932 }
933 CallerInfoQueryToken queryToken = new CallerInfoQueryToken(mQueryIdOfRemoteLookup, mCallId);
934 loadImage(null, bitmap, queryToken);
935 onImageLoadComplete(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE, null, bitmap, queryToken);
936 }
937 }
938
939 private boolean needForceQuery(DialerCall call, ContactCacheEntry cacheEntry) {
940 if (call == null || call.isConferenceCall()) {
941 return false;
942 }
943
944 String newPhoneNumber = PhoneNumberUtils.stripSeparators(call.getNumber());
945 if (cacheEntry == null) {
946 // No info in the map yet so it is the 1st query
947 Log.d(TAG, "needForceQuery: first query");
948 return true;
949 }
950 String oldPhoneNumber = PhoneNumberUtils.stripSeparators(cacheEntry.originalPhoneNumber);
951
952 if (!TextUtils.equals(oldPhoneNumber, newPhoneNumber)) {
953 Log.d(TAG, "phone number has changed: " + oldPhoneNumber + " -> " + newPhoneNumber);
954 return true;
955 }
956
957 return false;
958 }
959
960 private static final class CallerInfoQueryToken {
961 final int mQueryId;
962 final String mCallId;
963
964 CallerInfoQueryToken(int queryId, String callId) {
965 mQueryId = queryId;
966 mCallId = callId;
967 }
968 }
969
970 /** Check if the queryId in the cached map is the same as the one from query result. */
971 private boolean isWaitingForThisQuery(String callId, int queryId) {
972 final ContactCacheEntry existingCacheEntry = mInfoMap.get(callId);
973 if (existingCacheEntry == null) {
974 // This might happen if lookup on background thread comes back before the initial entry is
975 // created.
976 Log.d(TAG, "Cached entry is null.");
977 return true;
978 } else {
979 int waitingQueryId = existingCacheEntry.queryId;
980 Log.d(TAG, "waitingQueryId = " + waitingQueryId + "; queryId = " + queryId);
981 return waitingQueryId == queryId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800982 }
983 }
984}