summaryrefslogtreecommitdiffstats
path: root/src/com/android/dialer/discovery/DiscoveryEventHandler.java
blob: c73038baf900edb77bf77746c536159cfdfe431e (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
package com.android.dialer.discovery;

import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;

import com.android.dialer.DialtactsActivity;
import com.android.phone.common.ambient.AmbientConnection;
import com.android.phone.common.incall.utils.CallMethodUtils;
import com.android.phone.common.util.ImageUtils;

import com.cyanogen.ambient.common.api.AmbientApiClient;
import com.cyanogen.ambient.discovery.DiscoveryManagerServices;
import com.cyanogen.ambient.discovery.NudgeServices;
import com.cyanogen.ambient.discovery.nudge.NotificationNudge;
import com.cyanogen.ambient.discovery.nudge.Nudge;
import com.cyanogen.ambient.discovery.util.NudgeKey;
import com.cyanogen.ambient.discovery.results.NudgablePluginsResult;
import com.cyanogen.ambient.incall.InCallApi;
import com.cyanogen.ambient.incall.InCallServices;
import com.cyanogen.ambient.incall.results.InCallProviderInfoResult;
import com.cyanogen.ambient.incall.results.PluginStatusResult;
import com.cyanogen.ambient.incall.results.InstalledPluginsResult;

import com.cyanogen.ambient.plugin.PluginStatus;
import com.cyanogen.ambient.common.api.ResultCallback;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  A small, lean, nudge'r. For loading data from mods that can provide nudges.
 *
 *  All Dialer nudge events route through here, and if found worthy, will send a nudge to
 *  the Discovery Nudge Service in ModCore.
 */
public class DiscoveryEventHandler {

    private static final String TAG = "DiscoveryEventHandler";

    private Context mContext;
    private AmbientApiClient mClient;
    private HashMap<String, Bundle> availableNudges = new HashMap<String, Bundle>();
    private List<ComponentName> plugins = new ArrayList<ComponentName>();

    // Key for this instance
    private static String mKey;

    public DiscoveryEventHandler(Context context) {
        mContext = context;
        mClient = AmbientConnection.CLIENT.get(context);
    }

    public void getNudgeProvidersWithKey(final String key) {
        getNudgeProvidersWithKey(key, false);
    }

    /* package */ void getNudgeProvidersWithKey(final String key, final boolean isTesting) {
        mKey = key;
        getAvailableNudgesForKey(key, isTesting);
        getInstalledPlugins();
    }

    private void getAvailableNudgesForKey(final String key, final boolean isTesting) {
        NudgeServices.NudgeApi.getAvailableNudgesForKey(mClient, key)
                .setResultCallback(new ResultCallback<NudgablePluginsResult>() {
                    @Override
                    public void onResult(NudgablePluginsResult plugins) {
                        Map nudgePlugins = plugins.components;
                        if (nudgePlugins == null || nudgePlugins.size() == 0) {
                            return;
                        }

                        for (Object entry : nudgePlugins.entrySet()) {
                            Map.Entry<ComponentName, Bundle> theEntry
                                    = (Map.Entry<ComponentName, Bundle>) entry;

                            Bundle b = theEntry.getValue();

                            // If we are ready to show the nudge, then we will not increment the
                            // count here. Instead the count will be incremented in
                            // DiscoverySignalReceiver when the nudge is properly shown.
                            if (!validateShouldShowNudge(key, b) && !isTesting) {
                                // Nudge not yet ready for this item. increment event count
                                incrementCount(key, mContext);
                                continue;
                            }

                            availableNudges.put(theEntry.getKey().getPackageName(), b);
                        }

                        getStatusWhenReady();
                    }
                });
    }


    /**
     * Get installed plugins
     */
    private void getInstalledPlugins() {
        InCallServices.getInstance().getInstalledPlugins(mClient)
                .setResultCallback(new ResultCallback<InstalledPluginsResult>() {
                    @Override
                    public void onResult(InstalledPluginsResult installedPluginsResult) {
                        plugins = installedPluginsResult.components;

                        if (plugins == null || plugins.size() == 0) {
                            return;
                        }
                        getStatusWhenReady();
                    }
                });
    }

    /**
     * Get our plugin enabled status
     * @param cn
     */
    private void getCallMethodStatus(final ComponentName cn) {
        InCallServices.getInstance().getPluginStatus(mClient, cn)
            .setResultCallback(new ResultCallback<PluginStatusResult>() {
                @Override
                public void onResult(PluginStatusResult pluginStatusResult) {

                    boolean pluginIsApplicable = pluginStatusResult.status != PluginStatus.DISABLED
                            && pluginStatusResult.status != PluginStatus.UNAVAILABLE;

                    if (!pluginIsApplicable) {
                        plugins.remove(cn);
                        return;
                    }

                    getCallMethodIcon(cn);
                }
            });
    }

    private void getCallMethodIcon(final ComponentName cn) {
        InCallServices.getInstance().getProviderInfo(mClient, cn)
                .setResultCallback(new ResultCallback<InCallProviderInfoResult>() {
                    @Override
                    public void onResult(InCallProviderInfoResult providerInfo) {
                        if (providerInfo != null && providerInfo.inCallProviderInfo != null) {
                            try {
                                Resources pluginResources = mContext.getPackageManager()
                                        .getResourcesForApplication(cn.getPackageName());

                                Drawable d = pluginResources.getDrawable(
                                        providerInfo.inCallProviderInfo.getBrandIcon(), null);

                                createNudge(cn, ImageUtils.drawableToBitmap(d));
                            } catch (Resources.NotFoundException e) {
                                Log.e(TAG, "Unable to retrieve icon for plugin: " + cn);
                            } catch (PackageManager.NameNotFoundException e) {
                                Log.e(TAG, "Plugin isn't installed: " + cn);
                            }
                        }
                    }
        });
    }

    private void getStatusWhenReady() {
        if (plugins == null || plugins.size() == 0
                || availableNudges == null || availableNudges.size() == 0) {
            // Not ready or never will be, just bail man.
            return;
        }
        for (ComponentName cn : plugins) {
            if (availableNudges.containsKey(cn.getPackageName())) {
                getCallMethodStatus(cn);
            }
        }
    }

    private void createNudge(ComponentName component, Bitmap notificationIcon) {
        Bundle b = availableNudges.get(component.getPackageName());

        String title = b.getString(NudgeKey.NUDGE_PARAM_TITLE);
        String body = b.getString(NudgeKey.NOTIFICATION_PARAM_BODY);
        Parcelable[] actions = b.getParcelableArray(NudgeKey.NOTIFICATION_PARAM_NUDGE_ACTIONS);

        NotificationNudge nn = new NotificationNudge(mKey,
                Nudge.Type.IMMEDIATE, title, body);

        for (Parcelable action : actions) {
            NotificationNudge.Button button = (NotificationNudge.Button) action;
            nn.addButton(button);
        }

        nn.setLargeIcon(notificationIcon);
        nn.setOnShowIntent(buildActionIntent(body,
                DiscoverySignalReceiver.DISCOVERY_NUDGE_SHOWN, component));
        nn.setContentIntent(buildActionIntent(body,
                DiscoverySignalReceiver.DISCOVERY_NUDGE_DISMISS, component));

        DiscoveryManagerServices.DiscoveryManagerApi.publishNudge(mClient, nn);
    }

    private PendingIntent buildActionIntent(String body, String action, ComponentName component) {
        Intent intent = new Intent(action);
        String nudgeID;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(body.getBytes());
            nudgeID = new String(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "No Algo, defaulting to unknown", e);
            nudgeID = "unknown";
        }
        intent.putExtra(DiscoverySignalReceiver.NUDGE_ID, nudgeID);
        intent.putExtra(DiscoverySignalReceiver.NUDGE_KEY, mKey);
        intent.putExtra(DiscoverySignalReceiver.NUDGE_COMPONENT, component.flattenToShortString());

        return PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    }

    /**
     * Validates if a nudge should be shown.
     *
     * @param key the nudge key we're validating
     * @param b bundle with nudge data
     * @return true if the nudge is good to go, false if the nudge should not show.
     */
    private boolean validateShouldShowNudge(String key, Bundle b) {
        boolean checkCount;

        SharedPreferences preferences = mContext.getSharedPreferences(DialtactsActivity
                .SHARED_PREFS_NAME, Context.MODE_PRIVATE);

        String preferenceKey = getPreferenceKeyForNudgeKey(key);
        // If the preference does not exist then this is the first event so default to 1;
        int count = preferences.getInt(preferenceKey, 1);

        checkCount = (count == b.getInt(NudgeKey.NOTIFICATION_PARAM_EVENTS_FIRST_NUDGE, 0)) ||
                (count == b.getInt(NudgeKey.NOTIFICATION_PARAM_EVENTS_SECOND_NUDGE, 0));

        // return true if nudge should be shown
        return checkCount;
    }

    private static String getPreferenceKeyForNudgeKey(String nudgeKey) {
        String prefKey = null;
        switch(nudgeKey) {
            case NudgeKey.NOTIFICATION_INTERNATIONAL_CALL:
                prefKey = CallMethodUtils.PREF_INTERNATIONAL_CALLS;
                break;
            case NudgeKey.NOTIFICATION_WIFI_CALL:
                prefKey = CallMethodUtils.PREF_WIFI_CALL;
                break;
            case NudgeKey.NOTIFICATION_ROAMING:
                prefKey = CallMethodUtils.PREF_ROAMING_CALLS;
                break;
        }
        return prefKey;
    }

    public static void incrementCount(String nudgeKey, Context context) {
        String prefKey = getPreferenceKeyForNudgeKey(nudgeKey);

        if (prefKey != null) {
            SharedPreferences nudgePrefs = context.getSharedPreferences(
                    DialtactsActivity.SHARED_PREFS_NAME, Context.MODE_PRIVATE);
            // If the preference does not exist then set default to zero so when we increment it
            // right after then we will have the correct value (1).
            int currentCount = nudgePrefs.getInt(prefKey, 0);
            nudgePrefs.edit().putInt(prefKey, ++currentCount).apply();
        }
    }

}