summaryrefslogtreecommitdiff
path: root/navit/android/src/org/navitproject/navit/NavitTraff.java
blob: fd499b70b5c3ee6ff6b0e17d62f034e0f35afede (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
422
423
424
425
426
427
428
/*
 * Navit, a modular navigation system.
 * Copyright (C) 2005-2018 Navit Team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 */

package org.navitproject.navit;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * The TraFF receiver implementation.
 *
 * <p>This class registers the broadcast receiver for TraFF feeds, polls all registered sources once on creation,
 * receives TraFF feeds and forwards them to the traffic module for processing.</p>
 */
public class NavitTraff extends BroadcastReceiver {

    private static final String ACTION_TRAFF_GET_CAPABILITIES = "org.traffxml.traff.GET_CAPABILITIES";
    private static final String ACTION_TRAFF_HEARTBEAT = "org.traffxml.traff.HEARTBEAT";
    private static final String ACTION_TRAFF_FEED = "org.traffxml.traff.FEED";
    private static final String ACTION_TRAFF_POLL = "org.traffxml.traff.POLL";
    private static final String ACTION_TRAFF_SUBSCRIBE = "org.traffxml.traff.SUBSCRIBE";
    private static final String ACTION_TRAFF_SUBSCRIPTION_CHANGE = "org.traffxml.traff.SUBSCRIPTION_CHANGE";
    private static final String ACTION_TRAFF_UNSUBSCRIBE = "org.traffxml.traff.UNSUBSCRIBE";
    private static final String COLUMN_DATA = "data";
    private static final String CONTENT_SCHEMA = "content";
    private static final String[] ERROR_STRINGS = {
            "unknown (0)",
            "invalid request (1)",
            "subscription rejected by the source (2)",
            "requested area not covered (3)",
            "requested area partially covered (4)",
            "subscription ID not recognized by the source (5)",
            "unknown (6)",
            "source reported an internal error (7)"
    };
    private static final String EXTRA_CAPABILITIES = "capabilities";
    private static final String EXTRA_FEED = "feed";
    private static final String EXTRA_FILTER_LIST = "filter_list";
    private static final String EXTRA_PACKAGE = "package";
    private static final String EXTRA_SUBSCRIPTION_ID = "subscription_id";
    private static final String MIME_TYPE_TRAFF = "vnd.android.cursor.dir/org.traffxml.message";
    private static final int RESULT_OK = -1;
    private static final int RESULT_INTERNAL_ERROR = 7;
    private static final int RESULT_INVALID = 1;
    private static final int RESULT_SUBSCRIPTION_REJECTED = 2;
    private static final int RESULT_NOT_COVERED = 3;
    private static final int RESULT_PARTIALLY_COVERED = 4;
    private static final int RESULT_SUBSCRIPTION_UNKNOWN = 5;
    private static final String TAG = "NavitTraff";
    private final long mCbid;

    private final Context context;

    /** Active subscriptions (key is the subscription ID, value is the package ID). */
    private Map<String, String> subscriptions = new HashMap<String, String>();

    /**
     * Forwards a newly received TraFF feed to the traffic module for processing.
     *
     * <p>This is called when a TraFF feed is received.</p>
     *
     * @param id The identifier for the native callback implementation
     * @param feed The TraFF feed
     */
    public native void onFeedReceived(long id, String feed);

    /**
     * Creates a new {@code NavitTraff} instance.
     *
     * <p>Creating a new {@code NavitTraff} instance registers a broadcast receiver for TraFF broadcasts and polls all
     * registered sources once to ensure we have messages which were received by these sources before we started up.</p>
     *
     * @param context The context
     * @param cbid The callback identifier for the native method to call upon receiving a feed
     */
    NavitTraff(Context context, long cbid) {
        this.mCbid = cbid;
        this.context = context.getApplicationContext();

        /* An intent filter for TraFF 0.7 events. */
        IntentFilter traffFilter07 = new IntentFilter();
        traffFilter07.addAction(ACTION_TRAFF_FEED);

        /* An intent filter for TraFF 0.8 events. */
        IntentFilter traffFilter08 = new IntentFilter();
        traffFilter08.addAction(ACTION_TRAFF_FEED);
        traffFilter08.addDataScheme(CONTENT_SCHEMA);
        try {
            traffFilter08.addDataType(MIME_TYPE_TRAFF);
        } catch (MalformedMimeTypeException e) {
            // as long as the constant is a well-formed MIME type, this exception never gets thrown
            e.printStackTrace();
        }

        this.context.registerReceiver(this, traffFilter07);
        this.context.registerReceiver(this, traffFilter08);

        /* Broadcast a poll intent to all TraFF 0.7-only receivers */
        Intent outIntent = new Intent(ACTION_TRAFF_POLL);
        PackageManager pm = this.context.getPackageManager();
        List<ResolveInfo> receivers07 = pm.queryBroadcastReceivers(outIntent, 0);
        List<ResolveInfo> receivers08 = pm.queryBroadcastReceivers(new Intent(ACTION_TRAFF_GET_CAPABILITIES), 0);
        if (receivers07 != null) {
            /* get receivers which support only TraFF 0.7 and poll them */
            if (receivers08 != null)
                receivers07.removeAll(receivers08);
            for (ResolveInfo receiver : receivers07) {
                ComponentName cn = new ComponentName(receiver.activityInfo.applicationInfo.packageName,
                        receiver.activityInfo.name);
                outIntent = new Intent(ACTION_TRAFF_POLL);
                outIntent.setComponent(cn);
                this.context.sendBroadcast(outIntent, Manifest.permission.ACCESS_COARSE_LOCATION);
            }
        }
    }

    void close() {
        for (Map.Entry<String, String> subscription : subscriptions.entrySet()) {
            Bundle extras = new Bundle();
            extras.putString(EXTRA_SUBSCRIPTION_ID, subscription.getKey());
            sendTraffIntent(this.context, ACTION_TRAFF_UNSUBSCRIBE, null, extras, subscription.getValue(),
                    Manifest.permission.ACCESS_COARSE_LOCATION, this);
        }
        this.context.unregisterReceiver(this);
    }

    void onFilterUpdate(String filterList) {
        /* change existing subscriptions */
        for (Map.Entry<String, String> entry : subscriptions.entrySet()) {
            Log.d(TAG, String.format("changing subscription %s (%s)", entry.getKey(), entry.getValue()));
            Bundle extras = new Bundle();
            extras.putString(EXTRA_SUBSCRIPTION_ID, entry.getKey());
            extras.putString(EXTRA_FILTER_LIST, filterList);
            sendTraffIntent(context, ACTION_TRAFF_SUBSCRIPTION_CHANGE, null, extras,
                    entry.getValue(),
                    Manifest.permission.ACCESS_COARSE_LOCATION, this);
        }

        /* set up missing subscriptions */
        PackageManager pm = this.context.getPackageManager();
        List<ResolveInfo> receivers = pm.queryBroadcastReceivers(new Intent(ACTION_TRAFF_GET_CAPABILITIES), 0);
        if (receivers != null) {
            /* filter out receivers to which we are already subscribed */
            Iterator<ResolveInfo> iter = receivers.iterator();
            while (iter.hasNext()) {
                ResolveInfo receiver = iter.next();
                if (subscriptions.containsValue(receiver.activityInfo.applicationInfo.packageName))
                    iter.remove();
            }

            for (ResolveInfo receiver : receivers) {
                Log.d(TAG, "subscribing to " + receiver.activityInfo.applicationInfo.packageName);
                Bundle extras = new Bundle();
                extras.putString(EXTRA_PACKAGE, context.getPackageName());
                extras.putString(EXTRA_FILTER_LIST, filterList);
                sendTraffIntent(context, ACTION_TRAFF_SUBSCRIBE, null, extras,
                        receiver.activityInfo.applicationInfo.packageName,
                        Manifest.permission.ACCESS_COARSE_LOCATION, this);
            }
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
            if (intent.getAction().equals(ACTION_TRAFF_FEED)) {
                Uri uri = intent.getData();
                if (uri != null) {
                    /* 0.8 feed */
                    String subscriptionId = intent.getStringExtra(EXTRA_SUBSCRIPTION_ID);
                    if (subscriptions.containsKey(subscriptionId))
                        fetchMessages(context, uri);
                    else {
                        /*
                         * If we don’t recognize the subscription, skip processing and unsubscribe.
                         * Note: if EXTRA_PACKAGE is not set, sendTraffIntent() sends the request to every
                         * manifest-declared receiver which handles the request.
                         */
                        Log.d(TAG,
                                String.format("got a feed from %s for unknown subscription %s, URI %s; unsubscribing",
                                intent.getStringExtra(EXTRA_PACKAGE), subscriptionId, uri));
                        Bundle extras = new Bundle();
                        extras.putString(EXTRA_SUBSCRIPTION_ID, subscriptionId);
                        sendTraffIntent(context, ACTION_TRAFF_UNSUBSCRIBE, null, extras,
                                intent.getStringExtra(EXTRA_PACKAGE),
                                Manifest.permission.ACCESS_COARSE_LOCATION, this);
                    }
                } else {
                    /* 0.7 feed */
                    String packageName = intent.getStringExtra(EXTRA_PACKAGE);
                    /*
                     * If the feed comes from a TraFF 0.8+ source and we are subscribed, skip it.
                     * As a side effect of the current implementation, if a “bilingual” TraFF 0.7/0.8
                     * source sends a broadcast feed before we have subscribed to it, we would process
                     * the whole feed first, and then subscribe to a subset of that data.
                     * If that turns out to be an issue, we would need to detect TraFF 0.8-capable
                     * sources and discard broadcast feeds from them.
                     */
                    if ((packageName != null) && subscriptions.containsValue(packageName))
                        return;
                    String feed = intent.getStringExtra(EXTRA_FEED);
                    if (feed == null) {
                        Log.w(this.getClass().getSimpleName(), "empty feed, ignoring");
                    } else {
                        onFeedReceived(mCbid, feed);
                    }
                } // uri != null
            } else if (intent.getAction().equals(ACTION_TRAFF_SUBSCRIBE)) {
                if (this.getResultCode() != RESULT_OK) {
                    Bundle extras = this.getResultExtras(true);
                    if (extras != null)
                        Log.e(this.getClass().getSimpleName(), String.format("subscription to %s failed, %s",
                                extras.getString(EXTRA_PACKAGE), formatTraffError(this.getResultCode())));
                    else
                        Log.e(this.getClass().getSimpleName(), String.format("subscription failed, %s",
                                formatTraffError(this.getResultCode())));
                    return;
                }
                Bundle extras = this.getResultExtras(true);
                String data = this.getResultData();
                String packageName = extras.getString(EXTRA_PACKAGE);
                String subscriptionId = extras.getString(EXTRA_SUBSCRIPTION_ID);
                if (subscriptionId == null) {
                    Log.e(this.getClass().getSimpleName(),
                            String.format("subscription to %s failed: no subscription ID returned", packageName));
                    return;
                } else if (packageName == null) {
                    Log.e(this.getClass().getSimpleName(), "subscription failed: no package name");
                    return;
                } else if (data == null) {
                    Log.w(this.getClass().getSimpleName(),
                            String.format("subscription to %s successful (ID: %s) but no content URI was supplied. "
                                    + "This is an issue with the source and may result in delayed message retrieval.",
                                    packageName, subscriptionId));
                    subscriptions.put(subscriptionId, packageName);
                    return;
                }
                Log.d(TAG, "subscription to " + packageName + " successful, ID: " + subscriptionId);
                subscriptions.put(subscriptionId, packageName);
                fetchMessages(context, Uri.parse(data));
            } else if (intent.getAction().equals(ACTION_TRAFF_SUBSCRIPTION_CHANGE)) {
                if (this.getResultCode() != RESULT_OK) {
                    Bundle extras = this.getResultExtras(true);
                    if (extras != null)
                        Log.e(this.getClass().getSimpleName(),
                                String.format("subscription change for %s failed: %s",
                                        extras.getString(EXTRA_SUBSCRIPTION_ID),
                                        formatTraffError(this.getResultCode())));
                    else
                        Log.e(this.getClass().getSimpleName(),
                                String.format("subscription change failed: %s",
                                        formatTraffError(this.getResultCode())));
                    return;
                }
                Bundle extras = intent.getExtras();
                String data = this.getResultData();
                String subscriptionId = extras.getString(EXTRA_SUBSCRIPTION_ID);
                if (subscriptionId == null) {
                    Log.w(this.getClass().getSimpleName(),
                            "subscription change successful but the source did not specify the subscription ID. "
                                    + "This is an issue with the source and may result in delayed message retrieval. "
                                    + "URI: " + data);
                    return;
                } else if (data == null) {
                    Log.w(this.getClass().getSimpleName(),
                            String.format("subscription change for %s successful but no content URI was supplied. "
                                    + "This is an issue with the source and may result in delayed message retrieval.",
                                    subscriptionId));
                    return;
                } else if (!subscriptions.containsKey(subscriptionId)) {
                    Log.e(this.getClass().getSimpleName(),
                            "subscription change failed: unknown subscription ID " + subscriptionId);
                    return;
                }
                Log.d(TAG, "subscription change for " + subscriptionId + " successful");
                fetchMessages(context, Uri.parse(data));
            } else if (intent.getAction().equals(ACTION_TRAFF_UNSUBSCRIBE)) {
                /*
                 * If we ever unsubscribe for reasons other than that we are shutting down or got a feed for
                 * a subscription we don’t recognize, or if we start keeping a persistent list of
                 * subscriptions, we need to delete the subscription from our list. Until then, there is
                 * nothing to do here: either the subscription isn’t in the list, or we are about to shut
                 * down and the whole list is about to get discarded.
                 */
            } else if (intent.getAction().equals(ACTION_TRAFF_HEARTBEAT)) {
                String subscriptionId = intent.getStringExtra(EXTRA_SUBSCRIPTION_ID);
                if (subscriptions.containsKey(subscriptionId)) {
                    Log.d(TAG,
                            String.format("got a heartbeat from %s for subscription %s; sending result",
                            intent.getStringExtra(EXTRA_PACKAGE), subscriptionId));
                    this.setResult(RESULT_OK, null, null);
                } else {
                    /*
                     * If we don’t recognize the subscription, skip reply and unsubscribe.
                     * Note: if EXTRA_PACKAGE is not set, sendTraffIntent() sends the request to every
                     * manifest-declared receiver which handles the request.
                     */
                    Log.d(TAG,
                            String.format("got a heartbeat from %s for unknown subscription %s; unsubscribing",
                            intent.getStringExtra(EXTRA_PACKAGE), subscriptionId));
                    Bundle extras = new Bundle();
                    extras.putString(EXTRA_SUBSCRIPTION_ID, subscriptionId);
                    sendTraffIntent(context, ACTION_TRAFF_UNSUBSCRIBE, null, extras,
                            intent.getStringExtra(EXTRA_PACKAGE),
                            Manifest.permission.ACCESS_COARSE_LOCATION, this);
                }
            } // intent.getAction()
        } // intent != null
    }

    /**
     * Fetches messages from a content provider.
     *
     * @param context The context to use for the content resolver
     * @param uri The content provider URI
     */
    private void fetchMessages(Context context, Uri uri) {
        try {
            Cursor cursor = context.getContentResolver().query(uri, new String[] {COLUMN_DATA}, null, null, null);
            if (cursor == null)
                return;
            if (cursor.getCount() < 1) {
                cursor.close();
                return;
            }
            StringBuilder builder = new StringBuilder("<feed>\n");
            while (cursor.moveToNext())
                builder.append(cursor.getString(cursor.getColumnIndex(COLUMN_DATA))).append("\n");
            builder.append("</feed>");
            cursor.close();
            onFeedReceived(mCbid, builder.toString());
        } catch (Exception e) {
            Log.w(TAG, String.format("Unable to fetch messages from %s", uri.toString()), e);
            e.printStackTrace();
        }
    }

    /**
     * Sends a TraFF intent to a source.  This encapsulates most of the low-level Android handling.
     *
     * <p>If the recipient specified in {@code packageName} declares multiple receivers for the intent in its
     * manifest, a separate intent will be delivered to each of them. The intent will not be delivered to
     * receivers registered at runtime.
     *
     * <p>All intents are sent as explicit ordered broadcasts. This means two things:
     *
     * <p>Any app which declares a matching receiver in its manifest will be woken up to process the intent.
     * This works even with certain Android 7 builds which restrict intent delivery to apps which are not
     * currently running.
     *
     * <p>It is safe for the recipient to unconditionally set result data. If the recipient does not set result
     * data, the result will have a result code of {@link #RESULT_INTERNAL_ERROR}, no data and no extras.
     *
     * @param context The context
     * @param action The intent action.
     * @param data The intent data (for TraFF, this is the content provider URI), or null
     * @param extras The extras for the intent
     * @param packageName The package name for the recipient, or null to deliver the intent to all matching receivers
     * @param receiverPermission A permission which the recipient must hold, or null if not required
     * @param resultReceiver A BroadcastReceiver which will receive the result for the intent
     */
    /* From traff-consumer-android, by the same author and re-licensed under GPL2 for Navit */
    public static void sendTraffIntent(Context context, String action, Uri data, Bundle extras, String packageName,
            String receiverPermission, BroadcastReceiver resultReceiver) {
        Intent outIntent = new Intent(action);
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> receivers = pm.queryBroadcastReceivers(outIntent, 0);
        if (receivers != null)
            for (ResolveInfo receiver : receivers) {
                if ((packageName != null) && !packageName.equals(receiver.activityInfo.applicationInfo.packageName))
                    continue;
                ComponentName cn = new ComponentName(receiver.activityInfo.applicationInfo.packageName,
                        receiver.activityInfo.name);
                outIntent = new Intent(action);
                if (data != null)
                    outIntent.setData(data);
                if (extras != null)
                    outIntent.putExtras(extras);
                outIntent.setComponent(cn);
                context.sendOrderedBroadcast(outIntent,
                        receiverPermission,
                        resultReceiver,
                        null, // scheduler,
                        RESULT_INTERNAL_ERROR, // initialCode,
                        null, // initialData,
                        null);
            }
    }

    private static String formatTraffError(int code) {
        if ((code < 0) || (code >= ERROR_STRINGS.length))
            return String.format("unknown (%d)", code);
        else
            return ERROR_STRINGS[code];
    }
}