ThreatMapFragment.java 13 KB

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