mSuffixes;
69 |
70 | public SsidBlackList() {
71 | mPrefixes = new ArrayList<>();
72 | mSuffixes = new ArrayList<>();
73 | }
74 |
75 | /**
76 | * Loads blacklist from xml files
77 | * @param defaultList - generic list (well-known bad wifis, e.g. trains, buses, mobile hotspots)
78 | * @param extraUserList - user-provided list (e.g. own wifi)
79 | * @throws XmlPullParserException
80 | */
81 | public final void openFile(final String defaultList, final String extraUserList) {
82 |
83 | if (ALWAYS_RECREATE_SSID_BLACKLIST) {
84 | SsidBlackListBootstraper.run(defaultList);
85 | }
86 |
87 | if (defaultList != null) {
88 | try {
89 | final File file = new File(defaultList);
90 | final FileInputStream defaultStream = new FileInputStream(file);
91 | add(defaultStream);
92 | } catch (final FileNotFoundException e) {
93 | Log.i(TAG, "Default blacklist " + defaultList + " not found. Setting up..");
94 | SsidBlackListBootstraper.run(defaultList);
95 | }
96 | }
97 |
98 | if (extraUserList != null) {
99 | try {
100 | final File file = new File(extraUserList);
101 | final FileInputStream userStream = new FileInputStream(file);
102 | add(userStream);
103 | } catch (final FileNotFoundException e) {
104 | Log.w(TAG, "User-defined blacklist " + extraUserList + " not found. Skipping");
105 | }
106 | } else {
107 | Log.i(TAG, "No user-defined blacklist provided");
108 | }
109 | }
110 |
111 | /**
112 | * @param file
113 | */
114 | private void add(final FileInputStream file) {
115 | try {
116 | final XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
117 | factory.setNamespaceAware(true);
118 | final XmlPullParser xpp = factory.newPullParser();
119 |
120 | if (file != null) {
121 | xpp.setInput(new InputStreamReader(file));
122 |
123 | int eventType = xpp.getEventType();
124 | String currentTag = null;
125 | String value = null;
126 |
127 | while (eventType != XmlPullParser.END_DOCUMENT) {
128 | if (eventType == XmlPullParser.START_TAG) {
129 | currentTag = xpp.getName();
130 | } else if (eventType == XmlPullParser.TEXT) {
131 | if (PREFIX_TAG.equals(currentTag) || SUFFIX_TAG.equals(currentTag)) {
132 | value = xpp.getText();
133 | }
134 | } else if (eventType == XmlPullParser.END_TAG) {
135 | if (PREFIX_TAG.equals(xpp.getName())) {
136 | mPrefixes.add(value);
137 | }
138 | if (SUFFIX_TAG.equals(xpp.getName())) {
139 | mSuffixes.add(value);
140 | }
141 | }
142 | eventType = xpp.next();
143 | }
144 | }
145 | } catch (final IOException e) {
146 | Log.e(TAG, "I/O exception reading blacklist");
147 | } catch (final XmlPullParserException e) {
148 | Log.e(TAG, "Error parsing blacklist");
149 | }
150 | Log.i(TAG, "Loaded " + (mPrefixes.size() + mSuffixes.size()) + " SSID blacklist entries");
151 | }
152 |
153 | /**
154 | * Checks whether given ssid is in ignore list
155 | * @param ssid SSID to check
156 | * @return true, if in ignore list
157 | */
158 | @SuppressLint("DefaultLocale")
159 | public final boolean contains(final String ssid) {
160 | boolean match = false;
161 | for (final String prefix : mPrefixes) {
162 | if (ssid.toLowerCase().startsWith(prefix.toLowerCase())) {
163 | match = true;
164 | break;
165 | }
166 | }
167 |
168 | // don't look anyfurther
169 | if (match) {
170 | return match;
171 | }
172 |
173 | for (final String suffix : mSuffixes) {
174 | if (ssid.toLowerCase().endsWith(suffix.toLowerCase())) {
175 | match = true;
176 | break;
177 | }
178 | }
179 |
180 | return match; // OK
181 | }
182 | }
183 |
--------------------------------------------------------------------------------
/src/org/radiocells/unifiedNlp/utils/PermissionHelper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2013–2016 Michael von Glasow.
3 | *
4 | * This file is part of LSRN Tools.
5 | *
6 | * LSRN Tools is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * LSRN Tools is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with LSRN Tools. If not, see .
18 | */
19 |
20 | package org.radiocells.unifiedNlp.utils;
21 |
22 | import android.app.NotificationChannel;
23 | import android.app.NotificationManager;
24 | import android.app.PendingIntent;
25 | import android.content.Context;
26 | import android.content.Intent;
27 | import android.os.Build;
28 | import android.os.Bundle;
29 | import android.os.Handler;
30 | import android.os.Looper;
31 | import android.os.ResultReceiver;
32 |
33 | import androidx.appcompat.app.AppCompatActivity;
34 | import androidx.core.app.ActivityCompat;
35 | import androidx.core.app.NotificationCompat;
36 | import androidx.core.app.TaskStackBuilder;
37 |
38 |
39 | /**
40 | * Provides helper methods to request permissions from components other than Activities.
41 | */
42 | public class PermissionHelper {
43 | private static final String TAG = PermissionHelper.class.getSimpleName();
44 |
45 |
46 | /**
47 | * Requests permissions to be granted to this application.
48 | *
49 | * This method is a wrapper around
50 | * {@link android.support.v4.app.ActivityCompat#requestPermissions(android.app.Activity, String[], int)}
51 | * which works in a similar way, except it can be called from non-activity contexts. When called, it
52 | * displays a notification with a customizable title and text. When the user taps the notification, an
53 | * activity is launched in which the user is prompted to allow or deny the request.
54 | *
55 | * After the user has made a choice,
56 | * {@link android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])}
57 | * is called, reporting whether the permissions were granted or not.
58 | *
59 | * @param context The context from which the request was made. The context supplied must implement
60 | * {@link android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback} and will receive the
61 | * result of the operation.
62 | * @param permissions The requested permissions
63 | * @param requestCode Application specific request code to match with a result reported to
64 | * {@link android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])}
65 | * @param notificationTitle The title for the notification
66 | * @param notificationText The text for the notification
67 | * @param notificationIcon Resource identifier for the notification icon
68 | */
69 | public static
70 | void requestPermissions(final T context, String[] permissions, int requestCode, String notificationTitle, String notificationText, int notificationIcon) {
71 | ResultReceiver resultReceiver = new ResultReceiver(new Handler(Looper.getMainLooper())) {
72 | @Override
73 | protected void onReceiveResult(int resultCode, Bundle resultData) {
74 | String[] outPermissions = resultData.getStringArray("permissions");
75 | int[] grantResults = resultData.getIntArray("grantResults");
76 | context.onRequestPermissionsResult(resultCode, outPermissions, grantResults);
77 | }
78 | };
79 |
80 | Intent permIntent = new Intent(context, PermissionRequestActivity.class);
81 | permIntent.putExtra("resultReceiver", resultReceiver);
82 | permIntent.putExtra("permissions", permissions);
83 | permIntent.putExtra("requestCode", requestCode);
84 |
85 | TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
86 | stackBuilder.addNextIntent(permIntent);
87 |
88 | PendingIntent permPendingIntent =
89 | stackBuilder.getPendingIntent(
90 | 0,
91 | PendingIntent.FLAG_UPDATE_CURRENT
92 | );
93 |
94 | NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
95 | .setSmallIcon(notificationIcon)
96 | .setContentTitle(notificationTitle)
97 | .setContentText(notificationText)
98 | .setOngoing(true)
99 | //.setCategory(Notification.CATEGORY_STATUS)
100 | .setAutoCancel(true)
101 | .setWhen(0)
102 | .setContentIntent(permPendingIntent)
103 | .setStyle(null);
104 |
105 | NotificationManager notificationManager =
106 | (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
107 |
108 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
109 | String channelId = "channel_id";
110 | NotificationChannel channel = new NotificationChannel(
111 | channelId,
112 | "radiocells.org location service",
113 | NotificationManager.IMPORTANCE_HIGH);
114 | notificationManager.createNotificationChannel(channel);
115 | builder.setChannelId(channelId);
116 | }
117 |
118 | notificationManager.notify(requestCode, builder.build());
119 | }
120 |
121 |
122 | /**
123 | * A blank {@link Activity} on top of which permission request dialogs can be displayed
124 | */
125 | public static class PermissionRequestActivity extends AppCompatActivity {
126 | ResultReceiver resultReceiver;
127 | String[] permissions;
128 | int requestCode;
129 |
130 | /**
131 | * Called when the user has made a choice in the permission dialog.
132 | *
133 | * This method wraps the responses in a {@link Bundle} and passes it to the {@link ResultReceiver}
134 | * specified in the {@link Intent} that started the activity, then closes the activity.
135 | */
136 | @Override
137 | public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
138 | Bundle resultData = new Bundle();
139 | resultData.putStringArray("permissions", permissions);
140 | resultData.putIntArray("grantResults", grantResults);
141 | resultReceiver.send(requestCode, resultData);
142 | finish();
143 | }
144 |
145 |
146 | /**
147 | * Called when the activity is started.
148 | *
149 | * This method obtains several extras from the {@link Intent} that started the activity: the request
150 | * code, the requested permissions and the {@link ResultReceiver} which will receive the results.
151 | * After that, it issues the permission request.
152 | */
153 | @Override
154 | protected void onStart() {
155 | super.onStart();
156 |
157 | resultReceiver = this.getIntent().getParcelableExtra("\"resultReceiver\"");
158 | permissions = this.getIntent().getStringArrayExtra("permissions");
159 | requestCode = this.getIntent().getIntExtra("requestCode", 0);
160 |
161 | ActivityCompat.requestPermissions(this, permissions, requestCode);
162 | }
163 | }
164 | }
165 |
--------------------------------------------------------------------------------
/src/org/radiocells/unifiedNlp/DialogPreferenceCatalogs.java:
--------------------------------------------------------------------------------
1 | /*
2 | Radiobeacon - Openbmap wifi and cell logger
3 | Copyright (C) 2013 wish7
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as
7 | published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package org.radiocells.unifiedNlp;
20 |
21 | import android.app.ProgressDialog;
22 | import android.content.Context;
23 | import android.os.AsyncTask;
24 | import android.os.Bundle;
25 | import android.preference.DialogPreference;
26 | import android.util.AttributeSet;
27 | import android.util.Log;
28 | import android.util.SparseArray;
29 | import android.view.View;
30 | import android.widget.ExpandableListView;
31 |
32 | import org.json.JSONArray;
33 | import org.json.JSONException;
34 | import org.json.JSONObject;
35 | import org.radiocells.unifiedNlp.utils.CatalogDownload;
36 | import org.radiocells.unifiedNlp.utils.ICatalogsListAdapterListener;
37 |
38 | import java.io.BufferedReader;
39 | import java.io.InputStream;
40 | import java.io.InputStreamReader;
41 | import java.net.HttpURLConnection;
42 | import java.net.URL;
43 | import java.util.ArrayList;
44 | import java.util.List;
45 |
46 |
47 | public class DialogPreferenceCatalogs extends DialogPreference implements ICatalogsListAdapterListener {
48 |
49 | private static final String TAG = DialogPreferenceCatalogs.class.getSimpleName();
50 |
51 | private static final String LIST_DOWNLOADS_URL = Preferences.SERVER_BASE + "/downloads/catalog_downloads.json";
52 | private DialogPreferenceCatalogsListAdapter mAdapter;
53 | private final Context mContext;
54 | private SparseArray groups;
55 | private List mOnlineResults;
56 |
57 | private ProgressDialog checkDialog;
58 |
59 | public DialogPreferenceCatalogs(Context context, AttributeSet attrs) {
60 | super(context, attrs);
61 | mContext = context;
62 | setDialogLayoutResource(R.layout.dialogpreference_catalogs);
63 | }
64 |
65 | @Override
66 | protected void onBindDialogView(View v) {
67 | super.onBindDialogView(v);
68 | groups = new SparseArray<>();
69 | ExpandableListView listView = v.findViewById(R.id.list);
70 | mAdapter = new DialogPreferenceCatalogsListAdapter(getContext(), groups, this);
71 | listView.setAdapter(mAdapter);
72 |
73 | if (checkDialog == null || !checkDialog.isShowing()) {
74 | checkDialog = new ProgressDialog(getContext());
75 | }
76 | // retrieve online Catalogs
77 | GetAvailableCatalogsTask data = new GetAvailableCatalogsTask();
78 | data.execute();
79 | }
80 |
81 | @Override
82 | protected void showDialog(Bundle state) {
83 | super.showDialog(state);
84 | }
85 |
86 | @Override
87 | protected void onDialogClosed(boolean positiveResult) {
88 | if (checkDialog != null && checkDialog.isShowing()) {
89 | checkDialog.dismiss();
90 | }
91 | checkDialog = null;
92 | }
93 |
94 | /**
95 | * Creates list of online maps
96 | */
97 | private void populateListView() {
98 | DialogPreferenceCatalogsGroup group = null;
99 | String name;
100 | int j = 0;
101 | for (int i = 0; i < mOnlineResults.size(); i++) {
102 | if (i==0) {
103 | name = (mOnlineResults.get(i).getRegion() != null) ? mOnlineResults.get(i).getRegion() : "Unsorted";
104 | group = new DialogPreferenceCatalogsGroup(name);
105 | Log.d(TAG, "Added group " + name);
106 | } else if (!mOnlineResults.get(i).getRegion().equals(mOnlineResults.get(i - 1).getRegion())) {
107 | name = (mOnlineResults.get(i).getRegion() != null) ? mOnlineResults.get(i).getRegion() : "Unsorted";
108 | Log.d(TAG, "Added group " + name);
109 | groups.append(groups.size(), group);
110 | group = new DialogPreferenceCatalogsGroup(name);
111 | }
112 | group.children.add(mOnlineResults.get(i));
113 | }
114 | groups.append(j, group);
115 | mAdapter.notifyDataSetChanged();
116 | }
117 |
118 | @Override
119 | public void onItemClicked(CatalogDownload catalog) {
120 | ((ICatalogChooser) getContext()).catalogSelected(catalog.getUrl());
121 | getDialog().dismiss();
122 | }
123 |
124 | private class GetAvailableCatalogsTask extends AsyncTask> {
125 |
126 | @Override
127 | protected void onPreExecute() {
128 | checkDialog.setTitle(mContext.getString(R.string.prefs_check_server));
129 | checkDialog.setMessage(mContext.getString(R.string.please_stay_patient));
130 | checkDialog.setCancelable(false);
131 | checkDialog.setIndeterminate(true);
132 | checkDialog.show();
133 | }
134 |
135 | @Override
136 | protected List doInBackground(String... params) {
137 | List result = new ArrayList<>();
138 |
139 | String json = "";
140 | try {
141 | URL endpoint = new URL(LIST_DOWNLOADS_URL);
142 | HttpURLConnection con = (HttpURLConnection) endpoint.openConnection();
143 | con.setRequestProperty("Content-Type", "application/json");
144 | con.setRequestProperty("Accept", "application/json");
145 | con.connect();
146 | InputStream stream = con.getInputStream();
147 | BufferedReader rd = new BufferedReader(new InputStreamReader(stream));
148 | StringBuilder bf = new StringBuilder();
149 | String line;
150 |
151 | while ((line = rd.readLine()) != null) {
152 | bf.append(line).append("\n");
153 | }
154 | json = bf.toString();
155 | } catch (Exception e) {
156 | Log.e(TAG, "Error parsing json");
157 | }
158 |
159 | try {
160 | JSONObject jObject = new JSONObject(json);
161 | JSONArray arr;
162 | arr = jObject.getJSONArray("downloads");
163 | for (int i = 0; i < arr.length(); i++) {
164 | result.add(jsonToDownload(arr.getJSONObject(i)));
165 | }
166 | } catch (JSONException e) {
167 | Log.e(TAG, "Error parsing JSON");
168 | }
169 |
170 | return result;
171 | }
172 |
173 | @Override
174 | protected void onPostExecute(List result) {
175 | super.onPostExecute(result);
176 |
177 | if (checkDialog != null && checkDialog.isShowing()) {
178 | checkDialog.dismiss();
179 | }
180 |
181 | mOnlineResults = result;
182 | populateListView();
183 | }
184 |
185 | /**
186 | * Converts server json in a CatalogDownload record
187 | * @param obj server reply
188 | * @return parsed server reply
189 | * @throws JSONException
190 | */
191 | private CatalogDownload jsonToDownload(JSONObject obj) throws JSONException {
192 | String updated = obj.getString("last_updated");
193 | String title = obj.getString("title");
194 | String region = obj.getString("region");
195 | String url = obj.getString("url");
196 | String id = obj.getString("id");
197 | return new CatalogDownload(title, region, url, id, updated);
198 | }
199 | }
200 | }
--------------------------------------------------------------------------------
/src/org/radiocells/unifiedNlp/geocoders/OnlineProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | Radiobeacon - Openbmap Unified Network Location Provider
3 | Copyright (C) 2013 wish7
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as
7 | published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 | package org.radiocells.unifiedNlp.geocoders;
19 |
20 | import android.annotation.SuppressLint;
21 | import android.content.Context;
22 | import android.location.Location;
23 | import android.net.wifi.ScanResult;
24 | import android.os.AsyncTask;
25 | import android.os.Bundle;
26 | import android.util.Log;
27 |
28 | import org.json.JSONArray;
29 | import org.json.JSONException;
30 | import org.json.JSONObject;
31 | import org.radiocells.unifiedNlp.models.Cell;
32 | import org.radiocells.unifiedNlp.services.JSONParser;
33 |
34 | import java.util.ArrayList;
35 | import java.util.List;
36 |
37 | public class OnlineProvider extends AbstractProvider implements ILocationProvider {
38 |
39 | private static final String TAG = OnlineProvider.class.getName();
40 |
41 | /**
42 | * Geolocation service
43 | */
44 | private static final String REQUEST_URL = "https://%s.radiocells.org/geolocate";
45 |
46 | /**
47 | * Query extra debug information from webservice
48 | */
49 | private final boolean mDebug;
50 |
51 | private final Context mContext;
52 |
53 | /**
54 | * Example wifi query JSON
55 | */
56 | // {"wifiAccessPoints":[{"macAddress":"000000000000","signalStrength":-54}]}
57 |
58 | /**
59 | * Example cell query JSON
60 | */
61 | // {"cellTowers": [{"cellId": 21532831, "locationAreaCode": 2862, "mobileCountryCode": 214, "mobileNetworkCode": 7}]}
62 |
63 | /**
64 | * Example JSON reply
65 | */
66 | // {"accuracy":30,"location":{"lng":10.088244781346,"lat":52.567062375353}}
67 |
68 | /**
69 | * Callback function on results available
70 | */
71 | private ILocationCallback mListener;
72 |
73 | private ArrayList mWifiQuery;
74 | private ArrayList mCellQuery;
75 |
76 | public OnlineProvider(final Context context, final ILocationCallback listener, boolean debug) {
77 | mListener = listener;
78 | mDebug = debug;
79 | mContext = context;
80 | setLastFix(System.currentTimeMillis());
81 | }
82 |
83 | /**
84 | * Queries location for list of wifis
85 | */
86 | @SuppressLint("StaticFieldLeak")
87 | @Override
88 | public void getLocation(List wifisList, List cellsList) {
89 | ArrayList wifis = new ArrayList<>();
90 |
91 | if (wifisList != null) {
92 | // Generates a list of wifis from scan results
93 | for (ScanResult r : wifisList) {
94 | if ((r.BSSID != null) & !(r.SSID.endsWith("_nomap"))) {
95 | wifis.add(r.BSSID);
96 | }
97 | }
98 | Log.i(TAG, "Using " + wifis.size() + " wifis for geolocation");
99 | } else
100 | Log.i(TAG, "No wifis supplied for geolocation");
101 |
102 | new AsyncTask() {
103 | @Override
104 | protected JSONObject doInBackground(Object... params) {
105 | if (params == null) {
106 | throw new IllegalArgumentException("Wifi list was null");
107 | }
108 | mWifiQuery = (ArrayList) params[0];
109 | mCellQuery = new ArrayList<>();
110 | for (Cell temp : (List) params[1]) {
111 | mCellQuery.add(temp.toString());
112 | }
113 |
114 | // balancing is handle by the server - so removed choice here
115 | //Random r = new Random();
116 | int idx = 0; //r.nextInt(3);
117 | final String balancer = String.format(REQUEST_URL, new String[]{"a"}[idx]);
118 | return queryServer(balancer, (ArrayList) params[0], (List) params[1]);
119 | }
120 |
121 | @Override
122 | protected void onPostExecute(JSONObject jsonData) {
123 | if (jsonData == null) {
124 | Log.e(TAG, "JSON data was null");
125 | return;
126 | }
127 |
128 | try {
129 | Log.i(TAG, "JSON response: " + jsonData.toString());
130 |
131 | if (jsonData.has("location")) {
132 | String source = jsonData.optString("source", "unknown");
133 | JSONObject location = jsonData.getJSONObject("location");
134 | double lat = location.getDouble("lat");
135 | double lon = location.getDouble("lng");
136 | long acc = jsonData.getLong("accuracy");
137 | Location result = new Location(TAG);
138 | result.setLatitude(lat);
139 | result.setLongitude(lon);
140 | result.setAccuracy(acc);
141 | result.setTime(System.currentTimeMillis());
142 |
143 | Bundle b = new Bundle();
144 | b.putString("source", source);
145 | b.putStringArrayList("bssids", mWifiQuery);
146 | b.putStringArrayList("cells", mCellQuery);
147 | result.setExtras(b);
148 |
149 | if (plausibleLocationUpdate(result)) {
150 | setLastLocation(result);
151 | setLastFix(System.currentTimeMillis());
152 | mListener.onLocationReceived(result);
153 | } else {
154 | Log.i(TAG, "Strange location, ignoring");
155 | }
156 | } else {
157 | Log.w(TAG, "Server returned error, maybe not found / bad query?");
158 | }
159 | } catch (JSONException e) {
160 | Log.e(TAG, "Error parsing JSON:" + e.getMessage());
161 | }
162 | }
163 |
164 | private JSONObject queryServer(String url, ArrayList wifiParams, List cellParams) {
165 | // Creating JSON Parser instance
166 | JSONParser jParser = new JSONParser(mContext.getApplicationContext());
167 | JSONObject params = buildParams(wifiParams, cellParams);
168 | return jParser.getJSONFromUrl(url, params);
169 | }
170 |
171 | /**
172 | * Builds a JSON array with cell and wifi query
173 | * @param wifis bssids to query
174 | * @param cells cells to query
175 | * @return JSON object
176 | */
177 | private JSONObject buildParams(ArrayList wifis, List cells) {
178 | JSONObject root = new JSONObject();
179 | try {
180 | // add wifi objects
181 | JSONArray jsonArray = new JSONArray();
182 | for (String s : wifis) {
183 | JSONObject object = new JSONObject();
184 | object.put("macAddress", s);
185 | object.put("signalStrength", "-54");
186 | jsonArray.put(object);
187 | }
188 | if (jsonArray.length() > 0) {
189 | if (mDebug) {
190 | JSONObject object = new JSONObject();
191 | object.put("debug", "1");
192 | jsonArray.put(object);
193 | }
194 | root.put("wifiAccessPoints", jsonArray);
195 | }
196 |
197 | // add cell objects
198 | jsonArray = new JSONArray();
199 | for (Cell s : cells) {
200 | JSONObject object = new JSONObject();
201 | object.put("cellId", s.cellId);
202 | object.put("locationAreaCode", s.area);
203 | object.put("mobileCountryCode", s.mcc);
204 | object.put("mobileNetworkCode", s.mnc);
205 | jsonArray.put(object);
206 | }
207 | if (jsonArray.length() > 0) {
208 | root.put("cellTowers", jsonArray);
209 | }
210 | } catch (JSONException e) {
211 | e.printStackTrace();
212 | }
213 | Log.v(TAG, "Query param: " + root.toString());
214 | return root;
215 | }
216 | }.execute(wifis, cellsList);
217 | }
218 | }
--------------------------------------------------------------------------------
/src/org/radiocells/unifiedNlp/utils/SsidBlackListBootstraper.java:
--------------------------------------------------------------------------------
1 | /*
2 | Radiobeacon - Openbmap wifi and cell logger
3 | Copyright (C) 2013 wish7
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as
7 | published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 |
20 | package org.radiocells.unifiedNlp.utils;
21 |
22 | import android.util.Log;
23 |
24 | import java.io.BufferedWriter;
25 | import java.io.File;
26 | import java.io.FileWriter;
27 | import java.io.IOException;
28 |
29 | /**
30 | * Creates initial wifi blacklist with some default entries
31 | */
32 | public final class SsidBlackListBootstraper {
33 |
34 | private static final String TAG= SsidBlackListBootstraper.class.getSimpleName();
35 |
36 | /**
37 | * XML opening tag prefix
38 | */
39 | private static final String PREFIX_OPEN= "";
45 |
46 | /**
47 | * XML closing tag prefix
48 | */
49 | private static final String PREFIX_CLOSE = " ";
50 |
51 | /**
52 | * XML opening tag prefix
53 | */
54 | private static final String SUFFIX_OPEN= "";
60 |
61 | /**
62 | * XML closing tag prefix
63 | */
64 | private static final String SUFFIX_CLOSE = " ";
65 |
66 | /**
67 | *
68 | */
69 | private static final String START_TAG= "";
70 |
71 | /**
72 | *
73 | */
74 | private static final String END_TAG= " ";
75 |
76 | private static final String[][] PREFIXES = {
77 | {"default", "ASUS"},
78 | {"default", "Android Barnacle Wifi Tether"},
79 | {"default", "AndroidAP"},
80 | {"default", "AndroidTether"},
81 | {"default", "blackberry mobile hotspot"},
82 | {"default", "Clear Spot"},
83 | {"default", "ClearSpot"},
84 | {"default", "docomo"},
85 | {"Maintenance network on German ICE trains", "dr_I)p"},
86 | {"default", "Galaxy Note"},
87 | {"default", "Galaxy S"},
88 | {"default", "Galaxy Tab"},
89 | {"default", "HelloMoto"},
90 | {"default", "HTC "},
91 | {"default", "iDockUSA"},
92 | {"default", "iHub_"},
93 | {"default", "iPad"},
94 | {"default", "ipad"},
95 | {"default", "iPhone"},
96 | {"default", "LG VS910 4G"},
97 | {"default", "MIFI"},
98 | {"default", "MiFi"},
99 | {"default", "mifi"},
100 | {"default", "MOBILE"},
101 | {"default", "Mobile"},
102 | {"default", "mobile"},
103 | {"default", "myLGNet"},
104 | {"default", "myTouch 4G Hotspot"},
105 | {"default", "PhoneAP"},
106 | {"default", "SAMSUNG"},
107 | {"default", "Samsung"},
108 | {"default", "Sprint"},
109 | {"Long haul buses", "megabus-wifi"},
110 | {"German long haul buses", "DeinBus"},
111 | {"German long haul buses", "MeinFernbus"},
112 | {"German long haul buses", "adac_postbus"},
113 | {"German long haul buses", "flixbus"},
114 | {"Long haul buses", "eurolines"},
115 | {"Long haul buses", "ecolines"},
116 | {"Hurtigen lines", "guest@MS"},
117 | {"Hurtigen lines", "admin@MS"},
118 | {"German fast trains", "Telekom_ICE"},
119 | {"European fast trains", "thalysnet"},
120 | {"default", "Trimble "},
121 | {"default", "Verizon"},
122 | {"default", "VirginMobile"},
123 | {"default", "VTA Free Wi-Fi"},
124 | {"default", "webOS Network"},
125 | {"GoPro cams", "goprohero3"},
126 | {"Swiss Post Auto Wifi", "PostAuto"},
127 | {"Swiss Post Auto Wifi French", "CarPostal"},
128 | {"Swiss Post Auto Wifi Italian", "AutoPostale"},
129 |
130 | // mobile hotspots
131 | {"German 1und1 mobile hotspots", "1und1 mobile"},
132 | {"xperia tablet", "xperia tablet"},
133 | {"Sony devices", "XPERIA"},
134 | {"xperia tablet", "androidhotspot"},
135 | {"HP laptops", "HP envy"},
136 | {"empty ssid (not really hidden, just not broadcasting..)", ""},
137 |
138 |
139 | // some ssids from our friends at https://github.com/dougt/MozStumbler
140 | {"default", "ac_transit_wifi_bus"},
141 | {"Nazareen express transportation services (Israel)", "Afifi"},
142 | {"Oslo airport express train on-train WiFi (Norway)","AirportExpressZone"},
143 | {"default", "AmtrakConnect"},
144 | {"default", "amtrak_"},
145 | {"Arriva Nederland on-train Wifi (Netherlands)", "arriva"},
146 | {"Arcticbus on-bus WiFi (Sweden)","Arcticbus Wifi"},
147 | {"Swiss municipial busses on-bus WiFi (Italian speaking part)","AutoPostale"},
148 | {"Barcelona tourisitic buses http://barcelonabusturistic.cat","Barcelona Bus Turistic "},
149 | {"Tromso on-boat (and probably bus) WiFi (Norway)" ,"Boreal_Kundenett"},
150 | {"Bus4You on-bus WiFi (Norway)","Bus4You-"},
151 | {"Capital Bus on-bus WiFi (Taiwan)", "CapitalBus"},
152 | {"Swiss municipial busses on-bus WiFi (French speaking part)" ,"CarPostal"},
153 | {"Ceske drahy (Czech railways)", "CDWiFi"},
154 | {"Copenhagen S-Tog on-train WiFi: http://www.dsb.dk/s-tog/kampagner/fri-internet-i-s-tog" ,"CommuteNet"},
155 | {"CSAD Plzen","csadplzen_bus"},
156 | {"Egged transportation services (Israel)", "egged.co.il"},
157 | {"Empresa municipal de transportes de Madrid","EMT-Madrid"},
158 | {"First Bus wifi (United Kingdom)","first-wifi"},
159 | {"Oslo airport transportation on-bus WiFi (Norway)" ,"Flybussekspressen"},
160 | {"Airport transportation on-bus WiFi all over Norway (Norway)" ,"Flybussen"},
161 | {"Flygbussarna.se on-bus WiFi (Sweden)" ,"Flygbussarna Free WiFi"},
162 | {"GB Tours transportation services (Israel)", "gb-tours.com"},
163 | {"default", "GBUS"},
164 | {"default", "GBusWifi"},
165 | {"Gogo in-flight WiFi", "gogoinflight"},
166 | {"Koleje Slaskie transportation services (Poland)" ,"Hot-Spot-KS"},
167 | {"ISRAEL-RAILWAYS","ISRAEL-RAILWAYS"},
168 | {"Stavanger public transport on-boat WiFi (Norway)" ,"Kolumbus"},
169 | {"Kystbussen on-bus WiFi (Norway)" ,"Kystbussen_Kundennett"},
170 | {"Hungarian State Railways onboard hotspot on InterCity trains (Hungary)", "MAVSTART-WiFi"},
171 | {"Nateev Express transportation services (Israel)" ,"Nateev-WiFi"},
172 | {"National Express on-bus WiFi (United Kingdom)" ,"NationalExpress"},
173 | {"Norgesbuss on-bus WiFi (Norway)" ,"Norgesbuss"},
174 | {"Norwegian in-flight WiFi (Norway)" ,"Norwegian Internet Access"},
175 | {"NSB on-train WiFi (Norway)" ,"NSB_INTERAKTIV"},
176 | {"Omnibus transportation services (Israel)", "Omni-WiFi"},
177 | {"OnniBus.com Oy on-bus WiFi (Finland)" ,"onnibus.com"},
178 | {"Oxford Tube on-bus WiFi (United Kindom)" ,"Oxford Tube"},
179 | {"Swiss municipial busses on-bus WiFi (German speaking part)" ,"PostAuto"},
180 | {"Qbuzz on-bus WiFi (Netherlands)", "QbuzzWIFI"},
181 | {"default", "SF Shuttle Wireless"},
182 | {"default", "ShuttleWiFi"},
183 |
184 | {"Southwest Airlines in-flight WiFi", "Southwest WiFi"},
185 | {"default", "SST-PR-1"}, // Sears Home Service van hotspot?!
186 | {"Stagecoach on-bus WiFi (United Kingdom)" ,"stagecoach-wifi"},
187 |
188 | {"Taipei City on-bus WiFi (Taiwan)", "TPE-Free Bus"},
189 | {"Taiwan High Speed Rail on-train WiFi", "THSR-VeeTIME"},
190 | {"Triangle Transit on-bus WiFi" ,"TriangleTransitWiFi_"},
191 | {"Nederlandse Spoorwegen on-train WiFi by T-Mobile (Netherlands)", "tmobile"},
192 | {"Triangle Transit on-bus WiFi","TriangleTransitWiFi_"},
193 | {"VR on-train WiFi (Finland)", "VR-junaverkko"},
194 | {"Boreal on-bus WiFi (Norway)" ,"wifi@boreal.no"},
195 | {"Nettbuss on-bus WiFi (Norway)", "wifi@nettbuss.no"},
196 | {"BART", "wifi_rail"}
197 | };
198 |
199 | private static final String[][] SUFFIXES = {
200 | {"default", "MacBook"},
201 | {"default", "MacBook Pro"},
202 | {"default", "MiFi"},
203 | {"default", "MyWi"},
204 | {"default", "Tether"},
205 | {"default", "iPad"},
206 | {"default", "iPhone"},
207 | {"default", "ipad"},
208 | {"default", "iphone"},
209 | {"default", "tether"},
210 | {"default", "adhoc"},
211 | {"Google's SSID opt-out", "_nomap"}
212 | };
213 |
214 |
215 |
216 | public static void run(final String filename) {
217 | final File folder = new File(filename.substring(1, filename.lastIndexOf(File.separator)));
218 | boolean folderAccessible = false;
219 | if (folder.exists() && folder.canWrite()) {
220 | folderAccessible = true;
221 | }
222 |
223 | if (!folder.exists()) {
224 | Log.i(TAG, "Folder missing: create " + folder.getAbsolutePath());
225 | folderAccessible = folder.mkdirs();
226 | }
227 |
228 | if (folderAccessible) {
229 | final StringBuilder sb = new StringBuilder();
230 | sb.append(START_TAG);
231 | for (final String[] prefix : PREFIXES) {
232 | sb.append(PREFIX_OPEN).append(prefix[0]).append(PREFIX_MIDDLE).append(prefix[1]).append(PREFIX_CLOSE);
233 | }
234 |
235 | for (final String[] suffix : SUFFIXES) {
236 | sb.append(SUFFIX_OPEN).append(suffix[0]).append(SUFFIX_MIDDLE).append(suffix[1]).append(SUFFIX_CLOSE);
237 | }
238 | sb.append(END_TAG);
239 |
240 | try {
241 | final File file = new File(filename);
242 | final BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
243 | bw.append(sb);
244 | bw.close();
245 | Log.i(TAG, "Created default blacklist, " + PREFIXES.length + SUFFIXES.length + " entries");
246 | } catch (final IOException e) {
247 | Log.e(TAG, "Error writing blacklist");
248 | }
249 | } else {
250 | Log.e(TAG, "Folder not accessible: can't write blacklist");
251 | }
252 |
253 | }
254 |
255 | private SsidBlackListBootstraper() {
256 | }
257 | }
258 |
--------------------------------------------------------------------------------
/src/org/radiocells/unifiedNlp/utils/DirectoryChooserDialog.java:
--------------------------------------------------------------------------------
1 | package org.radiocells.unifiedNlp.utils;
2 | /*
3 | * Gregory Shpitalnik
4 | * http://www.codeproject.com/Articles/547636/Android-Ready-to-use-simple-directory-chooser-dial?msg=4923192#xx4923192xx
5 | */
6 |
7 | import android.app.AlertDialog;
8 | import android.content.Context;
9 | import android.content.DialogInterface;
10 | import android.content.DialogInterface.OnClickListener;
11 | import android.content.DialogInterface.OnKeyListener;
12 | import android.os.Environment;
13 | import android.text.Editable;
14 | import android.util.Log;
15 | import android.view.Gravity;
16 | import android.view.KeyEvent;
17 | import android.view.View;
18 | import android.view.ViewGroup;
19 | import android.view.ViewGroup.LayoutParams;
20 | import android.widget.ArrayAdapter;
21 | import android.widget.Button;
22 | import android.widget.EditText;
23 | import android.widget.LinearLayout;
24 | import android.widget.TextView;
25 | import android.widget.Toast;
26 |
27 | import androidx.annotation.NonNull;
28 |
29 | import org.radiocells.unifiedNlp.R;
30 |
31 | import java.io.File;
32 | import java.util.ArrayList;
33 | import java.util.Collections;
34 | import java.util.Comparator;
35 | import java.util.List;
36 |
37 | public class DirectoryChooserDialog {
38 | private static final String TAG = DirectoryChooserDialog.class.getSimpleName();
39 | private boolean mIsNewFolderEnabled = true;
40 | private String mSdcardDirectory;
41 | private Context mContext;
42 | private TextView mTitleView;
43 | private TextView mSubtitleView;
44 |
45 | private String mDir = "";
46 | private List mSubdirs = null;
47 | private ChosenDirectoryListener mChosenDirectoryListener;
48 | private ArrayAdapter mListAdapter = null;
49 |
50 | public DirectoryChooserDialog(Context context, ChosenDirectoryListener chosenDirectoryListener) {
51 | mContext = context;
52 | mSdcardDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath()).getAbsolutePath();
53 | mChosenDirectoryListener = chosenDirectoryListener;
54 | }
55 |
56 | public boolean getNewFolderEnabled() {
57 | return mIsNewFolderEnabled;
58 | }
59 |
60 | /**
61 | * enable/disable new folder button
62 | */
63 | public void setNewFolderEnabled(boolean isNewFolderEnabled) {
64 | mIsNewFolderEnabled = isNewFolderEnabled;
65 | }
66 |
67 | /**
68 | * chooseDirectory() - load directory chooser dialog for initial default sdcard directory
69 | */
70 | public void chooseDirectory() {
71 | // Initial directory is sdcard directory
72 | chooseDirectory(mSdcardDirectory);
73 | }
74 |
75 | /**
76 | * chooseDirectory(String dir) - load directory chooser dialog for initial input 'dir' directory
77 | */
78 | public void chooseDirectory(String dir) {
79 | File dirFile = new File(dir);
80 | if (!dirFile.exists() || !dirFile.isDirectory()) {
81 | dir = mSdcardDirectory;
82 | }
83 |
84 | dir = new File(dir).getAbsolutePath();
85 |
86 | mDir = dir;
87 | mSubdirs = getDirectories(dir);
88 |
89 | class DirectoryOnClickListener implements DialogInterface.OnClickListener {
90 | public void onClick(DialogInterface dialog, int item) {
91 | // handle folder up clicks
92 | if (((AlertDialog) dialog).getListView().getAdapter().getItem(item).equals("..")) {
93 | // handle '..' (directory up) clicks
94 | mDir = mDir.substring(0, mDir.lastIndexOf("/"));
95 | } else {
96 | // otherwise descend into sub-directory
97 | mDir += "/" + ((AlertDialog) dialog).getListView().getAdapter().getItem(item);
98 | }
99 | updateDirectory();
100 | }
101 | }
102 |
103 | AlertDialog.Builder dialogBuilder =
104 | createDirectoryChooserDialog("Select folder", dir, mSubdirs, new DirectoryOnClickListener());
105 |
106 | dialogBuilder.setPositiveButton("OK", new OnClickListener() {
107 | @Override
108 | public void onClick(DialogInterface dialog, int which) {
109 | // Current directory chosen
110 | if (mChosenDirectoryListener != null) {
111 | // Call registered listener supplied with the chosen directory
112 | mChosenDirectoryListener.onChosenDir(mDir);
113 | }
114 | }
115 | }).setNegativeButton("Cancel", null);
116 |
117 | final AlertDialog dirsDialog = dialogBuilder.create();
118 |
119 | dirsDialog.setOnKeyListener(new OnKeyListener() {
120 | @Override
121 | public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
122 | if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
123 | // Back button pressed
124 | if (mDir.equals(mSdcardDirectory)) {
125 | // The very top level directory, do nothing
126 | return false;
127 | } else {
128 | // Navigate back to an upper directory
129 | mDir = new File(mDir).getParent();
130 | updateDirectory();
131 | }
132 |
133 | return true;
134 | } else {
135 | return false;
136 | }
137 | }
138 | });
139 |
140 | // Show directory chooser dialog
141 | dirsDialog.show();
142 | }
143 |
144 | private boolean createSubDir(String newDir) {
145 | File newDirFile = new File(newDir);
146 | if (!newDirFile.exists()) {
147 | return newDirFile.mkdir();
148 | }
149 |
150 | return false;
151 | }
152 |
153 | private List getDirectories(String dir) {
154 | List dirs = new ArrayList<>();
155 | dirs.add("..");
156 | try {
157 | File dirFile = new File(dir);
158 | if (!dirFile.exists() || !dirFile.isDirectory()) {
159 | return dirs;
160 | }
161 |
162 | for (File file : dirFile.listFiles()) {
163 | if (file.isDirectory()) {
164 | dirs.add(file.getName());
165 | }
166 | }
167 | } catch (Exception e) {
168 | Log.e(TAG, "Error listing directory");
169 | }
170 |
171 | Collections.sort(dirs, new Comparator() {
172 | public int compare(String o1, String o2) {
173 | return o1.compareTo(o2);
174 | }
175 | });
176 |
177 | return dirs;
178 | }
179 |
180 | private AlertDialog.Builder createDirectoryChooserDialog(String title, String subtitle, List listItems,
181 | DialogInterface.OnClickListener onClickListener) {
182 | AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
183 |
184 | // Create custom view for AlertDialog title containing
185 | // current directory TextView and possible 'New folder' button.
186 | // Current directory TextView allows long directory path to be wrapped to multiple lines.
187 | LinearLayout titleLayout = new LinearLayout(mContext);
188 | titleLayout.setOrientation(LinearLayout.VERTICAL);
189 |
190 | mTitleView = new TextView(mContext);
191 | mTitleView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
192 | mTitleView.setTextAppearance(mContext, android.R.style.TextAppearance_Large);
193 | mTitleView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
194 | mTitleView.setText(title);
195 |
196 | mSubtitleView = new TextView(mContext);
197 | mSubtitleView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
198 | mSubtitleView.setTextAppearance(mContext, android.R.style.TextAppearance_Large);
199 | mSubtitleView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
200 | mSubtitleView.setTextAppearance(mContext, android.R.style.TextAppearance_Small);
201 | mSubtitleView.setText(subtitle);
202 |
203 | Button newDirButton = new Button(mContext);
204 | newDirButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
205 | newDirButton.setText(R.string.new_folder);
206 | newDirButton.setOnClickListener(new View.OnClickListener() {
207 | @Override
208 | public void onClick(View v) {
209 | final EditText input = new EditText(mContext);
210 |
211 | // Show new folder name input dialog
212 | new AlertDialog.Builder(mContext).
213 | setTitle("New folder name").
214 | setView(input).setPositiveButton("OK", new DialogInterface.OnClickListener() {
215 | public void onClick(DialogInterface dialog, int whichButton) {
216 | Editable newDir = input.getText();
217 | String newDirName = newDir.toString();
218 | // Create new directory
219 | if (createSubDir(mDir + "/" + newDirName)) {
220 | // Navigate into the new directory
221 | mDir += "/" + newDirName;
222 | updateDirectory();
223 | } else {
224 | Toast.makeText(
225 | mContext, "Failed to create '" + newDirName +
226 | "' folder", Toast.LENGTH_SHORT).show();
227 | }
228 | }
229 | }).setNegativeButton("Cancel", null).show();
230 | }
231 | });
232 |
233 | if (!mIsNewFolderEnabled) {
234 | newDirButton.setVisibility(View.GONE);
235 | }
236 |
237 | titleLayout.addView(mTitleView);
238 | titleLayout.addView(mSubtitleView);
239 | titleLayout.addView(newDirButton);
240 |
241 | dialogBuilder.setCustomTitle(titleLayout);
242 |
243 | mListAdapter = createListAdapter(listItems);
244 |
245 | dialogBuilder.setSingleChoiceItems(mListAdapter, -1, onClickListener);
246 | dialogBuilder.setCancelable(false);
247 |
248 | return dialogBuilder;
249 | }
250 |
251 | private void updateDirectory() {
252 | mSubdirs.clear();
253 | mSubdirs.addAll(getDirectories(mDir));
254 | mSubtitleView.setText(mDir);
255 |
256 | mListAdapter.notifyDataSetChanged();
257 | }
258 |
259 | private ArrayAdapter createListAdapter(List items) {
260 | return new ArrayAdapter(mContext,
261 | android.R.layout.select_dialog_item, android.R.id.text1, items) {
262 | @NonNull
263 | @Override
264 | public View getView(int position, View convertView,
265 | @NonNull ViewGroup parent) {
266 | View v = super.getView(position, convertView, parent);
267 |
268 | if (v instanceof TextView) {
269 | // Enable list item (directory) text wrapping
270 | TextView tv = (TextView) v;
271 | tv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
272 | tv.setEllipsize(null);
273 | }
274 | return v;
275 | }
276 | };
277 | }
278 |
279 | /*
280 | * Callback interface for selected directory
281 | */
282 | public interface ChosenDirectoryListener {
283 | void onChosenDir(String chosenDir);
284 | }
285 | }
--------------------------------------------------------------------------------
/src/org/radiocells/unifiedNlp/services/RadiocellsLocationService.java:
--------------------------------------------------------------------------------
1 | /*
2 | Radiobeacon - Openbmap Unified Network Location Provider
3 | Copyright (C) 2013 wish7
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as
7 | published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 | package org.radiocells.unifiedNlp.services;
19 |
20 | import android.Manifest;
21 | import android.content.BroadcastReceiver;
22 | import android.content.Context;
23 | import android.content.Intent;
24 | import android.content.IntentFilter;
25 | import android.content.pm.PackageManager;
26 | import android.location.Location;
27 | import android.net.wifi.ScanResult;
28 | import android.net.wifi.WifiManager;
29 | import android.net.wifi.WifiManager.WifiLock;
30 | import android.os.Build;
31 | import android.os.Handler;
32 | import android.preference.PreferenceManager;
33 | import android.telephony.CellInfo;
34 | import android.telephony.CellInfoCdma;
35 | import android.telephony.CellInfoGsm;
36 | import android.telephony.CellInfoLte;
37 | import android.telephony.CellInfoWcdma;
38 | import android.telephony.CellLocation;
39 | import android.telephony.TelephonyManager;
40 | import android.telephony.cdma.CdmaCellLocation;
41 | import android.telephony.gsm.GsmCellLocation;
42 | import android.util.Log;
43 |
44 | import androidx.core.content.ContextCompat;
45 |
46 | import org.microg.nlp.api.LocationBackendService;
47 | import org.radiocells.unifiedNlp.Preferences;
48 | import org.radiocells.unifiedNlp.R;
49 | import org.radiocells.unifiedNlp.UnifiedNlpApplication;
50 | import org.radiocells.unifiedNlp.geocoders.ILocationCallback;
51 | import org.radiocells.unifiedNlp.geocoders.ILocationProvider;
52 | import org.radiocells.unifiedNlp.geocoders.OfflineProvider;
53 | import org.radiocells.unifiedNlp.geocoders.OnlineProvider;
54 | import org.radiocells.unifiedNlp.models.Cell;
55 | import org.radiocells.unifiedNlp.utils.PermissionHelper;
56 |
57 | import java.util.ArrayList;
58 | import java.util.Calendar;
59 | import java.util.Collections;
60 | import java.util.HashMap;
61 | import java.util.List;
62 | import java.util.Map;
63 |
64 |
65 | public class RadiocellsLocationService extends LocationBackendService implements ILocationCallback {
66 | private static final String TAG = RadiocellsLocationService.class.getName();
67 |
68 | /**
69 | * Minimum interval between two queries
70 | * Please obey to this limit, you might kill the server otherwise
71 | */
72 | protected static final long ONLINE_REFRESH_INTERVAL = 5000;
73 |
74 | protected static final long OFFLINE_REFRESH_INTERVAL = 2000;
75 | private static final int REQ_CODE = 121212;
76 |
77 | /**
78 | * If true, online geolocation service is used
79 | */
80 | private boolean mOnlineMode;
81 |
82 | /**
83 | * If true, scan results are broadcasted for diagnostic app
84 | */
85 | private boolean mDebug;
86 |
87 | private Location last;
88 |
89 | /**
90 | * Phone state listeners to receive cell updates
91 | */
92 | private TelephonyManager mTelephonyManager;
93 |
94 | private WifiLock mWifiLock;
95 |
96 | /**
97 | * Wifi listeners to receive wifi updates
98 | */
99 | private WifiManager wifiManager;
100 |
101 | private boolean scanning;
102 |
103 | private Calendar nextScanningAllowedFrom;
104 |
105 | private ILocationProvider mGeocoder;
106 |
107 | /**
108 | * Time of last geolocation request (millis)
109 | */
110 | private long lastFix;
111 |
112 | private WifiScanCallback mWifiScanResults;
113 |
114 | /**
115 | * Receives location updates as well as wifi scan result updates
116 | */
117 | private BroadcastReceiver mReceiver = new BroadcastReceiver() {
118 |
119 | @Override
120 | public void onReceive(final Context context, final Intent intent) {
121 | // handling wifi scan results
122 | if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
123 | //Log.d(TAG, "Wifi manager signals wifi scan results.");
124 | // scan callback can be null after service has been stopped or another app has requested an update
125 | if (mWifiScanResults != null) {
126 | mWifiScanResults.onWifiResultsAvailable();
127 | } else {
128 | Log.i(TAG, "Scan Callback is null, skipping message");
129 | }
130 | }
131 | }
132 | };
133 |
134 | public static Map TECHNOLOGY_MAP() {
135 | final Map result = new HashMap<>();
136 | result.put(TelephonyManager.NETWORK_TYPE_UNKNOWN, "NA");
137 | // GPRS shall be mapped to "GSM"
138 | result.put(TelephonyManager.NETWORK_TYPE_GPRS, "GSM");
139 | result.put(TelephonyManager.NETWORK_TYPE_EDGE, "EDGE");
140 | result.put(TelephonyManager.NETWORK_TYPE_UMTS, "UMTS");
141 | result.put(TelephonyManager.NETWORK_TYPE_CDMA, "CDMA");
142 | result.put(TelephonyManager.NETWORK_TYPE_EVDO_0, "EDVO_0");
143 | result.put(TelephonyManager.NETWORK_TYPE_EVDO_A, "EDVO_A");
144 | result.put(TelephonyManager.NETWORK_TYPE_1xRTT, "1xRTT");
145 |
146 | result.put(TelephonyManager.NETWORK_TYPE_HSDPA, "HSDPA");
147 | result.put(TelephonyManager.NETWORK_TYPE_HSUPA, "HSUPA");
148 | result.put(TelephonyManager.NETWORK_TYPE_HSPA, "HSPA");
149 | result.put(TelephonyManager.NETWORK_TYPE_IDEN, "IDEN");
150 |
151 | // add new network types not available in all revisions
152 | result.put(TelephonyManager.NETWORK_TYPE_EVDO_B, "EDV0_B");
153 | result.put(TelephonyManager.NETWORK_TYPE_LTE, "LTE");
154 | result.put(TelephonyManager.NETWORK_TYPE_EHRPD, "eHRPD");
155 | result.put(TelephonyManager.NETWORK_TYPE_HSPAP, "HSPA+");
156 |
157 | return Collections.unmodifiableMap(result);
158 | }
159 |
160 | @Override
161 | protected void onOpen() {
162 | Log.i(TAG, "Opening " + TAG);
163 |
164 | wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
165 |
166 | mWifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "SCAN_LOCK");
167 | if (!mWifiLock.isHeld()) {
168 | mWifiLock.acquire();
169 | }
170 |
171 | registerReceiver(mReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
172 | mTelephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
173 |
174 | Log.d(TAG, "[Config] Debug Mode: " + PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Preferences.KEY_DEBUG_MESSAGES, Preferences.VAL_DEBUG_MESSAGES));
175 | mDebug = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Preferences.KEY_DEBUG_MESSAGES, Preferences.VAL_DEBUG_MESSAGES);
176 |
177 | Log.d(TAG, "[Config] Operation Mode: " + PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_OPERATION_MODE, Preferences.VAL_OPERATION_MODE));
178 | mOnlineMode = PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_OPERATION_MODE, Preferences.VAL_OPERATION_MODE).equals("online");
179 | }
180 |
181 | @Override
182 | protected void onClose() {
183 | if (mWifiLock != null) {
184 | if (mWifiLock.isHeld()) {
185 | mWifiLock.release();
186 | mWifiLock = null;
187 | }
188 | }
189 |
190 | unregisterReceiver(mReceiver);
191 | wifiManager = null;
192 | }
193 |
194 | Handler timerHandler = new Handler();
195 | Runnable timerRunnable = new Runnable() {
196 |
197 | @Override
198 | public void run() {
199 | if (nextScanningAllowedFrom == null) {
200 | return;
201 | }
202 | nextScanningAllowedFrom = null;
203 | getLocationFromWifisAndCells(new ArrayList());
204 | }
205 | };
206 |
207 | @Override
208 | protected Location update() {
209 | Calendar now = Calendar.getInstance();
210 |
211 | if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
212 | Log.d(TAG, "Fine location access available");
213 | } else {
214 | Log.i(TAG, "Missing fine location access - requesting");
215 | PermissionHelper.requestPermissions(
216 | (UnifiedNlpApplication) (getApplicationContext()),
217 | new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
218 | 1212,
219 | "Permission needed",
220 | "Location access is needed for radiocells.org UnifiedNLP backend",
221 | R.drawable.ic_launcher);
222 | return null;
223 | }
224 | if ((nextScanningAllowedFrom != null) && (nextScanningAllowedFrom.after(now))) {
225 | Log.d(TAG, "Another scan is taking place");
226 | return null;
227 | }
228 |
229 | if (mGeocoder == null) {
230 | if (mOnlineMode) {
231 | Log.i(TAG, "Using online geocoder");
232 | mGeocoder = new OnlineProvider(this, this, mDebug);
233 | } else {
234 | Log.i(TAG, "Using offline geocoder");
235 | mGeocoder = new OfflineProvider(this, this);
236 | }
237 | }
238 | if (isWifiSupported() && isWifisSourceSelected()) {
239 | Log.v(TAG, "Scanning wifis");
240 | if (nextScanningAllowedFrom == null) {
241 | scanning = wifiManager.startScan();
242 | nextScanningAllowedFrom = Calendar.getInstance();
243 | nextScanningAllowedFrom.add(Calendar.SECOND, 10);
244 | timerHandler.postDelayed(timerRunnable, 20000);
245 | }
246 |
247 | /**
248 | * Processes scan results and sends query to geocoding service
249 | */
250 | if (mWifiScanResults == null) {
251 | mWifiScanResults = new WifiScanCallback() {
252 |
253 | @Override
254 | public void onWifiResultsAvailable() {
255 | //Log.d(TAG, "Wifi results are available now.");
256 | nextScanningAllowedFrom = null;
257 | timerHandler.removeCallbacks(timerRunnable);
258 | if (scanning) {
259 | // TODO pass wifi signal strength to geocoder
260 | //Log.i(TAG, "Wifi scan results arrived..");
261 | List scans = wifiManager.getScanResults();
262 |
263 | if (scans == null)
264 | // @see http://code.google.com/p/android/issues/detail?id=19078
265 | Log.e(TAG, "WifiManager.getScanResults returned null");
266 |
267 | getLocationFromWifisAndCells(scans);
268 | }
269 | scanning = false;
270 | }
271 | };
272 | }
273 | } else if (isCellsSourceSelected()) {
274 | Log.d(TAG, "Scanning cells only");
275 | getLocationFromWifisAndCells(null);
276 | } else {
277 | Log.e(TAG, "Neigther cells nor wifis as source selected? Com'on..");
278 | }
279 |
280 | return null;
281 | }
282 |
283 | private void getLocationFromWifisAndCells(List scans) {
284 | final long passed = System.currentTimeMillis() - lastFix;
285 | final boolean ok_online = (mOnlineMode && (passed > ONLINE_REFRESH_INTERVAL) || lastFix == 0);
286 | final boolean ok_offline = (!mOnlineMode && (passed > OFFLINE_REFRESH_INTERVAL) || lastFix == 0);
287 |
288 | if (ok_online || ok_offline) {
289 | Log.d(TAG, "Scanning wifis & cells");
290 | lastFix = System.currentTimeMillis();
291 |
292 | List cells = new ArrayList<>();
293 | // if in combined mode also query cell information, otherwise pass empty list
294 | if (isCellsSourceSelected()) {
295 | cells = getCells();
296 | }
297 | if (mGeocoder != null) {
298 | mGeocoder.getLocation(scans, cells);
299 | } else {
300 | Log.e(TAG, "Geocoder is null!");
301 | }
302 | } else {
303 | Log.v(TAG, "Too frequent requests.. Skipping geolocation update..");
304 | }
305 | }
306 |
307 | /**
308 | * Checks whether user has selected wifis as geolocation source in settings
309 | *
310 | * @return true if source wifis or combined has been chosen
311 | */
312 | private boolean isWifisSourceSelected() {
313 | final String source = PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_SOURCE, Preferences.VAL_SOURCE);
314 | return (source.equals(Preferences.SOURCE_WIFIS)) || (source.equals(Preferences.SOURCE_COMBINED));
315 | }
316 |
317 | /**
318 | * Checks whether user has selected wifis as geolocation source in settings
319 | *
320 | * @return true if source cells or combined has been chosen
321 | */
322 | private boolean isCellsSourceSelected() {
323 | final String source = PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_SOURCE, Preferences.VAL_SOURCE);
324 | return (source.equals(Preferences.SOURCE_CELLS)) || (source.equals(Preferences.SOURCE_COMBINED));
325 | }
326 |
327 | /**
328 | * Returns cells phone is currently connected to
329 | *
330 | * @return list of cells
331 | */
332 | private List getCells() {
333 | List cells = new ArrayList<>();
334 |
335 | String operator = mTelephonyManager.getNetworkOperator();
336 | String mnc;
337 | int mcc;
338 |
339 | // getNetworkOperator() may return empty string, probably due to dropped connection
340 | if (operator != null && operator.length() > 3) {
341 | mcc = Integer.valueOf(operator.substring(0, 3));
342 | mnc = operator.substring(3);
343 | } else {
344 | Log.e(TAG, "Error retrieving network operator, skipping cell");
345 | mcc = 0;
346 | mnc = "";
347 | }
348 |
349 | CellLocation cellLocation = mTelephonyManager.getCellLocation();
350 |
351 | if (cellLocation != null) {
352 | if (cellLocation instanceof GsmCellLocation) {
353 | Cell cell = new Cell();
354 | cell.cellId = ((GsmCellLocation) cellLocation).getCid();
355 | cell.area = ((GsmCellLocation) cellLocation).getLac();
356 | cell.mcc = mcc;
357 | cell.mnc = mnc;
358 | cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType());
359 | Log.d(TAG, String.format("GsmCellLocation for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((GsmCellLocation) cellLocation).getPsc()));
360 | cells.add(cell);
361 | } else if (cellLocation instanceof CdmaCellLocation) {
362 | Log.w(TAG, "CdmaCellLocation: Using CDMA cells for NLP is not yet implemented");
363 | } else
364 | Log.wtf(TAG, "Got a CellLocation of an unknown class");
365 | } else {
366 | Log.d(TAG, "getCellLocation returned null");
367 | }
368 |
369 | List cellsRawList = mTelephonyManager.getAllCellInfo();
370 | if (cellsRawList != null) {
371 | Log.d(TAG, "getAllCellInfo found " + cellsRawList.size() + " cells");
372 | } else {
373 | Log.d(TAG, "getAllCellInfo returned null");
374 | }
375 |
376 | if (cellsRawList != null) {
377 | for (CellInfo c : cellsRawList) {
378 | Cell cell = new Cell();
379 | if (c instanceof CellInfoGsm) {
380 | //Log.v(TAG, "GSM cell found");
381 | cell.cellId = ((CellInfoGsm) c).getCellIdentity().getCid();
382 | cell.area = ((CellInfoGsm) c).getCellIdentity().getLac();
383 | cell.mcc = ((CellInfoGsm) c).getCellIdentity().getMcc();
384 | cell.mnc = String.valueOf(((CellInfoGsm) c).getCellIdentity().getMnc());
385 | cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType());
386 | Log.d(TAG, String.format("CellInfoGsm for %d|%s|%d|%d|%s", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology));
387 | } else if (c instanceof CellInfoCdma) {
388 | /*
389 | object.put("cellId", ((CellInfoCdma)s).getCellIdentity().getBasestationId());
390 | object.put("locationAreaCode", ((CellInfoCdma)s).getCellIdentity().getLac());
391 | object.put("mobileCountryCode", ((CellInfoCdma)s).getCellIdentity().get());
392 | object.put("mobileNetworkCode", ((CellInfoCdma)s).getCellIdentity().getMnc());*/
393 | Log.wtf(TAG, "Using of CDMA cells for NLP not yet implemented");
394 | } else if (c instanceof CellInfoLte) {
395 | //Log.v(TAG, "LTE cell found");
396 | cell.cellId = ((CellInfoLte) c).getCellIdentity().getCi();
397 | cell.area = ((CellInfoLte) c).getCellIdentity().getTac();
398 | cell.mcc = ((CellInfoLte) c).getCellIdentity().getMcc();
399 | cell.mnc = String.valueOf(((CellInfoLte) c).getCellIdentity().getMnc());
400 | cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType());
401 | Log.d(TAG, String.format("CellInfoLte for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoLte) c).getCellIdentity().getPci()));
402 | } else if (c instanceof CellInfoWcdma) {
403 | //Log.v(TAG, "CellInfoWcdma cell found");
404 | cell.cellId = ((CellInfoWcdma) c).getCellIdentity().getCid();
405 | cell.area = ((CellInfoWcdma) c).getCellIdentity().getLac();
406 | cell.mcc = ((CellInfoWcdma) c).getCellIdentity().getMcc();
407 | cell.mnc = String.valueOf(((CellInfoWcdma) c).getCellIdentity().getMnc());
408 | cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType());
409 | Log.d(TAG, String.format("CellInfoWcdma for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoWcdma) c).getCellIdentity().getPsc()));
410 | }
411 | cells.add(cell);
412 | }
413 | }
414 | return cells;
415 | }
416 |
417 | /**
418 | * Checks whether we can scan wifis
419 | *
420 | * @return true if wifi is enabled or background scanning allowed
421 | */
422 | public boolean isWifiSupported() {
423 | return ((wifiManager != null) && (wifiManager.isWifiEnabled() || ((Build.VERSION.SDK_INT >= 18) &&
424 | wifiManager.isScanAlwaysAvailable())));
425 | }
426 |
427 | /**
428 | * Callback when new location is available
429 | *
430 | * @param location
431 | * @return
432 | */
433 | @Override
434 | public Location onLocationReceived(Location location) {
435 | if (location == null) {
436 | Log.i(TAG, "Location was null, ignoring");
437 | return null;
438 | }
439 |
440 | if (mDebug) {
441 | Log.d(TAG, "[UnifiedNlp Results]: " + location.getExtras().toString());
442 |
443 | if (last != null) {
444 | Log.d(TAG, "[UnifiedNlp Results]: Est. Speed " + Math.round(location.distanceTo(last) / (location.getTime() - last.getTime() / 1000 / 60)) + " km/h");
445 | }
446 | }
447 |
448 | report(location);
449 |
450 | last = location;
451 | return location;
452 | }
453 | }
--------------------------------------------------------------------------------
/src/org/radiocells/unifiedNlp/SettingsActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | Radiobeacon - Openbmap Unified Network Location Provider
3 | Copyright (C) 2013 wish7
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as
7 | published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 | package org.radiocells.unifiedNlp;
19 |
20 | import android.app.AlertDialog;
21 | import android.app.DownloadManager;
22 | import android.content.BroadcastReceiver;
23 | import android.content.Context;
24 | import android.content.DialogInterface;
25 | import android.content.Intent;
26 | import android.content.IntentFilter;
27 | import android.content.SharedPreferences;
28 | import android.content.pm.PackageManager;
29 | import android.database.Cursor;
30 | import android.net.Uri;
31 | import android.os.Bundle;
32 | import android.preference.ListPreference;
33 | import android.preference.Preference;
34 | import android.preference.Preference.OnPreferenceChangeListener;
35 | import android.preference.PreferenceActivity;
36 | import android.preference.PreferenceManager;
37 | import android.util.Log;
38 | import android.widget.Toast;
39 |
40 | import org.radiocells.unifiedNlp.utils.DirectoryChooserDialog;
41 | import org.radiocells.unifiedNlp.utils.FileHelpers;
42 | import org.radiocells.unifiedNlp.utils.MediaScanner;
43 |
44 | import java.io.ByteArrayOutputStream;
45 | import java.io.File;
46 | import java.io.FilenameFilter;
47 | import java.io.IOException;
48 | import java.io.InputStream;
49 |
50 | /**
51 | * Preferences activity.
52 | */
53 | public class SettingsActivity extends PreferenceActivity implements ICatalogChooser {
54 |
55 | private static final String TAG = SettingsActivity.class.getSimpleName();
56 |
57 | private DownloadManager mDownloadManager;
58 | private BroadcastReceiver mReceiver = null;
59 |
60 | @Override
61 | protected final void onCreate(final Bundle savedInstanceState) {
62 | super.onCreate(savedInstanceState);
63 | addPreferencesFromResource(R.xml.preferences);
64 |
65 | registerDownloadManager();
66 |
67 | initFolderChooser();
68 |
69 | refreshCatalogList(PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_DATA_FOLDER, this.getExternalFilesDir(null).getAbsolutePath()));
70 |
71 | initOperationModeChooser();
72 | initSourceChooser();
73 |
74 | Log.d(TAG, "Selected wifi catalog: " + getSelectedCatalog());
75 | if (getSelectedCatalog().equals(Preferences.CATALOG_NONE)) {
76 | AlertDialog.Builder builder = new AlertDialog.Builder(this);
77 | builder.setMessage(getString(R.string.question_download_catalog));
78 | builder.setTitle(getString(R.string.offline_catalog_n_a));
79 | // Add the buttons
80 | builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
81 | public void onClick(DialogInterface dialog, int id) {
82 | showCatalogDownloadDialog();
83 | }
84 | });
85 | builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
86 | public void onClick(DialogInterface dialog, int id) {
87 | Preference pref = findPreference(Preferences.KEY_OPERATION_MODE);
88 | pref.getEditor().putString(Preferences.KEY_OPERATION_MODE, Preferences.OPERATION_MODE_ONLINE).apply();
89 | Toast.makeText(SettingsActivity.this, getString(R.string.using_online_mode), Toast.LENGTH_LONG).show();
90 | }
91 | });
92 |
93 | AlertDialog dialog = builder.create();
94 | dialog.show();
95 | }
96 |
97 | Preference pref = findPreference(Preferences.KEY_VERSION_INFO);
98 | String version = "n/a";
99 | try {
100 | version = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
101 | } catch (PackageManager.NameNotFoundException e) {
102 | e.printStackTrace();
103 | }
104 | pref.setSummary(version + " (" + readBuildInfo() + ")");
105 | }
106 |
107 | @Override
108 | public void onResume() {
109 | super.onResume();
110 | registerDownloadManager();
111 | }
112 |
113 |
114 | @Override
115 | protected final void onDestroy() {
116 | if (mReceiver != null) {
117 | unregisterReceiver(mReceiver);
118 | }
119 | super.onDestroy();
120 | }
121 |
122 | private void showCatalogDownloadDialog() {
123 | DialogPreferenceCatalogs catalogs = (DialogPreferenceCatalogs) findPreference(Preferences.KEY_CATALOGS_DIALOG);
124 | catalogs.showDialog(null);
125 | }
126 |
127 | private String getSelectedCatalog() {
128 | return PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_OFFLINE_CATALOG_FILE, Preferences.CATALOG_NONE);
129 | }
130 |
131 | private String getSelectedOperationMode() {
132 | return PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_OPERATION_MODE, Preferences.OPERATION_MODE_OFFLINE);
133 | }
134 |
135 | /**
136 | * Initializes data directory preference.
137 | */
138 | private void initFolderChooser() {
139 | Preference button = findPreference("data.dir");
140 | button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
141 | private String mChosenDir = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this).getString(Preferences.KEY_DATA_FOLDER,
142 | SettingsActivity.this.getExternalFilesDir(null).getAbsolutePath());
143 |
144 | @Override
145 | public boolean onPreferenceClick(Preference arg0) {
146 | DirectoryChooserDialog directoryChooserDialog =
147 | new DirectoryChooserDialog(SettingsActivity.this, new DirectoryChooserDialog.ChosenDirectoryListener() {
148 | @Override
149 | public void onChosenDir(String folder) {
150 | mChosenDir = folder;
151 | SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);
152 | settings.edit().putString("data.dir", folder).apply();
153 |
154 | // Rescan folder, in case user has copy file manually
155 | MediaScanner m = new MediaScanner(SettingsActivity.this, new File(mChosenDir));
156 | refreshCatalogList(folder);
157 | Toast.makeText(SettingsActivity.this, folder, Toast.LENGTH_LONG).show();
158 | }
159 | });
160 | directoryChooserDialog.setNewFolderEnabled(false);
161 | directoryChooserDialog.chooseDirectory(mChosenDir);
162 | return true;
163 | }
164 | });
165 | }
166 |
167 | /**
168 | * Populates the wifi catalog list preference by scanning catalog folder.
169 | * @param catalogFolder Root folder for WIFI_CATALOG_SUBDIR
170 | */
171 | private void refreshCatalogList(final String catalogFolder) {
172 | String[] entries;
173 | String[] values;
174 |
175 | // rescan
176 | new MediaScanner(this, new File(catalogFolder));
177 |
178 | // Check for presence of database directory
179 | File folder = new File(catalogFolder);
180 | if (folder.exists() && folder.canRead()) {
181 | // List each map file
182 | String[] dbFiles = folder.list(new FilenameFilter() {
183 | @Override
184 | public boolean accept(final File dir, final String filename) {
185 | return filename.endsWith(Preferences.CATALOG_FILE_EXTENSION);
186 | }
187 | });
188 |
189 | // Create array of values for each map file + one for not selected
190 | entries = new String[dbFiles.length + 1];
191 | values = new String[dbFiles.length + 1];
192 |
193 | // Create default / none entry
194 | entries[0] = getResources().getString(R.string.prefs_none);
195 | values[0] = Preferences.CATALOG_NONE;
196 |
197 | for (int i = 0; i < dbFiles.length; i++) {
198 | entries[i + 1] = dbFiles[i].substring(0, dbFiles[i].length() - Preferences.CATALOG_FILE_EXTENSION.length());
199 | values[i + 1] = dbFiles[i];
200 | }
201 | } else {
202 | // No wifi catalog found, populate values with just the default entry.
203 | entries = new String[]{getResources().getString(R.string.prefs_none)};
204 | values = new String[]{Preferences.CATALOG_NONE};
205 | }
206 |
207 | ListPreference lf = (ListPreference) findPreference(Preferences.KEY_OFFLINE_CATALOG_FILE);
208 | lf.setEntries(entries);
209 | lf.setEntryValues(values);
210 | }
211 |
212 | /**
213 | * Lets user select operation mode (online/offline)
214 | */
215 | private void initOperationModeChooser() {
216 | String[] entries = getResources().getStringArray(R.array.operation_mode_entries);
217 | String[] values = getResources().getStringArray(R.array.operation_mode_values);
218 |
219 | ListPreference lf = (ListPreference) findPreference(Preferences.KEY_OPERATION_MODE);
220 | lf.setEntries(entries);
221 | lf.setEntryValues(values);
222 |
223 | lf.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
224 | @Override
225 | public boolean onPreferenceChange(Preference preference, Object newValue) {
226 |
227 | String listValue = (String) newValue;
228 | Log.d(TAG, "New operation mode :" + listValue);
229 | if (listValue.equals(Preferences.OPERATION_MODE_OFFLINE) && getSelectedCatalog().equals(Preferences.CATALOG_NONE)) {
230 | AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
231 | builder.setMessage(getString(R.string.question_download_catalog));
232 | builder.setTitle(getString(R.string.offline_catalog_n_a));
233 | // Add the buttons
234 | builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
235 | public void onClick(DialogInterface dialog, int id) {
236 | showCatalogDownloadDialog();
237 | //Toast.makeText(SettingsActivity.this, getString(R.string.download_started), Toast.LENGTH_LONG).show();
238 | }
239 | });
240 | builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
241 | public void onClick(DialogInterface dialog, int id) {
242 | Toast.makeText(SettingsActivity.this, getString(R.string.warning_catalog_missing), Toast.LENGTH_LONG).show();
243 | }
244 | });
245 |
246 | AlertDialog dialog = builder.create();
247 | dialog.show();
248 | }
249 | return true;
250 | }
251 | });
252 | }
253 |
254 | /**
255 | * Lets user select source for geolocation (wifis, cells, combined)
256 | */
257 | private void initSourceChooser() {
258 | String[] entries = getResources().getStringArray(R.array.source_entries);
259 | String[] values = getResources().getStringArray(R.array.source_values);
260 |
261 | ListPreference lf = (ListPreference) findPreference(Preferences.KEY_SOURCE);
262 | lf.setEntries(entries);
263 | lf.setEntryValues(values);
264 | }
265 |
266 | /**
267 | * Initialises download manager for GINGERBREAD and newer
268 | */
269 | private void registerDownloadManager() {
270 | mDownloadManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
271 |
272 | if(mReceiver == null) {
273 | mReceiver = new BroadcastReceiver() {
274 | @Override
275 | public void onReceive(final Context context, final Intent intent) {
276 | final String action = intent.getAction();
277 | if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
278 | final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
279 | final DownloadManager.Query query = new DownloadManager.Query();
280 | query.setFilterById(downloadId);
281 | final Cursor c = mDownloadManager.query(query);
282 | if (c.moveToFirst()) {
283 | final int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
284 | if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
285 | final String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
286 | Log.i(TAG, "Download completed: " + uriString);
287 | onDownloadCompleted(uriString);
288 | } else {
289 | final int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
290 | Toast.makeText(SettingsActivity.this,
291 | String.format(getString(R.string.download_failed),
292 | String.valueOf(reason)), Toast.LENGTH_LONG).show();
293 | Log.e(TAG, "Download failed: " + reason);
294 | }
295 | }
296 | }
297 | }
298 | };
299 |
300 | registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
301 | }
302 | }
303 |
304 | /**
305 | * Selects downloaded file either as wifi catalog / active Catalog (based on file extension).
306 | * @param file
307 | */
308 | public final void onDownloadCompleted(String file) {
309 | // get current file extension
310 | final String[] filenameArray = file.split("\\.");
311 | final String extension = "." + filenameArray[filenameArray.length - 1];
312 |
313 | // TODO verify on newer Android versions (>4.2)
314 | // replace prefix file:// in filename string
315 | file = file.replace("file://", "");
316 |
317 | if (extension.equals(Preferences.CATALOG_FILE_EXTENSION)) {
318 | final File targetFolder = new File(PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_DATA_FOLDER, this.getExternalFilesDir(null).getAbsolutePath()));
319 | new MediaScanner(this, new File(targetFolder.getAbsolutePath()));
320 |
321 | // if file has been downloaded to cache folder, move to target folder
322 | if (file.contains(this.getExternalCacheDir().getPath())) {
323 | try {
324 | Log.i(TAG, "Moving file to" + targetFolder.getAbsolutePath());
325 | String target = targetFolder.getAbsolutePath()+ File.separator + file;
326 | FileHelpers.moveFile(file, target);
327 | } catch (IOException e) {
328 | Log.e(TAG, "Error moving file to " + targetFolder.getAbsolutePath());
329 | }
330 | }
331 | refreshCatalogList(targetFolder.getAbsolutePath());
332 | activateCatalog(file);
333 | }
334 | }
335 |
336 | /**
337 | * Changes catalog preference item to given filename.
338 | * Helper method to activate wifi catalog following successful download
339 | * @param absoluteFile absolute filename (including path)
340 | */
341 | public void activateCatalog(final String absoluteFile) {
342 |
343 | if (!new File(absoluteFile).exists()) {
344 | Toast.makeText(this, String.format("File %s doesn't exists!", absoluteFile),
345 | Toast.LENGTH_LONG).show();
346 | return;
347 | }
348 |
349 | ListPreference lf = (ListPreference) findPreference(Preferences.KEY_OFFLINE_CATALOG_FILE);
350 | // get filename
351 | String[] filenameArray = absoluteFile.split("/");
352 | String file = filenameArray[filenameArray.length - 1];
353 |
354 | CharSequence[] values = lf.getEntryValues();
355 | for (int i = 0; i < values.length; i++) {
356 | if (file.equals(values[i].toString())) {
357 | lf.setValueIndex(i);
358 | }
359 | }
360 |
361 | if (getSelectedOperationMode().equals(Preferences.OPERATION_MODE_ONLINE)) {
362 | AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
363 | builder.setMessage(getString(R.string.question_activate_offline_mode));
364 | builder.setTitle(getString(R.string.download_completed));
365 | // Add the buttons
366 | builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
367 | public void onClick(DialogInterface dialog, int id) {
368 | ListPreference pref = (ListPreference) findPreference(Preferences.KEY_OPERATION_MODE);
369 | pref.setValue(Preferences.OPERATION_MODE_OFFLINE);
370 | Toast.makeText(SettingsActivity.this, getString(R.string.using_offline_mode), Toast.LENGTH_LONG).show();
371 | }
372 | });
373 | builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
374 | public void onClick(DialogInterface dialog, int id) {
375 | //Toast.makeText(SettingsActivity.this, "Keep on using online mode", Toast.LENGTH_LONG).show();
376 | }
377 | });
378 |
379 | AlertDialog dialog = builder.create();
380 | dialog.show();
381 | }
382 | }
383 |
384 | /**
385 | * Read build information from ressources
386 | *
387 | * @return build version
388 | */
389 | private String readBuildInfo() {
390 | final InputStream buildInStream = getResources().openRawResource(R.raw.build);
391 | final ByteArrayOutputStream buildOutStream = new ByteArrayOutputStream();
392 |
393 | int i;
394 |
395 | try {
396 | i = buildInStream.read();
397 | while (i != -1) {
398 | buildOutStream.write(i);
399 | i = buildInStream.read();
400 | }
401 |
402 | buildInStream.close();
403 | } catch (final IOException e) {
404 | e.printStackTrace();
405 | }
406 |
407 | return buildOutStream.toString();
408 | // use buildOutStream.toString() to get the data
409 | }
410 |
411 | /**
412 | * Downloads selected catalog
413 | * @param url absolute url
414 | */
415 | @Override
416 | public void catalogSelected(String url) {
417 | if (url == null) {
418 | Toast.makeText(this, R.string.invalid_download, Toast.LENGTH_LONG).show();
419 | return;
420 | }
421 |
422 | Toast.makeText(this, getString(R.string.downloading) + " " + url, Toast.LENGTH_LONG).show();
423 |
424 | final File folder = new File(PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_DATA_FOLDER,
425 | getExternalFilesDir(null).getAbsolutePath()));
426 |
427 | Log.d(TAG, "Download destination" + folder.getAbsolutePath());
428 |
429 | boolean folderAccessible = false;
430 | if (folder.exists() && folder.canWrite()) {
431 | folderAccessible = true;
432 | } else {
433 | Log.e(TAG, "Folder not accessible: " + folder);
434 | }
435 |
436 | if (!folder.exists()) {
437 | Log.i(TAG, "Creating new folder " + folder);
438 | folderAccessible = folder.mkdirs();
439 | }
440 |
441 | if (folderAccessible) {
442 | final String filename = url.substring(url.lastIndexOf('/') + 1);
443 |
444 | final File target = new File(folder.getAbsolutePath() + File.separator + filename);
445 | if (target.exists()) {
446 | Log.i(TAG, "Catalog file " + filename + " already exists. Overwriting..");
447 | target.delete();
448 | }
449 |
450 | Log.i(TAG, String.format("Saving %s @ %s", url, folder.getAbsolutePath() + File.separator + filename));
451 |
452 | final DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
453 | long mCurrentCatalogDownloadId;
454 | try {
455 | // try to download to target. If target isn't below Environment.getExternalStorageDirectory(),
456 | // e.g. on second SD card a security exception is thrown
457 | final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
458 | request.setDestinationUri(Uri.fromFile(target));
459 | mCurrentCatalogDownloadId = dm.enqueue(request);
460 | } catch (final SecurityException sec) {
461 | // download to temp dir and try to move to target later
462 | Log.w(TAG, "Security exception, can't write to " + target + ", using " + getExternalCacheDir());
463 | final File tempFile = new File(getExternalCacheDir() + File.separator + filename);
464 | final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
465 | request.setDestinationUri(Uri.fromFile(tempFile));
466 | mCurrentCatalogDownloadId = dm.enqueue(request);
467 | }
468 | } else {
469 | Toast.makeText(this, R.string.error_save_file_failed, Toast.LENGTH_SHORT).show();
470 | }
471 | }
472 | }
473 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | TERMS AND CONDITIONS
2 | 0. Definitions.
3 |
4 | "This License" refers to version 3 of the GNU Affero General Public License.
5 |
6 | "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
7 |
8 | "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
9 |
10 | To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
11 |
12 | A "covered work" means either the unmodified Program or a work based on the Program.
13 |
14 | To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
15 |
16 | To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
17 |
18 | An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
19 | 1. Source Code.
20 |
21 | The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
22 |
23 | A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
24 |
25 | The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
26 |
27 | The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
28 |
29 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
30 |
31 | The Corresponding Source for a work in source code form is that same work.
32 | 2. Basic Permissions.
33 |
34 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
35 |
36 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
37 |
38 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
39 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
40 |
41 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
42 |
43 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
44 | 4. Conveying Verbatim Copies.
45 |
46 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
47 |
48 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
49 | 5. Conveying Modified Source Versions.
50 |
51 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
52 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
53 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
54 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
55 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
56 |
57 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
58 | 6. Conveying Non-Source Forms.
59 |
60 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
61 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
62 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
63 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
64 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
65 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
66 |
67 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
68 |
69 | A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
70 |
71 | "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
72 |
73 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
74 |
75 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
76 |
77 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
78 | 7. Additional Terms.
79 |
80 | "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
81 |
82 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
83 |
84 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
85 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
86 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
87 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
88 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
89 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
90 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
91 |
92 | All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
93 |
94 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
95 |
96 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
97 | 8. Termination.
98 |
99 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
100 |
101 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
102 |
103 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
104 |
105 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
106 | 9. Acceptance Not Required for Having Copies.
107 |
108 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
109 | 10. Automatic Licensing of Downstream Recipients.
110 |
111 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
112 |
113 | An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
114 |
115 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
116 | 11. Patents.
117 |
118 | A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
119 |
120 | A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
121 |
122 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
123 |
124 | In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
125 |
126 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
127 |
128 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
129 |
130 | A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
131 |
132 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
133 | 12. No Surrender of Others' Freedom.
134 |
135 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
136 | 13. Remote Network Interaction; Use with the GNU General Public License.
137 |
138 | Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
139 |
140 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
141 | 14. Revised Versions of this License.
142 |
143 | The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
144 |
145 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
146 |
147 | If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
148 |
149 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
150 | 15. Disclaimer of Warranty.
151 |
152 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
153 | 16. Limitation of Liability.
154 |
155 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
156 | 17. Interpretation of Sections 15 and 16.
157 |
158 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
159 |
160 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/src/org/radiocells/unifiedNlp/geocoders/OfflineProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | Radiobeacon - Openbmap Unified Network Location Provider
3 | Copyright (C) 2013 wish7
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as
7 | published by the Free Software Foundation, either version 3 of the
8 | License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | */
18 | package org.radiocells.unifiedNlp.geocoders;
19 |
20 | import android.annotation.SuppressLint;
21 | import android.annotation.TargetApi;
22 | import android.content.Context;
23 | import android.content.SharedPreferences;
24 | import android.database.Cursor;
25 | import android.database.sqlite.SQLiteCantOpenDatabaseException;
26 | import android.database.sqlite.SQLiteDatabase;
27 | import android.database.sqlite.SQLiteException;
28 | import android.location.Location;
29 | import android.net.wifi.ScanResult;
30 | import android.os.AsyncTask;
31 | import android.os.Build;
32 | import android.os.Bundle;
33 | import android.os.SystemClock;
34 | import android.preference.PreferenceManager;
35 | import android.util.Log;
36 |
37 | import org.radiocells.unifiedNlp.Preferences;
38 | import org.radiocells.unifiedNlp.models.Cell;
39 | import org.radiocells.unifiedNlp.utils.SsidBlackList;
40 |
41 | import java.io.File;
42 | import java.util.ArrayList;
43 | import java.util.Arrays;
44 | import java.util.HashMap;
45 | import java.util.List;
46 |
47 | public class OfflineProvider extends AbstractProvider implements ILocationProvider {
48 |
49 | // Default accuracy for wifi results (in meter)
50 | public static final int DEFAULT_WIFI_ACCURACY = 30;
51 | // Default accuracy for cell results (in meter)
52 | private static final int DEFAULT_CELL_ACCURACY = 3000;
53 | // Assumed ratio between maximum and typical range
54 | private static final int TYPICAL_RANGE_FACTOR = 7;
55 | private static final String BLACKLIST_SUBDIR = "blacklists";
56 | private static final String DEFAULT_SSID_BLOCK_FILE = "default_ssid.xml";
57 | private static final String TAG = OfflineProvider.class.getName();
58 | private ILocationCallback mListener;
59 |
60 | /**
61 | * Keeps the SharedPreferences.
62 | */
63 | private SharedPreferences prefs;
64 |
65 | /**
66 | * Database containing well-known wifis from openbmap.org.
67 | */
68 | private SQLiteDatabase mCatalog;
69 |
70 | /**
71 | * Blacklist to filter out well-known mobile SSIDs.
72 | */
73 | private SsidBlackList mSsidBlackList;
74 |
75 | private Context context;
76 |
77 | public OfflineProvider(final Context context, final ILocationCallback listener) {
78 | final String mBlacklistPath = context.getExternalFilesDir(null).getAbsolutePath() + File.separator + BLACKLIST_SUBDIR;
79 | mListener = listener;
80 | this.context = context;
81 | prefs = PreferenceManager.getDefaultSharedPreferences(context);
82 |
83 | if (prefs.getString(Preferences.KEY_OFFLINE_CATALOG_FILE, Preferences.VAL_CATALOG_FILE).equals(Preferences.CATALOG_NONE)) {
84 | Log.e(TAG, "Critical error: you chose offline provider, but didn't specify a offline catalog!");
85 | }
86 | // Open catalog database
87 | Log.d(TAG, String.format("Using blacklist in %s", mBlacklistPath));
88 | String path = prefs.getString(Preferences.KEY_DATA_FOLDER, context.getExternalFilesDir(null).getAbsolutePath())
89 | + File.separator + prefs.getString(Preferences.KEY_OFFLINE_CATALOG_FILE, Preferences.VAL_CATALOG_FILE);
90 |
91 | try {
92 | mCatalog = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
93 | } catch (SQLiteCantOpenDatabaseException e) {
94 | Log.e(TAG, "Error opening database");
95 | }
96 | mSsidBlackList = new SsidBlackList();
97 | mSsidBlackList.openFile(mBlacklistPath + File.separator + DEFAULT_SSID_BLOCK_FILE, null);
98 | setLastFix(System.currentTimeMillis());
99 | }
100 |
101 | @SuppressLint("StaticFieldLeak")
102 | @SuppressWarnings("unchecked")
103 | @Override
104 | public void getLocation(final List wifiList, final List cellsList) {
105 | LocationQueryParams params = new LocationQueryParams(wifiList, cellsList);
106 |
107 | new AsyncTask() {
108 | private static final int WIFIS_MASK = 0x0f; // mask for wifi flags
109 | private static final int CELLS_MASK = 0xf0; // mask for cell flags
110 | private static final int EMPTY_WIFIS_QUERY = 0x01; // no wifis were passed
111 | private static final int EMPTY_CELLS_QUERY = 0x10; // no cells were passed
112 | private static final int WIFIS_NOT_FOUND = 0x02; // none of the wifis in the list was found in the database
113 | private static final int CELLS_NOT_FOUND = 0x20; // none of the cells in the list was found in the database
114 | private static final int WIFIS_MATCH = 0x04; // matching wifis were found
115 | private static final int CELLS_MATCH = 0x40; // matching cells were found
116 | private static final int WIFI_DATABASE_NA = 0x08; // the database contains no wifi data
117 | private static final int CELLS_DATABASE_NA = 0x80; // the database contains no cell data
118 |
119 | private int state;
120 |
121 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
122 | @SuppressLint("DefaultLocale")
123 | @Override
124 | protected Location doInBackground(LocationQueryParams... params) {
125 | long now = SystemClock.elapsedRealtime();
126 | if (params == null) {
127 | throw new IllegalArgumentException("Wifi list was null");
128 | }
129 |
130 | if (prefs.getString(Preferences.KEY_OFFLINE_CATALOG_FILE, Preferences.CATALOG_NONE).equals(Preferences.CATALOG_NONE)) {
131 | throw new IllegalArgumentException("No catalog database was specified");
132 | }
133 |
134 | List wifiListRaw = params[0].wifiList;
135 | List cellsListRaw = params[0].cellsList;
136 | HashMap wifiList = new HashMap<>();
137 | List cellsList = new ArrayList<>();
138 | HashMap locations = new HashMap<>();
139 | String[] resultIds;
140 | ArrayList cellResults = new ArrayList<>();
141 | Location result = null;
142 |
143 | if (wifiListRaw != null) {
144 | // Generates a list of wifis from scan results
145 | for (ScanResult r : wifiListRaw) {
146 | long age = 0;
147 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
148 | // determine age (elapsedRealtime is in milliseconds, timestamp is in microseconds)
149 | age = now - (r.timestamp / 1000);
150 | /*
151 | * Any filtering of scan results can be done here. Examples include:
152 | * empty or bogus BSSIDs, SSIDs with "_nomap" suffix, blacklisted wifis
153 | */
154 | if (r.BSSID == null)
155 | Log.w(TAG, "skipping wifi with empty BSSID");
156 | else if (r.SSID.endsWith("_nomap")) {
157 | // BSSID with _nomap suffix, user does not want it to be mapped or used for geolocation
158 | } else if (mSsidBlackList.contains(r.SSID)) {
159 | Log.w(TAG, String.format("SSID '%s' is blacklisted, skipping", r.SSID));
160 | } else {
161 | if (age >= 2000)
162 | Log.w(TAG, String.format("wifi %s is stale (%d ms), using it anyway", r.BSSID, age));
163 | // wifi is OK to use for geolocation, add it to list
164 | wifiList.put(r.BSSID.replace(":", "").toUpperCase(), r);
165 | }
166 | }
167 | Log.i(TAG, "Using " + wifiList.size() + " wifis for geolocation");
168 | } else {
169 | Log.i(TAG, "No wifis supplied for geolocation");
170 | }
171 |
172 | String[] wifiQueryArgs = wifiList.keySet().toArray(new String[0]);
173 |
174 | if (cellsListRaw != null) {
175 | for (Cell r : cellsListRaw) {
176 | Log.d(TAG, "Evaluating " + r.toString());
177 | /*
178 | * Filtering of cells happens here. This is typically the case for neighboring
179 | * cells in UMTS or LTE networks, which are only identified by their PSC or PCI
180 | * (and are thus useless for lookup). Other filters can be added, such as
181 | * filtering out cells with bogus data or comparing against a blacklist of
182 | * "cells on wheels" (whose location can change).
183 | */
184 | if ((r.mcc <= 0) || (r.area <= 0) || (r.cellId <= 0)
185 | || (r.mcc == Integer.MAX_VALUE) || ("".equals(r.mnc)) || (r.area == Integer.MAX_VALUE) || (r.cellId == Integer.MAX_VALUE)) {
186 | Log.i(TAG, String.format("Cell %s has incomplete data, skipping", r.toString()));
187 | } else {
188 | cellsList.add(r);
189 | }
190 | }
191 | }
192 |
193 | state &= ~WIFIS_MASK & ~CELLS_MASK;
194 | if (wifiQueryArgs.length < 1) {
195 | Log.i(TAG, "Query contained no bssids");
196 | state |= EMPTY_WIFIS_QUERY;
197 | }
198 |
199 | if (cellsList.isEmpty()) {
200 | Log.w(TAG, "Query contained no cell infos");
201 | state |= EMPTY_CELLS_QUERY;
202 | }
203 |
204 | if ((state & (EMPTY_WIFIS_QUERY | EMPTY_CELLS_QUERY)) != (EMPTY_WIFIS_QUERY | EMPTY_CELLS_QUERY)) {
205 | Cursor c;
206 |
207 | if ((state & EMPTY_WIFIS_QUERY) == 0) {
208 | Log.d(TAG, "Looking up wifis");
209 | if (!hasWifiTables()) {
210 | Log.w(TAG, "Wifi tables not available. Check your database");
211 | state |= WIFI_DATABASE_NA;
212 | }
213 | StringBuilder whereClause = new StringBuilder();
214 | for (String k : wifiQueryArgs) {
215 | if (whereClause.length() > 1) {
216 | whereClause.append(" OR ");
217 | }
218 | whereClause.append(" bssid = ?");
219 | }
220 | final String wifiSql = "SELECT latitude, longitude, bssid FROM wifi_zone WHERE " + whereClause;
221 | //Log.d(TAG, sql);
222 | try {
223 | c = mCatalog.rawQuery(wifiSql, wifiQueryArgs);
224 | boolean zero = c.getCount() == 0;
225 | Log.i(TAG, String.format("Found %d known wifis", c.getCount()));
226 | for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
227 | Location location = new Location(TAG);
228 | location.setLatitude(c.getDouble(0));
229 | location.setLongitude(c.getDouble(1));
230 | location.setAccuracy(0);
231 | location.setTime(System.currentTimeMillis());
232 | Bundle b = new Bundle();
233 | b.putString("source", "wifis");
234 | b.putString("bssid", c.getString(2));
235 | location.setExtras(b);
236 | locations.put(c.getString(2), location);
237 | state |= WIFIS_MATCH;
238 | }
239 | c.close();
240 |
241 | if(zero) {
242 | c = mCatalog.rawQuery("SELECT count(0) FROM wifi_zone",
243 | new String[0]);
244 | c.moveToFirst();
245 | c.close();
246 | }
247 |
248 | } catch (SQLiteException e) {
249 | Log.e(TAG, "SQLiteException! Update your database!");
250 | state |= WIFI_DATABASE_NA;
251 | }
252 | if ((state & WIFIS_MATCH) != WIFIS_MATCH) {
253 | state |= WIFIS_NOT_FOUND;
254 | }
255 | }
256 |
257 | if ((state & EMPTY_CELLS_QUERY) == 0) {
258 | Log.d(TAG, "Looking up cells");
259 | if (!hasCellTables()) {
260 | Log.w(TAG, "Cell tables not available. Check your database");
261 | state |= CELLS_DATABASE_NA;
262 | }
263 |
264 | StringBuilder whereClause = new StringBuilder();
265 | List cellQueryArgs = new ArrayList<>();
266 | for (Cell k : cellsList) {
267 | if (whereClause.length() > 1) {
268 | whereClause.append(" OR ");
269 | }
270 | Log.d(TAG, "Using " + k.toString());
271 | whereClause.append(" (cid = ? AND mcc = ? AND mnc = ? AND area = ?)");
272 | cellQueryArgs.add(String.valueOf(k.cellId));
273 | cellQueryArgs.add(String.valueOf(k.mcc));
274 | cellQueryArgs.add(k.mnc);
275 | cellQueryArgs.add(String.valueOf(k.area));
276 | }
277 | // Ignore the cell technology for the time being, using cell technology causes problems when cell supports different protocols, e.g.
278 | // UMTS and HSUPA and HSUPA+
279 | // final String cellSql = "SELECT AVG(latitude), AVG(longitude) FROM cell_zone WHERE cid = ? AND mcc = ? AND mnc = ? AND area = ? and technology = ?";
280 | String cellSql = "SELECT AVG(latitude), AVG(longitude), mcc, mnc, area, cid FROM cell_zone WHERE " + whereClause + " GROUP BY mcc, mnc, area, cid";
281 | try {
282 | c = mCatalog.rawQuery(cellSql, cellQueryArgs.toArray(new String[0]));
283 | Log.i(TAG, String.format("Found %d known cells", c.getCount()));
284 | if (c.getCount() == 0) {
285 | c.close();
286 |
287 | whereClause = new StringBuilder();
288 | cellQueryArgs = new ArrayList<>();
289 | for (Cell k : cellsList) {
290 | if (whereClause.length() > 1) {
291 | whereClause.append(" OR ");
292 | }
293 | Log.d(TAG, "Using " + k.toString());
294 | whereClause.append(" (cid = ? AND mcc = ? AND mnc = ? AND area = ?)");
295 | cellQueryArgs.add(String.valueOf(k.cellId));
296 | cellQueryArgs.add(String.valueOf(k.mcc));
297 | cellQueryArgs.add(String.valueOf(Integer.valueOf(k.mnc)));
298 | cellQueryArgs.add(String.valueOf(k.area));
299 | }
300 | cellSql = "SELECT AVG(latitude), AVG(longitude), mcc, mnc, area, cid FROM cell_zone WHERE " + whereClause + " GROUP BY mcc, mnc, area, cid";
301 | c = mCatalog.rawQuery(cellSql, cellQueryArgs.toArray(new String[0]));
302 | Log.i(TAG, String.format("Found %d known cells", c.getCount()));
303 | }
304 |
305 | for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
306 | Location location = new Location(TAG);
307 | location.setLatitude(c.getDouble(0));
308 | location.setLongitude(c.getDouble(1));
309 | location.setAccuracy(0); // or DEFAULT_CELL_ACCURACY?
310 | location.setTime(System.currentTimeMillis());
311 | Bundle b = new Bundle();
312 | b.putString("source", "cells");
313 | b.putString("cell", c.getInt(2) + "|" + c.getInt(3) + "|" + c.getInt(4) + "|" + c.getInt(5));
314 | location.setExtras(b);
315 | locations.put(c.getInt(2) + "|" + c.getInt(3) + "|" + c.getInt(4) + "|" + c.getInt(5), location);
316 | cellResults.add(c.getInt(2) + "|" + c.getInt(3) + "|" + c.getInt(4) + "|" + c.getInt(5));
317 | state |= CELLS_MATCH;
318 | }
319 | c.close();
320 |
321 | if ((state & CELLS_MATCH) != CELLS_MATCH) {
322 | state |= CELLS_NOT_FOUND;
323 | }
324 | } catch (SQLiteException e) {
325 | Log.e(TAG, "SQLiteException! Update your database!");
326 | state |= CELLS_DATABASE_NA;
327 | }
328 | }
329 |
330 | resultIds = locations.keySet().toArray(new String[0]);
331 |
332 | if (resultIds.length == 0) {
333 | return null;
334 | } else if (resultIds.length == 1) {
335 | // We have just one location, pass it
336 | result = locations.get(resultIds[0]);
337 | if (resultIds[0].contains("|"))
338 | // the only result is a cell, assume default
339 | result.setAccuracy(DEFAULT_CELL_ACCURACY);
340 | else
341 | // the only result is a wifi, estimate accuracy based on RSSI
342 | result.setAccuracy(getWifiRxDist(wifiList.get(resultIds[0]).level) / 10);
343 | return result;
344 | } else {
345 | /*
346 | * Penalize outliers (which may be happen if a transmitter has moved and the
347 | * database still has the old location, or a mix of old and new location): Walk
348 | * through the array, calculating distances between each possible pair of
349 | * locations, subtracting the presumed distance from the receiver, and storing
350 | * the mean square of any positive distance. This is the presumed variance (i.e.
351 | * standard deviation, or accuracy, squared).
352 | *
353 | * This process does not distinguish between cells and wifis, other than by
354 | * determining ranges and distances in a different way. This is intentional, as
355 | * even cell towers can move (or may just have an inaccurate position in the
356 | * database).
357 | *
358 | * Note that we're "abusing" the accuracy field for variance (and interim values
359 | * to calculate variance) until we've fused the individual locations into a
360 | * final location. Only at that point will the true accuracy be set for that
361 | * location.
362 | *
363 | * Locations are fused using a simplified Kálmán filter: since accuracy (and
364 | * thus variance) is a scalar value, we're applying a one-dimensional Kálmán
365 | * filter to latitude and longitude independently. This may not be 100%
366 | * mathematically correct - improvements welcome.
367 | *
368 | * For now we are not considering the accuracy of the transmitter positions
369 | * themselves, as we don't have these values (this would require an additional
370 | * column in the wifi catalog).
371 | */
372 | for (int i = 0; i < resultIds.length; i++) {
373 | // for now, assume static speed (20 m/s = 72 km/h)
374 | // TODO get a better speed estimate
375 | final float speed = 20.0f;
376 |
377 | // RSSI-based distance
378 | float rxdist =
379 | (wifiList.get(resultIds[i]) == null) ?
380 | DEFAULT_CELL_ACCURACY * TYPICAL_RANGE_FACTOR :
381 | getWifiRxDist(wifiList.get(resultIds[i]).level);
382 |
383 | // distance penalty for stale wifis (supported only on Jellybean MR1 and higher)
384 | // for cells this value is always zero (cell scans are always current)
385 | float ageBasedDist = 0.0f;
386 | // penalize stale entries (wifis only, supported only on Jellybean MR1 and higher)
387 | if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) && !resultIds[i].contains("|")) {
388 | // elapsedRealtime is in milliseconds, timestamp is in microseconds
389 | ageBasedDist = (now - (wifiList.get(resultIds[i]).timestamp / 1000)) * speed / 1000;
390 | }
391 |
392 | for (int j = i + 1; j < resultIds.length; j++) {
393 | float[] distResults = new float[1];
394 | float jAgeBasedDist = 0.0f;
395 | Location.distanceBetween(locations.get(resultIds[i]).getLatitude(),
396 | locations.get(resultIds[i]).getLongitude(),
397 | locations.get(resultIds[j]).getLatitude(),
398 | locations.get(resultIds[j]).getLongitude(),
399 | distResults);
400 |
401 | // subtract distance between device and each transmitter to get "disagreement"
402 | if (wifiList.get(resultIds[j]) == null)
403 | distResults[0] -= rxdist + DEFAULT_CELL_ACCURACY * TYPICAL_RANGE_FACTOR;
404 | else {
405 | distResults[0] -= rxdist + getWifiRxDist(wifiList.get(resultIds[j]).level);
406 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
407 | jAgeBasedDist = (now - (wifiList.get(resultIds[j]).timestamp / 1000)) * speed / 1000;
408 | }
409 |
410 | /*
411 | * Consider the distance traveled between the two locations. This avoids
412 | * penalizing two locations that differ in time.
413 | */
414 | distResults[0] -= Math.abs(ageBasedDist - jAgeBasedDist);
415 |
416 | // apply penalty only if disagreement is greater than zero
417 | if (distResults[0] > 0) {
418 | // take the square of the distance
419 | distResults[0] *= distResults[0];
420 |
421 | // add to the penalty count for both locations
422 | locations.get(resultIds[i]).setAccuracy(locations.get(resultIds[i]).getAccuracy() + distResults[0]);
423 | locations.get(resultIds[j]).setAccuracy(locations.get(resultIds[j]).getAccuracy() + distResults[0]);
424 | }
425 | }
426 | locations.get(resultIds[i]).setAccuracy(locations.get(resultIds[i]).getAccuracy() / (resultIds.length - 1));
427 | // correct distance from transmitter to a realistic value
428 | rxdist /= TYPICAL_RANGE_FACTOR;
429 |
430 | Log.v(TAG, String.format("%s: disagreement = %.5f, rxdist = %.5f, age = %d ms, ageBasedDist = %.5f",
431 | resultIds[i],
432 | Math.sqrt(locations.get(resultIds[i]).getAccuracy()),
433 | rxdist,
434 | (wifiList.get(resultIds[i]) != null) ? (now - (wifiList.get(resultIds[i]).timestamp / 1000)) : 0,
435 | ageBasedDist));
436 |
437 | // add additional error sources: RSSI-based (distance from transmitter) and age-based (distance traveled since)
438 | locations.get(resultIds[i]).setAccuracy(locations.get(resultIds[i]).getAccuracy() + rxdist * rxdist + ageBasedDist * ageBasedDist);
439 |
440 | if (i == 0)
441 | result = locations.get(resultIds[i]);
442 | else {
443 | float k = result.getAccuracy() / (result.getAccuracy() + locations.get(resultIds[i]).getAccuracy());
444 | result.setLatitude((1 - k) * result.getLatitude() + k * locations.get(resultIds[i]).getLatitude());
445 | result.setLongitude((1 - k) * result.getLongitude() + k * locations.get(resultIds[i]).getLongitude());
446 | result.setAccuracy((1 - k) * result.getAccuracy());
447 | }
448 | }
449 |
450 | // finally, set actual accuracy (square root of the interim value)
451 | result.setAccuracy((float) Math.sqrt(result.getAccuracy()));
452 |
453 | // FIXME what do we want to reflect in results? transmitters we tried to look up, or only those which returned a location?
454 | Bundle b = new Bundle();
455 | if ((state & (WIFIS_MATCH | CELLS_MATCH)) == (WIFIS_MATCH | CELLS_MATCH)) {
456 | b.putString("source", "cells; wifis");
457 | } else if ((state & WIFIS_MATCH) != 0) {
458 | b.putString("source", "wifis");
459 | } else if ((state & CELLS_MATCH) != 0) {
460 | b.putString("source", "cells");
461 | }
462 | if ((state & WIFIS_MATCH) != 0)
463 | b.putStringArrayList("bssids", new ArrayList<>(Arrays.asList(wifiQueryArgs)));
464 | if ((state & CELLS_MATCH) != 0)
465 | b.putStringArrayList("cells", cellResults);
466 | result.setExtras(b);
467 | return result;
468 | }
469 | } else {
470 | return null;
471 | }
472 | }
473 |
474 | /**
475 | * Check whether cell zone table exists
476 | */
477 | private boolean hasCellTables() {
478 | final String sql = "SELECT count(name) FROM sqlite_master WHERE type='table' AND name='cell_zone'";
479 | final Cursor c = mCatalog.rawQuery(sql, null);
480 | c.moveToFirst();
481 | if (!c.isAfterLast()) {
482 | if (c.getLong(0) == 0) {
483 | c.close();
484 | return false;
485 | }
486 | }
487 | c.close();
488 | return true;
489 | }
490 |
491 | /**
492 | * Check whether wifi zone table exists
493 | */
494 | private boolean hasWifiTables() {
495 | final String sql = "SELECT count(name) FROM sqlite_master WHERE type='table' AND name='wifi_zone'";
496 | final Cursor c = mCatalog.rawQuery(sql, null);
497 | c.moveToFirst();
498 | if (!c.isAfterLast()) {
499 | if (c.getLong(0) == 0) {
500 | c.close();
501 | return false;
502 | }
503 | }
504 | c.close();
505 | return true;
506 | }
507 |
508 | @Override
509 | protected void onPostExecute(Location result) {
510 | if (result == null) {
511 | Log.w(TAG, "Location was null");
512 | return;
513 | }
514 |
515 | if (plausibleLocationUpdate(result)) {
516 | Log.d(TAG, "Broadcasting location" + result.toString());
517 | setLastLocation(result);
518 | setLastFix(System.currentTimeMillis());
519 | mListener.onLocationReceived(result);
520 | } else {
521 | Log.i(TAG, "Strange location, ignoring");
522 | }
523 | }
524 | }.execute(params);
525 | }
526 |
527 | /**
528 | * @param rxlev Received signal strength (RSSI) in dBm
529 | * @return Upper boundary for the distance between transmitter and receiver in meters
530 | * @brief Obtains a wifi receiver's maximum distance from the transmitter based on signal strength.
531 | *
532 | * Distance is calculated based on the assumption that the signal level is -100 dBm at a distance of
533 | * 1000 m, and that the signal level will increase by 6 dBm as the distance is halved. This model
534 | * does not consider additional signal degradation caused by obstacles, thus real distances will
535 | * almost always be lower than the result of this function. This "worst-case" approach is
536 | * intentional and consumers should apply any corrections they deem appropriate.
537 | */
538 | private static float getWifiRxDist(int rxlev) {
539 | final int refRxlev = -100;
540 | final float refDist = 1000.0f;
541 | float factor = (float) Math.pow(2.0f, 6.0f / (refRxlev - rxlev));
542 | return refDist * factor;
543 | }
544 |
545 | private static class LocationQueryParams {
546 | List wifiList;
547 | List cellsList;
548 |
549 | LocationQueryParams(List wifiList, List| cellsList) {
550 | this.wifiList = wifiList;
551 | this.cellsList = cellsList;
552 | }
553 | }
554 | }
555 |
--------------------------------------------------------------------------------
| | | | | | | | | | | | |