ThreatMapFragment.java 12 KB

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