Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7

- name: Setup JDK 21
uses: actions/setup-java@v6
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ The user can choose the length of the password, the number of passwords to gener

- [x] Generate passwords based on user preferences
- [x] Copy generated password to clipboard
- [x] Export generated passwords to TXT or CSV
- [x] Dark mode support
- [x] Material design
- [x] Open-source
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,15 @@ public int getItemCount() {
return items.size();
}

/**
* Get a copy of the items in the adapter
*
* @return A {@link List} of {@link PasswordItem} objects
*/
public List<PasswordItem> getItems() {
return new ArrayList<>(items);
}

/**
* Set the display strength setting
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.codedead.advancedpassgen.domain;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

public final class PasswordExporter {

/**
* The supported export formats
*/
public enum Format {
TXT,
CSV
}

/**
* Initialize a new PasswordExporter
*/
private PasswordExporter() {
// Default constructor
}

/**
* Write a {@link List} of {@link PasswordItem} objects to a {@link Writer}
*
* @param writer The {@link Writer} to write the passwords to
* @param items The {@link List} of {@link PasswordItem} objects to export
* @param format The {@link Format} to export the passwords in
* @throws IOException When an error occurs while writing the passwords
*/
public static void write(final Writer writer, final List<PasswordItem> items, final Format format) throws IOException {
switch (format) {
case TXT:
writeTxt(writer, items);
break;
case CSV:
writeCsv(writer, items);
break;
}
}

/**
* Write the passwords as plain text, one password per line
*
* @param writer The {@link Writer} to write the passwords to
* @param items The {@link List} of {@link PasswordItem} objects to export
* @throws IOException When an error occurs while writing the passwords
*/
private static void writeTxt(final Writer writer, final List<PasswordItem> items) throws IOException {
for (final PasswordItem item : items) {
writer.write(item.password());
writer.write('\n');
}
}

/**
* Write the passwords as CSV, using the Password header and RFC 4180 escaping
*
* @param writer The {@link Writer} to write the passwords to
* @param items The {@link List} of {@link PasswordItem} objects to export
* @throws IOException When an error occurs while writing the passwords
*/
private static void writeCsv(final Writer writer, final List<PasswordItem> items) throws IOException {
writer.write("Password\r\n");

for (final PasswordItem item : items) {
writer.write(escapeCsv(item.password()));
writer.write("\r\n");
}
}

/**
* Escape a value so it can be used in a CSV file
*
* @param value The value to escape
* @return The escaped value
*/
static String escapeCsv(final String value) {
if (value.indexOf(',') >= 0 || value.indexOf('"') >= 0 || value.indexOf('\n') >= 0 || value.indexOf('\r') >= 0) {
return '"' + value.replace("\"", "\"\"") + '"';
}

return value;
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
package com.codedead.advancedpassgen.ui.home;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
Expand All @@ -14,13 +22,24 @@
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.codedead.advancedpassgen.R;
import com.codedead.advancedpassgen.databinding.FragmentHomeBinding;
import com.codedead.advancedpassgen.domain.PasswordAdapter;
import com.codedead.advancedpassgen.domain.PasswordExporter;
import com.codedead.advancedpassgen.domain.PasswordGenerator;
import com.codedead.advancedpassgen.domain.PasswordItem;
import com.codedead.advancedpassgen.utils.UtilController;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

Expand All @@ -40,6 +59,15 @@ public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefre
private boolean numbers;
private boolean brackets;
private int poolSize;
private List<PasswordItem> pendingExportItems;

private final ActivityResultLauncher<String> exportTxtLauncher = registerForActivityResult(
new ActivityResultContracts.CreateDocument("text/plain"),
uri -> handleExportResult(uri, PasswordExporter.Format.TXT));

private final ActivityResultLauncher<String> exportCsvLauncher = registerForActivityResult(
new ActivityResultContracts.CreateDocument("text/csv"),
uri -> handleExportResult(uri, PasswordExporter.Format.CSV));

public View onCreateView(@NonNull final LayoutInflater inflater,
final ViewGroup container,
Expand All @@ -59,13 +87,34 @@ public View onCreateView(@NonNull final LayoutInflater inflater,
recyclerView.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapter);

adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
updateExportFabVisibility();
}

@Override
public void onItemRangeInserted(final int positionStart, final int itemCount) {
updateExportFabVisibility();
}

@Override
public void onItemRangeRemoved(final int positionStart, final int itemCount) {
updateExportFabVisibility();
}
});

binding.fabExport.setOnClickListener(view -> showExportFormatDialog());
updateExportFabVisibility();

binding.fabAdd.setOnClickListener(view -> {
binding.textHome.setVisibility(View.GONE);
binding.swipeRefresh.setVisibility(View.VISIBLE);

binding.fabClear.setEnabled(false);
binding.fabRefresh.setEnabled(false);
binding.fabAdd.setEnabled(false);
binding.fabExport.setEnabled(false);

final PasswordItem item = PasswordGenerator.generatePasswords(minimumLength, maximumLength, 1, smallLetters, capitalLetters, numbers, specialCharacters, brackets, spaces, customCharacterSet).get(0);

Expand All @@ -75,6 +124,7 @@ public View onCreateView(@NonNull final LayoutInflater inflater,
binding.fabClear.setEnabled(true);
binding.fabRefresh.setEnabled(true);
binding.fabAdd.setEnabled(true);
binding.fabExport.setEnabled(true);
});

binding.fabClear.setOnClickListener(view -> {
Expand Down Expand Up @@ -121,6 +171,7 @@ private void refreshPasswords() {
binding.fabClear.setEnabled(false);
binding.fabRefresh.setEnabled(false);
binding.fabAdd.setEnabled(false);
binding.fabExport.setEnabled(false);

adapter.clear();

Expand Down Expand Up @@ -155,6 +206,7 @@ private void refreshPasswords() {
binding.fabClear.setEnabled(true);
binding.fabRefresh.setEnabled(true);
binding.fabAdd.setEnabled(true);
binding.fabExport.setEnabled(true);

binding.swipeRefresh.setRefreshing(false);
binding.textHome.setRefreshing(false);
Expand All @@ -163,6 +215,137 @@ private void refreshPasswords() {
}
}

/**
* Show or hide the export button based on the number of passwords
*/
private void updateExportFabVisibility() {
if (binding == null || adapter == null) {
return;
}

binding.fabExport.setVisibility(adapter.getItemCount() > 0 ? View.VISIBLE : View.GONE);
}

/**
* Show a dialog which allows the user to pick an export format
*/
private void showExportFormatDialog() {
if (adapter == null || adapter.getItemCount() == 0) {
return;
}

new MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.export_passwords)
.setItems(new CharSequence[]{
getString(R.string.export_txt),
getString(R.string.export_csv)
}, (dialog, which) -> {
if (which == 0) {
startExport(PasswordExporter.Format.TXT);
} else {
startExport(PasswordExporter.Format.CSV);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}

/**
* Start an export by asking the user where to save the file
*
* @param format The {@link PasswordExporter.Format} to export the passwords in
*/
private void startExport(final PasswordExporter.Format format) {
if (adapter == null) {
return;
}

pendingExportItems = adapter.getItems();

if (pendingExportItems.isEmpty()) {
return;
}

final String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
final String filename = "passwords_" + timestamp;

if (format == PasswordExporter.Format.TXT) {
exportTxtLauncher.launch(filename + ".txt");
} else {
exportCsvLauncher.launch(filename + ".csv");
}
}

/**
* Handle the result of the file picker
*
* @param uri The {@link Uri} of the file to export to, or null if the user cancelled
* @param format The {@link PasswordExporter.Format} to export the passwords in
*/
private void handleExportResult(final Uri uri, final PasswordExporter.Format format) {
if (uri == null) {
pendingExportItems = null;
return;
}

writeExport(uri, format);
}

/**
* Write the pending passwords to the selected file
*
* @param uri The {@link Uri} of the file to export to
* @param format The {@link PasswordExporter.Format} to export the passwords in
*/
private void writeExport(final Uri uri, final PasswordExporter.Format format) {
final List<PasswordItem> items = pendingExportItems;
pendingExportItems = null;

if (items == null || items.isEmpty()) {
return;
}

final Context context = getContext();
if (context == null) {
return;
}

final Context applicationContext = context.getApplicationContext();
final ExecutorService executorService = Executors.newSingleThreadExecutor();

executorService.execute(() -> {
try {
final OutputStream outputStream = applicationContext.getContentResolver().openOutputStream(uri, "wt");
if (outputStream == null) {
throw new IOException("Unable to open the export file");
}

try (final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8))) {
PasswordExporter.write(writer, items, format);
}

showExportResult(applicationContext, true);
} catch (final Exception ex) {
Log.e(HomeFragment.class.getSimpleName(), "An error occurred while exporting passwords: " + ex.getMessage());
showExportResult(applicationContext, false);
} finally {
executorService.shutdown();
}
});
}

/**
* Show the result of an export
*
* @param context The {@link Context} that can be used to show the toast
* @param success Whether the export was successful
*/
private static void showExportResult(final Context context, final boolean success) {
final int message = success ? R.string.export_success : R.string.export_failed;

new Handler(Looper.getMainLooper()).post(() -> Toast.makeText(context, message, Toast.LENGTH_SHORT).show());
}

@Override
public void onResume() {
customCharacterSet = sharedPreferences.getString("customCharacterSet", "");
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/res/drawable/baseline_file_download_24.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="32dp"
android:height="32dp"
android:fillColor="?attr/colorSecondary"
android:viewportWidth="24"
android:viewportHeight="24">

<path
android:fillColor="?attr/colorSecondary"
android:pathData="M19,9h-4V3H9v6H5l7,7 7,-7zM5,18v2h14v-2H5z" />

</vector>
Loading
Loading