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