fix(download): salvar no app Android so o arquivo escolhido na pre-visualizacao via plugin nativo
WebView do Capacitor ignora link blob: com download; botao Baixar da pre-visualizacao passa a usar o plugin NativeDownload (MediaStore/Downloads). Sem salvamento automatico. Validacao: node --test test/native-download.test.js 2/2 ok; npm test 157/160, as 3 falhas (navigator JSDOM no Node 22 e sanitizacao de video no gateway) existem igualmente no HEAD anterior.
This commit is contained in:
parent
563a741a8e
commit
68ae249c33
@ -50,6 +50,7 @@
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
|
||||
|
||||
@ -29,6 +29,7 @@ public class MainActivity extends BridgeActivity {
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
registerPlugin(NativeDownloadPlugin.class);
|
||||
super.onCreate(savedInstanceState);
|
||||
try {
|
||||
initFirebaseSafely();
|
||||
@ -170,6 +171,11 @@ public class MainActivity extends BridgeActivity {
|
||||
permissionsNeeded.add(Manifest.permission.CAMERA);
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
|
||||
&& ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
permissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||
permissionsNeeded.add(Manifest.permission.POST_NOTIFICATIONS);
|
||||
|
||||
@ -0,0 +1,121 @@
|
||||
package com.maestri.remote;
|
||||
|
||||
import android.content.ContentResolver;
|
||||
import android.content.ContentValues;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
import android.provider.MediaStore;
|
||||
import android.util.Base64;
|
||||
import android.util.Log;
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.Plugin;
|
||||
import com.getcapacitor.PluginCall;
|
||||
import com.getcapacitor.PluginMethod;
|
||||
import com.getcapacitor.annotation.CapacitorPlugin;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
/**
|
||||
* Salva em Downloads o arquivo que o operador escolheu baixar na pré-visualização do app.
|
||||
* A WebView do Capacitor ignora links blob: com atributo download, por isso o conteúdo
|
||||
* (Base64) chega por este plugin e é gravado pelo MediaStore (Android 10+) ou direto na
|
||||
* pasta pública de Downloads (Android 9 ou anterior).
|
||||
*/
|
||||
@CapacitorPlugin(name = "NativeDownload")
|
||||
public class NativeDownloadPlugin extends Plugin {
|
||||
private static final String TAG = "MaestriNativeDownload";
|
||||
|
||||
@PluginMethod
|
||||
public void save(PluginCall call) {
|
||||
String name = sanitizeFileName(call.getString("name", "arquivo"));
|
||||
String mimeType = call.getString("mimeType", "application/octet-stream");
|
||||
String data = call.getString("data");
|
||||
|
||||
if (data == null || data.isEmpty()) {
|
||||
call.reject("Conteúdo do arquivo vazio.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
byte[] bytes = Base64.decode(data, Base64.DEFAULT);
|
||||
String savedPath;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
savedPath = saveWithMediaStore(name, mimeType, bytes);
|
||||
} else {
|
||||
savedPath = saveToPublicDownloads(name, bytes);
|
||||
}
|
||||
JSObject ret = new JSObject();
|
||||
ret.put("path", savedPath);
|
||||
call.resolve(ret);
|
||||
} catch (IllegalArgumentException e) {
|
||||
call.reject("Conteúdo Base64 inválido.");
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Falha ao salvar arquivo em Downloads: " + e.getMessage(), e);
|
||||
call.reject("Falha ao salvar em Downloads: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private String saveWithMediaStore(String name, String mimeType, byte[] bytes) throws IOException {
|
||||
ContentResolver resolver = getContext().getContentResolver();
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
|
||||
values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
|
||||
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
|
||||
values.put(MediaStore.MediaColumns.IS_PENDING, 1);
|
||||
|
||||
Uri uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values);
|
||||
if (uri == null) {
|
||||
throw new IOException("o sistema recusou criar o arquivo em Downloads");
|
||||
}
|
||||
try (OutputStream out = resolver.openOutputStream(uri)) {
|
||||
if (out == null) {
|
||||
throw new IOException("não foi possível abrir o arquivo para escrita");
|
||||
}
|
||||
out.write(bytes);
|
||||
} catch (IOException e) {
|
||||
resolver.delete(uri, null, null);
|
||||
throw e;
|
||||
}
|
||||
values.clear();
|
||||
values.put(MediaStore.MediaColumns.IS_PENDING, 0);
|
||||
resolver.update(uri, values, null, null);
|
||||
return Environment.DIRECTORY_DOWNLOADS + "/" + name;
|
||||
}
|
||||
|
||||
private String saveToPublicDownloads(String name, byte[] bytes) throws IOException {
|
||||
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
|
||||
if (!dir.exists() && !dir.mkdirs()) {
|
||||
throw new IOException("pasta Downloads indisponível");
|
||||
}
|
||||
File target = uniqueFile(dir, name);
|
||||
try (FileOutputStream out = new FileOutputStream(target)) {
|
||||
out.write(bytes);
|
||||
}
|
||||
return target.getAbsolutePath();
|
||||
}
|
||||
|
||||
private static File uniqueFile(File dir, String name) {
|
||||
File candidate = new File(dir, name);
|
||||
if (!candidate.exists()) return candidate;
|
||||
int dot = name.lastIndexOf('.');
|
||||
String base = dot > 0 ? name.substring(0, dot) : name;
|
||||
String ext = dot > 0 ? name.substring(dot) : "";
|
||||
for (int i = 1; i < 1000; i++) {
|
||||
candidate = new File(dir, base + " (" + i + ")" + ext);
|
||||
if (!candidate.exists()) return candidate;
|
||||
}
|
||||
return new File(dir, base + "-" + System.currentTimeMillis() + ext);
|
||||
}
|
||||
|
||||
private static String sanitizeFileName(String raw) {
|
||||
String name = raw == null ? "" : raw;
|
||||
int slash = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'));
|
||||
if (slash >= 0) name = name.substring(slash + 1);
|
||||
name = name.replaceAll("[\\x00-\\x1F:*?\"<>|]", "_").trim();
|
||||
if (name.isEmpty() || name.equals(".") || name.equals("..")) name = "arquivo";
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@ -2682,11 +2682,40 @@ function closeFilePreviewModal() {
|
||||
}
|
||||
window.closeFilePreviewModal = closeFilePreviewModal;
|
||||
|
||||
function saveCurrentActiveFile() {
|
||||
function getNativeDownloadPlugin() {
|
||||
const cap = window.Capacitor;
|
||||
if (!cap || typeof cap.isNativePlatform !== 'function' || !cap.isNativePlatform()) return null;
|
||||
if (typeof cap.isPluginAvailable === 'function' && !cap.isPluginAvailable('NativeDownload')) return undefined;
|
||||
return (cap.Plugins && cap.Plugins.NativeDownload) || undefined;
|
||||
}
|
||||
|
||||
async function saveCurrentActiveFile() {
|
||||
if (!currentActiveFile || !currentActiveFile.contentBase64) return;
|
||||
const { name, path: filePath, mimeType, contentBase64 } = currentActiveFile;
|
||||
const fileName = name || (filePath ? filePath.split('/').pop() : 'arquivo');
|
||||
|
||||
// No app Android (WebView do Capacitor), link blob: com a.download é ignorado em silêncio.
|
||||
// O arquivo escolhido na pré-visualização é salvo em Downloads pelo plugin nativo NativeDownload.
|
||||
const nativeDownload = getNativeDownloadPlugin();
|
||||
if (nativeDownload === undefined) {
|
||||
showToast('Atualize o app Android (APK) para baixar arquivos.', 'error');
|
||||
return;
|
||||
}
|
||||
if (nativeDownload) {
|
||||
try {
|
||||
const res = await nativeDownload.save({
|
||||
name: fileName,
|
||||
mimeType: mimeType || 'application/octet-stream',
|
||||
data: contentBase64
|
||||
});
|
||||
showToast(`"${fileName}" salvo em ${(res && res.path) || 'Downloads'}`, 'info');
|
||||
} catch (err) {
|
||||
console.error('[FileDownload] Erro ao salvar arquivo pelo app nativo:', err);
|
||||
showToast(`Erro ao salvar arquivo: ${(err && err.message) || err}`, 'error');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const byteCharacters = atob(contentBase64);
|
||||
const byteNumbers = new Array(byteCharacters.length);
|
||||
|
||||
103
test/native-download.test.js
Normal file
103
test/native-download.test.js
Normal file
@ -0,0 +1,103 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
<div id="file-preview-modal" style="display: none;">
|
||||
<span id="file-preview-icon"></span>
|
||||
<h3 id="file-preview-title"></h3>
|
||||
<span id="file-preview-meta"></span>
|
||||
<div id="file-preview-body"></div>
|
||||
<button id="btn-copy-file-content" style="display: none;"></button>
|
||||
<button id="btn-save-file"></button>
|
||||
<button id="btn-close-file-preview">×</button>
|
||||
</div>
|
||||
<div class="chat-messages" id="chat-messages"></div>
|
||||
<form id="chat-form"><input type="text" id="chat-input"></form>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
function setGlobal(name, value) {
|
||||
Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });
|
||||
}
|
||||
|
||||
test('Pré-visualização: no app Android, "Baixar" salva pelo plugin nativo NativeDownload só o arquivo escolhido', async () => {
|
||||
const dom = new JSDOM(html, { url: 'https://remote.test/' });
|
||||
const calls = [];
|
||||
dom.window.Capacitor = {
|
||||
isNativePlatform: () => true,
|
||||
isPluginAvailable: (name) => name === 'NativeDownload',
|
||||
Plugins: {
|
||||
NativeDownload: {
|
||||
save: async (opts) => {
|
||||
calls.push(opts);
|
||||
return { path: `Download/${opts.name}` };
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
dom.window.WebSocket = class { constructor() { this.readyState = 0; } send() {} close() {} };
|
||||
setGlobal('window', dom.window);
|
||||
setGlobal('document', dom.window.document);
|
||||
setGlobal('navigator', dom.window.navigator);
|
||||
setGlobal('WebSocket', dom.window.WebSocket);
|
||||
setGlobal('localStorage', dom.window.localStorage);
|
||||
|
||||
await import('../public/app.js?native-download');
|
||||
|
||||
const { openFilePreviewModal, saveCurrentActiveFile } = dom.window;
|
||||
assert.equal(typeof saveCurrentActiveFile, 'function');
|
||||
|
||||
const contentBase64 = Buffer.from('conteudo de teste').toString('base64');
|
||||
openFilePreviewModal({ ok: true, name: 'relatorio.txt', path: 'docs/relatorio.txt', mimeType: 'text/plain', size: 17, contentBase64 });
|
||||
|
||||
let blobClicked = false;
|
||||
const originalCreate = dom.window.document.createElement.bind(dom.window.document);
|
||||
dom.window.document.createElement = (tag) => {
|
||||
const el = originalCreate(tag);
|
||||
if (String(tag).toLowerCase() === 'a') el.click = () => { blobClicked = true; };
|
||||
return el;
|
||||
};
|
||||
|
||||
await saveCurrentActiveFile();
|
||||
|
||||
assert.equal(calls.length, 1, 'deve chamar NativeDownload.save uma vez');
|
||||
assert.deepEqual(calls[0], { name: 'relatorio.txt', mimeType: 'text/plain', data: contentBase64 });
|
||||
assert.equal(blobClicked, false, 'no app nativo não deve cair no link blob:, que a WebView ignora');
|
||||
});
|
||||
|
||||
test('Pré-visualização: em APK antigo sem o plugin NativeDownload, "Baixar" avisa para atualizar o app em vez de falhar calado', async () => {
|
||||
const dom = new JSDOM(html, { url: 'https://remote.test/' });
|
||||
dom.window.Capacitor = {
|
||||
isNativePlatform: () => true,
|
||||
isPluginAvailable: () => false,
|
||||
Plugins: {}
|
||||
};
|
||||
dom.window.WebSocket = class { constructor() { this.readyState = 0; } send() {} close() {} };
|
||||
setGlobal('window', dom.window);
|
||||
setGlobal('document', dom.window.document);
|
||||
setGlobal('navigator', dom.window.navigator);
|
||||
setGlobal('WebSocket', dom.window.WebSocket);
|
||||
setGlobal('localStorage', dom.window.localStorage);
|
||||
|
||||
await import('../public/app.js?native-download-old-apk');
|
||||
const { openFilePreviewModal, saveCurrentActiveFile } = dom.window;
|
||||
|
||||
openFilePreviewModal({ ok: true, name: 'a.txt', path: 'a.txt', mimeType: 'text/plain', size: 1, contentBase64: 'YQ==' });
|
||||
|
||||
let blobClicked = false;
|
||||
const originalCreate = dom.window.document.createElement.bind(dom.window.document);
|
||||
dom.window.document.createElement = (tag) => {
|
||||
const el = originalCreate(tag);
|
||||
if (String(tag).toLowerCase() === 'a') el.click = () => { blobClicked = true; };
|
||||
return el;
|
||||
};
|
||||
|
||||
await saveCurrentActiveFile();
|
||||
assert.equal(blobClicked, false);
|
||||
assert.match(dom.window.document.body.textContent, /Atualize o app Android/);
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user