Skip to content

Commit

Permalink
Merge pull request #24 from norkator/ssh-key-import-feature
Browse files Browse the repository at this point in the history
Ssh key import feature
  • Loading branch information
norkator authored Jun 7, 2021
2 parents 1b0a283 + 6cdb27c commit 7f6257c
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 22 deletions.
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ android {
minSdkVersion 22
targetSdkVersion 30

versionCode 35
versionName "1.10.0" // Use Semver
versionCode 36
versionName "1.11.0" // Use Semver
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
Expand Down
107 changes: 94 additions & 13 deletions app/src/main/java/com/nitramite/apcupsdmonitor/UpsEditor.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package com.nitramite.apcupsdmonitor;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
Expand All @@ -20,18 +25,31 @@

import androidx.appcompat.app.AppCompatActivity;

import com.nitramite.ui.FileDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class UpsEditor extends AppCompatActivity {

// Logging
private final static String TAG = UpsEditor.class.getSimpleName();

// Variables
private SharedPreferences sharedPreferences;
private String upsId = null;
private DatabaseHelper databaseHelper = new DatabaseHelper(this);
private static final int IMPORT_FILE_REQUEST_CODE = 2;

// View elements
private EditText privateKeyLocationET;

// File paths
public static final String PATH = "/keys/";

@SuppressLint("UseSwitchCompatOrMaterialCode")
@Override
Expand All @@ -56,7 +74,7 @@ protected void onCreate(Bundle savedInstanceState) {
final EditText serverPasswordET = findViewById(R.id.serverPasswordET);
final Switch privateKeyAuthSwitch = findViewById(R.id.privateKeyAuthSwitch);
final EditText privateKeyPassphraseET = findViewById(R.id.privateKeyPassphraseET);
final EditText privateKeyLocationET = findViewById(R.id.privateKeyLocationET);
privateKeyLocationET = findViewById(R.id.privateKeyLocationET);
final Switch strictHostKeyCheckingSwitch = findViewById(R.id.strictHostKeyCheckingSwitch);
final EditText statusCommandET = findViewById(R.id.statusCommandET);
final Switch loadUpsEventsSwitch = findViewById(R.id.loadUpsEventsSwitch);
Expand Down Expand Up @@ -150,15 +168,10 @@ public void onNothingSelected(AdapterView<?> parent) {

Button selectPrivateKeyLocationBtn = findViewById(R.id.selectPrivateKeyLocationBtn);
selectPrivateKeyLocationBtn.setOnClickListener(view -> {

File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
final FileDialog fileDialog = new FileDialog(UpsEditor.this, mPath, "");
fileDialog.addFileListener(file -> {
Toast.makeText(UpsEditor.this, getString(R.string.path) + ": " + file.toString(), Toast.LENGTH_SHORT).show();
privateKeyLocationET.setText(file.toString());
});
fileDialog.showDialog();

Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
chooseFile.setType("*/*");
startActivityForResult(Intent.createChooser(chooseFile, "Choose private key file"), IMPORT_FILE_REQUEST_CODE);
});


Expand Down Expand Up @@ -209,4 +222,72 @@ public void onNothingSelected(AdapterView<?> parent) {
} // End of onCreate();


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMPORT_FILE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri content_describer = data.getData();
assert content_describer != null;
Log.d(TAG, Objects.requireNonNull(content_describer.getPath()));
try {
String inFileName = queryName(this.getContentResolver(), content_describer);
InputStream inputStream = this.getContentResolver().openInputStream(content_describer);
assert inputStream != null;
if (ImportFile(this, inFileName, inputStream)) {
privateKeyLocationET.setText(new File(getFilesDir() + PATH + inFileName).toString());
Toast.makeText(this, R.string.private_key_file_imported_success, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.private_key_file_imported_failed, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}


private String queryName(ContentResolver resolver, Uri uri) {
Cursor returnCursor =
resolver.query(uri, null, null, null, null);
assert returnCursor != null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = returnCursor.getString(nameIndex);
returnCursor.close();
return name;
}


public static boolean ImportFile(Context context, String fileName, InputStream inputStream) {
try {
OutputStream dbFileOutputStream = getDBOutputStream(context, fileName);

byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
dbFileOutputStream.write(buffer, 0, length);
}
dbFileOutputStream.flush();
dbFileOutputStream.close();
inputStream.close();

return true;
} catch (IOException e) {
return false;
}
}


private static OutputStream getDBOutputStream(Context context, String fileName) throws NullPointerException, IOException {
File filePath = new File(context.getFilesDir(), PATH);
filePath.mkdirs();

File file = new File(context.getFilesDir(), PATH + fileName);
if (!file.exists()) {
file.createNewFile();
}
return new FileOutputStream(file);
}


}
16 changes: 9 additions & 7 deletions app/src/main/res/values-ru/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@
<string name="path">Дорожка</string>
<string name="ups_editor_create_new">Редактор ИБП (Создать новый)</string>
<string name="ups_editor_update_existing">Редактор ИБП (обновить существующие)</string>
<string name="private_key_file_imported_success">Файл закрытого ключа импортирован.</string>
<string name="private_key_file_imported_failed">Не удалось импортировать файл закрытого ключа.</string>

<!-- UpsViewer -->
<string name="m">M</string>
Expand Down Expand Up @@ -169,13 +171,13 @@
<string name="ups_battery_date">Дата батареи</string>
<string name="ups_start_time_na">Время начала N/A</string>
<string name="ups_start_time">Начальное время</string>
<string name="use_below_selector_to_select_suitable_command">Use below selector to select suitable command</string>
<string name="click_to_select">Click to select…</string>
<string name="apcupsd_daemon_software">APCUPSD Daemon software</string>
<string name="apcupsd_daemon_software_no_sudo">APCUPSD Daemon software (No sudo)</string>
<string name="use_below_selector_to_select_suitable_command">Используйте селектор ниже, чтобы выбрать подходящую команду</string>
<string name="click_to_select">Нажмите, чтобы выбрать…</string>
<string name="apcupsd_daemon_software">APCUPSD Программное обеспечение демона</string>
<string name="apcupsd_daemon_software_no_sudo">APCUPSD Программное обеспечение демона (без sudo)</string>
<string name="synology_upsc">Synology UPSC</string>
<string name="apc_network_management_card_aos">APC Network Management Card AOS</string>
<string name="project_on_github">Project on Github</string>
<string name="ups_unreachable">UPS UNREACHABLE</string>
<string name="apc_network_management_card_aos">APC Карта сетевого управления AOS</string>
<string name="project_on_github">Проект на Github</string>
<string name="ups_unreachable">ИБП недоступен</string>

</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@
<string name="path">Path</string>
<string name="ups_editor_create_new">UPS Editor (Create new)</string>
<string name="ups_editor_update_existing">UPS Editor (Update existing)</string>
<string name="private_key_file_imported_success">Private key file imported.</string>
<string name="private_key_file_imported_failed">Failed to import private key file.</string>

<!-- UpsViewer -->
<string name="m">M</string>
Expand Down

0 comments on commit 7f6257c

Please sign in to comment.