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