Browse Source

fix mail credentials customizer style + add more custom imap/smtp entries + replace legacy sending functionality info getting + make mail credentail customizer buttons do what they should

Noah Vogt 3 years ago
parent
commit
1e86e1cc4e

+ 78 - 71
app/src/main/java/com/noahvogt/miniprojekt/MainActivity.java

@@ -244,12 +244,15 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
         final View changeMailServerSettingsView = getLayoutInflater().inflate(R.layout.mail_credentials_customizer, null);
 
+        /* access objects */
         EditText incomingServerObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_incoming_server_text);
         EditText outgoingServerObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_outgoing_server_text);
         EditText incomingPortObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_incoming_port_text);
         EditText outgoingPortObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_outgoing_port_text);
         EditText serverUsernameObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_username_text);
         EditText passwordObject = (EditText) changeMailServerSettingsView.findViewById(R.id.custom_mail_server_password_text);
+        Button saveButton = (Button) changeMailServerSettingsView.findViewById(R.id.saveCustomizeButton);
+        Button cancelButton = (Button) changeMailServerSettingsView.findViewById(R.id.cancelCustomizeButton);
 
         /* set assumed input in corresponding fields */
         incomingServerObject.setText(MailFunctions.getImapHostFromEmail(email));
@@ -265,6 +268,17 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
         dialogBuilder.setView(changeMailServerSettingsView);
         dialog = dialogBuilder.create();
         dialog.show();
+
+        saveButton.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View view) {
+                addNewAccountCredentials(name, serverUsernameObject.getText().toString(), passwordObject.getText().toString(),
+                        Integer.parseInt(incomingPortObject.getText().toString()), Integer.parseInt(outgoingPortObject.getText().toString()),
+                        incomingServerObject.getText().toString(), outgoingServerObject.getText().toString(), dialog, false);
+            }
+        });
+
+        cancelButton.setOnClickListener(v -> dialog.dismiss());
     }
 
     public void askForChangeMailServerSettingsDialog(String name, String email, String password) {
@@ -282,7 +296,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
                     }
                 })
                 .setNegativeButton("No",new DialogInterface.OnClickListener() {
-                    public void onClick(DialogInterface dialog,int id) {
+                    public void onClick(DialogInterface dialog, int id) {
                         /* if this button is clicked, close the hole fragment */
                         dialog.dismiss();
                     }
@@ -294,6 +308,66 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
     public static MailServerCredentials newMailServerCredentials;
     public static SharedPreferences.Editor credentialsEditor;
 
+    public void addNewAccountCredentials(String name, String email, String password, int imapPort,
+                                         int smtpPort, String imapHost, String smtpHost, DialogInterface dialogContext,
+                                         boolean wantConnectionFailedDialog) {
+        SharedPreferences.Editor preferencesEditor = preferences.edit();
+        credentialsEditor = mailServerCredentials.edit();
+
+        /* connect to mail server */
+        showToast("Probe Connection ...");
+        if (MailFunctions.canConnect(MailFunctions.getImapHostFromEmail(email), email, password) == Boolean.TRUE) {
+            showToast("was able to connect");
+
+            /* TODO: replace legacy strings down below completely with serialized settings json string */
+            preferencesEditor.putString("name", name);
+            preferencesEditor.putString("email", email);
+            preferencesEditor.putString("password", password);
+            preferencesEditor.apply();
+
+            Gson gson = new Gson();
+
+            /* read login credentials from SharedPreferences */
+            SharedPreferences initialCredentialsReader = getSharedPreferences(
+                    "Credentials", Context.MODE_PRIVATE);
+            String initialReadJsonData = initialCredentialsReader.getString("data", "");
+            Type credentialsType = new TypeToken<ArrayList<MailServerCredentials>>(){}.getType();
+            ArrayList<MailServerCredentials> allUsersCredentials = gson.fromJson(initialReadJsonData, credentialsType);
+
+            /* check for unique email */
+            boolean newEmailIsUnique = true;
+            try {
+                for (int i = 0; i < allUsersCredentials.size(); i++) {
+                    if (allUsersCredentials.get(i).getUsername().equals(email)) {
+                        newEmailIsUnique = false;
+                        break;
+                    }
+                }
+            } catch (NullPointerException e) {
+                System.out.println("creating new arraylist for user credentials, as it seems to be empty");
+                allUsersCredentials = new ArrayList<>();
+            }
+
+            /* add new email account if the email hasn't been entered before */
+            if (newEmailIsUnique) {
+                allUsersCredentials.add(new MailServerCredentials(name, email, password, imapHost, smtpHost, imapPort,
+                        smtpPort, ""));
+                credentialsEditor.putString("data", gson.toJson(allUsersCredentials, credentialsType));
+                credentialsEditor.putString("currentUser", email);
+                credentialsEditor.apply();
+                showToast("Success: added new email account");
+                dialogContext.dismiss();
+            } else {
+                showToast("Error: cannot add the same email twice");
+            }
+        } else {
+            if (wantConnectionFailedDialog)
+                askForChangeMailServerSettingsDialog(name, email, password);
+            else
+                showToast("Error: failed to get connection");
+        }
+    }
+
     public void createNewEmailDialog(){
         /* define View window */
         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
@@ -318,12 +392,6 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
         SharedPreferences.Editor preferencesEditor = preferences.edit();
         credentialsEditor = mailServerCredentials.edit();
 
-        if (! Python.isStarted()) {
-            Python.start(new AndroidPlatform(this));
-        }
-
-
-
         /* store user input */
         newemail_save_button.setOnClickListener(new View.OnClickListener() {
             @Override
@@ -333,80 +401,19 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
                 String email = newemail_email.getText().toString();
                 String password = newemail_password.getText().toString();
 
-                Data.Builder builder = new Data.Builder();
-                builder.putString(emailData, email)
-                        .putString(passwordData, password)
-                        .putString(nameData, name);
-
+                /* validate user input before connecting */
                 if (!MailFunctions.validateEmail(newemail_email) | !MailFunctions.validateName(newemail_name) |
                         !MailFunctions.validatePassword(newemail_password)) {
                     return;
                 }
-                /* connect to mail server */
-                showToast("Probe Connection ...");
-                if (MailFunctions.canConnect(MailFunctions.getImapHostFromEmail(email), email, password) == Boolean.TRUE) {
-                    showToast("was able to connect");
-
-
-                    /*
-                    Intent intent = new Intent(getBaseContext(), DownloadWorker.class);
-                    intent.putExtra("Email", email);
-                    intent.putExtra("Password", password);
-                    startActivity(intent);
-
-                     */
-                    //startActivityForResult(intent, MainActivity.NEW_WORD_ACTIVITY_REQUEST_CODE);
-
-                    /* TODO: replace legacy strings down below completely with serialized settings json string */
-                    preferencesEditor.putString("name", name);
-                    preferencesEditor.putString("email", email);
-                    preferencesEditor.putString("password", password);
-                    preferencesEditor.apply();
-
-                    Gson gson = new Gson();
-
-                    /* read login credentials from SharedPreferences */
-                    SharedPreferences initialCredentialsReader = getSharedPreferences(
-                            "Credentials", Context.MODE_PRIVATE);
-                    String initialReadJsonData = initialCredentialsReader.getString("data", "");
-                    Type credentialsType = new TypeToken<ArrayList<MailServerCredentials>>(){}.getType();
-                    ArrayList<MailServerCredentials> allUsersCredentials = gson.fromJson(initialReadJsonData, credentialsType);
-
-                    /* check for unique email */
-                    boolean newEmailIsUnique = true;
-                    try {
-                        for (int i = 0; i < allUsersCredentials.size(); i++) {
-                            if (allUsersCredentials.get(i).getUsername().equals(email)) {
-                                newEmailIsUnique = false;
-                                break;
-                            }
-                        }
-                    } catch (NullPointerException e) {
-                        System.out.println("creating new arraylist for user credentials, as it seems to be empty");
-                        allUsersCredentials = new ArrayList<>();
-                    }
 
-                    /* add new email account if the email hasn't been entered before */
-                    if (newEmailIsUnique) {
-                        allUsersCredentials.add(new MailServerCredentials(name, email, password,
-                                MailFunctions.getImapHostFromEmail(email), MailFunctions.getSmtpHostFromEmail(email), 993,
-                                587, ""));
-                        credentialsEditor.putString("data", gson.toJson(allUsersCredentials, credentialsType));
-                        credentialsEditor.putString("currentUser", email);
-                        credentialsEditor.apply();
-                        showToast("Success: added new email account");
-                    } else {
-                        showToast("Error: cannot add the same email twice");
-                }
-            } else {
-                    askForChangeMailServerSettingsDialog(name, email, password);
-            }
+                addNewAccountCredentials(name, email, password, 993, 587, MailFunctions.getImapHostFromEmail(email),
+                        MailFunctions.getSmtpHostFromEmail(email), dialog, true);
         }});
 
     newemail_cancel_button.setOnClickListener(v -> dialog.dismiss());
  }
 
-
     /* show debug output in  specific view */
     private void showSnackbar(View View, String text) {
         Snackbar.make(View, text, Snackbar.LENGTH_LONG)

+ 28 - 10
app/src/main/java/com/noahvogt/miniprojekt/MessageCreateFragment.java

@@ -21,10 +21,14 @@ import androidx.annotation.Nullable;
 import androidx.appcompat.app.AlertDialog;
 import androidx.fragment.app.DialogFragment;
 
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
 import com.noahvogt.miniprojekt.DataBase.Message;
 import com.noahvogt.miniprojekt.data.EmailViewModel;
 import com.noahvogt.miniprojekt.data.MailFunctions;
 
+import java.lang.reflect.Type;
+import java.util.ArrayList;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 
@@ -65,23 +69,18 @@ public class MessageCreateFragment extends DialogFragment implements PopupMenu.O
     }
 
     private AlertDialog dialog;
-    SharedPreferences preferences;
-
 
     private static final int NUMBER_OF_THREADS = 4;
     static final ExecutorService databaseWriteExecutor =
             Executors.newFixedThreadPool(NUMBER_OF_THREADS);
 
-
     /* set theming style */
     @Override
     public void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setStyle(DialogFragment.STYLE_NORMAL, R.style.messageCreateTheme);
-        preferences = getActivity().getSharedPreferences("UserPreferences", Context.MODE_PRIVATE);
     }
 
-
     @Nullable
     @Override
     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
@@ -101,9 +100,11 @@ public class MessageCreateFragment extends DialogFragment implements PopupMenu.O
          subjectObject = (EditText) view.findViewById(R.id.create_message_subject_text);
          messageBodyObject = (EditText) view.findViewById(R.id.create_message_body_text);
 
+        SharedPreferences mailServerCredentials = getContext().getSharedPreferences("Credentials", Context.MODE_PRIVATE);
+        
         /* set logged in email address as sending address */
-        String loginEmail = preferences.getString("email","");
-        sendingAddressObject.setText(loginEmail);
+        String currentMailUser = mailServerCredentials.getString("currentUser", "");
+        sendingAddressObject.setText(currentMailUser);
 
         /* get string vars, MAYBE NOT HERE */
         if (mMessage != null) {
@@ -217,13 +218,30 @@ public class MessageCreateFragment extends DialogFragment implements PopupMenu.O
                 String ccStr = ccObject.getText().toString();
                 String bccStr = bccObject.getText().toString();
 
+                Gson gson = new Gson();
+
+                /* get string vars, MAYBE NOT HERE */
+                String jsonData = mailServerCredentials.getString("data", "");
+                Type credentialsType = new TypeToken<ArrayList<MailServerCredentials>>(){}.getType();
+                ArrayList<MailServerCredentials> allUsersCredentials = gson.fromJson(jsonData, credentialsType);
+                
+                String smtpHost = null, password = null; int smtpPort = 587;
+
+                for (int i = 0; i < allUsersCredentials.size(); i++) {
+                    if (allUsersCredentials.get(i).getUsername().equals(currentMailUser)) {
+                        smtpHost = allUsersCredentials.get(i).getSmtpHost();
+                        smtpPort = allUsersCredentials.get(i).getSmtpPort();
+                        password = allUsersCredentials.get(i).getPassword();
+                        break;
+                    }
+                }
+                
                 /* check for valid input */
                 if (MailFunctions.validateMessageBody(messageBodyObject) && MailFunctions.validateSubject(subjectObject) &&
                 MailFunctions.validateEmail(receivingAddressObject) && MailFunctions.validateEmail(sendingAddressObject) &&
                 !MailFunctions.checkForSameEmail(sendingAddressObject, receivingAddressObject)) {
-                    String password = preferences.getString("password","");
-                    MailFunctions.sendStarttlsMail("smtp.edubs.ch", sendingAddress, receivingAddress, password, messageBody,
-                            subject, ccStr, bccStr, 587);
+                    MailFunctions.sendStarttlsMail(smtpHost, sendingAddress, receivingAddress, password, messageBody,
+                            subject, ccStr, bccStr, smtpPort);
                     Toast.makeText(getActivity(), "sending ... ", Toast.LENGTH_SHORT).show();
                     dismiss();
                 } else {

+ 7 - 4
app/src/main/java/com/noahvogt/miniprojekt/data/MailFunctions.java

@@ -64,11 +64,13 @@ public class MailFunctions {
         if (topLevelHost.endsWith("edubs.ch")) {
             return "teamwork.edubs.ch";
 
-        }else if (topLevelHost.endsWith("yahoo.com")){
+        } else if (topLevelHost.endsWith("yahoo.com")){
             return "imap.mail.yahoo.com";
 
+        } else if (topLevelHost.equals("noahvogt.com")) {
+            return "mail.noahvogt.com";
         } else {
-            return "imap." + topLevelHost;
+                return "imap." + topLevelHost;
         }
     }
 
@@ -79,8 +81,9 @@ public class MailFunctions {
 
         } else if (topLevelHost.endsWith("yahoo.com")){
             return "smtp.mail.yahoo.com";
-        }
-        else {
+        } else if (topLevelHost.endsWith("edubs.ch")) {
+            return "smtp.edubs.ch";
+        } else {
             return "smtp." + topLevelHost;
         }
     }

+ 10 - 6
app/src/main/res/layout/mail_credentials_customizer.xml

@@ -40,7 +40,7 @@
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:orientation="vertical"
-            android:layout_marginBottom="100dp"
+            android:layout_marginBottom="50dp"
             >
 
             <com.google.android.material.textfield.TextInputLayout
@@ -111,6 +111,7 @@
 
                 <com.google.android.material.textfield.TextInputEditText
                     android:id="@+id/custom_mail_server_incoming_port_text"
+                    android:inputType="number"
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content" />
             </com.google.android.material.textfield.TextInputLayout>
@@ -135,6 +136,7 @@
 
                 <com.google.android.material.textfield.TextInputEditText
                     android:id="@+id/custom_mail_server_outgoing_port_text"
+                    android:inputType="number"
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content" />
             </com.google.android.material.textfield.TextInputLayout>
@@ -178,8 +180,6 @@
                 android:hint="Server Password"
                 app:startIconDrawable="@drawable/ic_lock"
 
-                android:paddingBottom="50dp"
-
                 app:layout_constraintEnd_toEndOf="parent"
                 app:layout_constraintStart_toStartOf="parent"
                 app:layout_constraintTop_toBottomOf="@+id/custom_mail_server_username_layout">
@@ -196,8 +196,12 @@
                 android:layout_height="wrap_content">
 
                 <Button
-                    android:id="@+id/cancelCustomizeButton"
+                    android:id="@+id/saveCustomizeButton"
+                    android:layout_marginTop="16dp"
+                    android:layout_marginEnd="16dp"
 
+                    android:layout_marginRight="16dp"
+                    android:layout_marginBottom="16dp"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
 
@@ -208,14 +212,14 @@
                     android:text="Save" />
 
                 <Button
-                    android:id="@+id/saveCustomizeButton"
+                    android:id="@+id/cancelCustomizeButton"
 
                     android:layout_marginEnd="42dp"
                     android:layout_marginRight="42dp"
 
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
-                    android:layout_alignBottom="@+id/cancelCustomizeButton"
+                    android:layout_alignBottom="@+id/saveCustomizeButton"
                     android:layout_alignParentRight="true"
                     android:text="Cancel" />