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