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