summaryrefslogtreecommitdiff
path: root/src/com/android/im/app/ImPluginHelper.java
blob: f557493b24ccd3188e4edaacef5e89607f1f28df (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
/*
 * Copyright (C) 2009 Myriad Group AG.
 * Copyright (C) 2009 The Android Open Source 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.android.im.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteFullException;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Im;
import android.text.TextUtils;
import android.util.Log;

import com.android.im.plugin.ImConfigNames;
import com.android.im.plugin.ImPlugin;
import com.android.im.plugin.ImPluginConstants;
import com.android.im.plugin.ImPluginInfo;

public class ImPluginHelper {

    private static final String TAG = "ImPluginUtils";

    private Context mContext;
    private ArrayList<ImPluginInfo> mPluginsInfo;
    private ArrayList<ImPlugin> mPluginObjects;
    private boolean mLoaded;

    private static ImPluginHelper sInstance;
    public static ImPluginHelper getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new ImPluginHelper(context);
        }
        return sInstance;
    }

    private ImPluginHelper(Context context) {
        mContext = context;
        mPluginsInfo = new ArrayList<ImPluginInfo>();
        mPluginObjects = new ArrayList<ImPlugin>();
    }

    public ArrayList<ImPluginInfo> getPluginsInfo() {
        if (!mLoaded) {
            loadAvaiablePlugins();
        }
        return mPluginsInfo;
    }

    public ArrayList<ImPlugin> getPluginObjects() {
        if (!mLoaded) {
            loadAvaiablePlugins();
        }
        return mPluginObjects;
    }

    public void loadAvaiablePlugins() {
        if (mLoaded) {
            return;
        }

        PackageManager pm = mContext.getPackageManager();
        List<ResolveInfo> plugins = pm.queryIntentServices(
                new Intent(ImPluginConstants.PLUGIN_ACTION_NAME), PackageManager.GET_META_DATA);
        for (ResolveInfo info : plugins) {
            Log.d(TAG, "Found plugin " + info);

            ServiceInfo serviceInfo = info.serviceInfo;
            if (serviceInfo == null) {
                Log.e(TAG, "Ignore bad IM plugin: " + info);
                continue;
            }
            String providerName = null;
            String providerFullName = null;
            String signUpUrl = null;
            Bundle metaData = serviceInfo.metaData;
            if (metaData != null) {
                providerName = metaData.getString(ImPluginConstants.METADATA_PROVIDER_NAME);
                providerFullName = metaData.getString(ImPluginConstants.METADATA_PROVIDER_FULL_NAME);
                signUpUrl = metaData.getString(ImPluginConstants.METADATA_SIGN_UP_URL);
            }
            if (TextUtils.isEmpty(providerName) || TextUtils.isEmpty(providerFullName)) {
                Log.e(TAG, "Ignore bad IM plugin: " + info + ". Lack of required meta data");
                continue;
            }

            if (isPluginDuplicated(providerName)) {
                Log.e(TAG, "Ignore duplicated IM plugin: " + info);
                continue;
            }

            if (!serviceInfo.packageName.equals(mContext.getPackageName())) {
                Log.e(TAG, "Ignore plugin in package: " + serviceInfo.packageName);
                continue;
            }
            ImPluginInfo pluginInfo = new ImPluginInfo(providerName, serviceInfo.packageName,
                    serviceInfo.name, serviceInfo.applicationInfo.sourceDir);

            ImPlugin plugin = loadPlugin(pluginInfo);
            if (plugin == null) {
                Log.e(TAG, "Ignore bad IM plugin");
                continue;
            }

            try {
                updateProviderDb(plugin, pluginInfo,providerFullName, signUpUrl);
            } catch (SQLiteFullException e) {
                Log.e(TAG, "Storage full", e);
                return;
            }
            mPluginsInfo.add(pluginInfo);
            mPluginObjects.add(plugin);
        }
        mLoaded = true;
    }

    private boolean isPluginDuplicated(String providerName) {
        for (ImPluginInfo plugin : mPluginsInfo) {
            if (plugin.mProviderName.equals(providerName)) {
                return true;
            }
        }
        return false;
    }

    private ImPlugin loadPlugin(ImPluginInfo pluginInfo) {
        // XXX Load the plug-in implementation directly from the apk rather than
        // binding to the service and call through IPC Binder API. This is much
        // more effective since we don't need to start the service in other
        // process. We can not run the plug-in service in the same process as a
        // local service because that the interface is defined in a shared
        // library in order to compile the plug-in separately. In this case, the
        // interface will be loaded by two class loader separately and a
        // ClassCastException will be thrown if we cast the binder to the
        // interface.
        ClassLoader loader = mContext.getClassLoader();
        try {
            Class<?> cls = loader.loadClass(pluginInfo.mClassName);
            return (ImPlugin) cls.newInstance();
        } catch (ClassNotFoundException e) {
            Log.e(TAG, "Could not find plugin class", e);
        } catch (IllegalAccessException e) {
            Log.e(TAG, "Could not create plugin instance", e);
        } catch (InstantiationException e) {
            Log.e(TAG, "Could not create plugin instance", e);
        } catch (SecurityException e) {
            Log.e(TAG, "Could not load plugin", e);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Could not load plugin", e);
        }
        return null;
    }

    private long updateProviderDb(ImPlugin plugin, ImPluginInfo info,
            String providerFullName, String signUpUrl) {
        Map<String, String> config = loadConfiguration(plugin, info);
        if (config == null) {
            return 0;
        }

        long providerId = 0;
        ContentResolver cr = mContext.getContentResolver();
        String where = Im.Provider.NAME + "=?";
        String[] selectionArgs = new String[]{info.mProviderName};
        Cursor c = cr.query(Im.Provider.CONTENT_URI,
                null /* projection */,
                where,
                selectionArgs,
                null /* sort order */);

        boolean pluginChanged;
        try {
            if (c.moveToFirst()) {
                providerId = c.getLong(c.getColumnIndexOrThrow(Im.Provider._ID));
                pluginChanged = isPluginChanged(cr, providerId, config);
                if (pluginChanged) {
                    // Update the full name, signup url and category each time when the plugin change
                    // instead of specific version change because this is called only once.
                    // It's ok to update them even the values are not changed.
                    // Note that we don't update the provider name because it's used as
                    // identifier at some place and the plugin should never change it.
                    ContentValues values = new ContentValues(3);
                    values.put(Im.Provider.FULLNAME, providerFullName);
                    values.put(Im.Provider.SIGNUP_URL, signUpUrl);
                    values.put(Im.Provider.CATEGORY, ImApp.IMPS_CATEGORY);
                    Uri uri = ContentUris.withAppendedId(Im.Provider.CONTENT_URI, providerId);
                    cr.update(uri, values, null, null);
                }
            } else {
                ContentValues values = new ContentValues(3);
                values.put(Im.Provider.NAME, info.mProviderName);
                values.put(Im.Provider.FULLNAME, providerFullName);
                values.put(Im.Provider.CATEGORY, ImApp.IMPS_CATEGORY);
                values.put(Im.Provider.SIGNUP_URL, signUpUrl);

                Uri result = cr.insert(Im.Provider.CONTENT_URI, values);
                providerId = ContentUris.parseId(result);
                pluginChanged = true;
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }

        if (pluginChanged) {
            // Remove all the old settings
            cr.delete(ContentUris.withAppendedId(
                    Im.ProviderSettings.CONTENT_URI, providerId),
                    null, /*where*/
                    null /*selectionArgs*/);

            ContentValues[] settingValues = new ContentValues[config.size()];

            int index = 0;
            for (Map.Entry<String, String> entry : config.entrySet()) {
                ContentValues settingValue = new ContentValues();
                settingValue.put(Im.ProviderSettings.PROVIDER, providerId);
                settingValue.put(Im.ProviderSettings.NAME, entry.getKey());
                settingValue.put(Im.ProviderSettings.VALUE, entry.getValue());
                settingValues[index++] = settingValue;
            }
            cr.bulkInsert(Im.ProviderSettings.CONTENT_URI, settingValues);
        }

        return providerId;
    }

    @SuppressWarnings("unchecked")
    private Map<String, String> loadConfiguration(ImPlugin plugin,
            ImPluginInfo info) {
        Map<String, String> config = null;

            config = plugin.getProviderConfig();

        if (config != null) {
            config.put(ImConfigNames.PLUGIN_PATH, info.mSrcPath);
            config.put(ImConfigNames.PLUGIN_CLASS, info.mClassName);
        }
        return config;
    }

    private boolean isPluginChanged(ContentResolver cr, long providerId,
            Map<String, String> config) {
        String origVersion = Im.ProviderSettings.getStringValue(cr, providerId,
                ImConfigNames.PLUGIN_VERSION);

        if (origVersion == null) {
            return true;
        }
        String newVersion = config.get(ImConfigNames.PLUGIN_VERSION);
        return !origVersion.equals(newVersion);
    }
}