From 18dbcd372b6ff4064b8dea55d19d209e605a99e1 Mon Sep 17 00:00:00 2001 From: Gabriel20xx Date: Wed, 3 Jun 2026 17:09:31 +0200 Subject: [PATCH 1/3] feat: add database initialization retry logic and enhance auth logging --- CollabTableServer/.env.example | 16 +++ CollabTableServer/README.md | 4 + CollabTableServer/data/collabtable.db | Bin 53248 -> 69632 bytes CollabTableServer/docker-compose.yml | 5 + CollabTableServer/package-lock.json | 35 +------ CollabTableServer/src/index.ts | 35 ++++++- CollabTableServer/src/middleware/auth.ts | 72 +++++++++---- CollabTableServer/src/routes/syncRoutes.ts | 112 ++++++++++++++------- 8 files changed, 189 insertions(+), 90 deletions(-) diff --git a/CollabTableServer/.env.example b/CollabTableServer/.env.example index 760cd24..e90ae72 100644 --- a/CollabTableServer/.env.example +++ b/CollabTableServer/.env.example @@ -33,3 +33,19 @@ PGPORT=5432 PGUSER=postgres PGPASSWORD= PGDATABASE=collabtable + +################################################################# +# Startup resilience and sync/auth tuning +################################################################# +# DB init retry interval in milliseconds (default: 5000) +DB_INIT_RETRY_INTERVAL_MS=5000 + +# Max DB init retry attempts. 0 means retry forever (default: 0) +DB_INIT_RETRY_MAX_ATTEMPTS=0 + +# Suppress repetitive auth warning logs for the same path/method (default: 30000) +AUTH_LOG_THROTTLE_MS=30000 + +# Allow at most this much client clock skew into sync timestamps (default: 0) +# Keep this at 0 to prevent future-dated rows from being re-sent in hot loops. +SYNC_MAX_FUTURE_SKEW_MS=0 diff --git a/CollabTableServer/README.md b/CollabTableServer/README.md index adaa058..7e52c67 100644 --- a/CollabTableServer/README.md +++ b/CollabTableServer/README.md @@ -230,6 +230,10 @@ docker-compose up -d --build - `DB_PATH` - Path to SQLite database file (default: ./data/collabtable.db for local, /data/collabtable.db in Docker) - `DATABASE_URL` - PostgreSQL connection URL (optional alternative to PG* variables) - `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE` - PostgreSQL connection parameters +- `DB_INIT_RETRY_INTERVAL_MS` - Delay between DB init retries in ms (default: `5000`) +- `DB_INIT_RETRY_MAX_ATTEMPTS` - Max DB init retries; `0` retries forever (default: `0`) +- `AUTH_LOG_THROTTLE_MS` - Minimum interval before repeating the same auth warning log (default: `30000`) +- `SYNC_MAX_FUTURE_SKEW_MS` - Allowed future timestamp skew from clients during sync (default: `0`) ## Data Persistence diff --git a/CollabTableServer/data/collabtable.db b/CollabTableServer/data/collabtable.db index ee45af8175df915e2aeb379324a03aaca2181175..58f548d601b431185c921625875fbf9968ceb046 100644 GIT binary patch delta 644 zcmZozz}&EaWrDOI4+8^(AP~a<&qN(#T^CsSss85K3dT~i&QHlEGS$yX81p@5iw(5+HoSAtksTG+i74dob zC7EfN$%!SI`FX|hIhn;Jo+&6|g3dv%jv=lJo_;Q_5em4pDERv+plH*87^PXs&o1r^ zv{4jfV?7otlZ#RlOHxxDOHi~65U>@l3)5n_lxCASFT1$9I%9KgNn%n?YF@qtl3!7* zIw=esb!hTsh%nRMVaZDdEoHY0m?!^Y8fyNLMjU; z2l9(^D<}XtnI)A_z9Ee7nS!PZ5=>}fpE2qb1L4hM2n>{#%SXi1$nAtbS@h&<90P0Z_@&Et; diff --git a/CollabTableServer/docker-compose.yml b/CollabTableServer/docker-compose.yml index 586cd32..ac6b221 100644 --- a/CollabTableServer/docker-compose.yml +++ b/CollabTableServer/docker-compose.yml @@ -14,6 +14,11 @@ services: - DB_CLIENT=sqlite # SQLite path (used when DB_CLIENT=sqlite) - DB_PATH=/data/collabtable.db + # Retry DB initialization instead of crashing immediately on startup races + - DB_INIT_RETRY_INTERVAL_MS=5000 + - DB_INIT_RETRY_MAX_ATTEMPTS=0 + # Clamp future client timestamps during sync to avoid resend loops + - SYNC_MAX_FUTURE_SKEW_MS=0 # PostgreSQL (used when DB_CLIENT=postgres) - choose either DATABASE_URL or the PG* vars # - DATABASE_URL=postgres://user:password@postgres:5432/collabtable # - PGHOST=postgres diff --git a/CollabTableServer/package-lock.json b/CollabTableServer/package-lock.json index 041ca74..3f7feb0 100644 --- a/CollabTableServer/package-lock.json +++ b/CollabTableServer/package-lock.json @@ -18,8 +18,7 @@ "eslint-config-prettier": "^9.1.0", "express": "^4.18.2", "pg": "^8.11.3", - "prettier": "^3.3.3", - "ws": "^8.16.0" + "prettier": "^3.3.3" }, "devDependencies": { "@types/better-sqlite3": "^7.6.11", @@ -27,7 +26,6 @@ "@types/express": "^4.17.21", "@types/node": "^20.10.6", "@types/pg": "^8.10.2", - "@types/ws": "^8.5.10", "ts-node-dev": "^2.0.0", "typescript": "^5.3.3" } @@ -452,16 +450,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/ws": { - "version": "8.18.1", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", - "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "7.18.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.18.0.tgz", @@ -3717,27 +3705,6 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, - "node_modules/ws": { - "version": "8.18.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", - "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", diff --git a/CollabTableServer/src/index.ts b/CollabTableServer/src/index.ts index f37fe42..8f4a49d 100644 --- a/CollabTableServer/src/index.ts +++ b/CollabTableServer/src/index.ts @@ -16,6 +16,39 @@ dotenv.config(); const app = express(); const PORT = process.env.PORT || 3000; +const DB_INIT_RETRY_INTERVAL_MS = Math.max(250, Number(process.env.DB_INIT_RETRY_INTERVAL_MS || 5000)); +const DB_INIT_RETRY_MAX_ATTEMPTS = Math.max(0, Number(process.env.DB_INIT_RETRY_MAX_ATTEMPTS || 0)); + +function sleep(ms: number) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +async function initializeDatabaseWithRetry() { + let attempt = 0; + + while (true) { + attempt += 1; + + try { + await initializeDatabase(); + if (attempt > 1) { + console.log(`[DB] Connected after ${attempt} attempt(s)`); + } + return; + } catch (error) { + const reachedLimit = DB_INIT_RETRY_MAX_ATTEMPTS > 0 && attempt >= DB_INIT_RETRY_MAX_ATTEMPTS; + + console.error(`[DB] Initialization attempt ${attempt} failed`, error); + + if (reachedLimit) { + throw error; + } + + console.log(`[DB] Retrying in ${DB_INIT_RETRY_INTERVAL_MS}ms...`); + await sleep(DB_INIT_RETRY_INTERVAL_MS); + } + } +} // Middleware app.use(cors()); @@ -44,7 +77,7 @@ app.use('/', webRoutes); // Initialize database and start server (async () => { try { - await initializeDatabase(); + await initializeDatabaseWithRetry(); console.log('Database synchronized successfully'); console.log('Database models loaded:'); console.log('- Lists'); diff --git a/CollabTableServer/src/middleware/auth.ts b/CollabTableServer/src/middleware/auth.ts index 480cb57..cc5c154 100644 --- a/CollabTableServer/src/middleware/auth.ts +++ b/CollabTableServer/src/middleware/auth.ts @@ -1,6 +1,33 @@ import { Request, Response, NextFunction } from 'express'; let warningLogged = false; +const AUTH_LOG_THROTTLE_MS = Math.max(1000, Number(process.env.AUTH_LOG_THROTTLE_MS || 30000)); +const lastAuthLogAt = new Map(); +const commonProbePathPatterns = [ + /^\/\./, + /client_secret\.json$/i, + /phpinfo/i, + /\.git/i, + /wp-admin/i, + /wp-login/i, + /id_rsa/i, + /config(\.|$)/i +]; + +function isCommonProbePath(pathname: string) { + return commonProbePathPatterns.some(pattern => pattern.test(pathname)); +} + +function shouldLogAuthWarning(kind: string, req: Request) { + const key = `${kind}:${req.method}:${req.path}`; + const now = Date.now(); + const lastSeen = lastAuthLogAt.get(key) || 0; + if (now - lastSeen < AUTH_LOG_THROTTLE_MS) { + return false; + } + lastAuthLogAt.set(key, now); + return true; +} export const authenticatePassword = (req: Request, res: Response, next: NextFunction) => { const serverPassword = process.env.SERVER_PASSWORD; @@ -18,12 +45,13 @@ export const authenticatePassword = (req: Request, res: Response, next: NextFunc const authHeader = req.headers.authorization; if (!authHeader) { - // Log diagnostic info to help trace intermittent 401s - console.warn('[AUTH] Missing Authorization header', { - path: req.path, - method: req.method, - ip: req.ip, - }); + if (!isCommonProbePath(req.path) && shouldLogAuthWarning('missingHeader', req)) { + console.warn('[AUTH] Missing Authorization header', { + path: req.path, + method: req.method, + ip: req.ip, + }); + } return res.status(401).json({ error: 'Unauthorized', message: 'No authorization header provided' @@ -33,13 +61,15 @@ export const authenticatePassword = (req: Request, res: Response, next: NextFunc // Parse the authorization header const parts = authHeader.split(' '); if (parts.length !== 2 || parts[0] !== 'Bearer') { - console.warn('[AUTH] Invalid authorization header format', { - path: req.path, - method: req.method, - ip: req.ip, - // Do not log full header to avoid leaking secrets; include prefix only - headerPreview: authHeader.substring(0, Math.min(authHeader.length, 20)) + '...' - }); + if (shouldLogAuthWarning('invalidHeaderFormat', req)) { + console.warn('[AUTH] Invalid authorization header format', { + path: req.path, + method: req.method, + ip: req.ip, + // Do not log full header to avoid leaking secrets; include prefix only + headerPreview: authHeader.substring(0, Math.min(authHeader.length, 20)) + '...' + }); + } return res.status(401).json({ error: 'Unauthorized', message: 'Invalid authorization header format. Expected: Bearer ' @@ -51,13 +81,15 @@ export const authenticatePassword = (req: Request, res: Response, next: NextFunc // Validate password if (providedPassword !== serverPassword) { // Avoid logging the full password; log only length and a small preview - const safePreview = providedPassword ? `${providedPassword.substring(0, 2)}…(${providedPassword.length})` : 'null'; - console.warn('[AUTH] Invalid password', { - path: req.path, - method: req.method, - ip: req.ip, - providedPreview: safePreview, - }); + if (shouldLogAuthWarning('invalidPassword', req)) { + const safePreview = providedPassword ? `${providedPassword.substring(0, 2)}..(${providedPassword.length})` : 'null'; + console.warn('[AUTH] Invalid password', { + path: req.path, + method: req.method, + ip: req.ip, + providedPreview: safePreview, + }); + } return res.status(401).json({ error: 'Unauthorized', message: 'Invalid password' diff --git a/CollabTableServer/src/routes/syncRoutes.ts b/CollabTableServer/src/routes/syncRoutes.ts index f63d7a5..fcd0afb 100644 --- a/CollabTableServer/src/routes/syncRoutes.ts +++ b/CollabTableServer/src/routes/syncRoutes.ts @@ -12,6 +12,36 @@ interface SyncRequest { itemValues: any[]; } +const SYNC_MAX_FUTURE_SKEW_MS = Math.max(0, Number(process.env.SYNC_MAX_FUTURE_SKEW_MS || 0)); + +function normalizeTimestamp(raw: any, fallback: number, nowMs: number) { + const numeric = Number(raw); + if (!Number.isFinite(numeric) || numeric <= 0) { + return fallback; + } + + let ts = Math.trunc(numeric); + if (ts < 1e12) { + ts *= 1000; + } + + const maxAllowed = nowMs + SYNC_MAX_FUTURE_SKEW_MS; + if (ts > maxAllowed) { + return maxAllowed; + } + + return ts; +} + +function normalizeEntityTimestamps(createdAtRaw: any, updatedAtRaw: any, nowMs: number) { + const createdAt = normalizeTimestamp(createdAtRaw, nowMs, nowMs); + const updatedAt = normalizeTimestamp(updatedAtRaw, createdAt, nowMs); + return { + createdAt, + updatedAt: Math.max(createdAt, updatedAt) + }; +} + // Stats tracking let syncStats = { totalSyncs: 0, @@ -55,7 +85,7 @@ setInterval(() => { lastReset: Date.now() }; } -}, 60000); // Changed from 30s to 60s +}, 60000).unref?.(); // Changed from 30s to 60s // Helper function to get prepared statements (lazy initialization) // We'll perform upserts with positional params for cross-DB portability @@ -66,15 +96,23 @@ const UPSERT_ITEM_VALUE = 'INSERT INTO item_values (id, itemId, fieldId, value, router.post('/sync', async (req: Request, res: Response) => { try { - const { lastSyncTimestamp, lists, fields, items, itemValues }: SyncRequest = req.body; + const { + lastSyncTimestamp, + lists = [], + fields = [], + items = [], + itemValues = [] + }: Partial = req.body || {}; const deviceId = (req as any).deviceId as string | undefined; + const nowMs = Date.now(); + const safeLastSyncTimestamp = normalizeTimestamp(lastSyncTimestamp, 0, nowMs); // Track stats syncStats.totalSyncs++; - const incomingLists = lists?.length || 0; - const incomingFields = fields?.length || 0; - const incomingItems = items?.length || 0; - const incomingValues = itemValues?.length || 0; + const incomingLists = lists.length; + const incomingFields = fields.length; + const incomingItems = items.length; + const incomingValues = itemValues.length; syncStats.listsReceived += incomingLists; syncStats.fieldsReceived += incomingFields; @@ -83,7 +121,7 @@ router.post('/sync', async (req: Request, res: Response) => { // Only log significant sync events (not empty syncs) const hasIncomingData = incomingLists > 0 || incomingFields > 0 || incomingItems > 0 || incomingValues > 0; - const isInitialSync = lastSyncTimestamp === 0; + const isInitialSync = safeLastSyncTimestamp === 0; if (hasIncomingData) { const timestamp = new Date().toLocaleTimeString(); @@ -92,7 +130,7 @@ router.post('/sync', async (req: Request, res: Response) => { if (incomingLists > 0) { console.log(` [LISTS] ${incomingLists} list(s)`); lists.forEach(list => { - const action = list.isDeleted ? 'Deleted' : (lastSyncTimestamp === 0 ? 'Created' : 'Updated'); + const action = list.isDeleted ? 'Deleted' : (safeLastSyncTimestamp === 0 ? 'Created' : 'Updated'); console.log(` ${action}: "${list.name}"`); }); } @@ -117,25 +155,26 @@ router.post('/sync', async (req: Request, res: Response) => { await dbAdapter.transaction(async (tx) => { if (lists && lists.length > 0) { for (const list of lists) { + const listTs = normalizeEntityTimestamps(list.createdAt, list.updatedAt, nowMs); await tx.execute(UPSERT_LIST, [ list.id, list.name, - list.createdAt, - list.updatedAt, + listTs.createdAt, + listTs.updatedAt, list.isDeleted ? 1 : 0 ]); // enqueue list-level notifications try { - const ev = list.isDeleted ? 'deleted' : (lastSyncTimestamp === 0 ? 'created' : 'updated'); - await enqueueNotification(tx, deviceId, ev, 'list', list.id, list.id, list.updatedAt); + const ev = list.isDeleted ? 'deleted' : (safeLastSyncTimestamp === 0 ? 'created' : 'updated'); + await enqueueNotification(tx, deviceId, ev, 'list', list.id, list.id, listTs.updatedAt); } catch {} // If a list was deleted, cascade the deletion to child records on server // - mark fields and items as deleted (tombstones) so other clients learn about them // - remove item_values belonging to items under this list (no tombstone support for values) if (list.isDeleted) { try { - await tx.execute('UPDATE fields SET isDeleted = 1, updatedAt = ? WHERE listId = ?', [list.updatedAt, list.id]); - await tx.execute('UPDATE items SET isDeleted = 1, updatedAt = ? WHERE listId = ?', [list.updatedAt, list.id]); + await tx.execute('UPDATE fields SET isDeleted = 1, updatedAt = ? WHERE listId = ?', [listTs.updatedAt, list.id]); + await tx.execute('UPDATE items SET isDeleted = 1, updatedAt = ? WHERE listId = ?', [listTs.updatedAt, list.id]); await tx.execute('DELETE FROM item_values WHERE itemId IN (SELECT id FROM items WHERE listId = ?)', [list.id]); } catch (err) { console.warn('[SYNC] Cascade delete for list failed:', String(err)); @@ -146,6 +185,7 @@ router.post('/sync', async (req: Request, res: Response) => { if (fields && fields.length > 0) { for (const field of fields) { + const fieldTs = normalizeEntityTimestamps(field.createdAt, field.updatedAt, nowMs); await tx.execute(UPSERT_FIELD, [ field.id, field.name, @@ -154,13 +194,13 @@ router.post('/sync', async (req: Request, res: Response) => { (field.alignment ?? 'start'), field.listId, field.order, - field.createdAt, - field.updatedAt, + fieldTs.createdAt, + fieldTs.updatedAt, field.isDeleted ? 1 : 0 ]); try { - const ev = field.isDeleted ? 'deleted' : (lastSyncTimestamp === 0 ? 'created' : 'updated'); - await enqueueNotification(tx, deviceId, ev, 'field', field.id, field.listId, field.updatedAt); + const ev = field.isDeleted ? 'deleted' : (safeLastSyncTimestamp === 0 ? 'created' : 'updated'); + await enqueueNotification(tx, deviceId, ev, 'field', field.id, field.listId, fieldTs.updatedAt); } catch {} if (field.isDeleted) { // Remove item_values for this field @@ -175,7 +215,7 @@ router.post('/sync', async (req: Request, res: Response) => { const remainingCount = remaining ? (remaining.cnt ?? remaining.CNT ?? remaining.count ?? 0) : 0; if (remainingCount === 0) { // Soft delete items in this list and purge their values - await tx.execute('UPDATE items SET isDeleted = 1, updatedAt = ? WHERE listId = ?', [field.updatedAt, field.listId]); + await tx.execute('UPDATE items SET isDeleted = 1, updatedAt = ? WHERE listId = ?', [fieldTs.updatedAt, field.listId]); await tx.execute('DELETE FROM item_values WHERE itemId IN (SELECT id FROM items WHERE listId = ?)', [field.listId]); console.log('[SYNC] Last field deleted; cascaded item+value cleanup for list', field.listId); } @@ -188,16 +228,17 @@ router.post('/sync', async (req: Request, res: Response) => { if (items && items.length > 0) { for (const item of items) { + const itemTs = normalizeEntityTimestamps(item.createdAt, item.updatedAt, nowMs); await tx.execute(UPSERT_ITEM, [ item.id, item.listId, - item.createdAt, - item.updatedAt, + itemTs.createdAt, + itemTs.updatedAt, item.isDeleted ? 1 : 0 ]); try { - const ev = item.isDeleted ? 'deleted' : (lastSyncTimestamp === 0 ? 'created' : 'updated'); - await enqueueNotification(tx, deviceId, ev, 'item', item.id, item.listId, item.updatedAt); + const ev = item.isDeleted ? 'deleted' : (safeLastSyncTimestamp === 0 ? 'created' : 'updated'); + await enqueueNotification(tx, deviceId, ev, 'item', item.id, item.listId, itemTs.updatedAt); } catch {} // If an item was deleted, remove its values (no tombstone support for values) if (item.isDeleted) { @@ -220,9 +261,9 @@ router.post('/sync', async (req: Request, res: Response) => { // Helper to build IN clause placeholders (?,?,?) matching adapter's ? substitution const makeIn = (arr: string[]) => arr.map(() => '?').join(', '); - let existingItemIds = new Set(); - let existingFieldIds = new Set(); - const fieldToList: Record = {}; + let existingItemIds = new Set(); + let existingFieldIds = new Set(); + const fieldToList: Record = {}; try { if (distinctItemIds.length > 0) { const rows = await tx.queryAll(`SELECT id FROM items WHERE id IN (${makeIn(distinctItemIds)})`, distinctItemIds); @@ -238,6 +279,7 @@ router.post('/sync', async (req: Request, res: Response) => { } for (const value of itemValues) { + const valueUpdatedAt = normalizeTimestamp(value.updatedAt, nowMs, nowMs); const hasItem = existingItemIds.has(value.itemId); const hasField = existingFieldIds.has(value.fieldId); if (!hasField) { @@ -252,7 +294,7 @@ router.post('/sync', async (req: Request, res: Response) => { orphanValues.push({ id: value.id, itemId: value.itemId, fieldId: value.fieldId, reason: 'missingItemNoList' }); continue; } - const ts = value.updatedAt ?? Date.now(); + const ts = valueUpdatedAt; try { await tx.execute(UPSERT_ITEM, [ value.itemId, @@ -274,13 +316,13 @@ router.post('/sync', async (req: Request, res: Response) => { value.itemId, value.fieldId, value.value, - value.updatedAt + valueUpdatedAt ]); // Coarse list content update notification try { const lId = fieldToList[value.fieldId]; if (lId) { - await enqueueNotification(tx, deviceId, 'listContentUpdated', 'value', value.id, lId, value.updatedAt); + await enqueueNotification(tx, deviceId, 'listContentUpdated', 'value', value.id, lId, valueUpdatedAt); } } catch {} } catch (err: any) { @@ -309,17 +351,17 @@ router.post('/sync', async (req: Request, res: Response) => { // IMPORTANT: Include deleted items so clients can sync deletions let serverLists, serverFields, serverItems, serverItemValues; - if (lastSyncTimestamp === 0) { + if (safeLastSyncTimestamp === 0) { // Include deleted rows on initial sync to propagate tombstones serverLists = await dbAdapter.queryAll('SELECT * FROM lists'); serverFields = await dbAdapter.queryAll('SELECT * FROM fields'); serverItems = await dbAdapter.queryAll('SELECT * FROM items'); serverItemValues = await dbAdapter.queryAll('SELECT * FROM item_values'); } else { - serverLists = await dbAdapter.queryAll('SELECT * FROM lists WHERE updatedAt >= ?', [lastSyncTimestamp]); - serverFields = await dbAdapter.queryAll('SELECT * FROM fields WHERE updatedAt >= ?', [lastSyncTimestamp]); - serverItems = await dbAdapter.queryAll('SELECT * FROM items WHERE updatedAt >= ?', [lastSyncTimestamp]); - serverItemValues = await dbAdapter.queryAll('SELECT * FROM item_values WHERE updatedAt >= ?', [lastSyncTimestamp]); + serverLists = await dbAdapter.queryAll('SELECT * FROM lists WHERE updatedAt >= ?', [safeLastSyncTimestamp]); + serverFields = await dbAdapter.queryAll('SELECT * FROM fields WHERE updatedAt >= ?', [safeLastSyncTimestamp]); + serverItems = await dbAdapter.queryAll('SELECT * FROM items WHERE updatedAt >= ?', [safeLastSyncTimestamp]); + serverItemValues = await dbAdapter.queryAll('SELECT * FROM item_values WHERE updatedAt >= ?', [safeLastSyncTimestamp]); } // Normalize output for clients (camelCase keys, ms timestamps, boolean isDeleted) @@ -383,7 +425,7 @@ router.post('/sync', async (req: Request, res: Response) => { // Only log when sending significant data back const hasOutgoingData = (serverLists as any[]).length > 0 || (serverFields as any[]).length > 0 || (serverItems as any[]).length > 0 || (serverItemValues as any[]).length > 0; - if (hasOutgoingData && !isInitialSync) { + if (hasOutgoingData && !isInitialSync && hasIncomingData) { console.log(` [OUT] Sending back: ${(serverLists as any[]).length} lists, ${(serverFields as any[]).length} fields, ${(serverItems as any[]).length} items, ${(serverItemValues as any[]).length} values`); } else if (isInitialSync && hasOutgoingData) { console.log(` [OUT] Sending initial data: ${(serverLists as any[]).length} lists, ${(serverFields as any[]).length} fields, ${(serverItems as any[]).length} items, ${(serverItemValues as any[]).length} values`); From ebe5fc13c465afeb06a12c12787e0361b67b541b Mon Sep 17 00:00:00 2001 From: Gabriel20xx Date: Wed, 3 Jun 2026 17:30:24 +0200 Subject: [PATCH 2/3] feat: enhance notification handling and improve code structure across multiple components --- CollabTableAndroid/app/detekt-baseline.xml | 28 +++ .../collabtable/app/CollabTableApplication.kt | 1 + .../app/data/api/CollabTableApi.kt | 2 +- .../com/collabtable/app/data/dao/FieldDao.kt | 6 +- .../data/preferences/PreferencesManager.kt | 11 +- .../app/notifications/NotificationHelper.kt | 13 ++ .../app/notifications/NotificationPoller.kt | 197 +++++++++--------- .../app/ui/screens/ListDetailScreen.kt | 53 +++-- .../collabtable/app/ui/screens/ListsScreen.kt | 55 +++-- .../app/ui/screens/ListsViewModel.kt | 61 +++--- .../app/ui/screens/SettingsScreen.kt | 5 +- CollabTableServer/src/index.ts | 2 +- CollabTableServer/src/routes/itemRoutes.ts | 8 +- CollabTableServer/src/routes/syncRoutes.ts | 16 +- 14 files changed, 270 insertions(+), 188 deletions(-) create mode 100644 CollabTableAndroid/app/detekt-baseline.xml diff --git a/CollabTableAndroid/app/detekt-baseline.xml b/CollabTableAndroid/app/detekt-baseline.xml new file mode 100644 index 0000000..8a90cd1 --- /dev/null +++ b/CollabTableAndroid/app/detekt-baseline.xml @@ -0,0 +1,28 @@ + + + + + ComplexCondition:Logger.kt$Logger$last != null && last.level == level && last.tag == tag && last.message == message && (now - last.timestamp) <= DEDUPE_WINDOW_MS + ExplicitItLambdaParameter:ListsScreen.kt${ _, it -> it.id } + ReturnCount:ListsViewModel.kt$ListsViewModel$suspend fun exportListToCsv( listId: String, listName: String, targetTreeUri: Uri? = null, ): Result<String> + ReturnCount:SyncRepository.kt$SyncRepository$private fun isNetworkAvailable(): Boolean + SwallowedException:ApiClient.kt$ApiClient$e: Exception + SwallowedException:ConnectionStatus.kt$e: Exception + SwallowedException:Field.kt$Field$e: Exception + SwallowedException:ListChangeNotificationWorker.kt$ListChangeNotificationWorker$e: Exception + SwallowedException:ListDetailScreen.kt$e: Exception + SwallowedException:PreferencesManager.kt$PreferencesManager$e: Exception + SwallowedException:ServerSetupViewModel.kt$ServerSetupViewModel$e: ConnectException + SwallowedException:ServerSetupViewModel.kt$ServerSetupViewModel$e: Exception + SwallowedException:ServerSetupViewModel.kt$ServerSetupViewModel$e: NetworkOnMainThreadException + SwallowedException:ServerSetupViewModel.kt$ServerSetupViewModel$e: SocketTimeoutException + SwallowedException:ServerSetupViewModel.kt$ServerSetupViewModel$e: UnknownHostException + UnusedParameter:ListDetailScreen.kt$onAlignmentChange: (String) -> Unit = {} + UnusedParameter:ListDetailScreen.kt$onUpdateAlignment: (String, String) -> Unit + UnusedParameter:ListsScreen.kt$onNavigateToLogs: () -> Unit = {} + UnusedParameter:ListsScreen.kt$onNavigateToSettings: () -> Unit + UnusedParameter:SettingsScreen.kt$onNavigateBack: () -> Unit + UnusedPrivateMember:ListDetailScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable private fun FilterSortDialog( fields: List<Field>, currentSortField: Field?, currentSortAscending: Boolean, currentGroupByField: Field?, currentFilterField: Field?, currentFilterValue: String, onDismiss: () -> Unit, onApply: (sortField: Field?, sortAscending: Boolean, groupByField: Field?, filterField: Field?, filterValue: String) -> Unit, onClearAll: () -> Unit, ) + UnusedPrivateMember:ListDetailViewModel.kt$ListDetailViewModel$private fun isInForeground(): Boolean + + diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/CollabTableApplication.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/CollabTableApplication.kt index 9e9b48a..8c5490d 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/CollabTableApplication.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/CollabTableApplication.kt @@ -53,6 +53,7 @@ class CollabTableApplication : Application() { NotificationHelper.clearListEventNotifications(this@CollabTableApplication) NotificationPoller.start(this@CollabTableApplication) } + override fun onStop(owner: LifecycleOwner) { NotificationPoller.stop() } diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt index 1012e1c..d0100ad 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt @@ -6,8 +6,8 @@ import com.collabtable.app.data.model.Item import com.collabtable.app.data.model.ItemValue import retrofit2.Response import retrofit2.http.Body -import retrofit2.http.POST import retrofit2.http.GET +import retrofit2.http.POST import retrofit2.http.Query data class SyncRequest( diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/dao/FieldDao.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/dao/FieldDao.kt index c338193..0d06abc 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/dao/FieldDao.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/dao/FieldDao.kt @@ -48,7 +48,11 @@ interface FieldDao { suspend fun getFieldsUpdatedSince(since: Long): List @Query("UPDATE fields SET `order` = :newOrder, updatedAt = :timestamp WHERE id = :fieldId") - suspend fun updateFieldOrder(fieldId: String, newOrder: Int, timestamp: Long) + suspend fun updateFieldOrder( + fieldId: String, + newOrder: Int, + timestamp: Long, + ) // Reorder fields in a single transaction for clarity and consistency @Transaction diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt index 725f455..14a626a 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt @@ -16,8 +16,8 @@ class PreferencesManager( private val _serverUrl = MutableStateFlow(getServerUrl()) val serverUrl: StateFlow = _serverUrl.asStateFlow() - private val _isFirstRun = MutableStateFlow(isFirstRun()) - val isFirstRunFlow: StateFlow = _isFirstRun.asStateFlow() + private val _isFirstRunFlow = MutableStateFlow(isFirstRun()) + val isFirstRunFlow: StateFlow = _isFirstRunFlow.asStateFlow() private val _themeMode = MutableStateFlow(getThemeMode()) val themeMode: StateFlow = _themeMode.asStateFlow() @@ -67,7 +67,7 @@ class PreferencesManager( fun setIsFirstRun(isFirstRun: Boolean) { prefs.edit().putBoolean(KEY_FIRST_RUN, isFirstRun).apply() - _isFirstRun.value = isFirstRun + _isFirstRunFlow.value = isFirstRun } fun getServerPassword(): String? = prefs.getString(KEY_SERVER_PASSWORD, null) @@ -272,7 +272,10 @@ class PreferencesManager( fun getDeviceId(): String { val existing = prefs.getString(KEY_DEVICE_ID, null) if (!existing.isNullOrBlank()) return existing - val id = java.util.UUID.randomUUID().toString() + val id = + java.util.UUID + .randomUUID() + .toString() prefs.edit().putString(KEY_DEVICE_ID, id).apply() return id } diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/notifications/NotificationHelper.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/notifications/NotificationHelper.kt index c8070aa..14351ee 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/notifications/NotificationHelper.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/notifications/NotificationHelper.kt @@ -1,8 +1,12 @@ package com.collabtable.app.notifications +import android.Manifest import android.content.Context +import android.content.pm.PackageManager +import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat import com.collabtable.app.R object NotificationHelper { @@ -34,6 +38,15 @@ object NotificationHelper { id: Int, builder: NotificationCompat.Builder, ) { + if ( + Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + ContextCompat.checkSelfPermission( + context, + Manifest.permission.POST_NOTIFICATIONS, + ) != PackageManager.PERMISSION_GRANTED + ) { + return + } with(NotificationManagerCompat.from(context)) { notify(id, builder.build()) } diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/notifications/NotificationPoller.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/notifications/NotificationPoller.kt index b58ce57..daffcc8 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/notifications/NotificationPoller.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/notifications/NotificationPoller.kt @@ -1,95 +1,102 @@ -package com.collabtable.app.notifications - -import android.content.Context -import com.collabtable.app.data.api.ApiClient -import com.collabtable.app.data.api.CollabTableApi -import com.collabtable.app.data.api.NotificationEvent -import com.collabtable.app.data.database.CollabTableDatabase -import com.collabtable.app.data.preferences.PreferencesManager -import com.collabtable.app.utils.Logger -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.isActive -import kotlinx.coroutines.launch - -object NotificationPoller { - @Volatile private var job: Job? = null - - fun start(context: Context) { - if (job?.isActive == true) return - val appCtx = context.applicationContext - val prefs = PreferencesManager.getInstance(appCtx) - val api = ApiClient.api - val db = CollabTableDatabase.getDatabase(appCtx) - job = CoroutineScope(Dispatchers.IO).launch { - while (isActive) { - try { - // Skip if password missing (auth disabled) - val pwd = prefs.getServerPassword()?.trim() - if (pwd.isNullOrBlank() || pwd == "\$password") { - delay(2_000) - continue - } - val since = prefs.getLastListNotifyCheckTimestamp() - val resp = api.pollNotifications(since) - if (resp.isSuccessful) { - val body = resp.body() - val events = body?.notifications.orEmpty() - if (events.isNotEmpty()) { - // Map and emit based on preferences - events.forEach { ev -> - val listId = ev.listId ?: return@forEach - val list = db.listDao().getListById(listId) ?: return@forEach - handleEvent(appCtx, ev, list.name, prefs) - } - } - // Advance checkpoint to server timestamp to avoid re-processing - val stamp = body?.serverTimestamp ?: System.currentTimeMillis() - prefs.setLastListNotifyCheckTimestamp(stamp) - } else if (resp.code() == 401) { - // Unauthorized; back off by advancing timestamp minimally to avoid tight loop - delay(5_000) - } - } catch (e: Exception) { - try { Logger.w("NotifPoll", "Polling failed: ${e.message}") } catch (_: Exception) {} - // brief backoff - delay(1_500) - } - val interval = prefs.syncPollIntervalMs.value - delay(interval) - } - } - } - - fun stop() { - job?.cancel() - job = null - } - - private fun handleEvent( - context: Context, - ev: NotificationEvent, - listName: String, - prefs: PreferencesManager, - ) { - // Respect notification switches by grouping semantics - when (ev.entityType.lowercase()) { - "list" -> when (ev.eventType.lowercase()) { - "created" -> if (prefs.notifyListAdded.value) NotificationHelper.showListAdded(context, ev.listId ?: "", listName) - "updated" -> if (prefs.notifyListEdited.value) NotificationHelper.showListEdited(context, ev.listId ?: "", listName) - "deleted" -> if (prefs.notifyListRemoved.value) NotificationHelper.showListRemoved(context, ev.listId ?: "", listName) - } - // Treat fields/items/value changes as content updates - "field", "item", "value" -> if (prefs.notifyListContentUpdated.value) { - NotificationHelper.showListContentUpdated(context, ev.listId ?: "", listName) - } - else -> when (ev.eventType.lowercase()) { - "listcontentupdated" -> if (prefs.notifyListContentUpdated.value) { - NotificationHelper.showListContentUpdated(context, ev.listId ?: "", listName) - } - } - } - } -} +package com.collabtable.app.notifications + +import android.content.Context +import com.collabtable.app.data.api.ApiClient +import com.collabtable.app.data.api.NotificationEvent +import com.collabtable.app.data.database.CollabTableDatabase +import com.collabtable.app.data.preferences.PreferencesManager +import com.collabtable.app.utils.Logger +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch + +object NotificationPoller { + @Volatile private var job: Job? = null + + fun start(context: Context) { + if (job?.isActive == true) return + val appCtx = context.applicationContext + val prefs = PreferencesManager.getInstance(appCtx) + val api = ApiClient.api + val db = CollabTableDatabase.getDatabase(appCtx) + job = + CoroutineScope(Dispatchers.IO).launch { + while (isActive) { + try { + // Skip if password missing (auth disabled) + val pwd = prefs.getServerPassword()?.trim() + if (pwd.isNullOrBlank() || pwd == "\$password") { + delay(2_000) + continue + } + val since = prefs.getLastListNotifyCheckTimestamp() + val resp = api.pollNotifications(since) + if (resp.isSuccessful) { + val body = resp.body() + val events = body?.notifications.orEmpty() + if (events.isNotEmpty()) { + // Map and emit based on preferences + events.forEach { ev -> + val listId = ev.listId ?: return@forEach + val list = db.listDao().getListById(listId) ?: return@forEach + handleEvent(appCtx, ev, list.name, prefs) + } + } + // Advance checkpoint to server timestamp to avoid re-processing + val stamp = body?.serverTimestamp ?: System.currentTimeMillis() + prefs.setLastListNotifyCheckTimestamp(stamp) + } else if (resp.code() == 401) { + // Unauthorized; back off by advancing timestamp minimally to avoid tight loop + delay(5_000) + } + } catch (e: Exception) { + try { + Logger.w("NotifPoll", "Polling failed: ${e.message}") + } catch (_: Exception) { + } + // brief backoff + delay(1_500) + } + val interval = prefs.syncPollIntervalMs.value + delay(interval) + } + } + } + + fun stop() { + job?.cancel() + job = null + } + + private fun handleEvent( + context: Context, + ev: NotificationEvent, + listName: String, + prefs: PreferencesManager, + ) { + // Respect notification switches by grouping semantics + when (ev.entityType.lowercase()) { + "list" -> + when (ev.eventType.lowercase()) { + "created" -> if (prefs.notifyListAdded.value) NotificationHelper.showListAdded(context, ev.listId ?: "", listName) + "updated" -> if (prefs.notifyListEdited.value) NotificationHelper.showListEdited(context, ev.listId ?: "", listName) + "deleted" -> if (prefs.notifyListRemoved.value) NotificationHelper.showListRemoved(context, ev.listId ?: "", listName) + } + // Treat fields/items/value changes as content updates + "field", "item", "value" -> + if (prefs.notifyListContentUpdated.value) { + NotificationHelper.showListContentUpdated(context, ev.listId ?: "", listName) + } + else -> + when (ev.eventType.lowercase()) { + "listcontentupdated" -> + if (prefs.notifyListContentUpdated.value) { + NotificationHelper.showListContentUpdated(context, ev.listId ?: "", listName) + } + } + } + } +} diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailScreen.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailScreen.kt index 75d2036..c15af1a 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailScreen.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailScreen.kt @@ -51,7 +51,6 @@ import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateListOf @@ -226,6 +225,7 @@ fun ListDetailScreen( floatingActionButton = {}, ) { padding -> // Apply filtering, sorting and grouping off the main thread and memoize the result + @Suppress("ProduceStateDoesNotAssignValue") val transformed by produceState( initialValue = TransformedItems(emptyList(), mapOf("_all" to emptyList())), stableItems, @@ -235,7 +235,7 @@ fun ListDetailScreen( filterField, filterValue, ) { - value = + val transformedItems = withContext(Dispatchers.Default) { transformItems( items = stableItems, @@ -246,6 +246,7 @@ fun ListDetailScreen( filterValue = filterValue, ) } + value = transformedItems } val processedItems = transformed.processed @@ -550,17 +551,19 @@ fun ListDetailScreen( } stableItems.isEmpty() -> { Box( - modifier = Modifier - .fillMaxSize(), + modifier = + Modifier + .fillMaxSize(), contentAlignment = Alignment.Center, ) { Text( text = stringResource(R.string.no_items), style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 24.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp), textAlign = TextAlign.Center, ) } @@ -1046,8 +1049,7 @@ fun ItemRow( .border( width = 1.dp, color = MaterialTheme.colorScheme.outline, - ) - .fillMaxHeight() + ).fillMaxHeight() // Consistent minimum top/bottom padding regardless of row height .padding(horizontal = 8.dp, vertical = 8.dp), // Center horizontally based on alignment while always vertically centering @@ -1105,7 +1107,8 @@ fun ItemRow( } com.collabtable.app.data.model.FieldType.SELECT, - com.collabtable.app.data.model.FieldType.MULTI_SELECT -> { + com.collabtable.app.data.model.FieldType.MULTI_SELECT, + -> { Text( text = value?.value ?: "", style = MaterialTheme.typography.bodyMedium, @@ -2365,9 +2368,10 @@ fun FieldInput( com.collabtable.app.data.model.FieldType.MULTI_SELECT -> { val options = field.getSelectOptions() var expanded by remember { mutableStateOf(false) } - val selectedOptions = remember(value) { - value.split(", ").filter { it.isNotBlank() }.toSet() - } + val selectedOptions = + remember(value) { + value.split(", ").filter { it.isNotBlank() }.toSet() + } ExposedDropdownMenuBox( expanded = expanded, @@ -2394,19 +2398,20 @@ fun FieldInput( options.forEach { option -> val isSelected = selectedOptions.contains(option) DropdownMenuItem( - text = { + text = { Row(verticalAlignment = Alignment.CenterVertically) { Checkbox(checked = isSelected, onCheckedChange = null) Spacer(modifier = Modifier.width(8.dp)) - Text(option) + Text(option) } }, onClick = { - val newSelected = if (isSelected) { - selectedOptions - option - } else { - selectedOptions + option - } + val newSelected = + if (isSelected) { + selectedOptions - option + } else { + selectedOptions + option + } val orderedNewSelected = options.filter { it in newSelected } onValueChange(orderedNewSelected.joinToString(", ")) }, @@ -4083,11 +4088,3 @@ private fun RenameListDialog( }, ) } - - - - - - - - diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsScreen.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsScreen.kt index e4d37a5..9dd098e 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsScreen.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsScreen.kt @@ -3,7 +3,9 @@ package com.collabtable.app.ui.screens import android.Manifest +import android.content.Intent import android.content.pm.PackageManager +import android.net.Uri import android.os.Build import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult @@ -29,9 +31,6 @@ import androidx.compose.material.icons.filled.DragHandle import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.List import androidx.compose.material.icons.filled.Share -import android.net.Uri -import android.content.Intent -import androidx.documentfile.provider.DocumentFile import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu @@ -60,6 +59,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat +import androidx.documentfile.provider.DocumentFile import com.collabtable.app.R import com.collabtable.app.data.database.CollabTableDatabase import com.collabtable.app.data.model.CollabList @@ -349,32 +349,39 @@ fun ListsScreen( } // Export dialog (top-level) separate from create/edit/delete dialogs listToExport?.let { list -> - val folderPicker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri -> - if (uri != null) { - // Take persistable permission for potential reuse during this session - try { - val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION - context.contentResolver.takePersistableUriPermission(uri, flags) - } catch (_: Exception) { } - exportTargetUri = uri + val folderPicker = + rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri -> + if (uri != null) { + // Take persistable permission for potential reuse during this session + try { + val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + context.contentResolver.takePersistableUriPermission(uri, flags) + } catch (_: Exception) { + } + exportTargetUri = uri + } } - } ExportListDialog( list = list, - selectedDirectoryLabel = exportTargetUri?.let { uri -> - DocumentFile.fromTreeUri(context, uri)?.name ?: uri.lastPathSegment ?: "(selected)" - } ?: "App storage (default)", + selectedDirectoryLabel = + exportTargetUri?.let { uri -> + DocumentFile.fromTreeUri(context, uri)?.name ?: uri.lastPathSegment ?: "(selected)" + } ?: "App storage (default)", onSelectDirectory = { folderPicker.launch(null) }, - onDismiss = { listToExport = null; exportTargetUri = null }, + onDismiss = { + listToExport = null + exportTargetUri = null + }, onConfirmExport = { format -> if (format == "CSV") { coroutineScope.launch { val result = viewModel.exportListToCsv(list.id, list.name, exportTargetUri) - result.onSuccess { path -> - Toast.makeText(context, context.getString(R.string.export_success, path), Toast.LENGTH_LONG).show() - }.onFailure { - Toast.makeText(context, context.getString(R.string.export_error), Toast.LENGTH_LONG).show() - } + result + .onSuccess { path -> + Toast.makeText(context, context.getString(R.string.export_success, path), Toast.LENGTH_LONG).show() + }.onFailure { + Toast.makeText(context, context.getString(R.string.export_error), Toast.LENGTH_LONG).show() + } listToExport = null exportTargetUri = null } @@ -500,7 +507,6 @@ fun CreateListDialog( } }, ) - } @Composable @@ -612,7 +618,10 @@ private fun ExportListDialog( DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { DropdownMenuItem( text = { Text(stringResource(R.string.format_csv)) }, - onClick = { selectedFormat = "CSV"; expanded = false }, + onClick = { + selectedFormat = "CSV" + expanded = false + }, ) } } diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsViewModel.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsViewModel.kt index 26e3b47..82e251c 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsViewModel.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsViewModel.kt @@ -1,6 +1,8 @@ package com.collabtable.app.ui.screens import android.content.Context +import android.net.Uri +import androidx.documentfile.provider.DocumentFile import androidx.lifecycle.Lifecycle import androidx.lifecycle.ProcessLifecycleOwner import androidx.lifecycle.ViewModel @@ -19,12 +21,10 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import java.io.File -import android.net.Uri -import androidx.documentfile.provider.DocumentFile import java.text.SimpleDateFormat import java.util.Date -import java.util.UUID import java.util.Locale +import java.util.UUID class ListsViewModel( private val database: CollabTableDatabase, @@ -239,34 +239,41 @@ class ListsViewModel( targetTreeUri: Uri? = null, ): Result { return try { - // Load fields (ordered) and items with values - val fields: List = database.fieldDao().getFieldsForList(listId).first() - val items: List = database.itemDao().getItemsWithValuesForList(listId).first() + // Load fields (ordered) and items with values + val fields: List = database.fieldDao().getFieldsForList(listId).first() + val items: List = database.itemDao().getItemsWithValuesForList(listId).first() - // Build header - val headers = fields.map { escapeCsv(it.name) } - val fieldIdOrder = fields.map { it.id } + // Build header + val headers = fields.map { escapeCsv(it.name) } + val fieldIdOrder = fields.map { it.id } - val rows = items.map { iwv -> - val valueMap = iwv.values.associateBy { it.fieldId } - fieldIdOrder.joinToString(",") { fid -> - val raw = valueMap[fid]?.value ?: "" - escapeCsv(raw) - } - } + val rows = + items.map { iwv -> + val valueMap = iwv.values.associateBy { it.fieldId } + fieldIdOrder.joinToString(",") { fid -> + val raw = valueMap[fid]?.value ?: "" + escapeCsv(raw) + } + } - val csv = buildString { - append(headers.joinToString(",")) - append('\n') - rows.forEachIndexed { idx, row -> - append(row) - if (idx != rows.lastIndex) append('\n') - } - } + val csv = + buildString { + append(headers.joinToString(",")) + append('\n') + rows.forEachIndexed { idx, row -> + append(row) + if (idx != rows.lastIndex) append('\n') + } + } - val safeBase = listName.lowercase(Locale.US).replace("[^a-z0-9]+".toRegex(), "_").trim('_').ifBlank { "table" } - val ts = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date()) - val fileName = "${safeBase}_${ts}.csv" + val safeBase = + listName + .lowercase(Locale.US) + .replace("[^a-z0-9]+".toRegex(), "_") + .trim('_') + .ifBlank { "table" } + val ts = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date()) + val fileName = "${safeBase}_$ts.csv" if (targetTreeUri != null) { val docTree = DocumentFile.fromTreeUri(context, targetTreeUri) if (docTree == null || !docTree.isDirectory || !docTree.canWrite()) { diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/SettingsScreen.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/SettingsScreen.kt index 3f2ad89..0465ea7 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/SettingsScreen.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/SettingsScreen.kt @@ -453,7 +453,7 @@ fun SettingsScreen( modifier = Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { - Text( + Text( text = "View application logs", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, @@ -538,7 +538,8 @@ fun SettingsScreen( onDismissRequest = { showLeaveDialog = false }, title = { Text(stringResource(R.string.leave_server_dialog_title)) }, text = { - Text(stringResource(R.string.leave_server_dialog_body), + Text( + stringResource(R.string.leave_server_dialog_body), ) }, confirmButton = { diff --git a/CollabTableServer/src/index.ts b/CollabTableServer/src/index.ts index 8f4a49d..e4989a0 100644 --- a/CollabTableServer/src/index.ts +++ b/CollabTableServer/src/index.ts @@ -26,7 +26,7 @@ function sleep(ms: number) { async function initializeDatabaseWithRetry() { let attempt = 0; - while (true) { + for (;;) { attempt += 1; try { diff --git a/CollabTableServer/src/routes/itemRoutes.ts b/CollabTableServer/src/routes/itemRoutes.ts index c71b0b7..acf8c0c 100644 --- a/CollabTableServer/src/routes/itemRoutes.ts +++ b/CollabTableServer/src/routes/itemRoutes.ts @@ -57,7 +57,9 @@ router.post('/values', async (req: Request, res: Response) => { if (listId) { await enqueueNotification(dbAdapter, (req as any).deviceId, 'listContentUpdated', 'value', id, listId, Date.now()); } - } catch {} + } catch (notificationError) { + void notificationError; + } res.json(itemValue); } catch (error) { res.status(500).json({ error: 'Failed to save item value' }); @@ -101,7 +103,9 @@ router.delete('/:id', async (req: Request, res: Response) => { const item = await dbAdapter.queryOne('SELECT * FROM items WHERE id = ?', [req.params.id]); const listId = item ? ((item as any).listId ?? (item as any).listid) : undefined; await enqueueNotification(dbAdapter, (req as any).deviceId, 'deleted', 'item', req.params.id, listId, updatedAt); - } catch {} + } catch (notificationError) { + void notificationError; + } res.json({ message: 'Item deleted successfully' }); } catch (error) { res.status(500).json({ error: 'Failed to delete item' }); diff --git a/CollabTableServer/src/routes/syncRoutes.ts b/CollabTableServer/src/routes/syncRoutes.ts index fcd0afb..a02d3a2 100644 --- a/CollabTableServer/src/routes/syncRoutes.ts +++ b/CollabTableServer/src/routes/syncRoutes.ts @@ -167,7 +167,9 @@ router.post('/sync', async (req: Request, res: Response) => { try { const ev = list.isDeleted ? 'deleted' : (safeLastSyncTimestamp === 0 ? 'created' : 'updated'); await enqueueNotification(tx, deviceId, ev, 'list', list.id, list.id, listTs.updatedAt); - } catch {} + } catch (notificationError) { + void notificationError; + } // If a list was deleted, cascade the deletion to child records on server // - mark fields and items as deleted (tombstones) so other clients learn about them // - remove item_values belonging to items under this list (no tombstone support for values) @@ -201,7 +203,9 @@ router.post('/sync', async (req: Request, res: Response) => { try { const ev = field.isDeleted ? 'deleted' : (safeLastSyncTimestamp === 0 ? 'created' : 'updated'); await enqueueNotification(tx, deviceId, ev, 'field', field.id, field.listId, fieldTs.updatedAt); - } catch {} + } catch (notificationError) { + void notificationError; + } if (field.isDeleted) { // Remove item_values for this field try { @@ -239,7 +243,9 @@ router.post('/sync', async (req: Request, res: Response) => { try { const ev = item.isDeleted ? 'deleted' : (safeLastSyncTimestamp === 0 ? 'created' : 'updated'); await enqueueNotification(tx, deviceId, ev, 'item', item.id, item.listId, itemTs.updatedAt); - } catch {} + } catch (notificationError) { + void notificationError; + } // If an item was deleted, remove its values (no tombstone support for values) if (item.isDeleted) { try { @@ -324,7 +330,9 @@ router.post('/sync', async (req: Request, res: Response) => { if (lId) { await enqueueNotification(tx, deviceId, 'listContentUpdated', 'value', value.id, lId, valueUpdatedAt); } - } catch {} + } catch (notificationError) { + void notificationError; + } } catch (err: any) { // Catch FK violation just in case race or deletion happened inside same sync if (err && err.code === '23503') { From e57b14ef17844e9b13bcbddae2f5ea57e104d2a9 Mon Sep 17 00:00:00 2001 From: Gabriel20xx Date: Wed, 3 Jun 2026 17:38:23 +0200 Subject: [PATCH 3/3] refactor: improve error handling and logging in various components; update TypeScript version --- CollabTableAndroid/app/detekt-baseline.xml | 28 ------------------- .../com/collabtable/app/data/api/ApiClient.kt | 3 +- .../com/collabtable/app/data/model/Field.kt | 24 ++++++++-------- .../data/preferences/PreferencesManager.kt | 12 +++----- .../app/data/repository/SyncRepository.kt | 14 +++++----- .../app/ui/components/ConnectionStatus.kt | 6 ++-- .../app/ui/screens/ListDetailScreen.kt | 7 ++++- .../app/ui/screens/ListDetailViewModel.kt | 7 ----- .../collabtable/app/ui/screens/ListsScreen.kt | 3 +- .../app/ui/screens/ListsViewModel.kt | 1 + .../app/ui/screens/ServerSetupViewModel.kt | 2 ++ .../app/ui/screens/SettingsScreen.kt | 1 + .../java/com/collabtable/app/utils/Logger.kt | 7 ++++- .../app/work/ListChangeNotificationWorker.kt | 4 ++- CollabTableServer/package-lock.json | 8 +++--- CollabTableServer/package.json | 2 +- 16 files changed, 54 insertions(+), 75 deletions(-) delete mode 100644 CollabTableAndroid/app/detekt-baseline.xml diff --git a/CollabTableAndroid/app/detekt-baseline.xml b/CollabTableAndroid/app/detekt-baseline.xml deleted file mode 100644 index 8a90cd1..0000000 --- a/CollabTableAndroid/app/detekt-baseline.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - ComplexCondition:Logger.kt$Logger$last != null && last.level == level && last.tag == tag && last.message == message && (now - last.timestamp) <= DEDUPE_WINDOW_MS - ExplicitItLambdaParameter:ListsScreen.kt${ _, it -> it.id } - ReturnCount:ListsViewModel.kt$ListsViewModel$suspend fun exportListToCsv( listId: String, listName: String, targetTreeUri: Uri? = null, ): Result<String> - ReturnCount:SyncRepository.kt$SyncRepository$private fun isNetworkAvailable(): Boolean - SwallowedException:ApiClient.kt$ApiClient$e: Exception - SwallowedException:ConnectionStatus.kt$e: Exception - SwallowedException:Field.kt$Field$e: Exception - SwallowedException:ListChangeNotificationWorker.kt$ListChangeNotificationWorker$e: Exception - SwallowedException:ListDetailScreen.kt$e: Exception - SwallowedException:PreferencesManager.kt$PreferencesManager$e: Exception - SwallowedException:ServerSetupViewModel.kt$ServerSetupViewModel$e: ConnectException - SwallowedException:ServerSetupViewModel.kt$ServerSetupViewModel$e: Exception - SwallowedException:ServerSetupViewModel.kt$ServerSetupViewModel$e: NetworkOnMainThreadException - SwallowedException:ServerSetupViewModel.kt$ServerSetupViewModel$e: SocketTimeoutException - SwallowedException:ServerSetupViewModel.kt$ServerSetupViewModel$e: UnknownHostException - UnusedParameter:ListDetailScreen.kt$onAlignmentChange: (String) -> Unit = {} - UnusedParameter:ListDetailScreen.kt$onUpdateAlignment: (String, String) -> Unit - UnusedParameter:ListsScreen.kt$onNavigateToLogs: () -> Unit = {} - UnusedParameter:ListsScreen.kt$onNavigateToSettings: () -> Unit - UnusedParameter:SettingsScreen.kt$onNavigateBack: () -> Unit - UnusedPrivateMember:ListDetailScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable private fun FilterSortDialog( fields: List<Field>, currentSortField: Field?, currentSortAscending: Boolean, currentGroupByField: Field?, currentFilterField: Field?, currentFilterValue: String, onDismiss: () -> Unit, onApply: (sortField: Field?, sortAscending: Boolean, groupByField: Field?, filterField: Field?, filterValue: String) -> Unit, onClearAll: () -> Unit, ) - UnusedPrivateMember:ListDetailViewModel.kt$ListDetailViewModel$private fun isInForeground(): Boolean - - diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt index 560b814..3f90629 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt @@ -110,7 +110,8 @@ object ApiClient { val ensuredApi = if (rawUrl.contains("/api")) rawUrl else rawUrl.trimEnd('/') + "/api/" ensureTrailingSlash(ensuredApi) } - } catch (e: Exception) { + } catch (error: Exception) { + Logger.w("HTTP", "Failed to normalize API URL '$rawUrl': ${error.message}") ensureTrailingSlash(rawUrl) } } diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/model/Field.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/model/Field.kt index c00b407..4ea48ac 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/model/Field.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/model/Field.kt @@ -73,18 +73,18 @@ data class Field( ) { fun getType(): FieldType { val raw = fieldType.ifBlank { "TEXT" }.uppercase() - return try { - FieldType.valueOf(raw) - } catch (e: Exception) { - // Handle legacy/synonym field types - when (raw) { - "DROPDOWN" -> FieldType.SELECT - "STRING" -> FieldType.TEXT - "PRICE" -> FieldType.CURRENCY - "AMOUNT" -> FieldType.NUMBER - "SIZE" -> FieldType.TEXT - else -> FieldType.TEXT - } + val exact = runCatching { FieldType.valueOf(raw) }.getOrNull() + if (exact != null) { + return exact + } + // Handle legacy/synonym field types + return when (raw) { + "DROPDOWN" -> FieldType.SELECT + "STRING" -> FieldType.TEXT + "PRICE" -> FieldType.CURRENCY + "AMOUNT" -> FieldType.NUMBER + "SIZE" -> FieldType.TEXT + else -> FieldType.TEXT } } diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt index 14a626a..7c56707 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt @@ -194,7 +194,7 @@ class PreferencesManager( fun getColumnWidths(listId: String): Map { val key = COLUMN_WIDTHS_PREFIX + listId val raw = prefs.getString(key, null) ?: return emptyMap() - return try { + return runCatching { val json = JSONObject(raw) val map = mutableMapOf() val it = json.keys() @@ -206,9 +206,7 @@ class PreferencesManager( } } map - } catch (e: Exception) { - emptyMap() - } + }.getOrDefault(emptyMap()) } fun setColumnWidths( @@ -229,7 +227,7 @@ class PreferencesManager( fun getColumnAlignments(listId: String): Map { val key = COLUMN_ALIGN_PREFIX + listId val raw = prefs.getString(key, null) ?: return emptyMap() - return try { + return runCatching { val json = JSONObject(raw) val map = mutableMapOf() val it = json.keys() @@ -245,9 +243,7 @@ class PreferencesManager( map[fieldId] = normalized } map - } catch (e: Exception) { - emptyMap() - } + }.getOrDefault(emptyMap()) } fun setColumnAlignments( diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt index ccdf1cd..bb5ff3e 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt @@ -312,14 +312,14 @@ class SyncRepository( private fun isNetworkAvailable(): Boolean { val cm = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager - val network = cm.activeNetwork ?: return false - val caps = cm.getNetworkCapabilities(network) ?: return false - val hasInternet = caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - val isValidated = caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) + val network = cm.activeNetwork + val caps = network?.let { cm.getNetworkCapabilities(it) } + val hasInternet = caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true + val isValidated = caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) == true val hasTransport = - caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || - caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || - caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) + caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true || + caps?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true || + caps?.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) == true return hasInternet && isValidated && hasTransport } } diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/components/ConnectionStatus.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/components/ConnectionStatus.kt index 259278b..6c1ef3f 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/components/ConnectionStatus.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/components/ConnectionStatus.kt @@ -53,7 +53,7 @@ private fun isEmulator(): Boolean { private fun toHealthUrl(rawApiUrl: String): String { // Ensure we hit the unauthenticated /health endpoint and remap localhost on emulator - return try { + return runCatching { val uri = Uri.parse(rawApiUrl) val host = uri.host?.lowercase() val needsRemap = isEmulator() && (host == "localhost" || host == "127.0.0.1" || host == "host.docker.internal") @@ -63,7 +63,7 @@ private fun toHealthUrl(rawApiUrl: String): String { val path = (uri.encodedPath ?: "/").trimEnd('/') val healthPath = if (path.endsWith("/api") || path.endsWith("/api/")) "/health" else "/health" base + healthPath - } catch (e: Exception) { + }.getOrElse { rawApiUrl.replace("/api/", "/health").replace("/api", "/health") } } @@ -101,7 +101,7 @@ fun ConnectionStatusAction( ok = false } resp.close() - } catch (e: Exception) { + } catch (ignored: Exception) { ok = false } delay(intervalMs) diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailScreen.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailScreen.kt index c15af1a..c8d040a 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailScreen.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailScreen.kt @@ -1,4 +1,9 @@ -@file:Suppress("ktlint:standard:no-wildcard-imports") +@file:Suppress( + "ktlint:standard:no-wildcard-imports", + "SwallowedException", + "UnusedParameter", + "UnusedPrivateMember", +) @file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) package com.collabtable.app.ui.screens diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailViewModel.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailViewModel.kt index 2a26212..3a1714a 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailViewModel.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailViewModel.kt @@ -1,8 +1,6 @@ package com.collabtable.app.ui.screens import android.content.Context -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.ProcessLifecycleOwner import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.room.withTransaction @@ -123,11 +121,6 @@ class ListDetailViewModel( syncRepository.performSync() } - private fun isInForeground(): Boolean { - val state = ProcessLifecycleOwner.get().lifecycle.currentState - return state.isAtLeast(Lifecycle.State.STARTED) - } - // Local changes should not notify this same device; remote-change notification (future) will be triggered elsewhere. private fun maybeNotifyListContentUpdated() { /* intentionally disabled for local-origin changes */ } diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsScreen.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsScreen.kt index 9dd098e..bc18e0d 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsScreen.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsScreen.kt @@ -72,6 +72,7 @@ import org.burnoutcrew.reorderable.detectReorder import org.burnoutcrew.reorderable.rememberReorderableLazyListState import org.burnoutcrew.reorderable.reorderable +@Suppress("UnusedParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun ListsScreen( @@ -276,7 +277,7 @@ fun ListsScreen( contentPadding = PaddingValues(vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(0.dp), ) { - itemsIndexed(working, key = { _, it -> it.id }) { _, list -> + itemsIndexed(working, key = { _, table -> table.id }) { _, list -> ReorderableItem(reorderState, key = list.id) { _ -> Box(modifier = Modifier.animateItemPlacement()) { ListItem( diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsViewModel.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsViewModel.kt index 82e251c..0d75e14 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsViewModel.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListsViewModel.kt @@ -233,6 +233,7 @@ class ListsViewModel( * stored in the app's external files directory. Returns a Result containing * the absolute file path on success. */ + @Suppress("ReturnCount") suspend fun exportListToCsv( listId: String, listName: String, diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ServerSetupViewModel.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ServerSetupViewModel.kt index b71b2f5..a3d260f 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ServerSetupViewModel.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ServerSetupViewModel.kt @@ -1,3 +1,5 @@ +@file:Suppress("SwallowedException") + package com.collabtable.app.ui.screens import android.net.Uri diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/SettingsScreen.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/SettingsScreen.kt index 0465ea7..299aac8 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/SettingsScreen.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/SettingsScreen.kt @@ -64,6 +64,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +@Suppress("UnusedParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsScreen( diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/utils/Logger.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/utils/Logger.kt index b757ec4..e513475 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/utils/Logger.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/utils/Logger.kt @@ -84,8 +84,13 @@ object Logger { ): Boolean { val now = System.currentTimeMillis() val last = _logs.value.lastOrNull() + val isDuplicateMessage = + last?.let { previous -> + previous.level == level && previous.tag == tag && previous.message == message + } ?: false + val withinDedupeWindow = last != null && (now - last.timestamp) <= DEDUPE_WINDOW_MS // Suppress exact duplicate consecutive logs within a short window - if (last != null && last.level == level && last.tag == tag && last.message == message && (now - last.timestamp) <= DEDUPE_WINDOW_MS) { + if (isDuplicateMessage && withinDedupeWindow) { return false } val entry = LogEntry(timestamp = now, level = level, tag = tag, message = message) diff --git a/CollabTableAndroid/app/src/main/java/com/collabtable/app/work/ListChangeNotificationWorker.kt b/CollabTableAndroid/app/src/main/java/com/collabtable/app/work/ListChangeNotificationWorker.kt index 8202aff..9cd4fb0 100644 --- a/CollabTableAndroid/app/src/main/java/com/collabtable/app/work/ListChangeNotificationWorker.kt +++ b/CollabTableAndroid/app/src/main/java/com/collabtable/app/work/ListChangeNotificationWorker.kt @@ -7,6 +7,7 @@ import com.collabtable.app.data.database.CollabTableDatabase import com.collabtable.app.data.model.CollabList import com.collabtable.app.data.preferences.PreferencesManager import com.collabtable.app.notifications.NotificationHelper +import com.collabtable.app.utils.Logger class ListChangeNotificationWorker( appContext: Context, @@ -28,7 +29,8 @@ class ListChangeNotificationWorker( // Update checkpoint regardless to avoid duplicate spam prefs.setLastListNotifyCheckTimestamp(now) Result.success() - } catch (e: Exception) { + } catch (error: Exception) { + Logger.w("ListNotifyWorker", "Background notification polling failed: ${error.message}") Result.retry() } } diff --git a/CollabTableServer/package-lock.json b/CollabTableServer/package-lock.json index 3f7feb0..ef86bfe 100644 --- a/CollabTableServer/package-lock.json +++ b/CollabTableServer/package-lock.json @@ -27,7 +27,7 @@ "@types/node": "^20.10.6", "@types/pg": "^8.10.2", "ts-node-dev": "^2.0.0", - "typescript": "^5.3.3" + "typescript": "5.5.4" } }, "node_modules/@cspotcode/source-map-support": { @@ -3607,9 +3607,9 @@ } }, "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "version": "5.5.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", + "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", diff --git a/CollabTableServer/package.json b/CollabTableServer/package.json index 8b832c3..e831527 100644 --- a/CollabTableServer/package.json +++ b/CollabTableServer/package.json @@ -32,7 +32,7 @@ "@types/node": "^20.10.6", "@types/better-sqlite3": "^7.6.11", "@types/pg": "^8.10.2", - "typescript": "^5.3.3", + "typescript": "5.5.4", "ts-node-dev": "^2.0.0" } }