ThreatMapFragment.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. package de.tudarmstadt.informatik.hostage.ui.fragment;
  2. import static com.google.android.gms.common.GooglePlayServicesUtil.getErrorDialog;
  3. import static com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import android.app.Activity;
  8. import android.app.AlertDialog;
  9. import android.app.FragmentManager;
  10. import android.content.BroadcastReceiver;
  11. import android.content.Context;
  12. import android.content.DialogInterface;
  13. import android.content.Intent;
  14. import android.content.IntentFilter;
  15. import android.graphics.Color;
  16. import android.location.Criteria;
  17. import android.location.Location;
  18. import android.location.LocationListener;
  19. import android.location.LocationManager;
  20. import android.os.Bundle;
  21. import android.support.v4.content.LocalBroadcastManager;
  22. import android.text.Html;
  23. import android.view.InflateException;
  24. import android.view.LayoutInflater;
  25. import android.view.View;
  26. import android.view.ViewGroup;
  27. import android.widget.TextView;
  28. import com.google.android.gms.common.ConnectionResult;
  29. import com.google.android.gms.common.GooglePlayServicesClient;
  30. import com.google.android.gms.maps.CameraUpdateFactory;
  31. import com.google.android.gms.maps.GoogleMap;
  32. import com.google.android.gms.maps.MapFragment;
  33. import com.google.android.gms.maps.model.BitmapDescriptor;
  34. import com.google.android.gms.maps.model.BitmapDescriptorFactory;
  35. import com.google.android.gms.maps.model.CircleOptions;
  36. import com.google.android.gms.maps.model.LatLng;
  37. import com.google.android.gms.maps.model.Marker;
  38. import com.google.android.gms.maps.model.MarkerOptions;
  39. import de.tudarmstadt.informatik.hostage.R;
  40. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  41. import de.tudarmstadt.informatik.hostage.logging.Record;
  42. import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
  43. import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
  44. import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
  45. /**
  46. * ThreatMapFragment
  47. *
  48. * Created by Fabio Arnold on 10.02.14.
  49. */
  50. public class ThreatMapFragment extends TrackerFragment implements GoogleMap.OnInfoWindowClickListener,
  51. GooglePlayServicesClient.ConnectionCallbacks,
  52. GooglePlayServicesClient.OnConnectionFailedListener,
  53. LocationListener {
  54. private static GoogleMap sMap = null;
  55. private static View sView = null;
  56. private static Thread mLoader = null;
  57. private static HashMap<String, String> sMarkerIDToSSID = new HashMap<String, String>();
  58. private LocationManager mLocationManager;
  59. //private LocationClient mLocationClient;
  60. private String mLocationProvider;
  61. // needed for LIVE threat map
  62. private boolean mReceiverRegistered = false;
  63. private BroadcastReceiver mReceiver;
  64. /**
  65. * if google play services aren't available an error notification will be displayed
  66. *
  67. * @return true if the google play services are available
  68. */
  69. private boolean isGooglePlay() {
  70. int status = isGooglePlayServicesAvailable(getActivity());
  71. boolean result = status == ConnectionResult.SUCCESS;
  72. if (!result) {
  73. getErrorDialog(status, getActivity(), 10).show();
  74. }
  75. return result;
  76. }
  77. /**
  78. * register a broadcast receiver if not already registered
  79. * and also update the number of attacks per protocol
  80. */
  81. private void registerBroadcastReceiver() {
  82. if (!mReceiverRegistered) {
  83. mReceiver = new BroadcastReceiver() {
  84. @Override
  85. public void onReceive(Context context, Intent intent) {
  86. if (sMap != null) {
  87. populateMap();
  88. }
  89. }
  90. };
  91. LocalBroadcastManager
  92. .getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
  93. this.mReceiverRegistered = true;
  94. }
  95. }
  96. /**
  97. * callback for when the info window of a marker gets clicked
  98. * open the RecordOverviewFragment and display all records belonging to an SSID
  99. *
  100. * @param marker this info window belongs to
  101. */
  102. @Override
  103. public void onInfoWindowClick(Marker marker) {
  104. //MainActivity.getInstance().displayView(MainActivity.MainMenuItem.RECORDS.getValue());
  105. //RecordOverviewFragment recordOverviewFragment = (RecordOverviewFragment)MainActivity.getInstance().getCurrentFragment();
  106. //if (recordOverviewFragment != null) {
  107. String ssid = sMarkerIDToSSID.get(marker.getId());
  108. ArrayList<String> ssids = new ArrayList<String>();
  109. ssids.add(ssid);
  110. LogFilter filter = new LogFilter();
  111. filter.setESSIDs(ssids);
  112. RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
  113. recordOverviewFragment.setFilter(filter);
  114. recordOverviewFragment.setGroupKey("ESSID");
  115. recordOverviewFragment.setAllowBack(true);
  116. MainActivity.getInstance().injectFragment(recordOverviewFragment);
  117. //recordOverviewFragment.showDetailsForSSID(getActivity(), ssid);
  118. //}
  119. }
  120. /**
  121. * callbacks from LocationClient
  122. */
  123. @Override
  124. public void onConnected(Bundle bundle) {
  125. }
  126. @Override
  127. public void onDisconnected() {
  128. }
  129. @Override
  130. public void onConnectionFailed(ConnectionResult connectionResult) {
  131. }
  132. @Override
  133. public void onLocationChanged(Location location) {
  134. sMap.animateCamera(CameraUpdateFactory.newLatLng(
  135. new LatLng(location.getLatitude(), location.getLongitude())));
  136. }
  137. @Override
  138. public void onStatusChanged(String provider, int status, Bundle extras) {
  139. }
  140. @Override
  141. public void onProviderEnabled(String provider) {
  142. }
  143. @Override
  144. public void onProviderDisabled(String provider) {
  145. }
  146. /**
  147. * helper class
  148. * easier to use than LatLng
  149. */
  150. private class Point {
  151. public double x, y;
  152. public Point(double sx, double sy) {
  153. x = sx;
  154. y = sy;
  155. }
  156. }
  157. /**
  158. * helper class
  159. * contains heuristic to split SSIDs by location
  160. * see MAX_DISTANCE
  161. */
  162. private class SSIDArea {
  163. private Point mMinimum, mMaximum;
  164. public int numPoints;
  165. public static final int MAX_NUM_ATTACKS = 20;
  166. public static final float MAX_DISTANCE = 1000.0f; // 1km
  167. public SSIDArea(LatLng initialLocation) {
  168. //mMinimum = new Point(360.0, 360.0);
  169. //mMaximum = new Point(-360.0, -360.0);
  170. mMinimum = new Point(initialLocation.latitude, initialLocation.longitude);
  171. mMaximum = new Point(initialLocation.latitude, initialLocation.longitude);
  172. numPoints = 1;
  173. }
  174. public boolean doesLocationBelongToArea(LatLng location) {
  175. LatLng center = calculateCenterLocation();
  176. float[] result = new float[1];
  177. Location.distanceBetween(center.latitude, center.longitude, location.latitude,
  178. location.longitude, result);
  179. return result[0] < MAX_DISTANCE;
  180. }
  181. public void addLocation(LatLng location) {
  182. Point point = new Point(location.latitude, location.longitude);
  183. if (point.x < mMinimum.x) {
  184. mMinimum.x = point.x;
  185. }
  186. if (point.x > mMaximum.x) {
  187. mMaximum.x = point.x;
  188. }
  189. if (point.y < mMinimum.y) {
  190. mMinimum.y = point.y;
  191. }
  192. if (point.y > mMaximum.y) {
  193. mMaximum.y = point.y;
  194. }
  195. numPoints++;
  196. }
  197. public LatLng calculateCenterLocation() {
  198. return new LatLng(0.5 * (mMinimum.x + mMaximum.x), 0.5 * (mMinimum.y + mMaximum.y));
  199. }
  200. public float calculateRadius() {
  201. float[] result = new float[1];
  202. Location.distanceBetween(mMinimum.x, mMinimum.y, mMaximum.x, mMaximum.y, result);
  203. return 0.5f * result[0];
  204. }
  205. public int calculateColor() {
  206. int threatLevel = numPoints;
  207. if (threatLevel > MAX_NUM_ATTACKS) {
  208. threatLevel = MAX_NUM_ATTACKS;
  209. }
  210. float alpha = 1.0f - (float) (threatLevel - 1) / (float) (MAX_NUM_ATTACKS - 1);
  211. return Color.argb(127, (int) (240.0 + 15.0 * alpha), (int) (80.0 + 175.0 * alpha), 60);
  212. }
  213. }
  214. /**
  215. * fills the map with markers and circle representing SSIDs
  216. * does it asynchronously in background thread
  217. */
  218. private void populateMap() {
  219. if (mLoader != null) {
  220. mLoader.interrupt();
  221. }
  222. mLoader = new Thread(new Runnable() {
  223. private void updateUI(final HashMap<String, ArrayList<SSIDArea>> threatAreas) {
  224. if (mLoader.isInterrupted()) {
  225. return;
  226. }
  227. Activity activity = getActivity();
  228. if (activity != null) {
  229. activity.runOnUiThread(new Runnable() {
  230. @Override
  231. public void run() {
  232. sMap.clear();
  233. CircleOptions circleOptions = new CircleOptions().radius(200.0)
  234. .fillColor(Color.argb(127, 240, 80, 60)).strokeWidth(0.0f);
  235. BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
  236. .fromResource(R.drawable.wifi_marker);
  237. for (Map.Entry<String, ArrayList<SSIDArea>> entry : threatAreas.entrySet()) {
  238. String ssid = entry.getKey();
  239. ArrayList<SSIDArea> areas = entry.getValue();
  240. for (SSIDArea area : areas) {
  241. int color = area.calculateColor();
  242. LatLng center = area.calculateCenterLocation();
  243. float radius = area.calculateRadius();
  244. sMap.addCircle(circleOptions.center(center).radius(100.0 + radius)
  245. .fillColor(color));
  246. Marker marker = sMap.addMarker(new MarkerOptions()
  247. .title(ssid + ": " + area.numPoints + (area.numPoints == 1
  248. ? getResources()
  249. .getString(R.string.attack)
  250. : getResources().getString(R.string.attacks))).position(
  251. center));
  252. marker.setIcon(bitmapDescriptor);
  253. sMarkerIDToSSID.put(marker.getId(), ssid);
  254. }
  255. }
  256. }
  257. });
  258. }
  259. }
  260. private HashMap<String, ArrayList<SSIDArea>> doInBackground() {
  261. HostageDBOpenHelper dbh = new HostageDBOpenHelper(getActivity());
  262. ArrayList<Record> records = dbh.getRecordsForFilter(new LogFilter());
  263. HashMap<String, ArrayList<SSIDArea>> threatAreas
  264. = new HashMap<String, ArrayList<SSIDArea>>();
  265. for (Record record : records) {
  266. LatLng location = new LatLng(record.getLatitude(), record.getLongitude());
  267. //Log.i("location", "lat: " + location.latitude + " long: " + location.longitude);
  268. ArrayList<SSIDArea> areas;
  269. if (threatAreas.containsKey(record.getSsid())) {
  270. areas = threatAreas.get(record.getSsid());
  271. boolean foundArea = false;
  272. for (SSIDArea area : areas) {
  273. if (area.doesLocationBelongToArea(location)) {
  274. area.addLocation(location);
  275. foundArea = true;
  276. break;
  277. }
  278. }
  279. if (!foundArea) {
  280. areas.add(new SSIDArea(location));
  281. }
  282. } else {
  283. areas = new ArrayList<SSIDArea>();
  284. areas.add(new SSIDArea(location));
  285. threatAreas.put(record.getSsid(), areas);
  286. }
  287. }
  288. return threatAreas;
  289. }
  290. @Override
  291. public void run() {
  292. updateUI(doInBackground());
  293. }
  294. });
  295. mLoader.start(); // run!
  296. }
  297. /**
  298. * performs initialization
  299. * checks if google play services are supported
  300. * view must be removed if this object has been created once before
  301. * that is why view is static
  302. *
  303. * @param inflater the inflater
  304. * @param container the container
  305. * @param savedInstanceState the savedInstanceState
  306. * @return the view
  307. */
  308. @Override
  309. public View onCreateView(final LayoutInflater inflater, ViewGroup container,
  310. Bundle savedInstanceState) {
  311. super.onCreateView(inflater, container, savedInstanceState);
  312. final Activity activity = getActivity();
  313. if (activity != null) {
  314. activity.setTitle(getResources().getString(R.string.drawer_threat_map));
  315. }
  316. if (sView != null) {
  317. ViewGroup parent = (ViewGroup) sView.getParent();
  318. if (parent != null) {
  319. parent.removeView(sView);
  320. }
  321. }
  322. try {
  323. sView = inflater.inflate(R.layout.fragment_threatmap, container, false);
  324. if (isGooglePlay()) {
  325. final FragmentManager fragmentManager = getFragmentManager();
  326. if (fragmentManager != null) {
  327. final MapFragment mapFragment = (MapFragment) getFragmentManager()
  328. .findFragmentById(R.id.threatmapfragment);
  329. if (mapFragment != null) {
  330. sMap = mapFragment.getMap();
  331. }
  332. }
  333. } else {
  334. AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.getInstance());
  335. builder.setMessage(Html.fromHtml(getString(R.string.google_play_services_unavailable)))
  336. .setCancelable(false)
  337. .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
  338. public void onClick(DialogInterface dialog, int id) {
  339. // :D-|< :D-/< :D-\<
  340. }
  341. });
  342. AlertDialog alert = builder.create();
  343. alert.show();
  344. }
  345. } catch (InflateException e) {
  346. // map already exists
  347. //e.printStackTrace();
  348. }
  349. if (sMap != null) {
  350. sMap.setOnInfoWindowClickListener(this);
  351. // custom info window layout
  352. sMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
  353. @Override
  354. public View getInfoWindow(Marker marker) {
  355. return null;
  356. }
  357. @Override
  358. public View getInfoContents(Marker marker) {
  359. View view = inflater.inflate(R.layout.fragment_threatmap_infowindow, null);
  360. if (view != null) {
  361. TextView titleTextView = (TextView) view
  362. .findViewById(R.id.threatmap_infowindow_title);
  363. if (titleTextView != null) {
  364. titleTextView.setText(marker.getTitle());
  365. }
  366. }
  367. return view;
  368. }
  369. });
  370. mLocationManager = (LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);
  371. Criteria criteria = new Criteria();
  372. criteria.setAccuracy(Criteria.ACCURACY_FINE);
  373. mLocationProvider = mLocationManager.getBestProvider(criteria, false);
  374. mLocationManager.requestLocationUpdates(mLocationProvider, (long)0, 1000.0f, (LocationListener)this);
  375. sMap.setMyLocationEnabled(true);
  376. LatLng tudarmstadt = new LatLng(49.86923, 8.6632768); // default location
  377. sMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tudarmstadt, 13));
  378. populateMap();
  379. registerBroadcastReceiver();
  380. }
  381. // tell the user to enable wifi so map data can be streamed
  382. if (activity != null && !HelperUtils.isNetworkAvailable(activity)) {
  383. new AlertDialog.Builder(activity)
  384. .setTitle(R.string.information)
  385. .setMessage(R.string.no_network_connection_threatmap_msg)
  386. .setPositiveButton(android.R.string.ok,
  387. new DialogInterface.OnClickListener() {
  388. public void onClick(DialogInterface dialog,
  389. int which) {
  390. }
  391. }
  392. )
  393. .setIcon(android.R.drawable.ic_dialog_info).show();
  394. }
  395. return sView;
  396. }
  397. @Override
  398. public void onResume() {
  399. super.onResume();
  400. if (sMap != null) {
  401. // repopulate
  402. populateMap();
  403. }
  404. if (mLocationManager != null) {
  405. mLocationManager.requestLocationUpdates(mLocationProvider, 0, 1000.0f, this);
  406. }
  407. }
  408. @Override
  409. public void onPause() {
  410. super.onPause();
  411. if (mLocationManager != null) {
  412. mLocationManager.removeUpdates(this);
  413. }
  414. }
  415. }