feat(android): Capacitor APK build + native save/share bridge

- android/ — Capacitor project (build/, local.properties ignored)
- app/js/native.js — bridge สำหรับ APK: savePhoto/saveZip/shareItems ผ่าน Filesystem+Share
- app/js/csv.js — นำเข้าโฟลเดอร์หลายรายการจาก CSV (site,letter,datetime,name)
- app/js/orient.js — จัดการ orientation ของ preview/กล้อง
- app/manual.html + APK.md — คู่มือใช้งานและวิธี build APK
- app/templates/folders-template.csv — เทมเพลต CSV
- package.json / package-lock.json / capacitor.config.json / scripts/build-apk.sh
- ปรับ ui, camera, exif, archive, db, naming, main, sw + css/README ตามงานข้างบน
This commit is contained in:
Bkk1234 committed 2026-11-20 08:50:42 +07:00
1 parent a0bccc2316
commit 6f146aef59
75 files changed
+4637 -151

No files matched your search

+80 -32
View File
@@ -1,5 +1,6 @@
// ── ZIP ทั้งโฟลเดอร์: สร้าง / ดาวน์โหลด / แชร์ผ่านระบบมือถือ ──
import { safeFileName, humanDateTime } from "./naming.js";
// ── ZIP: สร้าง / ดาวน์โหลด (ทุกโฟลเดอร์ หรือโฟลเดอร์เดียว) ──
// โครงสร้างใน ZIP: <ชื่อโฟลเดอร์>/<ชื่อไฟล์>.jpg → แตกไฟล์ออกมาเป็นโฟลเดอร์จริง
import { safeFileName, fileStamp } from "./naming.js";
const cache = { signature: "", file: null, fileName: "" };
@@ -11,49 +12,87 @@ function entryBase(folder) {
return safeFileName(folder.name).replace(/\s+/g, "_");
}
/** ชื่อโฟลเดอร์ภายใน zip — กันซ้ำและตัดอักขระที่ทำให้ path เพี้ยน */
function folderDirName(folder, used) {
const base = safeFileName(folder.name, "photos").replace(/[\\/]+/g, "-").replace(/\.+$/, "").trim() || "photos";
let dir = base;
let n = 2;
while (used.has(dir.toLowerCase())) dir = `${base} (${n++})`;
used.add(dir.toLowerCase());
return dir;
}
/** กันชื่อไฟล์ซ้ำภายในโฟลเดอร์เดียว (เช่นหลังเปลี่ยนชื่อโฟลเดอร์) */
function uniqueEntryName(name, usedNames) {
const clean = String(name || "photo.jpg").replace(/[\\/]+/g, "-");
let cand = clean;
let n = 2;
while (usedNames.has(cand.toLowerCase())) {
cand = clean.replace(/(\.[a-z0-9]+)?$/i, (ext) => `-${n++}${ext || ""}`);
}
usedNames.add(cand.toLowerCase());
return cand;
}
/**
* สร้าง ZIP ของ "ทุกรูปในโฟลเดอร์" + metadata.json
* ใช้ compression: STORE เพราะ JPEG บีบอัดต่อไม่ได้แล้ว (เร็วขึ้นมากบนมือถือ)
* ZIP ของโฟลเดอร์เดียว — ทุกรูปอยู่ในโฟลเดอร์ชื่อเดียวกับโฟลเดอร์
* compression STORE เพราะ JPEG บีบอัดต่อไม่ได้แล้ว
*/
export async function buildZip(folder, images, onProgress) {
if (!window.JSZip) throw new Error("JSZip not loaded");
const zip = new JSZip();
const base = entryBase(folder);
const photos = [];
const dir = folderDirName(folder, new Set());
const used = new Set();
zip.folder(dir);
images.forEach((img, idx) => {
const seq = String(idx + 1).padStart(4, "0");
const name = img.name || `${base}_${seq}.jpg`;
zip.file(name, img.blob);
photos.push({ file: name, ...(img.meta || {}) });
const fallback = `${entryBase(folder)}_${String(idx + 1).padStart(4, "0")}.jpg`;
zip.file(`${dir}/${uniqueEntryName(img.name || fallback, used)}`, img.blob);
});
zip.file(
"metadata.json",
JSON.stringify(
{
folder: folder.name,
count: images.length,
generated_at: new Date().toISOString(),
generated_at_th: humanDateTime(Date.now()),
app: "CamCat 2.0.0",
photos,
},
null,
2
)
);
const blob = await zip.generateAsync({ type: "blob", compression: "STORE" }, (m) => {
if (onProgress) onProgress(m.percent);
});
const fileName = safeFileName(folder.name, "photos") + ".zip";
const file = new File([blob], fileName, { type: "application/zip" });
return { blob, file, fileName };
return { blob, file, fileName, dir, photos: images.length };
}
/** ใช้ cache ถ้ารายการรูปไม่เปลี่ยน — ทำให้กดแชร์แล้วเปิด share sheet ได้ทันที */
/**
* ZIP รวมทุกโฟลเดอร์ในครั้งเดียว — แต่ละโฟลเดอร์เป็นโฟลเดอร์ย่อยของตัวเอง
* folders: [{id,name,...}] · imagesByFolder: { [folderId]: images[] }
*/
export async function buildAllZip(folders, imagesByFolder, onProgress) {
if (!window.JSZip) throw new Error("JSZip not loaded");
const zip = new JSZip();
const usedDirs = new Set();
let photos = 0;
let folderCount = 0;
folders.forEach((folder) => {
const images = imagesByFolder[folder.id] || [];
const dir = folderDirName(folder, usedDirs);
zip.folder(dir); // สร้างโฟลเดอร์แม้ยังไม่มีรูป
folderCount++;
const used = new Set();
images.forEach((img, idx) => {
const fallback = `${entryBase(folder)}_${String(idx + 1).padStart(4, "0")}.jpg`;
zip.file(`${dir}/${uniqueEntryName(img.name || fallback, used)}`, img.blob);
photos++;
});
});
const blob = await zip.generateAsync({ type: "blob", compression: "STORE" }, (m) => {
if (onProgress) onProgress(m.percent);
});
const fileName = `CamCat-all-${fileStamp()}.zip`;
const file = new File([blob], fileName, { type: "application/zip" });
return { blob, file, fileName, folders: folderCount, photos };
}
/** ใช้ cache ถ้ารายการรูปไม่เปลี่ยน */
export async function ensureZip(folder, images, onProgress, { force = false } = {}) {
const sig = signatureOf(folder, images);
if (!force && cache.file && cache.signature === sig) return cache;
@@ -65,6 +104,14 @@ export async function ensureZip(folder, images, onProgress, { force = false } =
return cache;
}
/** คืน File ที่สร้างไว้แล้วถ้ารายการรูปยังไม่เปลี่ยน */
export function peekZip(folder, images) {
try {
if (folder && cache.file && cache.signature === signatureOf(folder, images)) return cache.file;
} catch { /* ignore */ }
return null;
}
export function invalidateZip() {
cache.signature = "";
cache.file = null;
@@ -92,10 +139,7 @@ export function downloadFile(file) {
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
/**
* แชร์ผ่าน Web Share API ระดับไฟล์ → share sheet ของ Samsung → เลือกแอปปลายทาง
* คืน {ok, reason}
*/
/** แชร์ผ่าน Web Share API ระดับไฟล์ — คืน {ok, reason} */
export async function shareFile(file, { title, text } = {}) {
if (!navigator.share) return { ok: false, reason: "unsupported" };
const payload = { files: [file], title: title || file.name, text: text || "" };
@@ -107,6 +151,10 @@ export async function shareFile(file, { title, text } = {}) {
return { ok: true };
} catch (err) {
if (err && err.name === "AbortError") return { ok: false, reason: "cancelled" };
if (err && (err.name === "NotAllowedError" || err.name === "InvalidStateError")) {
return { ok: false, reason: "notallowed", error: err };
}
if (err && err.name === "TypeError") return { ok: false, reason: "nofiles", error: err };
return { ok: false, reason: "failed", error: err };
}
}
+71 -3
View File
@@ -125,6 +125,30 @@ export async function setZoom(value) {
}
}
/**
* บังคับให้เป็น JPEG จริง — EXIF ฝังได้เฉพาะ JPEG
* (ImageCapture บางเครื่อง/บางเวอร์ชันคืน PNG กลับมา)
*/
async function toJpegBlob(blob, quality = JPEG_QUALITY) {
if (!blob) return blob;
const head = new Uint8Array(await blob.slice(0, 3).arrayBuffer());
const isJpeg = head[0] === 0xff && head[1] === 0xd8;
if (isJpeg) return blob.type === "image/jpeg" ? blob : new Blob([blob], { type: "image/jpeg" });
try {
const bmp = await createImageBitmap(blob);
const canvas = document.createElement("canvas");
canvas.width = bmp.width;
canvas.height = bmp.height;
canvas.getContext("2d").drawImage(bmp, 0, 0);
bmp.close?.();
const out = await new Promise((res) => canvas.toBlob(res, "image/jpeg", quality));
return out || blob;
} catch {
return blob;
}
}
async function makeThumb(blob) {
try {
const bmp = await createImageBitmap(blob);
@@ -142,18 +166,57 @@ async function makeThumb(blob) {
}
/**
* ถ่ายภาพนิ่ง
/** ครอปกลางภาพให้ได้อัตราส่วนที่เลือก (4:3 = 1.333, 3:4 = 0.75) */
async function cropToRatio(blob, ratio) {
try {
const bmp = await createImageBitmap(blob);
const w = bmp.width, h = bmp.height;
const src = w / h;
let sw = w, sh = h, sx = 0, sy = 0;
if (src > ratio + 0.002) {
sw = Math.round(h * ratio);
sx = Math.round((w - sw) / 2);
} else if (src < ratio - 0.002) {
sh = Math.round(w / ratio);
sy = Math.round((h - sh) / 2);
}
if (sw === w && sh === h) { bmp.close?.(); return { blob, width: w, height: h }; }
const canvas = document.createElement("canvas");
canvas.width = sw;
canvas.height = sh;
canvas.getContext("2d").drawImage(bmp, sx, sy, sw, sh, 0, 0, sw, sh);
bmp.close?.();
const out = await new Promise((res) => canvas.toBlob(res, "image/jpeg", JPEG_QUALITY));
return { blob: out || blob, width: sw, height: sh };
} catch {
return { blob, width: 0, height: 0 };
}
}
function ratioValue(label) {
const m = /^(\d+)\s*[:x/]\s*(\d+)$/.exec(String(label || ""));
if (!m) return 4 / 3;
const a = Number(m[1]), b = Number(m[2]);
return b ? a / b : 4 / 3;
}
/** ถ่ายภาพนิ่ง
* 1) ImageCapture.takePhoto() — ได้ JPEG ความละเอียดเต็มเซนเซอร์ + EXIF จากกล้อง (S23)
* 2) fallback: วาดเฟรมวิดีโอลง canvas
*/
export async function captureStill() {
export async function captureStill({ ratio = "4:3" } = {}) {
if (!cam.track) throw camError("notready");
let blob = null;
let source = "canvas";
if (cam.imageCapture) {
try {
blob = await cam.imageCapture.takePhoto();
// บางเครื่อง takePhoto() ค้างไม่ resolve → กันด้วย timeout แล้วตกไปใช้ canvas
blob = await Promise.race([
cam.imageCapture.takePhoto(),
new Promise((_, rej) => setTimeout(() => rej(new Error("takePhoto timeout")), 4000)),
]);
source = "imagecapture";
} catch { blob = null; }
}
@@ -171,6 +234,11 @@ export async function captureStill() {
source = "canvas";
}
// EXIF ฝังได้เฉพาะ JPEG → แปลงถ้าจำเป็น (ก่อนอ่านขนาด/ทำ thumb)
blob = await toJpegBlob(blob);
// ครอป/จัดทิศทางทำที่ main.js (หลัง auto-orient) — ที่นี่คืนภาพดิบ
if (!width || !height) {
try {
const bmp = await createImageBitmap(blob);
+2 -2
View File
@@ -1,9 +1,9 @@
// ── ค่าคงที่ทั้งแอป ──────────────────────────────────────────
export const APP_VERSION = "2.0.0";
export const APP_VERSION = "2.1.4";
export const DB_NAME = "camcat-db";
export const DB_VERSION = 2;
export const SITE_LABEL = "Site A"; // ชื่อไซต์ ใช้เป็น prefix ของโฟลเดอร์
export const SITE_LABEL = "Site"; // prefix ของโฟลเดอร์ (ตัวอักษร a-z ต่อท้าย)
export const TIME_ZONE = "Asia/Bangkok"; // ปี พ.ศ. คำนวณจากโซนนี้เสมอ
export const JPEG_QUALITY = 0.92;
+111
View File
@@ -0,0 +1,111 @@
// ── นำเข้าโฟลเดอร์ทีละหลายรายการจาก CSV ─────────────────────
// หัวตาราง: site,letter,datetime,name
// site : คำนำหน้า (เว้นว่าง = "Site")
// letter : ตัวอักษร a-z/aa… (เว้นว่าง = ไล่ต่อจากของเดิมอัตโนมัติ)
// datetime : 2569.10.25.21.45 (รับ – / : ช่องว่าง หรือ ค.ศ. ได้)
// name : ชื่อเต็ม (ถ้าใส่ จะใช้ค่านี้แทนการประกอบชื่อ)
import { SITE_LABEL } from "./config.js";
import { safeFileName, letterForIndex, indexForLetters, nextLetter, normalizeFolderStamp } from "./naming.js";
const DELIMS = [",", ";", "\t"];
function sniffDelimiter(line) {
let best = ",";
let bestCount = -1;
for (const d of DELIMS) {
const n = line.split(d).length - 1;
if (n > bestCount) { best = d; bestCount = n; }
}
return best;
}
/** CSV → array ของ object (คีย์เป็นตัวพิมพ์เล็ก) รองรับ quote/CRLF/BOM */
export function parseCsv(text) {
const src = String(text || "").replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").trim();
if (!src) return { header: [], rows: [] };
const delim = sniffDelimiter(src.split("\n")[0]);
const rows = [];
let field = "";
let row = [];
let quoted = false;
for (let i = 0; i < src.length; i++) {
const ch = src[i];
if (quoted) {
if (ch === '"') {
if (src[i + 1] === '"') { field += '"'; i++; }
else quoted = false;
} else field += ch;
continue;
}
if (ch === '"') { quoted = true; continue; }
if (ch === delim) { row.push(field); field = ""; continue; }
if (ch === "\n") { row.push(field); rows.push(row); row = []; field = ""; continue; }
field += ch;
}
if (field.length || row.length) { row.push(field); rows.push(row); }
const header = rows.shift().map((h) => h.trim().toLowerCase());
const out = rows
.filter((r) => r.some((c) => String(c).trim() !== ""))
.map((r) => {
const obj = {};
header.forEach((h, idx) => { obj[h] = (r[idx] ?? "").trim(); });
return obj;
});
return { header, rows: out, delimiter: delim };
}
/**
* วางแผนสร้างโฟลเดอร์จากแถว CSV
* คืน { items:[{name,row}], errors:[{row,reason}] }
*/
export function planFolders(rows, existingNames = []) {
const taken = new Set(existingNames.map((n) => String(n)));
const items = [];
const errors = [];
let nextIdx = Math.max(0, indexForLetters(nextLetter(existingNames))); // ตัวอักษรถัดไป (a ถ้ายังไม่มี)
rows.forEach((row, i) => {
const line = i + 2; // +2 = เผื่อหัวตาราง (เริ่มนับที่ 1)
const rawName = (row.name || "").trim();
let site = (row.site || SITE_LABEL).trim() || SITE_LABEL;
site = site.replace(/\s+/g, " ");
let letter = (row.letter || "").trim().toLowerCase();
if (letter && !/^[a-z]+$/.test(letter)) {
errors.push({ row: line, reason: `letter "${row.letter}" ไม่ใช่ a-z` });
return;
}
const stamp = normalizeFolderStamp(row.datetime, null);
if (row.datetime && !stamp) {
errors.push({ row: line, reason: `datetime "${row.datetime}" อ่านไม่ได้ (ต้องเป็น ปี.เดือน.วัน.ชั่วโมง.นาที)` });
return;
}
let name = rawName ? safeFileName(rawName, "") : "";
if (!name) {
if (!stamp) {
errors.push({ row: line, reason: "ไม่มี datetime และไม่มี name" });
return;
}
if (!letter) {
// หา letter ว่างถัดไป (ข้ามชื่อที่มีอยู่แล้ว)
let guard = 0;
do { letter = letterForIndex(nextIdx++); guard++; } while (taken.has(`${site} ${letter} ${stamp}`) && guard < 500);
}
name = `${site} ${letter} ${stamp}`;
}
if (!name) { errors.push({ row: line, reason: "ชื่อว่าง" }); return; }
if (taken.has(name)) { errors.push({ row: line, reason: `ชื่อซ้ำ: ${name}` }); return; }
taken.add(name);
items.push({ name, row: line });
});
return { items, errors };
}
+44 -17
View File
@@ -3,29 +3,56 @@ import { DB_NAME, DB_VERSION, STORE_FOLDERS, STORE_IMAGES } from "./config.js";
let db = null;
function ensureSchema(req) {
const d = req.result;
if (!d.objectStoreNames.contains(STORE_FOLDERS)) {
d.createObjectStore(STORE_FOLDERS, { keyPath: "id" });
}
if (!d.objectStoreNames.contains(STORE_IMAGES)) {
const s = d.createObjectStore(STORE_IMAGES, { keyPath: "id" });
s.createIndex("folderId", "folderId", { unique: false });
s.createIndex("createdAt", "createdAt", { unique: false });
} else {
// อัปเกรดจาก v1: เพิ่ม index createdAt ถ้ายังไม่มี
const s = req.transaction.objectStore(STORE_IMAGES);
if (!s.indexNames.contains("createdAt")) {
s.createIndex("createdAt", "createdAt", { unique: false });
}
}
}
const hasStores = (d) =>
d.objectStoreNames.contains(STORE_FOLDERS) && d.objectStoreNames.contains(STORE_IMAGES);
export function open() {
if (db) return Promise.resolve(db);
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = () => {
// เปิดด้วยเวอร์ชันปัจจุบันก่อน — กัน VersionError ถ้าเครื่องมี DB ใหม่กว่า
const req = indexedDB.open(DB_NAME);
req.onupgradeneeded = () => ensureSchema(req);
req.onsuccess = () => {
const d = req.result;
if (!d.objectStoreNames.contains(STORE_FOLDERS)) {
d.createObjectStore(STORE_FOLDERS, { keyPath: "id" });
}
if (!d.objectStoreNames.contains(STORE_IMAGES)) {
const s = d.createObjectStore(STORE_IMAGES, { keyPath: "id" });
s.createIndex("folderId", "folderId", { unique: false });
s.createIndex("createdAt", "createdAt", { unique: false });
} else {
// อัปเกรดจาก v1: เพิ่ม index createdAt ถ้ายังไม่มี (ของเดิมเรียงตาม id ได้อยู่แล้ว)
const s = req.transaction.objectStore(STORE_IMAGES);
if (!s.indexNames.contains("createdAt")) {
s.createIndex("createdAt", "createdAt", { unique: false });
}
if (hasStores(d)) {
// ปิด connection เองเมื่อมีการขออัปเกรดจากแท็บอื่น กันการบล็อกค้าง
d.onversionchange = () => { try { d.close(); } catch {} db = null; };
db = d; resolve(db); return;
}
// DB มีอยู่แต่ไม่มี store (เช่นเคยถูกสร้างว่างจากสคริปต์อื่น) → อัปเกรด schemas
const next = d.version + 1;
d.close();
const up = indexedDB.open(DB_NAME, next);
up.onupgradeneeded = () => ensureSchema(up);
up.onsuccess = () => { db = up.result; resolve(db); };
up.onerror = () => reject(up.error);
};
req.onerror = () => {
// ถ้าเปิดไม่ได้เพราะเวอร์ชันต่ำกว่า ให้ลองแบบไม่ระบุเวอร์ชันซ้ำ
reject(req.error);
};
req.onsuccess = () => { db = req.result; resolve(db); };
req.onerror = () => reject(req.error);
});
}
+159 -32
View File
@@ -1,5 +1,6 @@
// ── อ่าน/เขียน EXIF (JPEG) ด้วย piexifjs ─────────────────────
// Metadata ที่ฝังในไฟล์จะติดไปกับรูปตอนแชร์ออกแอปอื่นด้วย
// เป้าหมาย: metadata อยู่ใน "ไฟล์รูป" แบบเดียวกับแอปกล้องของ Samsung
// (Make/Model/เวลา/GPS/ความละเอียด ฯลฯ ฝังใน EXIF — ไม่มีไฟล์ JSON แยก)
const piexif = () => (typeof window !== "undefined" ? window.piexif : undefined);
@@ -33,9 +34,13 @@ const dmsToDecimal = (dms, ref) => {
return ref === "S" || ref === "W" ? -v : v;
};
const str = (v) => (typeof v === "string" ? v.replace(/\0+$/, "").trim() : undefined);
const str = (v) => {
if (typeof v !== "string") return undefined;
const s = v.replace(/\0+$/, "").trim();
return s || undefined;
};
/** อ่าน EXIF จาก JPEG → object แบน (ค่าว่าง = ไม่มี tag) */
/** อ่าน EXIF จาก JPEG → object แบน (คีย์ไม่มี = ไฟล์ไม่มี tag นั้น) */
export async function readExif(blob) {
const px = piexif();
if (!px || !blob) return {};
@@ -44,28 +49,42 @@ export async function readExif(blob) {
if (!dataUrl.startsWith("data:image/jpeg")) return {};
const exif = px.load(dataUrl) || {};
const o = exif["0th"] || {};
const e = exif["Exif"] || {};
const g = exif["GPS"] || {};
const e = exif.Exif || {};
const g = exif.GPS || {};
return {
make: str(o[271]),
model: str(o[272]),
description: str(o[270]),
software: str(o[305]),
dateTime: str(o[306]) || str(e[36867]),
dateTime: str(o[306]),
dateTimeOriginal: str(e[36867]),
dateTimeDigitized: str(e[36868]),
orientation: typeof o[274] === "number" ? o[274] : undefined,
xResolution: o[282] ? rat(o[282]) : undefined,
resolutionUnit: o[296],
colorSpace: e[40961],
exifVersion: str(e[36864]),
uniqueId: str(e[42016]),
width: e[40962] || o[256] || undefined,
height: e[40963] || o[257] || undefined,
iso: typeof e[34855] === "number" ? e[34855] : undefined,
fNumber: e[33437] ? rat(e[33437]) : undefined,
exposureTime: e[33434] ? rat(e[33434]) : undefined,
exposureBias: e[37380] ? rat(e[37380]) : undefined,
focalLength: e[37386] ? rat(e[37386]) : undefined,
lensModel: str(e[42036]),
lensMake: str(e[42035]),
hasMakerNote: !!e[37500],
xpComment: fromUtf16le(o[40092]),
xpKeywords: fromUtf16le(o[40094]),
gps: g[2] ? {
lat: dmsToDecimal(g[2], str(g[1])),
lng: dmsToDecimal(g[4], str(g[3])),
altitude: g[6] ? rat(g[6]) * (str(g[5]) === "1" ? -1 : 1) : null,
accuracy: g[31] ? rat(g[31]) : null,
dateStamp: str(g[29]),
timeStamp: Array.isArray(g[7]) ? g[7].map(rat) : null,
processingMethod: str(g[27]),
} : null,
};
} catch {
@@ -73,6 +92,48 @@ export async function readExif(blob) {
}
}
/** ตัดอักษรนอก ASCII ออกให้หมด (ใช้กับชื่อที่ต้องอ่านรู้เรื่อง) */
const asciiStripped = (s, fallback = "CamCat") => {
const v = String(s ?? "").normalize("NFC").replace(/[^\x20-\x7E]/g, "").replace(/\s{2,}/g, " ").trim();
return v || fallback;
};
/** EXIF ASCII รับได้เฉพาะ Latin1 — แทนอักษรนอกช่วงด้วย ? (ชื่อไทยเก็บใน XPComment แทน) */
const ascii = (s, fallback = "") => {
const v = String(s ?? "").normalize("NFC").replace(/[^\x20-\x7E]/g, "?").trim();
return v || fallback;
};
/** XP* tags เก็บ Unicode แบบ UTF-16LE เป็น array ของ byte */
const utf16le = (s) => {
const out = [];
for (const ch of String(s ?? "")) {
const code = ch.codePointAt(0);
if (code > 0xffff) {
const v = code - 0x10000;
const hi = 0xd800 + (v >> 10);
const lo = 0xdc00 + (v & 0x3ff);
out.push(hi & 0xff, hi >> 8, lo & 0xff, lo >> 8);
} else {
out.push(code & 0xff, code >> 8);
}
}
out.push(0, 0); // null terminator
return out;
};
const fromUtf16le = (bytes) => {
if (!Array.isArray(bytes) || !bytes.length) return undefined;
const codes = [];
for (let i = 0; i + 1 < bytes.length; i += 2) {
const c = bytes[i] | (bytes[i + 1] << 8);
if (c === 0) break;
codes.push(c);
}
if (!codes.length) return undefined;
try { return String.fromCharCode(...codes); } catch { return undefined; }
};
const decToDms = (dec) => {
const abs = Math.abs(dec);
const d = Math.floor(abs);
@@ -82,52 +143,118 @@ const decToDms = (dec) => {
return [[d, 1], [m, 1], [s, 100]];
};
/** แยก "YYYY:MM:DD HH:MM:SS" เพื่อใช้กับ GPSTimeStamp/GPSDateStamp */
function splitDateTime(dateTime) {
const m = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/.exec(dateTime || "");
if (!m) return null;
return { date: `${m[1]}:${m[2]}:${m[3]}`, h: +m[4], mi: +m[5], s: +m[6] };
}
/**
* ฝัง EXIF ลง JPEG ก่อนบันทึก
* meta = { make, model, dateTime, gps:{lat,lng,altitude}, width, height, folder, source }
* คืน Blob ใหม่ (ถ้าฝังไม่ได้คืน blob เดิม)
* ฝัง EXIF มาตรฐานลง JPEG (แบบที่แอปกล้อง Samsung เขียน)
* meta = {
* make, model, modelName, software, dateTime,
* width, height, folder, orientation, uniqueId,
* gps: { lat, lng, altitude, accuracy },
* iso, fNumber, exposureTime, focalLength // ใส่เฉพาะที่มีค่าจริง
* }
* คืน Blob ใหม่ — ถ้าเขียนไม่ได้คืน blob เดิม
*/
export async function writeExif(blob, meta = {}) {
const px = piexif();
if (!px || !blob || blob.type !== "image/jpeg") return blob;
try {
const dataUrl = await blobToDataURL(blob);
let existing = {};
try { existing = px.load(dataUrl) || {}; } catch { existing = {}; }
const zeroth = Object.assign({}, existing["0th"] || {});
const exif = Object.assign({}, existing["Exif"] || {});
const gps = Object.assign({}, existing["GPS"] || {});
const zeroth = { ...(existing["0th"] || {}) };
const exif = { ...(existing.Exif || {}) };
const gps = { ...(existing.GPS || {}) };
zeroth[271] = meta.make || "Samsung";
zeroth[272] = meta.model || "Samsung Galaxy S23";
zeroth[305] = "CamCat " + (meta.version || "2.0.0");
zeroth[306] = meta.dateTime;
if (meta.folder) zeroth[270] = "Folder: " + meta.folder; // ImageDescription (IFD0)
if (!zeroth[274]) zeroth[274] = 1;
// ── IFD0 (ASCII เท่านั้น) ──
const fullLabel = meta.folder ? `CamCat · ${meta.folder}` : "CamCat";
zeroth[270] = asciiStripped(fullLabel, "CamCat"); // ImageDescription
zeroth[271] = ascii(meta.make, "samsung"); // Make
zeroth[272] = ascii(meta.model || meta.modelName, "CamCat Web"); // Model
zeroth[305] = ascii(meta.software, "CamCat"); // Software
zeroth[315] = asciiStripped(meta.folder || "CamCat", "CamCat"); // Artist = ชื่อโฟลเดอร์
// ชื่อที่มีอักษรไทย/Unicode → เก็บใน XPComment (UTF-16LE) และ XPKeywords
if (/[^\x20-\x7E]/.test(String(meta.folder || ""))) {
zeroth[40092] = utf16le(fullLabel); // XPComment
zeroth[40094] = utf16le(meta.folder); // XPKeywords
}
if (meta.dateTime) zeroth[306] = meta.dateTime;
zeroth[274] = meta.orientation || 1; // บังคับค่าหลัง normalize แล้ว
zeroth[282] = [72, 1];
zeroth[283] = [72, 1];
zeroth[296] = 2;
zeroth[296] = 2; // นิ้ว
exif[36867] = meta.dateTime; // DateTimeOriginal
exif[36868] = meta.dateTime; // DateTimeDigitized
// ── Exif IFD ──
exif[36864] = "0232"; // ExifVersion (Undefined 4 ไบต์)
if (meta.dateTime) {
exif[36867] = meta.dateTime; // DateTimeOriginal
exif[36868] = meta.dateTime; // DateTimeDigitized
}
exif[37121] = "\x01\x02\x03\x00"; // ComponentsConfiguration = YCbCr
exif[40961] = 1; // ColorSpace = sRGB
if (meta.width) exif[40962] = meta.width;
if (meta.height) exif[40963] = meta.height;
exif[37380] = [0, 1]; // ExposureBiasValue
exif[41985] = 0; // CustomRendered: normal
exif[41986] = 0; // ExposureMode: auto
exif[41987] = 0; // WhiteBalance: auto
exif[41988] = [1, 1]; // DigitalZoomRatio
exif[41990] = 0; // SceneCaptureType: standard
exif[41992] = 0; // Contrast: normal
exif[41993] = 0; // Saturation: normal
exif[41994] = 0; // Sharpness: normal
if (meta.uniqueId) exif[42016] = ascii(meta.uniqueId).slice(0, 32);
if (meta.gps && Number.isFinite(meta.gps.lat) && Number.isFinite(meta.gps.lng)) {
// ค่าที่วัดได้จริงเท่านั้น (ไม่เดา)
if (Number.isFinite(meta.iso) && meta.iso > 0) exif[34855] = Math.round(meta.iso);
if (Number.isFinite(meta.fNumber) && meta.fNumber > 0) exif[33437] = [Math.round(meta.fNumber * 10), 10];
if (Number.isFinite(meta.exposureTime) && meta.exposureTime > 0) {
exif[33434] = meta.exposureTime >= 1
? [Math.round(meta.exposureTime * 100), 100]
: [1, Math.round(1 / meta.exposureTime)];
}
if (Number.isFinite(meta.focalLength) && meta.focalLength > 0) exif[37386] = [Math.round(meta.focalLength * 10), 10];
if (meta.lensModel) exif[42036] = ascii(meta.lensModel);
// ── GPS IFD ──
const g = meta.gps;
if (g && Number.isFinite(g.lat) && Number.isFinite(g.lng)) {
const dt = splitDateTime(meta.dateTime);
gps[0] = [2, 3, 0, 0];
gps[1] = meta.gps.lat >= 0 ? "N" : "S";
gps[2] = decToDms(meta.gps.lat);
gps[3] = meta.gps.lng >= 0 ? "E" : "W";
gps[4] = decToDms(meta.gps.lng);
if (Number.isFinite(meta.gps.altitude)) {
gps[5] = meta.gps.altitude >= 0 ? 0 : 1;
gps[6] = [Math.round(Math.abs(meta.gps.altitude) * 100), 100];
gps[1] = g.lat >= 0 ? "N" : "S";
gps[2] = decToDms(g.lat);
gps[3] = g.lng >= 0 ? "E" : "W";
gps[4] = decToDms(g.lng);
if (Number.isFinite(g.altitude)) {
gps[5] = g.altitude >= 0 ? 0 : 1;
gps[6] = [Math.round(Math.abs(g.altitude) * 100), 100];
}
gps[29] = meta.dateTime.slice(0, 10).replace(/:/g, ":");
if (Number.isFinite(g.accuracy) && g.accuracy > 0) {
gps[31] = [Math.round(g.accuracy * 100), 100]; // GPSHPositioningError (เมตร)
}
if (dt) {
gps[7] = [[dt.h, 1], [dt.mi, 1], [dt.s, 1]]; // GPSTimeStamp
gps[29] = dt.date; // GPSDateStamp
}
gps[27] = "ASCII\x00\x00\x00GPS"; // GPSProcessingMethod
}
const dict = { "0th": zeroth, Exif: exif, GPS: gps, Interop: existing.Interop || {}, "1st": existing["1st"] || {}, thumbnail: null };
const dict = {
"0th": zeroth,
Exif: exif,
GPS: gps,
Interop: existing.Interop || {},
"1st": existing["1st"] || {},
thumbnail: existing.thumbnail || null,
};
const inserted = px.insert(px.dump(dict), dataUrl);
return dataURLToBlob(inserted);
} catch (err) {
@@ -136,7 +263,7 @@ export async function writeExif(blob, meta = {}) {
}
}
/** 1/125 · f/1.8 · 50mm */
/** "1/125 · f/1.8 · ISO 50 · 5mm" */
export function formatExposure(exif = {}) {
const bits = [];
if (exif.fNumber) bits.push("f/" + exif.fNumber.toFixed(1));
+382 -46
View File
@@ -11,10 +11,14 @@ import { detectDevice, exifModelName, environment } from "./device.js";
import {
defaultFolderName, exifDateString, safeFileName, uniqueName,
} from "./naming.js";
import { ensureZip, invalidateZip, downloadFile, shareFile, canShareFiles } from "./archive.js";
import { ensureZip, peekZip, invalidateZip, downloadFile, shareFile, canShareFiles, buildAllZip } from "./archive.js";
import { parseCsv, planFolders } from "./csv.js";
import * as native from "./native.js";
import { autoOrient, detectOrientation, cropToRatio, ratioValue, makeThumbFromBlob, rotateBlob } from "./orient.js";
const LS_FOLDER = "camcat.activeFolder";
const LS_FACING = "camcat.facing";
const LS_RATIO = "camcat.ratio";
const state = {
view: "camera",
@@ -30,7 +34,9 @@ const state = {
zoomRange: null,
zoomValue: null,
grid: false,
ratio: localStorage.getItem(LS_RATIO) || "4:3",
busy: false,
lastZip: null,
facing: localStorage.getItem(LS_FACING) || "environment",
storage: null,
};
@@ -105,6 +111,11 @@ function flash() {
setTimeout(() => el.remove(), 220);
}
function newUniqueId(ts = Date.now()) {
const rnd = () => Math.floor(Math.random() * 0xffff).toString(16).padStart(4, "0");
return (ts.toString(16) + rnd().repeat(8)).padEnd(32, "0").slice(0, 32);
}
function nextFileName(folderName, images) {
const base = safeFileName(folderName).replace(/\s+/g, "_");
let max = 0;
@@ -142,6 +153,20 @@ async function getGps() {
}
// ── camera view ─────────────────────────────────────────────
function fitFrame() {
const stage = document.querySelector(".stage");
const frame = document.getElementById("cam-frame");
if (!stage || !frame) return;
const box = stage.getBoundingClientRect();
if (!box.width || !box.height) return;
const r = state.ratio === "3:4" ? 3 / 4 : 4 / 3;
let w = box.width;
let h = w / r;
if (h > box.height) { h = box.height; w = h * r; }
frame.style.width = Math.round(w) + "px";
frame.style.height = Math.round(h) + "px";
}
function syncCam(overrides = {}) {
ui.syncCameraControls({
torchAvailable: state.torchAvailable && state.camReady,
@@ -150,10 +175,13 @@ function syncCam(overrides = {}) {
zoomValue: state.zoomValue,
gridOn: state.grid,
count: state.images.length,
ratio: state.ratio,
thumbUrl: state.images.length ? thumbUrl(state.images[state.images.length - 1]) : null,
ready: state.camReady,
...overrides,
});
fitFrame();
setTimeout(fitFrame, 80);
}
function renderCameraView() {
@@ -274,6 +302,12 @@ async function switchCamera() {
}
// ── shoot ───────────────────────────────────────────────────
const withTimeout = (p, ms, label) =>
Promise.race([
p,
new Promise((_, rej) => setTimeout(() => rej(new Error(label + " timeout")), ms)),
]);
async function shoot() {
if (state.busy) return;
if (!state.camReady) { ui.toast("กล้องยังไม่พร้อม"); return; }
@@ -281,25 +315,61 @@ async function shoot() {
const shutter = document.getElementById("shutter");
if (shutter) shutter.disabled = true;
// watchdog: บางเครื่อง promise ของกล้องค้าง → ปลดล็อกปุ่มเอง
const watchdog = setTimeout(() => {
state.busy = false;
const s = document.getElementById("shutter");
if (s) s.disabled = false;
ui.toast("ถ่ายใช้เวลานานเกินไป — ลองอีกครั้ง");
}, 20000);
try {
const folder = state.folder;
if (!folder) throw new Error("ยังไม่มีโฟลเดอร์");
const shot = await camApi.captureStill();
const gps = await getGps();
const at = Date.now();
const exifBlob = await writeExif(shot.blob, {
make: "Samsung",
model: exifModelName(),
dateTime: exifDateString(new Date(at)),
gps,
const shot = await Promise.race([
camApi.captureStill(),
new Promise((_, rej) => setTimeout(() => rej(new Error("capture timeout")), 12000)),
]);
// ① อ่าน EXIF Orientation ของไฟล์ แล้วหมุนพิกเซลให้ตั้งตรง (Orientation = 1)
const orientationTag = await detectOrientation(shot.blob);
const oriented = await autoOrient({
blob: shot.blob,
exifOrientation: orientationTag,
width: shot.width,
height: shot.height,
folder: folder.name,
source: shot.source,
version: APP_VERSION,
facing: shot.facing,
});
const exifRead = await readExif(exifBlob);
// ② ครอปตามอัตราส่วนที่เลือก (ทำหลังจัดทิศทาง เพื่อไม่ให้ครอปผิดแกน)
const cropped = await cropToRatio(oriented.blob, ratioValue(state.ratio));
const finalBlob = cropped.blob;
const fw = cropped.width || oriented.width || shot.width;
const fh = cropped.height || oriented.height || shot.height;
const thumb = await makeThumbFromBlob(finalBlob);
const gps = await getGps();
const at = Date.now();
const isSamsung = /^SM-/i.test(device.code) || device.brand === "Samsung";
const exifBlob = await writeExif(finalBlob, {
make: isSamsung ? "samsung" : device.brand || "CamCat",
model: /^SM-/i.test(device.code)
? device.code
: /^[\x20-\x7E]+$/.test(device.model || "")
? device.model
: "CamCat Web Camera",
modelName: exifModelName(),
software: `CamCat ${APP_VERSION} | Android ${device.androidVersion || "-"} | Chrome ${device.chromeVersion || "-"}`,
dateTime: exifDateString(new Date(at)),
gps,
width: fw,
height: fh,
folder: folder.name,
orientation: 1,
uniqueId: newUniqueId(at),
});
const exifRead = await withTimeout(readExif(exifBlob), 6000, "readExif");
const name = nextFileName(folder.name, state.images);
const record = {
@@ -307,17 +377,22 @@ async function shoot() {
folderId: folder.id,
name,
blob: exifBlob,
thumb: shot.thumb,
thumb: thumb,
size: exifBlob.size,
createdAt: at,
meta: {
width: shot.width,
height: shot.height,
width: fw,
height: fh,
ratio: state.ratio,
orientationTag,
rotationApplied: oriented.rotation || 0,
mirrored: !!oriented.mirrored,
device: exifModelName(),
facing: shot.facing,
facingLabel: shot.facing === "environment" ? "กล้องหลัง" : "กล้องหน้า",
source: shot.source,
sourceLabel: shot.source === "imagecapture" ? "ImageCapture (ความละเอียดเต็ม)" : "วิดีโอ (canvas)",
orientSource: oriented.source,
gps: gps ? { lat: gps.lat, lng: gps.lng, accuracy: gps.accuracy } : null,
exif: exifRead,
app: `CamCat ${APP_VERSION}`,
@@ -325,24 +400,76 @@ async function shoot() {
},
};
await db.putImage(record);
await db.touchFolder(folder.id);
await withTimeout(db.putImage(record), 8000, "db.putImage");
await withTimeout(db.touchFolder(folder.id), 5000, "db.touchFolder");
state.images.push(record);
state.counts = state.counts.map((c, i) => (state.folders[i]?.id === folder.id ? c + 1 : c));
flash();
invalidateZip();
syncCam({ thumbUrl: thumbUrl(record) });
ui.toast(`บันทึก ${name} · ${shot.width}×${shot.height}`);
let savedTo = "";
if (native.isNative()) {
const uri = await native.savePhoto(folder.name, name, exifBlob);
if (uri) savedTo = ` → ${native.displayPath(folder.name)}`;
}
ui.toast(`บันทึก ${name}${savedTo}`);
} catch (err) {
console.error(err);
ui.toast("ถ่ายไม่สำเร็จ: " + (err.code || err.message));
} finally {
clearTimeout(watchdog);
state.busy = false;
if (shutter) shutter.disabled = false;
}
}
async function rotatePhoto(id, deg) {
const rec = await db.getImage(id);
if (!rec) return;
try {
const out = await rotateBlob(rec.blob, deg);
const at = rec.createdAt;
const folderName = rec.meta?.folder || state.folder?.name || "";
const exifBlob = await writeExif(out.blob, {
make: rec.meta?.exif?.make || "samsung",
model: rec.meta?.exif?.model || "SM-S911B",
software: rec.meta?.exif?.software || `CamCat ${APP_VERSION}`,
dateTime: exifDateString(new Date(at)),
width: out.width,
height: out.height,
folder: folderName,
orientation: 1,
uniqueId: rec.meta?.exif?.uniqueId || newUniqueId(at),
gps: rec.meta?.gps
? { lat: rec.meta.gps.lat, lng: rec.meta.gps.lng, accuracy: rec.meta.gps.accuracy }
: null,
});
rec.blob = exifBlob;
rec.thumb = out.thumb;
rec.size = exifBlob.size;
rec.meta = {
...(rec.meta || {}),
width: out.width,
height: out.height,
rotationApplied: (((rec.meta?.rotationApplied || 0) + deg) % 360 + 360) % 360,
rotatedManually: true,
exif: await readExif(exifBlob),
};
await db.putImage(rec);
state.images = state.images.map((i) => (i.id === id ? rec : i));
dropThumb(id);
invalidateZip();
await openPhoto(id);
ui.toast(`หมุน ${deg > 0 ? "ขวา" : "ซ้าย"} 90° แล้ว`);
} catch (err) {
console.error(err);
ui.toast("หมุนรูปไม่สำเร็จ: " + err.message);
}
}
// ── folder data ─────────────────────────────────────────────
async function loadFolders() {
state.folders = await db.getFolders();
@@ -363,7 +490,7 @@ async function selectFolder(id, { silent = false } = {}) {
async function ensureDefaultFolder() {
await loadFolders();
if (!state.folders.length) {
const folder = { id: "f_" + Date.now(), name: defaultFolderName(), createdAt: Date.now(), updatedAt: Date.now() };
const folder = { id: "f_" + Date.now(), name: defaultFolderName(state.folders.map((f) => f.name)), createdAt: Date.now(), updatedAt: Date.now() };
await db.putFolder(folder);
await loadFolders();
await selectFolder(folder.id, { silent: true });
@@ -438,43 +565,105 @@ function schedulePrebuild() {
}, 1200);
}
async function buildZipFile() {
const { file } = await ensureZip(state.folder, state.images, (p) =>
ui.progressUpdate(p, `กำลังรวม ${state.images.length} รูป`)
);
state.lastZip = file;
return file;
}
function sharePayload(file) {
return {
title: state.folder?.name || file.name,
text: `รูปจาก ${state.folder?.name || ""} (${state.images.length} รูป)`,
};
}
function shareReasonText(reason) {
if (reason === "notallowed") return "เบราว์เซอร์ตัดสิทธิ์เพราะรอนาน — แตะอีกครั้ง";
if (reason === "nofiles") return "เบราว์เซอร์นี้ไม่รองรับการแชร์ไฟล์";
if (reason === "notsupported" || reason === "unsupported") return "ไม่มี Web Share API";
if (reason === "failed") return "ระบบแชร์ปฏิเสธ";
return "";
}
function showShareSheet(file, reason = "") {
ui.openSheet(
ui.shareReadySheet({
name: file.name,
size: file.size,
canShare: canShareFiles(file) && !!navigator.share,
reason: shareReasonText(reason),
})
);
}
async function handleShareResult(res, file) {
if (res.ok) { ui.closeSheet(); ui.toast("เปิด share sheet ของเครื่องแล้ว"); return; }
if (res.reason === "cancelled") { ui.closeSheet(); return; }
showShareSheet(file, res.reason);
}
async function deliverFile(file, note = "") {
if (native.isNative()) {
const uri = await native.saveZip(file);
if (uri) {
ui.toast(`บันทึก ${file.name} ลง Documents/CamCat-ZIP${note ? " · " + note : ""}`);
return;
}
}
downloadFile(file);
ui.toast(`ดาวน์โหลด ${file.name} (${ui.fmtBytes(file.size)})${note ? " · " + note : ""}`);
}
async function zipFlow(mode) {
if (!state.folder) { ui.toast("ยังไม่เลือกโฟลเดอร์"); return; }
if (!state.images.length) { ui.toast("ยังไม่มีรูปในโฟลเดอร์นี้"); return; }
if (state.busy) return;
state.busy = true;
ui.progressSheet(`กำลังรวม ${state.images.length} รูปเป็น ZIP`);
try {
const { file } = await ensureZip(state.folder, state.images, (p) =>
ui.progressUpdate(p, `กำลังรวม ${state.images.length} รูป`)
);
ui.closeSheet();
if (mode === "download") {
downloadFile(file);
ui.toast(`ดาวน์โหลด ${file.name} (${ui.fmtBytes(file.size)})`);
const cached = peekZip(state.folder, state.images);
let file = cached;
if (!file) {
ui.progressSheet(`กำลังรวม ${state.images.length} รูปเป็น ZIP`);
file = await buildZipFile();
ui.closeSheet();
}
await deliverFile(file);
return;
}
if (!canShareFiles(file)) {
downloadFile(file);
ui.toast("เครื่องนี้แชร์ไฟล์ผ่านเว็บไม่ได้ — ดาวน์โหลด ZIP ให้แล้ว");
// APK: ใช้ share sheet ของ Android ผ่านปลั๊กอิน Share (FileProvider)
if (native.isNative()) {
let file = peekZip(state.folder, state.images);
if (!file) {
ui.progressSheet(`กำลังรวม ${state.images.length} รูปเป็น ZIP`);
file = await buildZipFile();
ui.closeSheet();
}
const res = await native.shareItems([{ name: file.name, blob: file }], state.folder?.name || "");
if (res.ok) { ui.closeSheet(); ui.toast("แชร์ผ่านระบบของ Android แล้ว"); }
else if (res.reason === "cancelled") { ui.closeSheet(); }
else { await deliverFile(file); }
return;
}
const res = await shareFile(file, {
title: state.folder.name,
text: `รูปจาก ${state.folder.name} (${state.images.length} รูป)`,
});
if (res.ok) ui.toast("เปิดเมนูแชร์ของเครื่องแล้ว");
else if (res.reason === "cancelled") ui.toast("ยกเลิกการแชร์");
else if (res.reason === "unsupported" || res.reason === "nofiles") {
downloadFile(file);
ui.toast("แชร์ไฟล์ไม่ได้ — ดาวน์โหลด ZIP ให้แล้ว");
} else {
downloadFile(file);
ui.toast("แชร์ไม่สำเร็จ — ดาวน์โหลด ZIP ให้แล้ว");
// แชร์: ถ้ามี ZIP ที่สร้างไว้แล้ว → ยิง share ทันทีในจังหวะแตะ (activation ยังสด)
const cached = peekZip(state.folder, state.images);
if (cached) {
const res = await shareFile(cached, sharePayload(cached));
await handleShareResult(res, cached);
return;
}
// ยังไม่มี ZIP → สร้างก่อน แล้วให้ผู้ใช้แตะแชร์อีกครั้ง (activation ใหม่)
ui.progressSheet(`กำลังรวม ${state.images.length} รูปเป็น ZIP`);
const file = await buildZipFile();
ui.closeSheet();
showShareSheet(file, "");
} catch (err) {
console.error(err);
ui.closeSheet();
@@ -484,6 +673,53 @@ async function zipFlow(mode) {
}
}
// ZIP ทุกโฟลเดอร์ในครั้งเดียว (แยกโฟลเดอร์ย่อยในไฟล์ zip)
async function zipAllFolders() {
if (state.busy) return;
await loadFolders();
if (!state.folders.length) { ui.toast("ยังไม่มีโฟลเดอร์"); return; }
const byFolder = {};
let total = 0;
for (const f of state.folders) {
const imgs = await db.getImages(f.id);
byFolder[f.id] = imgs;
total += imgs.length;
}
if (!total) { ui.toast("ยังไม่มีรูปในทุกโฟลเดอร์"); return; }
state.busy = true;
ui.progressSheet(`กำลังรวม ${state.folders.length} โฟลเดอร์ (${total} รูป)`);
try {
const { file, photos, folders } = await buildAllZip(state.folders, byFolder, (p) =>
ui.progressUpdate(p, `กำลังรวม ${total} รูป`)
);
ui.closeSheet();
await deliverFile(file, `${folders} โฟลเดอร์ ${photos} รูป`);
} catch (err) {
console.error(err);
ui.closeSheet();
ui.toast("สร้าง ZIP รวมไม่สำเร็จ: " + err.message);
} finally {
state.busy = false;
}
}
async function shareCachedZip() {
const file = peekZip(state.folder, state.images) || state.lastZip;
if (!file) { ui.toast("ยังไม่มีไฟล์ ZIP"); return; }
const res = await shareFile(file, sharePayload(file));
await handleShareResult(res, file);
}
function saveCachedZip() {
const file = peekZip(state.folder, state.images) || state.lastZip;
if (!file) { ui.toast("ยังไม่มีไฟล์ ZIP"); return; }
downloadFile(file);
ui.closeSheet();
ui.toast(`บันทึก ${file.name} ลงเครื่องแล้ว`);
}
// ── photo sheet ─────────────────────────────────────────────
async function openPhoto(id) {
const rec = await db.getImage(id);
@@ -509,6 +745,12 @@ async function deletePhoto(id) {
async function shareOnePhoto(id) {
const rec = await db.getImage(id);
if (!rec) return;
if (native.isNative()) {
const res = await native.shareItems([{ name: rec.name || "photo.jpg", blob: rec.blob }], rec.name || "");
ui.toast(res.ok ? "แชร์ผ่านระบบของ Android แล้ว" : res.reason === "cancelled" ? "ยกเลิก" : "แชร์ไม่สำเร็จ");
return;
}
const file = new File([rec.blob], rec.name || "photo.jpg", { type: "image/jpeg" });
if (!canShareFiles(file)) {
downloadFile(file);
@@ -533,6 +775,9 @@ async function showDiagnostics() {
["visualViewport", env.visualViewport],
["จอจริง (px)", env.screen],
["โหมดติดตั้ง", env.standalone ? "PWA (standalone)" : "เบราว์เซอร์"],
["โหมดแอป", native.nativeInfo().label],
["ปุ่มเสียง", native.isNative() ? "กดถ่ายรูปได้ (Volume up/down)" : "ใช้ได้เฉพาะใน APK"],
["ที่เก็บไฟล์", native.isNative() ? "Documents/CamCat (โฟลเดอร์จริงในเครื่อง)" : "Download ของเบราว์เซอร์"],
["ความปลอดภัย", env.secureContext ? "HTTPS — ใช้กล้องได้" : "ไม่ปลอดภัย — กล้องถูกบล็อก"],
["URL", env.url],
["สตรีมกล้อง", s.width ? `${s.width}×${s.height} @${Math.round(s.frameRate || 0)}fps` : "ยังไม่เปิด"],
@@ -576,11 +821,67 @@ async function copyLink() {
}
}
// ── สร้างโฟลเดอร์เร็ว / นำเข้า CSV ───────────────────────────
async function quickCreateFolder() {
await loadFolders();
const name = defaultFolderName(state.folders.map((f) => f.name));
const folder = { id: "f_" + Date.now(), name, createdAt: Date.now(), updatedAt: Date.now() };
await db.putFolder(folder);
await selectFolder(folder.id, { silent: true });
await loadFolders();
await render();
ui.toast("สร้าง " + name + " — เปลี่ยนชื่อได้ที่ปุ่มดินสอ");
}
function pickCsvFile() {
const input = document.createElement("input");
input.type = "file";
input.accept = ".csv,text/csv,text/plain";
input.style.display = "none";
input.addEventListener("change", async () => {
const file = input.files && input.files[0];
input.remove();
if (!file) return;
try {
const text = await file.text();
const { rows } = parseCsv(text);
if (!rows.length) { ui.toast("ไฟล์ CSV ไม่มีแถวข้อมูล"); return; }
await loadFolders();
const { items, errors } = planFolders(rows, state.folders.map((f) => f.name));
const now = Date.now();
for (let i = 0; i < items.length; i++) {
await db.putFolder({ id: `f_${now}_${i}`, name: items[i].name, createdAt: now + i, updatedAt: now + i });
}
await loadFolders();
if (items.length) {
const first = state.folders.find((f) => f.name === items[0].name);
if (first) await selectFolder(first.id, { silent: true });
}
await render();
ui.openSheet(
ui.importResultSheet({
created: items.length,
skipped: errors.length,
errors,
total: rows.length,
})
);
if (items.length) ui.toast(`สร้าง ${items.length} โฟลเดอร์จาก CSV`);
} catch (err) {
console.error(err);
ui.toast("อ่านไฟล์ CSV ไม่สำเร็จ: " + err.message);
}
});
document.body.appendChild(input);
input.click();
}
// ── folder modals ───────────────────────────────────────────
async function openNewFolder() {
await loadFolders();
const base = defaultFolderName();
const suggested = uniqueName(base, state.folders.map((f) => f.name));
const suggested = defaultFolderName(state.folders.map((f) => f.name));
ui.openSheet(ui.folderSheet("new", { suggested }));
setTimeout(() => document.getElementById("folder-name-input")?.select(), 60);
}
@@ -636,7 +937,7 @@ async function confirmDeleteFolder(id) {
if (state.folder?.id === id) {
if (state.folders.length) await selectFolder(state.folders[0].id, { silent: true });
else {
const folder = { id: "f_" + Date.now(), name: defaultFolderName(), createdAt: Date.now(), updatedAt: Date.now() };
const folder = { id: "f_" + Date.now(), name: defaultFolderName(state.folders.map((f) => f.name)), createdAt: Date.now(), updatedAt: Date.now() };
await db.putFolder(folder);
await loadFolders();
await selectFolder(folder.id, { silent: true });
@@ -665,6 +966,13 @@ document.addEventListener("click", async (e) => {
syncCam();
break;
}
case "toggle-ratio": {
state.ratio = state.ratio === "4:3" ? "3:4" : "4:3";
localStorage.setItem(LS_RATIO, state.ratio);
syncCam();
ui.toast("อัตราส่วนภาพ " + state.ratio + " (บันทึกแล้ว)");
break;
}
case "toggle-grid":
state.grid = !state.grid;
syncCam();
@@ -677,6 +985,12 @@ document.addEventListener("click", async (e) => {
await render();
break;
case "new-folder": await openNewFolder(); break;
case "quick-new-folder": await quickCreateFolder(); break;
case "csv-sheet": ui.openSheet(ui.csvSheet()); break;
case "pick-csv": pickCsvFile(); break;
case "zip-all": await zipAllFolders(); break;
case "share-zip-now": await shareCachedZip(); break;
case "save-zip": saveCachedZip(); break;
case "rename-folder": openRenameFolder(id); break;
case "delete-folder": {
const f = state.folders.find((x) => x.id === id);
@@ -690,6 +1004,7 @@ document.addEventListener("click", async (e) => {
case "open-photo": await openPhoto(id); break;
case "delete-photo": await deletePhoto(id); break;
case "share-photo": await shareOnePhoto(id); break;
case "rotate-photo": await rotatePhoto(id, Number(el.dataset.dir || 90)); break;
case "zip-download": await zipFlow("download"); break;
case "zip-share": await zipFlow("share"); break;
case "diagnostics": await showDiagnostics(); break;
@@ -746,6 +1061,11 @@ async function init() {
document.getElementById("app").dataset.view = state.view;
renderCameraView();
// ล็อกแนวตั้ง (APK) — กัน UI หมุนตามตอนถือแนวนอนแล้วถ่ายไม่ได้
if (native.isNative() && screen.orientation && screen.orientation.lock) {
try { await screen.orientation.lock("portrait"); } catch { /* เว็บจะThrow — ข้าม */ }
}
const wanted = new URLSearchParams(location.search).get("view");
if (wanted === "gallery" || wanted === "folders") {
await navigate(wanted);
@@ -760,4 +1080,20 @@ async function init() {
}
}
// ปุ่มเพิ่ม/ลดเสียง (ส่งมาจาก MainActivity ใน APK) = ชัตเตอร์
let lastVolumeShot = 0;
window.addEventListener("camcat:shutter", () => {
const now = Date.now();
if (now - lastVolumeShot < 600) return; // กดค้าง/กดรัว
lastVolumeShot = now;
if (state.view !== "camera" || !state.camReady || state.busy) return;
if (navigator.vibrate) { try { navigator.vibrate(12); } catch { /* ignore */ } }
shoot();
});
window.addEventListener("resize", () => fitFrame());
window.addEventListener("orientationchange", () => setTimeout(fitFrame, 250));
window.addEventListener("DOMContentLoaded", init);
// เปิดให้ตรวจสถานะภายในได้ (ใช้ตอน debug บนเครื่องจริง)
window.__camcat = { state, cam, native, version: APP_VERSION };
+58 -3
View File
@@ -23,10 +23,65 @@ export function bkkParts(date = new Date()) {
};
}
/** "Site A 2569-10-24" */
export function defaultFolderName(date = new Date()) {
/** "2569.10.25.21.45" — ปี พ.ศ..เดือน.วัน.ชั่วโมง.นาที */
export function folderStamp(date = new Date()) {
const p = bkkParts(date);
return `${SITE_LABEL} ${p.thaiYear}-${p.month}-${p.day}`;
return `${p.thaiYear}.${p.month}.${p.day}.${p.hour}.${p.minute}`;
}
/** 0→a, 25→z, 26→aa, 27→ab … (แบบคอลัมน์ Excel) */
export function letterForIndex(index) {
let n = Math.max(0, Math.trunc(index)) + 1;
let s = "";
while (n > 0) {
const r = (n - 1) % 26;
s = String.fromCharCode(97 + r) + s;
n = Math.floor((n - 1) / 26);
}
return s;
}
/** a→0, z→25, aa→26 … (คืน -1 ถ้าไม่ใช่ a-z ล้วน) */
export function indexForLetters(letters) {
const s = String(letters || "").trim().toLowerCase();
if (!/^[a-z]+$/.test(s)) return -1;
let n = 0;
for (const ch of s) n = n * 26 + (ch.charCodeAt(0) - 97 + 1);
return n - 1;
}
/** ตัวอักษรถัดไปจากชื่อโฟลเดอร์ที่มีอยู่: Site a …, Site b … */
export function nextLetter(existingNames = []) {
let max = -1;
for (const name of existingNames) {
const m = /^site\s+([a-z]+)\s+\d/.exec(String(name).toLowerCase());
if (m) max = Math.max(max, indexForLetters(m[1]));
}
return letterForIndex(max + 1);
}
/** ประกอบชื่อ: Site <letter> <stamp> */
export function makeFolderName({ site = SITE_LABEL, letter = "a", date = new Date(), datetime } = {}) {
return `${site} ${letter} ${datetime || folderStamp(date)}`;
}
/** ชื่อเริ่มต้นของโฟลเดอร์ใหม่ (ไล่ตัวอักษรอัตโนมัติ) */
export function defaultFolderName(existingNames = [], date = new Date()) {
return makeFolderName({ letter: nextLetter(existingNames), date });
}
/** ตรวจ/ทำความสะอาดค่า datetime จาก CSV → "2569.10.25.21.45" (คืน null ถ้าใช้ไม่ได้) */
export function normalizeFolderStamp(input, fallback = null) {
const raw = String(input ?? "").trim();
if (!raw) return fallback;
const nums = raw.match(/\d+/g);
if (!nums || nums.length < 3) return null;
const [y, mo, d, h = "0", mi = "0"] = nums.map((x) => Number(x));
const year = y > 2400 ? y : y + 543; // รับทั้ง ค.ศ. และ พ.ศ.
if (year < 2400 || year > 2700) return null;
if (mo < 1 || mo > 12 || d < 1 || d > 31 || h > 23 || mi > 59) return null;
const p2 = (n) => String(n).padStart(2, "0");
return `${year}.${p2(mo)}.${p2(d)}.${p2(h)}.${p2(mi)}`;
}
/** EXIF DateTimeOriginal: "YYYY:MM:DD HH:MM:SS" (เวลาไทย) */
+143
View File
@@ -0,0 +1,143 @@
// ── Native bridge (Capacitor / Android APK) ───────────────────
// ทำงานเมื่อรันใน APK เท่านั้น — บนเว็บทุกฟังก์ชันคืน null แล้วแอปใช้ทางเดิม
// ต้องมีปลั๊กอิน: @capacitor/filesystem, @capacitor/share
const cap = () => (typeof window !== "undefined" ? window.Capacitor : undefined);
export function isNative() {
try {
return !!(cap() && typeof cap().isNativePlatform === "function" && cap().isNativePlatform());
} catch { return false; }
}
export function platform() {
try { return cap()?.getPlatform?.() || "web"; } catch { return "web"; }
}
function plugin(name) {
return cap()?.Plugins?.[name] || null;
}
const MAX_NAME = 120;
function safeSeg(s, fallback = "file") {
const v = String(s ?? "")
.replace(/[\\/:*?"<>|\u0000-\u001f]/g, "-")
.replace(/\s+/g, " ")
.trim()
.replace(/^\.+/, "");
return (v || fallback).slice(0, MAX_NAME);
}
let lastDirLabel = "";
export function displayPath(folderName) {
return `${lastDirLabel || "Documents"}/CamCat/${safeSeg(folderName, "folder")}`;
}
/**
* เขียนไฟล์โดยไล่ directory ที่ใช้ได้:
* DOCUMENTS (Android ≤10 / เข้าถึงจากแอปอื่นได้) → EXTERNAL (app-specific, ใช้ได้ทุกเวอร์ชัน)
*/
async function writeWithFallback(fs, path, data) {
const tries = [
{ directory: "DOCUMENTS", label: "Documents" },
{ directory: "EXTERNAL", label: "Android/data/…/files" },
];
let lastErr = null;
for (const t of tries) {
try {
const res = await fs.writeFile({ path, data, directory: t.directory, recursive: true });
lastDirLabel = t.label;
return res?.uri || "ok";
} catch (err) { lastErr = err; }
}
throw lastErr || new Error("write failed");
}
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const r = new FileReader();
r.onload = () => {
const s = String(r.result || "");
resolve(s.slice(s.indexOf(",") + 1));
};
r.onerror = () => reject(r.error);
r.readAsDataURL(blob);
});
}
/** เขียนรูปลงโฟลเดอร์จริงบนเครื่อง: Documents/CamCat/<โฟลเดอร์>/<ไฟล์>.jpg */
export async function savePhoto(folderName, fileName, blob) {
if (!isNative()) return null;
const fs = plugin("Filesystem");
if (!fs) return null;
try {
const data = await blobToBase64(blob);
return await writeWithFallback(fs, `CamCat/${safeSeg(folderName, "folder")}/${safeSeg(fileName, "photo.jpg")}`, data);
} catch (err) {
console.warn("native savePhoto failed", err);
return null;
}
}
/** เขียนไฟล์ ZIP ลง Documents/CamCat-ZIP */
export async function saveZip(file) {
if (!isNative()) return null;
const fs = plugin("Filesystem");
if (!fs) return null;
try {
const data = await blobToBase64(file);
return await writeWithFallback(fs, `CamCat-ZIP/${safeSeg(file.name, "photos.zip")}`, data);
} catch (err) {
console.warn("native saveZip failed", err);
return null;
}
}
/**
* แชร์ไฟล์ (รูปเดี่ยว/หลายรูป/ZIP) ผ่าน share sheet ของ Android
* items = [{ name, blob }]
* หมายเหตุ: Android แชร์ "โฟลเดอร์" ทั้งโฟลเดอร์เป็น URI ไม่ได้ → ใช้หลายไฟล์ หรือ ZIP
*/
export async function shareItems(items, title = "") {
if (!isNative()) return { ok: false, reason: "notnative" };
const fs = plugin("Filesystem");
const share = plugin("Share");
if (!fs || !share) return { ok: false, reason: "noplugin" };
try {
const uris = [];
for (const it of items) {
const data = await blobToBase64(it.blob);
const res = await fs.writeFile({
path: `share/${Date.now()}-${safeSeg(it.name, "file")}`,
data,
directory: "CACHE",
recursive: true,
});
if (res?.uri) uris.push(res.uri);
}
if (!uris.length) return { ok: false, reason: "nofiles" };
await share.share({
title: title || (items.length === 1 ? items[0].name : "CamCat"),
dialogTitle: title || "แชร์ด้วย",
files: uris,
});
return { ok: true };
} catch (err) {
const msg = String(err?.message || err);
if (/cancel/i.test(msg)) return { ok: false, reason: "cancelled" };
console.warn("native share failed", err);
return { ok: false, reason: "failed", error: err };
}
}
/** จำนวนไฟล์ที่บันทึกลงเครื่องแล้ว (ใช้โชว์ใน diagnostics) */
export function nativeInfo() {
return {
native: isNative(),
platform: platform(),
label: isNative() ? `APK (${platform()})` : "เว็บ / PWA",
};
}
+223
View File
@@ -0,0 +1,223 @@
// ── จัดการทิศทางภาพ (auto-orient) ─────────────────────────────
// เป้าหมาย: รูปที่ถ่าย/แชร์ออกไปต้องตั้งตรงทุกแอป แม้แอปปลายทางไม่สนใจ EXIF
// วิธี: อ่าน EXIF Orientation → หมุนพิกเซลให้ตรง → เขียน Orientation = 1 กลับ
import { JPEG_QUALITY, THUMB_MAX, THUMB_QUALITY } from "./config.js";
import { blobToDataURL, dataURLToBlob } from "./exif.js";
/** ตาราง EXIF orientation 1-8 → การแปลงเพื่อให้ภาพตั้งตรง */
export const ORIENTATION_MATRIX = {
1: { rotate: 0, mirror: false },
2: { rotate: 0, mirror: true },
3: { rotate: 180, mirror: false },
4: { rotate: 180, mirror: true },
5: { rotate: 90, mirror: true },
6: { rotate: 90, mirror: false },
7: { rotate: 270, mirror: true },
8: { rotate: 270, mirror: false },
};
/** อ่านค่า Orientation จาก JPEG โดยตรง (fallback ถ้า piexif ไม่มี) */
export function readOrientationTag(bytes) {
try {
const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
if (u8[0] !== 0xff || u8[1] !== 0xd8) return 1;
let i = 2;
while (i < u8.length - 4) {
if (u8[i] !== 0xff) { i++; continue; }
const marker = u8[i + 1];
const len = (u8[i + 2] << 8) | u8[i + 3];
if (marker === 0xe1 && u8[i + 4] === 0x45 && u8[i + 5] === 0x78) {
const tiff = i + 10;
const little = u8[tiff] === 0x49;
const rd16 = (o) => (little ? u8[o] | (u8[o + 1] << 8) : (u8[o] << 8) | u8[o + 1]);
const rd32 = (o) => (little
? u8[o] | (u8[o + 1] << 8) | (u8[o + 2] << 16) | (u8[o + 3] << 24)
: (u8[o] << 24) | (u8[o + 1] << 16) | (u8[o + 2] << 8) | u8[o + 3]) >>> 0;
const ifd0 = tiff + rd32(tiff + 4);
const count = rd16(ifd0);
for (let k = 0; k < count; k++) {
const entry = ifd0 + 2 + k * 12;
if (rd16(entry) === 0x0112) return rd16(entry + 8);
}
return 1;
}
i += 2 + len;
}
return 1;
} catch { return 1; }
}
/** อ่านขนาดจริงจากหัวไฟล์ JPEG (SOF) — ใช้ตรวจว่าเบราว์เซอร์หมุนให้แล้วหรือยัง */
export async function jpegSize(blob) {
try {
const u8 = new Uint8Array(await blob.slice(0, 65536).arrayBuffer());
if (u8[0] !== 0xff || u8[1] !== 0xd8) return null;
let i = 2;
while (i < u8.length - 9) {
if (u8[i] !== 0xff) { i++; continue; }
const m = u8[i + 1];
if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) {
return { h: (u8[i + 5] << 8) | u8[i + 6], w: (u8[i + 7] << 8) | u8[i + 8] };
}
const len = (u8[i + 2] << 8) | u8[i + 3];
if (!len) return null;
i += 2 + len;
}
return null;
} catch { return null; }
}
/** หมุน/พลิกพิกเซลด้วย canvas */
export async function transformImage(blob, rotateDeg = 0, mirror = false) {
const bmp = await createImageBitmap(blob, { imageOrientation: "none" });
const swap = Math.abs(rotateDeg) % 180 === 90;
const w = swap ? bmp.height : bmp.width;
const h = swap ? bmp.width : bmp.height;
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext("2d");
ctx.translate(w / 2, h / 2);
ctx.rotate((rotateDeg * Math.PI) / 180);
if (mirror) ctx.scale(-1, 1);
ctx.drawImage(bmp, -bmp.width / 2, -bmp.height / 2);
bmp.close?.();
const out = await new Promise((res) => canvas.toBlob(res, "image/jpeg", JPEG_QUALITY));
return { blob: out || blob, width: w, height: h, rotated: rotateDeg !== 0 || mirror };
}
async function makeThumb(blob) {
try {
const bmp = await createImageBitmap(blob, { imageOrientation: "none" });
const scale = Math.min(1, THUMB_MAX / Math.max(bmp.width, bmp.height));
const w = Math.max(1, Math.round(bmp.width * scale));
const h = Math.max(1, Math.round(bmp.height * scale));
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
canvas.getContext("2d").drawImage(bmp, 0, 0, w, h);
bmp.close?.();
return await new Promise((res) => canvas.toBlob(res, "image/jpeg", THUMB_QUALITY));
} catch { return blob; }
}
/**
* ปรับภาพให้ตั้งตรง
* - exifOrientation: ค่าจาก readExif() (ถ้ามี)
* - mirrorFront: true = กล้องหน้า → พลิกซ้าย-ขวาให้เหมือนพรีวิว (ค่าเริ่มต้น false)
* คืน { blob, width, height, rotation, mirrored, source }
*/
export async function autoOrient({ blob, exifOrientation = 1, width, height, mirrorFront = false, facing = "environment" }) {
const tag = ORIENTATION_MATRIX[exifOrientation] ? exifOrientation : 1;
const plan = ORIENTATION_MATRIX[tag];
// กล้องหน้า: พรีวิวถูก mirror แต่ไฟล์ดิบไม่ mirror → พลิกให้ตรงกับที่เห็น
const mirror = plan.mirror || (mirrorFront && facing === "user");
const rotate = plan.rotate;
if (!rotate && !mirror) {
return { blob, width: width || 0, height: height || 0, rotation: 0, mirrored: false, source: "none" };
}
// เบราว์เซอร์หมุนตาม EXIF ให้เองหรือไม่ (Chrome/Android = ใช่) — ตรวจครั้งเดียวแล้ว cache
if (await browserAppliesExif()) {
const probe = await createImageBitmap(blob);
const pw = probe.width, ph = probe.height;
probe.close?.();
const baked = await bakeToJpeg(blob);
if (mirror) {
const flipped = await transformImage(baked, 0, true);
return { ...flipped, width: pw, height: ph, rotation: 0, mirrored: true, source: `browser:${tag}+mirror` };
}
return { blob: baked, width: pw, height: ph, rotation: 0, mirrored: false, source: `browser:${tag}` };
}
// เบราว์เซอร์ไม่สนใจ EXIF → หมุนพิกเซลเองตามตาราง
const out = await transformImage(blob, rotate, mirror);
return {
...out,
rotation: rotate,
mirrored: mirror,
source: `exif:${tag}${mirrorFront && facing === "user" ? "+front" : ""}`,
};
}
let _exifSupport = null;
/** ทดสอบว่า createImageBitmap หมุนตาม EXIF ให้หรือไม่ (cache ผลไว้) */
async function browserAppliesExif() {
if (_exifSupport !== null) return _exifSupport;
try {
const px = window.piexif;
if (!px) { _exifSupport = true; return true; }
const c = document.createElement("canvas");
c.width = 40; c.height = 20;
c.getContext("2d").fillRect(0, 0, 40, 20);
const plain = await new Promise((r) => c.toBlob(r, "image/jpeg", 0.9));
const durl = await blobToDataURL(plain);
const raw = px.load(durl);
raw["0th"][274] = 6;
const tagged = dataURLToBlob(px.insert(px.dump(raw), durl));
const bmp = await createImageBitmap(tagged);
_exifSupport = bmp.width === 20 && bmp.height === 40;
bmp.close?.();
} catch { _exifSupport = true; }
return _exifSupport;
}
/** วาดภาพตามที่เบราว์เซอร์แสดง (bake) แล้วคืน JPEG ที่ไม่มี EXIF */
async function bakeToJpeg(blob) {
const bmp = await createImageBitmap(blob);
const canvas = document.createElement("canvas");
canvas.width = bmp.width;
canvas.height = bmp.height;
canvas.getContext("2d").drawImage(bmp, 0, 0);
bmp.close?.();
const out = await new Promise((res) => canvas.toBlob(res, "image/jpeg", JPEG_QUALITY));
return out || blob;
}
/** ครอปกลางภาพตามอัตราส่วน (4:3 = 1.333, 3:4 = 0.75) */
export async function cropToRatio(blob, ratio) {
try {
const bmp = await createImageBitmap(blob, { imageOrientation: "none" });
const w = bmp.width, h = bmp.height;
const src = w / h;
let sw = w, sh = h, sx = 0, sy = 0;
if (src > ratio + 0.002) { sw = Math.round(h * ratio); sx = Math.round((w - sw) / 2); }
else if (src < ratio - 0.002) { sh = Math.round(w / ratio); sy = Math.round((h - sh) / 2); }
if (sw === w && sh === h) { bmp.close?.(); return { blob, width: w, height: h }; }
const canvas = document.createElement("canvas");
canvas.width = sw; canvas.height = sh;
canvas.getContext("2d").drawImage(bmp, sx, sy, sw, sh, 0, 0, sw, sh);
bmp.close?.();
const out = await new Promise((res) => canvas.toBlob(res, "image/jpeg", JPEG_QUALITY));
return { blob: out || blob, width: sw, height: sh };
} catch { return { blob, width: 0, height: 0 }; }
}
/** "4:3" → 1.333 */
export function ratioValue(label) {
const m = /^(\d+)\s*[:x/]\s*(\d+)$/.exec(String(label || ""));
if (!m) return 4 / 3;
const a = Number(m[1]), b = Number(m[2]);
return b ? a / b : 4 / 3;
}
/** หมุนภาพตามองศา (ใช้กับปุ่มหมุนในชีตรูป) และสร้าง thumb ใหม่ */
export async function rotateBlob(blob, deg) {
const out = await transformImage(blob, deg, false);
const thumb = await makeThumb(out.blob);
return { ...out, thumb };
}
/** อ่าน orientation จาก blob แล้วคืนค่าตัวเลข 1-8 */
export async function detectOrientation(blob) {
try {
const buf = await blob.arrayBuffer();
return readOrientationTag(new Uint8Array(buf));
} catch { return 1; }
}
export { makeThumb as makeThumbFromBlob };
+105 -10
View File
@@ -64,9 +64,12 @@ export function cameraShell() {
return `
<div id="camera-view">
<div class="stage">
<video id="video" autoplay playsinline muted></video>
<div class="grid-lines" id="grid-lines"></div>
<div class="frame ratio-43" id="cam-frame">
<video id="video" autoplay playsinline muted></video>
<div class="grid-lines" id="grid-lines"></div>
</div>
<div class="cam-top">
<button class="cam-chip ratio-chip" type="button" id="chip-ratio" data-action="toggle-ratio" aria-label="สลับอัตราส่วนภาพ 4:3 / 3:4">4:3</button>
<button class="cam-chip" type="button" data-action="toggle-grid" aria-label="เส้นแบ่ง 3 ส่วน">${ICON.grid}</button>
<button class="cam-chip" type="button" id="chip-torch" data-action="toggle-torch" aria-pressed="false" aria-label="ไฟแฟลช" hidden>${ICON.torch}</button>
<button class="cam-chip" type="button" data-action="switch-camera" aria-label="สลับกล้องหน้า/หลัง">${ICON.flip}</button>
@@ -106,7 +109,7 @@ export function hero(kind, { title, text = "", steps = [], action = null, note =
</div>`;
}
export function syncCameraControls({ torchAvailable, torchOn, zoomRange, zoomValue, gridOn, count, thumbUrl, ready }) {
export function syncCameraControls({ torchAvailable, torchOn, zoomRange, zoomValue, gridOn, count, thumbUrl, ready, ratio }) {
const chip = document.getElementById("chip-torch");
if (chip) {
chip.hidden = !torchAvailable;
@@ -134,6 +137,15 @@ export function syncCameraControls({ torchAvailable, torchOn, zoomRange, zoomVal
}
}
const frame = document.getElementById("cam-frame");
const ratioChip = document.getElementById("chip-ratio");
if (frame) {
const portrait = ratio === "3:4";
frame.classList.toggle("ratio-43", !portrait);
frame.classList.toggle("ratio-34", portrait);
}
if (ratioChip) ratioChip.textContent = ratio || "4:3";
const grid = document.getElementById("grid-lines");
if (grid) grid.classList.toggle("on", !!gridOn);
const cnt = document.getElementById("shot-count");
@@ -147,9 +159,12 @@ export function syncCameraControls({ torchAvailable, torchOn, zoomRange, zoomVal
// ── Folders ──
export function renderFolders({ folders, counts, activeId, storage }) {
const total = counts.reduce((a, b) => a + b, 0);
let html = `<div class="section-head">
let html = `<div class="folder-view"><div class="section-head">
<div><h2>โฟลเดอร์</h2><div class="sub">${folders.length} โฟลเดอร์ · ${total} รูป</div></div>
<button class="btn btn-primary" type="button" data-action="new-folder">+ โฟลเดอร์ใหม่</button>
<div class="head-btns">
<button class="btn btn-ghost" type="button" data-action="csv-sheet">CSV</button>
<button class="btn btn-primary" type="button" data-action="new-folder">+ โฟลเดอร์ใหม่</button>
</div>
</div>`;
if (!folders.length) {
@@ -173,11 +188,17 @@ export function renderFolders({ folders, counts, activeId, storage }) {
html += `</div>`;
}
html += `<div class="folder-bulk">
<button class="btn btn-ghost btn-block" type="button" data-action="zip-all">${ICON.zip} ZIP ทุกโฟลเดอร์ (${total} รูป)</button>
</div>`;
html += `<div class="storage-line">
พื้นที่เก็บในเครื่อง${storage ? ` · ใช้ ${fmtBytes(storage.usage)} จาก ${fmtBytes(storage.quota)}` : ""}
<br><button class="btn btn-ghost" type="button" style="min-height:34px;height:34px;font-size:11px;margin-top:8px" data-action="diagnostics">ข้อมูลอุปกรณ์และกล้อง</button>
<button class="btn btn-ghost" type="button" style="min-height:34px;height:34px;font-size:11px;margin-top:8px;margin-left:6px" data-action="show-qr">QR ลิงก์ทดสอบ</button>
</div>`;
html += `</div>`;
return html;
}
@@ -205,9 +226,8 @@ export function renderGallery({ folder, images, thumbUrl }) {
html += `</div>`;
html += `<div class="action-bar">
<button class="btn btn-ghost" type="button" data-action="zip-download">${ICON.zip} ZIP (${images.length})</button>
<button class="btn btn-primary" type="button" data-action="zip-share">${ICON.share} แชร์ ZIP</button>
</div>`;
<button class="btn btn-primary btn-block" type="button" data-action="zip-download">${ICON.zip} ZIP โฟลเดอร์นี้ (${images.length} รูป)</button>
</div></div>`;
return html;
}
@@ -234,6 +254,12 @@ export function photoSheet({ record, url, folderName }) {
}
if (m.exif?.orientation) rows.push(["Orientation", String(m.exif.orientation)]);
if (m.exif?.dateTimeOriginal) rows.push(["EXIF DateTimeOriginal", m.exif.dateTimeOriginal]);
if (m.exif?.software) rows.push(["Software", m.exif.software]);
if (m.exif?.gps?.dateStamp) {
const t = Array.isArray(m.exif.gps.timeStamp) ? m.exif.gps.timeStamp.map((x) => String(Math.round(x)).padStart(2, "0")).join(":") : "";
rows.push(["GPS date/time", `${m.exif.gps.dateStamp}${t ? " " + t : ""}`]);
}
if (m.exif?.uniqueId) rows.push(["ImageUniqueID", m.exif.uniqueId.slice(0, 16) + "…"]);
const rowsHtml = rows
.map(([k, v]) => `<div class="row"><span class="k">${esc(k)}</span><span class="v">${esc(v)}</span></div>`)
@@ -244,7 +270,18 @@ export function photoSheet({ record, url, folderName }) {
<div class="hint">${esc(humanDateTime(record.createdAt))}</div>
<img class="preview" src="${url}" alt="">
<div class="meta-table">${rowsHtml}</div>
<div class="hint" style="margin-top:10px;margin-bottom:0">ข้อมูลทั้งหมดฝังอยู่ในไฟล์ JPEG (EXIF) แล้ว — ติดไปกับรูปตอนแชร์/ดาวน์โหลด ไม่มีไฟล์แยก</div>
<div class="sheet-actions" style="margin-top:14px">
<button class="btn btn-ghost" type="button" data-action="rotate-photo" data-id="${esc(record.id)}" data-dir="-90" aria-label="หมุนซ้าย 90 องศา">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12a10 10 0 1 0 3-7"/><path d="M2 3v6h6"/></svg>
ซ้าย
</button>
<button class="btn btn-ghost" type="button" data-action="rotate-photo" data-id="${esc(record.id)}" data-dir="90" aria-label="หมุนขวา 90 องศา">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 12a10 10 0 1 1-3-7"/><path d="M22 3v6h-6"/></svg>
ขวา
</button>
</div>
<div class="sheet-actions" style="margin-top:8px">
<button class="btn btn-ghost" type="button" data-action="close-sheet">ปิด</button>
<button class="btn btn-primary" type="button" data-action="share-photo" data-id="${esc(record.id)}">${ICON.share} แชร์รูปนี้</button>
</div>
@@ -265,9 +302,9 @@ export function folderSheet(mode, { id = "", name = "", suggested = "", count =
}
const isNew = mode === "new";
return `<h3>${isNew ? "โฟลเดอร์ใหม่" : "เปลี่ยนชื่อโฟลเดอร์"}</h3>
<div class="hint">ชื่อเริ่มต้นอิงวันที่ไทย (พ.ศ.) ของวันนี้ — แก้ไขได้</div>
<div class="hint">ชื่อเริ่มต้น = Site + ตัวอักษรถัดไป + ปี.เดือน.วัน.ชั่วโมง.นาที (แก้ได้)</div>
<input id="folder-name-input" type="text" inputmode="text" autocomplete="off"
value="${esc(isNew ? suggested : name)}" placeholder="Site A 2569-10-24">
value="${esc(isNew ? suggested : name)}" placeholder="Site a 2569.10.25.21.45">
${isNew ? `<div class="hint" style="margin-top:-6px">ถ้าชื่อซ้ำ ระบบจะเติม (2) ให้อัตโนมัติ</div>` : ""}
<div class="sheet-actions">
<button class="btn btn-ghost" type="button" data-action="close-sheet">ยกเลิก</button>
@@ -290,6 +327,64 @@ export function qrSheet(url) {
</div></div>`;
}
// ── CSV import ──────────────────────────────────────────────
export function csvSheet() {
return `<h3>นำเข้าโฟลเดอร์จาก CSV</h3>
<div class="hint">สร้างทีละหลายโฟลเดอร์ในครั้งเดียว — ชื่อที่ได้จะใช้กฎ Site + ตัวอักษร + ปี.เดือน.วัน.ชั่วโมง.นาที</div>
<div class="meta-table">
<div class="row"><span class="k">site</span><span class="v">คำนำหน้า เช่น Site (เว้นว่าง = Site)</span></div>
<div class="row"><span class="k">letter</span><span class="v">a…z, aa… (เว้นว่าง = ไล่ต่ออัตโนมัติ)</span></div>
<div class="row"><span class="k">datetime</span><span class="v">2569.10.25.21.45</span></div>
<div class="row"><span class="k">name</span><span class="v">ชื่อเต็ม (ถ้าใส่ จะทับชื่อที่ประกอบ)</span></div>
</div>
<div class="hint" style="margin-top:12px">ตัวอย่างแถว<br><code>Site,a,2569.10.25.21.45,</code><br><code>Site,b,2569.10.25.22.10,</code></div>
<div class="sheet-actions" style="margin-top:12px">
<a class="btn btn-ghost" href="templates/folders-template.csv" download="folders-template.csv">ไฟล์เปล่า</a>
<button class="btn btn-primary" type="button" data-action="pick-csv">เลือกไฟล์ CSV</button>
</div>
<div class="sheet-actions" style="margin-top:8px">
<button class="btn btn-ghost btn-block" type="button" data-action="close-sheet">ปิด</button>
</div>`;
}
export function importResultSheet({ created, skipped, errors = [], total }) {
const list = errors.length
? `<div class="notice" style="margin:12px 0 0">
<b>ข้าม ${skipped} แถว</b>
<ol>${errors.slice(0, 12).map((e) => `<li>แถว ${e.row}: ${esc(e.reason)}</li>`).join("")}</ol>
${errors.length > 12 ? `<div style="margin-top:6px">…อีก ${errors.length - 12} แถว</div>` : ""}
</div>`
: "";
return `<h3>สร้างโฟลเดอร์แล้ว ${created} รายการ</h3>
<div class="hint">อ่าน ${total} แถว · สำเร็จ ${created} · ข้าม ${skipped}</div>
${list}
<div class="sheet-actions" style="margin-top:14px">
<button class="btn btn-primary btn-block" type="button" data-action="close-sheet">เรียบร้อย</button>
</div>`;
}
// ── พร้อมแชร์ (หลังสร้าง ZIP) ────────────────────────────────
export function shareReadySheet({ name, size, canShare, reason }) {
const status = canShare ? "พร้อมส่งเข้าแอปอื่น" : "เบราว์เซอร์นี้ไม่รองรับการแชร์ไฟล์";
const note = canShare
? "แตะปุ่มด้านล่างเพื่อเปิด share sheet ของ Samsung"
: "บันทึกไฟล์แล้วแชร์ผ่าน Files/My Files หรือเปิดด้วย Chrome";
return `<h3>ZIP พร้อมแล้ว</h3>
<div class="meta-table">
<div class="row"><span class="k">ไฟล์</span><span class="v">${esc(name)}</span></div>
<div class="row"><span class="k">ขนาด</span><span class="v">${esc(fmtBytes(size))}</span></div>
<div class="row"><span class="k">การแชร์</span><span class="v">${esc(status)}</span></div>
</div>
<div class="hint" style="margin-top:12px">${esc(note)}${reason ? " · " + esc(reason) : ""}</div>
<div class="sheet-actions">
<button class="btn btn-ghost" type="button" data-action="save-zip">บันทึกไฟล์</button>
<button class="btn btn-primary" type="button" data-action="share-zip-now" ${canShare ? "" : "disabled"}>แชร์ไปแอปอื่น</button>
</div>
<div class="sheet-actions" style="margin-top:8px">
<button class="btn btn-ghost btn-block" type="button" data-action="close-sheet">ปิด</button>
</div>`;
}
// ── Diagnostics ──
export function diagnosticsSheet(rows) {
const body = rows