RecordOverviewFragment.java 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  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. }
  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. return titles;
  1020. }
  1021. /**Return a boolean array of the selected / filtered protocols. If the filter object has
  1022. * an protocol from the protocolTitles() array, the index of it will be true, otherwise false.
  1023. * @return boolean[] protocol selection
  1024. * */
  1025. public boolean[] selectedProtocols(){
  1026. ArrayList<String> protocols = this.protocolTitles();
  1027. boolean[] selected = new boolean[protocols.size()];
  1028. int i = 0;
  1029. for(String protocol : protocols){
  1030. selected[i] =(this.filter.protocols.contains(protocol));
  1031. i++;
  1032. }
  1033. return selected;
  1034. }
  1035. /**
  1036. * Returns the Sorttype Titles
  1037. * @return ArayList<String> Sort type titles
  1038. * */
  1039. public ArrayList<String> sortTypeTiles(){
  1040. ArrayList<String> titles = new ArrayList<String>();
  1041. titles.add(MainActivity.getContext().getString(R.string.rec_time));
  1042. titles.add(MainActivity.getContext().getString(R.string.rec_protocol));
  1043. titles.add(MainActivity.getContext().getString(R.string.ESSID));
  1044. titles.add(MainActivity.getContext().getString(R.string.BSSID));
  1045. return titles;
  1046. }
  1047. /**
  1048. * Returns an boolean array. The array is true at the index of the selected sort type..
  1049. * The index of the selected sort type is the same index in the sortTypeTiles array.
  1050. * @return boolean array, length == sortTypeTiles().length
  1051. * */
  1052. public boolean[] selectedSorttype(){
  1053. ArrayList<String> types = this.sortTypeTiles();
  1054. boolean[] selected = new boolean[types.size()];
  1055. int i = 0;
  1056. for(String sorttype : types){
  1057. selected[i] =(this.filter.sorttype.toString().equals(sorttype));
  1058. i++;
  1059. }
  1060. return selected;
  1061. }
  1062. /**
  1063. * Returns all unique bssids.
  1064. * @return ArrayList<String>
  1065. * */
  1066. public ArrayList<String> bssids(){
  1067. ArrayList<String> records = dbh.getUniqueBSSIDRecords();
  1068. return records;
  1069. }
  1070. /**
  1071. * Returns an boolean array. The array is true at the indices of the selected bssids.
  1072. * The index of the selected bssid is the same index in the bssids() array.
  1073. * @return boolean array, length == bssids().length
  1074. * */
  1075. public boolean[] selectedBSSIDs(){
  1076. ArrayList<String> bssids = this.bssids();
  1077. boolean[] selected = new boolean[bssids.size()];
  1078. int i = 0;
  1079. for(String bssid : bssids){
  1080. selected[i] =(this.filter.BSSIDs.contains(bssid));
  1081. i++;
  1082. }
  1083. return selected;
  1084. }
  1085. /**
  1086. * Returns all unique essids.
  1087. * @return ArrayList<String>
  1088. * */
  1089. public ArrayList<String> essids(){
  1090. ArrayList<String> records = dbh.getUniqueESSIDRecords();
  1091. return records;
  1092. }
  1093. /**
  1094. * Returns an boolean array. The array is true at the indices of the selected essids.
  1095. * The index of the selected essid is the same index in the essids() array.
  1096. * @return boolean array, length == essids().length
  1097. * */
  1098. public boolean[] selectedESSIDs(){
  1099. ArrayList<String> essids = this.essids();
  1100. boolean[] selected = new boolean[essids.size()];
  1101. int i = 0;
  1102. for(String essid : essids){
  1103. selected[i] =(this.filter.ESSIDs.contains(essid));
  1104. i++;
  1105. }
  1106. return selected;
  1107. }
  1108. /**
  1109. * Returns all filter menu titles.
  1110. * @return ArrayList<String>
  1111. * */
  1112. private ArrayList<String> filterMenuTitles(){
  1113. ArrayList<String> titles = new ArrayList<String>();
  1114. titles.add(FILTER_MENU_TITLE_BSSID);
  1115. titles.add(FILTER_MENU_TITLE_ESSID);
  1116. titles.add(FILTER_MENU_TITLE_PROTOCOLS);
  1117. titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
  1118. titles.add(FILTER_MENU_TITLE_TIMESTAMP_BELOW);
  1119. if (this.filter.isSet())titles.add(FILTER_MENU_TITLE_REMOVE);
  1120. return titles;
  1121. }
  1122. /*****************************
  1123. *
  1124. * Listener Actions
  1125. *
  1126. * ***************************/
  1127. /**
  1128. * Will be called if the users selects a timestamp.
  1129. * @param dialog {@link DateTimeDialogFragment DateTimeDialogFragment }
  1130. * */
  1131. public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
  1132. if(this.wasBelowTimePicker){
  1133. this.filter.setBelowTimestamp(dialog.getDate());
  1134. } else {
  1135. this.filter.setAboveTimestamp(dialog.getDate());
  1136. }
  1137. this.actualiseListViewInBackground();
  1138. this.actualiseFilterButton();
  1139. }
  1140. /**
  1141. * Will be called if the users cancels a timestamp selection.
  1142. * @param dialog {@link DateTimeDialogFragment DateTimeDialogFragment }
  1143. * */
  1144. public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
  1145. if(this.wasBelowTimePicker){
  1146. this.filter.setBelowTimestamp(Long.MAX_VALUE);
  1147. } else {
  1148. this.filter.setAboveTimestamp(Long.MIN_VALUE);
  1149. }
  1150. this.actualiseListViewInBackground();
  1151. this.actualiseFilterButton();
  1152. }
  1153. /**
  1154. * Will be called if the users clicks the positiv button on a ChechlistDialog.
  1155. * @param dialog {@link ChecklistDialog ChecklistDialog }
  1156. */
  1157. public void onDialogPositiveClick(ChecklistDialog dialog) {
  1158. String title = dialog.getTitle();
  1159. if(title.equals(FILTER_MENU_TITLE_BSSID)){
  1160. ArrayList<String> titles =dialog.getSelectedItemTitles();
  1161. if (titles.size() == this.bssids().size()){
  1162. this.filter.setBSSIDs(new ArrayList<String>());
  1163. } else {
  1164. this.filter.setBSSIDs(titles);
  1165. }
  1166. }
  1167. if(title.equals(FILTER_MENU_TITLE_ESSID)){
  1168. ArrayList<String> titles =dialog.getSelectedItemTitles();
  1169. if (titles.size() == this.essids().size()){
  1170. this.filter.setESSIDs(new ArrayList<String>());
  1171. } else {
  1172. this.filter.setESSIDs(titles);
  1173. }
  1174. }
  1175. if(title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
  1176. ArrayList<String> protocols = dialog.getSelectedItemTitles();
  1177. if (protocols.size() == this.protocolTitles().size()){
  1178. this.filter.setProtocols(new ArrayList<String>());
  1179. } else {
  1180. this.filter.setProtocols(dialog.getSelectedItemTitles());
  1181. }
  1182. }
  1183. if(title.equals(FILTER_MENU_TITLE_SORTING)){
  1184. ArrayList<String> titles = dialog.getSelectedItemTitles();
  1185. if (titles.size() == 0) return;
  1186. // ALWAYS GET THE FIRST ELEMENT (SHOULD BE ALWAYS ONE)
  1187. String t = titles.get(0);
  1188. int sortType = this.sortTypeTiles().indexOf(t);
  1189. this.filter.setSorttype(SortType.values()[sortType]);
  1190. }
  1191. if (title.equals(FILTER_MENU_TITLE_GROUP)){
  1192. ArrayList<String> titles = dialog.getSelectedItemTitles();
  1193. if (titles.size() == 0) return;
  1194. // ALWAYS GET THE FIRST ELEMENT (SHOULD BE ALWAYS ONE)
  1195. this.groupingKey = titles.get(0);
  1196. }
  1197. this.actualiseListViewInBackground();
  1198. this.actualiseFilterButton();
  1199. }
  1200. /**Paints the filter button if the current filter object is set.*/
  1201. private void actualiseFilterButton(){
  1202. if (this.filter.isSet() ){
  1203. ImageButton filterButton = this.getFilterButton();
  1204. if (filterButton != null){
  1205. filterButton.setImageResource(R.drawable.ic_filter_pressed);
  1206. filterButton.invalidate();
  1207. }
  1208. } else {
  1209. ImageButton filterButton = this.getFilterButton();
  1210. if (filterButton != null){
  1211. filterButton.setImageResource(R.drawable.ic_filter);
  1212. filterButton.invalidate();
  1213. }
  1214. }
  1215. }
  1216. /**
  1217. * Deletes the current displayed attacks.
  1218. */
  1219. public void deleteFilteredAttacks(){
  1220. LogFilter filter = this.filter;
  1221. dbh.deleteAttacksByFilter(filter);
  1222. this.actualiseListViewInBackground();
  1223. }
  1224. /**
  1225. * Will be called if the users clicks the negativ button on a ChechlistDialog.
  1226. * @param dialog {@link ChecklistDialog ChecklistDialog }
  1227. */
  1228. public void onDialogNegativeClick(ChecklistDialog dialog) {}
  1229. /*****************************
  1230. *
  1231. * TEST
  1232. *
  1233. * ***************************/
  1234. /**
  1235. * This will clear the database at first and than add new attacks.
  1236. * @param createNetworks number of networks to create
  1237. * @param attacksPerNetwork maximal number of attack per network
  1238. * @param maxMessagePerAttack maximal number of messages per attack
  1239. * */
  1240. private void addRecordToDB( int createNetworks, int attacksPerNetwork, int maxMessagePerAttack) {
  1241. if ((dbh.getRecordCount() > 0)) dbh.clearData();
  1242. Calendar cal = Calendar.getInstance();
  1243. int maxProtocolsIndex = this.getResources().getStringArray(
  1244. R.array.protocols).length;
  1245. Random random = new Random();
  1246. LatLng tudarmstadtLoc = new LatLng(49.86923, 8.6632768);
  1247. final double ssidRadius = 0.1;
  1248. final double bssidRadius = 0.004;
  1249. int attackId = 0;
  1250. ArrayList<NetworkRecord> networkRecords = new ArrayList<NetworkRecord>();
  1251. ArrayList<AttackRecord> attackRecords = new ArrayList<AttackRecord>();
  1252. ArrayList<MessageRecord> messageRecords = new ArrayList<MessageRecord>();
  1253. for (int numOfNetworks = 0; numOfNetworks < createNetworks; numOfNetworks++){
  1254. String ssidName = "WiFi" + ((numOfNetworks) + 1);
  1255. String bssidName = "127.0.0." + ((numOfNetworks) + 1);
  1256. int protocolIndex = numOfNetworks % maxProtocolsIndex;
  1257. String protocolName = this.getResources().getStringArray(
  1258. R.array.protocols)[protocolIndex];
  1259. int numOfAttackPerNetwork = (Math.abs(random.nextInt()) % Math.max(1, attacksPerNetwork + 1));
  1260. NetworkRecord network = new NetworkRecord();
  1261. network.setBssid(bssidName);
  1262. network.setSsid(ssidName);
  1263. LatLng ssidLocation = new LatLng(tudarmstadtLoc.latitude - ssidRadius + 2.0 * ssidRadius * Math.random(), tudarmstadtLoc.longitude - ssidRadius + 2.0 * ssidRadius * Math.random());
  1264. double latitude = ssidLocation.latitude - bssidRadius + 2.0 * bssidRadius * Math.random();
  1265. double longitude = ssidLocation.longitude - bssidRadius + 2.0 * bssidRadius * Math.random();
  1266. long timestamp = cal.getTimeInMillis();
  1267. network.setTimestampLocation(timestamp);
  1268. network.setLongitude(longitude);
  1269. network.setLatitude(latitude);
  1270. network.setAccuracy(0.f);
  1271. //dbh.updateNetworkInformation(network);
  1272. networkRecords.add(network);
  1273. // ATTACKS PER NETWORK
  1274. for (int attackNumber = 0; attackNumber < numOfAttackPerNetwork; attackNumber++) {
  1275. int numRecordsPerAttack = (Math.abs(random.nextInt()) % (Math.max( maxMessagePerAttack, 1))) + 1;
  1276. if (maxMessagePerAttack <= 0) numRecordsPerAttack = 0;
  1277. /* ADD A ATTACK*/
  1278. AttackRecord attack = new AttackRecord(true);
  1279. attack.setBssid(bssidName);
  1280. attack.setProtocol(protocolName);
  1281. attack.setLocalIP(bssidName);
  1282. //dbh.addAttackRecord(attack);
  1283. attackRecords.add(attack);
  1284. // MESSAGE PER ATTACK
  1285. for (int messageID = attackId; messageID < attackId + numRecordsPerAttack; messageID++) {
  1286. MessageRecord message = new MessageRecord(true);
  1287. //message.setId(messageID);
  1288. message.setAttack_id(attack.getAttack_id());
  1289. // GO BACK IN TIME
  1290. message.setTimestamp(cal.getTimeInMillis()
  1291. - ((messageID * 60 * 60 * 24) * 1000) + (1000 * ((messageID - attackId) + 1)));
  1292. if ((messageID - attackId) % 2 == 0){
  1293. message.setType(MessageRecord.TYPE.RECEIVE);
  1294. } else {
  1295. message.setType(MessageRecord.TYPE.SEND);
  1296. }
  1297. message.setPacket("");
  1298. //dbh.addMessageRecord(message);
  1299. messageRecords.add(message);
  1300. }
  1301. attackId+=numRecordsPerAttack;
  1302. }
  1303. }
  1304. dbh.updateNetworkInformation(networkRecords);
  1305. dbh.insertAttackRecords(attackRecords);
  1306. dbh.insertMessageRecords(messageRecords);
  1307. // int countAllLogs = dbh.getAllRecords().size();
  1308. // int countRecords = dbh.getRecordCount();
  1309. // int countAttacks = dbh.getAttackCount();
  1310. //
  1311. // if ((countRecords == 0)) {
  1312. // Record rec = dbh.getRecordOfAttackId(0);
  1313. // Record rec2 = dbh.getRecord(0);
  1314. //
  1315. // System.out.println("" + "Could not create logs!");
  1316. // }
  1317. }
  1318. /**Navigation. Shows the record detail view for the given record
  1319. * @param record {@link Record Record } to show
  1320. * */
  1321. private void pushRecordDetailViewForRecord(Record record){
  1322. FragmentManager fm = this.getActivity().getFragmentManager();
  1323. if (fm != null){
  1324. RecordDetailFragment newFragment = new RecordDetailFragment();
  1325. newFragment.setRecord(record);
  1326. newFragment.setUpNavigatible(true);
  1327. MainActivity.getInstance().injectFragment(newFragment);
  1328. }
  1329. }
  1330. }