Search in sources :

Example 1 with GetSshHostFingerprintTask

use of com.amaze.filemanager.asynchronous.asynctasks.ssh.GetSshHostFingerprintTask in project AmazeFileManager by TeamAmaze.

the class SftpConnectDialog method onCreateDialog.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    context = getActivity();
    final boolean edit = getArguments().getBoolean("edit", false);
    final View v2 = getActivity().getLayoutInflater().inflate(R.layout.sftp_dialog, null);
    final EditText connectionET = v2.findViewById(R.id.connectionET);
    final EditText addressET = v2.findViewById(R.id.ipET);
    final EditText portET = v2.findViewById(R.id.portET);
    final EditText usernameET = v2.findViewById(R.id.usernameET);
    final EditText passwordET = v2.findViewById(R.id.passwordET);
    final Button selectPemBTN = v2.findViewById(R.id.selectPemBTN);
    // Otherwise, use given Bundle instance for filling in the blanks
    if (!edit) {
        connectionET.setText(R.string.scp_con);
        portET.setText(Integer.toString(SshConnectionPool.SSH_DEFAULT_PORT));
    } else {
        connectionET.setText(getArguments().getString("name"));
        addressET.setText(getArguments().getString("address"));
        portET.setText(getArguments().getString("port"));
        usernameET.setText(getArguments().getString("username"));
        if (getArguments().getBoolean("hasPassword")) {
            passwordET.setHint(R.string.password_unchanged);
        } else {
            selectedParsedKeyPairName = getArguments().getString("keypairName");
            selectPemBTN.setText(selectedParsedKeyPairName);
        }
    }
    // For convenience, so I don't need to press backspace all the time
    portET.setOnFocusChangeListener((v, hasFocus) -> {
        if (hasFocus)
            portET.selectAll();
    });
    int accentColor = utilsProvider.getColorPreference().getColor(ColorUsage.ACCENT);
    // Use system provided action to get Uri to PEM.
    // If MaterialDialog.Builder can be upgraded we may use their file selection dialog too
    selectPemBTN.setOnClickListener(v -> {
        Intent intent = new Intent().setType("*/*").setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_PEM_INTENT);
    });
    // Define action for buttons
    final MaterialDialog.Builder dialogBuilder = new MaterialDialog.Builder(context);
    dialogBuilder.title((R.string.scp_con));
    dialogBuilder.autoDismiss(false);
    dialogBuilder.customView(v2, true);
    dialogBuilder.theme(utilsProvider.getAppTheme().getMaterialDialogTheme());
    dialogBuilder.negativeText(R.string.cancel);
    dialogBuilder.positiveText(edit ? R.string.update : R.string.create);
    dialogBuilder.positiveColor(accentColor);
    dialogBuilder.negativeColor(accentColor);
    dialogBuilder.neutralColor(accentColor);
    dialogBuilder.onPositive((dialog, which) -> {
        final String connectionName = connectionET.getText().toString();
        final String hostname = addressET.getText().toString();
        final int port = Integer.parseInt(portET.getText().toString());
        final String username = usernameET.getText().toString();
        final String password = passwordET.getText() != null ? passwordET.getText().toString() : null;
        String sshHostKey = utilsHandler.getSshHostKey(deriveSftpPathFrom(hostname, port, username, password, selectedParsedKeyPair));
        if (sshHostKey != null) {
            authenticateAndSaveSetup(connectionName, hostname, port, sshHostKey, username, password, selectedParsedKeyPairName, selectedParsedKeyPair, edit);
        } else {
            new GetSshHostFingerprintTask(hostname, port, taskResult -> {
                PublicKey hostKey = taskResult.result;
                if (hostKey != null) {
                    final String hostKeyFingerprint = SecurityUtils.getFingerprint(hostKey);
                    StringBuilder sb = new StringBuilder(hostname);
                    if (port != SshConnectionPool.SSH_DEFAULT_PORT && port > 0)
                        sb.append(':').append(port);
                    final String hostAndPort = sb.toString();
                    new AlertDialog.Builder(context).setTitle(R.string.ssh_host_key_verification_prompt_title).setMessage(String.format(getResources().getString(R.string.ssh_host_key_verification_prompt), hostAndPort, hostKey.getAlgorithm(), hostKeyFingerprint)).setCancelable(true).setPositiveButton(R.string.yes, (dialog1, which1) -> {
                        // This closes the host fingerprint verification dialog
                        dialog1.dismiss();
                        if (authenticateAndSaveSetup(connectionName, hostname, port, hostKeyFingerprint, username, password, selectedParsedKeyPairName, selectedParsedKeyPair, edit)) {
                            dialog1.dismiss();
                            Log.d(TAG, "Saved setup");
                            dismiss();
                        }
                    }).setNegativeButton(R.string.no, (dialog1, which1) -> dialog1.dismiss()).show();
                }
            }).execute();
        }
    }).onNegative((dialog, which) -> dialog.dismiss());
    // If we are editing connection settings, give new actions for neutral and negative buttons
    if (edit) {
        Log.d(TAG, "Edit? " + edit);
        dialogBuilder.negativeText(R.string.delete).onNegative((dialog, which) -> {
            final String connectionName = connectionET.getText().toString();
            final String hostname = addressET.getText().toString();
            final int port = Integer.parseInt(portET.getText().toString());
            final String username = usernameET.getText().toString();
            final String path = deriveSftpPathFrom(hostname, port, username, getArguments().getString("password", null), selectedParsedKeyPair);
            int i = DataUtils.getInstance().containsServer(new String[] { connectionName, path });
            if (i != -1) {
                DataUtils.getInstance().removeServer(i);
                AppConfig.runInBackground(() -> {
                    utilsHandler.removeSftpPath(connectionName, path);
                });
                ((MainActivity) getActivity()).getDrawer().refreshDrawer();
            }
            dialog.dismiss();
        }).neutralText(R.string.cancel).onNeutral((dialog, which) -> dialog.dismiss());
    }
    MaterialDialog dialog = dialogBuilder.build();
    // Some validations to make sure the Create/Update button is clickable only when required
    // setting values are given
    final View okBTN = dialog.getActionButton(DialogAction.POSITIVE);
    if (!edit)
        okBTN.setEnabled(false);
    TextWatcher validator = new SimpleTextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            int port = portET.getText().toString().length() > 0 ? Integer.parseInt(portET.getText().toString()) : -1;
            okBTN.setEnabled((connectionET.getText().length() > 0 && addressET.getText().length() > 0 && port > 0 && port < 65536 && usernameET.getText().length() > 0 && (passwordET.getText().length() > 0 || selectedParsedKeyPair != null)));
        }
    };
    addressET.addTextChangedListener(validator);
    portET.addTextChangedListener(validator);
    usernameET.addTextChangedListener(validator);
    passwordET.addTextChangedListener(validator);
    return dialog;
}
Also used : EditText(android.widget.EditText) Context(android.content.Context) KeyPair(java.security.KeyPair) BookSorter(com.amaze.filemanager.utils.BookSorter) Bundle(android.os.Bundle) AppConfig(com.amaze.filemanager.utils.application.AppConfig) ColorUsage(com.amaze.filemanager.utils.color.ColorUsage) Uri(android.net.Uri) MainFragment(com.amaze.filemanager.fragments.MainFragment) UtilsHandler(com.amaze.filemanager.database.UtilsHandler) Dialog(android.app.Dialog) Intent(android.content.Intent) AsyncTaskResult(com.amaze.filemanager.asynchronous.asynctasks.AsyncTaskResult) Editable(android.text.Editable) MainActivity(com.amaze.filemanager.activities.MainActivity) MDButton(com.afollestad.materialdialogs.internal.MDButton) SecurityUtils(net.schmizz.sshj.common.SecurityUtils) SshClientUtils(com.amaze.filemanager.filesystem.ssh.SshClientUtils) GetSshHostFingerprintTask(com.amaze.filemanager.asynchronous.asynctasks.ssh.GetSshHostFingerprintTask) DataUtils(com.amaze.filemanager.utils.DataUtils) View(android.view.View) Button(android.widget.Button) DialogFragment(android.app.DialogFragment) Log(android.util.Log) UtilitiesProvider(com.amaze.filemanager.utils.provider.UtilitiesProvider) SshConnectionPool(com.amaze.filemanager.filesystem.ssh.SshConnectionPool) DialogAction(com.afollestad.materialdialogs.DialogAction) IOException(java.io.IOException) PublicKey(java.security.PublicKey) InputStreamReader(java.io.InputStreamReader) FileNotFoundException(java.io.FileNotFoundException) AlertDialog(android.app.AlertDialog) SshAuthenticationTask(com.amaze.filemanager.asynchronous.asynctasks.ssh.SshAuthenticationTask) PemToKeyPairTask(com.amaze.filemanager.asynchronous.asynctasks.ssh.PemToKeyPairTask) SSHClient(net.schmizz.sshj.SSHClient) R(com.amaze.filemanager.R) BufferedReader(java.io.BufferedReader) Snackbar(android.support.design.widget.Snackbar) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Activity(android.app.Activity) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) OpenMode(com.amaze.filemanager.utils.OpenMode) Collections(java.util.Collections) EditText(android.widget.EditText) TextWatcher(android.text.TextWatcher) InputStream(java.io.InputStream) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) PublicKey(java.security.PublicKey) Intent(android.content.Intent) View(android.view.View) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) MDButton(com.afollestad.materialdialogs.internal.MDButton) Button(android.widget.Button) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) GetSshHostFingerprintTask(com.amaze.filemanager.asynchronous.asynctasks.ssh.GetSshHostFingerprintTask)

Aggregations

Activity (android.app.Activity)1 AlertDialog (android.app.AlertDialog)1 Dialog (android.app.Dialog)1 DialogFragment (android.app.DialogFragment)1 Context (android.content.Context)1 Intent (android.content.Intent)1 Uri (android.net.Uri)1 Bundle (android.os.Bundle)1 Snackbar (android.support.design.widget.Snackbar)1 Editable (android.text.Editable)1 TextWatcher (android.text.TextWatcher)1 Log (android.util.Log)1 View (android.view.View)1 Button (android.widget.Button)1 EditText (android.widget.EditText)1 DialogAction (com.afollestad.materialdialogs.DialogAction)1 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)1 MDButton (com.afollestad.materialdialogs.internal.MDButton)1 R (com.amaze.filemanager.R)1 MainActivity (com.amaze.filemanager.activities.MainActivity)1