|
|
@@ -0,0 +1,876 @@
|
|
|
+package cn.fmode.app;
|
|
|
+
|
|
|
+import android.app.Activity;
|
|
|
+import android.content.ClipData;
|
|
|
+import android.content.ContentResolver;
|
|
|
+import android.content.Context;
|
|
|
+import android.content.Intent;
|
|
|
+import android.database.Cursor;
|
|
|
+import android.net.Uri;
|
|
|
+import android.os.SystemClock;
|
|
|
+import android.provider.OpenableColumns;
|
|
|
+import android.util.AtomicFile;
|
|
|
+import android.util.Base64;
|
|
|
+import android.webkit.MimeTypeMap;
|
|
|
+
|
|
|
+import com.getcapacitor.JSObject;
|
|
|
+import com.getcapacitor.Plugin;
|
|
|
+import com.getcapacitor.PluginCall;
|
|
|
+import com.getcapacitor.PluginMethod;
|
|
|
+import com.getcapacitor.annotation.CapacitorPlugin;
|
|
|
+
|
|
|
+import org.json.JSONArray;
|
|
|
+import org.json.JSONException;
|
|
|
+import org.json.JSONObject;
|
|
|
+
|
|
|
+import java.io.ByteArrayOutputStream;
|
|
|
+import java.io.File;
|
|
|
+import java.io.FileInputStream;
|
|
|
+import java.io.FileNotFoundException;
|
|
|
+import java.io.FileOutputStream;
|
|
|
+import java.io.IOException;
|
|
|
+import java.io.InputStream;
|
|
|
+import java.io.OutputStream;
|
|
|
+import java.net.HttpURLConnection;
|
|
|
+import java.net.CookieHandler;
|
|
|
+import java.net.SocketTimeoutException;
|
|
|
+import java.net.URI;
|
|
|
+import java.net.URL;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.security.MessageDigest;
|
|
|
+import java.security.SecureRandom;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.Arrays;
|
|
|
+import java.util.Comparator;
|
|
|
+import java.util.Collections;
|
|
|
+import java.util.HashSet;
|
|
|
+import java.util.LinkedHashMap;
|
|
|
+import java.util.LinkedHashSet;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Locale;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.Set;
|
|
|
+import java.util.UUID;
|
|
|
+import java.util.concurrent.Executors;
|
|
|
+import java.util.concurrent.ScheduledExecutorService;
|
|
|
+import java.util.concurrent.ScheduledFuture;
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
+
|
|
|
+import javax.crypto.Mac;
|
|
|
+import javax.crypto.spec.SecretKeySpec;
|
|
|
+import javax.net.ssl.HttpsURLConnection;
|
|
|
+
|
|
|
+@CapacitorPlugin(name = "NativeShare")
|
|
|
+public class NativeSharePlugin extends Plugin {
|
|
|
+ static final long MAX_FILE_BYTES = 800L * 1024 * 1024;
|
|
|
+ static final long MAX_CACHE_BYTES = 2L * 1024 * 1024 * 1024;
|
|
|
+ static final long CACHE_TTL_MS = TimeUnit.HOURS.toMillis(24);
|
|
|
+ static final long TRANSFER_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(5);
|
|
|
+ static final int MAX_FILES_PER_SHARE = 32;
|
|
|
+ static final int MAX_CACHED_FILES = 128;
|
|
|
+ private static final int MAX_OUTGOING_FILES = 32;
|
|
|
+ private static final String EVENT = "shareReceived";
|
|
|
+ private static final String RECEIPT_ID = "cn.fmode.app.NativeShare.id";
|
|
|
+ private static final String RECEIPT_MAC = "cn.fmode.app.NativeShare.receipt";
|
|
|
+ private static final Object LOCK = new Object();
|
|
|
+ private static final java.util.concurrent.ExecutorService WORKER = Executors.newSingleThreadExecutor();
|
|
|
+ private static final ScheduledExecutorService TIMER = Executors.newSingleThreadScheduledExecutor();
|
|
|
+ private static volatile NativeSharePlugin instance;
|
|
|
+ private static ShareStore store;
|
|
|
+ private static volatile String storageFailure;
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void load() {
|
|
|
+ instance = this;
|
|
|
+ Context context = getContext().getApplicationContext();
|
|
|
+ WORKER.execute(() -> {
|
|
|
+ try {
|
|
|
+ getStore(context).maintain();
|
|
|
+ } catch (Exception failure) {
|
|
|
+ storageFailure = "E_QUEUE_STORAGE: 无法恢复原生分享队列";
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ protected void handleOnDestroy() {
|
|
|
+ if (instance == this) instance = null;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static void receiveIntent(Activity activity, Intent intent) {
|
|
|
+ if (activity == null || intent == null) return;
|
|
|
+ String action = intent.getAction();
|
|
|
+ if (!Intent.ACTION_SEND.equals(action) && !Intent.ACTION_SEND_MULTIPLE.equals(action)) return;
|
|
|
+ Context context = activity.getApplicationContext();
|
|
|
+ try {
|
|
|
+ ShareStore current = getStore(context);
|
|
|
+ Incoming incoming = current.accept(intent);
|
|
|
+ if (incoming == null) return;
|
|
|
+ WORKER.execute(() -> {
|
|
|
+ current.copyIncoming(incoming);
|
|
|
+ publish(current, incoming.id);
|
|
|
+ });
|
|
|
+ } catch (Exception failure) {
|
|
|
+ storageFailure = "E_QUEUE_STORAGE: 无法持久保存收到的分享,请勿关闭应用并重新分享";
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @PluginMethod
|
|
|
+ public void getPendingShares(PluginCall call) {
|
|
|
+ WORKER.execute(() -> {
|
|
|
+ try {
|
|
|
+ ShareStore current = getStore(getContext());
|
|
|
+ current.maintain();
|
|
|
+ if (storageFailure != null) {
|
|
|
+ call.reject(storageFailure, "E_QUEUE_STORAGE");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ call.resolve(new JSObject().put("shares", current.pending()));
|
|
|
+ } catch (Exception failure) {
|
|
|
+ call.reject("无法读取原生分享队列", "E_QUEUE_STORAGE");
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ @PluginMethod(returnType = PluginMethod.RETURN_NONE)
|
|
|
+ public void addListener(PluginCall call) {
|
|
|
+ WORKER.execute(() -> {
|
|
|
+ boolean replay = EVENT.equals(call.getString("eventName")) && !hasListeners(EVENT);
|
|
|
+ super.addListener(call);
|
|
|
+ if (!replay) return;
|
|
|
+ try {
|
|
|
+ ShareStore current = getStore(getContext());
|
|
|
+ current.maintain();
|
|
|
+ JSONArray shares = current.pending();
|
|
|
+ for (int index = 0; index < shares.length(); index++) {
|
|
|
+ notifyListeners(EVENT, new JSObject().put("share", shares.getJSONObject(index)));
|
|
|
+ }
|
|
|
+ } catch (Exception failure) {
|
|
|
+ storageFailure = "E_QUEUE_STORAGE: 无法重放原生分享队列";
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ @PluginMethod(returnType = PluginMethod.RETURN_NONE)
|
|
|
+ public void removeListener(PluginCall call) {
|
|
|
+ WORKER.execute(() -> super.removeListener(call));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ @PluginMethod
|
|
|
+ public void removeAllListeners(PluginCall call) {
|
|
|
+ WORKER.execute(() -> super.removeAllListeners(call));
|
|
|
+ }
|
|
|
+
|
|
|
+ @PluginMethod
|
|
|
+ public void acknowledgeShare(PluginCall call) {
|
|
|
+ String id = call.getString("id");
|
|
|
+ if (!validId(id)) {
|
|
|
+ call.reject("id 必须是分享队列返回的 UUID", "E_INVALID_ID");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ WORKER.execute(() -> {
|
|
|
+ try {
|
|
|
+ getStore(getContext()).acknowledge(id);
|
|
|
+ call.resolve();
|
|
|
+ } catch (Exception failure) {
|
|
|
+ call.reject("无法确认分享或清理对应缓存,可使用同一 id 重试", "E_ACK_STORAGE");
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ @PluginMethod
|
|
|
+ public void prepareOutgoing(PluginCall call) {
|
|
|
+ String url = call.getString("url");
|
|
|
+ String name = call.getString("name");
|
|
|
+ WORKER.execute(() -> {
|
|
|
+ try {
|
|
|
+ File file = getStore(getContext()).download(url, name);
|
|
|
+ call.resolve(new JSObject().put("path", Uri.fromFile(file).toString()));
|
|
|
+ } catch (ShareFailure failure) {
|
|
|
+ call.reject(failure.getMessage(), failure.code);
|
|
|
+ } catch (SocketTimeoutException failure) {
|
|
|
+ call.reject("下载超时", "E_DOWNLOAD_TIMEOUT");
|
|
|
+ } catch (Exception failure) {
|
|
|
+ call.reject("下载失败,临时文件已清理", "E_DOWNLOAD_IO");
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ private static ShareStore getStore(Context context) throws IOException, JSONException {
|
|
|
+ synchronized (LOCK) {
|
|
|
+ if (store == null) store = new ShareStore(context.getApplicationContext());
|
|
|
+ return store;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static void publish(ShareStore current, String id) {
|
|
|
+ NativeSharePlugin target = instance;
|
|
|
+ if (target == null || !target.hasListeners(EVENT)) return;
|
|
|
+ JSObject share = current.share(id);
|
|
|
+ if (share != null) target.notifyListeners(EVENT, new JSObject().put("share", share));
|
|
|
+ }
|
|
|
+
|
|
|
+ static boolean validId(String id) {
|
|
|
+ return id != null && id.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
|
|
|
+ }
|
|
|
+
|
|
|
+ static URL checkedUrl(String value) throws ShareFailure {
|
|
|
+ try {
|
|
|
+ if (value == null || value.length() > 16384) throw new IllegalArgumentException();
|
|
|
+ URI parsed = new URI(value);
|
|
|
+ String host = parsed.getHost();
|
|
|
+ if (!"https".equalsIgnoreCase(parsed.getScheme()) || parsed.getRawUserInfo() != null
|
|
|
+ || (parsed.getPort() != -1 && parsed.getPort() != 443) || parsed.getRawFragment() != null
|
|
|
+ || host == null || !Arrays.asList("s3.fmode.cn", "matrix.fmode.cn", "server.fmode.cn")
|
|
|
+ .contains(host.toLowerCase(Locale.ROOT))) {
|
|
|
+ throw new IllegalArgumentException();
|
|
|
+ }
|
|
|
+ return parsed.toURL();
|
|
|
+ } catch (Exception failure) {
|
|
|
+ throw new ShareFailure("E_URL_NOT_ALLOWED", "仅允许 HTTPS 项目白名单域名,禁止用户凭证、非标准端口及跨域重定向");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ static String sanitizeName(String input) {
|
|
|
+ String value = input == null ? "" : input;
|
|
|
+ int codePoints = value.codePointCount(0, value.length());
|
|
|
+ if (codePoints > 180) value = value.substring(0, value.offsetByCodePoints(0, 180));
|
|
|
+ value = value.replaceAll("[\\p{Cntrl}\\p{Cf}<>:\"/\\\\|?*]", "_");
|
|
|
+ value = value.replaceAll("^[.\\s]+|[.\\s]+$", "");
|
|
|
+ if (value.isEmpty()) value = "shared-file";
|
|
|
+ while (value.getBytes(StandardCharsets.UTF_8).length > 180) {
|
|
|
+ value = value.substring(0, value.offsetByCodePoints(value.length(), -1));
|
|
|
+ }
|
|
|
+ return value;
|
|
|
+ }
|
|
|
+
|
|
|
+ static String completeMime(String supplied, String name) {
|
|
|
+ String value = supplied == null ? "" : supplied.split(";", 2)[0].trim().toLowerCase(Locale.ROOT);
|
|
|
+ if (value.matches("[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+")
|
|
|
+ && !"application/octet-stream".equals(value) && !"binary/octet-stream".equals(value)) return value;
|
|
|
+ int separator = name.lastIndexOf('.');
|
|
|
+ String extension = separator >= 0 ? name.substring(separator + 1).toLowerCase(Locale.ROOT) : "";
|
|
|
+ String inferred = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
|
|
|
+ if (inferred != null) return inferred;
|
|
|
+ switch (extension) {
|
|
|
+ case "md": return "text/markdown";
|
|
|
+ case "csv": return "text/csv";
|
|
|
+ case "json": return "application/json";
|
|
|
+ case "heic": return "image/heic";
|
|
|
+ case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
|
|
+ case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
|
|
+ case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
|
|
|
+ default: return "application/octet-stream";
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ static String completeName(String name, String mime) {
|
|
|
+ String safe = sanitizeName(name);
|
|
|
+ if (!safe.contains(".")) {
|
|
|
+ String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime);
|
|
|
+ if (extension != null && extension.matches("[A-Za-z0-9]{1,12}")) safe += "." + extension;
|
|
|
+ }
|
|
|
+ return safe;
|
|
|
+ }
|
|
|
+
|
|
|
+ static long copyBounded(InputStream input, OutputStream output, long limit, long deadline) throws IOException {
|
|
|
+ byte[] buffer = new byte[64 * 1024];
|
|
|
+ long copied = 0;
|
|
|
+ while (true) {
|
|
|
+ if (SystemClock.elapsedRealtime() >= deadline) throw new ShareFailure("E_TRANSFER_TIMEOUT", "文件传输超时");
|
|
|
+ int count = input.read(buffer);
|
|
|
+ if (count == -1) return copied;
|
|
|
+ if (count == 0) continue;
|
|
|
+ if (count > limit - copied) {
|
|
|
+ if (limit < MAX_FILE_BYTES) throw new ShareFailure("E_CACHE_LIMIT", "分享缓存总量或可用空间不足");
|
|
|
+ throw new ShareFailure("E_FILE_TOO_LARGE", "单文件实际数据超过 800 MiB");
|
|
|
+ }
|
|
|
+ output.write(buffer, 0, count);
|
|
|
+ copied += count;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ static final class ShareFailure extends IOException {
|
|
|
+ final String code;
|
|
|
+
|
|
|
+ ShareFailure(String code, String message) {
|
|
|
+ super(code + ": " + message);
|
|
|
+ this.code = code;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ static final class Incoming {
|
|
|
+ final String id;
|
|
|
+ final List<Uri> uris;
|
|
|
+
|
|
|
+ Incoming(String id, List<Uri> uris) {
|
|
|
+ this.id = id;
|
|
|
+ this.uris = uris;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ interface ConnectionFactory {
|
|
|
+ HttpsURLConnection open(URL url) throws IOException;
|
|
|
+ }
|
|
|
+
|
|
|
+ static final class DownloadCookies extends CookieHandler {
|
|
|
+ private final CookieHandler previous;
|
|
|
+ private final Thread owner = Thread.currentThread();
|
|
|
+
|
|
|
+ DownloadCookies(CookieHandler previous) {
|
|
|
+ this.previous = previous;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public Map<String, List<String>> get(URI uri, Map<String, List<String>> headers) throws IOException {
|
|
|
+ return Thread.currentThread() == owner || previous == null ? Collections.emptyMap() : previous.get(uri, headers);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void put(URI uri, Map<String, List<String>> headers) throws IOException {
|
|
|
+ if (Thread.currentThread() != owner && previous != null) previous.put(uri, headers);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ static final class ShareStore {
|
|
|
+ private final Context context;
|
|
|
+ private final File journal;
|
|
|
+ private final File incomingRoot;
|
|
|
+ private final File outgoingRoot;
|
|
|
+ private final byte[] receiptKey;
|
|
|
+ private final ConnectionFactory connections;
|
|
|
+ private final Map<String, JSObject> records = new LinkedHashMap<>();
|
|
|
+
|
|
|
+ ShareStore(Context context) throws IOException, JSONException {
|
|
|
+ this(context, url -> (HttpsURLConnection) url.openConnection());
|
|
|
+ }
|
|
|
+
|
|
|
+ ShareStore(Context context, ConnectionFactory connections) throws IOException, JSONException {
|
|
|
+ this.context = context;
|
|
|
+ this.connections = connections;
|
|
|
+ journal = directory(new File(context.getNoBackupFilesDir(), "native-share-queue"));
|
|
|
+ incomingRoot = directory(new File(context.getCacheDir(), "shared-incoming"));
|
|
|
+ outgoingRoot = directory(new File(context.getCacheDir(), "shared-outgoing"));
|
|
|
+ AtomicFile keyFile = new AtomicFile(new File(journal, "receipt.key"));
|
|
|
+ if (keyFile.getBaseFile().exists() || new File(journal, "receipt.key.bak").exists()) {
|
|
|
+ receiptKey = readAtomic(keyFile, 64);
|
|
|
+ if (receiptKey.length != 32) throw new IOException("Invalid receipt key");
|
|
|
+ } else {
|
|
|
+ receiptKey = new byte[32];
|
|
|
+ new SecureRandom().nextBytes(receiptKey);
|
|
|
+ writeAtomic(keyFile, receiptKey);
|
|
|
+ }
|
|
|
+ restore();
|
|
|
+ }
|
|
|
+
|
|
|
+ synchronized Incoming accept(Intent intent) throws IOException {
|
|
|
+ try {
|
|
|
+ String oldId = intent.getStringExtra(RECEIPT_ID);
|
|
|
+ String oldMac = intent.getStringExtra(RECEIPT_MAC);
|
|
|
+ if (validId(oldId) && oldMac != null && MessageDigest.isEqual(
|
|
|
+ receipt(oldId).getBytes(StandardCharsets.UTF_8), oldMac.getBytes(StandardCharsets.UTF_8))) return null;
|
|
|
+ } catch (RuntimeException ignored) {
|
|
|
+ }
|
|
|
+ String id = UUID.randomUUID().toString();
|
|
|
+ JSObject record = new JSObject().put("id", id).put("state", "copying")
|
|
|
+ .put("createdAt", System.currentTimeMillis()).put("files", new JSONArray());
|
|
|
+ LinkedHashSet<Uri> uris = new LinkedHashSet<>();
|
|
|
+ try {
|
|
|
+ readText(intent, Intent.EXTRA_TEXT, "text", 32768, record);
|
|
|
+ readText(intent, Intent.EXTRA_SUBJECT, "title", 2048, record);
|
|
|
+ Object streams = intent.getExtras() == null ? null : intent.getExtras().get(Intent.EXTRA_STREAM);
|
|
|
+ if (streams instanceof ArrayList<?>) {
|
|
|
+ List<?> values = (ArrayList<?>) streams;
|
|
|
+ int count = Math.min(values.size(), 256);
|
|
|
+ for (int index = 0; index < count; index++) addUri(values.get(index), uris, record);
|
|
|
+ if (values.size() > count) error(record, "E_TOO_MANY_FILES: 超出分享附件数量限制");
|
|
|
+ } else if (streams != null) {
|
|
|
+ addUri(streams, uris, record);
|
|
|
+ }
|
|
|
+ ClipData clip = intent.getClipData();
|
|
|
+ if (clip != null) {
|
|
|
+ int count = Math.min(clip.getItemCount(), 256);
|
|
|
+ for (int index = 0; index < count; index++) {
|
|
|
+ Uri uri = clip.getItemAt(index).getUri();
|
|
|
+ if (uri != null) addUri(uri, uris, record);
|
|
|
+ }
|
|
|
+ if (clip.getItemCount() > count) error(record, "E_TOO_MANY_FILES: 超出分享附件数量限制");
|
|
|
+ }
|
|
|
+ } catch (RuntimeException failure) {
|
|
|
+ error(record, "E_INVALID_SHARE: 无法读取分享 Intent 中的部分数据");
|
|
|
+ }
|
|
|
+ if (uris.isEmpty() && !record.has("text") && !record.has("title") && !record.has("errors")) {
|
|
|
+ error(record, "E_EMPTY_SHARE: 分享不包含可读取的附件或文本");
|
|
|
+ }
|
|
|
+ save(record);
|
|
|
+ records.put(id, record);
|
|
|
+ intent.putExtra(RECEIPT_ID, id);
|
|
|
+ intent.putExtra(RECEIPT_MAC, receipt(id));
|
|
|
+ return new Incoming(id, new ArrayList<>(uris));
|
|
|
+ }
|
|
|
+
|
|
|
+ private void readText(Intent intent, String extra, String field, int maximum, JSObject record) {
|
|
|
+ CharSequence value = intent.getCharSequenceExtra(extra);
|
|
|
+ if (value == null) return;
|
|
|
+ int length = Math.min(value.length(), maximum);
|
|
|
+ record.put(field, value.subSequence(0, length).toString());
|
|
|
+ if (value.length() > maximum) error(record, "E_TEXT_TRUNCATED: 分享文本超过长度限制,已截断");
|
|
|
+ }
|
|
|
+
|
|
|
+ private void addUri(Object value, Set<Uri> uris, JSObject record) {
|
|
|
+ if (!(value instanceof Uri)) {
|
|
|
+ error(record, "E_INVALID_STREAM: 附件必须是 content URI");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ Uri uri = ((Uri) value).normalizeScheme();
|
|
|
+ if (!"content".equals(uri.getScheme()) || uri.getAuthority() == null || uri.getAuthority().isEmpty()) {
|
|
|
+ error(record, "E_URI_SCHEME: 只接受 content:// 附件");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (uris.contains(uri)) return;
|
|
|
+ if (uris.size() >= MAX_FILES_PER_SHARE) {
|
|
|
+ error(record, "E_TOO_MANY_FILES: 每次最多接收 32 个附件");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ uris.add(uri);
|
|
|
+ }
|
|
|
+
|
|
|
+ void copyIncoming(Incoming incoming) {
|
|
|
+ JSObject record;
|
|
|
+ synchronized (this) {
|
|
|
+ record = records.get(incoming.id);
|
|
|
+ }
|
|
|
+ if (record == null) return;
|
|
|
+ try {
|
|
|
+ maintain();
|
|
|
+ File destination = incoming.uris.isEmpty() ? null : directory(child(incomingRoot, incoming.id));
|
|
|
+ int index = 0;
|
|
|
+ for (Uri uri : incoming.uris) {
|
|
|
+ index++;
|
|
|
+ try {
|
|
|
+ copyUri(uri, destination, index, record);
|
|
|
+ } catch (Exception failure) {
|
|
|
+ error(record, "附件 " + index + " " + incomingError(failure));
|
|
|
+ record.remove("pendingFile");
|
|
|
+ save(record);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (Exception failure) {
|
|
|
+ error(record, incomingError(failure));
|
|
|
+ } finally {
|
|
|
+ synchronized (this) {
|
|
|
+ record.put("state", "ready");
|
|
|
+ try {
|
|
|
+ save(record);
|
|
|
+ } catch (IOException failure) {
|
|
|
+ error(record, "E_QUEUE_STORAGE: 完成状态写入失败,重启后将恢复为中断分享");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void copyUri(Uri uri, File destination, int index, JSObject record) throws IOException, JSONException {
|
|
|
+ ContentResolver resolver = context.getContentResolver();
|
|
|
+ String name = null;
|
|
|
+ long advertisedSize = -1;
|
|
|
+ try (Cursor cursor = resolver.query(uri, new String[] {OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE}, null, null, null)) {
|
|
|
+ if (cursor != null && cursor.moveToFirst()) {
|
|
|
+ int nameColumn = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
|
|
|
+ int sizeColumn = cursor.getColumnIndex(OpenableColumns.SIZE);
|
|
|
+ if (nameColumn >= 0 && !cursor.isNull(nameColumn)) name = cursor.getString(nameColumn);
|
|
|
+ if (sizeColumn >= 0 && !cursor.isNull(sizeColumn)) advertisedSize = cursor.getLong(sizeColumn);
|
|
|
+ }
|
|
|
+ } catch (SecurityException failure) {
|
|
|
+ throw failure;
|
|
|
+ } catch (RuntimeException failure) {
|
|
|
+ error(record, "附件 " + index + " E_METADATA: 无法读取附件名称或声明大小,尝试读取数据流");
|
|
|
+ }
|
|
|
+ if (advertisedSize > MAX_FILE_BYTES) throw new ShareFailure("E_FILE_TOO_LARGE", "附件声明大小超过 800 MiB");
|
|
|
+ if (name == null || name.trim().isEmpty()) name = "shared-file-" + index;
|
|
|
+ name = sanitizeName(name);
|
|
|
+ String suppliedMime = null;
|
|
|
+ try {
|
|
|
+ suppliedMime = resolver.getType(uri);
|
|
|
+ } catch (RuntimeException failure) {
|
|
|
+ error(record, "附件 " + index + " E_MIME: 无法读取附件类型,使用扩展名推断");
|
|
|
+ }
|
|
|
+ String mime = completeMime(suppliedMime, name);
|
|
|
+ name = completeName(name, mime);
|
|
|
+ File target = child(destination, String.format(Locale.ROOT, "%03d-%s", index, name));
|
|
|
+ File partial = child(destination, target.getName() + ".part");
|
|
|
+ long allowance = allowance(false);
|
|
|
+ if (advertisedSize > allowance) throw new ShareFailure("E_CACHE_LIMIT", "附件超出剩余缓存空间");
|
|
|
+ JSObject metadata = new JSObject().put("path", Uri.fromFile(target).toString())
|
|
|
+ .put("name", name).put("mimeType", mime).put("size", 0L);
|
|
|
+ record.put("pendingFile", metadata);
|
|
|
+ save(record);
|
|
|
+ boolean committed = false;
|
|
|
+ try {
|
|
|
+ InputStream opened = resolver.openInputStream(uri);
|
|
|
+ if (opened == null) throw new FileNotFoundException();
|
|
|
+ try (InputStream input = opened; FileOutputStream output = new FileOutputStream(partial)) {
|
|
|
+ ScheduledFuture<?> timeout = TIMER.schedule(() -> closeQuietly(input), TRANSFER_TIMEOUT_MS, TimeUnit.MILLISECONDS);
|
|
|
+ try {
|
|
|
+ long size = copyBounded(input, output, allowance, SystemClock.elapsedRealtime() + TRANSFER_TIMEOUT_MS);
|
|
|
+ output.getFD().sync();
|
|
|
+ metadata.put("size", size);
|
|
|
+ } finally {
|
|
|
+ timeout.cancel(false);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (!partial.renameTo(target)) throw new IOException("Cannot commit incoming file");
|
|
|
+ committed = true;
|
|
|
+ record.getJSONArray("files").put(metadata);
|
|
|
+ record.remove("pendingFile");
|
|
|
+ save(record);
|
|
|
+ } finally {
|
|
|
+ if (!committed) removeTree(incomingRoot, partial);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ synchronized JSONArray pending() throws JSONException {
|
|
|
+ JSONArray result = new JSONArray();
|
|
|
+ for (JSObject record : records.values()) {
|
|
|
+ if ("ready".equals(record.optString("state"))) result.put(external(record));
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ synchronized JSObject share(String id) {
|
|
|
+ JSObject record = records.get(id);
|
|
|
+ return record != null && "ready".equals(record.optString("state")) ? external(record) : null;
|
|
|
+ }
|
|
|
+
|
|
|
+ private JSObject external(JSObject record) {
|
|
|
+ JSObject result = new JSObject().put("id", record.optString("id"));
|
|
|
+ if (record.has("text")) result.put("text", record.optString("text"));
|
|
|
+ if (record.has("title")) result.put("title", record.optString("title"));
|
|
|
+ try {
|
|
|
+ result.put("files", new JSONArray(record.getJSONArray("files").toString()));
|
|
|
+ if (record.has("errors")) result.put("errors", new JSONArray(record.getJSONArray("errors").toString()));
|
|
|
+ } catch (JSONException failure) {
|
|
|
+ result.put("files", new JSONArray()).put("errors", new JSONArray().put("E_QUEUE_CORRUPT: 分享元数据损坏"));
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ synchronized void acknowledge(String id) throws IOException {
|
|
|
+ JSObject record = records.get(id);
|
|
|
+ if (record != null) {
|
|
|
+ JSObject tombstone = new JSObject().put("id", id).put("state", "acked").put("files", new JSONArray());
|
|
|
+ save(tombstone);
|
|
|
+ records.remove(id);
|
|
|
+ }
|
|
|
+ removeTree(incomingRoot, child(incomingRoot, id));
|
|
|
+ atomic(id).delete();
|
|
|
+ }
|
|
|
+
|
|
|
+ synchronized void maintain() throws IOException, JSONException {
|
|
|
+ long now = System.currentTimeMillis();
|
|
|
+ for (JSObject record : records.values()) {
|
|
|
+ if (!"ready".equals(record.optString("state"))) continue;
|
|
|
+ JSONArray files = record.getJSONArray("files");
|
|
|
+ JSONArray kept = new JSONArray();
|
|
|
+ boolean expired = now - record.optLong("createdAt", 0) >= CACHE_TTL_MS;
|
|
|
+ for (int index = 0; index < files.length(); index++) {
|
|
|
+ JSONObject metadata = files.getJSONObject(index);
|
|
|
+ File file = localFile(metadata, incomingRoot, record.getString("id"));
|
|
|
+ if (expired || file == null || !file.isFile() || file.length() != metadata.optLong("size", -1)) {
|
|
|
+ error(record, expired ? "E_CACHE_EXPIRED: 分享附件缓存已超过 24 小时,文本和错误记录保留至确认"
|
|
|
+ : "E_CACHE_MISSING: 分享附件缓存丢失或不完整,请重新分享");
|
|
|
+ } else {
|
|
|
+ kept.put(metadata);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (kept.length() != files.length()) {
|
|
|
+ record.put("files", kept);
|
|
|
+ save(record);
|
|
|
+ }
|
|
|
+ if (expired) removeTree(incomingRoot, child(incomingRoot, record.getString("id")));
|
|
|
+ }
|
|
|
+ cleanOrphans(incomingRoot, now, true);
|
|
|
+ cleanOrphans(outgoingRoot, now, false);
|
|
|
+ }
|
|
|
+
|
|
|
+ private void cleanOrphans(File root, long now, boolean incoming) throws IOException {
|
|
|
+ for (File directory : children(root)) {
|
|
|
+ if (!validId(directory.getName())) continue;
|
|
|
+ if (incoming && records.containsKey(directory.getName())) continue;
|
|
|
+ if (now - directory.lastModified() >= CACHE_TTL_MS) removeTree(root, directory);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void restore() throws IOException, JSONException {
|
|
|
+ Set<String> ids = new HashSet<>();
|
|
|
+ for (File file : children(journal)) {
|
|
|
+ String base = file.getName().replaceFirst("\\.json(?:\\.bak|\\.new)?$", "");
|
|
|
+ if (validId(base)) ids.add(base);
|
|
|
+ }
|
|
|
+ List<JSObject> restored = new ArrayList<>();
|
|
|
+ for (String id : ids) {
|
|
|
+ JSObject record;
|
|
|
+ try {
|
|
|
+ record = new JSObject(new String(readAtomic(atomic(id), 512 * 1024), StandardCharsets.UTF_8));
|
|
|
+ if (!id.equals(record.getString("id")) || record.optJSONArray("files") == null) throw new JSONException("Invalid record");
|
|
|
+ } catch (JSONException failure) {
|
|
|
+ record = new JSObject().put("id", id).put("state", "ready").put("createdAt", System.currentTimeMillis())
|
|
|
+ .put("files", new JSONArray());
|
|
|
+ error(record, "E_QUEUE_CORRUPT: 分享元数据损坏,原记录未被静默丢弃");
|
|
|
+ save(record);
|
|
|
+ } catch (FileNotFoundException failure) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if ("acked".equals(record.optString("state"))) {
|
|
|
+ removeTree(incomingRoot, child(incomingRoot, id));
|
|
|
+ atomic(id).delete();
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (!"ready".equals(record.optString("state"))) {
|
|
|
+ JSONObject pending = record.optJSONObject("pendingFile");
|
|
|
+ if (pending != null) {
|
|
|
+ File committed = localFile(pending, incomingRoot, id);
|
|
|
+ if (committed != null && committed.isFile()) {
|
|
|
+ pending.put("size", committed.length());
|
|
|
+ record.getJSONArray("files").put(pending);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ record.remove("pendingFile");
|
|
|
+ error(record, "E_COPY_INTERRUPTED: 上次接收被进程退出中断,已完成附件保留,未完成附件请重新分享");
|
|
|
+ record.put("state", "ready");
|
|
|
+ save(record);
|
|
|
+ }
|
|
|
+ File shareDirectory = child(incomingRoot, id);
|
|
|
+ for (File file : children(shareDirectory)) {
|
|
|
+ if (file.getName().endsWith(".part")) removeTree(incomingRoot, file);
|
|
|
+ }
|
|
|
+ restored.add(record);
|
|
|
+ }
|
|
|
+ restored.sort(Comparator.comparingLong(record -> record.optLong("createdAt", 0)));
|
|
|
+ for (JSObject record : restored) records.put(record.getString("id"), record);
|
|
|
+ for (File outgoing : children(outgoingRoot)) {
|
|
|
+ if (!validId(outgoing.getName())) continue;
|
|
|
+ for (File file : children(outgoing)) {
|
|
|
+ if (file.getName().endsWith(".part")) {
|
|
|
+ removeTree(outgoingRoot, outgoing);
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ maintain();
|
|
|
+ }
|
|
|
+
|
|
|
+ File download(String value, String requestedName) throws IOException, JSONException {
|
|
|
+ URL url = checkedUrl(value);
|
|
|
+ maintain();
|
|
|
+ File destination = directory(child(outgoingRoot, UUID.randomUUID().toString()));
|
|
|
+ boolean complete = false;
|
|
|
+ long deadline = SystemClock.elapsedRealtime() + TRANSFER_TIMEOUT_MS;
|
|
|
+ DownloadCookies cookies;
|
|
|
+ synchronized (CookieHandler.class) {
|
|
|
+ cookies = new DownloadCookies(CookieHandler.getDefault());
|
|
|
+ CookieHandler.setDefault(cookies);
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ for (int redirects = 0; redirects <= 5; redirects++) {
|
|
|
+ if (SystemClock.elapsedRealtime() >= deadline) throw new ShareFailure("E_DOWNLOAD_TIMEOUT", "下载超时");
|
|
|
+ HttpsURLConnection connection = connections.open(url);
|
|
|
+ connection.setInstanceFollowRedirects(false);
|
|
|
+ connection.setUseCaches(false);
|
|
|
+ connection.setAllowUserInteraction(false);
|
|
|
+ connection.setConnectTimeout(20000);
|
|
|
+ connection.setReadTimeout(20000);
|
|
|
+ connection.setRequestProperty("Accept-Encoding", "identity");
|
|
|
+ connection.setRequestProperty("Cookie", "");
|
|
|
+ connection.setRequestProperty("Authorization", "");
|
|
|
+ ScheduledFuture<?> timeout = TIMER.schedule(connection::disconnect,
|
|
|
+ Math.max(1, deadline - SystemClock.elapsedRealtime()), TimeUnit.MILLISECONDS);
|
|
|
+ try {
|
|
|
+ int status = connection.getResponseCode();
|
|
|
+ if (status == 301 || status == 302 || status == 303 || status == 307 || status == 308) {
|
|
|
+ String location = connection.getHeaderField("Location");
|
|
|
+ if (location == null || redirects == 5) throw new ShareFailure("E_REDIRECT_LIMIT", "下载重定向无效或次数过多");
|
|
|
+ url = checkedUrl(new URL(url, location).toExternalForm());
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (status != HttpURLConnection.HTTP_OK) throw new ShareFailure("E_HTTP_STATUS", "下载服务器返回 HTTP " + status);
|
|
|
+ long advertisedSize = connection.getContentLengthLong();
|
|
|
+ if (advertisedSize > MAX_FILE_BYTES) throw new ShareFailure("E_FILE_TOO_LARGE", "下载文件超过 800 MiB");
|
|
|
+ long allowance = allowance(true);
|
|
|
+ if (advertisedSize > allowance) throw new ShareFailure("E_CACHE_LIMIT", "下载文件超出剩余缓存空间");
|
|
|
+ String suggested = requestedName == null || requestedName.trim().isEmpty()
|
|
|
+ ? Uri.parse(url.toExternalForm()).getLastPathSegment() : requestedName;
|
|
|
+ String mime = completeMime(connection.getContentType(), sanitizeName(suggested));
|
|
|
+ File target = child(destination, completeName(suggested, mime));
|
|
|
+ File partial = child(destination, target.getName() + ".part");
|
|
|
+ long copied;
|
|
|
+ try (InputStream input = connection.getInputStream(); FileOutputStream output = new FileOutputStream(partial)) {
|
|
|
+ copied = copyBounded(input, output, allowance, deadline);
|
|
|
+ output.getFD().sync();
|
|
|
+ }
|
|
|
+ if (advertisedSize >= 0 && advertisedSize != copied) throw new ShareFailure("E_DOWNLOAD_INCOMPLETE", "下载长度与服务器声明不一致");
|
|
|
+ if (!partial.renameTo(target)) throw new IOException("Cannot commit outgoing file");
|
|
|
+ complete = true;
|
|
|
+ return target;
|
|
|
+ } finally {
|
|
|
+ timeout.cancel(false);
|
|
|
+ connection.disconnect();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ throw new ShareFailure("E_REDIRECT_LIMIT", "下载重定向次数过多");
|
|
|
+ } finally {
|
|
|
+ synchronized (CookieHandler.class) {
|
|
|
+ if (CookieHandler.getDefault() == cookies) CookieHandler.setDefault(cookies.previous);
|
|
|
+ }
|
|
|
+ if (!complete) removeTree(outgoingRoot, destination);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private long allowance(boolean outgoing) throws IOException {
|
|
|
+ long[] incomingUsage = usage(incomingRoot);
|
|
|
+ long[] outgoingUsage = usage(outgoingRoot);
|
|
|
+ if (incomingUsage[1] + outgoingUsage[1] >= MAX_CACHED_FILES
|
|
|
+ || (outgoing && outgoingUsage[1] >= MAX_OUTGOING_FILES)) {
|
|
|
+ throw new ShareFailure("E_CACHE_COUNT", "分享缓存附件数量已达上限,请确认已处理分享或等待缓存过期");
|
|
|
+ }
|
|
|
+ long remaining = MAX_CACHE_BYTES - incomingUsage[0] - outgoingUsage[0];
|
|
|
+ long disk = context.getCacheDir().getUsableSpace() - 32L * 1024 * 1024;
|
|
|
+ long allowance = Math.min(MAX_FILE_BYTES, Math.min(remaining, disk));
|
|
|
+ if (allowance <= 0) throw new ShareFailure("E_CACHE_LIMIT", "分享缓存达到 2 GiB 上限或磁盘剩余空间不足");
|
|
|
+ return allowance;
|
|
|
+ }
|
|
|
+
|
|
|
+ private long[] usage(File root) throws IOException {
|
|
|
+ long bytes = 0;
|
|
|
+ long count = 0;
|
|
|
+ for (File directory : children(root)) {
|
|
|
+ if (!validId(directory.getName())) continue;
|
|
|
+ for (File file : children(directory)) {
|
|
|
+ if (contained(root, file) && file.isFile()) {
|
|
|
+ bytes += file.length();
|
|
|
+ count++;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return new long[] {bytes, count};
|
|
|
+ }
|
|
|
+
|
|
|
+ private String receipt(String id) throws IOException {
|
|
|
+ try {
|
|
|
+ Mac mac = Mac.getInstance("HmacSHA256");
|
|
|
+ mac.init(new SecretKeySpec(receiptKey, "HmacSHA256"));
|
|
|
+ return Base64.encodeToString(mac.doFinal(id.getBytes(StandardCharsets.UTF_8)), Base64.NO_WRAP | Base64.URL_SAFE);
|
|
|
+ } catch (Exception failure) {
|
|
|
+ throw new IOException("Cannot create receipt");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private AtomicFile atomic(String id) throws IOException {
|
|
|
+ return new AtomicFile(child(journal, id + ".json"));
|
|
|
+ }
|
|
|
+
|
|
|
+ private void save(JSObject record) throws IOException {
|
|
|
+ writeAtomic(atomic(record.optString("id")), record.toString().getBytes(StandardCharsets.UTF_8));
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String incomingError(Exception failure) {
|
|
|
+ if (failure instanceof ShareFailure) return failure.getMessage();
|
|
|
+ if (failure instanceof SecurityException) return "E_URI_PERMISSION: 无临时读取授权或授权已失效,请从来源应用重新分享";
|
|
|
+ if (failure instanceof FileNotFoundException) return "E_URI_NOT_FOUND: 来源附件不存在或不可读取";
|
|
|
+ if (failure instanceof SocketTimeoutException) return "E_TRANSFER_TIMEOUT: 读取附件超时";
|
|
|
+ if (failure instanceof IOException) return "E_COPY_IO: 附件读取、缓存写入或队列持久化失败";
|
|
|
+ return "E_COPY_FAILED: 来源提供器返回异常或附件格式无效";
|
|
|
+ }
|
|
|
+
|
|
|
+ private static void error(JSObject record, String message) {
|
|
|
+ JSONArray errors = record.optJSONArray("errors");
|
|
|
+ if (errors == null) {
|
|
|
+ errors = new JSONArray();
|
|
|
+ record.put("errors", errors);
|
|
|
+ }
|
|
|
+ for (int index = 0; index < errors.length(); index++) {
|
|
|
+ if (message.equals(errors.optString(index))) return;
|
|
|
+ }
|
|
|
+ if (errors.length() < 128) errors.put(message);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static File directory(File file) throws IOException {
|
|
|
+ if (!file.isDirectory() && !file.mkdirs()) throw new IOException("Cannot create private share directory");
|
|
|
+ return file;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static File child(File parent, String name) throws IOException {
|
|
|
+ File result = new File(parent, name);
|
|
|
+ if (!result.getCanonicalFile().getParentFile().equals(parent.getCanonicalFile())) {
|
|
|
+ throw new IOException("Invalid share cache path");
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static boolean contained(File root, File target) throws IOException {
|
|
|
+ return target.getCanonicalPath().startsWith(root.getCanonicalPath() + File.separator);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static File localFile(JSONObject metadata, File root, String id) throws IOException {
|
|
|
+ try {
|
|
|
+ Uri uri = Uri.parse(metadata.optString("path", ""));
|
|
|
+ if (!"file".equals(uri.getScheme()) || uri.getPath() == null) return null;
|
|
|
+ File file = new File(uri.getPath());
|
|
|
+ File directory = child(root, id);
|
|
|
+ return file.getCanonicalFile().getParentFile().equals(directory.getCanonicalFile()) ? file : null;
|
|
|
+ } catch (RuntimeException failure) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static File[] children(File directory) throws IOException {
|
|
|
+ if (!directory.exists()) return new File[0];
|
|
|
+ File[] files = directory.listFiles();
|
|
|
+ if (files == null) throw new IOException("Cannot list share directory");
|
|
|
+ return files;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static void removeTree(File root, File target) throws IOException {
|
|
|
+ if (!target.exists()) return;
|
|
|
+ if (!contained(root, target)) throw new IOException("Refusing to delete outside private share directory");
|
|
|
+ if (target.isDirectory()) {
|
|
|
+ for (File child : children(target)) removeTree(root, child);
|
|
|
+ }
|
|
|
+ if (!target.delete()) throw new IOException("Cannot delete share cache");
|
|
|
+ }
|
|
|
+
|
|
|
+ private static byte[] readAtomic(AtomicFile file, int limit) throws IOException {
|
|
|
+ try (FileInputStream input = file.openRead(); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
|
|
|
+ byte[] buffer = new byte[4096];
|
|
|
+ int count;
|
|
|
+ while ((count = input.read(buffer)) != -1) {
|
|
|
+ if (count > limit - output.size()) throw new IOException("Share metadata exceeds limit");
|
|
|
+ output.write(buffer, 0, count);
|
|
|
+ }
|
|
|
+ return output.toByteArray();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static void writeAtomic(AtomicFile file, byte[] bytes) throws IOException {
|
|
|
+ FileOutputStream output = null;
|
|
|
+ try {
|
|
|
+ output = file.startWrite();
|
|
|
+ output.write(bytes);
|
|
|
+ output.getFD().sync();
|
|
|
+ file.finishWrite(output);
|
|
|
+ } catch (IOException failure) {
|
|
|
+ if (output != null) file.failWrite(output);
|
|
|
+ throw failure;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static void closeQuietly(InputStream input) {
|
|
|
+ try {
|
|
|
+ input.close();
|
|
|
+ } catch (IOException ignored) {
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|