From 18a70dc4c15e1a6ee8eff24a05ae15b3c5046747 Mon Sep 17 00:00:00 2001 From: Sharqan Ahamed <61654902+shatheitguy@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:53:35 +0400 Subject: [PATCH 1/3] Trash for deleted forms and responses; dashboard shows new forms right away MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trash (Settings → Trash, admins) - Deleting a form or responses now copies them to a new TrashItem table (form + responses + access list, or one response) and then deletes them as before, so no existing query had to change - Restore puts a form back with its responses and access; a response can be restored once its form exists. A form whose link/port/domain was taken meanwhile gets new ones - Delete forever / Empty Trash; anything older than 30 days is removed every hour. Uploaded files stay until an item leaves the Trash - Included in system backups (older backups still restore) - Delete dialogs now say items go to the Trash; Arabic and Tamil text added Dashboard - experimental.staleTimes.dynamic = 0: links no longer reuse a page seen in the last 30 s, so a form created in the builder shows on the dashboard without a reload --- app/api/admin/trash/[id]/route.ts | 36 ++++ app/api/admin/trash/route.ts | 26 +++ app/api/forms/[id]/route.ts | 7 +- app/api/forms/[id]/submissions/route.ts | 13 +- app/settings/trash/page.tsx | 16 ++ components/hub/hub-client.tsx | 4 +- components/settings/settings-nav.tsx | 3 +- components/settings/trash-settings.tsx | 131 +++++++++++ components/submissions/submissions-view.tsx | 2 +- lib/i18n/dict/settings.ts | 68 ++++++ lib/startup.ts | 2 + lib/system-backup.ts | 10 +- lib/trash.ts | 227 ++++++++++++++++++++ next.config.mjs | 4 + prisma/schema.prisma | 23 ++ 15 files changed, 553 insertions(+), 19 deletions(-) create mode 100644 app/api/admin/trash/[id]/route.ts create mode 100644 app/api/admin/trash/route.ts create mode 100644 app/settings/trash/page.tsx create mode 100644 components/settings/trash-settings.tsx create mode 100644 lib/trash.ts diff --git a/app/api/admin/trash/[id]/route.ts b/app/api/admin/trash/[id]/route.ts new file mode 100644 index 0000000..6b8ff11 --- /dev/null +++ b/app/api/admin/trash/[id]/route.ts @@ -0,0 +1,36 @@ +import { NextResponse } from 'next/server'; +import { forbidden, getCurrentUser, unauthorized } from '@/lib/auth'; +import { syncPortListeners } from '@/lib/port-router'; +import { deleteTrashItemForever, restoreTrashItem } from '@/lib/trash'; + +export const dynamic = 'force-dynamic'; +type Ctx = { params: { id: string } }; + +async function admin() { + const me = await getCurrentUser(); + if (!me) return unauthorized(); + if (me.role !== 'ADMIN') return forbidden(); + return null; +} + +/** POST → restore this item (a form with its responses, or one response). */ +export async function POST(_req: Request, { params }: Ctx) { + const denied = await admin(); + if (denied) return denied; + try { + const result = await restoreTrashItem(params.id); + if (result.kind === 'form') await syncPortListeners(); + return NextResponse.json(result); + } catch (e) { + return NextResponse.json({ error: e instanceof Error ? e.message : 'Could not restore it.' }, { status: 409 }); + } +} + +/** DELETE → remove this item (and its files) for good. */ +export async function DELETE(_req: Request, { params }: Ctx) { + const denied = await admin(); + if (denied) return denied; + const deleted = await deleteTrashItemForever(params.id); + if (!deleted) return NextResponse.json({ error: 'This item is no longer in the Trash.' }, { status: 404 }); + return NextResponse.json({ deleted }); +} diff --git a/app/api/admin/trash/route.ts b/app/api/admin/trash/route.ts new file mode 100644 index 0000000..20d34d6 --- /dev/null +++ b/app/api/admin/trash/route.ts @@ -0,0 +1,26 @@ +import { NextResponse } from 'next/server'; +import { forbidden, getCurrentUser, unauthorized } from '@/lib/auth'; +import { emptyTrash, listTrash, TRASH_DAYS } from '@/lib/trash'; + +export const dynamic = 'force-dynamic'; + +async function admin() { + const me = await getCurrentUser(); + if (!me) return unauthorized(); + if (me.role !== 'ADMIN') return forbidden(); + return null; +} + +/** GET → everything in the Trash (newest first). */ +export async function GET() { + const denied = await admin(); + if (denied) return denied; + return NextResponse.json({ items: await listTrash(), days: TRASH_DAYS }); +} + +/** DELETE → empty the Trash: removes every item and its files for good. */ +export async function DELETE() { + const denied = await admin(); + if (denied) return denied; + return NextResponse.json({ deleted: await emptyTrash() }); +} diff --git a/app/api/forms/[id]/route.ts b/app/api/forms/[id]/route.ts index b67e767..7da9626 100644 --- a/app/api/forms/[id]/route.ts +++ b/app/api/forms/[id]/route.ts @@ -5,7 +5,7 @@ import { DOMAIN_RE, nextFreePort, portRange, SLUG_RE } from '@/lib/form-links'; import { syncPortListeners } from '@/lib/port-router'; import { isValidSchema, normalizeTags, sanitizeBranding, sanitizeLayout, toFormDTO } from '@/lib/forms'; import { formAudience, notifyFormEvent } from '@/lib/activity'; -import { deleteFormFiles } from '@/lib/response-files'; +import { trashForm } from '@/lib/trash'; import { sanitizeFormNotify } from '@/lib/form-alerts'; import { getSettings } from '@/lib/settings'; @@ -102,9 +102,10 @@ export async function DELETE(_req: Request, { params }: Ctx) { if (!canEditForm(me, params.id)) return forbidden(); try { const audience = await formAudience(params.id); - const form = await prisma.form.delete({ where: { id: params.id } }); + // Into the Trash (Settings → Trash) for 30 days; its uploaded files stay until it leaves the Trash. + const form = await trashForm(params.id, me); + if (!form) throw new Error('not found'); await syncPortListeners(); - void deleteFormFiles(form.id); void notifyFormEvent('form.deleted', me, form, audience); return NextResponse.json({ ok: true }); } catch { diff --git a/app/api/forms/[id]/submissions/route.ts b/app/api/forms/[id]/submissions/route.ts index 1b103df..5457b48 100644 --- a/app/api/forms/[id]/submissions/route.ts +++ b/app/api/forms/[id]/submissions/route.ts @@ -6,7 +6,8 @@ import { formLanguages } from '@/lib/form-i18n'; import { notifySubmission } from '@/lib/notify'; import { sendConfirmation } from '@/lib/form-alerts'; import { notifySubmissionInApp } from '@/lib/activity'; -import { deleteAnswerFiles, responseFileExists } from '@/lib/response-files'; +import { responseFileExists } from '@/lib/response-files'; +import { trashSubmissions } from '@/lib/trash'; import { computeScore } from '@/lib/scoring'; import { validateAnswers } from '@/lib/validation'; import { duplicateAnswers } from '@/lib/unique-answers'; @@ -100,13 +101,7 @@ export async function DELETE(req: Request, { params }: Ctx) { const body = await req.json().catch(() => null); const ids: string[] = Array.isArray(body?.ids) ? body.ids.filter((x: unknown) => typeof x === 'string') : []; if (!ids.length) return NextResponse.json({ error: 'No ids provided' }, { status: 400 }); - // Remember attached files first so they can be removed with the responses. - const doomed = await prisma.submission.findMany({ where: { formId: params.id, id: { in: ids } }, select: { data: true } }); - const { count } = await prisma.submission.deleteMany({ where: { formId: params.id, id: { in: ids } } }); - const form = await prisma.form.findUnique({ where: { id: params.id }, select: { schema: true } }); - if (form) { - const answers = doomed.map((d) => { try { return JSON.parse(d.data); } catch { return {}; } }); - await deleteAnswerFiles(params.id, parseSchema(form.schema).fields, answers).catch(() => {}); - } + // Into the Trash (Settings → Trash) for 30 days; attached files stay until they leave the Trash. + const count = await trashSubmissions(params.id, ids, me); return NextResponse.json({ deleted: count }); } diff --git a/app/settings/trash/page.tsx b/app/settings/trash/page.tsx new file mode 100644 index 0000000..1f3b788 --- /dev/null +++ b/app/settings/trash/page.tsx @@ -0,0 +1,16 @@ +import type { Metadata } from 'next'; +import { TrashSettings } from '@/components/settings/trash-settings'; +import { requireAdmin } from '@/lib/auth'; +import { getServerT } from '@/lib/i18n/server'; +import { listTrash, TRASH_DAYS } from '@/lib/trash'; + +export const dynamic = 'force-dynamic'; +export async function generateMetadata(): Promise { + const t = await getServerT(); + return { title: t('Trash') }; +} + +export default async function TrashPage() { + await requireAdmin(); + return ; +} diff --git a/components/hub/hub-client.tsx b/components/hub/hub-client.tsx index 36f2957..e70172a 100644 --- a/components/hub/hub-client.tsx +++ b/components/hub/hub-client.tsx @@ -386,8 +386,8 @@ export function HubClient({ forms, canCreate, portRange }: { forms: HubForm[]; c {toDelete?.title} {' — '} {toDelete?.responses === 1 - ? t('This form and its 1 response will be permanently deleted. This can’t be undone.') - : t('This form and all of its {n} responses will be permanently deleted. This can’t be undone.', { n: fmtNumber(toDelete?.responses ?? 0, locale) })} + ? t('This form and its 1 response will move to the Trash. An admin can restore them from Settings → Trash for 30 days.') + : t('This form and all of its {n} responses will move to the Trash. An admin can restore them from Settings → Trash for 30 days.', { n: fmtNumber(toDelete?.responses ?? 0, locale) })} } /> diff --git a/components/settings/settings-nav.tsx b/components/settings/settings-nav.tsx index cbd0df6..675f961 100644 --- a/components/settings/settings-nav.tsx +++ b/components/settings/settings-nav.tsx @@ -1,6 +1,6 @@ 'use client'; -import { Bell, Database, Info, Palette, UserCircle2, Users } from 'lucide-react'; +import { Bell, Database, Info, Palette, Trash2, UserCircle2, Users } from 'lucide-react'; import Link from 'next/link'; import { usePathname } from 'next/navigation'; import { useEffect, useRef } from 'react'; @@ -13,6 +13,7 @@ const WORKSPACE = [ { href: '/settings/users', label: 'Users & roles', icon: Users }, { href: '/settings/notifications', label: 'Notifications', icon: Bell }, { href: '/settings/database', label: 'Database & Backup', icon: Database }, + { href: '/settings/trash', label: 'Trash', icon: Trash2 }, { href: '/settings/about', label: 'About', icon: Info }, ]; diff --git a/components/settings/trash-settings.tsx b/components/settings/trash-settings.tsx new file mode 100644 index 0000000..803e7cc --- /dev/null +++ b/components/settings/trash-settings.tsx @@ -0,0 +1,131 @@ +'use client'; + +import { FileText, Inbox, RotateCcw, Trash2 } from 'lucide-react'; +import { useRouter } from 'next/navigation'; +import { useState } from 'react'; +import { useI18n } from '@/components/i18n'; +import { useToast } from '@/components/toast'; +import { Button, ConfirmDialog, EmptyState } from '@/components/ui'; +import type { TrashEntry } from '@/lib/trash'; +import { cn, formatDateTime, timeAgo } from '@/lib/utils'; +import { SettingsCard } from './settings-ui'; + +const DAY_MS = 86_400_000; + +/** Settings → Trash: deleted forms and responses, kept for `days` days, with Restore and Delete forever. */ +export function TrashSettings({ initial, days }: { initial: TrashEntry[]; days: number }) { + const { t, locale } = useI18n(); + const toast = useToast(); + const router = useRouter(); + const [items, setItems] = useState(initial); + const [busy, setBusy] = useState(null); + const [confirm, setConfirm] = useState<{ kind: 'one'; item: TrashEntry } | { kind: 'all' } | null>(null); + + const restore = async (item: TrashEntry) => { + setBusy(item.id); + const res = await fetch(`/api/admin/trash/${item.id}`, { method: 'POST' }); + const j = await res.json().catch(() => null); + setBusy(null); + if (!res.ok) return toast(t(typeof j?.error === 'string' ? j.error : 'Could not restore it.'), 'error'); + setItems((list) => list.filter((i) => i.id !== item.id)); + toast( + item.kind === 'form' + ? j?.changedLink + ? t('Form restored. Its old link was taken, so it got a new one.') + : t('Form restored with its responses.') + : t('Response restored.'), + ); + router.refresh(); + }; + + const remove = async () => { + if (!confirm) return; + setBusy(confirm.kind === 'all' ? 'all' : confirm.item.id); + const res = await fetch(confirm.kind === 'all' ? '/api/admin/trash' : `/api/admin/trash/${confirm.item.id}`, { method: 'DELETE' }); + setBusy(null); + if (!res.ok) { + const j = await res.json().catch(() => null); + return toast(t(typeof j?.error === 'string' ? j.error : 'Could not delete it.'), 'error'); + } + if (confirm.kind === 'all') setItems([]); + // Deleting a form for good also removes its responses that were in the Trash. + else setItems((list) => list.filter((i) => i.id !== confirm.item.id && !(confirm.item.kind === 'form' && i.kind === 'submission' && i.formId === confirm.item.formId))); + setConfirm(null); + toast(confirm.kind === 'all' ? t('Trash emptied.') : t('Deleted for good.')); + }; + + const daysLeft = (i: TrashEntry) => Math.max(0, Math.ceil((new Date(i.expiresAt).getTime() - Date.now()) / DAY_MS)); + + return ( +
+ } + description={t('Deleted forms and responses stay here for {n} days, then they are removed for good together with their uploaded files.', { n: days })} + aside={ + items.length > 0 && ( + + ) + } + > + {items.length === 0 ? ( + } title={t('The Trash is empty')} description={t('Forms and responses you delete appear here.')} /> + ) : ( +
    + {items.map((i) => { + const left = daysLeft(i); + return ( +
  • + + {i.kind === 'form' ? : } + +
    +
    + {i.title || t('Untitled form')} + + {i.kind === 'form' ? (i.count === 1 ? t('Form · 1 response') : t('Form · {n} responses', { n: i.count })) : t('Response')} + +
    + {i.preview &&

    {i.preview}

    } +

    + {t('Deleted {when} by {name}', { when: timeAgo(i.deletedAt, t), name: i.deletedByName || t('someone') })} + {' · '} + {left === 1 ? t('removed for good in 1 day') : t('removed for good in {n} days', { n: left })} +

    + {i.formMissing &&

    {t('Its form is deleted. Restore the form first, then this response.')}

    } +
    +
    + + +
    +
  • + ); + })} +
+ )} +
+ + setConfirm(null)} + onConfirm={remove} + loading={!!busy} + title={confirm?.kind === 'all' ? t('Empty the Trash?') : t('Delete forever?')} + description={ + confirm?.kind === 'all' + ? t('Everything in the Trash and its uploaded files will be removed for good. This can’t be undone.') + : confirm?.item.kind === 'form' + ? t('This form, its responses and its uploaded files will be removed for good. This can’t be undone.') + : t('This response and its uploaded files will be removed for good. This can’t be undone.') + } + confirmLabel={t('Delete forever')} + /> +
+ ); +} diff --git a/components/submissions/submissions-view.tsx b/components/submissions/submissions-view.tsx index 04f18d6..219ef97 100644 --- a/components/submissions/submissions-view.tsx +++ b/components/submissions/submissions-view.tsx @@ -481,7 +481,7 @@ export function SubmissionsView({ onConfirm={doDelete} loading={deleting} title={confirm && confirm.length > 1 ? t('Delete {n} responses?', { n: confirm.length }) : t('Delete response?')} - description={t('This permanently removes the selected response data. This can’t be undone.')} + description={t('The selected responses will move to the Trash. An admin can restore them from Settings → Trash for 30 days.')} confirmLabel={t('Delete')} /> diff --git a/lib/i18n/dict/settings.ts b/lib/i18n/dict/settings.ts index 9abd53c..79ba21a 100644 --- a/lib/i18n/dict/settings.ts +++ b/lib/i18n/dict/settings.ts @@ -3,6 +3,40 @@ import type { AreaDict } from '.'; // Translations for the settings area. Keys are the exact English strings passed to t(). const dict: AreaDict = { ar: { + // Trash + 'Trash': 'سلة المحذوفات', + 'Deleted forms and responses stay here for {n} days, then they are removed for good together with their uploaded files.': 'تبقى النماذج والردود المحذوفة هنا لمدة {n} يومًا، ثم تُزال نهائيًا مع ملفاتها المرفوعة.', + 'Empty Trash': 'إفراغ السلة', + 'The Trash is empty': 'سلة المحذوفات فارغة', + 'Forms and responses you delete appear here.': 'تظهر هنا النماذج والردود التي تحذفها.', + 'Form · 1 response': 'نموذج · رد واحد', + 'Form · {n} responses': 'نموذج · {n} ردود', + 'Response': 'رد', + 'Deleted {when} by {name}': 'حُذف {when} بواسطة {name}', + 'someone': 'شخص ما', + 'removed for good in 1 day': 'يُزال نهائيًا خلال يوم واحد', + 'removed for good in {n} days': 'يُزال نهائيًا خلال {n} يومًا', + 'Its form is deleted. Restore the form first, then this response.': 'نموذجه محذوف. استعد النموذج أولًا، ثم هذا الرد.', + 'Restore': 'استعادة', + 'Delete forever': 'حذف نهائي', + 'Empty the Trash?': 'إفراغ سلة المحذوفات؟', + 'Delete forever?': 'حذف نهائي؟', + 'Everything in the Trash and its uploaded files will be removed for good. This can’t be undone.': 'ستُزال كل محتويات السلة وملفاتها المرفوعة نهائيًا. لا يمكن التراجع عن ذلك.', + 'This form, its responses and its uploaded files will be removed for good. This can’t be undone.': 'سيُزال هذا النموذج وردوده وملفاته المرفوعة نهائيًا. لا يمكن التراجع عن ذلك.', + 'This response and its uploaded files will be removed for good. This can’t be undone.': 'سيُزال هذا الرد وملفاته المرفوعة نهائيًا. لا يمكن التراجع عن ذلك.', + 'Form restored. Its old link was taken, so it got a new one.': 'تمت استعادة النموذج. رابطه القديم مستخدم، لذا حصل على رابط جديد.', + 'Form restored with its responses.': 'تمت استعادة النموذج مع ردوده.', + 'Response restored.': 'تمت استعادة الرد.', + 'Trash emptied.': 'تم إفراغ السلة.', + 'Deleted for good.': 'حُذف نهائيًا.', + 'Could not restore it.': 'تعذّرت الاستعادة.', + 'Could not delete it.': 'تعذّر الحذف.', + 'This item is no longer in the Trash.': 'لم يعد هذا العنصر في السلة.', + 'This item could not be read.': 'تعذّرت قراءة هذا العنصر.', + 'This form already exists.': 'هذا النموذج موجود بالفعل.', + 'This form and its 1 response will move to the Trash. An admin can restore them from Settings → Trash for 30 days.': 'سينتقل هذا النموذج ورده الوحيد إلى سلة المحذوفات. يمكن للمسؤول استعادتهما من الإعدادات ← سلة المحذوفات لمدة 30 يومًا.', + 'This form and all of its {n} responses will move to the Trash. An admin can restore them from Settings → Trash for 30 days.': 'سينتقل هذا النموذج وجميع ردوده البالغة {n} إلى سلة المحذوفات. يمكن للمسؤول استعادتها من الإعدادات ← سلة المحذوفات لمدة 30 يومًا.', + 'The selected responses will move to the Trash. An admin can restore them from Settings → Trash for 30 days.': 'ستنتقل الردود المحددة إلى سلة المحذوفات. يمكن للمسؤول استعادتها من الإعدادات ← سلة المحذوفات لمدة 30 يومًا.', // Layout & navigation 'Manage your workspace, users, notifications and database.': 'أدر مساحة العمل والمستخدمين والإشعارات وقاعدة البيانات.', 'Manage your profile and notification preferences.': 'أدر ملفك الشخصي وتفضيلات الإشعارات.', @@ -412,6 +446,40 @@ const dict: AreaDict = { "Database & Backup": "قاعدة البيانات والنسخ الاحتياطي", }, ta: { + // Trash + 'Trash': 'குப்பைத் தொட்டி', + 'Deleted forms and responses stay here for {n} days, then they are removed for good together with their uploaded files.': 'நீக்கப்பட்ட படிவங்களும் பதில்களும் {n} நாட்கள் இங்கே இருக்கும், பின்னர் அவற்றின் பதிவேற்றிய கோப்புகளுடன் நிரந்தரமாக நீக்கப்படும்.', + 'Empty Trash': 'தொட்டியைக் காலியாக்கு', + 'The Trash is empty': 'குப்பைத் தொட்டி காலியாக உள்ளது', + 'Forms and responses you delete appear here.': 'நீங்கள் நீக்கும் படிவங்களும் பதில்களும் இங்கே தோன்றும்.', + 'Form · 1 response': 'படிவம் · 1 பதில்', + 'Form · {n} responses': 'படிவம் · {n} பதில்கள்', + 'Response': 'பதில்', + 'Deleted {when} by {name}': '{name} {when} நீக்கினார்', + 'someone': 'யாரோ', + 'removed for good in 1 day': '1 நாளில் நிரந்தரமாக நீக்கப்படும்', + 'removed for good in {n} days': '{n} நாட்களில் நிரந்தரமாக நீக்கப்படும்', + 'Its form is deleted. Restore the form first, then this response.': 'இதன் படிவம் நீக்கப்பட்டுள்ளது. முதலில் படிவத்தை மீட்டெடுத்து, பின்னர் இந்தப் பதிலை மீட்டெடுக்கவும்.', + 'Restore': 'மீட்டெடு', + 'Delete forever': 'நிரந்தரமாக நீக்கு', + 'Empty the Trash?': 'குப்பைத் தொட்டியைக் காலியாக்கவா?', + 'Delete forever?': 'நிரந்தரமாக நீக்கவா?', + 'Everything in the Trash and its uploaded files will be removed for good. This can’t be undone.': 'தொட்டியில் உள்ள அனைத்தும் அவற்றின் பதிவேற்றிய கோப்புகளும் நிரந்தரமாக நீக்கப்படும். இதைச் செயல்தவிர்க்க முடியாது.', + 'This form, its responses and its uploaded files will be removed for good. This can’t be undone.': 'இந்தப் படிவம், அதன் பதில்கள், பதிவேற்றிய கோப்புகள் நிரந்தரமாக நீக்கப்படும். இதைச் செயல்தவிர்க்க முடியாது.', + 'This response and its uploaded files will be removed for good. This can’t be undone.': 'இந்தப் பதிலும் அதன் பதிவேற்றிய கோப்புகளும் நிரந்தரமாக நீக்கப்படும். இதைச் செயல்தவிர்க்க முடியாது.', + 'Form restored. Its old link was taken, so it got a new one.': 'படிவம் மீட்டெடுக்கப்பட்டது. பழைய இணைப்பு பயன்பாட்டில் இருந்ததால் புதிய இணைப்பு வழங்கப்பட்டது.', + 'Form restored with its responses.': 'படிவம் அதன் பதில்களுடன் மீட்டெடுக்கப்பட்டது.', + 'Response restored.': 'பதில் மீட்டெடுக்கப்பட்டது.', + 'Trash emptied.': 'தொட்டி காலியாக்கப்பட்டது.', + 'Deleted for good.': 'நிரந்தரமாக நீக்கப்பட்டது.', + 'Could not restore it.': 'மீட்டெடுக்க முடியவில்லை.', + 'Could not delete it.': 'நீக்க முடியவில்லை.', + 'This item is no longer in the Trash.': 'இந்த உருப்படி இப்போது தொட்டியில் இல்லை.', + 'This item could not be read.': 'இந்த உருப்படியைப் படிக்க முடியவில்லை.', + 'This form already exists.': 'இந்தப் படிவம் ஏற்கனவே உள்ளது.', + 'This form and its 1 response will move to the Trash. An admin can restore them from Settings → Trash for 30 days.': 'இந்தப் படிவமும் அதன் 1 பதிலும் குப்பைத் தொட்டிக்குச் செல்லும். நிர்வாகி 30 நாட்கள் வரை அமைப்புகள் → குப்பைத் தொட்டியில் இருந்து மீட்டெடுக்கலாம்.', + 'This form and all of its {n} responses will move to the Trash. An admin can restore them from Settings → Trash for 30 days.': 'இந்தப் படிவமும் அதன் {n} பதில்களும் குப்பைத் தொட்டிக்குச் செல்லும். நிர்வாகி 30 நாட்கள் வரை அமைப்புகள் → குப்பைத் தொட்டியில் இருந்து மீட்டெடுக்கலாம்.', + 'The selected responses will move to the Trash. An admin can restore them from Settings → Trash for 30 days.': 'தேர்ந்தெடுத்த பதில்கள் குப்பைத் தொட்டிக்குச் செல்லும். நிர்வாகி 30 நாட்கள் வரை அமைப்புகள் → குப்பைத் தொட்டியில் இருந்து மீட்டெடுக்கலாம்.', // Layout & navigation 'Manage your workspace, users, notifications and database.': 'உங்கள் பணியிடம், பயனர்கள், அறிவிப்புகள் மற்றும் தரவுத்தளத்தை நிர்வகிக்கவும்.', 'Manage your profile and notification preferences.': 'உங்கள் சுயவிவரம் மற்றும் அறிவிப்பு விருப்பங்களை நிர்வகிக்கவும்.', diff --git a/lib/startup.ts b/lib/startup.ts index a1e7fa9..d1a3c5b 100644 --- a/lib/startup.ts +++ b/lib/startup.ts @@ -3,6 +3,7 @@ import { syncPortListeners } from './port-router'; import { startUpdateChecks } from './activity'; import { startAutoBackups } from './auto-backup'; import { startFormAlertDigests } from './form-alerts'; +import { startTrashPurge } from './trash'; /** Boot tasks: give every form a unique link/port and start the per-form port listeners. */ export async function startup() { @@ -12,6 +13,7 @@ export async function startup() { startUpdateChecks(); startAutoBackups(); startFormAlertDigests(); + startTrashPurge(); // WhatsApp linked in Settings → Notifications: connect again. import('./whatsapp').then((m) => m.waResume()).catch((e) => console.error('[formcraft] whatsapp', e?.message || e)); } catch (err) { diff --git a/lib/system-backup.ts b/lib/system-backup.ts index d44b6ab..4ed5da9 100644 --- a/lib/system-backup.ts +++ b/lib/system-backup.ts @@ -27,9 +27,10 @@ const TABLES = { setting: ['key', 'value', 'updatedAt'], notificationLog: ['id', 'channel', 'target', 'subject', 'status', 'error', 'createdAt'], appMeta: ['key', 'value'], + trashItem: ['id', 'kind', 'formId', 'itemId', 'title', 'count', 'data', 'deletedById', 'deletedByName', 'deletedAt'], } as const; type Table = keyof typeof TABLES; -const DATE_FIELDS = new Set(['createdAt', 'updatedAt', 'lastLoginAt']); +const DATE_FIELDS = new Set(['createdAt', 'updatedAt', 'lastLoginAt', 'deletedAt']); export interface BackupFile { format: typeof BACKUP_FORMAT; @@ -72,7 +73,7 @@ async function readResponseFiles(): Promise { - const [user, form, formAccess, submission, setting, notificationLog, appMeta] = await Promise.all([ + const [user, form, formAccess, submission, setting, notificationLog, appMeta, trashItem] = await Promise.all([ prisma.user.findMany(), prisma.form.findMany(), prisma.formAccess.findMany(), @@ -80,6 +81,7 @@ export async function createSystemBackup({ includeUploads = true }: { includeUpl prisma.setting.findMany(), prisma.notificationLog.findMany(), prisma.appMeta.findMany(), + prisma.trashItem.findMany(), ]); const uploads: BackupFile['uploads'] = []; @@ -93,7 +95,7 @@ export async function createSystemBackup({ includeUploads = true }: { includeUpl const responseFiles = includeUploads ? await readResponseFiles() : []; - const tables = { user, form, formAccess, submission, setting, notificationLog, appMeta } as unknown as BackupFile['tables']; + const tables = { user, form, formAccess, submission, setting, notificationLog, appMeta, trashItem } as unknown as BackupFile['tables']; const counts = { ...Object.fromEntries(Object.entries(tables).map(([k, v]) => [k, v.length])), uploads: uploads.length, responseFiles: responseFiles.length } as BackupFile['counts']; const file: BackupFile = { format: BACKUP_FORMAT, version: BACKUP_VERSION, createdAt: new Date().toISOString(), provider: dbProvider(), counts, tables, uploads, responseFiles }; return { buffer: gzipSync(Buffer.from(JSON.stringify(file)), { level: 9 }), counts }; @@ -151,6 +153,7 @@ export async function restoreSystemBackup(b: BackupFile) { await tx.notificationLog.deleteMany(); await tx.setting.deleteMany(); await tx.appMeta.deleteMany(); + await tx.trashItem.deleteMany(); await tx.form.deleteMany(); await tx.user.deleteMany(); @@ -162,6 +165,7 @@ export async function restoreSystemBackup(b: BackupFile) { for (const c of chunks(rows('setting'))) await tx.setting.createMany({ data: c as any }); for (const c of chunks(rows('notificationLog'))) await tx.notificationLog.createMany({ data: c as any }); for (const c of chunks(rows('appMeta'))) await tx.appMeta.createMany({ data: c as any }); + for (const c of chunks(rows('trashItem'))) await tx.trashItem.createMany({ data: c as any }); /* eslint-enable @typescript-eslint/no-explicit-any */ }, { timeout: 180_000, maxWait: 15_000 }, diff --git a/lib/trash.ts b/lib/trash.ts new file mode 100644 index 0000000..17c8e19 --- /dev/null +++ b/lib/trash.ts @@ -0,0 +1,227 @@ +import type { Form, FormAccess, Submission } from '@prisma/client'; +import { prisma } from './db'; +import { backfillLinks } from './form-links'; +import { parseSchema } from './forms'; +import { deleteAnswerFiles, deleteFormFiles } from './response-files'; +import type { SessionUser } from './roles'; +import type { Answers } from './types'; +import { safeJson } from './utils'; + +/** + * Trash: deleted forms and responses are copied here (full JSON) before they are deleted, and kept for + * TRASH_DAYS so an admin can restore them from Settings → Trash. Their uploaded files stay on disk until the + * item leaves the Trash for good (emptied, deleted forever, or older than TRASH_DAYS). + */ +export const TRASH_DAYS = 30; +const DAY_MS = 86_400_000; + +type Row = Omit & { createdAt: string; updatedAt?: string }; +interface FormSnapshot { + form: Row
; + submissions: Row[]; + access: FormAccess[]; +} +interface SubmissionSnapshot { + submission: Row; +} + +export interface TrashEntry { + id: string; + kind: 'form' | 'submission'; + formId: string; + title: string; + count: number; + deletedByName: string; + deletedAt: string; + expiresAt: string; + /** Response only: a short preview of its answers. */ + preview?: string; + /** Response only: its form is no longer there (deleted or in the Trash), so it can't be restored yet. */ + formMissing?: boolean; +} + +const who = (me: SessionUser) => ({ deletedById: me.id, deletedByName: me.name || me.username }); + +/** Moves a form (with all its responses and its access list) to the Trash. Returns the deleted form. */ +export async function trashForm(formId: string, me: SessionUser) { + const form = await prisma.form.findUnique({ where: { id: formId }, include: { submissions: true, access: true } }); + if (!form) return null; + const { submissions, access, ...row } = form; + await prisma.$transaction([ + prisma.trashItem.create({ + // Dates become ISO strings in the JSON copy (FormSnapshot). + data: { kind: 'form', formId, itemId: formId, title: form.title, count: submissions.length, data: JSON.stringify({ form: row, submissions, access }), ...who(me) }, + }), + prisma.form.delete({ where: { id: formId } }), + ]); + return row; +} + +/** Moves responses of one form to the Trash (one Trash item each). Returns how many were deleted. */ +export async function trashSubmissions(formId: string, ids: string[], me: SessionUser) { + const [rows, form] = await Promise.all([ + prisma.submission.findMany({ where: { formId, id: { in: ids } } }), + prisma.form.findUnique({ where: { id: formId }, select: { title: true } }), + ]); + if (!rows.length) return 0; + await prisma.$transaction([ + prisma.trashItem.createMany({ + data: rows.map((s) => ({ kind: 'submission', formId, itemId: s.id, title: form?.title ?? '', count: 1, data: JSON.stringify({ submission: s }), ...who(me) })), + }), + prisma.submission.deleteMany({ where: { formId, id: { in: rows.map((r) => r.id) } } }), + ]); + return rows.length; +} + +/** A few answers of a response, for the Trash list. */ +function previewOf(data: string, fieldLabels: Map) { + const answers = safeJson(data, {}); + const parts: string[] = []; + for (const [id, v] of Object.entries(answers)) { + if (v === undefined || v === null || v === '') continue; + const text = Array.isArray(v) ? v.join(', ') : String(v); + if (!text || text.startsWith('{')) continue; + parts.push(fieldLabels.has(id) ? `${fieldLabels.get(id)}: ${text}` : text); + if (parts.length >= 2) break; + } + return parts.join(' · ').slice(0, 140); +} + +export async function listTrash(): Promise { + const items = await prisma.trashItem.findMany({ orderBy: { deletedAt: 'desc' }, take: 1000 }); + const formIds = [...new Set(items.filter((i) => i.kind === 'submission').map((i) => i.formId))]; + const forms = formIds.length ? await prisma.form.findMany({ where: { id: { in: formIds } }, select: { id: true, schema: true } }) : []; + const labels = new Map(forms.map((f) => [f.id, new Map(parseSchema(f.schema).fields.map((x) => [x.id, x.label]))])); + return items.map((i) => { + const entry: TrashEntry = { + id: i.id, + kind: i.kind === 'form' ? 'form' : 'submission', + formId: i.formId, + title: i.title, + count: i.count, + deletedByName: i.deletedByName, + deletedAt: i.deletedAt.toISOString(), + expiresAt: new Date(i.deletedAt.getTime() + TRASH_DAYS * DAY_MS).toISOString(), + }; + if (entry.kind === 'submission') { + const snap = safeJson(i.data, null); + entry.preview = snap ? previewOf(snap.submission.data, labels.get(i.formId) ?? new Map()) : ''; + entry.formMissing = !labels.has(i.formId); + } + return entry; + }); +} + +const date = (v: string | undefined) => (v ? new Date(v) : new Date()); + +/** Puts a Trash item back. Throws an Error with a message for the person when it can't. */ +export async function restoreTrashItem(id: string) { + const item = await prisma.trashItem.findUnique({ where: { id } }); + if (!item) throw new Error('This item is no longer in the Trash.'); + + if (item.kind === 'submission') { + const snap = safeJson(item.data, null); + if (!snap) throw new Error('This item could not be read.'); + const form = await prisma.form.findUnique({ where: { id: item.formId }, select: { id: true } }); + if (!form) throw new Error('Its form is deleted. Restore the form first, then this response.'); + const s = snap.submission; + await prisma.$transaction([ + prisma.submission.upsert({ + where: { id: s.id }, + update: {}, + create: { id: s.id, formId: s.formId, data: s.data, score: s.score, maxScore: s.maxScore, language: s.language, respondentId: s.respondentId, ipHash: s.ipHash, createdAt: date(s.createdAt) }, + }), + prisma.trashItem.delete({ where: { id } }), + ]); + return { kind: 'submission' as const, formId: item.formId }; + } + + const snap = safeJson(item.data, null); + if (!snap) throw new Error('This item could not be read.'); + if (await prisma.form.findUnique({ where: { id: item.formId }, select: { id: true } })) throw new Error('This form already exists.'); + const f = snap.form; + // Its public link, port or domain may have been given to another form meanwhile: then it gets new ones. + const [slugTaken, portTaken, domainTaken] = await Promise.all([ + f.slug ? prisma.form.count({ where: { slug: f.slug } }) : 0, + f.port ? prisma.form.count({ where: { port: f.port } }) : 0, + f.customDomain ? prisma.form.count({ where: { customDomain: f.customDomain } }) : 0, + ]); + const users = new Set((await prisma.user.findMany({ where: { id: { in: snap.access.map((a) => a.userId) } }, select: { id: true } })).map((u) => u.id)); + const createdBy = f.createdById ? await prisma.user.count({ where: { id: f.createdById } }) : 0; + await prisma.$transaction(async (tx) => { + await tx.form.create({ + data: { + id: f.id, + title: f.title, + description: f.description, + category: f.category, + tags: f.tags, + status: f.status, + schema: f.schema, + slug: slugTaken ? null : f.slug, + port: portTaken ? null : f.port, + customDomain: domainTaken ? null : f.customDomain, + createdById: createdBy ? f.createdById : null, + createdAt: date(f.createdAt), + }, + }); + const subs = snap.submissions; + for (let i = 0; i < subs.length; i += 500) { + await tx.submission.createMany({ + data: subs.slice(i, i + 500).map((s) => ({ id: s.id, formId: f.id, data: s.data, score: s.score, maxScore: s.maxScore, language: s.language, respondentId: s.respondentId, ipHash: s.ipHash, createdAt: date(s.createdAt) })), + }); + } + const access = snap.access.filter((a) => users.has(a.userId)); + if (access.length) await tx.formAccess.createMany({ data: access.map((a) => ({ userId: a.userId, formId: f.id })) }); + await tx.trashItem.delete({ where: { id } }); + }); + if (slugTaken || portTaken) await backfillLinks(); + return { kind: 'form' as const, formId: item.formId, changedLink: !!(slugTaken || portTaken || domainTaken) }; +} + +/** Removes Trash items for good, together with their uploaded files. */ +async function purge(items: { id: string; kind: string; formId: string; data: string }[]) { + if (!items.length) return 0; + const goneForms = items.filter((i) => i.kind === 'form').map((i) => i.formId); + for (const formId of goneForms) await deleteFormFiles(formId); + // Responses: remove their files (only when the form still exists; otherwise its folder is gone already). + const subs = items.filter((i) => i.kind === 'submission' && !goneForms.includes(i.formId)); + const formIds = [...new Set(subs.map((s) => s.formId))]; + const forms = formIds.length ? await prisma.form.findMany({ where: { id: { in: formIds } }, select: { id: true, schema: true } }) : []; + for (const f of forms) { + const answers = subs.filter((s) => s.formId === f.id).map((s) => safeJson(safeJson(s.data, null)?.submission.data ?? '{}', {})); + await deleteAnswerFiles(f.id, parseSchema(f.schema).fields, answers).catch(() => {}); + } + const { count } = await prisma.trashItem.deleteMany({ + // A form deleted for good also takes its trashed responses with it (they can't be restored without it). + where: { OR: [{ id: { in: items.map((i) => i.id) } }, ...(goneForms.length ? [{ kind: 'submission', formId: { in: goneForms } }] : [])] }, + }); + return count; +} + +export async function deleteTrashItemForever(id: string) { + const item = await prisma.trashItem.findUnique({ where: { id } }); + if (!item) return 0; + return purge([item]); +} + +export async function emptyTrash() { + return purge(await prisma.trashItem.findMany()); +} + +/** Items older than TRASH_DAYS are removed for good. */ +export async function purgeExpiredTrash() { + const cutoff = new Date(Date.now() - TRASH_DAYS * DAY_MS); + return purge(await prisma.trashItem.findMany({ where: { deletedAt: { lt: cutoff } } })); +} + +const g = globalThis as unknown as { __fcTrashTimer?: ReturnType }; + +/** Empties expired Trash items every hour (once per process; first run shortly after boot). */ +export function startTrashPurge() { + if (g.__fcTrashTimer) return; + const run = () => void purgeExpiredTrash().catch((e) => console.error('[formcraft] trash purge:', e instanceof Error ? e.message : e)); + g.__fcTrashTimer = setInterval(run, 3_600_000); + g.__fcTrashTimer.unref?.(); + setTimeout(run, 30_000).unref?.(); +} diff --git a/next.config.mjs b/next.config.mjs index 4dc6569..6fc5d72 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -24,6 +24,10 @@ const nextConfig = { experimental: { // Starts per-form port listeners on boot (instrumentation.ts). instrumentationHook: true, + // Every page shows live data (forms, responses, settings). By default the browser re-used a page it had seen + // in the last 30 s, so e.g. a form created in the builder was missing on the dashboard until a reload. + // 0 = always ask the server on navigation (the branded loading screen covers the wait). + staleTimes: { dynamic: 0 }, serverComponentsExternalPackages: ['@prisma/client', 'nodemailer', '@whiskeysockets/baileys', 'pino', 'pdf-lib'], }, }; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 9667110..f787e27 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -211,3 +211,26 @@ model AppMeta { key String @id value String } + +/// Deleted forms and responses, kept for 30 days (Settings → Trash) so they can be restored. +/// `data` is a full JSON copy: a form with its responses and access list, or one response. +model TrashItem { + id String @id @default(cuid()) + /// "form" | "submission" + kind String + /// The form (for a response: the form it belongs to) + formId String + /// The deleted form's or response's own id + itemId String + /// Form title at the time it was deleted + title String @default("") + /// Number of responses in a deleted form (1 for a response) + count Int @default(0) + data String + deletedById String? + deletedByName String @default("") + deletedAt DateTime @default(now()) + + @@index([deletedAt]) + @@index([formId]) +} From 1fa29bbdc34637acc7f2efdf8deccbf2100414cc Mon Sep 17 00:00:00 2001 From: Sharqan Ahamed <61654902+shatheitguy@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:56:57 +0400 Subject: [PATCH 2/3] Android app: update itself from GitHub releases - Once a day on start (and on demand) the app asks GitHub for the latest release; if it is newer and has FormCraft.apk, it offers Update / Later - Update downloads the APK with a notification and opens Android's installer; the first time Android asks to allow "Install unknown apps" for FormCraft - "Check for updates" via a long-press app-icon shortcut and a link under the connect screen, which now also shows the app version - New permission: REQUEST_INSTALL_PACKAGES (nothing installs without a tap) - README: how updates work and how to publish one (same signing key) --- mobile/README.md | 13 +- .../android/app/src/main/AndroidManifest.xml | 3 + .../in/shatheitguy/formcraft/AppUpdater.java | 234 ++++++++++++++++++ .../shatheitguy/formcraft/MainActivity.java | 29 +++ .../app/src/main/res/values/strings.xml | 13 + .../app/src/main/res/xml/file_paths.xml | 2 + .../app/src/main/res/xml/shortcuts.xml | 12 + mobile/www/index.html | 16 +- 8 files changed, 319 insertions(+), 3 deletions(-) create mode 100644 mobile/android/app/src/main/java/in/shatheitguy/formcraft/AppUpdater.java diff --git a/mobile/README.md b/mobile/README.md index ab2066f..445c950 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -33,8 +33,17 @@ Behaviour: - **Links.** Pages on your server stay in the app. Links to other websites open in the phone's browser. `mailto:`, `tel:`, WhatsApp and other links open in the matching app. - **Sign-in.** The session cookie is kept across restarts. Cookies are flushed when the app goes to the background. -- **File uploads.** `` uses Android's file/photo picker. "Take photo" uses the camera app. The - app asks for no permissions except Internet. +- **File uploads.** `` uses Android's file/photo picker. "Take photo" uses the camera app. No + storage or camera permission is needed. +- **App updates.** Once a day when the app opens, it asks GitHub for the latest release + (`shatheitguy/formcraft`). If that release has a newer version with a `FormCraft.apk` file, the app offers + **Update / Later**. Update downloads the APK (with a notification) and opens Android's installer. The first + time, Android asks to allow *Install unknown apps* for FormCraft. To check by hand, long-press the app icon → + **Check for updates**, or tap *Check for updates* under the connect screen. Permissions: Internet, plus + *install packages* for updates (Android asks before anything is installed). + To publish an update: raise `VERSION`, build, and attach the APK as `FormCraft.apk` to a new GitHub release. + It must be signed with the same key as the installed app (the same release keystore, or for debug builds the + same PC's debug key), or Android refuses to install it over the old one. - **Downloads.** - Normal `http(s)` downloads go through Android's DownloadManager with your session cookie and land in *Downloads* with a notification. These include attachments, backups and files sent as diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml index 1deaf03..d3d4a6d 100644 --- a/mobile/android/app/src/main/AndroidManifest.xml +++ b/mobile/android/app/src/main/AndroidManifest.xml @@ -44,6 +44,9 @@ + + diff --git a/mobile/android/app/src/main/java/in/shatheitguy/formcraft/AppUpdater.java b/mobile/android/app/src/main/java/in/shatheitguy/formcraft/AppUpdater.java new file mode 100644 index 0000000..a7d7ffc --- /dev/null +++ b/mobile/android/app/src/main/java/in/shatheitguy/formcraft/AppUpdater.java @@ -0,0 +1,234 @@ +package in.shatheitguy.formcraft; + +import android.app.Activity; +import android.app.DownloadManager; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.provider.Settings; +import android.widget.Toast; +import androidx.appcompat.app.AlertDialog; +import androidx.core.content.ContextCompat; +import androidx.core.content.FileProvider; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import org.json.JSONArray; +import org.json.JSONObject; + +/** + * In-app updates. New APKs are published as GitHub release files (FormCraft.apk on the latest release). Once a + * day when the app opens (and whenever the person asks: app-icon shortcut or the connect screen), the app asks + * GitHub for the latest release. If it's newer than the installed app, it offers to download it and then opens + * Android's installer. The APK must be signed with the same key as the installed app, or Android refuses it. + */ +class AppUpdater { + + private static final String LATEST = "https://api.github.com/repos/shatheitguy/formcraft/releases/latest"; + private static final String PREFS = "FormCraftUpdates"; + private static final String KEY_LAST_CHECK = "lastCheck"; + private static final long DAY_MS = 24L * 60 * 60 * 1000; + private static final String FILE_NAME = "FormCraft-update.apk"; + + private final Activity activity; + private long downloadId = -1; + /** Downloaded, waiting for the person to allow "Install unknown apps" for FormCraft. */ + private File pendingInstall; + private boolean checking; + + AppUpdater(Activity activity) { + this.activity = activity; + } + + /** The installed app's version, e.g. "1.1.2". */ + String currentVersion() { + try { + return activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionName; + } catch (Exception e) { + return "0"; + } + } + + /** Automatic check: at most once a day, silent unless there is an update. */ + void checkDaily() { + SharedPreferences p = activity.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + if (System.currentTimeMillis() - p.getLong(KEY_LAST_CHECK, 0) < DAY_MS) return; + check(false); + } + + /** `manual`: the person asked, so also say when the app is already up to date or the check failed. */ + void check(boolean manual) { + if (checking) return; + checking = true; + if (manual) toast(R.string.update_checking); + new Thread(() -> { + String tag = null; + String apkUrl = null; + String error = null; + try { + HttpURLConnection c = (HttpURLConnection) new URL(LATEST).openConnection(); + c.setConnectTimeout(10000); + c.setReadTimeout(10000); + c.setRequestProperty("Accept", "application/vnd.github+json"); + c.setRequestProperty("User-Agent", "FormCraft-Android"); + if (c.getResponseCode() != 200) throw new Exception("HTTP " + c.getResponseCode()); + StringBuilder sb = new StringBuilder(); + try (BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream(), "UTF-8"))) { + String line; + while ((line = r.readLine()) != null) sb.append(line); + } + JSONObject release = new JSONObject(sb.toString()); + tag = release.optString("tag_name", "").replaceFirst("^[vV]", ""); + JSONArray assets = release.optJSONArray("assets"); + if (assets != null) { + for (int i = 0; i < assets.length(); i++) { + JSONObject a = assets.getJSONObject(i); + String name = a.optString("name", ""); + String url = a.optString("browser_download_url", ""); + if (name.equals("FormCraft.apk")) { + apkUrl = url; + break; + } + if (apkUrl == null && name.toLowerCase().endsWith(".apk")) apkUrl = url; + } + } + activity.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putLong(KEY_LAST_CHECK, System.currentTimeMillis()).apply(); + } catch (Exception e) { + error = e.getMessage(); + } + final String latest = tag; + final String url = apkUrl; + final boolean failed = error != null; + activity.runOnUiThread(() -> { + checking = false; + if (activity.isFinishing()) return; + if (failed || latest == null || latest.isEmpty()) { + if (manual) toast(R.string.update_check_failed); + } else if (url != null && isNewer(latest, currentVersion())) { + offer(latest, url); + } else if (manual) { + Toast.makeText(activity, activity.getString(R.string.update_latest, currentVersion()), Toast.LENGTH_LONG).show(); + } + }); + }).start(); + } + + /** "1.10.0" > "1.9.3"; extra parts count ("1.2.1" > "1.2"). */ + static boolean isNewer(String latest, String current) { + String[] a = latest.split("[.\\-+]"); + String[] b = current.split("[.\\-+]"); + for (int i = 0; i < Math.max(a.length, b.length); i++) { + int x = i < a.length ? num(a[i]) : 0; + int y = i < b.length ? num(b[i]) : 0; + if (x != y) return x > y; + } + return false; + } + + private static int num(String s) { + try { + return Integer.parseInt(s.replaceAll("\\D", "")); + } catch (NumberFormatException e) { + return 0; + } + } + + private void offer(String version, String url) { + new AlertDialog.Builder(activity) + .setTitle(activity.getString(R.string.update_available_title, version)) + .setMessage(activity.getString(R.string.update_available_text, currentVersion(), version)) + .setPositiveButton(R.string.update_now, (d, w) -> download(url)) + .setNegativeButton(R.string.update_later, null) + .show(); + } + + private void download(String url) { + try { + File dir = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); + if (dir == null) throw new IllegalStateException("no folder"); + File old = new File(dir, FILE_NAME); + if (old.exists() && !old.delete()) throw new IllegalStateException("old file"); + DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url)); + req.setTitle(activity.getString(R.string.update_download_title)); + req.setMimeType("application/vnd.android.package-archive"); + req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); + req.setDestinationInExternalFilesDir(activity, Environment.DIRECTORY_DOWNLOADS, FILE_NAME); + DownloadManager dm = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE); + ContextCompat.registerReceiver(activity, done, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE), ContextCompat.RECEIVER_EXPORTED); + downloadId = dm.enqueue(req); + toast(R.string.update_downloading); + } catch (Exception e) { + toast(R.string.update_failed); + } + } + + private final BroadcastReceiver done = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); + if (id != downloadId) return; + try { + activity.unregisterReceiver(this); + } catch (Exception ignored) { + // already unregistered + } + DownloadManager dm = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE); + boolean ok = false; + try (Cursor c = dm.query(new DownloadManager.Query().setFilterById(id))) { + if (c != null && c.moveToFirst()) { + ok = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL; + } + } + File dir = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); + File apk = dir == null ? null : new File(dir, FILE_NAME); + if (!ok || apk == null || !apk.exists()) { + toast(R.string.update_failed); + return; + } + install(apk); + } + }; + + private void install(File apk) { + // Android 8+: FormCraft needs "Install unknown apps" once; ask for it, then install when the person comes back. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !activity.getPackageManager().canRequestPackageInstalls()) { + pendingInstall = apk; + toast(R.string.update_allow_install); + try { + activity.startActivity(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + activity.getPackageName()))); + } catch (Exception e) { + toast(R.string.update_failed); + } + return; + } + pendingInstall = null; + try { + Uri uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", apk); + Intent i = new Intent(Intent.ACTION_VIEW); + i.setDataAndType(uri, "application/vnd.android.package-archive"); + i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK); + activity.startActivity(i); + } catch (Exception e) { + toast(R.string.update_failed); + } + } + + /** Back from the "Install unknown apps" setting: install now if it was allowed. */ + void onResume() { + if (pendingInstall == null) return; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !activity.getPackageManager().canRequestPackageInstalls()) return; + install(pendingInstall); + } + + private void toast(int res) { + Toast.makeText(activity, res, Toast.LENGTH_LONG).show(); + } +} diff --git a/mobile/android/app/src/main/java/in/shatheitguy/formcraft/MainActivity.java b/mobile/android/app/src/main/java/in/shatheitguy/formcraft/MainActivity.java index 33916dd..86600f1 100644 --- a/mobile/android/app/src/main/java/in/shatheitguy/formcraft/MainActivity.java +++ b/mobile/android/app/src/main/java/in/shatheitguy/formcraft/MainActivity.java @@ -47,6 +47,8 @@ public class MainActivity extends BridgeActivity { private static final String KEY_SERVER = "serverUrl"; /** Static app shortcut (long-press the app icon): "Change server". */ private static final String ACTION_CHANGE_SERVER = "in.shatheitguy.formcraft.CHANGE_SERVER"; + /** Static app shortcut: "Check for updates". */ + private static final String ACTION_CHECK_UPDATE = "in.shatheitguy.formcraft.CHECK_UPDATE"; /** * Runs at document start in every page: remembers Blobs passed to URL.createObjectURL so a later @@ -70,6 +72,7 @@ public class MainActivity extends BridgeActivity { "if(a&&save(a))e.preventDefault();},true);})();"; private boolean shimAtDocumentStart = false; + private AppUpdater updater; @Override public void onCreate(Bundle savedInstanceState) { @@ -114,7 +117,10 @@ public void handleOnBackPressed() { } ); + updater = new AppUpdater(this); handleIntent(getIntent()); + // Once a day: is there a newer FormCraft app on GitHub? (Only says something when there is.) + updater.checkDaily(); } @Override @@ -127,6 +133,15 @@ private void handleIntent(Intent intent) { if (intent != null && ACTION_CHANGE_SERVER.equals(intent.getAction())) { bridge.getWebView().loadUrl(bridge.getLocalUrl() + "/?change=1"); } + if (intent != null && ACTION_CHECK_UPDATE.equals(intent.getAction()) && updater != null) { + updater.check(true); + } + } + + @Override + public void onResume() { + super.onResume(); + if (updater != null) updater.onResume(); } @Override @@ -273,6 +288,20 @@ private void onDownload(String url, String userAgent, String contentDisposition, /** Called from DOWNLOAD_SHIM with the file as a data: URL. */ private class NativeFiles { + /** The installed app's version (shown on the connect screen). */ + @JavascriptInterface + public String appVersion() { + return updater == null ? "" : updater.currentVersion(); + } + + /** "Check for updates" on the connect screen. */ + @JavascriptInterface + public void checkForUpdate() { + runOnUiThread(() -> { + if (updater != null) updater.check(true); + }); + } + @JavascriptInterface public void saveFile(String dataUrl, String fileName, String mimeType) { int comma = dataUrl == null ? -1 : dataUrl.indexOf(','); diff --git a/mobile/android/app/src/main/res/values/strings.xml b/mobile/android/app/src/main/res/values/strings.xml index e5b7701..93e25d7 100644 --- a/mobile/android/app/src/main/res/values/strings.xml +++ b/mobile/android/app/src/main/res/values/strings.xml @@ -11,4 +11,17 @@ The download failed. This download can\'t be saved in the app. Open FormCraft in your browser to download it. No app on this phone can open that link. + Check for updates + Check for a new FormCraft app version + Checking for updates… + Couldn\'t check for updates. Check your internet connection and try again. + You have the latest version (%1$s). + FormCraft %1$s is available + You have %1$s. Update to %2$s now? It downloads in the background, then Android asks you to install it. Your server and sign-in stay as they are. + Update + Later + FormCraft update + Downloading the update… + The update couldn\'t be downloaded or opened. Try again later. + Allow FormCraft to install apps, then go back to finish the update. diff --git a/mobile/android/app/src/main/res/xml/file_paths.xml b/mobile/android/app/src/main/res/xml/file_paths.xml index bd0c4d8..c0ca7bc 100644 --- a/mobile/android/app/src/main/res/xml/file_paths.xml +++ b/mobile/android/app/src/main/res/xml/file_paths.xml @@ -2,4 +2,6 @@ + + \ No newline at end of file diff --git a/mobile/android/app/src/main/res/xml/shortcuts.xml b/mobile/android/app/src/main/res/xml/shortcuts.xml index 49973ab..ca76529 100644 --- a/mobile/android/app/src/main/res/xml/shortcuts.xml +++ b/mobile/android/app/src/main/res/xml/shortcuts.xml @@ -12,4 +12,16 @@ android:targetPackage="in.shatheitguy.formcraft" android:targetClass="in.shatheitguy.formcraft.MainActivity" /> + + + + diff --git a/mobile/www/index.html b/mobile/www/index.html index 6ce381c..54ca79b 100644 --- a/mobile/www/index.html +++ b/mobile/www/index.html @@ -102,6 +102,8 @@ .btn, .link { touch-action: manipulation; } .btn:active:not([disabled]) { transform: scale(.98); } @media (prefers-reduced-motion: reduce) { .mark, .mark .bar, .mark .dot, .mark-wrap .halo { animation: none; } } + footer #app-info { margin-top: 6px; } + .inline-link { padding: 4px 2px; background: none; border: 0; font: inherit; font-weight: 600; color: var(--link); cursor: pointer; touch-action: manipulation; } [hidden] { display: none !important; } @@ -176,7 +178,10 @@

Can't reach your server

-
Your data stays on your own FormCraft server.
+
+ Your data stays on your own FormCraft server. + +