RecordOverviewFragment.java 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. package de.tudarmstadt.informatik.hostage.ui.fragment;
  2. import android.annotation.SuppressLint;
  3. import android.app.Activity;
  4. import android.app.AlertDialog;
  5. import android.app.FragmentManager;
  6. import android.content.BroadcastReceiver;
  7. import android.content.Context;
  8. import android.content.DialogInterface;
  9. import android.content.Intent;
  10. import android.content.IntentFilter;
  11. import android.content.SharedPreferences;
  12. import android.os.Bundle;
  13. import android.preference.PreferenceManager;
  14. import android.support.v4.content.LocalBroadcastManager;
  15. import android.util.Log;
  16. import android.view.LayoutInflater;
  17. import android.view.Menu;
  18. import android.view.MenuInflater;
  19. import android.view.MenuItem;
  20. import android.view.View;
  21. import android.view.ViewGroup;
  22. import android.widget.ExpandableListView;
  23. import android.widget.ImageButton;
  24. import android.widget.ProgressBar;
  25. import android.widget.Toast;
  26. import com.google.android.gms.maps.model.LatLng;
  27. import java.text.DateFormat;
  28. import java.text.SimpleDateFormat;
  29. import java.util.ArrayList;
  30. import java.util.Calendar;
  31. import java.util.Collections;
  32. import java.util.Comparator;
  33. import java.util.Date;
  34. import java.util.HashMap;
  35. import java.util.List;
  36. import java.util.Locale;
  37. import java.util.Random;
  38. import de.tudarmstadt.informatik.hostage.Handler;
  39. import de.tudarmstadt.informatik.hostage.Hostage;
  40. import de.tudarmstadt.informatik.hostage.R;
  41. import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
  42. import de.tudarmstadt.informatik.hostage.logging.LogExport;
  43. import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
  44. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  45. import de.tudarmstadt.informatik.hostage.logging.Record;
  46. import de.tudarmstadt.informatik.hostage.logging.SyncData;
  47. import de.tudarmstadt.informatik.hostage.logging.SyncInfo;
  48. import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
  49. import de.tudarmstadt.informatik.hostage.sync.android.SyncUtils;
  50. import de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSyncActivity;
  51. import de.tudarmstadt.informatik.hostage.sync.nfc.NFCSyncActivity;
  52. import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncActivity;
  53. import de.tudarmstadt.informatik.hostage.sync.wifi_direct.ui.WiFiP2pSyncActivity;
  54. import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
  55. import de.tudarmstadt.informatik.hostage.ui.adapter.RecordListAdapter;
  56. import de.tudarmstadt.informatik.hostage.ui.dialog.ChecklistDialog;
  57. import de.tudarmstadt.informatik.hostage.ui.dialog.DateTimeDialogFragment;
  58. import de.tudarmstadt.informatik.hostage.ui.model.ExpandableListItem;
  59. import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
  60. import de.tudarmstadt.informatik.hostage.ui.model.LogFilter.SortType;
  61. import de.tudarmstadt.informatik.hostage.ui.model.ServicesListItem;
  62. import de.tudarmstadt.informatik.hostage.ui.popup.AbstractPopup;
  63. import de.tudarmstadt.informatik.hostage.ui.popup.AbstractPopupItem;
  64. import de.tudarmstadt.informatik.hostage.ui.popup.SimplePopupItem;
  65. import de.tudarmstadt.informatik.hostage.ui.popup.SimplePopupTable;
  66. import de.tudarmstadt.informatik.hostage.ui.popup.SplitPopupItem;
  67. public class RecordOverviewFragment extends UpNavigatibleFragment implements ChecklistDialog.ChecklistDialogListener, DateTimeDialogFragment.DateTimeDialogFragmentListener {
  68. static final String FILTER_MENU_TITLE_BSSID = MainActivity.getContext().getString(R.string.BSSID);
  69. static final String FILTER_MENU_TITLE_ESSID = MainActivity.getContext().getString(R.string.ESSID);
  70. static final String FILTER_MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(R.string.rec_protocol);
  71. static final String FILTER_MENU_TITLE_TIMESTAMP_BELOW = MainActivity.getContext().getString(
  72. R.string.rec_latest);
  73. static final String FILTER_MENU_TITLE_TIMESTAMP_ABOVE = MainActivity.getContext().getString(
  74. R.string.rec_earliest);
  75. static final String FILTER_MENU_TITLE_SORTING = MainActivity.getContext().getString(R.string.rec_sortby);
  76. static final String FILTER_MENU_TITLE_REMOVE = MainActivity.getContext().getString(R.string.rec_reset_filter);
  77. static final String FILTER_MENU_TITLE_GROUP = MainActivity.getContext().getString(
  78. R.string.rec_group_by);
  79. static final String FILTER_MENU_POPUP_TITLE = MainActivity.getContext().getString(
  80. R.string.rec_filter_by);
  81. static final int DEFAULT_GROUPING_KEY_INDEX = 0;
  82. private boolean wasBelowTimePicker;
  83. private LogFilter filter;
  84. private boolean showFilterButton;
  85. private View rootView;
  86. private int mListPosition = -1;
  87. private int mItemPosition = -1;
  88. public String groupingKey;
  89. private ExpandableListView expListView;
  90. private ProgressBar spinner;
  91. private Toast noDataNotificationToast;
  92. HostageDBOpenHelper dbh;
  93. private String sectionToOpen = "";
  94. private ArrayList<Integer> openSections;
  95. private SharedPreferences pref;
  96. Thread loader;
  97. private boolean mReceiverRegistered = false;
  98. private BroadcastReceiver mReceiver;
  99. /* DATE CONVERSION STUFF*/
  100. static final DateFormat localisedDateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
  101. // DATE WHICH PATTERN
  102. static final String localDatePattern = ((SimpleDateFormat)localisedDateFormatter).toLocalizedPattern();
  103. static final String groupingDatePattern = "MMMM yyyy";
  104. // INSERT HERE YOUR DATE PATERN
  105. static final SimpleDateFormat groupingDateFormatter = new SimpleDateFormat(groupingDatePattern);
  106. static final Calendar calendar = Calendar.getInstance();
  107. // DATE STRINGS
  108. static final String TODAY = MainActivity.getInstance().getResources().getString( R.string.TODAY);
  109. static final String YESTERDAY = MainActivity.getInstance().getResources().getString( R.string.YESTERDAY);
  110. private SyncInfo si ;// = s.getSyncInfo();
  111. private SyncData sd ;//= s.getSyncData(si);
  112. /**
  113. * Constructor
  114. */
  115. public RecordOverviewFragment(){}
  116. @Override
  117. public void onCreate(Bundle savedInstanceState) {
  118. super.onCreate(savedInstanceState);
  119. setHasOptionsMenu(true);
  120. }
  121. @Override
  122. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  123. Bundle savedInstanceState) {
  124. setHasOptionsMenu(true);
  125. getActivity().setTitle(getResources().getString(R.string.drawer_records));
  126. dbh = new HostageDBOpenHelper(this.getActivity().getBaseContext());
  127. pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
  128. // Get the message from the intent
  129. //this.addRecordToDB(4,4,4);
  130. /*
  131. Synchronizer s = new Synchronizer(this.dbh);
  132. si = s.getSyncInfo();
  133. HashMap<String, Long> map = new HashMap<String, Long>();
  134. map.put(SyncDevice.currentDevice().getDeviceID(), new Long(-1));
  135. si.deviceMap = map;
  136. sd = s.getSyncData(si);
  137. s.updateFromSyncData(sd);
  138. */
  139. if (this.filter == null){
  140. Intent intent = this.getActivity().getIntent();
  141. LogFilter filter = intent.getParcelableExtra(LogFilter.LOG_FILTER_INTENT_KEY);
  142. if(filter == null){
  143. this.clearFilter();
  144. } else {
  145. this.filter = filter;
  146. }
  147. }
  148. if (this.groupingKey == null) this.groupingKey = this.groupingTitles().get(DEFAULT_GROUPING_KEY_INDEX);
  149. this.setShowFilterButton(!this.filter.isNotEditable());
  150. View rootView = inflater.inflate(this.getLayoutId(), container, false);
  151. this.rootView = rootView;
  152. ExpandableListView mylist = (ExpandableListView) rootView.findViewById(R.id.loglistview);
  153. this.spinner =(ProgressBar) rootView.findViewById(R.id.progressBar1);
  154. this.spinner.setVisibility(View.GONE);
  155. this.expListView = mylist;
  156. this.initialiseListView();
  157. ImageButton deleteButton = (ImageButton) rootView.findViewById(R.id.DeleteButton);
  158. deleteButton.setOnClickListener(new View.OnClickListener() {
  159. public void onClick(View v) {
  160. RecordOverviewFragment.this.openDeleteFilteredAttacksDialog();
  161. }
  162. });
  163. deleteButton.setVisibility(this.showFilterButton? View.VISIBLE : View.INVISIBLE);
  164. ImageButton filterButton = (ImageButton) rootView.findViewById(R.id.FilterButton);
  165. filterButton.setOnClickListener(new View.OnClickListener() {
  166. public void onClick(View v) {
  167. RecordOverviewFragment.this.openFilterPopupMenuOnView(v);
  168. }
  169. });
  170. filterButton.setVisibility(this.showFilterButton? View.VISIBLE : View.INVISIBLE);
  171. ImageButton sortButton = (ImageButton) rootView.findViewById(R.id.SortButton);
  172. sortButton.setOnClickListener(new View.OnClickListener() {
  173. public void onClick(View v) {
  174. // Open SortMenu
  175. RecordOverviewFragment.this.openSortingDialog();
  176. }
  177. });
  178. ImageButton groupButton = (ImageButton) rootView.findViewById(R.id.GroupButton);
  179. groupButton.setOnClickListener(new View.OnClickListener() {
  180. public void onClick(View v) {
  181. // Open SortMenu
  182. RecordOverviewFragment.this.openGroupingDialog();
  183. }
  184. });
  185. this.registerBroadcastReceiver();
  186. return rootView;
  187. }
  188. /**Initialises the expandable list view in a backgorund thread*/
  189. private void initialiseListView(){
  190. if (loader != null) loader.interrupt();
  191. if (this.openSections == null) this.openSections = new ArrayList<Integer>();
  192. this.spinner.setVisibility(View.VISIBLE);
  193. loader = new Thread(new Runnable(){
  194. private void updateUI(final RecordListAdapter currentAdapter)
  195. {
  196. if(loader.isInterrupted()){
  197. return;
  198. }
  199. Activity activity = RecordOverviewFragment.this.getActivity();
  200. if (activity != null){
  201. activity.runOnUiThread(new Runnable() {
  202. @Override
  203. public void run() {
  204. RecordOverviewFragment.this.expListView.setAdapter(currentAdapter);
  205. // Update view and remove loading spinner etc...
  206. RecordListAdapter adapter = (RecordListAdapter) RecordOverviewFragment.this.expListView.getExpandableListAdapter();
  207. if (adapter != null){
  208. adapter.notifyDataSetChanged();
  209. if (adapter.getGroupCount() >= 1){
  210. RecordOverviewFragment.this.expListView.expandGroup(DEFAULT_GROUPING_KEY_INDEX);
  211. if (!RecordOverviewFragment.this.openSections.contains(DEFAULT_GROUPING_KEY_INDEX)){
  212. RecordOverviewFragment.this.openSections.add(DEFAULT_GROUPING_KEY_INDEX);
  213. }
  214. } else {
  215. RecordOverviewFragment.this.setSectionToOpen(RecordOverviewFragment.this.sectionToOpen);
  216. }
  217. }
  218. if (RecordOverviewFragment.this.openSections != null && RecordOverviewFragment.this.openSections.size() != 0){
  219. for (int i = 0; i < RecordOverviewFragment.this.openSections.size(); i++){
  220. int index = RecordOverviewFragment.this.openSections.get(i);
  221. RecordOverviewFragment.this.expListView.expandGroup(index);
  222. }
  223. } else {
  224. RecordOverviewFragment.this.openSections = new ArrayList<Integer>();
  225. }
  226. if (mListPosition != -1 && mItemPosition != -1)
  227. RecordOverviewFragment.this.expListView.setSelectedChild(mListPosition, mItemPosition, true);
  228. mListPosition = -1;
  229. mItemPosition = -1;
  230. registerListClickCallback(RecordOverviewFragment.this.expListView);
  231. RecordOverviewFragment.this.spinner.setVisibility(View.GONE);
  232. RecordOverviewFragment.this.actualiseFilterButton();
  233. RecordOverviewFragment.this.showEmptyDataNotification();
  234. }
  235. });
  236. }
  237. }
  238. private RecordListAdapter doInBackground()
  239. {
  240. return populateListViewFromDB(RecordOverviewFragment.this.expListView);
  241. }
  242. @Override
  243. public void run()
  244. {
  245. //RecordOverviewFragment.this.addRecordToDB(40, 10, 4);
  246. updateUI(doInBackground());
  247. }
  248. });
  249. loader.start();
  250. this.actualiseFilterButton();
  251. }
  252. /**
  253. * Returns the Fragment layout ID
  254. * @return int The fragment layout ID
  255. * */
  256. public int getLayoutId(){
  257. return R.layout.fragment_record_list;
  258. }
  259. /**
  260. * Gets called if the user clicks on item in the filter menu.
  261. *
  262. * @param item {@link AbstractPopupItem AbstractPopupItem }
  263. * */
  264. public void onFilterMenuItemSelected(AbstractPopupItem item) {
  265. String title = item.getTitle();
  266. if (item instanceof SplitPopupItem){
  267. SplitPopupItem splitItem = (SplitPopupItem)item;
  268. if (splitItem.wasRightTouch){
  269. this.openTimestampToFilterDialog();
  270. } else {
  271. this.openTimestampFromFilterDialog();
  272. }
  273. return;
  274. }
  275. if (title != null){
  276. if(title.equals(FILTER_MENU_TITLE_BSSID)){
  277. this.openBSSIDFilterDialog();
  278. }
  279. if(title.equals(FILTER_MENU_TITLE_ESSID)){
  280. this.openESSIDFilterDialog();
  281. }
  282. if(title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
  283. this.openProtocolsFilterDialog();
  284. }
  285. if(title.equals(FILTER_MENU_TITLE_SORTING)){
  286. this.openSortingDialog();
  287. }
  288. if(title.equals(FILTER_MENU_TITLE_REMOVE)){
  289. this.clearFilter();
  290. this.actualiseListViewInBackground();
  291. }
  292. if(title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)){
  293. this.openTimestampToFilterDialog();
  294. }
  295. if(title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)){
  296. this.openTimestampFromFilterDialog();
  297. }
  298. }
  299. //return super.onOptionsItemSelected(item);
  300. }
  301. @Override
  302. public void onStart() {
  303. super.onStart();
  304. if (this.expListView.getExpandableListAdapter() != null){
  305. if (this.expListView.getExpandableListAdapter().getGroupCount() == 1){
  306. this.expListView.expandGroup(0);
  307. } else {
  308. this.setSectionToOpen(this.sectionToOpen);
  309. }
  310. }
  311. }
  312. @Override
  313. public void onDestroy(){
  314. if (mReceiver != null){
  315. }
  316. super.onDestroy();
  317. }
  318. @Override
  319. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  320. // Inflate the menu items for use in the action bar
  321. inflater.inflate(R.menu.records_overview_actions, menu);
  322. }
  323. @Override
  324. public boolean onOptionsItemSelected(MenuItem item) {
  325. switch (item.getItemId()) {
  326. case R.id.records_action_synchronize:
  327. AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
  328. builder.setTitle(MainActivity.getInstance().getString(R.string.rec_sync_rec));
  329. builder.setItems(new String[]{
  330. MainActivity.getInstance().getString(R.string.rec_via_bt),
  331. "With TraCINg",
  332. "Via WifiDirect"
  333. }, new DialogInterface.OnClickListener() {
  334. @Override
  335. public void onClick(DialogInterface dialog, int position) {
  336. switch(position){
  337. case 0:
  338. startActivityForResult(new Intent(getBaseContext(), BluetoothSyncActivity.class), 0);
  339. break;
  340. /*case 1:
  341. getActivity().startActivity(new Intent(getActivity(), NFCSyncActivity.class));
  342. break;*/
  343. case 1:
  344. startActivityForResult(new Intent(getActivity(), TracingSyncActivity.class), 0);
  345. break;
  346. case 2:
  347. startActivityForResult(new Intent(getActivity(), WiFiP2pSyncActivity.class), 0);
  348. break;
  349. }
  350. }
  351. });
  352. builder.create();
  353. builder.show();
  354. return true;
  355. case R.id.records_action_export:
  356. AlertDialog.Builder builderExport = new AlertDialog.Builder(getActivity());
  357. builderExport.setTitle(MainActivity.getInstance().getString(R.string.rec_choose_export_format));
  358. builderExport.setItems(R.array.format, new DialogInterface.OnClickListener() {
  359. @Override
  360. public void onClick(DialogInterface dialog, int position) {
  361. //RecordOverviewFragment.this.exportDatabase(position);
  362. Intent intent = new Intent(getActivity(), LogExport.class);
  363. intent.setAction(LogExport.ACTION_EXPORT_DATABASE);
  364. intent.putExtra(LogExport.FORMAT_EXPORT_DATABASE, position);
  365. RecordOverviewFragment.this.getActivity().startService(intent);
  366. }
  367. });
  368. builderExport.create();
  369. builderExport.show();
  370. return true;
  371. }
  372. return false;
  373. }
  374. public void openDeleteFilteredAttacksDialog() {
  375. // Use the Builder class for convenient dialog construction
  376. AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  377. String deleteFILTEREDAttacksTitle = MainActivity.getInstance().getString(R.string.deleteFILTEREDAttacksTitle);
  378. String deleteALLAttacksTitle = MainActivity.getInstance().getString(R.string.deleteALLAttacksTitle);
  379. String cancelTitle = MainActivity.getInstance().getString(R.string.cancel);
  380. String deleteTitle = MainActivity.getInstance().getString(R.string.delete);
  381. String text = this.filter.isSet()? deleteFILTEREDAttacksTitle : deleteALLAttacksTitle;
  382. builder.setMessage(text)
  383. .setPositiveButton(deleteTitle, new DialogInterface.OnClickListener() {
  384. private RecordOverviewFragment recordOverviewFragment = null;
  385. public void onClick(DialogInterface dialog, int id) {
  386. recordOverviewFragment.deleteFilteredAttacks();
  387. MainActivity.getInstance().getHostageService().notifyUI(Handler.class.toString(), null);
  388. }
  389. public DialogInterface.OnClickListener init(RecordOverviewFragment rf){
  390. this.recordOverviewFragment = rf;
  391. return this;
  392. }
  393. }.init(this))
  394. .setNegativeButton(cancelTitle, new DialogInterface.OnClickListener() {
  395. public void onClick(DialogInterface dialog, int id) {
  396. // User cancelled the dialog
  397. }
  398. });
  399. AlertDialog dialog = builder.create();
  400. dialog.show();
  401. }
  402. @Override
  403. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  404. super.onActivityResult(requestCode, resultCode, data);
  405. if(requestCode == 0){
  406. if(resultCode == SyncUtils.SYNC_SUCCESSFUL){
  407. actualiseListViewInBackground();
  408. }
  409. }
  410. }
  411. /*****************************
  412. *
  413. * Public API
  414. *
  415. * ***************************/
  416. /**
  417. * Group records by SSID and expand given SSID
  418. *
  419. * @param SSID the SSID
  420. */
  421. public void showDetailsForSSID(Context context, String SSID) {
  422. Log.e("RecordOverviewFragment", "Implement showDetailsForSSID!!");
  423. this.clearFilter();
  424. int ESSID_INDEX = 2;
  425. ArrayList<String> ssids = new ArrayList<String>();
  426. this.sectionToOpen = SSID;
  427. this.groupingKey = this.groupingTitles().get(ESSID_INDEX);
  428. }
  429. /*****************************
  430. *
  431. * ListView Stuff
  432. *
  433. * ***************************/
  434. /**
  435. * Reloads the data in the ExpandableListView for the given filter object.
  436. * @param mylist {@link ExpandableListView ExpandableListView}
  437. * */
  438. private RecordListAdapter populateListViewFromDB(ExpandableListView mylist) {
  439. ArrayList<String> groupTitle = new ArrayList<String>();
  440. HashMap<String, ArrayList<ExpandableListItem>> sectionData = this.fetchDataForFilter(this.filter, groupTitle);
  441. RecordListAdapter adapter = null;
  442. if (mylist.getAdapter() != null && mylist.getAdapter() instanceof RecordListAdapter){
  443. adapter = (RecordListAdapter) mylist.getAdapter();
  444. adapter.setData(sectionData);
  445. adapter.setSectionHeader(groupTitle);
  446. } else {
  447. adapter = new RecordListAdapter( RecordOverviewFragment.this.getApplicationContext(), groupTitle, sectionData);
  448. }
  449. return adapter;
  450. }
  451. private HashMap<String, ArrayList<ExpandableListItem>> fetchDataForFilter(LogFilter filter, ArrayList<String> groupTitle){
  452. HashMap<String, ArrayList<ExpandableListItem>> sectionData = new HashMap<String, ArrayList<ExpandableListItem>>();
  453. ArrayList<Record> data = dbh.getRecordsForFilter(filter == null ? this.filter : filter);
  454. // Adding Items to ListView
  455. String keys[] = new String[] { RecordOverviewFragment.this.getString(R.string.RecordBSSID), RecordOverviewFragment.this.getString(R.string.RecordSSID), RecordOverviewFragment.this.getString(R.string.RecordProtocol), RecordOverviewFragment.this.getString(R.string.RecordTimestamp)};
  456. int ids[] = new int[] {R.id.RecordTextFieldBSSID, R.id.RecordTextFieldSSID, R.id.RecordTextFieldProtocol, R.id.RecordTextFieldTimestamp };
  457. HashMap<String, Integer> mapping = new HashMap<String, Integer>();
  458. int i = 0;
  459. for(String key : keys){
  460. mapping.put(key, ids[i]);
  461. i++;
  462. }
  463. if (groupTitle == null){
  464. groupTitle = new ArrayList<String>();
  465. } else {
  466. groupTitle.clear();
  467. }
  468. for (Record val : data) {
  469. // DO GROUPING IN HERE
  470. HashMap<String, String> map = new HashMap<String, String>();
  471. map.put(RecordOverviewFragment.this.getString(R.string.RecordBSSID), val.getBssid());
  472. map.put(RecordOverviewFragment.this.getString(R.string.RecordSSID), val.getSsid());
  473. map.put(RecordOverviewFragment.this.getString(R.string.RecordProtocol), val.getProtocol());
  474. map.put(RecordOverviewFragment.this.getString(R.string.RecordTimestamp),
  475. RecordOverviewFragment.this.getDateAsString(val.getTimestamp()));
  476. ExpandableListItem item = new ExpandableListItem();
  477. item.setData(map);
  478. item.setId_Mapping(mapping);
  479. item.setTag(val.getAttack_id());
  480. String groupID = RecordOverviewFragment.this.getGroupValue(val);
  481. ArrayList<ExpandableListItem> items = sectionData.get(groupID);
  482. if (items == null) {
  483. items = new ArrayList<ExpandableListItem>();
  484. sectionData.put(groupID, items);
  485. groupTitle.add(groupID);
  486. }
  487. items.add(item);
  488. }
  489. if (this.groupingKey.equals(this.groupingTitles().get(DEFAULT_GROUPING_KEY_INDEX))){
  490. Collections.sort(groupTitle,new DateStringComparator());
  491. } else {
  492. Collections.sort(groupTitle, new Comparator<String>() {
  493. @Override
  494. public int compare(String s1, String s2) {
  495. return s1.compareToIgnoreCase(s2);
  496. }
  497. });
  498. }
  499. return sectionData;
  500. }
  501. /**
  502. * The DateStringComparator compares formatted date strings by converting the into date.
  503. * This class is mainly used for grouping the records by their timestamp.
  504. */
  505. class DateStringComparator implements Comparator<String>
  506. {
  507. public int compare(String lhs, String rhs)
  508. {
  509. Date date1 = RecordOverviewFragment.this.convertStringToDate(lhs);
  510. Date date2 = RecordOverviewFragment.this.convertStringToDate(rhs);
  511. return date2.compareTo(date1);
  512. }
  513. }
  514. /**
  515. * register a broadcast receiver if not already registered
  516. * and also update the number of attacks per protocol
  517. */
  518. private void registerBroadcastReceiver() {
  519. if (!mReceiverRegistered) {
  520. mReceiver = new BroadcastReceiver() {
  521. @Override
  522. public void onReceive(Context context, Intent intent) {
  523. RecordOverviewFragment.this.actualiseListViewInBackground();
  524. }
  525. };
  526. LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
  527. this.mReceiverRegistered = true;
  528. }
  529. }
  530. /**
  531. * Actualises the list in a background thread
  532. */
  533. private void actualiseListViewInBackground(){
  534. if (loader != null && loader.isAlive()) loader.interrupt();
  535. loader = null;
  536. this.spinner.setVisibility(View.VISIBLE);
  537. this.actualiseFilterButton();
  538. loader = new Thread(new Runnable() {
  539. @Override
  540. public void run() {
  541. this.runOnUiThread(this.doInBackground());
  542. }
  543. private RecordListAdapter doInBackground(){
  544. return RecordOverviewFragment.this.populateListViewFromDB(RecordOverviewFragment.this.expListView);
  545. }
  546. private void runOnUiThread(final RecordListAdapter adapter){
  547. Activity actv = RecordOverviewFragment.this.getActivity();
  548. if (actv != null){
  549. actv.runOnUiThread(new Runnable() {
  550. @Override
  551. public void run() {
  552. this.actualiseUI();
  553. }
  554. private void actualiseUI(){
  555. RecordOverviewFragment self = RecordOverviewFragment.this;
  556. if (adapter != null){
  557. self.expListView.setAdapter(adapter);
  558. adapter.notifyDataSetChanged();
  559. self.spinner.setVisibility(View.GONE);
  560. }
  561. self.showEmptyDataNotification();
  562. if (self.openSections != null && self.expListView != null){
  563. for (int i = 0; i < self.openSections.size(); i++){
  564. int index = self.openSections.get(i);
  565. self.expListView.expandGroup(index);
  566. }
  567. }
  568. }
  569. });
  570. }
  571. }
  572. });
  573. loader.start();
  574. }
  575. /**
  576. * Shows a small toast if the data to show is empty (no records).
  577. */
  578. private void showEmptyDataNotification(){
  579. if (RecordOverviewFragment.this.noDataNotificationToast == null){
  580. RecordOverviewFragment.this.noDataNotificationToast = Toast.makeText(getApplicationContext(), R.string.no_data_notification, Toast.LENGTH_SHORT);
  581. }
  582. RecordListAdapter adapter = (RecordListAdapter) RecordOverviewFragment.this.expListView.getExpandableListAdapter();
  583. if (this.getFilterButton().getVisibility() == View.VISIBLE && this.filter.isSet()){
  584. this.noDataNotificationToast.setText(R.string.no_data_notification);
  585. } else {
  586. this.noDataNotificationToast.setText(R.string.no_data_notification_no_filter);
  587. }
  588. if (adapter == null || adapter.getData().isEmpty())
  589. RecordOverviewFragment.this.noDataNotificationToast.show();
  590. }
  591. /**This will open a section in the ExpandableListView with the same title as the parameter s.
  592. *
  593. * @param s String (the section title to open)
  594. *
  595. * */
  596. private void setSectionToOpen(String s){
  597. this.sectionToOpen = s;
  598. if (this.sectionToOpen != null && this.sectionToOpen.length() != 0){
  599. if (this.getGroupTitles().contains(this.sectionToOpen)){
  600. int section = this.getGroupTitles().indexOf(this.sectionToOpen);
  601. this.expListView.expandGroup(section);
  602. this.sectionToOpen = "";
  603. if (!this.openSections.contains(section)){
  604. RecordOverviewFragment.this.openSections.add(section);
  605. }
  606. }
  607. }
  608. }
  609. /**
  610. * Returns the base context.
  611. * @return Context baseContext
  612. * */
  613. private Context getBaseContext(){
  614. return this.getActivity().getBaseContext();
  615. }
  616. /**Returns the application context.
  617. * @return Context application context
  618. * */
  619. private Context getApplicationContext(){
  620. return this.getActivity().getApplicationContext();
  621. }
  622. /**Sets the list view listener on the given ExpandableListView.
  623. *
  624. * @param mylist {@link ExpandableListView ExpandableListView }
  625. * */
  626. private void registerListClickCallback(ExpandableListView mylist) {
  627. mylist.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
  628. @Override
  629. public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i2, long l) {
  630. RecordListAdapter adapter = (RecordListAdapter)expandableListView.getExpandableListAdapter();
  631. ExpandableListItem item = (ExpandableListItem)adapter.getChild(i,i2);
  632. mListPosition = i;
  633. mItemPosition = i2;
  634. HostageDBOpenHelper dbh = new HostageDBOpenHelper(getBaseContext());
  635. Record rec = dbh.getRecordOfAttackId((int) item.getTag());
  636. RecordOverviewFragment.this.pushRecordDetailViewForRecord(rec);
  637. return true;
  638. }
  639. });
  640. mylist.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
  641. @Override
  642. public void onGroupExpand(int i) {
  643. if (!RecordOverviewFragment.this.openSections.contains(i)){
  644. RecordOverviewFragment.this.openSections.add(i);
  645. }
  646. }
  647. });
  648. mylist.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
  649. @Override
  650. public void onGroupCollapse(int i) {
  651. RecordOverviewFragment.this.openSections.remove(i);
  652. }
  653. });
  654. }
  655. /*****************************
  656. *
  657. * Date Transformation / Conversion
  658. *
  659. * ***************************/
  660. /**Returns the localised date format for the given timestamp
  661. * @param timeStamp long */
  662. @SuppressLint("SimpleDateFormat")
  663. private String getDateAsString(long timeStamp) {
  664. Date date = (new Date(timeStamp));
  665. try {
  666. DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
  667. return formatter.format(date);
  668. } catch (Exception ex) {
  669. return "---";
  670. }
  671. }
  672. /**
  673. * Returns the timestamp in a own format.
  674. * Depending on the returned format the grouping by timestamp will change.
  675. *
  676. * e.g.
  677. * If you return a DateAsMonth formatted Date the records will be mapped by their month and year.
  678. * If you return the a DateAsDay formatted Date the records will be mapped by their day, month and year.
  679. * and so on...
  680. *
  681. * @param timestamp long
  682. * @return formatted date String
  683. */
  684. public String getFormattedDateForGrouping(long timestamp) {
  685. // DECIDE WHICH KIND OF FORMAT SHOULD BE USED
  686. // MONTH FORMAT
  687. String date = this.getDateAsMonthString(timestamp);
  688. // DAY FORMAT
  689. //String date = this.getDateAsDayString(timestamp);
  690. return date;
  691. }
  692. /**Returns a date as a formated string
  693. * @param timestamp date
  694. * @return String date format is localised*/
  695. @SuppressLint("SimpleDateFormat")
  696. private String getDateAsDayString(long timestamp) {
  697. try {
  698. Date netDate = (new Date(timestamp));
  699. String dateString;
  700. long date = this.dayMilliseconds(timestamp);
  701. if(this.todayMilliseconds() == date ){
  702. dateString = TODAY;
  703. }else if(this.yesterdayMilliseconds() == date ){
  704. dateString = YESTERDAY;
  705. } else {
  706. dateString = localisedDateFormatter.format(netDate);
  707. }
  708. return dateString;
  709. } catch (Exception ex) {
  710. return "---";
  711. }
  712. }
  713. /**
  714. * Converts a formatted DateString into a date.
  715. * @param dateString String
  716. * @return Date
  717. */
  718. private Date convertStringToDate(String dateString){
  719. if (dateString != null && dateString.length() != 0){
  720. SimpleDateFormat dateFormat = groupingDateFormatter; //new SimpleDateFormat(localDatePattern);
  721. Date date;
  722. try {
  723. if (dateString.equals(TODAY)){
  724. long millisec = RecordOverviewFragment.this.todayMilliseconds();
  725. date = new Date(millisec);
  726. } else if (dateString.equals(YESTERDAY)){
  727. long millisec = RecordOverviewFragment.this.yesterdayMilliseconds();
  728. date = new Date(millisec);
  729. } else {
  730. date = dateFormat.parse(dateString);
  731. }
  732. return date;
  733. } catch (java.text.ParseException e ) {
  734. date = new Date(0);
  735. return date;
  736. }
  737. } else {
  738. return new Date(0);
  739. }
  740. }
  741. /**
  742. * Returns the milliseconds for the day today (not the time).
  743. * @return long
  744. */
  745. private long todayMilliseconds(){
  746. Date current = new Date();
  747. calendar.setTimeInMillis(current.getTime());
  748. int day = calendar.get(Calendar.DATE);
  749. int month = calendar.get(Calendar.MONTH);
  750. int year = calendar.get(Calendar.YEAR);
  751. calendar.set(year, month, day, 0,0,0);
  752. long milli = calendar.getTimeInMillis();
  753. Date today = new Date(milli);
  754. return (milli / (long) 1000) * (long) 1000;
  755. }
  756. /**
  757. * Returns the milliseconds for the day yesterday (not the time).
  758. * @return long
  759. */
  760. private long yesterdayMilliseconds(){
  761. Date current = new Date();
  762. calendar.setTimeInMillis(current.getTime());
  763. int day = calendar.get(Calendar.DATE);
  764. int month = calendar.get(Calendar.MONTH);
  765. int year = calendar.get(Calendar.YEAR);
  766. calendar.set(year, month, day, 0,0,0);
  767. calendar.add(Calendar.DATE, -1);
  768. long milli = calendar.getTimeInMillis();
  769. Date today = new Date(milli);
  770. return (milli / (long) 1000) * (long) 1000;
  771. }
  772. /**
  773. * returns just the date not the time of a date.
  774. * @param date Date
  775. * @return long
  776. */
  777. private long dayMilliseconds(long date){
  778. //Date current = new Date();
  779. calendar.setTimeInMillis(date);
  780. int day = calendar.get(Calendar.DATE);
  781. int month = calendar.get(Calendar.MONTH);
  782. int year = calendar.get(Calendar.YEAR);
  783. calendar.set(year, month, day, 0,0,0);
  784. long milli = calendar.getTimeInMillis();
  785. Date test = new Date(milli);
  786. return (milli / (long) 1000) * (long) 1000;
  787. }
  788. /**Returns a date as a formated string
  789. * @param timeStamp date
  790. * @return String date format is localised*/
  791. @SuppressLint("SimpleDateFormat")
  792. private String getDateAsMonthString(long timeStamp) {
  793. try {
  794. Date netDate = (new Date(timeStamp));
  795. return groupingDateFormatter.format(netDate);
  796. } catch (Exception ex) {
  797. return "xx";
  798. }
  799. }
  800. /*****************************
  801. *
  802. * Getter / Setter
  803. *
  804. * ***************************/
  805. public boolean isShowFilterButton() {
  806. return showFilterButton;
  807. }
  808. public void setShowFilterButton(boolean showFilterButton) {
  809. this.showFilterButton = showFilterButton;
  810. }
  811. /**
  812. * Set the group key for grouping the records.
  813. * All possible grouping keys are:
  814. * R.string.date,
  815. * R.string.rec_protocol,
  816. * R.string.ESSID,
  817. * R.string.BSSID
  818. * @param key String
  819. */
  820. public void setGroupKey(String key){
  821. this.groupingKey = key;
  822. }
  823. public void setFilter(LogFilter filter){
  824. this.filter = filter;
  825. }
  826. /*****************************
  827. *
  828. * Open Dialog Methods
  829. *
  830. * ***************************/
  831. /**Opens the grouping dialog*/
  832. private void openGroupingDialog(){
  833. ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_GROUP, this.groupingTitles(), this.selectedGroup(), false , this);
  834. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_GROUP);
  835. }
  836. /**opens the bssid filter dialog*/
  837. private void openBSSIDFilterDialog(){
  838. ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_BSSID,this.bssids(), this.selectedBSSIDs(), true , this);
  839. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_BSSID);
  840. }
  841. /**opens the essid filter dialog*/
  842. private void openESSIDFilterDialog(){
  843. ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_ESSID,this.essids(), this.selectedESSIDs(), true , this);
  844. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_ESSID);
  845. }
  846. /**opens the protocol filter dialog*/
  847. private void openProtocolsFilterDialog(){
  848. ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_PROTOCOLS,this.protocolTitles(), this.selectedProtocols(), true , this);
  849. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_PROTOCOLS);
  850. }
  851. /**opens the timestamp filter dialog (minimal timestamp required)*/
  852. private void openTimestampFromFilterDialog(){
  853. this.wasBelowTimePicker = false;
  854. DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
  855. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
  856. if (this.filter.aboveTimestamp != Long.MIN_VALUE)newFragment.setDate(this.filter.aboveTimestamp);
  857. }
  858. /**opens time timestamp filter dialog (maximal timestamp required)*/
  859. private void openTimestampToFilterDialog(){
  860. this.wasBelowTimePicker = true;
  861. DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
  862. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
  863. if (this.filter.belowTimestamp != Long.MAX_VALUE) newFragment.setDate(this.filter.belowTimestamp);
  864. }
  865. /**opens the sorting dialog*/
  866. private void openSortingDialog(){
  867. ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_SORTING,this.sortTypeTiles(), this.selectedSorttype(), false , this);
  868. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
  869. }
  870. /*****************************
  871. *
  872. * Grouping Stuff
  873. *
  874. * ***************************/
  875. /**returns the group title for the given record. Uses the groupingKey to decied which value of the record should be used.
  876. * @param rec {@link Record Record }
  877. * @return String grouptitle*/
  878. public String getGroupValue(Record rec){
  879. int index = this.groupingTitles().indexOf(this.groupingKey);
  880. switch (index){
  881. case 1:
  882. return rec.getProtocol();
  883. case 2:
  884. return rec.getSsid();
  885. case 3:
  886. return rec.getBssid();
  887. case 0:
  888. return this.getFormattedDateForGrouping(rec.getTimestamp());
  889. default:
  890. return this.getFormattedDateForGrouping(rec.getTimestamp());
  891. }
  892. }
  893. /**Returns the Group titles for the specified grouping key. e.g. groupingKey is "ESSID" it returns all available essids.
  894. * @return ArrayList<String> grouptitles*/
  895. public List<String> getGroupTitles(){
  896. int index = this.groupingTitles().indexOf(this.groupingKey);
  897. switch (index){
  898. case 1:
  899. return this.protocolTitles();
  900. case 2:
  901. return this.essids();
  902. case 3:
  903. return this.bssids();
  904. case 0:
  905. default:
  906. RecordListAdapter adapter = (RecordListAdapter) this.expListView.getExpandableListAdapter();
  907. if (adapter != null){
  908. return adapter.getSectionHeaders();
  909. }
  910. return new ArrayList<String>();
  911. }
  912. }
  913. /*****************************
  914. *
  915. * Filter Stuff
  916. *
  917. * ***************************/
  918. /**Returns the FilterButton.
  919. * @return ImageButton filterButton*/
  920. private ImageButton getFilterButton(){
  921. return (ImageButton) this.rootView.findViewById(R.id.FilterButton);
  922. }
  923. /**Opens the filter menu on a anchor view. The filter menu will always be on top of the anchor.
  924. * @param v View the anchorView*/
  925. private void openFilterPopupMenuOnView(View v){
  926. SimplePopupTable filterMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
  927. public void onItemClick(Object ob) {
  928. if (ob instanceof AbstractPopupItem){
  929. AbstractPopupItem item = (AbstractPopupItem) ob;
  930. RecordOverviewFragment.this.onFilterMenuItemSelected(item);
  931. }
  932. }
  933. });
  934. filterMenu.setTitle(FILTER_MENU_POPUP_TITLE);
  935. for(String title : RecordOverviewFragment.this.filterMenuTitles()){
  936. AbstractPopupItem item = null;
  937. if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)) continue;
  938. if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)){
  939. item = new SplitPopupItem(this.getActivity());
  940. item.setValue(SplitPopupItem.RIGHT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_BELOW);
  941. item.setValue(SplitPopupItem.LEFT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
  942. if (this.filter.hasBelowTimestamp()){
  943. item.setValue(SplitPopupItem.RIGHT_SUBTITLE, this.getDateAsString(this.filter.belowTimestamp));
  944. }
  945. if (this.filter.hasAboveTimestamp()){
  946. item.setValue(SplitPopupItem.LEFT_SUBTITLE, this.getDateAsString(this.filter.aboveTimestamp));
  947. }
  948. } else {
  949. item = new SimplePopupItem(this.getActivity());
  950. item.setTitle(title);
  951. ((SimplePopupItem)item).setSelected(this.isFilterSetForTitle(title));
  952. }
  953. filterMenu.addItem(item);
  954. }
  955. filterMenu.showOnView(v);
  956. }
  957. /**Returns true if the filter object is set for the given title otherwise false. e.g. the filter object has protocols,
  958. * so the method will return for the title FILTER_MENU_TITLE_PROTOCOLS TRUE.
  959. * @param title String
  960. * @return boolean value
  961. * */
  962. private boolean isFilterSetForTitle(String title){
  963. if (title.equals(FILTER_MENU_TITLE_BSSID)){
  964. return this.filter.hasBSSIDs();
  965. }
  966. if (title.equals(FILTER_MENU_TITLE_ESSID)){
  967. return this.filter.hasESSIDs();
  968. }
  969. if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
  970. return this.filter.hasProtocols();
  971. }
  972. if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)){
  973. return this.filter.hasBelowTimestamp();
  974. }
  975. if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)){
  976. return this.filter.hasAboveTimestamp();
  977. }
  978. return false;
  979. }
  980. /**clears the filter. Does not invoke populatelistview!*/
  981. private void clearFilter(){
  982. if(filter == null) this.filter = new LogFilter();
  983. this.filter.clear();
  984. }
  985. /**Returns all grouping titles.
  986. * @return ArrayList<String> tiles*/
  987. public ArrayList<String> groupingTitles(){
  988. ArrayList<String> titles = new ArrayList<String>();
  989. titles.add(MainActivity.getContext().getString(R.string.date));
  990. titles.add(MainActivity.getContext().getString(R.string.rec_protocol));
  991. titles.add(MainActivity.getContext().getString(R.string.ESSID));
  992. titles.add(MainActivity.getContext().getString(R.string.BSSID));
  993. return titles;
  994. }
  995. /**
  996. * Returns a bool array. This array is true at the index of the groupingKey in groupingTitles(), otherwise false.
  997. * @return boolean[] selection
  998. * */
  999. public boolean[] selectedGroup(){
  1000. ArrayList<String> groups = this.groupingTitles();
  1001. boolean[] selected = new boolean[groups.size()];
  1002. int i = 0;
  1003. for(String group : groups){
  1004. selected[i] =(group.equals(this.groupingKey));
  1005. i++;
  1006. }
  1007. return selected;
  1008. }
  1009. /**Returns all protocol titles / names.
  1010. * @return ArrayList<String> protocolTitles
  1011. * */
  1012. public ArrayList<String> protocolTitles(){
  1013. ArrayList<String> titles = new ArrayList<String>();
  1014. for (String protocol : this.getResources().getStringArray(
  1015. R.array.protocols)) {
  1016. titles.add(protocol);
  1017. }
  1018. titles.add("PORTSCAN");
  1019. titles.add("FILE INJECTION");
  1020. titles.add("MULTISTAGE ATTACK");
  1021. return titles;
  1022. }
  1023. /**Return a boolean array of the selected / filtered protocols. If the filter object has
  1024. * an protocol from the protocolTitles() array, the index of it will be true, otherwise false.
  1025. * @return boolean[] protocol selection
  1026. * */
  1027. public boolean[] selectedProtocols(){
  1028. ArrayList<String> protocols = this.protocolTitles();
  1029. boolean[] selected = new boolean[protocols.size()];
  1030. int i = 0;
  1031. for(String protocol : protocols){
  1032. selected[i] =(this.filter.protocols.contains(protocol));
  1033. i++;
  1034. }
  1035. return selected;
  1036. }
  1037. /**
  1038. * Returns the Sorttype Titles
  1039. * @return ArayList<String> Sort type titles
  1040. * */
  1041. public ArrayList<String> sortTypeTiles(){
  1042. ArrayList<String> titles = new ArrayList<String>();
  1043. titles.add(MainActivity.getContext().getString(R.string.rec_time));
  1044. titles.add(MainActivity.getContext().getString(R.string.rec_protocol));
  1045. titles.add(MainActivity.getContext().getString(R.string.ESSID));
  1046. titles.add(MainActivity.getContext().getString(R.string.BSSID));
  1047. return titles;
  1048. }
  1049. /**
  1050. * Returns an boolean array. The array is true at the index of the selected sort type..
  1051. * The index of the selected sort type is the same index in the sortTypeTiles array.
  1052. * @return boolean array, length == sortTypeTiles().length
  1053. * */
  1054. public boolean[] selectedSorttype(){
  1055. ArrayList<String> types = this.sortTypeTiles();
  1056. boolean[] selected = new boolean[types.size()];
  1057. int i = 0;
  1058. for(String sorttype : types){
  1059. selected[i] =(this.filter.sorttype.toString().equals(sorttype));
  1060. i++;
  1061. }
  1062. return selected;
  1063. }
  1064. /**
  1065. * Returns all unique bssids.
  1066. * @return ArrayList<String>
  1067. * */
  1068. public ArrayList<String> bssids(){
  1069. ArrayList<String> records = dbh.getUniqueBSSIDRecords();
  1070. return records;
  1071. }
  1072. /**
  1073. * Returns an boolean array. The array is true at the indices of the selected bssids.
  1074. * The index of the selected bssid is the same index in the bssids() array.
  1075. * @return boolean array, length == bssids().length
  1076. * */
  1077. public boolean[] selectedBSSIDs(){
  1078. ArrayList<String> bssids = this.bssids();
  1079. boolean[] selected = new boolean[bssids.size()];
  1080. int i = 0;
  1081. for(String bssid : bssids){
  1082. selected[i] =(this.filter.BSSIDs.contains(bssid));
  1083. i++;
  1084. }
  1085. return selected;
  1086. }
  1087. /**
  1088. * Returns all unique essids.
  1089. * @return ArrayList<String>
  1090. * */
  1091. public ArrayList<String> essids(){
  1092. ArrayList<String> records = dbh.getUniqueESSIDRecords();
  1093. return records;
  1094. }
  1095. /**
  1096. * Returns an boolean array. The array is true at the indices of the selected essids.
  1097. * The index of the selected essid is the same index in the essids() array.
  1098. * @return boolean array, length == essids().length
  1099. * */
  1100. public boolean[] selectedESSIDs(){
  1101. ArrayList<String> essids = this.essids();
  1102. boolean[] selected = new boolean[essids.size()];
  1103. int i = 0;
  1104. for(String essid : essids){
  1105. selected[i] =(this.filter.ESSIDs.contains(essid));
  1106. i++;
  1107. }
  1108. return selected;
  1109. }
  1110. /**
  1111. * Returns all filter menu titles.
  1112. * @return ArrayList<String>
  1113. * */
  1114. private ArrayList<String> filterMenuTitles(){
  1115. ArrayList<String> titles = new ArrayList<String>();
  1116. titles.add(FILTER_MENU_TITLE_BSSID);
  1117. titles.add(FILTER_MENU_TITLE_ESSID);
  1118. titles.add(FILTER_MENU_TITLE_PROTOCOLS);
  1119. titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
  1120. titles.add(FILTER_MENU_TITLE_TIMESTAMP_BELOW);
  1121. if (this.filter.isSet())titles.add(FILTER_MENU_TITLE_REMOVE);
  1122. return titles;
  1123. }
  1124. /*****************************
  1125. *
  1126. * Listener Actions
  1127. *
  1128. * ***************************/
  1129. /**
  1130. * Will be called if the users selects a timestamp.
  1131. * @param dialog {@link DateTimeDialogFragment DateTimeDialogFragment }
  1132. * */
  1133. public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
  1134. if(this.wasBelowTimePicker){
  1135. this.filter.setBelowTimestamp(dialog.getDate());
  1136. } else {
  1137. this.filter.setAboveTimestamp(dialog.getDate());
  1138. }
  1139. this.actualiseListViewInBackground();
  1140. this.actualiseFilterButton();
  1141. }
  1142. /**
  1143. * Will be called if the users cancels a timestamp selection.
  1144. * @param dialog {@link DateTimeDialogFragment DateTimeDialogFragment }
  1145. * */
  1146. public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
  1147. if(this.wasBelowTimePicker){
  1148. this.filter.setBelowTimestamp(Long.MAX_VALUE);
  1149. } else {
  1150. this.filter.setAboveTimestamp(Long.MIN_VALUE);
  1151. }
  1152. this.actualiseListViewInBackground();
  1153. this.actualiseFilterButton();
  1154. }
  1155. /**
  1156. * Will be called if the users clicks the positiv button on a ChechlistDialog.
  1157. * @param dialog {@link ChecklistDialog ChecklistDialog }
  1158. */
  1159. public void onDialogPositiveClick(ChecklistDialog dialog) {
  1160. String title = dialog.getTitle();
  1161. if(title.equals(FILTER_MENU_TITLE_BSSID)){
  1162. ArrayList<String> titles =dialog.getSelectedItemTitles();
  1163. if (titles.size() == this.bssids().size()){
  1164. this.filter.setBSSIDs(new ArrayList<String>());
  1165. } else {
  1166. this.filter.setBSSIDs(titles);
  1167. }
  1168. }
  1169. if(title.equals(FILTER_MENU_TITLE_ESSID)){
  1170. ArrayList<String> titles =dialog.getSelectedItemTitles();
  1171. if (titles.size() == this.essids().size()){
  1172. this.filter.setESSIDs(new ArrayList<String>());
  1173. } else {
  1174. this.filter.setESSIDs(titles);
  1175. }
  1176. }
  1177. if(title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
  1178. ArrayList<String> protocols = dialog.getSelectedItemTitles();
  1179. if (protocols.size() == this.protocolTitles().size()){
  1180. this.filter.setProtocols(new ArrayList<String>());
  1181. } else {
  1182. this.filter.setProtocols(dialog.getSelectedItemTitles());
  1183. }
  1184. }
  1185. if(title.equals(FILTER_MENU_TITLE_SORTING)){
  1186. ArrayList<String> titles = dialog.getSelectedItemTitles();
  1187. if (titles.size() == 0) return;
  1188. // ALWAYS GET THE FIRST ELEMENT (SHOULD BE ALWAYS ONE)
  1189. String t = titles.get(0);
  1190. int sortType = this.sortTypeTiles().indexOf(t);
  1191. this.filter.setSorttype(SortType.values()[sortType]);
  1192. }
  1193. if (title.equals(FILTER_MENU_TITLE_GROUP)){
  1194. ArrayList<String> titles = dialog.getSelectedItemTitles();
  1195. if (titles.size() == 0) return;
  1196. // ALWAYS GET THE FIRST ELEMENT (SHOULD BE ALWAYS ONE)
  1197. this.groupingKey = titles.get(0);
  1198. }
  1199. this.actualiseListViewInBackground();
  1200. this.actualiseFilterButton();
  1201. }
  1202. /**Paints the filter button if the current filter object is set.*/
  1203. private void actualiseFilterButton(){
  1204. if (this.filter.isSet() ){
  1205. ImageButton filterButton = this.getFilterButton();
  1206. if (filterButton != null){
  1207. filterButton.setImageResource(R.drawable.ic_filter_pressed);
  1208. filterButton.invalidate();
  1209. }
  1210. } else {
  1211. ImageButton filterButton = this.getFilterButton();
  1212. if (filterButton != null){
  1213. filterButton.setImageResource(R.drawable.ic_filter);
  1214. filterButton.invalidate();
  1215. }
  1216. }
  1217. }
  1218. /**
  1219. * Deletes the current displayed attacks.
  1220. */
  1221. public void deleteFilteredAttacks(){
  1222. LogFilter filter = this.filter;
  1223. dbh.deleteAttacksByFilter(filter);
  1224. this.actualiseListViewInBackground();
  1225. }
  1226. /**
  1227. * Will be called if the users clicks the negativ button on a ChechlistDialog.
  1228. * @param dialog {@link ChecklistDialog ChecklistDialog }
  1229. */
  1230. public void onDialogNegativeClick(ChecklistDialog dialog) {}
  1231. /*****************************
  1232. *
  1233. * TEST
  1234. *
  1235. * ***************************/
  1236. /**
  1237. * This will clear the database at first and than add new attacks.
  1238. * @param createNetworks number of networks to create
  1239. * @param attacksPerNetwork maximal number of attack per network
  1240. * @param maxMessagePerAttack maximal number of messages per attack
  1241. * */
  1242. private void addRecordToDB( int createNetworks, int attacksPerNetwork, int maxMessagePerAttack) {
  1243. if ((dbh.getRecordCount() > 0)) dbh.clearData();
  1244. Calendar cal = Calendar.getInstance();
  1245. int maxProtocolsIndex = this.getResources().getStringArray(
  1246. R.array.protocols).length;
  1247. Random random = new Random();
  1248. LatLng tudarmstadtLoc = new LatLng(49.86923, 8.6632768);
  1249. final double ssidRadius = 0.1;
  1250. final double bssidRadius = 0.004;
  1251. int attackId = 0;
  1252. ArrayList<NetworkRecord> networkRecords = new ArrayList<NetworkRecord>();
  1253. ArrayList<AttackRecord> attackRecords = new ArrayList<AttackRecord>();
  1254. ArrayList<MessageRecord> messageRecords = new ArrayList<MessageRecord>();
  1255. for (int numOfNetworks = 0; numOfNetworks < createNetworks; numOfNetworks++){
  1256. String ssidName = "WiFi" + ((numOfNetworks) + 1);
  1257. String bssidName = "127.0.0." + ((numOfNetworks) + 1);
  1258. int protocolIndex = numOfNetworks % maxProtocolsIndex;
  1259. String protocolName = this.getResources().getStringArray(
  1260. R.array.protocols)[protocolIndex];
  1261. int numOfAttackPerNetwork = (Math.abs(random.nextInt()) % Math.max(1, attacksPerNetwork + 1));
  1262. NetworkRecord network = new NetworkRecord();
  1263. network.setBssid(bssidName);
  1264. network.setSsid(ssidName);
  1265. LatLng ssidLocation = new LatLng(tudarmstadtLoc.latitude - ssidRadius + 2.0 * ssidRadius * Math.random(), tudarmstadtLoc.longitude - ssidRadius + 2.0 * ssidRadius * Math.random());
  1266. double latitude = ssidLocation.latitude - bssidRadius + 2.0 * bssidRadius * Math.random();
  1267. double longitude = ssidLocation.longitude - bssidRadius + 2.0 * bssidRadius * Math.random();
  1268. long timestamp = cal.getTimeInMillis();
  1269. network.setTimestampLocation(timestamp);
  1270. network.setLongitude(longitude);
  1271. network.setLatitude(latitude);
  1272. network.setAccuracy(0.f);
  1273. //dbh.updateNetworkInformation(network);
  1274. networkRecords.add(network);
  1275. // ATTACKS PER NETWORK
  1276. for (int attackNumber = 0; attackNumber < numOfAttackPerNetwork; attackNumber++) {
  1277. int numRecordsPerAttack = (Math.abs(random.nextInt()) % (Math.max( maxMessagePerAttack, 1))) + 1;
  1278. if (maxMessagePerAttack <= 0) numRecordsPerAttack = 0;
  1279. /* ADD A ATTACK*/
  1280. AttackRecord attack = new AttackRecord(true);
  1281. attack.setBssid(bssidName);
  1282. attack.setProtocol(protocolName);
  1283. attack.setLocalIP(bssidName);
  1284. //dbh.addAttackRecord(attack);
  1285. attackRecords.add(attack);
  1286. // MESSAGE PER ATTACK
  1287. for (int messageID = attackId; messageID < attackId + numRecordsPerAttack; messageID++) {
  1288. MessageRecord message = new MessageRecord(true);
  1289. //message.setId(messageID);
  1290. message.setAttack_id(attack.getAttack_id());
  1291. // GO BACK IN TIME
  1292. message.setTimestamp(cal.getTimeInMillis()
  1293. - ((messageID * 60 * 60 * 24) * 1000) + (1000 * ((messageID - attackId) + 1)));
  1294. if ((messageID - attackId) % 2 == 0){
  1295. message.setType(MessageRecord.TYPE.RECEIVE);
  1296. } else {
  1297. message.setType(MessageRecord.TYPE.SEND);
  1298. }
  1299. message.setPacket("");
  1300. //dbh.addMessageRecord(message);
  1301. messageRecords.add(message);
  1302. }
  1303. attackId+=numRecordsPerAttack;
  1304. }
  1305. }
  1306. dbh.updateNetworkInformation(networkRecords);
  1307. dbh.insertAttackRecords(attackRecords);
  1308. dbh.insertMessageRecords(messageRecords);
  1309. // int countAllLogs = dbh.getAllRecords().size();
  1310. // int countRecords = dbh.getRecordCount();
  1311. // int countAttacks = dbh.getAttackCount();
  1312. //
  1313. // if ((countRecords == 0)) {
  1314. // Record rec = dbh.getRecordOfAttackId(0);
  1315. // Record rec2 = dbh.getRecord(0);
  1316. //
  1317. // System.out.println("" + "Could not create logs!");
  1318. // }
  1319. }
  1320. /**Navigation. Shows the record detail view for the given record
  1321. * @param record {@link Record Record } to show
  1322. * */
  1323. private void pushRecordDetailViewForRecord(Record record){
  1324. FragmentManager fm = this.getActivity().getFragmentManager();
  1325. if (fm != null){
  1326. RecordDetailFragment newFragment = new RecordDetailFragment();
  1327. newFragment.setRecord(record);
  1328. newFragment.setUpNavigatible(true);
  1329. MainActivity.getInstance().injectFragment(newFragment);
  1330. }
  1331. }
  1332. }