1 /*
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 
17 package android.telecom;
18 
19 import android.app.ActivityManager;
20 import android.content.AsyncQueryHandler;
21 import android.content.ContentResolver;
22 import android.content.Context;
23 import android.content.pm.PackageManager.NameNotFoundException;
24 import android.database.Cursor;
25 import android.database.SQLException;
26 import android.net.Uri;
27 import android.os.Handler;
28 import android.os.Looper;
29 import android.os.Message;
30 import android.os.SystemClock;
31 import android.os.UserHandle;
32 import android.os.UserManager;
33 import android.provider.ContactsContract.PhoneLookup;
34 import android.telephony.PhoneNumberUtils;
35 import android.telephony.SubscriptionManager;
36 import android.text.TextUtils;
37 import java.util.ArrayList;
38 import java.util.List;
39 
40 /**
41  * Helper class to make it easier to run asynchronous caller-id lookup queries.
42  * @see CallerInfo
43  *
44  * {@hide}
45  */
46 public class CallerInfoAsyncQuery {
47     private static final boolean DBG = false;
48     private static final String LOG_TAG = "CallerInfoAsyncQuery";
49 
50     private static final int EVENT_NEW_QUERY = 1;
51     private static final int EVENT_ADD_LISTENER = 2;
52     private static final int EVENT_END_OF_QUEUE = 3;
53     private static final int EVENT_EMERGENCY_NUMBER = 4;
54     private static final int EVENT_VOICEMAIL_NUMBER = 5;
55     private static final int EVENT_GET_GEO_DESCRIPTION = 6;
56 
57     private CallerInfoAsyncQueryHandler mHandler;
58 
59     // If the CallerInfo query finds no contacts, should we use the
60     // PhoneNumberOfflineGeocoder to look up a "geo description"?
61     // (TODO: This could become a flag in config.xml if it ever needs to be
62     // configured on a per-product basis.)
63     private static final boolean ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION = true;
64 
65     /**
66      * Interface for a CallerInfoAsyncQueryHandler result return.
67      */
68     public interface OnQueryCompleteListener {
69         /**
70          * Called when the query is complete.
71          */
onQueryComplete(int token, Object cookie, CallerInfo ci)72         public void onQueryComplete(int token, Object cookie, CallerInfo ci);
73     }
74 
75 
76     /**
77      * Wrap the cookie from the WorkerArgs with additional information needed by our
78      * classes.
79      */
80     private static final class CookieWrapper {
81         public OnQueryCompleteListener listener;
82         public Object cookie;
83         public int event;
84         public String number;
85         public String geoDescription;
86 
87         public int subId;
88     }
89 
90 
91     /**
92      * Simple exception used to communicate problems with the query pool.
93      */
94     public static class QueryPoolException extends SQLException {
QueryPoolException(String error)95         public QueryPoolException(String error) {
96             super(error);
97         }
98     }
99 
100     /**
101      * @return {@link ContentResolver} for the "current" user.
102      */
getCurrentProfileContentResolver(Context context)103     static ContentResolver getCurrentProfileContentResolver(Context context) {
104 
105         if (DBG) Log.d(LOG_TAG, "Trying to get current content resolver...");
106 
107         final int currentUser = ActivityManager.getCurrentUser();
108         final int myUser = UserManager.get(context).getUserHandle();
109 
110         if (DBG) Log.d(LOG_TAG, "myUser=" + myUser + "currentUser=" + currentUser);
111 
112         if (myUser != currentUser) {
113             final Context otherContext;
114             try {
115                 otherContext = context.createPackageContextAsUser(context.getPackageName(),
116                         /* flags =*/ 0, UserHandle.of(currentUser));
117                 return otherContext.getContentResolver();
118             } catch (NameNotFoundException e) {
119                 Log.e(LOG_TAG, e, "Can't find self package");
120                 // Fall back to the primary user.
121             }
122         }
123         return context.getContentResolver();
124     }
125 
126     /**
127      * Our own implementation of the AsyncQueryHandler.
128      */
129     private class CallerInfoAsyncQueryHandler extends AsyncQueryHandler {
130 
131         /*
132          * The information relevant to each CallerInfo query.  Each query may have multiple
133          * listeners, so each AsyncCursorInfo is associated with 2 or more CookieWrapper
134          * objects in the queue (one with a new query event, and one with a end event, with
135          * 0 or more additional listeners in between).
136          */
137 
138         /**
139          * Context passed by the caller.
140          *
141          * NOTE: The actual context we use for query may *not* be this context; since we query
142          * against the "current" contacts provider.  In the constructor we pass the "current"
143          * context resolver (obtained via {@link #getCurrentProfileContentResolver) and pass it
144          * to the super class.
145          */
146         private Context mContext;
147         private Uri mQueryUri;
148         private CallerInfo mCallerInfo;
149         private List<Runnable> mPendingListenerCallbacks = new ArrayList<>();
150 
151         /**
152          * Our own query worker thread.
153          *
154          * This thread handles the messages enqueued in the looper.  The normal sequence
155          * of events is that a new query shows up in the looper queue, followed by 0 or
156          * more add listener requests, and then an end request.  Of course, these requests
157          * can be interlaced with requests from other tokens, but is irrelevant to this
158          * handler since the handler has no state.
159          *
160          * Note that we depend on the queue to keep things in order; in other words, the
161          * looper queue must be FIFO with respect to input from the synchronous startQuery
162          * calls and output to this handleMessage call.
163          *
164          * This use of the queue is required because CallerInfo objects may be accessed
165          * multiple times before the query is complete.  All accesses (listeners) must be
166          * queued up and informed in order when the query is complete.
167          */
168         protected class CallerInfoWorkerHandler extends WorkerHandler {
CallerInfoWorkerHandler(Looper looper)169             public CallerInfoWorkerHandler(Looper looper) {
170                 super(looper);
171             }
172 
173             @Override
handleMessage(Message msg)174             public void handleMessage(Message msg) {
175                 WorkerArgs args = (WorkerArgs) msg.obj;
176                 CookieWrapper cw = (CookieWrapper) args.cookie;
177 
178                 if (cw == null) {
179                     // Normally, this should never be the case for calls originating
180                     // from within this code.
181                     // However, if there is any code that this Handler calls (such as in
182                     // super.handleMessage) that DOES place unexpected messages on the
183                     // queue, then we need pass these messages on.
184                     Log.i(LOG_TAG, "Unexpected command (CookieWrapper is null): " + msg.what +
185                             " ignored by CallerInfoWorkerHandler, passing onto parent.");
186 
187                     super.handleMessage(msg);
188                 } else {
189 
190                     Log.d(LOG_TAG, "Processing event: " + cw.event + " token (arg1): " + msg.arg1 +
191                         " command: " + msg.what + " query URI: " + sanitizeUriToString(args.uri));
192 
193                     switch (cw.event) {
194                         case EVENT_NEW_QUERY:
195                             //start the sql command.
196                             super.handleMessage(msg);
197                             break;
198 
199                         // shortcuts to avoid query for recognized numbers.
200                         case EVENT_EMERGENCY_NUMBER:
201                         case EVENT_VOICEMAIL_NUMBER:
202 
203                         case EVENT_ADD_LISTENER:
204                         case EVENT_END_OF_QUEUE:
205                             // query was already completed, so just send the reply.
206                             // passing the original token value back to the caller
207                             // on top of the event values in arg1.
208                             Message reply = args.handler.obtainMessage(msg.what);
209                             reply.obj = args;
210                             reply.arg1 = msg.arg1;
211 
212                             reply.sendToTarget();
213 
214                             break;
215                         case EVENT_GET_GEO_DESCRIPTION:
216                             handleGeoDescription(msg);
217                             break;
218                         default:
219                     }
220                 }
221             }
222 
handleGeoDescription(Message msg)223             private void handleGeoDescription(Message msg) {
224                 WorkerArgs args = (WorkerArgs) msg.obj;
225                 CookieWrapper cw = (CookieWrapper) args.cookie;
226                 if (!TextUtils.isEmpty(cw.number) && cw.cookie != null && mContext != null) {
227                     final long startTimeMillis = SystemClock.elapsedRealtime();
228                     cw.geoDescription = CallerInfo.getGeoDescription(mContext, cw.number);
229                     final long duration = SystemClock.elapsedRealtime() - startTimeMillis;
230                     if (duration > 500) {
231                         if (DBG) Log.d(LOG_TAG, "[handleGeoDescription]" +
232                                 "Spends long time to retrieve Geo description: " + duration);
233                     }
234                 }
235                 Message reply = args.handler.obtainMessage(msg.what);
236                 reply.obj = args;
237                 reply.arg1 = msg.arg1;
238                 reply.sendToTarget();
239             }
240         }
241 
242 
243         /**
244          * Asynchronous query handler class for the contact / callerinfo object.
245          */
CallerInfoAsyncQueryHandler(Context context)246         private CallerInfoAsyncQueryHandler(Context context) {
247             super(getCurrentProfileContentResolver(context));
248             mContext = context;
249         }
250 
251         @Override
createHandler(Looper looper)252         protected Handler createHandler(Looper looper) {
253             return new CallerInfoWorkerHandler(looper);
254         }
255 
256         /**
257          * Overrides onQueryComplete from AsyncQueryHandler.
258          *
259          * This method takes into account the state of this class; we construct the CallerInfo
260          * object only once for each set of listeners. When the query thread has done its work
261          * and calls this method, we inform the remaining listeners in the queue, until we're
262          * out of listeners.  Once we get the message indicating that we should expect no new
263          * listeners for this CallerInfo object, we release the AsyncCursorInfo back into the
264          * pool.
265          */
266         @Override
onQueryComplete(int token, Object cookie, Cursor cursor)267         protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
268             Log.d(LOG_TAG, "##### onQueryComplete() #####   query complete for token: " + token);
269 
270             //get the cookie and notify the listener.
271             CookieWrapper cw = (CookieWrapper) cookie;
272             if (cw == null) {
273                 // Normally, this should never be the case for calls originating
274                 // from within this code.
275                 // However, if there is any code that calls this method, we should
276                 // check the parameters to make sure they're viable.
277                 Log.i(LOG_TAG, "Cookie is null, ignoring onQueryComplete() request.");
278                 if (cursor != null) {
279                     cursor.close();
280                 }
281                 return;
282             }
283 
284             if (cw.event == EVENT_END_OF_QUEUE) {
285                 for (Runnable r : mPendingListenerCallbacks) {
286                     r.run();
287                 }
288                 mPendingListenerCallbacks.clear();
289 
290                 release();
291                 if (cursor != null) {
292                     cursor.close();
293                 }
294                 return;
295             }
296 
297             // If the cw.event == EVENT_GET_GEO_DESCRIPTION, means it would not be the 1st
298             // time entering the onQueryComplete(), mCallerInfo should not be null.
299             if (cw.event == EVENT_GET_GEO_DESCRIPTION) {
300                 if (mCallerInfo != null) {
301                     mCallerInfo.geoDescription = cw.geoDescription;
302                 }
303                 // notify that we can clean up the queue after this.
304                 CookieWrapper endMarker = new CookieWrapper();
305                 endMarker.event = EVENT_END_OF_QUEUE;
306                 startQuery(token, endMarker, null, null, null, null, null);
307             }
308 
309             // check the token and if needed, create the callerinfo object.
310             if (mCallerInfo == null) {
311                 if ((mContext == null) || (mQueryUri == null)) {
312                     throw new QueryPoolException
313                             ("Bad context or query uri, or CallerInfoAsyncQuery already released.");
314                 }
315 
316                 // adjust the callerInfo data as needed, and only if it was set from the
317                 // initial query request.
318                 // Change the callerInfo number ONLY if it is an emergency number or the
319                 // voicemail number, and adjust other data (including photoResource)
320                 // accordingly.
321                 if (cw.event == EVENT_EMERGENCY_NUMBER) {
322                     // Note we're setting the phone number here (refer to javadoc
323                     // comments at the top of CallerInfo class).
324                     mCallerInfo = new CallerInfo().markAsEmergency(mContext);
325                 } else if (cw.event == EVENT_VOICEMAIL_NUMBER) {
326                     mCallerInfo = new CallerInfo().markAsVoiceMail(mContext, cw.subId);
327                 } else {
328                     mCallerInfo = CallerInfo.getCallerInfo(mContext, mQueryUri, cursor);
329                     if (DBG) Log.d(LOG_TAG, "==> Got mCallerInfo: " + mCallerInfo);
330 
331                     CallerInfo newCallerInfo = CallerInfo.doSecondaryLookupIfNecessary(
332                             mContext, cw.number, mCallerInfo);
333                     if (newCallerInfo != mCallerInfo) {
334                         mCallerInfo = newCallerInfo;
335                         if (DBG) Log.d(LOG_TAG, "#####async contact look up with numeric username"
336                                 + mCallerInfo);
337                     }
338 
339                     // Use the number entered by the user for display.
340                     if (!TextUtils.isEmpty(cw.number)) {
341                         mCallerInfo.setPhoneNumber(PhoneNumberUtils.formatNumber(cw.number,
342                                 mCallerInfo.normalizedNumber,
343                                 CallerInfo.getCurrentCountryIso(mContext)));
344                     }
345 
346                     // This condition refer to the google default code for geo.
347                     // If the number exists in Contacts, the CallCard would never show
348                     // the geo description, so it would be unnecessary to query it.
349                     if (ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION) {
350                         if (TextUtils.isEmpty(mCallerInfo.getName())) {
351                             if (DBG) Log.d(LOG_TAG, "start querying geo description");
352                             cw.event = EVENT_GET_GEO_DESCRIPTION;
353                             startQuery(token, cw, null, null, null, null, null);
354                             return;
355                         }
356                     }
357                 }
358 
359                 if (DBG) Log.d(LOG_TAG, "constructing CallerInfo object for token: " + token);
360 
361                 //notify that we can clean up the queue after this.
362                 CookieWrapper endMarker = new CookieWrapper();
363                 endMarker.event = EVENT_END_OF_QUEUE;
364                 startQuery(token, endMarker, null, null, null, null, null);
365             }
366 
367             //notify the listener that the query is complete.
368             if (cw.listener != null) {
369                 mPendingListenerCallbacks.add(new Runnable() {
370                     @Override
371                     public void run() {
372                         if (DBG) Log.d(LOG_TAG, "notifying listener: "
373                                 + cw.listener.getClass().toString() + " for token: " + token
374                                 + mCallerInfo);
375                         cw.listener.onQueryComplete(token, cw.cookie, mCallerInfo);
376                     }
377                 });
378             } else {
379                 Log.w(LOG_TAG, "There is no listener to notify for this query.");
380             }
381 
382             if (cursor != null) {
383                cursor.close();
384             }
385         }
386     }
387 
388     /**
389      * Private constructor for factory methods.
390      */
CallerInfoAsyncQuery()391     private CallerInfoAsyncQuery() {
392     }
393 
394 
395     /**
396      * Factory method to start query with a Uri query spec
397      */
startQuery(int token, Context context, Uri contactRef, OnQueryCompleteListener listener, Object cookie)398     public static CallerInfoAsyncQuery startQuery(int token, Context context, Uri contactRef,
399             OnQueryCompleteListener listener, Object cookie) {
400 
401         CallerInfoAsyncQuery c = new CallerInfoAsyncQuery();
402         c.allocate(context, contactRef);
403 
404         if (DBG) Log.d(LOG_TAG, "starting query for URI: " + contactRef + " handler: " + c.toString());
405 
406         //create cookieWrapper, start query
407         CookieWrapper cw = new CookieWrapper();
408         cw.listener = listener;
409         cw.cookie = cookie;
410         cw.event = EVENT_NEW_QUERY;
411 
412         c.mHandler.startQuery(token, cw, contactRef, null, null, null, null);
413 
414         return c;
415     }
416 
417     /**
418      * Factory method to start the query based on a number.
419      *
420      * Note: if the number contains an "@" character we treat it
421      * as a SIP address, and look it up directly in the Data table
422      * rather than using the PhoneLookup table.
423      * TODO: But eventually we should expose two separate methods, one for
424      * numbers and one for SIP addresses, and then have
425      * PhoneUtils.startGetCallerInfo() decide which one to call based on
426      * the phone type of the incoming connection.
427      */
startQuery(int token, Context context, String number, OnQueryCompleteListener listener, Object cookie)428     public static CallerInfoAsyncQuery startQuery(int token, Context context, String number,
429             OnQueryCompleteListener listener, Object cookie) {
430 
431         int subId = SubscriptionManager.getDefaultSubscriptionId();
432         return startQuery(token, context, number, listener, cookie, subId);
433     }
434 
435     /**
436      * Factory method to start the query based on a number with specific subscription.
437      *
438      * Note: if the number contains an "@" character we treat it
439      * as a SIP address, and look it up directly in the Data table
440      * rather than using the PhoneLookup table.
441      * TODO: But eventually we should expose two separate methods, one for
442      * numbers and one for SIP addresses, and then have
443      * PhoneUtils.startGetCallerInfo() decide which one to call based on
444      * the phone type of the incoming connection.
445      */
startQuery(int token, Context context, String number, OnQueryCompleteListener listener, Object cookie, int subId)446     public static CallerInfoAsyncQuery startQuery(int token, Context context, String number,
447             OnQueryCompleteListener listener, Object cookie, int subId) {
448 
449         if (DBG) {
450             Log.d(LOG_TAG, "##### CallerInfoAsyncQuery startQuery()... #####");
451             Log.d(LOG_TAG, "- number: " + /*number*/ "xxxxxxx");
452             Log.d(LOG_TAG, "- cookie: " + cookie);
453         }
454 
455         // Construct the URI object and query params, and start the query.
456 
457         final Uri contactRef = PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI.buildUpon()
458                 .appendPath(number)
459                 .appendQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS,
460                         String.valueOf(PhoneNumberUtils.isUriNumber(number)))
461                 .build();
462 
463         if (DBG) {
464             Log.d(LOG_TAG, "==> contactRef: " + sanitizeUriToString(contactRef));
465         }
466 
467         CallerInfoAsyncQuery c = new CallerInfoAsyncQuery();
468         c.allocate(context, contactRef);
469 
470         //create cookieWrapper, start query
471         CookieWrapper cw = new CookieWrapper();
472         cw.listener = listener;
473         cw.cookie = cookie;
474         cw.number = number;
475         cw.subId = subId;
476 
477         // check to see if these are recognized numbers, and use shortcuts if we can.
478         if (PhoneNumberUtils.isLocalEmergencyNumber(context, number)) {
479             cw.event = EVENT_EMERGENCY_NUMBER;
480         } else if (PhoneNumberUtils.isVoiceMailNumber(context, subId, number)) {
481             cw.event = EVENT_VOICEMAIL_NUMBER;
482         } else {
483             cw.event = EVENT_NEW_QUERY;
484         }
485 
486         c.mHandler.startQuery(token,
487                               cw,  // cookie
488                               contactRef,  // uri
489                               null,  // projection
490                               null,  // selection
491                               null,  // selectionArgs
492                               null);  // orderBy
493         return c;
494     }
495 
496     /**
497      * Method to add listeners to a currently running query
498      */
addQueryListener(int token, OnQueryCompleteListener listener, Object cookie)499     public void addQueryListener(int token, OnQueryCompleteListener listener, Object cookie) {
500 
501         if (DBG) Log.d(LOG_TAG, "adding listener to query: "
502                 + sanitizeUriToString(mHandler.mQueryUri) + " handler: " + mHandler.toString());
503 
504         //create cookieWrapper, add query request to end of queue.
505         CookieWrapper cw = new CookieWrapper();
506         cw.listener = listener;
507         cw.cookie = cookie;
508         cw.event = EVENT_ADD_LISTENER;
509 
510         mHandler.startQuery(token, cw, null, null, null, null, null);
511     }
512 
513     /**
514      * Method to create a new CallerInfoAsyncQueryHandler object, ensuring correct
515      * state of context and uri.
516      */
allocate(Context context, Uri contactRef)517     private void allocate(Context context, Uri contactRef) {
518         if ((context == null) || (contactRef == null)){
519             throw new QueryPoolException("Bad context or query uri.");
520         }
521         mHandler = new CallerInfoAsyncQueryHandler(context);
522         mHandler.mQueryUri = contactRef;
523     }
524 
525     /**
526      * Releases the relevant data.
527      */
release()528     private void release() {
529         mHandler.mContext = null;
530         mHandler.mQueryUri = null;
531         mHandler.mCallerInfo = null;
532         mHandler = null;
533     }
534 
sanitizeUriToString(Uri uri)535     private static String sanitizeUriToString(Uri uri) {
536         if (uri != null) {
537             String uriString = uri.toString();
538             int indexOfLastSlash = uriString.lastIndexOf('/');
539             if (indexOfLastSlash > 0) {
540                 return uriString.substring(0, indexOfLastSlash) + "/xxxxxxx";
541             } else {
542                 return uriString;
543             }
544         } else {
545             return "";
546         }
547     }
548 }
549