MainActivity.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. package com.noahvogt.miniprojekt;
  2. import android.content.Context;
  3. import android.content.DialogInterface;
  4. import android.content.Intent;
  5. import android.content.SharedPreferences;
  6. import android.os.Bundle;
  7. import android.view.LayoutInflater;
  8. import android.view.Menu;
  9. import android.view.MenuItem;
  10. import android.view.View;
  11. import android.view.ViewGroup;
  12. import android.widget.ArrayAdapter;
  13. import android.widget.AutoCompleteTextView;
  14. import android.widget.Button;
  15. import android.widget.EditText;
  16. import android.widget.PopupMenu;
  17. import android.widget.TextView;
  18. import android.widget.Toast;
  19. import androidx.appcompat.app.AlertDialog;
  20. import androidx.appcompat.app.AppCompatActivity;
  21. import androidx.appcompat.widget.Toolbar;
  22. import androidx.drawerlayout.widget.DrawerLayout;
  23. import androidx.fragment.app.DialogFragment;
  24. import com.google.android.material.floatingactionbutton.FloatingActionButton;
  25. import com.google.gson.GsonBuilder;
  26. import com.google.gson.reflect.TypeToken;
  27. import com.noahvogt.miniprojekt.DataBase.Message;
  28. import androidx.fragment.app.Fragment;
  29. import androidx.fragment.app.FragmentManager;
  30. import androidx.lifecycle.ViewModelProvider;
  31. import androidx.recyclerview.widget.LinearLayoutManager;
  32. import androidx.recyclerview.widget.RecyclerView;
  33. import com.google.android.material.navigation.NavigationView;
  34. import androidx.navigation.NavController;
  35. import androidx.navigation.Navigation;
  36. import androidx.navigation.ui.AppBarConfiguration;
  37. import androidx.navigation.ui.NavigationUI;
  38. import androidx.work.Data;
  39. import com.chaquo.python.Python;
  40. import com.chaquo.python.android.AndroidPlatform;
  41. import com.google.android.material.snackbar.Snackbar;
  42. import com.noahvogt.miniprojekt.data.CustomAdapter;
  43. import com.noahvogt.miniprojekt.data.EmailViewModel;
  44. import com.noahvogt.miniprojekt.data.MailFunctions;
  45. import com.noahvogt.miniprojekt.workers.DownloadWorker;
  46. import com.noahvogt.miniprojekt.ui.show.MessageShowFragment;
  47. import com.noahvogt.miniprojekt.data.BooleanTypeAdapter;
  48. import java.lang.reflect.Type;
  49. import java.text.SimpleDateFormat;
  50. import java.util.ArrayList;
  51. import java.util.Date;
  52. import java.util.List;
  53. import com.google.gson.Gson;
  54. import static com.noahvogt.miniprojekt.R.id.drawer_layout;
  55. import org.w3c.dom.Text;
  56. public class MainActivity extends AppCompatActivity implements View.OnClickListener, CustomAdapter.SelectedMessage, PopupMenu.OnMenuItemClickListener {
  57. private AppBarConfiguration mAppBarConfiguration;
  58. public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
  59. public static final String emailData = "Email";
  60. public static final String passwordData = "Password";
  61. public static final String nameData = "Name";
  62. public static EmailViewModel mEmailViewModel;
  63. public static RecyclerView recyclerView;
  64. private AlertDialog dialog;
  65. private EditText newemail_name, newemail_email, newemail_password; /* may not be private */
  66. SharedPreferences mailServerCredentials;
  67. /* leave descriptor empty */
  68. public MainActivity() {}
  69. public String getVisibleFragment(){
  70. FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
  71. List<Fragment> fragments = fragmentManager.getFragments();
  72. if(fragments != null){
  73. showToast("not null");
  74. for(Fragment fragment : fragments){
  75. showToast(fragment.toString());
  76. if(fragment.isVisible())
  77. showToast("found visible fragment");
  78. return "is gallery";
  79. }
  80. } else {
  81. showToast("null");}
  82. return null;
  83. }
  84. @Override
  85. protected void onCreate(Bundle savedInstanceState) {
  86. super.onCreate(savedInstanceState);
  87. setContentView(R.layout.activity_main);
  88. /* define button listeners */
  89. /*creates account manager by clicking on profile */
  90. View accountView = findViewById(R.id.accountView);
  91. accountView.setOnClickListener(new View.OnClickListener() {
  92. @Override
  93. public void onClick(View v) {
  94. /* define View window */
  95. AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
  96. final View accountManagerView = getLayoutInflater().inflate(R.layout.account_manager, null);
  97. AutoCompleteTextView accountSelectorObject =
  98. (AutoCompleteTextView) accountManagerView.findViewById(R.id.accountSelectorTextView);
  99. /* get string data for drop down menu */
  100. String[] dummyMails = getResources().getStringArray(R.array.dummy_emails);
  101. ArrayAdapter<String> dropDownAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.dropdown_item,
  102. R.id.textViewDropDownItem, dummyMails);
  103. accountSelectorObject.setAdapter(dropDownAdapter);
  104. /* open View window */
  105. dialogBuilder.setView(accountManagerView);
  106. dialog = dialogBuilder.create();
  107. dialog.show();
  108. }
  109. });
  110. /* invoke toolbar */
  111. Toolbar toolbar = findViewById(R.id.toolbar);
  112. setSupportActionBar(toolbar);
  113. /* invoke drawer */
  114. DrawerLayout drawer = findViewById(drawer_layout);
  115. NavigationView navigationView = findViewById(R.id.nav_view);
  116. View headerView = navigationView.getHeaderView(0);
  117. /*
  118. Passing each menu ID as a set of Ids because each
  119. menu should be considered as top level destinations.
  120. */
  121. mAppBarConfiguration = new AppBarConfiguration.Builder(
  122. R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.nav_archive, R.id.nav_spam)
  123. .setDrawerLayout(drawer)
  124. .build();
  125. NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
  126. NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
  127. NavigationUI.setupWithNavController(navigationView, navController);
  128. /* Lookup the recyclerview in activity layout */
  129. recyclerView = findViewById(R.id.recyclerView);
  130. final CustomAdapter adapter = new CustomAdapter(new CustomAdapter.EmailDiff(),this);
  131. /* Attach the adapter to the recyclerview to populate items */
  132. recyclerView.setAdapter(adapter);
  133. recyclerView.setLayoutManager(new LinearLayoutManager(this));
  134. /* get Inbox Messages in Recyclerviewer at begining is overwritten by Fragments but has to stay*/
  135. mEmailViewModel = new ViewModelProvider(this).get(EmailViewModel.class);
  136. mEmailViewModel.getInboxMessage().observe(this, messages -> {
  137. /* Update the cached copy of the messages in the adapter*/
  138. adapter.submitList(messages);
  139. });
  140. updateNavHeaderText(headerView);
  141. Button settingButton = findViewById(R.id.settingsButton);
  142. settingButton.setOnClickListener(new View.OnClickListener() {
  143. @Override
  144. public void onClick(View v) {
  145. Intent i = new Intent(MainActivity.this, SettingsActivity.class);
  146. startActivity(i);
  147. }
  148. });
  149. Button add_email_button = (Button) findViewById(R.id.addEmailButton);
  150. add_email_button.setOnClickListener(new View.OnClickListener() {
  151. @Override
  152. public void onClick(View v) {
  153. createNewEmailDialog(headerView);
  154. }
  155. });
  156. /* Start email Writer*/
  157. FloatingActionButton message_create_button = findViewById(R.id.messageButton);
  158. message_create_button.setOnClickListener(new View.OnClickListener() {
  159. @Override
  160. public void onClick(View v) {
  161. DialogFragment dialog = MessageCreateFragment.newInstance();
  162. dialog.show(getSupportFragmentManager(), "tag");
  163. }
  164. });
  165. /* start python instance right on startup */
  166. if (! Python.isStarted()) {
  167. Python.start(new AndroidPlatform(this));
  168. }
  169. }
  170. /* gets the data from the Email writer and adds it to the Database */
  171. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  172. super.onActivityResult(requestCode, resultCode, MessageCreateFragment.replyIntent);
  173. /* Creates class for the Date when Email is written */
  174. Date dNow = new Date();
  175. SimpleDateFormat ft =
  176. new SimpleDateFormat("dd.MM.yy");
  177. System.out.println(dNow);
  178. // if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
  179. Message word = new Message(
  180. MessageCreateFragment.replyIntent.getStringExtra(MessageCreateFragment.EXTRA_TO),
  181. null,
  182. null,
  183. MessageCreateFragment.replyIntent.getStringExtra(MessageCreateFragment.EXTRA_FROM),
  184. ft.format(dNow),
  185. MessageCreateFragment.replyIntent.getStringExtra(MessageCreateFragment.EXTRA_SUBJECT),
  186. MessageCreateFragment.replyIntent.getStringExtra(MessageCreateFragment.EXTRA_MESSAGE),
  187. "Draft",false);
  188. mEmailViewModel.insert(word);
  189. }
  190. /* set nav header name + email to current user data */
  191. public void updateNavHeaderText(View headerView) {
  192. mailServerCredentials = getSharedPreferences("Credentials", Context.MODE_PRIVATE);
  193. TextView navHeaderNameObject = (TextView) headerView.findViewById(R.id.navHeaderName);
  194. TextView navHeaderEmailObject = (TextView) headerView.findViewById(R.id.navHeaderEmail);
  195. String startupUser = mailServerCredentials.getString("currentUser","");
  196. if (!startupUser.isEmpty()) {
  197. Gson gson = new Gson();
  198. String startupJsonData = mailServerCredentials.getString("data", "");
  199. Type credentialsType = new TypeToken<ArrayList<MailServerCredentials>>(){}.getType();
  200. ArrayList<MailServerCredentials> startupUsersCredentials = gson.fromJson(startupJsonData, credentialsType);
  201. for (int i = 0; i < startupUsersCredentials.size(); i++) {
  202. if (startupUsersCredentials.get(i).getUsername().equals(startupUser)) {
  203. navHeaderNameObject.setText(startupUser);
  204. navHeaderEmailObject.setText(startupUsersCredentials.get(i).getName());
  205. break;
  206. }
  207. }
  208. }
  209. }
  210. @Override
  211. public boolean onCreateOptionsMenu(Menu menu) {
  212. /* Inflate the menu; this adds items to the action bar if it is present. */
  213. getMenuInflater().inflate(R.menu.main, menu);
  214. return true;
  215. }
  216. @Override
  217. public boolean onSupportNavigateUp() {
  218. NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
  219. return NavigationUI.navigateUp(navController, mAppBarConfiguration)
  220. || super.onSupportNavigateUp();
  221. }
  222. /* better leave empty to avoid any listener disambiguity */
  223. public void onClick(View view) { }
  224. public void changeMailServerSettingsDialog(String name, String email, String password, View headerView) {
  225. /* define View window */
  226. AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
  227. final View changeMailServerSettingsView = getLayoutInflater().inflate(R.layout.mail_credentials_customizer, null);
  228. /* access objects */
  229. EditText incomingServerObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_incoming_server_text);
  230. EditText outgoingServerObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_outgoing_server_text);
  231. EditText incomingPortObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_incoming_port_text);
  232. EditText outgoingPortObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_outgoing_port_text);
  233. EditText serverUsernameObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_username_text);
  234. EditText passwordObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_password_text);
  235. Button saveButton = (Button) changeMailServerSettingsView.findViewById(R.id.saveCustomizeButton);
  236. Button cancelButton = (Button) changeMailServerSettingsView.findViewById(R.id.cancelCustomizeButton);
  237. /* set assumed input in corresponding fields */
  238. incomingServerObject.setText(MailFunctions.getImapHostFromEmail(email));
  239. outgoingServerObject.setText(MailFunctions.getSmtpHostFromEmail(email));
  240. incomingPortObject.setText("993");
  241. outgoingPortObject.setText("587");
  242. serverUsernameObject.setText(email);
  243. passwordObject.setText(password);
  244. /* TODO: add save and cancel button functionality */
  245. /* open View window */
  246. dialogBuilder.setView(changeMailServerSettingsView);
  247. dialog = dialogBuilder.create();
  248. dialog.show();
  249. saveButton.setOnClickListener(new View.OnClickListener() {
  250. @Override
  251. public void onClick(View view) {
  252. addNewAccountCredentials(name, serverUsernameObject.getText().toString(), passwordObject.getText().toString(),
  253. Integer.parseInt(incomingPortObject.getText().toString()), Integer.parseInt(outgoingPortObject.getText().toString()),
  254. incomingServerObject.getText().toString(), outgoingServerObject.getText().toString(), dialog, false,
  255. headerView);
  256. }
  257. });
  258. cancelButton.setOnClickListener(v -> dialog.dismiss());
  259. }
  260. public void askForChangeMailServerSettingsDialog(String name, String email, String password, View headerView) {
  261. /* define View window */
  262. AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
  263. /* open View window */
  264. dialogBuilder.setTitle("failed to connect :(");
  265. dialogBuilder
  266. .setMessage("Do you want to further customize your mail server settings?")
  267. .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
  268. public void onClick(DialogInterface dialog, int id) {
  269. /*if this button is clicked, close the whole fragment */
  270. changeMailServerSettingsDialog(name, email, password, headerView);
  271. }
  272. })
  273. .setNegativeButton("No",new DialogInterface.OnClickListener() {
  274. public void onClick(DialogInterface dialog, int id) {
  275. /* if this button is clicked, close the hole fragment */
  276. dialog.dismiss();
  277. }
  278. });
  279. dialog = dialogBuilder.create();
  280. dialog.show();
  281. }
  282. public static MailServerCredentials newMailServerCredentials;
  283. public static SharedPreferences.Editor credentialsEditor;
  284. public void addNewAccountCredentials(String name, String email, String password, int imapPort,
  285. int smtpPort, String imapHost, String smtpHost, DialogInterface dialogContext,
  286. boolean wantConnectionFailedDialog, View headerView) {
  287. credentialsEditor = mailServerCredentials.edit();
  288. /* connect to mail server */
  289. showToast("Probe Connection ...");
  290. if (MailFunctions.canConnect(MailFunctions.getImapHostFromEmail(email), email, password) == Boolean.TRUE) {
  291. showToast("was able to connect");
  292. Gson gson = new Gson();
  293. /* read login credentials from SharedPreferences */
  294. SharedPreferences initialCredentialsReader = getSharedPreferences(
  295. "Credentials", Context.MODE_PRIVATE);
  296. String initialReadJsonData = initialCredentialsReader.getString("data", "");
  297. Type credentialsType = new TypeToken<ArrayList<MailServerCredentials>>(){}.getType();
  298. ArrayList<MailServerCredentials> allUsersCredentials = gson.fromJson(initialReadJsonData, credentialsType);
  299. /* check for unique email */
  300. boolean newEmailIsUnique = true;
  301. try {
  302. for (int i = 0; i < allUsersCredentials.size(); i++) {
  303. if (allUsersCredentials.get(i).getUsername().equals(email)) {
  304. newEmailIsUnique = false;
  305. break;
  306. }
  307. }
  308. } catch (NullPointerException e) {
  309. System.out.println("creating new arraylist for user credentials, as it seems to be empty");
  310. allUsersCredentials = new ArrayList<>();
  311. }
  312. /* add new email account if the email hasn't been entered before */
  313. if (newEmailIsUnique) {
  314. allUsersCredentials.add(new MailServerCredentials(name, email, password, imapHost, smtpHost, imapPort,
  315. smtpPort, ""));
  316. credentialsEditor.putString("data", gson.toJson(allUsersCredentials, credentialsType));
  317. credentialsEditor.putString("currentUser", email);
  318. credentialsEditor.apply();
  319. showToast("Success: added new email account");
  320. updateNavHeaderText(headerView);
  321. dialogContext.dismiss();
  322. } else {
  323. showToast("Error: cannot add the same email twice");
  324. }
  325. } else {
  326. if (wantConnectionFailedDialog)
  327. askForChangeMailServerSettingsDialog(name, email, password, headerView);
  328. else
  329. showToast("Error: failed to get connection");
  330. }
  331. }
  332. public void createNewEmailDialog(View headerView){
  333. /* define View window */
  334. AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
  335. final View emailPopupView = getLayoutInflater().inflate(R.layout.popup, null);
  336. /* init text field variables */
  337. newemail_name = emailPopupView.findViewById(R.id.popup_material_name_asking_text);
  338. newemail_email = emailPopupView.findViewById(R.id.popup_material_email_asking_text);
  339. newemail_password = emailPopupView.findViewById(R.id.popup_material_password_asking_text);
  340. /* init button variables */
  341. Button newemail_save_button = (Button) emailPopupView.findViewById(R.id.saveButton);
  342. /* may not be private */
  343. Button newemail_cancel_button = (Button) emailPopupView.findViewById(R.id.cancelButton);
  344. /* open View window */
  345. dialogBuilder.setView(emailPopupView);
  346. dialog = dialogBuilder.create();
  347. dialog.show();
  348. credentialsEditor = mailServerCredentials.edit();
  349. /* store user input */
  350. newemail_save_button.setOnClickListener(new View.OnClickListener() {
  351. @Override
  352. public void onClick(View v) {
  353. /* store user input */
  354. String name = newemail_name.getText().toString();
  355. String email = newemail_email.getText().toString();
  356. String password = newemail_password.getText().toString();
  357. /* validate user input before connecting */
  358. if (!MailFunctions.validateEmail(newemail_email) | !MailFunctions.validateName(newemail_name) |
  359. !MailFunctions.validatePassword(newemail_password)) {
  360. return;
  361. }
  362. addNewAccountCredentials(name, email, password, 993, 587, MailFunctions.getImapHostFromEmail(email),
  363. MailFunctions.getSmtpHostFromEmail(email), dialog, true, headerView);
  364. }});
  365. newemail_cancel_button.setOnClickListener(v -> dialog.dismiss());
  366. }
  367. /* show debug output in specific view */
  368. private void showSnackbar(View View, String text) {
  369. Snackbar.make(View, text, Snackbar.LENGTH_LONG)
  370. .setAction("Action", null).show();
  371. }
  372. /* like showSnackbar(), but global and uglier */
  373. private void showToast(String text) {
  374. Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
  375. }
  376. @Override
  377. public void selectedMessage(Message messages, EmailViewModel emailViewModel) {
  378. DialogFragment dialog = MessageShowFragment.newInstance(messages, mEmailViewModel);
  379. dialog.show(getSupportFragmentManager(), "tag");
  380. }
  381. @Override
  382. public boolean onMenuItemClick(MenuItem item) {
  383. switch (item.getItemId()){
  384. case R.id.action_refresh:
  385. return true;
  386. }
  387. return false;
  388. }
  389. }