ThreatMapFragment.java 11 KB

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