From 60cadff951c0cc689151dd8d23f1d85949d722ca Mon Sep 17 00:00:00 2001 From: Timi Date: Wed, 18 Nov 2026 12:20:13 +0800 Subject: [PATCH] feat(system): write to system media for tack photo --- NATIVE_UPGRADE.md | 2 + .../com/imyeyu/gao/customer/MainActivity.java | 2 + .../customer/mediasaver/MediaSaverPlugin.java | 187 ++++++++++++++++++ android/variables.gradle | 2 +- .../attachmentSelector/AttachmentSelector.vue | 11 ++ src/pages/setting/AppSettings.vue | 7 + src/store/settingStore.ts | 11 ++ src/utils/mediaSaver.ts | 68 +++++++ 8 files changed, 289 insertions(+), 1 deletion(-) create mode 100644 android/app/src/main/java/com/imyeyu/gao/customer/mediasaver/MediaSaverPlugin.java create mode 100644 src/utils/mediaSaver.ts diff --git a/NATIVE_UPGRADE.md b/NATIVE_UPGRADE.md index e005e63..1005b79 100644 --- a/NATIVE_UPGRADE.md +++ b/NATIVE_UPGRADE.md @@ -40,6 +40,8 @@ grep versionCode android/app/build.gradle - 增删插件后执行 `pnpm exec cap sync android` - 确认 `capacitor.config.ts` 无遗漏 +- **`minSdkVersion` 已是 29(Android 10+)**:下一次发壳,Android 9 及以下的机器装不上, + 会永久停在旧版本。发之前先确认设备分布,别把一个还在用老系统的门店锁死 - **打壳前先 `pnpm run android:sync:prod` 重建资源**:它用 `.env.production` 构建并会清掉 残留的 `VITE_API_BASE_URL`。真机调试用的 `android:sync:dev`(或 `android:open`)会把局域网地址 写进 `dist` 和 `android/app/src/main/assets/public`,直接拿去打包就会打出一个连内网的正式包 diff --git a/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java b/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java index 8c7b4e3..f068a0d 100644 --- a/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java +++ b/android/app/src/main/java/com/imyeyu/gao/customer/MainActivity.java @@ -14,6 +14,7 @@ import androidx.core.view.ViewCompat; import androidx.core.view.WindowCompat; import androidx.core.view.WindowInsetsCompat; import com.getcapacitor.BridgeActivity; +import com.imyeyu.gao.customer.mediasaver.MediaSaverPlugin; import com.imyeyu.gao.customer.shellupdater.ShellUpdaterPlugin; import java.util.Locale; @@ -22,6 +23,7 @@ public class MainActivity extends BridgeActivity { @Override public void onCreate(Bundle savedInstanceState) { registerPlugin(ShellUpdaterPlugin.class); + registerPlugin(MediaSaverPlugin.class); super.onCreate(savedInstanceState); applyEdgeToEdge(); getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) { diff --git a/android/app/src/main/java/com/imyeyu/gao/customer/mediasaver/MediaSaverPlugin.java b/android/app/src/main/java/com/imyeyu/gao/customer/mediasaver/MediaSaverPlugin.java new file mode 100644 index 0000000..77df146 --- /dev/null +++ b/android/app/src/main/java/com/imyeyu/gao/customer/mediasaver/MediaSaverPlugin.java @@ -0,0 +1,187 @@ +package com.imyeyu.gao.customer.mediasaver; + +import android.content.ContentResolver; +import android.content.ContentValues; +import android.net.Uri; +import android.os.Environment; +import android.provider.MediaStore; +import android.util.Base64; +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.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/// 把网页里拍到的照片/视频写进系统相册 +/// +/// 走 MediaStore 的 IS_PENDING 流程,Android 10 起不需要任何存储权限。 +/// 分块接收是为了避免大视频在 JS 与原生之间一次性复制导致内存翻倍。 +@CapacitorPlugin(name = "MediaSaver") +public class MediaSaverPlugin extends Plugin { + + /// 单个文件上限,防止异常调用把手机存储写满 + private static final long MAX_BYTES = 512L * 1024 * 1024; + + private final ExecutorService executor = Executors.newSingleThreadExecutor(); + private final Map sessions = new ConcurrentHashMap<>(); + + private static class Session { + final File temp; + final String fileName; + final String mimeType; + final boolean video; + long size; + + Session(File temp, String fileName, String mimeType, boolean video) { + this.temp = temp; + this.fileName = fileName; + this.mimeType = mimeType; + this.video = video; + } + } + + /// 开始一次写入,返回后续分块要用的 id + @PluginMethod + public void begin(PluginCall call) { + String fileName = call.getString("fileName"); + String mimeType = call.getString("mimeType"); + String mediaType = call.getString("mediaType", "image"); + if (fileName == null || !fileName.matches("[\\w.\\-]{1,120}")) { + call.reject("文件名不合法"); + return; + } + if (mimeType == null || !mimeType.matches("(image|video)/[\\w.+-]+")) { + call.reject("媒体类型不合法"); + return; + } + File directory = new File(getContext().getCacheDir(), "media-save"); + if (!directory.exists() && !directory.mkdirs()) { + call.reject("无法创建缓存目录"); + return; + } + String id = UUID.randomUUID().toString(); + Session session = new Session(new File(directory, id + ".part"), fileName, mimeType, "video".equals(mediaType)); + sessions.put(id, session); + JSObject result = new JSObject(); + result.put("id", id); + call.resolve(result); + } + + /// 追加一块 base64 数据 + @PluginMethod + public void append(PluginCall call) { + String id = call.getString("id"); + String data = call.getString("data"); + Session session = id == null ? null : sessions.get(id); + if (session == null) { + call.reject("会话不存在"); + return; + } + if (data == null) { + call.reject("数据为空"); + return; + } + executor.execute(() -> { + try { + byte[] bytes = Base64.decode(data, Base64.DEFAULT); + if (MAX_BYTES < session.size + bytes.length) { + throw new IllegalStateException("文件超过大小上限"); + } + try (FileOutputStream output = new FileOutputStream(session.temp, true)) { + output.write(bytes); + } + session.size += bytes.length; + call.resolve(); + } catch (Exception e) { + sessions.remove(id); + session.temp.delete(); + call.reject("写入失败", e); + } + }); + } + + /// 收尾:把临时文件搬进相册,成功后清理临时文件 + @PluginMethod + public void finish(PluginCall call) { + String id = call.getString("id"); + Session session = id == null ? null : sessions.remove(id); + if (session == null) { + call.reject("会话不存在"); + return; + } + executor.execute(() -> { + Uri uri = null; + try { + ContentResolver resolver = getContext().getContentResolver(); + ContentValues values = new ContentValues(); + values.put(MediaStore.MediaColumns.DISPLAY_NAME, session.fileName); + values.put(MediaStore.MediaColumns.MIME_TYPE, session.mimeType); + values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/GaoCustomer"); + values.put(MediaStore.MediaColumns.IS_PENDING, 1); + Uri collection = session.video + ? MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) + : MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY); + uri = resolver.insert(collection, values); + if (uri == null) { + throw new IllegalStateException("无法创建相册条目"); + } + try (InputStream input = new FileInputStream(session.temp); OutputStream output = resolver.openOutputStream(uri)) { + if (output == null) { + throw new IllegalStateException("无法写入相册"); + } + byte[] buffer = new byte[32768]; + int size; + while ((size = input.read(buffer)) != -1) { + output.write(buffer, 0, size); + } + } + // 清掉 PENDING,相册 App 才会看到这个文件 + ContentValues done = new ContentValues(); + done.put(MediaStore.MediaColumns.IS_PENDING, 0); + resolver.update(uri, done, null, null); + session.temp.delete(); + call.resolve(); + } catch (Exception e) { + if (uri != null) { + try { + getContext().getContentResolver().delete(uri, null, null); + } catch (Exception ignored) { + // 清理失败不影响主流程 + } + } + session.temp.delete(); + call.reject("保存到相册失败", e); + } + }); + } + + /// 放弃本次写入 + @PluginMethod + public void cancel(PluginCall call) { + String id = call.getString("id"); + Session session = id == null ? null : sessions.remove(id); + if (session != null) { + session.temp.delete(); + } + call.resolve(); + } + + @Override + protected void handleOnDestroy() { + executor.shutdown(); + for (Session session : sessions.values()) { + session.temp.delete(); + } + sessions.clear(); + } +} diff --git a/android/variables.gradle b/android/variables.gradle index ee4ba41..147cb52 100644 --- a/android/variables.gradle +++ b/android/variables.gradle @@ -1,5 +1,5 @@ ext { - minSdkVersion = 24 + minSdkVersion = 29 compileSdkVersion = 36 targetSdkVersion = 36 androidxActivityVersion = '1.11.0' diff --git a/src/components/attachmentSelector/AttachmentSelector.vue b/src/components/attachmentSelector/AttachmentSelector.vue index 14019e0..b2adc07 100644 --- a/src/components/attachmentSelector/AttachmentSelector.vue +++ b/src/components/attachmentSelector/AttachmentSelector.vue @@ -53,6 +53,8 @@ import type { import type { PhotoItem } from "@/types/Photo.ts"; import { getAttachmentReadURL } from "@/utils/attachment.ts"; import { Message } from "@/utils/message.ts"; +import { saveToAlbum } from "@/utils/mediaSaver"; +import { useSettingStore } from "@/store/settingStore"; defineOptions({ inheritAttrs: false @@ -76,6 +78,8 @@ const props = withDefaults(defineProps(), { required: false }); +const settingStore = useSettingStore(); + const emit = defineEmits<{ "update:items": [items: PhotoItem[]]; select: [selection: AttachmentSelectorSelection]; @@ -88,6 +92,13 @@ const isBusy = computed(() => props.busy || isUploading.value); const attachmentItems = computed(() => props.items.map(toAttachmentSelectorItem)); async function handleSelect(selection: AttachmentSelectorSelection): Promise { + // 直接拍摄的媒体额外存一份到系统相册,可在「应用设置」里关掉;失败不阻塞上传 + if (settingStore.albumSave && selection.input.capture && selection.files.length) { + const mediaType: "image" | "video" = selection.input.accept.toLowerCase().includes("video") ? "video" : "image"; + for (const file of selection.files) { + void saveToAlbum(file, mediaType).catch(() => Message.warning("保存到系统相册失败")); + } + } if (!props.upload) { emit("select", selection); return; diff --git a/src/pages/setting/AppSettings.vue b/src/pages/setting/AppSettings.vue index 888e6fe..f9384be 100644 --- a/src/pages/setting/AppSettings.vue +++ b/src/pages/setting/AppSettings.vue @@ -25,6 +25,13 @@ + + + + +