feat(system): write to system media for tack photo

This commit is contained in:
Timi
2026-11-18 14:08:47 +08:00
parent 635192eae1
commit 60cadff951
8 changed files with 289 additions and 1 deletions
+2
View File
@@ -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`,直接拿去打包就会打出一个连内网的正式包
@@ -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) {
@@ -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<String, Session> 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();
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
ext {
minSdkVersion = 24
minSdkVersion = 29
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.11.0'
@@ -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<Props>(), {
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<void> {
// 直接拍摄的媒体额外存一份到系统相册,可在「应用设置」里关掉;失败不阻塞上传
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;
+7
View File
@@ -25,6 +25,13 @@
</template>
</t-cell>
</t-cell-group>
<t-cell-group title="照片" theme="card" v-entrance-transition>
<t-cell title="拍照后存入相册">
<template #right-icon>
<t-switch :model-value="settingStore.albumSave" @change="value => settingStore.setAlbumSave(value === true)" />
</template>
</t-cell>
</t-cell-group>
<t-cell-group title="声音" theme="card" v-entrance-transition>
<t-cell title="扫码成功">
<template #right-icon>
+11
View File
@@ -10,6 +10,7 @@ export interface SoundSetting {
type SoundType = "scanSuccess" | "registerSuccess";
const SOUND_STORAGE_KEY = "gao-customer-h5:sound";
const ALBUM_SAVE_STORAGE_KEY = "gao-customer-h5:album-save";
const soundUrlMap: Record<SoundType, string> = {
scanSuccess: scanSuccessSoundUrl,
registerSuccess: registrationSuccessSoundUrl
@@ -48,6 +49,8 @@ function readStoredSoundSetting(): SoundSetting {
export const useSettingStore = defineStore("setting", () => {
const sound = ref<SoundSetting>(readStoredSoundSetting());
/** 拍照后是否额外存一份到系统相册,默认开启 */
const albumSave = ref(localStorage.getItem(ALBUM_SAVE_STORAGE_KEY) !== "0");
const soundPlayerMap = shallowRef<Record<SoundType, HTMLAudioElement> | null>(null);
const audioContext = shallowRef<AudioContext | null>(null);
const scanSuccessBuffer = shallowRef<AudioBuffer | null>(null);
@@ -64,6 +67,12 @@ export const useSettingStore = defineStore("setting", () => {
applySoundVolume();
}
/** 开关相册副本,只影响后续拍摄,已保存的文件不动 */
function setAlbumSave(value: boolean): void {
albumSave.value = value;
localStorage.setItem(ALBUM_SAVE_STORAGE_KEY, value ? "1" : "0");
}
function loadSoundPlayers(): void {
if (soundPlayerMap.value) {
return;
@@ -223,7 +232,9 @@ export const useSettingStore = defineStore("setting", () => {
return {
sound,
albumSave,
setSound,
setAlbumSave,
loadSoundPlayers,
unlockSoundPlayers,
playScanSuccessSound,
+68
View File
@@ -0,0 +1,68 @@
import { Capacitor, registerPlugin } from "@capacitor/core";
interface MediaSaverPlugin {
begin(options: { fileName: string; mimeType: string; mediaType: "image" | "video" }): Promise<{ id: string }>;
append(options: { id: string; data: string }): Promise<void>;
finish(options: { id: string }): Promise<void>;
cancel(options: { id: string }): Promise<void>;
}
const MediaSaver = registerPlugin<MediaSaverPlugin>("MediaSaver");
/** 分块大小,base64 后约 683KB,避免把整个视频一次性塞进桥接调用 */
const CHUNK_SIZE = 512 * 1024;
/** 相册文件名只允许安全字符 */
const SAFE_NAME = /^[\w.-]{1,120}$/;
/** 当前外壳是否具备写相册的能力 */
export function supportsAlbumSave(): boolean {
return Capacitor.isPluginAvailable("MediaSaver");
}
/**
* 把直接拍摄得到的媒体写进系统相册
*
* 写的是 MediaStore 自己的记录,Android 10 起不需要存储权限。
* 失败由调用方决定怎么处理——相册保存是增强能力,绝不能影响上传。
*
* @param file 拍摄产物
* @param mediaType 媒体类型,决定落到 DCIM 还是视频集合
*/
export async function saveToAlbum(file: File, mediaType: "image" | "video"): Promise<void> {
if (!supportsAlbumSave() || !file.size) {
return;
}
const { id } = await MediaSaver.begin({
fileName: buildFileName(file, mediaType),
mimeType: file.type || (mediaType === "video" ? "video/mp4" : "image/jpeg"),
mediaType
});
try {
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
await MediaSaver.append({ id, data: toBase64(chunk) });
}
await MediaSaver.finish({ id });
} catch (error) {
await MediaSaver.cancel({ id }).catch(() => undefined);
throw error;
}
}
/** 生成相册里的显示名,拿不到可用原名时用时间戳兜底 */
function buildFileName(file: File, mediaType: "image" | "video"): string {
const suffix = mediaType === "video" ? "mp4" : "jpg";
const name = file.name && SAFE_NAME.test(file.name) ? file.name : `IMG_${Date.now()}.${suffix}`;
return name.includes(".") ? name : `${name}.${suffix}`;
}
/** ArrayBuffer 转 base64,分段拼接避免超长参数撑爆调用栈 */
function toBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let index = 0; index < bytes.length; index += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
}
return window.btoa(binary);
}