create branch dev and commit code
This commit is contained in:
parent
3b70cc9fe8
commit
ea68fa5cc4
44 changed files with 12421 additions and 214 deletions
833
src/routes/(authed)/tools/adv-upload/+page.svelte
Normal file
833
src/routes/(authed)/tools/adv-upload/+page.svelte
Normal file
|
|
@ -0,0 +1,833 @@
|
|||
<script lang="ts">
|
||||
import { auth } from '$lib/core/stores/auth';
|
||||
import { addNotification } from '$lib/core/stores/noti';
|
||||
import Button from '$lib/components/ui/button/button.svelte';
|
||||
import Label from '$lib/components/ui/label/label.svelte';
|
||||
import * as Card from '$lib/components/ui/card/index.js';
|
||||
import * as Select from '$lib/components/ui/select/index.js';
|
||||
import Badge from '$lib/components/ui/badge/badge.svelte';
|
||||
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
|
||||
import Progress from '$lib/components/ui/progress/progress.svelte';
|
||||
import { Upload, X, Video, CheckCircle, AlertCircle, MonitorPlay } from '@lucide/svelte/icons';
|
||||
import * as adb from '$lib/core/adb/adb';
|
||||
import { AdbInstance } from '../../../state.svelte';
|
||||
|
||||
const UPLOAD_PROXY_ENDPOINT = '/api/adv-upload';
|
||||
const MANIFEST_PROXY_ENDPOINT = '/api/adv-manifest';
|
||||
const MANIFEST_FILENAME = 'sync_1.file';
|
||||
const ALLOWED_EXTENSIONS = ['.mp4'];
|
||||
const MACHINE_PROJECT_DIR = '/sdcard/coffeevending/taobin_project';
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// CONFIG — choose how the sync_1.file manifest is built (change this value).
|
||||
// Either way the manifest lists ONLY the selected/active set, never the whole
|
||||
// FTP folder (production keeps many inactive variants in the folder).
|
||||
// 'ftp_listdir' = manifest built (in the browser) from the files you upload
|
||||
// this session. No ADB, doesn't touch the machine. Recommended.
|
||||
// 'machine' = original flow. On Upload it: rm -rf the machine adv folder,
|
||||
// pushes the selected .mp4 (from the browser), then
|
||||
// `ls -l > sync_1.file` on the machine, pulls it, uploads it.
|
||||
// ⚠️ FULL REPLACE — requires ADB; select the COMPLETE adv set.
|
||||
//const MANIFEST_MODE: 'ftp_listdir' | 'machine' = 'ftp_listdir';
|
||||
const MANIFEST_MODE: 'ftp_listdir' | 'machine' = 'machine';
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// adv folder on the machine. Domestic Thailand uses the flat folder; every
|
||||
// international country uses inter/<country>/adv (matches the on-machine and
|
||||
// taobin_project source structure).
|
||||
function machineAdvDir(country: string): string {
|
||||
return country === 'tha'
|
||||
? `${MACHINE_PROJECT_DIR}/adv`
|
||||
: `${MACHINE_PROJECT_DIR}/inter/${country}/adv`;
|
||||
}
|
||||
|
||||
// Each country can target a different SFTP host (configured on the backend
|
||||
// via ADV_SFTP_COUNTRY_CONFIG). The selected country is sent with the upload.
|
||||
const COUNTRIES = [
|
||||
{ value: 'tha', label: 'Thailand (tha)' },
|
||||
{ value: 'mys', label: 'Malaysia (mys)' },
|
||||
{ value: 'aus', label: 'Australia (aus)' },
|
||||
{ value: 'sgp', label: 'Singapore (sgp)' },
|
||||
{ value: 'hkg', label: 'Hong Kong (hkg)' },
|
||||
{ value: 'gbr', label: 'United Kingdom (gbr)' },
|
||||
{ value: 'uae_dubai', label: 'UAE Dubai (uae_dubai)' },
|
||||
{ value: 'ltu', label: 'Lithuania (ltu)' },
|
||||
{ value: 'rou', label: 'Romania (rou)' },
|
||||
{ value: 'lva', label: 'Latvia (lva)' },
|
||||
{ value: 'est', label: 'Estonia (est)' }
|
||||
];
|
||||
|
||||
let selectedCountry = $state('tha');
|
||||
|
||||
// Expected dimensions are derived from the filename convention.
|
||||
const ADV_SPECS = {
|
||||
menu: { width: 1080, height: 380, label: 'Menu banner', pattern: /^taobin_adv_menu_[a-z0-9]+\.mp4$/i },
|
||||
fullscreen: { width: 1080, height: 608, label: 'Fullscreen / Idle', pattern: /^taobin_adv_[a-z0-9]+\.mp4$/i }
|
||||
} as const;
|
||||
|
||||
type AdvCategory = 'menu' | 'fullscreen' | 'invalid';
|
||||
|
||||
interface AdvFileItem {
|
||||
id: string;
|
||||
file: File;
|
||||
preview: string;
|
||||
status: 'pending' | 'uploading' | 'success' | 'error';
|
||||
error?: string;
|
||||
category: AdvCategory;
|
||||
expectedWidth?: number;
|
||||
expectedHeight?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
dimChecked: boolean;
|
||||
dimOk: boolean;
|
||||
}
|
||||
|
||||
let files = $state<AdvFileItem[]>([]);
|
||||
let uploading = $state(false);
|
||||
let uploadProgress = $state({ current: 0, total: 0 });
|
||||
let dragOver = $state(false);
|
||||
|
||||
// Push-to-machine (ADB) state
|
||||
let isAdbConnected = $derived(Boolean(AdbInstance.instance));
|
||||
let pushingToMachine = $state(false);
|
||||
let pushProgress = $state({ current: 0, total: 0, name: '', percent: 0 });
|
||||
|
||||
let generatingManifest = $state(false);
|
||||
|
||||
function generateId() {
|
||||
return Math.random().toString(36).substring(2, 9);
|
||||
}
|
||||
|
||||
// Classify by filename. Menu must be checked before fullscreen because a menu
|
||||
// name also satisfies the broader fullscreen pattern.
|
||||
function classify(name: string): { category: AdvCategory; width?: number; height?: number } {
|
||||
const lower = name.toLowerCase();
|
||||
if (!lower.endsWith('.mp4')) return { category: 'invalid' };
|
||||
if (ADV_SPECS.menu.pattern.test(lower)) {
|
||||
return { category: 'menu', width: ADV_SPECS.menu.width, height: ADV_SPECS.menu.height };
|
||||
}
|
||||
if (ADV_SPECS.fullscreen.pattern.test(lower)) {
|
||||
return {
|
||||
category: 'fullscreen',
|
||||
width: ADV_SPECS.fullscreen.width,
|
||||
height: ADV_SPECS.fullscreen.height
|
||||
};
|
||||
}
|
||||
return { category: 'invalid' };
|
||||
}
|
||||
|
||||
function readVideoDimensions(file: File): Promise<{ width: number; height: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const video = document.createElement('video');
|
||||
video.preload = 'metadata';
|
||||
const url = URL.createObjectURL(file);
|
||||
video.onloadedmetadata = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
resolve({ width: video.videoWidth, height: video.videoHeight });
|
||||
};
|
||||
video.onerror = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
reject(new Error('Cannot read video metadata'));
|
||||
};
|
||||
video.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
function handleFileSelect(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
if (input.files) {
|
||||
addFiles(Array.from(input.files));
|
||||
}
|
||||
input.value = '';
|
||||
}
|
||||
|
||||
function handleDrop(event: DragEvent) {
|
||||
event.preventDefault();
|
||||
dragOver = false;
|
||||
if (event.dataTransfer?.files) {
|
||||
addFiles(Array.from(event.dataTransfer.files));
|
||||
}
|
||||
}
|
||||
|
||||
function handleDragOver(event: DragEvent) {
|
||||
event.preventDefault();
|
||||
dragOver = true;
|
||||
}
|
||||
|
||||
function handleDragLeave() {
|
||||
dragOver = false;
|
||||
}
|
||||
|
||||
function addFiles(newFiles: File[]) {
|
||||
const toAdd: AdvFileItem[] = [];
|
||||
|
||||
for (const file of newFiles) {
|
||||
const ext = '.' + file.name.split('.').pop()?.toLowerCase();
|
||||
if (!ALLOWED_EXTENSIONS.includes(ext)) {
|
||||
addNotification(`WARN:${file.name} - Only .mp4 allowed`);
|
||||
continue;
|
||||
}
|
||||
if (files.some((f) => f.file.name === file.name)) {
|
||||
addNotification(`WARN:${file.name} - Already added`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const { category, width, height } = classify(file.name);
|
||||
if (category === 'invalid') {
|
||||
addNotification(
|
||||
`WARN:${file.name} - Name must be taobin_adv_*.mp4 or taobin_adv_menu_*.mp4`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
toAdd.push({
|
||||
id: generateId(),
|
||||
file,
|
||||
preview: URL.createObjectURL(file),
|
||||
status: 'pending',
|
||||
category,
|
||||
expectedWidth: width,
|
||||
expectedHeight: height,
|
||||
dimChecked: false,
|
||||
dimOk: false
|
||||
});
|
||||
}
|
||||
|
||||
if (toAdd.length === 0) return;
|
||||
files = [...files, ...toAdd];
|
||||
|
||||
// Read each video's real dimensions and validate against the spec.
|
||||
for (const item of toAdd) {
|
||||
readVideoDimensions(item.file)
|
||||
.then(({ width, height }) => {
|
||||
const index = files.findIndex((f) => f.id === item.id);
|
||||
if (index === -1) return;
|
||||
const ok = width === item.expectedWidth && height === item.expectedHeight;
|
||||
files[index].width = width;
|
||||
files[index].height = height;
|
||||
files[index].dimChecked = true;
|
||||
files[index].dimOk = ok;
|
||||
if (!ok) {
|
||||
files[index].status = 'error';
|
||||
files[index].error = `Size ${width}x${height}, expected ${item.expectedWidth}x${item.expectedHeight}`;
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
const index = files.findIndex((f) => f.id === item.id);
|
||||
if (index === -1) return;
|
||||
files[index].dimChecked = true;
|
||||
files[index].dimOk = false;
|
||||
files[index].status = 'error';
|
||||
files[index].error = 'Cannot read video dimensions';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function removeFile(id: string) {
|
||||
const item = files.find((f) => f.id === id);
|
||||
if (item) URL.revokeObjectURL(item.preview);
|
||||
files = files.filter((f) => f.id !== id);
|
||||
}
|
||||
|
||||
function clearAllFiles() {
|
||||
files.forEach((f) => URL.revokeObjectURL(f.preview));
|
||||
files = [];
|
||||
}
|
||||
|
||||
// A video that passed name + dimension validation (eligible for push/upload).
|
||||
function isValidVideo(item: AdvFileItem) {
|
||||
return item.dimChecked && item.dimOk && item.category !== 'invalid';
|
||||
}
|
||||
|
||||
function isUploadable(item: AdvFileItem) {
|
||||
return isValidVideo(item) && (item.status === 'pending' || item.status === 'error');
|
||||
}
|
||||
|
||||
const uploadableCount = $derived(files.filter(isUploadable).length);
|
||||
const validVideoCount = $derived(files.filter(isValidVideo).length);
|
||||
|
||||
// Step 1 (mirrors original sync.sh): push the valid videos to the connected
|
||||
// machine via ADB so you can preview them before sending to the server.
|
||||
async function pushToMachine() {
|
||||
if (!AdbInstance.instance) {
|
||||
addNotification('ERR:Machine not connected (ADB)');
|
||||
return;
|
||||
}
|
||||
const targets = files.filter(isValidVideo);
|
||||
if (targets.length === 0) {
|
||||
addNotification('WARN:No valid videos to push');
|
||||
return;
|
||||
}
|
||||
|
||||
const targetDir = machineAdvDir(selectedCountry);
|
||||
|
||||
pushingToMachine = true;
|
||||
pushProgress = { current: 0, total: targets.length, name: '', percent: 0 };
|
||||
|
||||
let success = 0;
|
||||
try {
|
||||
for (let i = 0; i < targets.length; i++) {
|
||||
const item = targets[i];
|
||||
pushProgress = { current: i, total: targets.length, name: item.file.name, percent: 0 };
|
||||
|
||||
const bytes = new Uint8Array(await item.file.arrayBuffer());
|
||||
const ok = await adb.pushBinary(
|
||||
`${targetDir}/${item.file.name}`,
|
||||
bytes,
|
||||
(sent, total) => {
|
||||
pushProgress = {
|
||||
current: i,
|
||||
total: targets.length,
|
||||
name: item.file.name,
|
||||
percent: total > 0 ? Math.round((sent / total) * 100) : 0
|
||||
};
|
||||
}
|
||||
);
|
||||
if (ok) {
|
||||
success++;
|
||||
pushProgress = { current: i + 1, total: targets.length, name: item.file.name, percent: 100 };
|
||||
} else {
|
||||
addNotification(`ERR:Push failed: ${item.file.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (success > 0) {
|
||||
addNotification(`INFO:Pushed ${success} video(s) to machine (${targetDir})`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Adv] push to machine error:', error);
|
||||
addNotification(`ERR:Push error: ${error instanceof Error ? error.message : 'unknown'}`);
|
||||
} finally {
|
||||
pushingToMachine = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadFiles() {
|
||||
const currentUser = $auth;
|
||||
if (!currentUser) {
|
||||
addNotification('ERR:Not logged in');
|
||||
return;
|
||||
}
|
||||
|
||||
const pendingFiles = files.filter(isUploadable);
|
||||
if (pendingFiles.length === 0) {
|
||||
addNotification('WARN:No valid files to upload');
|
||||
return;
|
||||
}
|
||||
|
||||
const uid = currentUser.uid;
|
||||
const displayName = currentUser.displayName || 'unknown';
|
||||
const email = currentUser.email || 'unknown@email.com';
|
||||
|
||||
// Method 2 mirrors the original flow: make the machine's adv folder hold
|
||||
// EXACTLY the selected set (rm -rf + push) BEFORE its ls -l manifest is
|
||||
// generated — so machine = FTP = manifest. The .mp4 still come from the
|
||||
// browser (the dragged files), only the manifest comes from the machine.
|
||||
if (MANIFEST_MODE === 'machine') {
|
||||
const synced = await syncMachineFolder(pendingFiles);
|
||||
if (!synced) return;
|
||||
}
|
||||
|
||||
uploading = true;
|
||||
uploadProgress = { current: 0, total: pendingFiles.length };
|
||||
|
||||
for (let i = 0; i < pendingFiles.length; i++) {
|
||||
const item = pendingFiles[i];
|
||||
const index = files.findIndex((f) => f.id === item.id);
|
||||
if (index === -1) continue;
|
||||
|
||||
files[index].status = 'uploading';
|
||||
files[index].error = undefined;
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('country', selectedCountry);
|
||||
formData.append('uid', uid);
|
||||
formData.append('displayName', displayName);
|
||||
formData.append('email', email);
|
||||
formData.append('file', item.file);
|
||||
// Manifest is built from the selected set (method 1) or the machine
|
||||
// (method 2) — never from the whole FTP folder. So tell the backend
|
||||
// not to rebuild it from the FTP listing.
|
||||
formData.append('regenerate', 'false');
|
||||
|
||||
const response = await fetch(UPLOAD_PROXY_ENDPOINT, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ detail: response.statusText }));
|
||||
throw new Error(errorData.detail || errorData.message || 'Upload failed');
|
||||
}
|
||||
|
||||
files[index].status = 'success';
|
||||
uploadProgress = { current: i + 1, total: pendingFiles.length };
|
||||
} catch (error) {
|
||||
files[index].status = 'error';
|
||||
files[index].error = error instanceof Error ? error.message : 'Unknown error';
|
||||
console.error(`Upload error for ${item.file.name}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
uploading = false;
|
||||
|
||||
const successCount = files.filter((f) => f.status === 'success').length;
|
||||
const errorCount = files.filter((f) => f.status === 'error').length;
|
||||
|
||||
if (errorCount === 0) {
|
||||
addNotification(`INFO:Uploaded ${successCount} adv video(s) successfully`);
|
||||
} else {
|
||||
addNotification(`WARN:Uploaded ${successCount}, failed ${errorCount}`);
|
||||
}
|
||||
|
||||
// Build the manifest (sync_1.file) — only from the selected/active set,
|
||||
// never the whole FTP folder (production keeps many inactive variants there).
|
||||
if (successCount > 0) {
|
||||
if (MANIFEST_MODE === 'machine') {
|
||||
// Method 2: ls -l on the (rm -rf + pushed) machine, then upload.
|
||||
await generateMachineManifest(uid, displayName, email);
|
||||
} else {
|
||||
// Method 1: manifest = the successfully-uploaded files in the UI list.
|
||||
await uploadSelectedManifest(uid, displayName, email);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Method 1 — build sync_1.file from the active set the user assembled in the
|
||||
// UI (the successfully-uploaded files), NOT the whole FTP folder. The FTP keeps
|
||||
// any other/variant files; the manifest lists only what you chose.
|
||||
async function uploadSelectedManifest(uid: string, displayName: string, email: string) {
|
||||
const active = files.filter((f) => f.status === 'success');
|
||||
if (active.length === 0) return;
|
||||
generatingManifest = true;
|
||||
try {
|
||||
const text = buildManifestText(active);
|
||||
await uploadManifestText(text, uid, displayName, email);
|
||||
addNotification(`INFO:Manifest uploaded (${active.length} active file(s))`);
|
||||
} catch (error) {
|
||||
console.error('[Adv] selected manifest error:', error);
|
||||
addNotification(`ERR:Manifest failed: ${error instanceof Error ? error.message : 'unknown'}`);
|
||||
} finally {
|
||||
generatingManifest = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ls -l style line the machine's FileSyncServer parses (size at field 4, name
|
||||
// at field 7). sync_1.file lists itself as size 0 so the machine skips it.
|
||||
function buildManifestText(items: AdvFileItem[]): string {
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
const fmt = (ms: number) => {
|
||||
const d = new Date(ms);
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
};
|
||||
const now = Date.now();
|
||||
const rows = [
|
||||
{ name: MANIFEST_FILENAME, size: 0, mtime: now },
|
||||
...items.map((it) => ({
|
||||
name: it.file.name,
|
||||
size: it.file.size,
|
||||
mtime: it.file.lastModified || now
|
||||
}))
|
||||
].sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
const lines = ['total 0'];
|
||||
for (const r of rows) {
|
||||
lines.push(`-rw-rw---- 1 root sdcard_rw ${r.size} ${fmt(r.mtime)} ${r.name}`);
|
||||
}
|
||||
return lines.join('\n') + '\n';
|
||||
}
|
||||
|
||||
async function uploadManifestText(
|
||||
text: string,
|
||||
uid: string,
|
||||
displayName: string,
|
||||
email: string
|
||||
) {
|
||||
const fd = new FormData();
|
||||
fd.append('country', selectedCountry);
|
||||
fd.append('uid', uid);
|
||||
fd.append('displayName', displayName);
|
||||
fd.append('email', email);
|
||||
fd.append('file', new File([text], MANIFEST_FILENAME, { type: 'text/plain' }));
|
||||
|
||||
const res = await fetch(MANIFEST_PROXY_ENDPOINT, { method: 'POST', body: fd });
|
||||
if (!res.ok) {
|
||||
const e = await res.json().catch(() => ({ detail: res.statusText }));
|
||||
throw new Error(e.detail || 'Manifest upload failed');
|
||||
}
|
||||
}
|
||||
|
||||
// Method 2 step 1 — make the machine's adv folder hold EXACTLY the selected
|
||||
// files (rm -rf + push), like the original `rm -Rf adv` + push of the whole
|
||||
// folder. After this, the machine's `ls -l` matches what we upload to the FTP.
|
||||
// ⚠️ This WIPES the machine's adv folder — method 2 is a full replace, so the
|
||||
// dragged set must be the complete intended adv set.
|
||||
async function syncMachineFolder(targets: AdvFileItem[]): Promise<boolean> {
|
||||
if (!AdbInstance.instance) {
|
||||
addNotification('ERR:Method 2 (machine manifest) needs the machine connected via ADB');
|
||||
return false;
|
||||
}
|
||||
const advDir = machineAdvDir(selectedCountry);
|
||||
pushingToMachine = true;
|
||||
try {
|
||||
// Wipe + recreate so only the selected set remains on the machine.
|
||||
await adb.executeCmd(`rm -rf "${advDir}" && mkdir -p "${advDir}"`);
|
||||
|
||||
for (let i = 0; i < targets.length; i++) {
|
||||
const item = targets[i];
|
||||
pushProgress = { current: i, total: targets.length, name: item.file.name, percent: 0 };
|
||||
const bytes = new Uint8Array(await item.file.arrayBuffer());
|
||||
const ok = await adb.pushBinary(
|
||||
`${advDir}/${item.file.name}`,
|
||||
bytes,
|
||||
(sent, total) => {
|
||||
pushProgress = {
|
||||
current: i,
|
||||
total: targets.length,
|
||||
name: item.file.name,
|
||||
percent: total > 0 ? Math.round((sent / total) * 100) : 0
|
||||
};
|
||||
}
|
||||
);
|
||||
if (!ok) {
|
||||
addNotification(`ERR:Push to machine failed: ${item.file.name}`);
|
||||
return false;
|
||||
}
|
||||
pushProgress = { current: i + 1, total: targets.length, name: item.file.name, percent: 100 };
|
||||
}
|
||||
addNotification(`INFO:Machine adv folder synced (${targets.length} file(s))`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('[Adv] machine sync error:', error);
|
||||
addNotification(`ERR:Machine sync failed: ${error instanceof Error ? error.message : 'unknown'}`);
|
||||
return false;
|
||||
} finally {
|
||||
pushingToMachine = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Method 2 step 2 — generate the manifest from the (now synced) machine adv
|
||||
// folder (`ls -l > sync_1.file`), pull it, and upload it to the FTP.
|
||||
async function generateMachineManifest(uid: string, displayName: string, email: string) {
|
||||
if (!AdbInstance.instance) {
|
||||
addNotification('ERR:Machine not connected — cannot generate manifest from machine');
|
||||
return;
|
||||
}
|
||||
const advDir = machineAdvDir(selectedCountry);
|
||||
generatingManifest = true;
|
||||
try {
|
||||
// ls -l > sync_1.file on the machine (shell truncates the manifest first,
|
||||
// so it lists itself as size 0 — exactly what the original flow produces).
|
||||
await adb.executeCmd(`cd ${advDir} && ls -l > ${MANIFEST_FILENAME}`);
|
||||
|
||||
const manifestText = await adb.pull(`${advDir}/${MANIFEST_FILENAME}`);
|
||||
if (!manifestText || manifestText.trim().length === 0) {
|
||||
addNotification('ERR:Failed to read sync_1.file from machine');
|
||||
return;
|
||||
}
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('country', selectedCountry);
|
||||
fd.append('uid', uid);
|
||||
fd.append('displayName', displayName);
|
||||
fd.append('email', email);
|
||||
fd.append(
|
||||
'file',
|
||||
new File([manifestText], MANIFEST_FILENAME, { type: 'text/plain' })
|
||||
);
|
||||
|
||||
const res = await fetch(MANIFEST_PROXY_ENDPOINT, { method: 'POST', body: fd });
|
||||
if (!res.ok) {
|
||||
const e = await res.json().catch(() => ({ detail: res.statusText }));
|
||||
throw new Error(e.detail || 'Manifest upload failed');
|
||||
}
|
||||
addNotification('INFO:Manifest (from machine) uploaded to server');
|
||||
} catch (error) {
|
||||
console.error('[Adv] machine manifest error:', error);
|
||||
addNotification(`ERR:Machine manifest failed: ${error instanceof Error ? error.message : 'unknown'}`);
|
||||
} finally {
|
||||
generatingManifest = false;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
return () => {
|
||||
files.forEach((f) => URL.revokeObjectURL(f.preview));
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex min-h-screen flex-col">
|
||||
<!-- Header -->
|
||||
<div class="sticky top-0 z-10 border-b bg-background">
|
||||
<div class="flex items-center justify-between px-8 py-4">
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold">Adv Upload</h1>
|
||||
<p class="text-sm text-muted-foreground">Upload advertisement videos (.mp4) to the server</p>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-3">
|
||||
<Badge variant={isAdbConnected ? 'default' : 'secondary'}>
|
||||
{isAdbConnected ? 'Machine connected' : 'Machine offline'}
|
||||
</Badge>
|
||||
|
||||
{#if files.length > 0}
|
||||
<Button
|
||||
variant="outline"
|
||||
onclick={clearAllFiles}
|
||||
disabled={uploading || pushingToMachine}
|
||||
>
|
||||
<X class="mr-2 h-4 w-4" />
|
||||
Clear All
|
||||
</Button>
|
||||
{/if}
|
||||
|
||||
<!-- Step 1: push to the connected machine to preview -->
|
||||
<Button
|
||||
variant="outline"
|
||||
onclick={pushToMachine}
|
||||
disabled={pushingToMachine || uploading || !isAdbConnected || validVideoCount === 0}
|
||||
>
|
||||
{#if pushingToMachine}
|
||||
<Spinner class="mr-2 h-4 w-4" />
|
||||
Pushing {pushProgress.current}/{pushProgress.total}...
|
||||
{:else}
|
||||
<MonitorPlay class="mr-2 h-4 w-4" />
|
||||
Push to Machine ({validVideoCount})
|
||||
{/if}
|
||||
</Button>
|
||||
|
||||
<!-- Step 2: upload to server -->
|
||||
<Button
|
||||
onclick={uploadFiles}
|
||||
disabled={uploading || pushingToMachine || generatingManifest || uploadableCount === 0}
|
||||
>
|
||||
{#if uploading}
|
||||
<Spinner class="mr-2 h-4 w-4" />
|
||||
Uploading {uploadProgress.current}/{uploadProgress.total}...
|
||||
{:else}
|
||||
<Upload class="mr-2 h-4 w-4" />
|
||||
Upload ({uploadableCount})
|
||||
{/if}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="flex-1 overflow-y-auto p-8">
|
||||
<div class="mx-auto max-w-6xl space-y-6">
|
||||
<!-- Settings -->
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title>Upload Settings</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<div class="space-y-2 md:max-w-sm">
|
||||
<Label>Country</Label>
|
||||
<Select.Root type="single" bind:value={selectedCountry}>
|
||||
<Select.Trigger class="w-full">
|
||||
{COUNTRIES.find((c) => c.value === selectedCountry)?.label || 'Select country'}
|
||||
</Select.Trigger>
|
||||
<Select.Content>
|
||||
{#each COUNTRIES as country}
|
||||
<Select.Item value={country.value}>{country.label}</Select.Item>
|
||||
{/each}
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
<!-- <p class="text-xs text-muted-foreground">
|
||||
Machine push path: <code class="font-mono">{machineAdvDir(selectedCountry)}</code>
|
||||
</p> -->
|
||||
</div>
|
||||
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<!-- Naming guide -->
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title>Naming & Size Rules</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<div class="rounded-lg border p-4">
|
||||
<p class="font-mono text-sm font-semibold">taobin_adv_menu_*.mp4</p>
|
||||
<p class="text-sm text-muted-foreground">Menu banner ad</p>
|
||||
<Badge variant="secondary" class="mt-2">1080 × 380</Badge>
|
||||
</div>
|
||||
<div class="rounded-lg border p-4">
|
||||
<p class="font-mono text-sm font-semibold">taobin_adv_*.mp4</p>
|
||||
<p class="text-sm text-muted-foreground">Fullscreen / Idle ad</p>
|
||||
<Badge variant="secondary" class="mt-2">1080 × 608</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<!-- Drop Zone -->
|
||||
<Card.Root>
|
||||
<Card.Content class="p-6">
|
||||
<label
|
||||
class="flex min-h-[200px] cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed transition-colors {dragOver
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-muted-foreground/25 hover:border-primary/50 hover:bg-muted/50'}"
|
||||
ondrop={handleDrop}
|
||||
ondragover={handleDragOver}
|
||||
ondragleave={handleDragLeave}
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept=".mp4,video/mp4"
|
||||
class="hidden"
|
||||
onchange={handleFileSelect}
|
||||
disabled={uploading}
|
||||
/>
|
||||
<Video class="mb-4 h-12 w-12 text-muted-foreground" />
|
||||
<p class="mb-2 text-lg font-medium">Drop .mp4 videos here or click to browse</p>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
Filenames must follow the taobin_adv_*.mp4 convention
|
||||
</p>
|
||||
</label>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<!-- Push-to-Machine Progress -->
|
||||
{#if pushingToMachine}
|
||||
<div class="space-y-2">
|
||||
<Progress
|
||||
value={pushProgress.total > 0 ? (pushProgress.current / pushProgress.total) * 100 : 0}
|
||||
max={100}
|
||||
class="h-2"
|
||||
/>
|
||||
<p class="flex items-center justify-center gap-2 text-center text-sm text-muted-foreground">
|
||||
<Spinner class="h-3.5 w-3.5" />
|
||||
Sending to machine ({pushProgress.current}/{pushProgress.total}): {pushProgress.name}
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Upload Progress -->
|
||||
{#if uploading}
|
||||
<div class="space-y-2">
|
||||
<Progress
|
||||
value={uploadProgress.total > 0
|
||||
? (uploadProgress.current / uploadProgress.total) * 100
|
||||
: 0}
|
||||
max={100}
|
||||
class="h-2"
|
||||
/>
|
||||
<p class="text-center text-sm text-muted-foreground">
|
||||
Uploading: {uploadProgress.current} / {uploadProgress.total}
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Generating manifest from machine (method 2) -->
|
||||
{#if generatingManifest}
|
||||
<p class="flex items-center justify-center gap-2 text-center text-sm text-muted-foreground">
|
||||
<Spinner class="h-3.5 w-3.5" />
|
||||
Generating sync_1.file on machine and uploading...
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<!-- File List -->
|
||||
{#if files.length > 0}
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title class="flex items-center justify-between">
|
||||
<span>Selected Files ({files.length})</span>
|
||||
<div class="flex gap-2">
|
||||
{#if files.some((f) => f.status === 'success')}
|
||||
<Badge variant="default" class="bg-green-500">
|
||||
{files.filter((f) => f.status === 'success').length} uploaded
|
||||
</Badge>
|
||||
{/if}
|
||||
{#if files.some((f) => f.status === 'error')}
|
||||
<Badge variant="destructive">
|
||||
{files.filter((f) => f.status === 'error').length} invalid/failed
|
||||
</Badge>
|
||||
{/if}
|
||||
</div>
|
||||
</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{#each files as item (item.id)}
|
||||
<div
|
||||
class="group relative overflow-hidden rounded-lg border bg-muted/30 transition-shadow hover:shadow-md"
|
||||
>
|
||||
<!-- Video preview -->
|
||||
<div class="relative aspect-video bg-black">
|
||||
<!-- svelte-ignore a11y_media_has_caption -->
|
||||
<video src={item.preview} class="h-full w-full object-contain" muted controls
|
||||
></video>
|
||||
|
||||
{#if item.status === 'uploading'}
|
||||
<div class="absolute inset-0 flex items-center justify-center bg-black/50">
|
||||
<Spinner class="h-8 w-8 text-white" />
|
||||
</div>
|
||||
{:else if item.status === 'success'}
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center bg-green-500/20"
|
||||
>
|
||||
<CheckCircle class="h-10 w-10 text-green-500" />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Remove button -->
|
||||
{#if item.status !== 'uploading'}
|
||||
<button
|
||||
class="absolute top-2 right-2 rounded-full bg-black/60 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100"
|
||||
onclick={() => removeFile(item.id)}
|
||||
disabled={uploading}
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- File info -->
|
||||
<div class="space-y-1 p-3">
|
||||
<p class="truncate text-sm font-medium" title={item.file.name}>
|
||||
{item.file.name}
|
||||
</p>
|
||||
<div class="flex flex-wrap items-center gap-1.5">
|
||||
<Badge variant="outline" class="text-[11px]">
|
||||
{item.category === 'menu' ? 'Menu banner' : 'Fullscreen'}
|
||||
</Badge>
|
||||
{#if !item.dimChecked}
|
||||
<Badge variant="secondary" class="text-[11px]">Reading…</Badge>
|
||||
{:else if item.dimOk}
|
||||
<Badge variant="default" class="bg-green-500 text-[11px]">
|
||||
{item.width}×{item.height}
|
||||
</Badge>
|
||||
{:else}
|
||||
<Badge variant="destructive" class="text-[11px]">
|
||||
{item.width ?? '?'}×{item.height ?? '?'}
|
||||
</Badge>
|
||||
{/if}
|
||||
<span class="text-[11px] text-muted-foreground">
|
||||
{(item.file.size / (1024 * 1024)).toFixed(1)} MB
|
||||
</span>
|
||||
</div>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
Expected {item.expectedWidth}×{item.expectedHeight}
|
||||
</p>
|
||||
{#if item.error}
|
||||
<p class="flex items-center gap-1 text-[11px] text-red-500" title={item.error}>
|
||||
<AlertCircle class="h-3 w-3 shrink-0" />
|
||||
<span class="truncate">{item.error}</span>
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
42
src/routes/(authed)/tools/android-recipe/+page.svelte
Normal file
42
src/routes/(authed)/tools/android-recipe/+page.svelte
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
<script lang="ts">
|
||||
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let AndroidRecipeExportView = $state<any>(null);
|
||||
let loadError = $state('');
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const module = await import('$lib/components/android-recipe-export-view.svelte');
|
||||
AndroidRecipeExportView = module.default;
|
||||
} catch (error: any) {
|
||||
loadError = error?.message ?? 'Unable to load Android recipe export.';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if AndroidRecipeExportView}
|
||||
<AndroidRecipeExportView />
|
||||
{:else}
|
||||
<div class="mx-auto flex w-full max-w-[1600px] flex-col gap-6 px-8 py-8">
|
||||
<div class="space-y-2">
|
||||
<h1 class="text-4xl font-bold tracking-normal">Android Recipe Export</h1>
|
||||
<p class="text-muted-foreground">Preparing recipe export viewer.</p>
|
||||
</div>
|
||||
|
||||
<div class="rounded-lg border border-border bg-card p-8">
|
||||
{#if loadError}
|
||||
<h2 class="text-xl font-semibold text-destructive">Unable to load viewer</h2>
|
||||
<p class="mt-2 text-muted-foreground">{loadError}</p>
|
||||
{:else}
|
||||
<div class="flex items-center gap-3">
|
||||
<Spinner class="h-6 w-6" />
|
||||
<div>
|
||||
<h2 class="text-xl font-semibold">Processing</h2>
|
||||
<p class="mt-1 text-muted-foreground">Loading Android recipe tools...</p>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
|
@ -1,7 +1,8 @@
|
|||
<script lang="ts">
|
||||
import Button from '$lib/components/ui/button/button.svelte';
|
||||
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import * as Dialog from '$lib/components/ui/dialog/index.js';
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
|
||||
import * as adb from '$lib/core/adb/adb';
|
||||
import { addNotification } from '$lib/core/stores/noti';
|
||||
|
|
@ -26,11 +27,20 @@
|
|||
} from '@yume-chan/adb-daemon-webusb';
|
||||
import AdbWebCredentialStore from '@yume-chan/adb-credential-web';
|
||||
import { deviceCredentialManager } from '$lib/core/adb/deviceCredManager';
|
||||
import { afterNavigate } from '$app/navigation';
|
||||
import { afterNavigate, goto } from '$app/navigation';
|
||||
import { env } from '$env/dynamic/public';
|
||||
import { fade } from 'svelte/transition';
|
||||
import { adbWriter, isAdbWriterAvailable, sendToAndroid } from '$lib/core/stores/adbWriter';
|
||||
import { AdbInstance } from '../../../state.svelte';
|
||||
import {
|
||||
setOnMenuSavedCallback,
|
||||
clearOnMenuSavedCallback,
|
||||
clearMenuSaveState
|
||||
} from '$lib/core/stores/menuSaveStore';
|
||||
|
||||
const sourceDir = '/sdcard/coffeevending';
|
||||
const stagedMenuStorageKey = 'brew.create-menu.drafts.v1';
|
||||
const deletedStagedMenuStorageKey = `${stagedMenuStorageKey}.deleted`;
|
||||
const stagedMenuAndroidPath = `${sourceDir}/cfg/supra_draft_menus.json`;
|
||||
|
||||
// fetched recipe
|
||||
let devRecipe: any | undefined = $state();
|
||||
|
|
@ -44,39 +54,63 @@
|
|||
|
||||
// refresh command
|
||||
let refresh_counter: number = $state(0);
|
||||
let stagedMenus: any[] = $state([]);
|
||||
let brewConfirmOpen = $state(false);
|
||||
let pendingBrewMenu: any | null = $state(null);
|
||||
let recipeLoading = $state(false);
|
||||
let recipeAutoLoadAttempted = $state(false);
|
||||
let isAdbConnected = $derived(Boolean(AdbInstance.instance));
|
||||
let isAndroidSocketConnected = $derived(Boolean($adbWriter));
|
||||
let isRecipeLoaded = $derived(Boolean(devRecipe));
|
||||
|
||||
async function pullTextWithRetry(path: string, timeoutMs = 15000, attempts = 2) {
|
||||
for (let attempt = 1; attempt <= attempts; attempt++) {
|
||||
const content = await adb.pull(path, timeoutMs);
|
||||
if (content != undefined) return content;
|
||||
if (attempt < attempts) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function startFetchRecipeFromMachine() {
|
||||
if (recipeLoading) return;
|
||||
|
||||
let instance = adb.getAdbInstance();
|
||||
// recipeFromMachineLoading.set(true);
|
||||
referenceFromPage.set('brew');
|
||||
console.log('check instance', instance);
|
||||
if (instance) {
|
||||
console.log('instance passed!');
|
||||
let dev_recipe = await adb.pull(`${sourceDir}/cfg/recipe_branch_dev.json`);
|
||||
console.log('dev recipe ok', dev_recipe != undefined, dev_recipe);
|
||||
if (dev_recipe) {
|
||||
if (dev_recipe.length == 0) {
|
||||
// case error, do last retry
|
||||
dev_recipe = await adb.pull(`${sourceDir}/coffeethai02.json`);
|
||||
recipeLoading = true;
|
||||
try {
|
||||
console.log('instance passed!');
|
||||
const recipePaths = [
|
||||
`${sourceDir}/cfg/recipe_branch_dev.json`,
|
||||
`${sourceDir}/coffeethai02.json`
|
||||
];
|
||||
|
||||
if (dev_recipe && dev_recipe.length == 0)
|
||||
addNotification('ERROR:Cannot fetch recipe from machine');
|
||||
else if (dev_recipe) {
|
||||
// From coffeethai02
|
||||
for (const recipePath of recipePaths) {
|
||||
const dev_recipe = await pullTextWithRetry(recipePath);
|
||||
console.log('dev recipe pull result', {
|
||||
recipePath,
|
||||
loaded: dev_recipe != undefined,
|
||||
size: dev_recipe?.length ?? 0
|
||||
});
|
||||
if (!dev_recipe || dev_recipe.trim().length == 0) continue;
|
||||
|
||||
try {
|
||||
devRecipe = JSON.parse(dev_recipe);
|
||||
// recipeFromMachineLoading.set(false);
|
||||
addNotification('INFO:Fetch recipe success!');
|
||||
|
||||
buildOverviewForBrewing();
|
||||
return;
|
||||
} catch (error) {
|
||||
console.error('failed to parse recipe json', recipePath, error);
|
||||
addNotification(`ERROR:Invalid recipe JSON from ${recipePath}`);
|
||||
}
|
||||
} else {
|
||||
// from recipe_branch_dev
|
||||
devRecipe = JSON.parse(dev_recipe);
|
||||
// recipeFromMachineLoading.set(false);
|
||||
// addNotification('INFO:Fetch recipe success!');
|
||||
|
||||
buildOverviewForBrewing();
|
||||
}
|
||||
|
||||
addNotification('ERROR:Cannot fetch recipe from machine');
|
||||
} finally {
|
||||
recipeLoading = false;
|
||||
}
|
||||
} else {
|
||||
addNotification('ERROR:Cannot connect to machine');
|
||||
|
|
@ -122,6 +156,14 @@
|
|||
|
||||
async function connectAdb() {
|
||||
try {
|
||||
if (adb.getAdbInstance()) {
|
||||
if (!isAdbWriterAvailable()) {
|
||||
await adb.reconnectAndroidServer();
|
||||
}
|
||||
await loadBrewDataFromConnectedAdb();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!('usb' in navigator)) {
|
||||
throw new Error('WebUSB not supported, try using fallback method or different browser');
|
||||
}
|
||||
|
|
@ -130,16 +172,28 @@
|
|||
let instance = adb.getAdbInstance();
|
||||
|
||||
if (instance) {
|
||||
await startFetchRecipeFromMachine();
|
||||
await loadEssentialFiles();
|
||||
await loadBrewDataFromConnectedAdb();
|
||||
}
|
||||
} catch (e: any) {
|
||||
addNotification(`ERROR:${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBrewDataFromConnectedAdb() {
|
||||
await startFetchRecipeFromMachine();
|
||||
await loadEssentialFiles();
|
||||
await loadStagedMenusFromAndroid();
|
||||
}
|
||||
|
||||
async function tryAutoConnect() {
|
||||
try {
|
||||
if (adb.getAdbInstance()) {
|
||||
if (!isAdbWriterAvailable()) {
|
||||
await adb.reconnectAndroidServer();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!('usb' in navigator) || !AdbDaemonWebUsbDeviceManager.BROWSER) {
|
||||
throw new Error('WebUSB not supported, try using fallback method or different browser');
|
||||
}
|
||||
|
|
@ -179,6 +233,24 @@
|
|||
}
|
||||
}
|
||||
|
||||
async function ensureAndroidSocket() {
|
||||
if (isAdbWriterAvailable()) return true;
|
||||
|
||||
if (!adb.getAdbInstance()) {
|
||||
addNotification('ERR:ADB is not connected');
|
||||
return false;
|
||||
}
|
||||
|
||||
await adb.reconnectAndroidServer();
|
||||
|
||||
if (!isAdbWriterAvailable()) {
|
||||
addNotification('ERR:Android socket is not connected');
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
afterNavigate(async () => {
|
||||
console.log('after navigate brew');
|
||||
await startFetchRecipeFromMachine();
|
||||
|
|
@ -315,6 +387,20 @@
|
|||
}
|
||||
}
|
||||
|
||||
for (const stagedMenu of stagedMenus) {
|
||||
if (!recipe01_query[stagedMenu.productCode]) {
|
||||
data.recipes.push({
|
||||
productCode: stagedMenu.productCode ?? '<not set>',
|
||||
name: stagedMenu.name ? stagedMenu.name : (stagedMenu.otherName ?? '<not set>'),
|
||||
description: stagedMenu.Description
|
||||
? stagedMenu.Description
|
||||
: (stagedMenu.otherDescription ?? '<not set>'),
|
||||
tags: buildTags(stagedMenu),
|
||||
status: 'drafted'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let materialFromMachine = devRecipe['MaterialSetting'];
|
||||
|
||||
let currentQuery = get(recipeFromMachineQuery);
|
||||
|
|
@ -337,16 +423,330 @@
|
|||
}
|
||||
}
|
||||
|
||||
function findRecipeByProductCode(productCode: string) {
|
||||
if (!devRecipe?.Recipe01) return null;
|
||||
for (const recipe of devRecipe.Recipe01) {
|
||||
if (recipe?.productCode === productCode) return recipe;
|
||||
for (const subMenu of recipe?.SubMenu ?? []) {
|
||||
if (subMenu?.productCode === productCode) return subMenu;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isToppingSlotMaterial(materialId: number) {
|
||||
return materialId > 8110 && materialId < 8131;
|
||||
}
|
||||
|
||||
function getDeletedStagedMenuCodes() {
|
||||
try {
|
||||
const stored = localStorage.getItem(deletedStagedMenuStorageKey);
|
||||
const parsed = stored ? JSON.parse(stored) : [];
|
||||
return new Set(Array.isArray(parsed) ? parsed.map(String) : []);
|
||||
} catch (error) {
|
||||
return new Set<string>();
|
||||
}
|
||||
}
|
||||
|
||||
function persistDeletedStagedMenuCodes(codes: Set<string>) {
|
||||
localStorage.setItem(deletedStagedMenuStorageKey, JSON.stringify([...codes]));
|
||||
}
|
||||
|
||||
function markDeletedStagedMenu(productCode: string) {
|
||||
const deletedCodes = getDeletedStagedMenuCodes();
|
||||
deletedCodes.add(productCode);
|
||||
persistDeletedStagedMenuCodes(deletedCodes);
|
||||
}
|
||||
|
||||
function persistStagedMenus() {
|
||||
localStorage.setItem(stagedMenuStorageKey, JSON.stringify(stagedMenus));
|
||||
void persistStagedMenusToAndroid();
|
||||
}
|
||||
|
||||
async function persistStagedMenusToAndroid() {
|
||||
if (!adb.getAdbInstance()) return;
|
||||
|
||||
try {
|
||||
await adb.push(
|
||||
stagedMenuAndroidPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
version: 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
menus: stagedMenus
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('failed to persist staged menus to Android', error);
|
||||
addNotification('WARN:Failed to save draft menus to Android');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStagedMenusFromAndroid() {
|
||||
if (!adb.getAdbInstance()) return false;
|
||||
|
||||
try {
|
||||
const content = await adb.pull(stagedMenuAndroidPath, 10000);
|
||||
if (!content || content.trim().length === 0) {
|
||||
if (stagedMenus.length > 0) {
|
||||
await persistStagedMenusToAndroid();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(content);
|
||||
const menus = Array.isArray(parsed) ? parsed : parsed?.menus;
|
||||
if (!Array.isArray(menus)) {
|
||||
addNotification('WARN:Android draft menu file has invalid format');
|
||||
return false;
|
||||
}
|
||||
|
||||
const deletedCodes = getDeletedStagedMenuCodes();
|
||||
const filteredMenus = menus.filter((menu) => !deletedCodes.has(String(menu?.productCode)));
|
||||
|
||||
stagedMenus = filteredMenus;
|
||||
localStorage.setItem(stagedMenuStorageKey, JSON.stringify(stagedMenus));
|
||||
if (filteredMenus.length !== menus.length) {
|
||||
await persistStagedMenusToAndroid();
|
||||
}
|
||||
buildOverviewForBrewing();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('failed to load staged menus from Android', error);
|
||||
addNotification('WARN:Failed to load draft menus from Android');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function materialDisplayName(material: any) {
|
||||
const thaiName = material?.materialName ?? '';
|
||||
const englishName = material?.materialOtherName ?? '';
|
||||
if (thaiName && englishName) return `${material.id} - ${thaiName} (${englishName})`;
|
||||
return `${material?.id ?? '-'} - ${thaiName || englishName || 'Unnamed material'}`;
|
||||
}
|
||||
|
||||
function getMaterial(materialPathId: number | null) {
|
||||
if (materialPathId == null) return undefined;
|
||||
return (devRecipe?.MaterialSetting ?? []).find(
|
||||
(material: any) => Number(material?.id) === Number(materialPathId)
|
||||
);
|
||||
}
|
||||
|
||||
function toppingGroupDisplayName(group: any) {
|
||||
const groupName = group?.otherName || group?.name || 'Unnamed group';
|
||||
return `${group?.groupID ?? '-'} - ${groupName}`;
|
||||
}
|
||||
|
||||
function toppingListDisplayName(topping: any) {
|
||||
const toppingName = topping?.otherName || topping?.name || 'Unnamed topping';
|
||||
return `${topping?.id ?? '-'} - ${toppingName}`;
|
||||
}
|
||||
|
||||
function getAnyToppingGroup(groupID: number | null) {
|
||||
if (groupID == null) return undefined;
|
||||
return (devRecipe?.Topping?.ToppingGroup ?? []).find(
|
||||
(group: any) => Number(group?.groupID) === Number(groupID)
|
||||
);
|
||||
}
|
||||
|
||||
function getAnyToppingList(toppingID: number | null) {
|
||||
if (toppingID == null) return undefined;
|
||||
return (devRecipe?.Topping?.ToppingList ?? []).find(
|
||||
(topping: any) => Number(topping?.id) === Number(toppingID)
|
||||
);
|
||||
}
|
||||
|
||||
async function brewMenuOnAndroid(menu: any) {
|
||||
if (!(await ensureAndroidSocket())) return;
|
||||
|
||||
await sendToAndroid({
|
||||
type: 'brew_prep',
|
||||
payload: {
|
||||
start: new Date().toLocaleTimeString()
|
||||
}
|
||||
});
|
||||
await sendToAndroid({
|
||||
type: 'brew',
|
||||
payload: {
|
||||
start: new Date().toLocaleTimeString(),
|
||||
target: '-',
|
||||
data: menu
|
||||
}
|
||||
});
|
||||
addNotification(`INFO:Brew request sent: ${menu.productCode}`);
|
||||
}
|
||||
|
||||
function getRecipeStepValueSummary(step: any) {
|
||||
const fields = [
|
||||
['powderGram', 'Powder gram'],
|
||||
['powderTime', 'Powder time'],
|
||||
['syrupGram', 'Syrup gram'],
|
||||
['syrupTime', 'Syrup time'],
|
||||
['waterCold', 'Water cold'],
|
||||
['waterYield', 'Water yield'],
|
||||
['stirTime', 'Stir time']
|
||||
];
|
||||
|
||||
return fields
|
||||
.map(([key, label]) => ({ label, value: Number(step?.[key] ?? 0) }))
|
||||
.filter((field) => Number.isFinite(field.value) && field.value !== 0);
|
||||
}
|
||||
|
||||
function getPendingBrewMaterials() {
|
||||
return (pendingBrewMenu?.recipes ?? [])
|
||||
.filter((step: any) => {
|
||||
const materialPathId = Number(step?.materialPathId);
|
||||
return (
|
||||
step?.isUse !== false &&
|
||||
Number.isFinite(materialPathId) &&
|
||||
!isToppingSlotMaterial(materialPathId)
|
||||
);
|
||||
})
|
||||
.map((step: any, index: number) => {
|
||||
const materialPathId = Number(step.materialPathId);
|
||||
const material = getMaterial(materialPathId);
|
||||
return {
|
||||
index: index + 1,
|
||||
materialPathId,
|
||||
name: material ? materialDisplayName(material) : `${materialPathId} - Unknown material`,
|
||||
values: getRecipeStepValueSummary(step)
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getPendingBrewToppings() {
|
||||
return (pendingBrewMenu?.ToppingSet ?? [])
|
||||
.map((toppingSet: any, index: number) => {
|
||||
const groupID = Number(toppingSet?.groupID);
|
||||
const defaultIDSelect = Number(toppingSet?.defaultIDSelect);
|
||||
if (
|
||||
toppingSet?.isUse === false ||
|
||||
!Number.isFinite(groupID) ||
|
||||
!Number.isFinite(defaultIDSelect) ||
|
||||
defaultIDSelect <= 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const group = getAnyToppingGroup(groupID);
|
||||
const topping = getAnyToppingList(defaultIDSelect);
|
||||
const slotMaterial = getMaterial(8111 + index);
|
||||
|
||||
return {
|
||||
slot: index + 1,
|
||||
slotName:
|
||||
slotMaterial?.materialOtherName ||
|
||||
slotMaterial?.materialName ||
|
||||
`Topping slot ${index + 1}`,
|
||||
groupName: group ? toppingGroupDisplayName(group) : `${groupID} - Unknown group`,
|
||||
toppingName: topping
|
||||
? toppingListDisplayName(topping)
|
||||
: `${defaultIDSelect} - Unknown topping`
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function openBrewConfirm(menu: any) {
|
||||
pendingBrewMenu = menu;
|
||||
brewConfirmOpen = true;
|
||||
}
|
||||
|
||||
function promptBrewStagedMenu(menu: any) {
|
||||
openBrewConfirm(menu);
|
||||
}
|
||||
|
||||
async function confirmBrewNow() {
|
||||
if (!pendingBrewMenu) return;
|
||||
await brewMenuOnAndroid(pendingBrewMenu);
|
||||
brewConfirmOpen = false;
|
||||
pendingBrewMenu = null;
|
||||
}
|
||||
|
||||
// Track menus pending save verification
|
||||
let pendingSaveVerification = $state<Set<string>>(new Set());
|
||||
|
||||
async function verifyMenuSaved(productCode: string, attempt: number = 1): Promise<boolean> {
|
||||
const maxAttempts = 3;
|
||||
const delayMs = 2000; // 2 seconds between attempts
|
||||
|
||||
if (!adb.getAdbInstance() || recipeLoading) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await startFetchRecipeFromMachine();
|
||||
|
||||
if (findRecipeByProductCode(productCode)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Retry if not found and attempts remaining
|
||||
if (attempt < maxAttempts) {
|
||||
addNotification(`INFO:Retry ${attempt}/${maxAttempts} for ${productCode}...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
return verifyMenuSaved(productCode, attempt + 1);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function handleMenuSaved(productCode: string) {
|
||||
markDeletedStagedMenu(productCode);
|
||||
stagedMenus = stagedMenus.filter((menu) => menu.productCode !== productCode);
|
||||
persistStagedMenus();
|
||||
clearMenuSaveState(productCode);
|
||||
addNotification(`INFO:Menu saved: ${productCode}`);
|
||||
buildOverviewForBrewing();
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
// Set up callback for when menu is saved to Android
|
||||
setOnMenuSavedCallback(handleMenuSaved);
|
||||
|
||||
try {
|
||||
const stored = localStorage.getItem(stagedMenuStorageKey);
|
||||
stagedMenus = stored ? JSON.parse(stored) : [];
|
||||
} catch (error) {
|
||||
stagedMenus = [];
|
||||
}
|
||||
buildOverviewForBrewing();
|
||||
if (adb.getAdbInstance()) {
|
||||
void loadStagedMenusFromAndroid();
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
clearOnMenuSavedCallback();
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!isAdbConnected) {
|
||||
recipeAutoLoadAttempted = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (isRecipeLoaded || recipeLoading || recipeAutoLoadAttempted) return;
|
||||
|
||||
recipeAutoLoadAttempted = true;
|
||||
void loadBrewDataFromConnectedAdb();
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const brewAppStatusInterval = setInterval(async () => {
|
||||
// schedule status from .brew_web_status.log
|
||||
let inst = adb.getAdbInstance();
|
||||
if (inst && devRecipe) {
|
||||
if (inst && devRecipe && !recipeLoading) {
|
||||
await adb.executeCmd(
|
||||
'tail -n 1 /sdcard/coffeevending/.brew_web_status.log > /sdcard/coffeevending/.brew_web_status.latest.log'
|
||||
);
|
||||
|
||||
let brew_status_log = await adb.pull(env.PUBLIC_BREW_WEB_LATEST_STATUS);
|
||||
const latestStatusPath = env.PUBLIC_BREW_WEB_LATEST_STATUS;
|
||||
if (!latestStatusPath) return;
|
||||
|
||||
let brew_status_log = await adb.pull(latestStatusPath);
|
||||
if (brew_status_log) {
|
||||
let latest_log = brew_status_log;
|
||||
|
||||
|
|
@ -391,16 +791,31 @@
|
|||
<div class="mb-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 class="m-8 text-4xl font-bold">Brew</h1>
|
||||
<p class="mx-8 my-0 text-muted-foreground">Brewing directly from web to machine</p>
|
||||
<!-- <p class="mx-8 my-0 text-muted-foreground">Brewing directly from web to machine</p>
|
||||
<p class="mx-8 my-0 text-muted-foreground">
|
||||
Note: refreshing page may cut connection with machine
|
||||
</p>
|
||||
</p> -->
|
||||
</div>
|
||||
<div class="mx-8 my-4 flex gap-2">
|
||||
{#if !adb.getAdbInstance() || !devRecipe}
|
||||
{#if !isAdbConnected}
|
||||
<Button variant="default" onclick={() => connectAdb()}>Connect</Button>
|
||||
{:else if !isRecipeLoaded}
|
||||
<Button
|
||||
variant="default"
|
||||
onclick={() => loadBrewDataFromConnectedAdb()}
|
||||
disabled={recipeLoading}
|
||||
>
|
||||
{recipeLoading ? 'Loading...' : 'Load Recipes'}
|
||||
</Button>
|
||||
{#if !isAndroidSocketConnected}
|
||||
<Button variant="outline" onclick={() => adb.reconnectAndroidServer()}
|
||||
>Reconnect Socket</Button
|
||||
>
|
||||
{/if}
|
||||
{:else}
|
||||
<Button variant="default">+ Create Menu</Button>
|
||||
<Button variant="default" onclick={() => goto('/tools/create-menu?open=true')}
|
||||
>+ Create Menu</Button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
|
|
@ -423,3 +838,107 @@
|
|||
{/key}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Dialog.Root bind:open={brewConfirmOpen}>
|
||||
<Dialog.Content class="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
|
||||
<Dialog.Header>
|
||||
<Dialog.Title>Confirm Brew</Dialog.Title>
|
||||
<Dialog.Description>
|
||||
Check the material and topping list before sending this menu to Android.
|
||||
</Dialog.Description>
|
||||
</Dialog.Header>
|
||||
|
||||
{#if pendingBrewMenu}
|
||||
<div class="grid gap-4 py-2">
|
||||
<div class="rounded-md border bg-muted/20 p-4">
|
||||
<div class="text-sm text-muted-foreground">Menu</div>
|
||||
<div class="mt-1 text-lg font-semibold">
|
||||
{pendingBrewMenu.name || pendingBrewMenu.otherName || pendingBrewMenu.productCode}
|
||||
</div>
|
||||
<div class="mt-1 font-mono text-sm text-muted-foreground">
|
||||
{pendingBrewMenu.productCode}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-md border p-4">
|
||||
<div class="mb-3 flex items-center justify-between gap-3">
|
||||
<h3 class="text-base font-semibold">Materials</h3>
|
||||
<span class="rounded-full bg-muted px-2.5 py-1 text-xs text-muted-foreground">
|
||||
{getPendingBrewMaterials().length} items
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-2">
|
||||
{#each getPendingBrewMaterials() as material}
|
||||
<div class="rounded-md border bg-background/70 p-3">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-xs text-muted-foreground">Step {material.index}</div>
|
||||
<div class="font-medium">{material.name}</div>
|
||||
</div>
|
||||
<div class="font-mono text-xs text-muted-foreground">
|
||||
{material.materialPathId}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if material.values.length > 0}
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
{#each material.values as field}
|
||||
<span
|
||||
class="rounded-full bg-emerald-500 px-2.5 py-1 font-mono text-xs font-semibold text-white"
|
||||
>
|
||||
{field.label}: {field.value}
|
||||
</span>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="mt-3 text-sm text-muted-foreground">No amount values set</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-md border p-4">
|
||||
<div class="mb-3 flex items-center justify-between gap-3">
|
||||
<h3 class="text-base font-semibold">Toppings</h3>
|
||||
<span class="rounded-full bg-muted px-2.5 py-1 text-xs text-muted-foreground">
|
||||
{getPendingBrewToppings().length} items
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{#if getPendingBrewToppings().length === 0}
|
||||
<div class="rounded-md border border-dashed p-3 text-sm text-muted-foreground">
|
||||
No toppings selected.
|
||||
</div>
|
||||
{:else}
|
||||
<div class="grid gap-2">
|
||||
{#each getPendingBrewToppings() as topping}
|
||||
<div class="rounded-md border bg-background/70 p-3">
|
||||
<div class="text-xs text-muted-foreground">
|
||||
Slot {topping.slot}: {topping.slotName}
|
||||
</div>
|
||||
<div class="mt-1 font-medium">{topping.toppingName}</div>
|
||||
<div class="mt-1 text-sm text-muted-foreground">{topping.groupName}</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<Dialog.Footer>
|
||||
<Button
|
||||
variant="outline"
|
||||
onclick={() => {
|
||||
brewConfirmOpen = false;
|
||||
pendingBrewMenu = null;
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onclick={confirmBrewNow} disabled={!pendingBrewMenu}>Confirm Brew</Button>
|
||||
</Dialog.Footer>
|
||||
</Dialog.Content>
|
||||
</Dialog.Root>
|
||||
|
|
|
|||
1892
src/routes/(authed)/tools/create-menu/+page.svelte
Normal file
1892
src/routes/(authed)/tools/create-menu/+page.svelte
Normal file
File diff suppressed because it is too large
Load diff
442
src/routes/(authed)/tools/image-upload/+page.svelte
Normal file
442
src/routes/(authed)/tools/image-upload/+page.svelte
Normal file
|
|
@ -0,0 +1,442 @@
|
|||
<script lang="ts">
|
||||
import { auth } from '$lib/core/stores/auth';
|
||||
import { addNotification } from '$lib/core/stores/noti';
|
||||
import Button from '$lib/components/ui/button/button.svelte';
|
||||
import Label from '$lib/components/ui/label/label.svelte';
|
||||
import * as Card from '$lib/components/ui/card/index.js';
|
||||
import * as Select from '$lib/components/ui/select/index.js';
|
||||
import Badge from '$lib/components/ui/badge/badge.svelte';
|
||||
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
|
||||
import Progress from '$lib/components/ui/progress/progress.svelte';
|
||||
import { Upload, X, ImageIcon, CheckCircle, AlertCircle } from '@lucide/svelte/icons';
|
||||
|
||||
const UPLOAD_PROXY_ENDPOINT = '/api/image-upload';
|
||||
|
||||
const ALLOWED_FOLDERS = [
|
||||
{ value: 'page_drink_picture2_n', label: 'page_drink_picture2_n' },
|
||||
{ value: 'page_drink_n', label: 'page_drink_n' },
|
||||
{ value: 'page_drink_disable_n2', label: 'page_drink_disable_n2' },
|
||||
{ value: 'page_drink_press', label: 'page_drink_press' },
|
||||
// { value: 'page_drink', label: 'page_drink' },
|
||||
// { value: 'page_drink_disable', label: 'page_drink_disable' },
|
||||
// { value: 'page_drink_disable_n', label: 'page_drink_disable_n' },
|
||||
// { value: 'page_drink_press_n', label: 'page_drink_press_n' },
|
||||
// { value: 'page_drink_select', label: 'page_drink_select' }
|
||||
];
|
||||
|
||||
const COUNTRIES = [
|
||||
{ value: 'tha', label: 'Thailand (tha)' },
|
||||
{ value: 'myn', label: 'Myanmar (myn)' },
|
||||
{ value: 'jpn', label: 'Japan (jpn)' },
|
||||
{ value: 'chn', label: 'China (chn)' },
|
||||
{ value: '', label: 'No Country (Global)' }
|
||||
];
|
||||
|
||||
const ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
|
||||
|
||||
interface FileItem {
|
||||
id: string;
|
||||
file: File;
|
||||
preview: string;
|
||||
status: 'pending' | 'uploading' | 'success' | 'error';
|
||||
error?: string;
|
||||
}
|
||||
|
||||
let selectedCountry = $state('tha');
|
||||
let selectedFolder = $state('page_drink_picture2_n');
|
||||
let files = $state<FileItem[]>([]);
|
||||
let uploading = $state(false);
|
||||
let uploadProgress = $state({ current: 0, total: 0 });
|
||||
let dragOver = $state(false);
|
||||
|
||||
function generateId() {
|
||||
return Math.random().toString(36).substring(2, 9);
|
||||
}
|
||||
|
||||
function isValidFile(file: File): boolean {
|
||||
const ext = '.' + file.name.split('.').pop()?.toLowerCase();
|
||||
return ALLOWED_EXTENSIONS.includes(ext);
|
||||
}
|
||||
|
||||
function handleFileSelect(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
if (input.files) {
|
||||
addFiles(Array.from(input.files));
|
||||
}
|
||||
input.value = '';
|
||||
}
|
||||
|
||||
function handleDrop(event: DragEvent) {
|
||||
event.preventDefault();
|
||||
dragOver = false;
|
||||
if (event.dataTransfer?.files) {
|
||||
addFiles(Array.from(event.dataTransfer.files));
|
||||
}
|
||||
}
|
||||
|
||||
function handleDragOver(event: DragEvent) {
|
||||
event.preventDefault();
|
||||
dragOver = true;
|
||||
}
|
||||
|
||||
function handleDragLeave() {
|
||||
dragOver = false;
|
||||
}
|
||||
|
||||
function addFiles(newFiles: File[]) {
|
||||
const validFiles = newFiles.filter((file) => {
|
||||
if (!isValidFile(file)) {
|
||||
addNotification(`WARN:${file.name} - Invalid file type`);
|
||||
return false;
|
||||
}
|
||||
// Check for duplicates
|
||||
if (files.some((f) => f.file.name === file.name)) {
|
||||
addNotification(`WARN:${file.name} - Already added`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const newItems: FileItem[] = validFiles.map((file) => ({
|
||||
id: generateId(),
|
||||
file,
|
||||
preview: URL.createObjectURL(file),
|
||||
status: 'pending'
|
||||
}));
|
||||
|
||||
files = [...files, ...newItems];
|
||||
}
|
||||
|
||||
function removeFile(id: string) {
|
||||
const item = files.find((f) => f.id === id);
|
||||
if (item) {
|
||||
URL.revokeObjectURL(item.preview);
|
||||
}
|
||||
files = files.filter((f) => f.id !== id);
|
||||
}
|
||||
|
||||
function clearAllFiles() {
|
||||
files.forEach((f) => URL.revokeObjectURL(f.preview));
|
||||
files = [];
|
||||
}
|
||||
|
||||
async function uploadFiles() {
|
||||
const currentUser = $auth;
|
||||
if (!currentUser) {
|
||||
addNotification('ERR:Not logged in');
|
||||
return;
|
||||
}
|
||||
|
||||
const pendingFiles = files.filter((f) => f.status === 'pending' || f.status === 'error');
|
||||
if (pendingFiles.length === 0) {
|
||||
addNotification('WARN:No files to upload');
|
||||
return;
|
||||
}
|
||||
|
||||
uploading = true;
|
||||
uploadProgress = { current: 0, total: pendingFiles.length };
|
||||
|
||||
const uid = currentUser.uid;
|
||||
const displayName = currentUser.displayName || 'unknown';
|
||||
const email = currentUser.email || 'unknown@email.com';
|
||||
|
||||
for (let i = 0; i < pendingFiles.length; i++) {
|
||||
const item = pendingFiles[i];
|
||||
const index = files.findIndex((f) => f.id === item.id);
|
||||
if (index === -1) continue;
|
||||
|
||||
files[index].status = 'uploading';
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('country', selectedCountry);
|
||||
formData.append('folder', selectedFolder);
|
||||
formData.append('uid', uid);
|
||||
formData.append('displayName', displayName);
|
||||
formData.append('email', email);
|
||||
formData.append('file', item.file);
|
||||
|
||||
const response = await fetch(UPLOAD_PROXY_ENDPOINT, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ detail: response.statusText }));
|
||||
throw new Error(errorData.detail || 'Upload failed');
|
||||
}
|
||||
|
||||
files[index].status = 'success';
|
||||
uploadProgress = { current: i + 1, total: pendingFiles.length };
|
||||
} catch (error) {
|
||||
files[index].status = 'error';
|
||||
files[index].error = error instanceof Error ? error.message : 'Unknown error';
|
||||
console.error(`Upload error for ${item.file.name}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
uploading = false;
|
||||
|
||||
const successCount = files.filter((f) => f.status === 'success').length;
|
||||
const errorCount = files.filter((f) => f.status === 'error').length;
|
||||
|
||||
if (errorCount === 0) {
|
||||
addNotification(`INFO:Uploaded ${successCount} file(s) successfully`);
|
||||
} else {
|
||||
addNotification(`WARN:Uploaded ${successCount}, failed ${errorCount}`);
|
||||
}
|
||||
}
|
||||
|
||||
function getStatusIcon(status: FileItem['status']) {
|
||||
switch (status) {
|
||||
case 'success':
|
||||
return CheckCircle;
|
||||
case 'error':
|
||||
return AlertCircle;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getStatusColor(status: FileItem['status']) {
|
||||
switch (status) {
|
||||
case 'success':
|
||||
return 'text-green-500';
|
||||
case 'error':
|
||||
return 'text-red-500';
|
||||
case 'uploading':
|
||||
return 'text-blue-500';
|
||||
default:
|
||||
return 'text-muted-foreground';
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
return () => {
|
||||
files.forEach((f) => URL.revokeObjectURL(f.preview));
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex min-h-screen flex-col">
|
||||
<!-- Header -->
|
||||
<div class="sticky top-0 z-10 border-b bg-background">
|
||||
<div class="flex items-center justify-between px-8 py-4">
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold">Image Upload</h1>
|
||||
<p class="text-sm text-muted-foreground">Upload menu images to the server</p>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-4">
|
||||
{#if files.length > 0}
|
||||
<Button variant="outline" onclick={clearAllFiles} disabled={uploading}>
|
||||
<X class="mr-2 h-4 w-4" />
|
||||
Clear All
|
||||
</Button>
|
||||
{/if}
|
||||
<Button onclick={uploadFiles} disabled={uploading || files.length === 0}>
|
||||
{#if uploading}
|
||||
<Spinner class="mr-2 h-4 w-4" />
|
||||
Uploading {uploadProgress.current}/{uploadProgress.total}...
|
||||
{:else}
|
||||
<Upload class="mr-2 h-4 w-4" />
|
||||
Upload ({files.filter((f) => f.status === 'pending' || f.status === 'error').length})
|
||||
{/if}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="flex-1 overflow-y-auto p-8">
|
||||
<div class="mx-auto max-w-6xl space-y-6">
|
||||
<!-- Settings -->
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title>Upload Settings</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<div class="grid gap-6 md:grid-cols-2">
|
||||
<div class="space-y-2">
|
||||
<Label>Country</Label>
|
||||
<Select.Root type="single" bind:value={selectedCountry}>
|
||||
<Select.Trigger class="w-full">
|
||||
{COUNTRIES.find((c) => c.value === selectedCountry)?.label || 'Select country'}
|
||||
</Select.Trigger>
|
||||
<Select.Content>
|
||||
{#each COUNTRIES as country}
|
||||
<Select.Item value={country.value}>{country.label}</Select.Item>
|
||||
{/each}
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<Label>Folder</Label>
|
||||
<Select.Root type="single" bind:value={selectedFolder}>
|
||||
<Select.Trigger class="w-full">
|
||||
{ALLOWED_FOLDERS.find((f) => f.value === selectedFolder)?.label || 'Select folder'}
|
||||
</Select.Trigger>
|
||||
<Select.Content>
|
||||
{#each ALLOWED_FOLDERS as folder}
|
||||
<Select.Item value={folder.value}>{folder.label}</Select.Item>
|
||||
{/each}
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<!-- <p class="text-xs text-muted-foreground">
|
||||
Endpoint: <code class="rounded bg-muted px-1 py-0.5">
|
||||
{selectedCountry
|
||||
? `/inter/${selectedCountry}/image/${selectedFolder}/upload/...`
|
||||
: `/image/${selectedFolder}/upload/...`}
|
||||
</code>
|
||||
</p> -->
|
||||
</div>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<!-- Drop Zone -->
|
||||
<Card.Root>
|
||||
<Card.Content class="p-6">
|
||||
<label
|
||||
class="flex min-h-[200px] cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed transition-colors {dragOver
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-muted-foreground/25 hover:border-primary/50 hover:bg-muted/50'}"
|
||||
ondrop={handleDrop}
|
||||
ondragover={handleDragOver}
|
||||
ondragleave={handleDragLeave}
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept=".jpg,.jpeg,.png,.gif,.webp"
|
||||
class="hidden"
|
||||
onchange={handleFileSelect}
|
||||
disabled={uploading}
|
||||
/>
|
||||
<ImageIcon class="mb-4 h-12 w-12 text-muted-foreground" />
|
||||
<p class="mb-2 text-lg font-medium">Drop images here or click to browse</p>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
Supported formats: JPG, JPEG, PNG, GIF, WEBP
|
||||
</p>
|
||||
</label>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<!-- Upload Progress -->
|
||||
{#if uploading}
|
||||
<div class="space-y-2">
|
||||
<Progress
|
||||
value={uploadProgress.total > 0
|
||||
? (uploadProgress.current / uploadProgress.total) * 100
|
||||
: 0}
|
||||
max={100}
|
||||
class="h-2"
|
||||
/>
|
||||
<p class="text-center text-sm text-muted-foreground">
|
||||
Uploading: {uploadProgress.current} / {uploadProgress.total}
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- File List -->
|
||||
{#if files.length > 0}
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title class="flex items-center justify-between">
|
||||
<span>Selected Files ({files.length})</span>
|
||||
<div class="flex gap-2">
|
||||
{#if files.some((f) => f.status === 'success')}
|
||||
<Badge variant="default" class="bg-green-500">
|
||||
{files.filter((f) => f.status === 'success').length} uploaded
|
||||
</Badge>
|
||||
{/if}
|
||||
{#if files.some((f) => f.status === 'error')}
|
||||
<Badge variant="destructive">
|
||||
{files.filter((f) => f.status === 'error').length} failed
|
||||
</Badge>
|
||||
{/if}
|
||||
{#if files.some((f) => f.status === 'pending')}
|
||||
<Badge variant="secondary">
|
||||
{files.filter((f) => f.status === 'pending').length} pending
|
||||
</Badge>
|
||||
{/if}
|
||||
</div>
|
||||
</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
|
||||
{#each files as item (item.id)}
|
||||
<div
|
||||
class="group relative overflow-hidden rounded-lg border bg-muted/30 transition-shadow hover:shadow-md"
|
||||
>
|
||||
<!-- Preview Image -->
|
||||
<div class="aspect-square">
|
||||
<img
|
||||
src={item.preview}
|
||||
alt={item.file.name}
|
||||
class="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Overlay for status -->
|
||||
{#if item.status === 'uploading'}
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center bg-black/50"
|
||||
>
|
||||
<Spinner class="h-8 w-8 text-white" />
|
||||
</div>
|
||||
{:else if item.status === 'success'}
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center bg-green-500/20"
|
||||
>
|
||||
<CheckCircle class="h-10 w-10 text-green-500" />
|
||||
</div>
|
||||
{:else if item.status === 'error'}
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center bg-red-500/20"
|
||||
>
|
||||
<AlertCircle class="h-10 w-10 text-red-500" />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Remove button -->
|
||||
{#if item.status !== 'uploading'}
|
||||
<button
|
||||
class="absolute top-2 right-2 rounded-full bg-black/60 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100"
|
||||
onclick={() => removeFile(item.id)}
|
||||
disabled={uploading}
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
<!-- File info -->
|
||||
<div class="p-2">
|
||||
<p
|
||||
class="truncate text-xs font-medium"
|
||||
title={item.file.name}
|
||||
>
|
||||
{item.file.name}
|
||||
</p>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
{(item.file.size / 1024).toFixed(1)} KB
|
||||
</p>
|
||||
{#if item.error}
|
||||
<p class="truncate text-xs text-red-500" title={item.error}>
|
||||
{item.error}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
Loading…
Add table
Add a link
Reference in a new issue