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