From 831d935f0c6d4b5bf65436b91387ef5dac0bd22d Mon Sep 17 00:00:00 2001 From: CodeDead Date: Sat, 31 Oct 2026 04:48:53 +0100 Subject: [PATCH 1/2] feat: added ability to export passwords as txt or csv --- README.md | 1 + .../domain/PasswordAdapter.java | 9 + .../domain/PasswordExporter.java | 86 ++++++++ .../advancedpassgen/ui/home/HomeFragment.java | 185 +++++++++++++++++- .../drawable/baseline_file_download_24.xml | 12 ++ app/src/main/res/layout/fragment_home.xml | 11 ++ app/src/main/res/values-fr/strings.xml | 5 + app/src/main/res/values-nl/strings.xml | 5 + app/src/main/res/values/strings.xml | 5 + 9 files changed, 318 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/com/codedead/advancedpassgen/domain/PasswordExporter.java create mode 100644 app/src/main/res/drawable/baseline_file_download_24.xml diff --git a/README.md b/README.md index c5fb769..f44f9ee 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/app/src/main/java/com/codedead/advancedpassgen/domain/PasswordAdapter.java b/app/src/main/java/com/codedead/advancedpassgen/domain/PasswordAdapter.java index 0671cc2..2484b6e 100644 --- a/app/src/main/java/com/codedead/advancedpassgen/domain/PasswordAdapter.java +++ b/app/src/main/java/com/codedead/advancedpassgen/domain/PasswordAdapter.java @@ -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 getItems() { + return new ArrayList<>(items); + } + /** * Set the display strength setting * diff --git a/app/src/main/java/com/codedead/advancedpassgen/domain/PasswordExporter.java b/app/src/main/java/com/codedead/advancedpassgen/domain/PasswordExporter.java new file mode 100644 index 0000000..c685baf --- /dev/null +++ b/app/src/main/java/com/codedead/advancedpassgen/domain/PasswordExporter.java @@ -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 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 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 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; + } +} diff --git a/app/src/main/java/com/codedead/advancedpassgen/ui/home/HomeFragment.java b/app/src/main/java/com/codedead/advancedpassgen/ui/home/HomeFragment.java index 4583ea2..48dbb9d 100644 --- a/app/src/main/java/com/codedead/advancedpassgen/ui/home/HomeFragment.java +++ b/app/src/main/java/com/codedead/advancedpassgen/ui/home/HomeFragment.java @@ -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; @@ -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; @@ -40,6 +59,15 @@ public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefre private boolean numbers; private boolean brackets; private int poolSize; + private List pendingExportItems; + + private final ActivityResultLauncher exportTxtLauncher = registerForActivityResult( + new ActivityResultContracts.CreateDocument("text/plain"), + uri -> handleExportResult(uri, PasswordExporter.Format.TXT)); + + private final ActivityResultLauncher exportCsvLauncher = registerForActivityResult( + new ActivityResultContracts.CreateDocument("text/csv"), + uri -> handleExportResult(uri, PasswordExporter.Format.CSV)); public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, @@ -59,6 +87,26 @@ 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); @@ -66,6 +114,7 @@ public View onCreateView(@NonNull final LayoutInflater inflater, 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); @@ -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 -> { @@ -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(); @@ -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); @@ -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 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", ""); diff --git a/app/src/main/res/drawable/baseline_file_download_24.xml b/app/src/main/res/drawable/baseline_file_download_24.xml new file mode 100644 index 0000000..2b7372b --- /dev/null +++ b/app/src/main/res/drawable/baseline_file_download_24.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/app/src/main/res/layout/fragment_home.xml b/app/src/main/res/layout/fragment_home.xml index b891991..caf4367 100644 --- a/app/src/main/res/layout/fragment_home.xml +++ b/app/src/main/res/layout/fragment_home.xml @@ -96,6 +96,17 @@ android:contentDescription="@string/add" app:srcCompat="@drawable/baseline_add_24" /> + + diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 2afc6ca..6ebfc06 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -59,4 +59,9 @@ Le nombre de threads à utiliser pour la génération de mot de passe Afficher la force du mot de passe Afficher la force du mot de passe généré dans la liste + Exporter les mots de passe + Texte brut (.txt) + CSV (.csv) + Mots de passe exportés + Impossible d\'exporter les mots de passe diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index c6ce804..57ea228 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -59,4 +59,9 @@ Het aantal threads dat moet worden gebruikt voor wachtwoordgeneratie Toon wachtwoordsterkte Toon de sterkte van het gegenereerde wachtwoord in de lijst + Wachtwoorden exporteren + Platte tekst (.txt) + CSV (.csv) + Wachtwoorden geëxporteerd + Kan wachtwoorden niet exporteren diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2cae8ce..674f590 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -58,4 +58,9 @@ The amount of threads to use for password generation Display password strength Display the strength of the generated password in the list + Export passwords + Plain text (.txt) + CSV (.csv) + Passwords exported + Could not export passwords From 3a309c73e497300ee330aa94e2c9e4c19ccb9078 Mon Sep 17 00:00:00 2001 From: CodeDead Date: Sat, 31 Oct 2026 04:51:14 +0100 Subject: [PATCH 2/2] feat: update action --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1b72a19..a51b8c0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -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