82 lines
2.8 KiB
Java
82 lines
2.8 KiB
Java
package org.julianfamily.keepassgo;
|
|
|
|
import android.content.Context;
|
|
import android.content.Intent;
|
|
import android.net.Uri;
|
|
|
|
import java.io.File;
|
|
import java.io.FileInputStream;
|
|
import java.io.FileOutputStream;
|
|
import java.io.IOException;
|
|
|
|
public final class AndroidShare {
|
|
private static final String DEFAULT_TITLE = "KeePassGO Vault";
|
|
|
|
private AndroidShare() {
|
|
}
|
|
|
|
public static void shareVault(Context context, String path, String title) throws IOException {
|
|
File source = new File(path);
|
|
if (!source.isFile()) {
|
|
throw new IOException("vault file not found: " + path);
|
|
}
|
|
File shared = copyToSharedExport(context, source);
|
|
Uri uri = SharedVaultProvider.uriForFile(shared.getName());
|
|
|
|
Intent send = new Intent(Intent.ACTION_SEND);
|
|
send.setType("application/x-keepass2");
|
|
send.putExtra(Intent.EXTRA_STREAM, uri);
|
|
send.putExtra(Intent.EXTRA_TITLE, sanitizeTitle(title, source.getName()));
|
|
send.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
|
|
|
Intent chooser = Intent.createChooser(send, "Share vault");
|
|
chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
|
chooser.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
|
context.startActivity(chooser);
|
|
}
|
|
|
|
static File sharedDirectory(Context context) {
|
|
return new File(new File(context.getFilesDir(), "keepassgo"), "shared");
|
|
}
|
|
|
|
private static File copyToSharedExport(Context context, File source) throws IOException {
|
|
File dir = sharedDirectory(context);
|
|
if (!dir.exists() && !dir.mkdirs()) {
|
|
throw new IOException("failed to create " + dir.getAbsolutePath());
|
|
}
|
|
File target = new File(dir, sanitizeFilename(source.getName()));
|
|
try (FileInputStream in = new FileInputStream(source);
|
|
FileOutputStream out = new FileOutputStream(target, false)) {
|
|
byte[] buffer = new byte[8192];
|
|
int count;
|
|
while ((count = in.read(buffer)) >= 0) {
|
|
out.write(buffer, 0, count);
|
|
}
|
|
}
|
|
return target;
|
|
}
|
|
|
|
private static String sanitizeFilename(String name) {
|
|
String trimmed = name == null ? "" : name.trim();
|
|
if (trimmed.isEmpty()) {
|
|
return "shared-vault.kdbx";
|
|
}
|
|
if (trimmed.endsWith(".kdbx")) {
|
|
return trimmed;
|
|
}
|
|
return trimmed + ".kdbx";
|
|
}
|
|
|
|
private static String sanitizeTitle(String title, String fallbackName) {
|
|
String trimmed = title == null ? "" : title.trim();
|
|
if (!trimmed.isEmpty()) {
|
|
return trimmed;
|
|
}
|
|
String fallback = fallbackName == null ? "" : fallbackName.trim();
|
|
if (!fallback.isEmpty()) {
|
|
return fallback;
|
|
}
|
|
return DEFAULT_TITLE;
|
|
}
|
|
}
|