summaryrefslogtreecommitdiffstats
path: root/src/com/cyanogenmod/messaging/lookup/LookupProviderManager.java
blob: a5a6e495c7263ec91b2e47676ff2648f614b6c2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/*
* Copyright (C) 2015 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cyanogenmod.messaging.lookup;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;

import com.cyanogen.lookup.phonenumber.contract.LookupProvider;
import com.cyanogen.lookup.phonenumber.provider.LookupProviderImpl;
import com.cyanogen.lookup.phonenumber.response.StatusCode;
import com.cyanogen.lookup.phonenumber.util.LookupHandlerThread;
import com.cyanogen.lookup.phonenumber.request.LookupRequest;
import com.cyanogen.lookup.phonenumber.response.LookupResponse;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <pre>
 *      Class intended for handling communication and interaction between the lookup provider and
 *      the application
 * </pre>
 *
 * @see {@link Application.ActivityLifecycleCallbacks}
 * @see {@link LookupRequest.Callback}
 * @see {@link ILookupClient}
 */
public class LookupProviderManager extends BroadcastReceiver implements Application
        .ActivityLifecycleCallbacks, LookupRequest.Callback, ILookupClient {

    private static final String TAG = "LookupProviderManager";
    private static final String THREAD_NAME = "PhoneLookupProviderThread";

    // Members
    private static final Handler sHandler = new Handler(Looper.getMainLooper());
    private static final LinkedHashMap<String, Bitmap> sAttributionLogoBitmapCache = new
            LinkedHashMap<>(1);
    private Application mApplication;
    private ConcurrentHashMap<String, LookupResponse> mPhoneNumberLookupCache;
    private ConcurrentHashMap<String, HashSet<LookupProviderListener>> mLookupListeners;
    private LookupHandlerThread mLookupHandlerThread;
    private boolean mIsPhoneNumberLookupInitialized;
    private short mActivityCount = 0;
    private short mServiceCount = 0;

    public static final String ACTION_CREATED = "service_created";
    public static final String ACTION_DESTROYED = "service_destroyed";

    public LookupProviderManager() {
    }

    /**
     * Constructor
     *
     * @param application {@link Application}
     */
    public LookupProviderManager(Application application) {
        log("LookupProviderManager(" + application + ")");
        if (application == null) {
            throw new IllegalArgumentException("'application' must not be null!");
        }
        mPhoneNumberLookupCache = new ConcurrentHashMap<String, LookupResponse>();
        mLookupListeners = new ConcurrentHashMap<String, HashSet<LookupProviderListener>>();
        application.registerActivityLifecycleCallbacks(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_CREATED);
        filter.addAction(ACTION_DESTROYED);
        application.registerReceiver(this, filter);
        mApplication = application;
    }

    private boolean isDebug() {
        return Log.isLoggable(TAG, Log.DEBUG);
    }

    private void log(String str) {
        if (isDebug()) {
            Log.d(TAG, "::" + str);
        }
    }

    private boolean start() {
        log("start()");
        if (mLookupHandlerThread == null) {
            LookupProvider lookupProvider = LookupProviderImpl.INSTANCE.get(mApplication);
            if (lookupProvider.isEnabled()) {
                mLookupHandlerThread = new LookupHandlerThread(THREAD_NAME, mApplication,
                        lookupProvider);
                mLookupHandlerThread.initialize();

            }
        }
        return mLookupHandlerThread != null;
    }

    private void stop() {
        log("stop()");
        if (mLookupHandlerThread != null) {
            mLookupHandlerThread.tearDown();
            mLookupHandlerThread = null;
        }
        mPhoneNumberLookupCache.clear();
        mLookupListeners.clear();
        for (Bitmap bitmap : sAttributionLogoBitmapCache.values()) {
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }
        sAttributionLogoBitmapCache.clear();
    }

    /**
     * Registration mechanism for anyone interested in new contact info being available from an
     * external provider.  The updates aren't granular as of now - you will be notified of
     * updates to all contact info request
     *
     * @param number {@link String}
     * @param listener {@link LookupProviderListener}
     */
    public void addLookupProviderListener(String number, LookupProviderListener listener) {
        log("addLookupProviderListener(" + number + ", " + listener + ")");
        if (TextUtils.isEmpty(number) || listener == null) {
            return;
        }
        if (!mLookupListeners.contains(number)) {
            mLookupListeners.put(number, new HashSet<LookupProviderListener>());
        }
        if (!mLookupListeners.get(number).contains(listener)) { // prevent adding same listener
            mLookupListeners.get(number).add(listener);
        }
    }

    /**
     * Stop getting updates about newly added contact info
     *
     * @param number {@link String}
     * @param listener {@link LookupProviderListener}
     */
    public void removeLookupProviderListener(String number, LookupProviderListener listener) {
        log("removeLookupProviderListener(" + number + ", " + listener + ")");
        if (TextUtils.isEmpty(number)) {
            return;
        }
        if (mLookupListeners.containsKey(number)) {
            mLookupListeners.get(number).remove(listener);
        }
    }

    public void onLowMemory() {
        log("onLowMemory()");
        mPhoneNumberLookupCache.clear();
    }

    /* ---------------------  LookupRequest callback interfaces  --------------------------------*/
    @Override
    public void onNewInfo(LookupRequest lookupRequest, final LookupResponse response) {
        log("onNewInfo(" + lookupRequest + ", " + response + ")");
        mPhoneNumberLookupCache.put(lookupRequest.mPhoneNumber, response);
        // Cache the attribution logo as a bitmap since needed by widget's remoteviews
        if (!sAttributionLogoBitmapCache.containsKey(response.mProviderName)) {
            Bitmap bitmap = Bitmap.createBitmap(response.mAttributionLogo
                    .getIntrinsicWidth(), response.mAttributionLogo
                    .getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(bitmap);
            response.mAttributionLogo
                    .setBounds(0, 0, c.getWidth(), c.getHeight());
            response.mAttributionLogo.draw(c);
            sAttributionLogoBitmapCache.put(response.mProviderName, bitmap);
        }
        if (mLookupListeners.containsKey(lookupRequest.mPhoneNumber)) {
            int i = 0;
            List<Integer> removalIndexes = new ArrayList<Integer>();
            for (final LookupProviderListener listener : mLookupListeners.get(lookupRequest
                    .mPhoneNumber)) {
                if (listener == null) {
                    removalIndexes.add(i);
                }
                sHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (listener != null) {
                            listener.onNewInfoAvailable(response);
                        }
                    }
                });
                i++;
            }
            for (int index : removalIndexes) {
                mLookupListeners.get(lookupRequest.mPhoneNumber).remove(index);
            }
        }
    }

    /* ---------------------  Private level service count methods -------------------------------*/

    private void onServiceCreated() {
        ++mServiceCount;
        if (mServiceCount == 1) {
            if (!mIsPhoneNumberLookupInitialized) {
                mIsPhoneNumberLookupInitialized = start();
            }
        }
    }

    private void onServiceDestroyed() {
        --mServiceCount;
        if (mServiceCount == 0 && mActivityCount == 0) {
            if (mIsPhoneNumberLookupInitialized) {
                stop();
                mIsPhoneNumberLookupInitialized = false;
            }
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_CREATED.equalsIgnoreCase(action)) {
            onServiceCreated();
        } else if (ACTION_DESTROYED.equalsIgnoreCase(action)) {
            onServiceDestroyed();
        }
    }

    /* ---------------------  Activity callback interfaces  -------------------------------------*/
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        log("onActivityCreated(" + activity + ", " + savedInstanceState + ")");
        ++mActivityCount;
        if (mActivityCount == 1) {
            if (!mIsPhoneNumberLookupInitialized) {
                mIsPhoneNumberLookupInitialized = start();
            }
        }
    }

    /* ---------------------  Lookup Client interfaces  -----------------------------------------*/
    @Override
    public void onActivityStarted(Activity activity) {}

    @Override
    public void onActivityResumed(Activity activity) {}

    @Override
    public void onActivityPaused(Activity activity) {}

    @Override
    public void onActivityStopped(Activity activity) {}

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

    @Override
    public void onActivityDestroyed(Activity activity) {
        log("onActivityCreated(" + activity + ")");
        --mActivityCount;
        if (mActivityCount == 0 && mServiceCount == 0) {
            if (mIsPhoneNumberLookupInitialized) {
                stop();
                mIsPhoneNumberLookupInitialized = false;
            }
        }
    }

    @Override
    public LookupResponse blockingLookupInfoForPhoneNumber(String phoneNumber) {
        LookupResponse response = null;
        if (mLookupHandlerThread != null) {
            response = mLookupHandlerThread.blockingFetchInfoForPhoneNumber(new
                    LookupRequest(phoneNumber, this));
            if (response != null && response.mStatusCode != StatusCode.SUCCESS) {
                response = null;
            }
        }
        if (response != null) {
            // Cache the attribution logos as bitmaps since widget needs it
            if (!sAttributionLogoBitmapCache.containsKey(response.mProviderName)) {
                Bitmap bitmap = Bitmap.createBitmap(response.mAttributionLogo
                        .getIntrinsicWidth(), response.mAttributionLogo
                        .getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
                Canvas c = new Canvas(bitmap);
                response.mAttributionLogo
                        .setBounds(0, 0, c.getWidth(), c.getHeight());
                response.mAttributionLogo.draw(c);
                sAttributionLogoBitmapCache.put(response.mProviderName, bitmap);
            }
        }
        return response;
    }

    @Override
    public Bitmap getCachedAttributionLogoBitmap(String providerName) {
        if (!TextUtils.isEmpty(providerName)) {
            return sAttributionLogoBitmapCache.get(providerName);
        }
        return null;
    }

    @Override
    public void lookupInfoForPhoneNumber(String phoneNumber) {
        log("lookupInfoForPhoneNumber(" + phoneNumber + ")");
        lookupInfoForPhoneNumber(phoneNumber, false);
    }

    /**
     * @param phoneNumber {@link String} not null or empty and should be formatted to E164 already!
     * @param requery {@link Boolean}
     *
     * In the messaging app we store a normalized version of the number and are using this to call
     * this method.  If you call PhoneNumberUtils.formatNumberToE164 with an already formatted
     * number, it returns null.  So we just use the number and expect it to be formatted.
     */
    @Override
    public void lookupInfoForPhoneNumber(String phoneNumber, boolean requery) {
        log("lookupInfoForPhoneNumber(" + phoneNumber + ", " + requery + ")");

        if (TextUtils.isEmpty(phoneNumber)) {
            return;
        }

        // If we have already fetched it before
        if (mPhoneNumberLookupCache.containsKey(phoneNumber)) {
            // Short circuit and call callback
            if (mLookupListeners.containsKey(phoneNumber)) {
                for (LookupProviderListener listener : mLookupListeners.get(phoneNumber)) {
                    listener.onNewInfoAvailable(mPhoneNumberLookupCache.get(phoneNumber));
                }
            }
            return;
        }

        if (mIsPhoneNumberLookupInitialized) {
            LookupRequest request = new LookupRequest(phoneNumber, this,
                    LookupRequest.RequestOrigin.SMS);
            // [TODO][MSB]: Could pass up the return of this
            mLookupHandlerThread.fetchInfoForPhoneNumber(request);
        }

    }

    @Override
    public void markAsSpam(String phoneNumber) {
        log("markAsSpam(" + phoneNumber + ")");
        if (TextUtils.isEmpty(phoneNumber)) {
            throw new IllegalArgumentException("'phoneNumber' cannot be null!");
        }
        phoneNumber = PhoneNumberUtils.formatNumberToE164(phoneNumber,
                mApplication.getResources().getConfiguration().locale.getISO3Country());
        markAsSpamInternal(phoneNumber);
    }

    private void markAsSpamInternal(String phoneNumber) {
        log("markAsSpamInternal(" + phoneNumber + ")");
        if (TextUtils.isEmpty(phoneNumber)) {
            throw new IllegalArgumentException("'phoneNumber' cannot be null!");
        }
        if (mIsPhoneNumberLookupInitialized) {
            mLookupHandlerThread.markAsSpam(phoneNumber);
            // Don't remove from cache in case user presses "undo" in snackbar.
        }
    }

    @Override
    public boolean hasSpamReporting() {
        log("hasSpamReporting()");
        return mIsPhoneNumberLookupInitialized && mLookupHandlerThread.isProviderInterestedInSpam();
    }

    @Override
    public String getProviderName() {
        log("getProviderName()");
        if (mIsPhoneNumberLookupInitialized) {
            return mLookupHandlerThread.getProviderName();
        }
        return null;
    }

    /* ---------------------  Interface  --------------------------------------------------------*/
    /**
     * Callback for clients requesting phone number lookups
     */
    public interface LookupProviderListener {
        // generic callback for when new info is available

        /**
         * Tell listener to handle update
         *
         * @param response {@link LookupResponse}
         */
        void onNewInfoAvailable(LookupResponse response);
    }

}