MainActivity.java 20 KB

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