blob: f8d7ac65a2e40c215fb23538dc2d9330c44bac3f [file] [log] [blame]
Eric Erfanianccca3152017-02-22 16:32:36 -08001/*
2 * Copyright (C) 2006 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.Manifest;
20import android.annotation.TargetApi;
21import android.content.AsyncQueryHandler;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.database.Cursor;
25import android.database.SQLException;
26import android.net.Uri;
27import android.os.Build.VERSION;
28import android.os.Build.VERSION_CODES;
29import android.os.Handler;
30import android.os.Looper;
31import android.os.Message;
32import android.provider.ContactsContract;
33import android.provider.ContactsContract.Directory;
34import android.support.annotation.MainThread;
35import android.support.annotation.RequiresPermission;
36import android.support.annotation.WorkerThread;
37import android.telephony.PhoneNumberUtils;
38import android.text.TextUtils;
39import com.android.contacts.common.compat.DirectoryCompat;
40import com.android.dialer.phonenumbercache.CachedNumberLookupService;
41import com.android.dialer.phonenumbercache.CachedNumberLookupService.CachedContactInfo;
42import com.android.dialer.phonenumbercache.ContactInfoHelper;
43import com.android.dialer.phonenumbercache.PhoneNumberCache;
44import java.io.IOException;
45import java.io.InputStream;
46import java.util.ArrayList;
47import java.util.Arrays;
48
49/**
50 * Helper class to make it easier to run asynchronous caller-id lookup queries.
51 *
52 * @see CallerInfo
53 */
54@TargetApi(VERSION_CODES.M)
55public class CallerInfoAsyncQuery {
56
57 /** Interface for a CallerInfoAsyncQueryHandler result return. */
58 public interface OnQueryCompleteListener {
59
60 /** Called when the query is complete. */
61 @MainThread
62 void onQueryComplete(int token, Object cookie, CallerInfo ci);
63
64 /** Called when data is loaded. Must be called in worker thread. */
65 @WorkerThread
66 void onDataLoaded(int token, Object cookie, CallerInfo ci);
67 }
68
69 private static final boolean DBG = false;
70 private static final String LOG_TAG = "CallerInfoAsyncQuery";
71
72 private static final int EVENT_NEW_QUERY = 1;
73 private static final int EVENT_ADD_LISTENER = 2;
74 private static final int EVENT_EMERGENCY_NUMBER = 3;
75 private static final int EVENT_VOICEMAIL_NUMBER = 4;
76 // If the CallerInfo query finds no contacts, should we use the
77 // PhoneNumberOfflineGeocoder to look up a "geo description"?
78 // (TODO: This could become a flag in config.xml if it ever needs to be
79 // configured on a per-product basis.)
80 private static final boolean ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION = true;
81 /* Directory lookup related code - START */
82 private static final String[] DIRECTORY_PROJECTION = new String[] {Directory._ID};
83
84 /** Private constructor for factory methods. */
85 private CallerInfoAsyncQuery() {}
86
87 @RequiresPermission(Manifest.permission.READ_CONTACTS)
88 public static void startQuery(
89 final int token,
90 final Context context,
91 final CallerInfo info,
92 final OnQueryCompleteListener listener,
93 final Object cookie) {
94 Log.d(LOG_TAG, "##### CallerInfoAsyncQuery startContactProviderQuery()... #####");
95 Log.d(LOG_TAG, "- number: " + info.phoneNumber);
96 Log.d(LOG_TAG, "- cookie: " + cookie);
97
98 OnQueryCompleteListener contactsProviderQueryCompleteListener =
99 new OnQueryCompleteListener() {
100 @Override
101 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
102 Log.d(LOG_TAG, "contactsProviderQueryCompleteListener done");
103 // If there are no other directory queries, make sure that the listener is
104 // notified of this result. see b/27621628
105 if ((ci != null && ci.contactExists)
106 || !startOtherDirectoriesQuery(token, context, info, listener, cookie)) {
107 if (listener != null && ci != null) {
108 listener.onQueryComplete(token, cookie, ci);
109 }
110 }
111 }
112
113 @Override
114 public void onDataLoaded(int token, Object cookie, CallerInfo ci) {
115 listener.onDataLoaded(token, cookie, ci);
116 }
117 };
118 startDefaultDirectoryQuery(token, context, info, contactsProviderQueryCompleteListener, cookie);
119 }
120
121 // Private methods
122 private static void startDefaultDirectoryQuery(
123 int token,
124 Context context,
125 CallerInfo info,
126 OnQueryCompleteListener listener,
127 Object cookie) {
128 // Construct the URI object and query params, and start the query.
129 Uri uri = ContactInfoHelper.getContactInfoLookupUri(info.phoneNumber);
130 startQueryInternal(token, context, info, listener, cookie, uri);
131 }
132
133 /**
134 * Factory method to start the query based on a CallerInfo object.
135 *
136 * <p>Note: if the number contains an "@" character we treat it as a SIP address, and look it up
137 * directly in the Data table rather than using the PhoneLookup table. TODO: But eventually we
138 * should expose two separate methods, one for numbers and one for SIP addresses, and then have
139 * PhoneUtils.startGetCallerInfo() decide which one to call based on the phone type of the
140 * incoming connection.
141 */
142 private static void startQueryInternal(
143 int token,
144 Context context,
145 CallerInfo info,
146 OnQueryCompleteListener listener,
147 Object cookie,
148 Uri contactRef) {
149 if (DBG) {
150 Log.d(LOG_TAG, "==> contactRef: " + sanitizeUriToString(contactRef));
151 }
152
153 if ((context == null) || (contactRef == null)) {
154 throw new QueryPoolException("Bad context or query uri.");
155 }
156 CallerInfoAsyncQueryHandler handler = new CallerInfoAsyncQueryHandler(context, contactRef);
157
158 //create cookieWrapper, start query
159 CookieWrapper cw = new CookieWrapper();
160 cw.listener = listener;
161 cw.cookie = cookie;
162 cw.number = info.phoneNumber;
163
164 // check to see if these are recognized numbers, and use shortcuts if we can.
165 if (PhoneNumberUtils.isLocalEmergencyNumber(context, info.phoneNumber)) {
166 cw.event = EVENT_EMERGENCY_NUMBER;
167 } else if (info.isVoiceMailNumber()) {
168 cw.event = EVENT_VOICEMAIL_NUMBER;
169 } else {
170 cw.event = EVENT_NEW_QUERY;
171 }
172
173 String[] proejection = CallerInfo.getDefaultPhoneLookupProjection(contactRef);
174 handler.startQuery(
175 token,
176 cw, // cookie
177 contactRef, // uri
178 proejection, // projection
179 null, // selection
180 null, // selectionArgs
181 null); // orderBy
182 }
183
184 // Return value indicates if listener was notified.
185 private static boolean startOtherDirectoriesQuery(
186 int token,
187 Context context,
188 CallerInfo info,
189 OnQueryCompleteListener listener,
190 Object cookie) {
191 long[] directoryIds = getDirectoryIds(context);
192 int size = directoryIds.length;
193 if (size == 0) {
194 return false;
195 }
196
197 DirectoryQueryCompleteListenerFactory listenerFactory =
198 new DirectoryQueryCompleteListenerFactory(context, size, listener);
199
200 // The current implementation of multiple async query runs in single handler thread
201 // in AsyncQueryHandler.
202 // intermediateListener.onQueryComplete is also called from the same caller thread.
203 // TODO(b/26019872): use thread pool instead of single thread.
204 for (int i = 0; i < size; i++) {
205 long directoryId = directoryIds[i];
206 Uri uri = ContactInfoHelper.getContactInfoLookupUri(info.phoneNumber, directoryId);
207 if (DBG) {
208 Log.d(LOG_TAG, "directoryId: " + directoryId + " uri: " + uri);
209 }
210 OnQueryCompleteListener intermediateListener = listenerFactory.newListener(directoryId);
211 startQueryInternal(token, context, info, intermediateListener, cookie, uri);
212 }
213 return true;
214 }
215
216 private static long[] getDirectoryIds(Context context) {
217 ArrayList<Long> results = new ArrayList<>();
218
219 Uri uri = Directory.CONTENT_URI;
220 if (VERSION.SDK_INT >= VERSION_CODES.N) {
221 uri = Uri.withAppendedPath(ContactsContract.AUTHORITY_URI, "directories_enterprise");
222 }
223
224 ContentResolver cr = context.getContentResolver();
225 Cursor cursor = cr.query(uri, DIRECTORY_PROJECTION, null, null, null);
226 addDirectoryIdsFromCursor(cursor, results);
227
228 long[] result = new long[results.size()];
229 for (int i = 0; i < results.size(); i++) {
230 result[i] = results.get(i);
231 }
232 return result;
233 }
234
235 private static void addDirectoryIdsFromCursor(Cursor cursor, ArrayList<Long> results) {
236 if (cursor != null) {
237 int idIndex = cursor.getColumnIndex(Directory._ID);
238 while (cursor.moveToNext()) {
239 long id = cursor.getLong(idIndex);
240 if (DirectoryCompat.isRemoteDirectoryId(id)) {
241 results.add(id);
242 }
243 }
244 cursor.close();
245 }
246 }
247
248 private static String sanitizeUriToString(Uri uri) {
249 if (uri != null) {
250 String uriString = uri.toString();
251 int indexOfLastSlash = uriString.lastIndexOf('/');
252 if (indexOfLastSlash > 0) {
253 return uriString.substring(0, indexOfLastSlash) + "/xxxxxxx";
254 } else {
255 return uriString;
256 }
257 } else {
258 return "";
259 }
260 }
261
262 /** Wrap the cookie from the WorkerArgs with additional information needed by our classes. */
263 private static final class CookieWrapper {
264
265 public OnQueryCompleteListener listener;
266 public Object cookie;
267 public int event;
268 public String number;
269 }
270 /* Directory lookup related code - END */
271
272 /** Simple exception used to communicate problems with the query pool. */
273 public static class QueryPoolException extends SQLException {
274
275 public QueryPoolException(String error) {
276 super(error);
277 }
278 }
279
280 private static final class DirectoryQueryCompleteListenerFactory {
281
282 private final OnQueryCompleteListener mListener;
283 private final Context mContext;
284 // Make sure listener to be called once and only once
285 private int mCount;
286 private boolean mIsListenerCalled;
287
288 DirectoryQueryCompleteListenerFactory(
289 Context context, int size, OnQueryCompleteListener listener) {
290 mCount = size;
291 mListener = listener;
292 mIsListenerCalled = false;
293 mContext = context;
294 }
295
296 private void onDirectoryQueryComplete(
297 int token, Object cookie, CallerInfo ci, long directoryId) {
298 boolean shouldCallListener = false;
299 synchronized (this) {
300 mCount = mCount - 1;
301 if (!mIsListenerCalled && (ci.contactExists || mCount == 0)) {
302 mIsListenerCalled = true;
303 shouldCallListener = true;
304 }
305 }
306
307 // Don't call callback in synchronized block because mListener.onQueryComplete may
308 // take long time to complete
309 if (shouldCallListener && mListener != null) {
310 addCallerInfoIntoCache(ci, directoryId);
311 mListener.onQueryComplete(token, cookie, ci);
312 }
313 }
314
315 private void addCallerInfoIntoCache(CallerInfo ci, long directoryId) {
316 CachedNumberLookupService cachedNumberLookupService =
317 PhoneNumberCache.get(mContext).getCachedNumberLookupService();
318 if (ci.contactExists && cachedNumberLookupService != null) {
319 // 1. Cache caller info
320 CachedContactInfo cachedContactInfo =
321 CallerInfoUtils.buildCachedContactInfo(cachedNumberLookupService, ci);
322 String directoryLabel = mContext.getString(R.string.directory_search_label);
323 cachedContactInfo.setDirectorySource(directoryLabel, directoryId);
324 cachedNumberLookupService.addContact(mContext, cachedContactInfo);
325
326 // 2. Cache photo
327 if (ci.contactDisplayPhotoUri != null && ci.normalizedNumber != null) {
328 try (InputStream in =
329 mContext.getContentResolver().openInputStream(ci.contactDisplayPhotoUri)) {
330 if (in != null) {
331 cachedNumberLookupService.addPhoto(mContext, ci.normalizedNumber, in);
332 }
333 } catch (IOException e) {
334 Log.e(LOG_TAG, "failed to fetch directory contact photo", e);
335 }
336 }
337 }
338 }
339
340 public OnQueryCompleteListener newListener(long directoryId) {
341 return new DirectoryQueryCompleteListener(directoryId);
342 }
343
344 private class DirectoryQueryCompleteListener implements OnQueryCompleteListener {
345
346 private final long mDirectoryId;
347
348 DirectoryQueryCompleteListener(long directoryId) {
349 mDirectoryId = directoryId;
350 }
351
352 @Override
353 public void onDataLoaded(int token, Object cookie, CallerInfo ci) {
354 mListener.onDataLoaded(token, cookie, ci);
355 }
356
357 @Override
358 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
359 onDirectoryQueryComplete(token, cookie, ci, mDirectoryId);
360 }
361 }
362 }
363
364 /** Our own implementation of the AsyncQueryHandler. */
365 private static class CallerInfoAsyncQueryHandler extends AsyncQueryHandler {
366
367 /**
368 * The information relevant to each CallerInfo query. Each query may have multiple listeners, so
369 * each AsyncCursorInfo is associated with 2 or more CookieWrapper objects in the queue (one
370 * with a new query event, and one with a end event, with 0 or more additional listeners in
371 * between).
372 */
373 private Context mQueryContext;
374
375 private Uri mQueryUri;
376 private CallerInfo mCallerInfo;
377
378 /** Asynchronous query handler class for the contact / callerinfo object. */
379 private CallerInfoAsyncQueryHandler(Context context, Uri contactRef) {
380 super(context.getContentResolver());
381 this.mQueryContext = context;
382 this.mQueryUri = contactRef;
383 }
384
385 @Override
386 public void startQuery(
387 int token,
388 Object cookie,
389 Uri uri,
390 String[] projection,
391 String selection,
392 String[] selectionArgs,
393 String orderBy) {
394 if (DBG) {
395 // Show stack trace with the arguments.
396 Log.d(
397 LOG_TAG,
398 "InCall: startQuery: url="
399 + uri
400 + " projection=["
401 + Arrays.toString(projection)
402 + "]"
403 + " selection="
404 + selection
405 + " "
406 + " args=["
407 + Arrays.toString(selectionArgs)
408 + "]",
409 new RuntimeException("STACKTRACE"));
410 }
411 super.startQuery(token, cookie, uri, projection, selection, selectionArgs, orderBy);
412 }
413
414 @Override
415 protected Handler createHandler(Looper looper) {
416 return new CallerInfoWorkerHandler(looper);
417 }
418
419 /**
420 * Overrides onQueryComplete from AsyncQueryHandler.
421 *
422 * <p>This method takes into account the state of this class; we construct the CallerInfo object
423 * only once for each set of listeners. When the query thread has done its work and calls this
424 * method, we inform the remaining listeners in the queue, until we're out of listeners. Once we
425 * get the message indicating that we should expect no new listeners for this CallerInfo object,
426 * we release the AsyncCursorInfo back into the pool.
427 */
428 @Override
429 protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
430 Log.d(this, "##### onQueryComplete() ##### query complete for token: " + token);
431
432 CookieWrapper cw = (CookieWrapper) cookie;
433
434 if (cw.listener != null) {
435 Log.d(
436 this,
437 "notifying listener: "
438 + cw.listener.getClass().toString()
439 + " for token: "
440 + token
441 + mCallerInfo);
442 cw.listener.onQueryComplete(token, cw.cookie, mCallerInfo);
443 }
444 mQueryContext = null;
445 mQueryUri = null;
446 mCallerInfo = null;
447 }
448
449 protected void updateData(int token, Object cookie, Cursor cursor) {
450 try {
451 Log.d(this, "##### updateData() ##### for token: " + token);
452
453 //get the cookie and notify the listener.
454 CookieWrapper cw = (CookieWrapper) cookie;
455 if (cw == null) {
456 // Normally, this should never be the case for calls originating
457 // from within this code.
458 // However, if there is any code that calls this method, we should
459 // check the parameters to make sure they're viable.
460 Log.d(this, "Cookie is null, ignoring onQueryComplete() request.");
461 return;
462 }
463
464 // check the token and if needed, create the callerinfo object.
465 if (mCallerInfo == null) {
466 if ((mQueryContext == null) || (mQueryUri == null)) {
467 throw new QueryPoolException(
468 "Bad context or query uri, or CallerInfoAsyncQuery already released.");
469 }
470
471 // adjust the callerInfo data as needed, and only if it was set from the
472 // initial query request.
473 // Change the callerInfo number ONLY if it is an emergency number or the
474 // voicemail number, and adjust other data (including photoResource)
475 // accordingly.
476 if (cw.event == EVENT_EMERGENCY_NUMBER) {
477 // Note we're setting the phone number here (refer to javadoc
478 // comments at the top of CallerInfo class).
479 mCallerInfo = new CallerInfo().markAsEmergency(mQueryContext);
480 } else if (cw.event == EVENT_VOICEMAIL_NUMBER) {
481 mCallerInfo = new CallerInfo().markAsVoiceMail(mQueryContext);
482 } else {
483 mCallerInfo = CallerInfo.getCallerInfo(mQueryContext, mQueryUri, cursor);
484 Log.d(this, "==> Got mCallerInfo: " + mCallerInfo);
485
486 CallerInfo newCallerInfo =
487 CallerInfo.doSecondaryLookupIfNecessary(mQueryContext, cw.number, mCallerInfo);
488 if (newCallerInfo != mCallerInfo) {
489 mCallerInfo = newCallerInfo;
490 Log.d(this, "#####async contact look up with numeric username" + mCallerInfo);
491 }
492
493 // Final step: look up the geocoded description.
494 if (ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION) {
495 // Note we do this only if we *don't* have a valid name (i.e. if
496 // no contacts matched the phone number of the incoming call),
497 // since that's the only case where the incoming-call UI cares
498 // about this field.
499 //
500 // (TODO: But if we ever want the UI to show the geoDescription
501 // even when we *do* match a contact, we'll need to either call
502 // updateGeoDescription() unconditionally here, or possibly add a
503 // new parameter to CallerInfoAsyncQuery.startQuery() to force
504 // the geoDescription field to be populated.)
505
506 if (TextUtils.isEmpty(mCallerInfo.name)) {
507 // Actually when no contacts match the incoming phone number,
508 // the CallerInfo object is totally blank here (i.e. no name
509 // *or* phoneNumber). So we need to pass in cw.number as
510 // a fallback number.
511 mCallerInfo.updateGeoDescription(mQueryContext, cw.number);
512 }
513 }
514
515 // Use the number entered by the user for display.
516 if (!TextUtils.isEmpty(cw.number)) {
517 mCallerInfo.phoneNumber = cw.number;
518 }
519 }
520
521 Log.d(this, "constructing CallerInfo object for token: " + token);
522
523 if (cw.listener != null) {
524 cw.listener.onDataLoaded(token, cw.cookie, mCallerInfo);
525 }
526 }
527
528 } finally {
529 // The cursor may have been closed in CallerInfo.getCallerInfo()
530 if (cursor != null && !cursor.isClosed()) {
531 cursor.close();
532 }
533 }
534 }
535
536 /**
537 * Our own query worker thread.
538 *
539 * <p>This thread handles the messages enqueued in the looper. The normal sequence of events is
540 * that a new query shows up in the looper queue, followed by 0 or more add listener requests,
541 * and then an end request. Of course, these requests can be interlaced with requests from other
542 * tokens, but is irrelevant to this handler since the handler has no state.
543 *
544 * <p>Note that we depend on the queue to keep things in order; in other words, the looper queue
545 * must be FIFO with respect to input from the synchronous startQuery calls and output to this
546 * handleMessage call.
547 *
548 * <p>This use of the queue is required because CallerInfo objects may be accessed multiple
549 * times before the query is complete. All accesses (listeners) must be queued up and informed
550 * in order when the query is complete.
551 */
552 protected class CallerInfoWorkerHandler extends WorkerHandler {
553
554 public CallerInfoWorkerHandler(Looper looper) {
555 super(looper);
556 }
557
558 @Override
559 public void handleMessage(Message msg) {
560 WorkerArgs args = (WorkerArgs) msg.obj;
561 CookieWrapper cw = (CookieWrapper) args.cookie;
562
563 if (cw == null) {
564 // Normally, this should never be the case for calls originating
565 // from within this code.
566 // However, if there is any code that this Handler calls (such as in
567 // super.handleMessage) that DOES place unexpected messages on the
568 // queue, then we need pass these messages on.
569 Log.d(
570 this,
571 "Unexpected command (CookieWrapper is null): "
572 + msg.what
573 + " ignored by CallerInfoWorkerHandler, passing onto parent.");
574
575 super.handleMessage(msg);
576 } else {
577 Log.d(
578 this,
579 "Processing event: "
580 + cw.event
581 + " token (arg1): "
582 + msg.arg1
583 + " command: "
584 + msg.what
585 + " query URI: "
586 + sanitizeUriToString(args.uri));
587
588 switch (cw.event) {
589 case EVENT_NEW_QUERY:
590 final ContentResolver resolver = mQueryContext.getContentResolver();
591
592 // This should never happen.
593 if (resolver == null) {
594 Log.e(this, "Content Resolver is null!");
595 return;
596 }
597 //start the sql command.
598 Cursor cursor;
599 try {
600 cursor =
601 resolver.query(
602 args.uri,
603 args.projection,
604 args.selection,
605 args.selectionArgs,
606 args.orderBy);
607 // Calling getCount() causes the cursor window to be filled,
608 // which will make the first access on the main thread a lot faster.
609 if (cursor != null) {
610 cursor.getCount();
611 }
612 } catch (Exception e) {
613 Log.e(this, "Exception thrown during handling EVENT_ARG_QUERY", e);
614 cursor = null;
615 }
616
617 args.result = cursor;
618 updateData(msg.arg1, cw, cursor);
619 break;
620
621 // shortcuts to avoid query for recognized numbers.
622 case EVENT_EMERGENCY_NUMBER:
623 case EVENT_VOICEMAIL_NUMBER:
624 case EVENT_ADD_LISTENER:
625 updateData(msg.arg1, cw, (Cursor) args.result);
626 break;
627 default:
628 }
629 Message reply = args.handler.obtainMessage(msg.what);
630 reply.obj = args;
631 reply.arg1 = msg.arg1;
632
633 reply.sendToTarget();
634 }
635 }
636 }
637 }
638}