From e907a98c5cbd9a8c3c106f99e6a0ec0342e05c51 Mon Sep 17 00:00:00 2001 From: Jonas Lochmann Date: Mon, 3 Aug 2026 02:00:00 +0200 Subject: [PATCH] prepare new database abstraction layer --- src/api/admin.ts | 41 ++++++------ src/api/auth.ts | 6 +- src/api/child.ts | 6 +- src/api/index.ts | 6 +- src/api/parent.ts | 38 +++++------ src/api/purchase.ts | 16 ++--- src/api/sync.ts | 21 +++--- src/cli/delete-old-families.ts | 5 +- src/cli/find-old-families.ts | 5 +- src/connected-devices/index.ts | 37 +++++----- src/database/simple/index.ts | 59 ++++++++++++++++ src/function/authentication/index.ts | 30 ++++----- src/function/authentication/login-by-mail.ts | 31 +++++---- src/function/child/add-device.ts | 28 ++++---- .../child/logout-at-primary-device.ts | 18 ++--- src/function/child/set-primary-device.ts | 37 +++++----- src/function/cleanup/account-deletion.ts | 23 +++---- src/function/cleanup/delete-families.ts | 58 ++++++++-------- src/function/cleanup/delete-old-families.ts | 17 +++-- src/function/device/remove-device.ts | 38 +++++------ src/function/device/report-device-removed.ts | 30 ++++----- src/function/dh/decrypt.ts | 11 ++- src/function/dh/parentpassword.ts | 3 +- src/function/dh/shared-secret.ts | 16 ++--- .../parent/create-add-device-token.ts | 17 +++-- src/function/parent/create-family.ts | 25 ++++--- .../parent/get-status-by-mail-address.ts | 20 +++--- src/function/parent/link-mail-address.ts | 31 +++++---- .../parent/recover-parent-password.ts | 25 ++++--- src/function/parent/sign-in-into-family.ts | 30 ++++----- src/function/purchase/add-purchase.ts | 26 ++++--- src/function/purchase/require-family-entry.ts | 15 ++--- src/function/statusmessage/index.ts | 26 +++---- src/function/sync/apply-actions/baseinfo.ts | 17 +++-- src/function/sync/apply-actions/cache.ts | 67 +++++++++---------- .../dispatch-app-logic-action/addusedtime.ts | 26 +++---- .../dispatch-app-logic-action/addusedtime2.ts | 42 ++++++------ .../finishkeyrequest.ts | 6 +- .../marktaskpendingaction.ts | 26 +++---- .../dispatch-app-logic-action/ping.ts | 12 ++-- .../replytokeyrequest.ts | 22 +++--- .../sendkeyrequest.ts | 18 ++--- .../signoutatdevice.ts | 6 +- .../trieddisablingdeviceadmin.ts | 9 ++- .../updatedevicestatus.ts | 9 ++- .../updateinstalledapps.ts | 6 +- .../uploaddevicepublickey.ts | 8 +-- .../childchangepassword.ts | 6 +- .../dispatch-child-action/childsignin.ts | 10 +-- .../dispatch-helper/parent-action.ts | 10 +-- .../dispatch-parent-action/addcategoryapps.ts | 30 ++++----- .../addcategorynetworkid.ts | 18 ++--- .../dispatch-parent-action/addu2fkey.ts | 10 +-- .../dispatch-parent-action/adduser.ts | 6 +- .../changeparentpassword.ts | 6 +- .../dispatch-parent-action/createcategory.ts | 14 ++-- .../createtimelimitrule.ts | 10 +-- .../dispatch-parent-action/deletecategory.ts | 28 ++++---- .../deletechildtaskaction.ts | 10 +-- .../deletetimelimitrule.ts | 8 +-- .../ignoremanipulation.ts | 8 +-- .../incrementcategoryextratime.ts | 12 ++-- .../removecategoryapps.ts | 6 +- .../dispatch-parent-action/removeu2fkey.ts | 6 +- .../dispatch-parent-action/removeuser.ts | 48 ++++++------- .../dispatch-parent-action/renamechild.ts | 10 +-- .../resetcategorynetworkids.ts | 10 +-- .../reviewchildtaskaction.ts | 26 +++---- .../setcategoryextratime.ts | 10 +-- .../setcategoryforunassignedapps.ts | 14 ++-- .../setchildpassword.ts | 6 +- .../setconsiderrebootmanipulation.ts | 10 +-- .../setdevicedefaultuser.ts | 10 +-- .../setdevicedefaultusertimeout.ts | 10 +-- .../dispatch-parent-action/setdeviceuser.ts | 10 +-- .../dispatch-parent-action/setkeepsignedin.ts | 10 +-- .../setparentcategory.ts | 14 ++-- .../setrelaxprimarydevice.ts | 10 +-- .../setsenddeviceconnected.ts | 6 +- .../setuserdisablelmitsuntil.ts | 10 +-- .../dispatch-parent-action/setusertimezone.ts | 10 +-- .../updatecategorybatterylimit.ts | 8 +-- .../updatecategoryblockallnotifications.ts | 10 +-- .../updatecategoryblockedtimes.ts | 10 +-- .../updatecategorydisablelimits.ts | 10 +-- .../updatecategoryflags.ts | 8 +-- .../updatecategorysorting.ts | 6 +- .../updatecategorytemporarilyblocked.ts | 10 +-- .../updatecategorytimewarnings.ts | 16 ++--- .../updatecategorytitle.ts | 10 +-- .../updatechildtaskaction.ts | 18 ++--- .../updatedevicename.ts | 10 +-- .../updateenableactivitylevelblocking.ts | 10 +-- .../updatenetworktimeverification.ts | 10 +-- .../updateparentnotificationflags.ts | 8 +-- .../updatetimelimitrule.ts | 10 +-- .../dispatch-parent-action/updateuserflags.ts | 8 +-- .../updateuserlimitlogincategory.ts | 18 ++--- .../updateuserlimitloginpreblockduration.ts | 14 ++-- src/function/sync/apply-actions/index.ts | 23 +++---- src/function/sync/apply-actions/integrity.ts | 7 +- .../category/assigned-apps.ts | 13 ++-- .../category/base-data.ts | 21 +++--- .../get-server-data-status/category/diff.ts | 14 ++-- .../get-server-data-status/category/rules.ts | 13 ++-- .../get-server-data-status/category/tasks.ts | 13 ++-- .../category/used-times.ts | 17 +++-- .../get-server-data-status/device-detail.ts | 21 +++--- .../get-server-data-status/device-list.ts | 14 ++-- .../sync/get-server-data-status/dh-keys.ts | 26 ++++--- .../get-server-data-status/family-entry.ts | 14 ++-- .../sync/get-server-data-status/index.ts | 34 ++++------ .../get-server-data-status/key-requests.ts | 13 ++-- .../get-server-data-status/key-responses.ts | 17 +++-- .../sync/get-server-data-status/pings.ts | 12 ++-- .../sync/get-server-data-status/u2f.ts | 14 ++-- .../sync/get-server-data-status/user-list.ts | 18 +++-- src/function/u2f/index.ts | 18 ++--- src/function/warningmail/manipulation.ts | 15 ++--- src/function/warningmail/uninstall.ts | 15 ++--- src/function/websocket/index.ts | 15 ++--- src/index.ts | 11 +-- src/websocket/index.ts | 6 +- src/worker/delete-deprecated-purchases.ts | 17 +++-- src/worker/delete-old-families.ts | 6 +- src/worker/delete-old-tokens.ts | 35 +++++----- src/worker/delete-old-used-times.ts | 28 ++++---- src/worker/index.ts | 6 +- 128 files changed, 1078 insertions(+), 1083 deletions(-) create mode 100644 src/database/simple/index.ts diff --git a/src/api/admin.ts b/src/api/admin.ts index 884211d..05fb14e 100644 --- a/src/api/admin.ts +++ b/src/api/admin.ts @@ -19,7 +19,7 @@ import { json } from 'body-parser' import { Router } from 'express' import { BadRequest, Conflict } from 'http-errors' import * as Sequelize from 'sequelize' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { addPurchase, canDoNextPurchase } from '../function/purchase' import { getStatusMessage, setStatusMessage } from '../function/statusmessage' import { EventHandler } from '../monitoring/eventhandler' @@ -28,7 +28,7 @@ import { verifyIdentitifyToken, TokenValidationException } from '../util/identit import { WebsocketApi } from '../websocket' export const createAdminRouter = ({ database, websocket, eventHandler }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi eventHandler: EventHandler }) => { @@ -60,7 +60,9 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: { router.get('/status-message', async (_, res, next) => { try { - const currentStatusMessage = await getStatusMessage({ database }) + const currentStatusMessage = await database.transaction(async (transaction) => { + return getStatusMessage({ transaction }) + }) res.json({ statusMessage: currentStatusMessage @@ -102,12 +104,12 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: { } await database.transaction(async (transaction) => { - const userEntryUnsafe = await database.user.findOne({ + const userEntryUnsafe = await transaction.legacy.database.user.findOne({ where: { mail }, attributes: ['familyId'], - transaction + transaction: transaction.legacy.transaction }) if (!userEntryUnsafe) { @@ -119,13 +121,12 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: { } await addPurchase({ - database, + transaction, familyId: userEntry.familyId, type, service: 'directpurchase', transactionId: 'legacyunlock-' + type + '-' + generatePurchaseId(), - websocket, - transaction + websocket }) }) @@ -165,14 +166,14 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: { } const response = await database.transaction(async (transaction) => { - const userValid = await database.user.count({ + const userValid = await transaction.legacy.database.user.count({ where: { familyId: tokenContent.familyId, userId: tokenContent.userId, mail: tokenContent.mail, type: 'parent' }, - transaction + transaction: transaction.legacy.transaction }) if (!userValid) return { @@ -185,7 +186,7 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: { if (tokenContent.mail !== '') mailToReturn = tokenContent.mail else { - const userEntryWithMail = await database.user.findOne({ + const userEntryWithMail = await transaction.legacy.database.user.findOne({ where: { familyId: tokenContent.familyId, mail: { @@ -193,7 +194,7 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: { }, type: 'parent' }, - transaction + transaction: transaction.legacy.transaction }) if (!userEntryWithMail) return { @@ -207,11 +208,12 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: { let wasAlreadyExecuted: boolean - const oldPurchaseByPurchaseId = await database.purchase.findOne({ + const oldPurchaseByPurchaseId = await transaction.legacy.database.purchase.findOne({ where: { service: 'directpurchase', transactionId: purchaseId - } + }, + transaction: transaction.legacy.transaction }) if (oldPurchaseByPurchaseId === null) wasAlreadyExecuted = false @@ -222,11 +224,11 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: { } if (!wasAlreadyExecuted) { - const familyEntry = await database.family.findOne({ + const familyEntry = await transaction.legacy.database.family.findOne({ where: { familyId: tokenContent.familyId }, - transaction + transaction: transaction.legacy.transaction }) if (!familyEntry) return { @@ -240,11 +242,11 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: { }) if (!canDoPurchase) { - const lastPurchase = await database.purchase.findOne({ + const lastPurchase = await transaction.legacy.database.purchase.findOne({ where: { familyId: tokenContent.familyId }, - transaction, + transaction: transaction.legacy.transaction, order: [['loggedAt', 'DESC']], limit: 1 }) @@ -263,13 +265,12 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: { if (!dryRun) { await addPurchase({ - database, + transaction, familyId: tokenContent.familyId, type, service: 'directpurchase', transactionId: purchaseId, websocket, - transaction }) } } diff --git a/src/api/auth.ts b/src/api/auth.ts index ae13b7e..9aecea3 100644 --- a/src/api/auth.ts +++ b/src/api/auth.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2021 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,7 +18,7 @@ import { json } from 'body-parser' import { Router } from 'express' import { BadRequest } from 'http-errors' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { sendLoginCode, signInByMailCode } from '../function/authentication/login-by-mail' import { isMailAddressCoveredByWhitelist, isMailServerBlacklisted, sanitizeMailAddress } from '../util/mail' import { @@ -26,7 +26,7 @@ import { isSignInByMailCodeRequest } from './validator' -export const createAuthRouter = (database: Database) => { +export const createAuthRouter = (database: SimpleDatabase) => { const router = Router() router.post('/send-mail-login-code-v2', json(), async (req, res, next) => { diff --git a/src/api/child.ts b/src/api/child.ts index 2e298b2..d6cef9b 100644 --- a/src/api/child.ts +++ b/src/api/child.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,7 +18,7 @@ import { json } from 'body-parser' import { Router } from 'express' import { BadRequest } from 'http-errors' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { addChildDevice } from '../function/child/add-device' import { logoutAtPrimaryDevice } from '../function/child/logout-at-primary-device' import { setPrimaryDevice } from '../function/child/set-primary-device' @@ -27,7 +27,7 @@ import { isRegisterChildDeviceRequest, isRequestWithAuthToken, isUpdatePrimaryDe import { EventHandler } from '../monitoring/eventhandler' export const createChildRouter = ({ database, websocket, eventHandler }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi eventHandler: EventHandler }) => { diff --git a/src/api/index.ts b/src/api/index.ts index 86f7c9e..ed74f8e 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,7 +18,7 @@ import * as basicAuth from 'basic-auth' import * as express from 'express' import { VisibleConnectedDevicesManager } from '../connected-devices' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { EventHandler } from '../monitoring/eventhandler' import { WebsocketApi } from '../websocket' import { createAdminRouter } from './admin' @@ -31,7 +31,7 @@ import { createSyncRouter } from './sync' const adminToken = process.env.ADMIN_TOKEN || '' export const createApi = ({ database, websocket, connectedDevicesManager, eventHandler }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi connectedDevicesManager: VisibleConnectedDevicesManager eventHandler: EventHandler diff --git a/src/api/parent.ts b/src/api/parent.ts index e0e7eca..dd01a09 100644 --- a/src/api/parent.ts +++ b/src/api/parent.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2023 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -20,7 +20,7 @@ import { createHmac } from 'crypto' import { Router } from 'express' import { BadRequest, Forbidden, Unauthorized } from 'http-errors' import { config } from '../config' -import { Database, Transaction } from '../database' +import { SimpleDatabase, SimpleDatabaseTransaction } from '../database/simple' import { deleteAccount } from '../function/cleanup/account-deletion' import { removeDevice } from '../function/device/remove-device' import { createAddDeviceToken } from '../function/parent/create-add-device-token' @@ -44,7 +44,7 @@ import { export const createParentRouter = ({ database, websocket, eventHandler }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi eventHandler: EventHandler }) => { @@ -58,7 +58,7 @@ export const createParentRouter = ({ const { mailAuthToken } = req.body const { status, mail } = await database.transaction(async (transaction) => { - return getStatusByMailToken({ database, mailAuthToken, transaction }) + return getStatusByMailToken({ transaction, mailAuthToken }) }) res.json({ @@ -153,13 +153,13 @@ export const createParentRouter = ({ deviceAuthToken: string parentId: string secondPasswordHash: string - transaction: Transaction + transaction: SimpleDatabaseTransaction }) { - const deviceEntry = await database.device.findOne({ + const deviceEntry = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken: deviceAuthToken }, - transaction + transaction: transaction.legacy.transaction }) if (!deviceEntry) { @@ -171,13 +171,13 @@ export const createParentRouter = ({ throw new Unauthorized() } - const parentEntry = await database.user.findOne({ + const parentEntry = await transaction.legacy.database.user.findOne({ where: { familyId: deviceEntry.familyId, type: 'parent', userId: deviceEntry.currentUserId }, - transaction + transaction: transaction.legacy.transaction }) if (!parentEntry) { @@ -187,11 +187,11 @@ export const createParentRouter = ({ return { deviceEntry, parentEntry } } else if (secondPasswordHash.startsWith('u2f:')) { try { - const familyEntryUnsafe = await database.family.findOne({ + const familyEntryUnsafe = await transaction.legacy.database.family.findOne({ where: { familyId: deviceEntry.familyId }, - transaction, + transaction: transaction.legacy.transaction, attributes: ['hasFullVersion'] }) @@ -208,7 +208,6 @@ export const createParentRouter = ({ hasFullVersion, familyId: deviceEntry.familyId, deviceId: deviceEntry.deviceId, - database, transaction, calculateHmac: (secret) => createHmac('sha256', secret) .update('direct action') @@ -217,13 +216,13 @@ export const createParentRouter = ({ if (u2fResult.userId !== parentId) throw new Unauthorized() - const parentEntry = await database.user.findOne({ + const parentEntry = await transaction.legacy.database.user.findOne({ where: { familyId: deviceEntry.familyId, type: 'parent', userId: u2fResult.userId }, - transaction + transaction: transaction.legacy.transaction }) if (!parentEntry) { @@ -236,14 +235,14 @@ export const createParentRouter = ({ else throw ex } } else { - const parentEntry = await database.user.findOne({ + const parentEntry = await transaction.legacy.database.user.findOne({ where: { familyId: deviceEntry.familyId, type: 'parent', userId: parentId, secondPasswordHash: secondPasswordHash }, - transaction + transaction: transaction.legacy.transaction }) if (!parentEntry) { @@ -268,7 +267,7 @@ export const createParentRouter = ({ transaction }) - return createAddDeviceToken({ familyId: deviceEntry.familyId, database, transaction }) + return createAddDeviceToken({ familyId: deviceEntry.familyId, transaction }) }) res.json({ token, deviceId }) @@ -313,11 +312,10 @@ export const createParentRouter = ({ }) await removeDevice({ - database, + transaction, familyId: deviceEntry.familyId, deviceId: req.body.deviceId, - websocket, - transaction + websocket }) }) diff --git a/src/api/purchase.ts b/src/api/purchase.ts index fdc5a60..6d1be47 100644 --- a/src/api/purchase.ts +++ b/src/api/purchase.ts @@ -18,7 +18,7 @@ import { json } from 'body-parser' import { Router } from 'express' import { BadRequest, Conflict, Unauthorized } from 'http-errors' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { addPurchase, areGooglePlayPaymentsPossible, @@ -31,7 +31,7 @@ import { WebsocketApi } from '../websocket' import { isCanDoPurchaseRequest, isFinishPurchaseByGooglePlayRequest } from './validator' export const createPurchaseRouter = ({ database, websocket }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi }) => { const router = Router() @@ -49,9 +49,8 @@ export const createPurchaseRouter = ({ database, websocket }: { const result: boolean = await database.transaction(async (transaction) => { const familyEntry = await requireFamilyEntry({ - database, + transaction, deviceAuthToken: req.body.deviceAuthToken, - transaction }) return canDoNextPurchase({ @@ -76,12 +75,12 @@ export const createPurchaseRouter = ({ database, websocket }: { } await database.transaction(async (transaction) => { - const deviceEntryUnsafe = await database.device.findOne({ + const deviceEntryUnsafe = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken: req.body.deviceAuthToken }, attributes: ['familyId'], - transaction + transaction: transaction.legacy.transaction }) if (!deviceEntryUnsafe) { @@ -122,13 +121,12 @@ export const createPurchaseRouter = ({ database, websocket }: { } await addPurchase({ - database, + transaction, familyId: deviceEntry.familyId, type, service: 'googleplay', transactionId: orderId, - websocket, - transaction + websocket }) }) diff --git a/src/api/sync.ts b/src/api/sync.ts index dd95f9b..ce72b28 100644 --- a/src/api/sync.ts +++ b/src/api/sync.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -19,7 +19,7 @@ import { json } from 'body-parser' import { Router } from 'express' import { BadRequest, Unauthorized } from 'http-errors' import { VisibleConnectedDevicesManager } from '../connected-devices' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { reportDeviceRemoved } from '../function/device/report-device-removed' import { applyActionsFromDevice } from '../function/sync/apply-actions' import { generateServerDataStatus } from '../function/sync/get-server-data-status' @@ -34,7 +34,7 @@ const getRoundedTimestampForLastConnectivity = () => { } export const createSyncRouter = ({ database, websocket, connectedDevicesManager, eventHandler }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi connectedDevicesManager: VisibleConnectedDevicesManager eventHandler: EventHandler @@ -86,12 +86,12 @@ export const createSyncRouter = ({ database, websocket, connectedDevicesManager, } const serverStatus = await database.transaction(async (transaction) => { - const deviceEntryUnsafe = await database.device.findOne({ + const deviceEntryUnsafe = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken: body.deviceAuthToken }, attributes: ['familyId', 'deviceId', 'lastConnectivity'], - transaction + transaction: transaction.legacy.transaction }) if (!deviceEntryUnsafe) { @@ -102,22 +102,21 @@ export const createSyncRouter = ({ database, websocket, connectedDevicesManager, const now = getRoundedTimestampForLastConnectivity() if (parseInt(lastConnectivity, 10) !== now) { - await database.device.update({ + await transaction.legacy.database.device.update({ lastConnectivity: now.toString(10) }, { where: { deviceAuthToken: body.deviceAuthToken }, - transaction + transaction: transaction.legacy.transaction }) } return generateServerDataStatus({ - database, + transaction, familyId, deviceId, clientStatus: body.status, - transaction, eventHandler }) }) @@ -165,11 +164,11 @@ export const createSyncRouter = ({ database, websocket, connectedDevicesManager, } const isDeviceRemoved: boolean = await database.transaction(async (transaction) => { - const removedEntry = await database.oldDevice.findOne({ + const removedEntry = await transaction.legacy.database.oldDevice.findOne({ where: { deviceAuthToken: req.body.deviceAuthToken }, - transaction + transaction: transaction.legacy.transaction }) return !!removedEntry diff --git a/src/cli/delete-old-families.ts b/src/cli/delete-old-families.ts index 227339d..ffbbee0 100644 --- a/src/cli/delete-old-families.ts +++ b/src/cli/delete-old-families.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,9 +16,10 @@ */ import { defaultDatabase } from '../database' +import { fromLegacy as createSimpleDatabase } from '../database/simple' import { deleteOldFamilies } from '../function/cleanup/delete-old-families' -const database = defaultDatabase +const database = createSimpleDatabase(defaultDatabase) deleteOldFamilies(database) .then(() => console.log('done')) diff --git a/src/cli/find-old-families.ts b/src/cli/find-old-families.ts index f21e12a..ae7c426 100644 --- a/src/cli/find-old-families.ts +++ b/src/cli/find-old-families.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,9 +16,10 @@ */ import { defaultDatabase } from '../database' +import { fromLegacy as createSimpleDatabase } from '../database/simple' import { findOldFamilyIds } from '../function/cleanup/delete-old-families' -const database = defaultDatabase +const database = createSimpleDatabase(defaultDatabase) findOldFamilyIds(database) .then((res) => console.log(JSON.stringify(res))) diff --git a/src/connected-devices/index.ts b/src/connected-devices/index.ts index 529edcf..0914f68 100644 --- a/src/connected-devices/index.ts +++ b/src/connected-devices/index.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,7 +16,7 @@ */ import { EventEmitter } from 'events' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' export class ConnectedDevicesManager { private deviceConnectionCounters = new Map() @@ -59,10 +59,10 @@ export class ConnectedDevicesManager { export class VisibleConnectedDevicesManager { connectedDevicesManager = new ConnectedDevicesManager() - private database: Database + private database: SimpleDatabase constructor ({ database }: { - database: Database + database: SimpleDatabase }) { this.database = database } @@ -174,19 +174,24 @@ export class VisibleConnectedDevicesManager { // add all current devices ;(async () => { - const devicesUnsafe = await this.database.device.findAll({ - where: { - familyId - }, - attributes: [ - 'deviceId', - 'showDeviceConnected' - ] - }) + const devices = await this.database.transaction(async (transaction) => { + const devicesUnsafe = await transaction.legacy.database.device.findAll({ + where: { + familyId + }, + attributes: [ + 'deviceId', + 'showDeviceConnected' + ], + transaction: transaction.legacy.transaction + }) - const devices = devicesUnsafe.map(({ deviceId, showDeviceConnected }) => ({ - deviceId, showDeviceConnected - })) + const devices = devicesUnsafe.map(({ deviceId, showDeviceConnected }) => ({ + deviceId, showDeviceConnected + })) + + return devices + }) devices.forEach(({ deviceId, showDeviceConnected }) => { addDevice({ deviceId, showDeviceConnected }) diff --git a/src/database/simple/index.ts b/src/database/simple/index.ts new file mode 100644 index 0000000..9324176 --- /dev/null +++ b/src/database/simple/index.ts @@ -0,0 +1,59 @@ +/* + * server component for the TimeLimit App + * Copyright (C) 2019 - 2026 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import { Database as LegacyDatabase, Transaction as LegacyTransaction } from '../main' + +export interface SimpleDatabase { + legacy: LegacyDatabase + transaction: ( + inner: (t: SimpleDatabaseTransaction) => Promise + ) => Promise +} + +export interface SimpleDatabaseTransaction { + transaction: ( + inner: (t: SimpleDatabaseTransaction) => Promise + ) => Promise + + enqueueAfterCommit(callback: () => void): void + + legacy: { + database: LegacyDatabase + transaction: LegacyTransaction + } +} + +export function fromLegacy(database: LegacyDatabase): SimpleDatabase { + return { + legacy: database, + transaction: (inner) => database.transaction((legacyTransaction) => inner(fromLegacyTransaction(database, legacyTransaction))) + } +} + +function fromLegacyTransaction(database: LegacyDatabase, legacyTransaction: LegacyTransaction): SimpleDatabaseTransaction { + return { + transaction: (inner) => database.transaction( + (innerTransaction) => inner(fromLegacyTransaction(database, innerTransaction)), + { transaction: legacyTransaction } + ), + enqueueAfterCommit: (afterCommitAction) => legacyTransaction.afterCommit(afterCommitAction), + legacy: { + database, + transaction: legacyTransaction + } + } +} diff --git a/src/function/authentication/index.ts b/src/function/authentication/index.ts index 6351acf..32a748d 100644 --- a/src/function/authentication/index.ts +++ b/src/function/authentication/index.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2021 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,45 +16,45 @@ */ import { Unauthorized } from 'http-errors' -import { Database, Transaction } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' import { generateAuthToken } from '../../util/token' export const createAuthTokenByMailAddress = async ({ - mail, database, transaction, locale + mail, transaction, locale }: { - mail: string, database: Database, transaction: Transaction, locale: string + mail: string, transaction: SimpleDatabaseTransaction, locale: string }) => { const token = generateAuthToken() - await database.authtoken.create({ + await transaction.legacy.database.authtoken.create({ token, mail, createdAt: Date.now().toString(), locale - }, { transaction }) + }, { transaction: transaction.legacy.transaction }) return token } export const getMailAndLocaleByAuthToken = async ({ - mailAuthToken, database, transaction, invalidate + mailAuthToken, transaction, invalidate }: { - mailAuthToken: string, database: Database, transaction: Transaction, invalidate: boolean + mailAuthToken: string, transaction: SimpleDatabaseTransaction, invalidate: boolean }) => { - const entry = await database.authtoken.findOne({ + const entry = await transaction.legacy.database.authtoken.findOne({ where: { token: mailAuthToken }, - transaction + transaction: transaction.legacy.transaction }) if (entry) { if (invalidate) { - const rowCounter = await database.authtoken.destroy({ + const rowCounter = await transaction.legacy.database.authtoken.destroy({ where: { token: mailAuthToken }, - transaction + transaction: transaction.legacy.transaction }) if (rowCounter !== 1) { @@ -72,11 +72,11 @@ export const getMailAndLocaleByAuthToken = async ({ } export const requireMailAndLocaleByAuthToken = async ({ - mailAuthToken, database, transaction, invalidate + mailAuthToken, transaction, invalidate }: { - mailAuthToken: string, database: Database, transaction: Transaction, invalidate: boolean + mailAuthToken: string, transaction: SimpleDatabaseTransaction, invalidate: boolean }) => { - const result = await getMailAndLocaleByAuthToken({ mailAuthToken, database, transaction, invalidate }) + const result = await getMailAndLocaleByAuthToken({ mailAuthToken, transaction, invalidate }) if (!result) { throw new Unauthorized() diff --git a/src/function/authentication/login-by-mail.ts b/src/function/authentication/login-by-mail.ts index c36be68..062d2a9 100644 --- a/src/function/authentication/login-by-mail.ts +++ b/src/function/authentication/login-by-mail.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2023 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,7 +16,7 @@ */ import { Forbidden, Gone, TooManyRequests, Unauthorized } from 'http-errors' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { sendAuthenticationMail } from '../../util/mail' import { areWordSequencesEqual, randomWords } from '../../util/random-words' import { checkMailSendLimit } from '../../util/ratelimit-authmail' @@ -27,17 +27,17 @@ export const sendLoginCode = async ({ mail, deviceAuthToken, locale, database }: mail: string deviceAuthToken?: string locale: string - database: Database + database: SimpleDatabase // no transaction here because this is directly called from an API endpoint }): Promise<{ mailLoginToken: string }> => { let deviceName = null if (deviceAuthToken !== undefined) { const info = await database.transaction(async (transaction) => { - const deviceEntryUnsafe = await database.device.findOne({ + const deviceEntryUnsafe = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken }, attributes: ['familyId', 'name'], - transaction + transaction: transaction.legacy.transaction }) if (!deviceEntryUnsafe) { @@ -49,12 +49,12 @@ export const sendLoginCode = async ({ mail, deviceAuthToken, locale, database }: name: deviceEntryUnsafe.name } - const userEntryCounter = await database.user.count({ + const userEntryCounter = await transaction.legacy.database.user.count({ where: { familyId: deviceEntry.familyId, mail }, - transaction + transaction: transaction.legacy.transaction }) if (userEntryCounter === 1) { @@ -86,14 +86,14 @@ export const sendLoginCode = async ({ mail, deviceAuthToken, locale, database }: }) await database.transaction(async (transaction) => { - await database.mailLoginToken.create({ + await transaction.legacy.database.mailLoginToken.create({ mailLoginToken, receivedCode: code, mail, createdAt: Date.now().toString(10), remainingAttempts: 3, locale - }, { transaction }) + }, { transaction: transaction.legacy.transaction }) }) return { @@ -106,15 +106,15 @@ export const sendLoginCode = async ({ mail, deviceAuthToken, locale, database }: export const signInByMailCode = async ({ mailLoginToken, receivedCode, database }: { mailLoginToken: string receivedCode: string - database: Database + database: SimpleDatabase // no transaction here because this is directly called from an API endpoint }): Promise<{ mailAuthToken: string }> => { const result = await database.transaction(async (transaction) => { - const entry = await database.mailLoginToken.findOne({ + const entry = await transaction.legacy.database.mailLoginToken.findOne({ where: { mailLoginToken }, - transaction + transaction: transaction.legacy.transaction }) if ((!entry) || entry.remainingAttempts === 0) { @@ -124,7 +124,7 @@ export const signInByMailCode = async ({ mailLoginToken, receivedCode, database if (!areWordSequencesEqual(entry.receivedCode, receivedCode)) { entry.remainingAttempts-- - await entry.save({ transaction }) + await entry.save({ transaction: transaction.legacy.transaction }) if (entry.remainingAttempts === 0) { return () => { throw new Gone() } @@ -133,11 +133,11 @@ export const signInByMailCode = async ({ mailLoginToken, receivedCode, database } } - const counter = await database.mailLoginToken.destroy({ + const counter = await transaction.legacy.database.mailLoginToken.destroy({ where: { mailLoginToken }, - transaction + transaction: transaction.legacy.transaction }) if (counter !== 1) { @@ -147,7 +147,6 @@ export const signInByMailCode = async ({ mailLoginToken, receivedCode, database const mailAuthToken = await createAuthTokenByMailAddress({ mail: entry.mail, locale: entry.locale, - database, transaction }) diff --git a/src/function/child/add-device.ts b/src/function/child/add-device.ts index ede948c..14db160 100644 --- a/src/function/child/add-device.ts +++ b/src/function/child/add-device.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -17,7 +17,7 @@ import { Unauthorized } from 'http-errors' import { RegisterChildDeviceRequest } from '../../api/schema' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { generateAuthToken, generateVersionId } from '../../util/token' import { WebsocketApi } from '../../websocket' import { prepareDeviceEntry } from '../device/prepare-device-entry' @@ -28,7 +28,7 @@ import { ServerDataStatus } from '../../object/serverdatastatus' import { createEmptyClientDataStatus } from '../../object/clientdatastatus' export const addChildDevice = async ({ database, eventHandler, websocket, request }: { - database: Database + database: SimpleDatabase eventHandler: EventHandler websocket: WebsocketApi request: RegisterChildDeviceRequest @@ -39,23 +39,23 @@ export const addChildDevice = async ({ database, eventHandler, websocket, reques data: ServerDataStatus }> => { return database.transaction(async (transaction) => { - const entry = await database.addDeviceToken.findOne({ + const entry = await transaction.legacy.database.addDeviceToken.findOne({ where: { token: request.registerToken.toLowerCase() }, - transaction + transaction: transaction.legacy.transaction }) if (!entry) { throw new Unauthorized() } - await entry.destroy({ transaction }) + await entry.destroy({ transaction: transaction.legacy.transaction }) const { deviceId, familyId } = entry const deviceAuthToken = generateAuthToken() - await database.device.create(prepareDeviceEntry({ + await transaction.legacy.database.device.create(prepareDeviceEntry({ familyId, deviceId, deviceAuthToken, @@ -63,33 +63,31 @@ export const addChildDevice = async ({ database, eventHandler, websocket, reques newDeviceInfo: request.childDevice, userId: '', isUserKeptSignedIn: false - }), { transaction }) + }), { transaction: transaction.legacy.transaction }) - await database.family.update({ + await transaction.legacy.database.family.update({ deviceListVersion: generateVersionId() }, { where: { familyId }, - transaction + transaction: transaction.legacy.transaction }) await notifyClientsAboutChangesDelayed({ familyId, websocket, - database, + transaction, generalLevel: 1, targetedLevels: new Map(), - sourceDeviceId: deviceId, - transaction + sourceDeviceId: deviceId }) const data = await generateServerDataStatus({ - database, + transaction, clientStatus: createEmptyClientDataStatus({ clientLevel: request.clientLevel || null }), familyId: entry.familyId, deviceId, - transaction, eventHandler }) diff --git a/src/function/child/logout-at-primary-device.ts b/src/function/child/logout-at-primary-device.ts index 36fde61..6211e95 100644 --- a/src/function/child/logout-at-primary-device.ts +++ b/src/function/child/logout-at-primary-device.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,21 +16,21 @@ */ import { Conflict, Unauthorized } from 'http-errors' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { WebsocketApi } from '../../websocket' export const logoutAtPrimaryDevice = async ({ deviceAuthToken, database, websocket }: { deviceAuthToken: string - database: Database + database: SimpleDatabase websocket: WebsocketApi // no transaction here because this is directly called from an API endpoint }) => { await database.transaction(async (transaction) => { - const ownDeviceEntryUnsafe = await database.device.findOne({ + const ownDeviceEntryUnsafe = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken }, - transaction, + transaction: transaction.legacy.transaction, attributes: ['familyId', 'currentUserId', 'deviceId'] }) @@ -43,14 +43,14 @@ export const logoutAtPrimaryDevice = async ({ deviceAuthToken, database, websock currentUserId: ownDeviceEntryUnsafe.currentUserId } - const deviceUserEntryUnsafe = await database.user.findOne({ + const deviceUserEntryUnsafe = await transaction.legacy.database.user.findOne({ where: { familyId: ownDeviceEntry.familyId, userId: ownDeviceEntry.currentUserId, type: 'child' }, attributes: ['currentDevice'], - transaction + transaction: transaction.legacy.transaction }) if (!deviceUserEntryUnsafe) { @@ -61,14 +61,14 @@ export const logoutAtPrimaryDevice = async ({ deviceAuthToken, database, websock currentDevice: deviceUserEntryUnsafe.currentDevice } - const otherDeviceEntryUnsafe = await database.device.findOne({ + const otherDeviceEntryUnsafe = await transaction.legacy.database.device.findOne({ where: { familyId: ownDeviceEntry.familyId, deviceId: deviceUserEntry.currentDevice, currentUserId: ownDeviceEntry.currentUserId }, attributes: ['deviceAuthToken'], - transaction + transaction: transaction.legacy.transaction }) if (!otherDeviceEntryUnsafe) { diff --git a/src/function/child/set-primary-device.ts b/src/function/child/set-primary-device.ts index 4fb6d1a..91e8026 100644 --- a/src/function/child/set-primary-device.ts +++ b/src/function/child/set-primary-device.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -17,13 +17,13 @@ import { Conflict, InternalServerError, Unauthorized } from 'http-errors' import { config } from '../../config' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { generateVersionId } from '../../util/token' import { WebsocketApi } from '../../websocket' import { notifyClientsAboutChangesDelayed } from '../websocket' export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, currentUserId, action }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi deviceAuthToken: string currentUserId: string @@ -31,11 +31,11 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c // no transaction here because this is directly called from an API endpoint }): Promise<'assigned to other device' | 'requires full version' | 'success'> => { return database.transaction(async (transaction): Promise<'assigned to other device' | 'requires full version' | 'success'> => { - const deviceEntryUnsafe = await database.device.findOne({ + const deviceEntryUnsafe = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken }, - transaction, + transaction: transaction.legacy.transaction, attributes: ['familyId', 'currentUserId', 'deviceId'] }) @@ -53,12 +53,12 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c throw new Conflict() } - const userEntryUnsafe = await database.user.findOne({ + const userEntryUnsafe = await transaction.legacy.database.user.findOne({ where: { familyId: deviceEntry.familyId, userId: deviceEntry.currentUserId }, - transaction, + transaction: transaction.legacy.transaction, attributes: ['currentDevice'] }) @@ -70,12 +70,12 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c currentDevice: userEntryUnsafe.currentDevice } - const userDeviceEntriesUnsafe = await database.device.findAll({ + const userDeviceEntriesUnsafe = await transaction.legacy.database.device.findAll({ where: { familyId: deviceEntry.familyId, currentUserId }, - transaction, + transaction: transaction.legacy.transaction, attributes: ['deviceId'] }) @@ -84,11 +84,11 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c })) if (userDeviceEntries.length >= 2) { - const familyEntryUnsafe = await database.family.findOne({ + const familyEntryUnsafe = await transaction.legacy.database.family.findOne({ where: { familyId: deviceEntry.familyId }, - transaction, + transaction: transaction.legacy.transaction, attributes: ['hasFullVersion'] }) @@ -112,14 +112,14 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c } // update - const [affectedRows] = await database.user.update({ + const [affectedRows] = await transaction.legacy.database.user.update({ currentDevice: deviceEntry.deviceId }, { where: { familyId: deviceEntry.familyId, userId: currentUserId }, - transaction + transaction: transaction.legacy.transaction }) if (affectedRows !== 1) { @@ -131,14 +131,14 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c } // update - const [affectedRows] = await database.user.update({ + const [affectedRows] = await transaction.legacy.database.user.update({ currentDevice: '' }, { where: { familyId: deviceEntry.familyId, userId: currentUserId }, - transaction + transaction: transaction.legacy.transaction }) if (affectedRows !== 1) { @@ -149,10 +149,10 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c } // invalidiate user list - await database.family.update({ + await transaction.legacy.database.family.update({ userListVersion: generateVersionId() }, { - transaction, + transaction: transaction.legacy.transaction, where: { familyId: deviceEntry.familyId } @@ -163,10 +163,9 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c familyId: deviceEntry.familyId, sourceDeviceId: deviceEntry.deviceId, websocket, - database, + transaction, generalLevel: 1, // the source device knows it already targetedLevels: new Map(), - transaction }) return 'success' diff --git a/src/function/cleanup/account-deletion.ts b/src/function/cleanup/account-deletion.ts index cf783f5..506f35f 100644 --- a/src/function/cleanup/account-deletion.ts +++ b/src/function/cleanup/account-deletion.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2023 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -17,7 +17,7 @@ import { Unauthorized } from 'http-errors' import { DeleteAccountPayload } from '../../api/schema' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { sendAccountDeletedMail } from '../../util/mail' import { WebsocketApi } from '../../websocket' import { requireMailAndLocaleByAuthToken } from '../authentication' @@ -25,14 +25,14 @@ import { deleteFamilies } from './delete-families' export async function deleteAccount({ request, database, websocket }: { request: DeleteAccountPayload - database: Database + database: SimpleDatabase websocket: WebsocketApi }) { await database.transaction(async (transaction) => { - const deviceEntryUnsafe = await database.device.findOne({ + const deviceEntryUnsafe = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken: request.deviceAuthToken }, attributes: ['familyId'], - transaction + transaction: transaction.legacy.transaction }) if (!deviceEntryUnsafe) { @@ -43,13 +43,13 @@ export async function deleteAccount({ request, database, websocket }: { familyId: deviceEntryUnsafe.familyId } - const userEntries = (await database.user.findAll({ + const userEntries = (await transaction.legacy.database.user.findAll({ where: { familyId: deviceEntry.familyId, type: 'parent' }, attributes: ['mail'], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ mail: item.mail })) const registeredMailAddresses = new Set() @@ -63,7 +63,6 @@ export async function deleteAccount({ request, database, websocket }: { for (const mailAuthToken of request.mailAuthTokens) { const info = await requireMailAndLocaleByAuthToken({ mailAuthToken, - database, transaction, invalidate: true }) @@ -79,17 +78,17 @@ export async function deleteAccount({ request, database, websocket }: { if (!authenticatedMailAddresses.has(mail)) throw new Unauthorized() }) - const deviceEntries = (await database.device.findAll({ + const deviceEntries = (await transaction.legacy.database.device.findAll({ where: { familyId: deviceEntry.familyId }, - transaction, + transaction: transaction.legacy.transaction, attributes: ['deviceAuthToken'] })).map((item) => ({ deviceAuthToken: item.deviceAuthToken })) - await deleteFamilies({ database, transaction, familiyIds: [deviceEntry.familyId] }) + await deleteFamilies({ transaction, familiyIds: [deviceEntry.familyId] }) - transaction.afterCommit(() => { + transaction.enqueueAfterCommit(() => { for (const device of deviceEntries) { websocket.triggerSyncByDeviceAuthToken({ deviceAuthToken: device.deviceAuthToken, diff --git a/src/function/cleanup/delete-families.ts b/src/function/cleanup/delete-families.ts index cf65f86..0cf57d0 100644 --- a/src/function/cleanup/delete-families.ts +++ b/src/function/cleanup/delete-families.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2023 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -17,138 +17,136 @@ import { difference } from 'lodash' import * as Sequelize from 'sequelize' -import { Database, Transaction } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' -export async function deleteFamilies ({ database, transaction, familiyIds }: { - database: Database - transaction: Transaction +export async function deleteFamilies ({ transaction, familiyIds }: { + transaction: SimpleDatabaseTransaction familiyIds: Array - // no transaction here because this should run isolated }) { if (familiyIds.length === 0) { return } // category - await database.category.destroy({ + await transaction.legacy.database.category.destroy({ where: { familyId: { [Sequelize.Op.in]: familiyIds } }, - transaction + transaction: transaction.legacy.transaction }) // categoryapp - await database.categoryApp.destroy({ + await transaction.legacy.database.categoryApp.destroy({ where: { familyId: { [Sequelize.Op.in]: familiyIds } }, - transaction + transaction: transaction.legacy.transaction }) // purchase - await database.purchase.destroy({ + await transaction.legacy.database.purchase.destroy({ where: { familyId: { [Sequelize.Op.in]: familiyIds } }, - transaction + transaction: transaction.legacy.transaction }) // timelimitrule - await database.timelimitRule.destroy({ + await transaction.legacy.database.timelimitRule.destroy({ where: { familyId: { [Sequelize.Op.in]: familiyIds } }, - transaction + transaction: transaction.legacy.transaction }) // usedtime - await database.usedTime.destroy({ + await transaction.legacy.database.usedTime.destroy({ where: { familyId: { [Sequelize.Op.in]: familiyIds } }, - transaction + transaction: transaction.legacy.transaction }) // session durations - await database.sessionDuration.destroy({ + await transaction.legacy.database.sessionDuration.destroy({ where: { familyId: { [Sequelize.Op.in]: familiyIds } }, - transaction + transaction: transaction.legacy.transaction }) // user - await database.user.destroy({ + await transaction.legacy.database.user.destroy({ where: { familyId: { [Sequelize.Op.in]: familiyIds } }, - transaction + transaction: transaction.legacy.transaction }) // device - const oldDeviceAuthTokens = (await database.device.findAll({ + const oldDeviceAuthTokens = (await transaction.legacy.database.device.findAll({ where: { familyId: { [Sequelize.Op.in]: familiyIds } }, attributes: ['deviceAuthToken'], - transaction + transaction: transaction.legacy.transaction })).map((item) => item.deviceAuthToken) - await database.device.destroy({ + await transaction.legacy.database.device.destroy({ where: { familyId: { [Sequelize.Op.in]: familiyIds } }, - transaction + transaction: transaction.legacy.transaction }) // olddevice if (oldDeviceAuthTokens.length > 0) { - const knownOldDeviceAuthTokens = (await database.oldDevice.findAll({ + const knownOldDeviceAuthTokens = (await transaction.legacy.database.oldDevice.findAll({ where: { deviceAuthToken: { [Sequelize.Op.in]: oldDeviceAuthTokens } }, - transaction + transaction: transaction.legacy.transaction })).map((item) => item.deviceAuthToken) const oldDeviceAuthTokensToAdd = difference(oldDeviceAuthTokens, knownOldDeviceAuthTokens) if (oldDeviceAuthTokensToAdd.length > 0) { - await database.oldDevice.bulkCreate( + await transaction.legacy.database.oldDevice.bulkCreate( oldDeviceAuthTokensToAdd.map((item) => ({ deviceAuthToken: item })), - { transaction } + { transaction: transaction.legacy.transaction } ) } } // family - await database.family.destroy({ + await transaction.legacy.database.family.destroy({ where: { familyId: { [Sequelize.Op.in]: familiyIds } }, - transaction + transaction: transaction.legacy.transaction }) } diff --git a/src/function/cleanup/delete-old-families.ts b/src/function/cleanup/delete-old-families.ts index 2f6bf6b..f6f1bb6 100644 --- a/src/function/cleanup/delete-old-families.ts +++ b/src/function/cleanup/delete-old-families.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2023 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -17,10 +17,10 @@ import { difference } from 'lodash' import * as Sequelize from 'sequelize' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { deleteFamilies } from './delete-families' -export async function deleteOldFamilies (database: Database) { +export async function deleteOldFamilies (database: SimpleDatabase) { const oldFamilyIds = await findOldFamilyIds(database) if (oldFamilyIds.length > 0) { @@ -28,7 +28,6 @@ export async function deleteOldFamilies (database: Database) { await database.transaction(async (transaction) => { await deleteFamilies({ - database, transaction, familiyIds: familyIdsToDelete }) @@ -36,23 +35,23 @@ export async function deleteOldFamilies (database: Database) { } } -export async function findOldFamilyIds (database: Database) { +export async function findOldFamilyIds (database: SimpleDatabase): Promise> { return database.transaction(async (transaction) => { - const familyIdsWithExpiredLicenses = (await database.family.findAll({ + const familyIdsWithExpiredLicenses = (await transaction.legacy.database.family.findAll({ where: { fullVersionUntil: { [Sequelize.Op.lt]: (Date.now() - 1000 * 60 * 60 * 24 * 90 /* 90 days */).toString(10) } }, attributes: ['familyId'], - transaction + transaction: transaction.legacy.transaction })).map((item) => item.familyId) if (familyIdsWithExpiredLicenses.length === 0) { return [] } - const recentlyUsedFamilyIds = (await database.device.findAll({ + const recentlyUsedFamilyIds = (await transaction.legacy.database.device.findAll({ where: { familyId: { [Sequelize.Op.in]: familyIdsWithExpiredLicenses @@ -62,7 +61,7 @@ export async function findOldFamilyIds (database: Database) { } }, attributes: ['familyId'], - transaction + transaction: transaction.legacy.transaction })).map((item) => item.familyId) return difference(familyIdsWithExpiredLicenses, recentlyUsedFamilyIds) diff --git a/src/function/device/remove-device.ts b/src/function/device/remove-device.ts index 87e09db..6cbcb30 100644 --- a/src/function/device/remove-device.ts +++ b/src/function/device/remove-device.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,24 +16,23 @@ */ import { Conflict } from 'http-errors' -import { Database, Transaction } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' import { generateVersionId } from '../../util/token' import { WebsocketApi } from '../../websocket' import { notifyClientsAboutChangesDelayed } from '../websocket' -export async function removeDevice ({ database, familyId, deviceId, websocket, transaction }: { - database: Database +export async function removeDevice ({ familyId, deviceId, websocket, transaction }: { + transaction: SimpleDatabaseTransaction familyId: string deviceId: string websocket: WebsocketApi - transaction: Transaction }) { - const deviceEntry = await database.device.findOne({ + const deviceEntry = await transaction.legacy.database.device.findOne({ where: { familyId, deviceId }, - transaction + transaction: transaction.legacy.transaction }) if (!deviceEntry) { @@ -41,37 +40,37 @@ export async function removeDevice ({ database, familyId, deviceId, websocket, t } // remove as current device - await database.user.update({ + await transaction.legacy.database.user.update({ currentDevice: '' }, { where: { familyId, currentDevice: deviceId }, - transaction + transaction: transaction.legacy.transaction }) // add to old devices if it is not yet there (it could be there if it reported a uninstall) - const oldOldDeviceEntry = await database.oldDevice.findOne({ + const oldOldDeviceEntry = await transaction.legacy.database.oldDevice.findOne({ where: { deviceAuthToken: deviceEntry.deviceAuthToken }, - transaction + transaction: transaction.legacy.transaction }) if (!oldOldDeviceEntry) { - await database.oldDevice.create({ + await transaction.legacy.database.oldDevice.create({ deviceAuthToken: deviceEntry.deviceAuthToken }, { - transaction + transaction: transaction.legacy.transaction }) } // remove from the device list - await deviceEntry.destroy({ transaction }) + await deviceEntry.destroy({ transaction: transaction.legacy.transaction }) // invalidiate the caches - await database.family.update({ + await transaction.legacy.database.family.update({ deviceListVersion: generateVersionId(), // the device could have become unassigned during this userListVersion: generateVersionId() @@ -79,20 +78,19 @@ export async function removeDevice ({ database, familyId, deviceId, websocket, t where: { familyId: deviceEntry.familyId }, - transaction + transaction: transaction.legacy.transaction }) await notifyClientsAboutChangesDelayed({ - database, + transaction, websocket, familyId, sourceDeviceId: null, generalLevel: 1, - targetedLevels: new Map(), - transaction + targetedLevels: new Map() }) - transaction.afterCommit(() => { + transaction.enqueueAfterCommit(() => { websocket.triggerSyncByDeviceAuthToken({ deviceAuthToken: deviceEntry.deviceAuthToken, isImportant: true diff --git a/src/function/device/report-device-removed.ts b/src/function/device/report-device-removed.ts index bfda3a7..fe09fd7 100644 --- a/src/function/device/report-device-removed.ts +++ b/src/function/device/report-device-removed.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,24 +16,24 @@ */ import { Unauthorized } from 'http-errors' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { generateAuthToken, generateVersionId } from '../../util/token' import { WebsocketApi } from '../../websocket' import { sendUninstallWarnings } from '../warningmail/uninstall' import { notifyClientsAboutChangesDelayed } from '../websocket' export async function reportDeviceRemoved ({ database, deviceAuthToken, websocket }: { - database: Database + database: SimpleDatabase deviceAuthToken: string websocket: WebsocketApi // no transaction here because this is directly called from an API endpoint }) { await database.transaction(async (transaction) => { - const deviceEntry = await database.device.findOne({ + const deviceEntry = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken }, - transaction + transaction: transaction.legacy.transaction }) if (deviceEntry) { @@ -41,47 +41,45 @@ export async function reportDeviceRemoved ({ database, deviceAuthToken, websocke deviceEntry.didDeviceReportUninstall = true deviceEntry.deviceAuthToken = generateAuthToken() // invalidiate the token - await deviceEntry.save({ transaction }) + await deviceEntry.save({ transaction: transaction.legacy.transaction }) // invalidiate device list - await database.family.update({ + await transaction.legacy.database.family.update({ deviceListVersion: generateVersionId() }, { where: { familyId: deviceEntry.familyId }, - transaction + transaction: transaction.legacy.transaction }) // add to old devices - await database.oldDevice.create({ + await transaction.legacy.database.oldDevice.create({ deviceAuthToken: currentAuthToken }, { - transaction + transaction: transaction.legacy.transaction }) await notifyClientsAboutChangesDelayed({ - database, + transaction, websocket, familyId: deviceEntry.familyId, sourceDeviceId: null, generalLevel: 1, targetedLevels: new Map(), - transaction }) await sendUninstallWarnings({ - database, + transaction, familyId: deviceEntry.familyId, deviceName: deviceEntry.name, - transaction }) } else { - const oldDeviceEntry = await database.oldDevice.findOne({ + const oldDeviceEntry = await transaction.legacy.database.oldDevice.findOne({ where: { deviceAuthToken }, - transaction + transaction: transaction.legacy.transaction }) if (!oldDeviceEntry) { diff --git a/src/function/dh/decrypt.ts b/src/function/dh/decrypt.ts index bd6534c..a853041 100644 --- a/src/function/dh/decrypt.ts +++ b/src/function/dh/decrypt.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,17 +15,15 @@ * along with this program. If not, see . */ -import * as Sequelize from 'sequelize' import { createDecipheriv } from 'crypto' -import { Database } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' import { isVersionId } from '../../util/token' import { getSharedSecret, SharedSecretException } from './shared-secret' export async function decrypt({ - database, transaction, familyId, deviceId, encryptedData, authData + transaction, familyId, deviceId, encryptedData, authData }: { - database: Database - transaction: Sequelize.Transaction + transaction: SimpleDatabaseTransaction familyId: string deviceId: string encryptedData: string @@ -46,7 +44,6 @@ export async function decrypt({ const sharedSecret = await (async () => { try { return getSharedSecret({ - database, transaction, familyId, deviceId, diff --git a/src/function/dh/parentpassword.ts b/src/function/dh/parentpassword.ts index 322cee7..38cb919 100644 --- a/src/function/dh/parentpassword.ts +++ b/src/function/dh/parentpassword.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -31,7 +31,6 @@ export async function decryptParentPassword({ cache, password } : { try { const secondHash = (await decrypt({ - database: cache.database, transaction: cache.transaction, familyId: cache.familyId, deviceId: cache.deviceId, diff --git a/src/function/dh/shared-secret.ts b/src/function/dh/shared-secret.ts index 257c7c1..182b727 100644 --- a/src/function/dh/shared-secret.ts +++ b/src/function/dh/shared-secret.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,17 +15,15 @@ * along with this program. If not, see . */ -import * as Sequelize from 'sequelize' import { createPrivateKey, createPublicKey, diffieHellman } from 'crypto' -import { Database } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' import { calculateExpireTime } from '../../database/devicedhkey' import { isVersionId } from '../../util/token' export async function getSharedSecret({ - database, transaction, familyId, deviceId, keyId, otherPublicKey + transaction, familyId, deviceId, keyId, otherPublicKey }: { - database: Database - transaction: Sequelize.Transaction + transaction: SimpleDatabaseTransaction familyId: string deviceId: string keyId: string @@ -33,20 +31,20 @@ export async function getSharedSecret({ }) { if (!isVersionId(keyId)) throw new KeyNotFoundException('invalid key id') - const databaseKeyEntry = await database.deviceDhKey.findOne({ + const databaseKeyEntry = await transaction.legacy.database.deviceDhKey.findOne({ where: { familyId, deviceId, version: keyId }, - transaction + transaction: transaction.legacy.transaction }) if (!databaseKeyEntry) throw new KeyNotFoundException('private key not found') if (databaseKeyEntry.expireAt === null) { databaseKeyEntry.expireAt = calculateExpireTime(BigInt(Date.now())).toString(10) - await databaseKeyEntry.save({ transaction }) + await databaseKeyEntry.save({ transaction: transaction.legacy.transaction }) } else { if (BigInt(databaseKeyEntry.expireAt) < BigInt(Date.now())) throw new KeyExpiredException() } diff --git a/src/function/parent/create-add-device-token.ts b/src/function/parent/create-add-device-token.ts index d314175..39e50eb 100644 --- a/src/function/parent/create-add-device-token.ts +++ b/src/function/parent/create-add-device-token.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,31 +15,30 @@ * along with this program. If not, see . */ -import { Database, Transaction } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' import { randomWords } from '../../util/random-words' import { generateIdWithinFamily } from '../../util/token' -export const createAddDeviceToken = async ({ familyId, database, transaction }: { +export const createAddDeviceToken = async ({ familyId, transaction }: { familyId: string - database: Database - transaction: Transaction + transaction: SimpleDatabaseTransaction }) => { const token = randomWords(5) const deviceId = generateIdWithinFamily() - await database.addDeviceToken.destroy({ + await transaction.legacy.database.addDeviceToken.destroy({ where: { familyId }, - transaction + transaction: transaction.legacy.transaction }) - await database.addDeviceToken.create({ + await transaction.legacy.database.addDeviceToken.create({ familyId, token: token.toLowerCase(), deviceId, createdAt: Date.now().toString() - }, { transaction }) + }, { transaction: transaction.legacy.transaction }) return { token, deviceId } } diff --git a/src/function/parent/create-family.ts b/src/function/parent/create-family.ts index 9dd1d13..c4a6ebf 100644 --- a/src/function/parent/create-family.ts +++ b/src/function/parent/create-family.ts @@ -18,7 +18,7 @@ import { Conflict } from 'http-errors' import { generateServerDataStatus } from '../sync/get-server-data-status' import { NewDeviceInfo, PlaintextParentPassword, assertPlaintextParentPasswordValid } from '../../api/schema' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { maxMailNotificationFlags } from '../../database/user' import { EventHandler } from '../../monitoring/eventhandler' import { ServerDataStatus } from '../../object/serverdatastatus' @@ -33,7 +33,7 @@ export async function createFamily ({ database, eventHandler, mailAuthToken, firstParentDevice, password, timeZone, parentName, deviceName, clientLevel }: { - database: Database + database: SimpleDatabase eventHandler: EventHandler mailAuthToken: string firstParentDevice: NewDeviceInfo @@ -52,14 +52,14 @@ export async function createFamily ({ return database.transaction(async (transaction) => { const now = Date.now().toString(10) - const mailInfo = await requireMailAndLocaleByAuthToken({ database, mailAuthToken, transaction, invalidate: true }) + const mailInfo = await requireMailAndLocaleByAuthToken({ transaction, mailAuthToken, invalidate: true }) // ensure that no family was created for this mail yet - const existingUserEntry = await database.user.findOne({ + const existingUserEntry = await transaction.legacy.database.user.findOne({ where: { mail: mailInfo.mail }, - transaction + transaction: transaction.legacy.transaction }) if (existingUserEntry) { @@ -72,7 +72,7 @@ export async function createFamily ({ const deviceAuthToken = generateAuthToken() // create family - await database.family.create({ + await transaction.legacy.database.family.create({ familyId, name: '', createdAt: now, @@ -84,10 +84,10 @@ export async function createFamily ({ nextServerKeyRequestSeq: '1', u2fKeysVersion: generateVersionId(), fullVersionDebts: '0' - }, { transaction }) + }, { transaction: transaction.legacy.transaction }) // create parent user - await database.user.create({ + await transaction.legacy.database.user.create({ familyId, userId, name: parentName, @@ -104,10 +104,10 @@ export async function createFamily ({ mailNotificationFlags: maxMailNotificationFlags, blockedTimes: '', flags: '0' - }, { transaction }) + }, { transaction: transaction.legacy.transaction }) // add parent device - await database.device.create(prepareDeviceEntry({ + await transaction.legacy.database.device.create(prepareDeviceEntry({ familyId, deviceId, deviceName, @@ -115,14 +115,13 @@ export async function createFamily ({ userId, deviceAuthToken, isUserKeptSignedIn: true - }), { transaction }) + }), { transaction: transaction.legacy.transaction }) const data = await generateServerDataStatus({ - database, + transaction, clientStatus: createEmptyClientDataStatus({ clientLevel }), familyId, deviceId, - transaction, eventHandler }) diff --git a/src/function/parent/get-status-by-mail-address.ts b/src/function/parent/get-status-by-mail-address.ts index 1f5d967..6bc6514 100644 --- a/src/function/parent/get-status-by-mail-address.ts +++ b/src/function/parent/get-status-by-mail-address.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2021 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,22 +15,22 @@ * along with this program. If not, see . */ -import { Database, Transaction } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' import { StaticMessageException } from '../../exception' import { requireMailAndLocaleByAuthToken } from '../authentication' const getStatusByMailAddress = async ({ - mail, database, transaction -}: { mail: string, database: Database, transaction: Transaction }) => { + mail, transaction +}: { mail: string, transaction: SimpleDatabaseTransaction }) => { if (!mail) { throw new StaticMessageException({ staticMessage: 'getStatusByMailAddress: no mail address provided' }) } - const entry = await database.user.findOne({ + const entry = await transaction.legacy.database.user.findOne({ where: { mail }, - transaction + transaction: transaction.legacy.transaction }) if (entry) { @@ -41,12 +41,12 @@ const getStatusByMailAddress = async ({ } export const getStatusByMailToken = async ({ - mailAuthToken, database, transaction -}: { mailAuthToken: string, database: Database, transaction: Transaction }) => { - const mailInfo = await requireMailAndLocaleByAuthToken({ mailAuthToken, database, transaction, invalidate: false }) + mailAuthToken, transaction +}: { mailAuthToken: string, transaction: SimpleDatabaseTransaction }) => { + const mailInfo = await requireMailAndLocaleByAuthToken({ mailAuthToken, transaction, invalidate: false }) const mail = mailInfo.mail - const status = await getStatusByMailAddress({ mail, database, transaction }) + const status = await getStatusByMailAddress({ mail, transaction }) return { mail, status } } diff --git a/src/function/parent/link-mail-address.ts b/src/function/parent/link-mail-address.ts index 4d0661f..cde9d1d 100644 --- a/src/function/parent/link-mail-address.ts +++ b/src/function/parent/link-mail-address.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,7 +16,7 @@ */ import { Conflict, Unauthorized } from 'http-errors' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { generateVersionId } from '../../util/token' import { WebsocketApi } from '../../websocket' import { requireMailAndLocaleByAuthToken } from '../authentication' @@ -27,16 +27,16 @@ export const linkMailAddress = async ({ mailAuthToken, deviceAuthToken, parentUs deviceAuthToken: string parentUserId: string parentPasswordSecondHash: string - database: Database + database: SimpleDatabase websocket: WebsocketApi // no transaction here because this is directly called from an API endpoint }) => { await database.transaction(async (transaction) => { - const deviceEntry = await database.device.findOne({ + const deviceEntry = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken }, - transaction + transaction: transaction.legacy.transaction }) if (!deviceEntry) { @@ -45,26 +45,26 @@ export const linkMailAddress = async ({ mailAuthToken, deviceAuthToken, parentUs const familyId = deviceEntry.familyId - const mailInfo = await requireMailAndLocaleByAuthToken({ mailAuthToken, database, transaction, invalidate: true }) + const mailInfo = await requireMailAndLocaleByAuthToken({ mailAuthToken, transaction, invalidate: true }) - const exisitingUser = await database.user.findOne({ + const exisitingUser = await transaction.legacy.database.user.findOne({ where: { mail: mailInfo.mail }, - transaction + transaction: transaction.legacy.transaction }) if (exisitingUser) { throw new Conflict() } - const parentEntry = await database.user.findOne({ + const parentEntry = await transaction.legacy.database.user.findOne({ where: { type: 'parent', familyId, userId: parentUserId }, - transaction + transaction: transaction.legacy.transaction }) if (!parentEntry) { @@ -85,16 +85,16 @@ export const linkMailAddress = async ({ mailAuthToken, deviceAuthToken, parentUs parentEntry.mail = mailInfo.mail - await parentEntry.save({ transaction }) + await parentEntry.save({ transaction: transaction.legacy.transaction }) // invalidiate client caches - await database.family.update({ + await transaction.legacy.database.family.update({ userListVersion: generateVersionId() }, { where: { familyId }, - transaction + transaction: transaction.legacy.transaction }) // notify @@ -103,9 +103,8 @@ export const linkMailAddress = async ({ mailAuthToken, deviceAuthToken, parentUs sourceDeviceId: null, generalLevel: 1, targetedLevels: new Map(), - database, - websocket, - transaction + transaction, + websocket }) }) } diff --git a/src/function/parent/recover-parent-password.ts b/src/function/parent/recover-parent-password.ts index 056234a..b9dfebc 100644 --- a/src/function/parent/recover-parent-password.ts +++ b/src/function/parent/recover-parent-password.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -17,7 +17,7 @@ import { Conflict } from 'http-errors' import { PlaintextParentPassword, assertPlaintextParentPasswordValid } from '../../api/schema' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { sendPasswordRecoveryUsedMail } from '../../util/mail' import { generateVersionId } from '../../util/token' import { WebsocketApi } from '../../websocket' @@ -25,7 +25,7 @@ import { requireMailAndLocaleByAuthToken } from '../authentication' import { notifyClientsAboutChangesDelayed } from '../websocket' export const recoverParentPassword = async ({ database, websocket, password, mailAuthToken }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi password: PlaintextParentPassword mailAuthToken: string @@ -34,14 +34,14 @@ export const recoverParentPassword = async ({ database, websocket, password, mai assertPlaintextParentPasswordValid(password) await database.transaction(async (transaction) => { - const mailInfo = await requireMailAndLocaleByAuthToken({ mailAuthToken, database, transaction, invalidate: true }) + const mailInfo = await requireMailAndLocaleByAuthToken({ mailAuthToken, transaction, invalidate: true }) // update the user entry - const userEntry = await database.user.findOne({ + const userEntry = await transaction.legacy.database.user.findOne({ where: { mail: mailInfo.mail }, - transaction + transaction: transaction.legacy.transaction }) if (!userEntry) { @@ -52,29 +52,28 @@ export const recoverParentPassword = async ({ database, websocket, password, mai userEntry.secondPasswordHash = password.secondHash userEntry.secondPasswordSalt = password.secondSalt - await userEntry.save({ transaction }) + await userEntry.save({ transaction: transaction.legacy.transaction }) // invalidate the user list - await database.family.update({ + await transaction.legacy.database.family.update({ userListVersion: generateVersionId() }, { where: { familyId: userEntry.familyId }, - transaction + transaction: transaction.legacy.transaction }) await notifyClientsAboutChangesDelayed({ - database, + transaction, familyId: userEntry.familyId, websocket, generalLevel: 2, targetedLevels: new Map(), - sourceDeviceId: null, - transaction + sourceDeviceId: null }) - transaction.afterCommit(async () => { + transaction.enqueueAfterCommit(async () => { await sendPasswordRecoveryUsedMail({ receiver: mailInfo.mail, locale: mailInfo.locale diff --git a/src/function/parent/sign-in-into-family.ts b/src/function/parent/sign-in-into-family.ts index 8637b4e..d492879 100644 --- a/src/function/parent/sign-in-into-family.ts +++ b/src/function/parent/sign-in-into-family.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -17,7 +17,7 @@ import { Conflict } from 'http-errors' import { NewDeviceInfo } from '../../api/schema' -import { Database } from '../../database' +import { SimpleDatabase } from '../../database/simple' import { sendDeviceLinkedMail } from '../../util/mail' import { generateAuthToken, generateIdWithinFamily, generateVersionId } from '../../util/token' import { WebsocketApi } from '../../websocket' @@ -30,7 +30,7 @@ import { ServerDataStatus } from '../../object/serverdatastatus' import { createEmptyClientDataStatus } from '../../object/clientdatastatus' export const signInIntoFamily = async ({ database, eventHandler, mailAuthToken, newDeviceInfo, deviceName, websocket, clientLevel }: { - database: Database + database: SimpleDatabase eventHandler: EventHandler mailAuthToken: string newDeviceInfo: NewDeviceInfo @@ -40,14 +40,14 @@ export const signInIntoFamily = async ({ database, eventHandler, mailAuthToken, // no transaction here because this is directly called from an API endpoint }): Promise<{ deviceId: string; deviceAuthToken: string; data: ServerDataStatus }> => { return database.transaction(async (transaction) => { - const mailInfo = await requireMailAndLocaleByAuthToken({ database, mailAuthToken, transaction, invalidate: true }) + const mailInfo = await requireMailAndLocaleByAuthToken({ mailAuthToken, transaction, invalidate: true }) - const userEntryUnsafe = await database.user.findOne({ + const userEntryUnsafe = await transaction.legacy.database.user.findOne({ where: { mail: mailInfo.mail }, attributes: ['familyId', 'userId'], - transaction + transaction: transaction.legacy.transaction }) if (!userEntryUnsafe) { @@ -62,7 +62,7 @@ export const signInIntoFamily = async ({ database, eventHandler, mailAuthToken, const deviceAuthToken = generateAuthToken() const deviceId = generateIdWithinFamily() - await database.device.create(prepareDeviceEntry({ + await transaction.legacy.database.device.create(prepareDeviceEntry({ familyId: userEntry.familyId, deviceId, userId: userEntry.userId, @@ -70,29 +70,28 @@ export const signInIntoFamily = async ({ database, eventHandler, mailAuthToken, deviceAuthToken, newDeviceInfo, isUserKeptSignedIn: true - }), { transaction }) + }), { transaction: transaction.legacy.transaction }) // notify about changes - await database.family.update({ + await transaction.legacy.database.family.update({ deviceListVersion: generateVersionId() }, { where: { familyId: userEntry.familyId }, - transaction + transaction: transaction.legacy.transaction }) await notifyClientsAboutChangesDelayed({ familyId: userEntry.familyId, websocket, - database, + transaction, generalLevel: 1, targetedLevels: new Map(), - sourceDeviceId: deviceId, - transaction + sourceDeviceId: deviceId }) - transaction.afterCommit(async () => { + transaction.enqueueAfterCommit(async () => { await sendDeviceLinkedMail({ receiver: mailInfo.mail, locale: mailInfo.locale, @@ -101,11 +100,10 @@ export const signInIntoFamily = async ({ database, eventHandler, mailAuthToken, }) const data = await generateServerDataStatus({ - database, + transaction, clientStatus: createEmptyClientDataStatus({ clientLevel }), familyId: userEntry.familyId, deviceId, - transaction, eventHandler }) diff --git a/src/function/purchase/add-purchase.ts b/src/function/purchase/add-purchase.ts index a676b85..e52110f 100644 --- a/src/function/purchase/add-purchase.ts +++ b/src/function/purchase/add-purchase.ts @@ -16,7 +16,7 @@ */ import { Conflict } from 'http-errors' -import { Database, Transaction } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' import { notifyClientsAboutChangesDelayed } from '../../function/websocket' import { WebsocketApi } from '../../websocket' @@ -25,32 +25,31 @@ const week = day * 7 const month = day * 31 const year = day * 366 -export const addPurchase = async ({ database, familyId, type, service, transactionId, websocket, transaction }: { - database: Database +export const addPurchase = async ({ familyId, type, service, transactionId, websocket, transaction }: { + transaction: SimpleDatabaseTransaction familyId: string type: 'month' | 'year' | 'unpaid14' service: 'googleplay' | 'directpurchase' transactionId: string websocket: WebsocketApi - transaction: Transaction }) => { - const oldPurchaseEntry = await database.purchase.findOne({ + const oldPurchaseEntry = await transaction.legacy.database.purchase.findOne({ where: { service, transactionId }, - transaction + transaction: transaction.legacy.transaction }) if (oldPurchaseEntry) { return } - const familyEntry = await database.family.findOne({ + const familyEntry = await transaction.legacy.database.family.findOne({ where: { familyId }, - transaction + transaction: transaction.legacy.transaction }) if (!familyEntry) { @@ -95,9 +94,9 @@ export const addPurchase = async ({ database, familyId, type, service, transacti throw new Error() } - await familyEntry.save({ transaction }) + await familyEntry.save({ transaction: transaction.legacy.transaction }) - await database.purchase.create({ + await transaction.legacy.database.purchase.create({ familyId, service, transactionId, @@ -106,16 +105,15 @@ export const addPurchase = async ({ database, familyId, type, service, transacti previousFullVersionEndTime, newFullVersionEndTime: familyEntry.fullVersionUntil }, { - transaction + transaction: transaction.legacy.transaction }) await notifyClientsAboutChangesDelayed({ familyId, sourceDeviceId: null, - database, + transaction, websocket, generalLevel: 2, - targetedLevels: new Map(), - transaction + targetedLevels: new Map() }) } diff --git a/src/function/purchase/require-family-entry.ts b/src/function/purchase/require-family-entry.ts index 88feaee..ebd4024 100644 --- a/src/function/purchase/require-family-entry.ts +++ b/src/function/purchase/require-family-entry.ts @@ -16,19 +16,18 @@ */ import { InternalServerError, Unauthorized } from 'http-errors' -import { Database, Transaction } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' -export const requireFamilyEntry = async ({ database, deviceAuthToken, transaction }: { - database: Database +export const requireFamilyEntry = async ({ transaction, deviceAuthToken }: { + transaction: SimpleDatabaseTransaction deviceAuthToken: string - transaction: Transaction }) => { - const deviceEntryUnsafe = await database.device.findOne({ + const deviceEntryUnsafe = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken }, attributes: ['familyId'], - transaction + transaction: transaction.legacy.transaction }) if (!deviceEntryUnsafe) { @@ -39,12 +38,12 @@ export const requireFamilyEntry = async ({ database, deviceAuthToken, transactio familyId: deviceEntryUnsafe.familyId } - const familyEntryUnsafe = await database.family.findOne({ + const familyEntryUnsafe = await transaction.legacy.database.family.findOne({ where: { familyId: deviceEntry.familyId }, attributes: ['fullVersionUntil', 'fullVersionDebts'], - transaction + transaction: transaction.legacy.transaction }) if (!familyEntryUnsafe) { diff --git a/src/function/statusmessage/index.ts b/src/function/statusmessage/index.ts index e4ee70e..5302813 100644 --- a/src/function/statusmessage/index.ts +++ b/src/function/statusmessage/index.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,37 +15,39 @@ * along with this program. If not, see . */ -import * as Sequelize from 'sequelize' -import { Database } from '../../database' +import { SimpleDatabase, SimpleDatabaseTransaction } from '../../database/simple' import { configItemIds } from '../../database/config' -export const getStatusMessage = async ({ database, transaction }: { - database: Database - transaction?: Sequelize.Transaction +export const getStatusMessage = async ({ transaction }: { + transaction: SimpleDatabaseTransaction }) => { - const currentStatusMessageItem = await database.config.findByPk(configItemIds.statusMessage, { transaction }) + const currentStatusMessageItem = await transaction.legacy.database.config.findByPk( + configItemIds.statusMessage, + { transaction: transaction.legacy.transaction } + ) + const currentStatusMessage = (currentStatusMessageItem ? currentStatusMessageItem.value : null) || '' return currentStatusMessage } export const setStatusMessage = async ({ database, newStatusMessage }: { - database: Database + database: SimpleDatabase newStatusMessage: string }) => { await database.transaction(async (transaction) => { if (newStatusMessage === '') { - await database.config.destroy({ + await transaction.legacy.database.config.destroy({ where: { id: configItemIds.statusMessage }, - transaction + transaction: transaction.legacy.transaction }) } else { - await database.config.upsert({ + await transaction.legacy.database.config.upsert({ id: configItemIds.statusMessage, value: newStatusMessage - }, { transaction }) + }, { transaction: transaction.legacy.transaction }) } }) } diff --git a/src/function/sync/apply-actions/baseinfo.ts b/src/function/sync/apply-actions/baseinfo.ts index 334192b..89cd2f3 100644 --- a/src/function/sync/apply-actions/baseinfo.ts +++ b/src/function/sync/apply-actions/baseinfo.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,7 +16,7 @@ */ import { Unauthorized } from 'http-errors' -import { Database, Transaction } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { SourceFamilyNotFoundException } from './exception/illegal-state' export interface ApplyActionBaseInfo { @@ -26,15 +26,14 @@ export interface ApplyActionBaseInfo { hasFullVersion: boolean } -export async function getApplyActionBaseInfo ({ database, transaction, deviceAuthToken }: { - database: Database - transaction: Transaction +export async function getApplyActionBaseInfo ({ transaction, deviceAuthToken }: { + transaction: SimpleDatabaseTransaction deviceAuthToken: string }): Promise { - const deviceEntryUnsafe = await database.device.findOne({ + const deviceEntryUnsafe = await transaction.legacy.database.device.findOne({ where: { deviceAuthToken }, attributes: ['familyId', 'deviceId', 'nextSequenceNumber'], - transaction + transaction: transaction.legacy.transaction }) if (!deviceEntryUnsafe) { @@ -47,11 +46,11 @@ export async function getApplyActionBaseInfo ({ database, transaction, deviceAut nextSequenceNumber: deviceEntryUnsafe.nextSequenceNumber } - const familyEntryUnsafe = await database.family.findOne({ + const familyEntryUnsafe = await transaction.legacy.database.family.findOne({ where: { familyId: deviceEntry.familyId }, - transaction, + transaction: transaction.legacy.transaction, attributes: ['hasFullVersion'] }) diff --git a/src/function/sync/apply-actions/cache.ts b/src/function/sync/apply-actions/cache.ts index fcf9555..4049b18 100644 --- a/src/function/sync/apply-actions/cache.ts +++ b/src/function/sync/apply-actions/cache.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -19,7 +19,7 @@ import { memoize } from 'lodash' import * as Sequelize from 'sequelize' import { config } from '../../../config' import { VisibleConnectedDevicesManager } from '../../../connected-devices' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { setToList } from '../../../util/list' import { generateVersionId } from '../../../util/token' import { SourceUserNotFoundException } from './exception/illegal-state' @@ -29,8 +29,7 @@ export class Cache { readonly familyId: string readonly deviceId: string readonly hasFullVersion: boolean - transaction: Sequelize.Transaction - readonly database: Database + transaction: SimpleDatabaseTransaction readonly connectedDevicesManager: VisibleConnectedDevicesManager private requireSenderDoFullSync = false @@ -48,18 +47,16 @@ export class Cache { triggeredSyncLevel: 0 | 1 | 2 = 0 // 0 = no, 1 = unimportant, 2 = important targetedTriggeredSyncLevels = new Map() - constructor ({ familyId, deviceId, hasFullVersion, database, transaction, connectedDevicesManager }: { + constructor ({ familyId, deviceId, hasFullVersion, transaction, connectedDevicesManager }: { familyId: string deviceId: string hasFullVersion: boolean - database: Database - transaction: Sequelize.Transaction + transaction: SimpleDatabaseTransaction connectedDevicesManager: VisibleConnectedDevicesManager }) { this.familyId = familyId this.deviceId = deviceId this.hasFullVersion = hasFullVersion || config.alwaysPro - this.database = database this.transaction = transaction this.connectedDevicesManager = connectedDevicesManager } @@ -77,7 +74,7 @@ export class Cache { async subtransaction (callback: () => Promise): Promise { const oldTransaction = this.transaction - return this.database.transaction(async (newTransaction) => { + return this.transaction.transaction(async (newTransaction) => { try { this.transaction = newTransaction @@ -87,18 +84,18 @@ export class Cache { } finally { this.transaction = oldTransaction } - }, { transaction: oldTransaction }) + }) } getSecondPasswordHashOfParent = memoize(async (parentId: string) => { - const userEntryUnsafe = await this.database.user.findOne({ + const userEntryUnsafe = await this.transaction.legacy.database.user.findOne({ where: { familyId: this.familyId, userId: parentId, type: 'parent' }, attributes: ['secondPasswordHash'], - transaction: this.transaction + transaction: this.transaction.legacy.transaction }) if (!userEntryUnsafe) { @@ -109,14 +106,14 @@ export class Cache { }) getSecondPasswordHashOfChild = memoize(async (childId: string) => { - const userEntryUnsafe = await this.database.user.findOne({ + const userEntryUnsafe = await this.transaction.legacy.database.user.findOne({ where: { familyId: this.familyId, userId: childId, type: 'child' }, attributes: ['secondPasswordHash'], - transaction: this.transaction + transaction: this.transaction.legacy.transaction }) if (!userEntryUnsafe) { @@ -131,24 +128,24 @@ export class Cache { }) doesCategoryExist = memoize(async (categoryId: string) => { - const categoryEntry = await this.database.category.findOne({ + const categoryEntry = await this.transaction.legacy.database.category.findOne({ where: { familyId: this.familyId, categoryId }, - transaction: this.transaction + transaction: this.transaction.legacy.transaction }) return !!categoryEntry }) doesUserExist = memoize(async (userId: string) => { - const userEntry = await this.database.user.findOne({ + const userEntry = await this.transaction.legacy.database.user.findOne({ where: { familyId: this.familyId, userId }, - transaction: this.transaction + transaction: this.transaction.legacy.transaction }) return !!userEntry @@ -158,10 +155,10 @@ export class Cache { requireSenderFullSync: () => void = () => this.requireSenderDoFullSync = true async saveModifiedVersionNumbers () { - const { database, transaction, familyId } = this + const { familyId } = this if (this.categoriesWithModifiedApps.size > 0) { - await database.category.update({ + await this.transaction.legacy.database.category.update({ assignedAppsVersion: generateVersionId() }, { where: { @@ -170,14 +167,14 @@ export class Cache { [Sequelize.Op.in]: setToList(this.categoriesWithModifiedApps) } }, - transaction + transaction: this.transaction.legacy.transaction }) this.categoriesWithModifiedApps.clear() } if (this.categoriesWithModifiedBaseData.size > 0) { - await database.category.update({ + await this.transaction.legacy.database.category.update({ baseVersion: generateVersionId() }, { where: { @@ -186,14 +183,14 @@ export class Cache { [Sequelize.Op.in]: setToList(this.categoriesWithModifiedBaseData) } }, - transaction + transaction: this.transaction.legacy.transaction }) this.categoriesWithModifiedBaseData.clear() } if (this.categoriesWithModifiedTimeLimitRules.size > 0) { - await database.category.update({ + await this.transaction.legacy.database.category.update({ timeLimitRulesVersion: generateVersionId() }, { where: { @@ -202,14 +199,14 @@ export class Cache { [Sequelize.Op.in]: setToList(this.categoriesWithModifiedTimeLimitRules) } }, - transaction + transaction: this.transaction.legacy.transaction }) this.categoriesWithModifiedTimeLimitRules.clear() } if (this.categoriesWithModifiedUsedTimes.size > 0) { - await database.category.update({ + await this.transaction.legacy.database.category.update({ usedTimesVersion: generateVersionId() }, { where: { @@ -218,14 +215,14 @@ export class Cache { [Sequelize.Op.in]: setToList(this.categoriesWithModifiedUsedTimes) } }, - transaction + transaction: this.transaction.legacy.transaction }) this.categoriesWithModifiedUsedTimes.clear() } if (this.categoriesWithModifiedTasks.size > 0) { - await database.category.update({ + await this.transaction.legacy.database.category.update({ taskListVersion: generateVersionId() }, { where: { @@ -234,46 +231,46 @@ export class Cache { [Sequelize.Op.in]: setToList(this.categoriesWithModifiedTasks) } }, - transaction + transaction: this.transaction.legacy.transaction }) this.categoriesWithModifiedUsedTimes.clear() } if (this.invalidiateUserList) { - await database.family.update({ + await this.transaction.legacy.database.family.update({ userListVersion: generateVersionId() }, { where: { familyId: this.familyId }, - transaction + transaction: this.transaction.legacy.transaction }) this.invalidiateUserList = false } if (this.invalidiateDeviceList) { - await database.family.update({ + await this.transaction.legacy.database.family.update({ deviceListVersion: generateVersionId() }, { where: { familyId: this.familyId }, - transaction + transaction: this.transaction.legacy.transaction }) this.invalidiateDeviceList = false } if (this.invalidateU2fList) { - await database.family.update({ + await this.transaction.legacy.database.family.update({ u2fKeysVersion: generateVersionId() }, { where: { familyId: this.familyId }, - transaction + transaction: this.transaction.legacy.transaction }) this.invalidateU2fList = false diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/addusedtime.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/addusedtime.ts index 3f3be9f..8895383 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/addusedtime.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/addusedtime.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -37,12 +37,12 @@ export async function dispatchAddUsedTime ({ action, cache }: { }) { const roundedTimestamp = getRoundedTimestamp().toString(10) - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: [ 'childId', 'parentCategoryId', @@ -65,7 +65,7 @@ export async function dispatchAddUsedTime ({ action, cache }: { currentExtraTime: number }) => { if (action.timeToAdd !== 0) { - const oldItem = await cache.database.usedTime.findOne({ + const oldItem = await cache.transaction.legacy.database.usedTime.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId, @@ -73,7 +73,7 @@ export async function dispatchAddUsedTime ({ action, cache }: { startMinuteOfDay: MinuteOfDay.MIN, endMinuteOfDay: MinuteOfDay.MAX }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (oldItem) { @@ -84,7 +84,7 @@ export async function dispatchAddUsedTime ({ action, cache }: { const newLastUpdate = parseInt(roundedTimestamp, 10) if (oldUsedTime !== newUsedTime || oldLastUpdate !== newLastUpdate) { - const [updatedRows] = await cache.database.usedTime.update({ + const [updatedRows] = await cache.transaction.legacy.database.usedTime.update({ usedTime: newUsedTime, lastUpdate: newLastUpdate.toString(10) }, { @@ -95,7 +95,7 @@ export async function dispatchAddUsedTime ({ action, cache }: { startMinuteOfDay: MinuteOfDay.MIN, endMinuteOfDay: MinuteOfDay.MAX }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (updatedRows === 0) { @@ -103,7 +103,7 @@ export async function dispatchAddUsedTime ({ action, cache }: { } } } else { - await cache.database.usedTime.create({ + await cache.transaction.legacy.database.usedTime.create({ familyId: cache.familyId, categoryId: action.categoryId, dayOfEpoch: action.dayOfEpoch, @@ -112,20 +112,20 @@ export async function dispatchAddUsedTime ({ action, cache }: { startMinuteOfDay: MinuteOfDay.MIN, endMinuteOfDay: MinuteOfDay.MAX }, { - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) } } if (action.extraTimeToSubtract !== 0) { - await cache.database.category.update({ + await cache.transaction.legacy.database.category.update({ extraTimeInMillis: Math.max(0, currentExtraTime - action.extraTimeToSubtract) }, { where: { familyId: cache.familyId, categoryId: categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedBaseData.add(categoryId) @@ -140,13 +140,13 @@ export async function dispatchAddUsedTime ({ action, cache }: { }) if (categoryEntry.parentCategoryId !== '') { - const parentCategoryEntry = await cache.database.category.findOne({ + const parentCategoryEntry = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: categoryEntry.parentCategoryId, childId: categoryEntry.childId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (parentCategoryEntry) { diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/addusedtime2.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/addusedtime2.ts index 0e5a04d..5745a49 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/addusedtime2.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/addusedtime2.ts @@ -37,13 +37,13 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev cache: Cache eventHandler: EventHandler }) { - const deviceEntryUnsafe = await cache.database.device.findOne({ + const deviceEntryUnsafe = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId: deviceId }, attributes: ['currentUserId'], - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!deviceEntryUnsafe) { @@ -60,12 +60,12 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev let addUsedTimeForADifferentUserThanTheCurrentUserOfTheDevice = false for (const item of action.items) { - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: item.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: [ 'childId', 'extraTimeInMillis' @@ -93,7 +93,7 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev const lengthInMinutes = (end - start) + 1 const lengthInMs = lengthInMinutes * 1000 * 60 - const oldItem = await cache.database.usedTime.findOne({ + const oldItem = await cache.transaction.legacy.database.usedTime.findOne({ where: { familyId: cache.familyId, categoryId: item.categoryId, @@ -101,7 +101,7 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev startMinuteOfDay: start, endMinuteOfDay: end }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (oldItem) { @@ -112,7 +112,7 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev const newLastUpdate = parseInt(roundedTimestampForUsedTime, 10) if (oldUsedTime !== newUsedTime || oldLastUpdate !== newLastUpdate) { - const [updatedRows] = await cache.database.usedTime.update({ + const [updatedRows] = await cache.transaction.legacy.database.usedTime.update({ usedTime: newUsedTime, lastUpdate: newLastUpdate.toString(10) }, { @@ -123,7 +123,7 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev startMinuteOfDay: start, endMinuteOfDay: end }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (updatedRows === 0) { @@ -131,7 +131,7 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev } } } else { - const oldTime: number | null = await cache.database.usedTime.aggregate( + const oldTime: number | null = await cache.transaction.legacy.database.usedTime.aggregate( 'usedTime', 'MAX', { @@ -146,13 +146,13 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev [Sequelize.Op.lte]: end } }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction } ) || 0 if (oldTime !== null && typeof oldTime !== 'number') throw new Error() - await cache.database.usedTime.create({ + await cache.transaction.legacy.database.usedTime.create({ familyId: cache.familyId, categoryId: item.categoryId, dayOfEpoch: action.dayOfEpoch, @@ -161,7 +161,7 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev startMinuteOfDay: start, endMinuteOfDay: end }, { - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) } } @@ -179,7 +179,7 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev for (let j = 0; j < item.sessionDurationLimits.length; j++) { const limit = item.sessionDurationLimits[j] - const oldItem = await cache.database.sessionDuration.findOne({ + const oldItem = await cache.transaction.legacy.database.sessionDuration.findOne({ where: { familyId: cache.familyId, categoryId: item.categoryId, @@ -188,11 +188,11 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev startMinuteOfDay: limit.start, endMinuteOfDay: limit.end }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) const oldDuration: () => Promise = async () => { - const fittingDurationItems = await cache.database.sessionDuration.findAll({ + const fittingDurationItems = await cache.transaction.legacy.database.sessionDuration.findAll({ where: { familyId: cache.familyId, categoryId: item.categoryId, @@ -209,7 +209,7 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev [Sequelize.Op.lte]: limit.pause } }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) const fittingDurationItemsLastUsageFiltered = @@ -259,9 +259,9 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev } } - await oldItem.save({ transaction: cache.transaction }) + await oldItem.save({ transaction: cache.transaction.legacy.transaction }) } else { - await cache.database.sessionDuration.create({ + await cache.transaction.legacy.database.sessionDuration.create({ familyId: cache.familyId, categoryId: item.categoryId, maxSessionDuration: limit.duration, @@ -272,21 +272,21 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache, ev lastUsage: action.trustedTimestamp.toString(10), lastSessionDuration: await oldDuration() + item.timeToAdd, roundedLastUpdate: roundedTimestampForSessionDuration - }, { transaction: cache.transaction }) + }, { transaction: cache.transaction.legacy.transaction }) } } cache.categoriesWithModifiedUsedTimes.add(item.categoryId) if (item.extraTimeToSubtract !== 0) { - await cache.database.category.update({ + await cache.transaction.legacy.database.category.update({ extraTimeInMillis: Math.max(0, categoryEntry.extraTimeInMillis - item.extraTimeToSubtract) }, { where: { familyId: cache.familyId, categoryId: item.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedBaseData.add(item.categoryId) diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/finishkeyrequest.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/finishkeyrequest.ts index 74b3129..6b90c54 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/finishkeyrequest.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/finishkeyrequest.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,13 +23,13 @@ export async function dispatchFinishKeyRequestAction ({ action, cache, deviceId action: FinishKeyRequestAction cache: Cache }) { - await cache.database.keyRequest.destroy({ + await cache.transaction.legacy.database.keyRequest.destroy({ where: { familyId: cache.familyId, senderDeviceId: deviceId, senderSequenceNumber: action.deviceSequenceNumber.toString(10) }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) // no sync triggered diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/marktaskpendingaction.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/marktaskpendingaction.ts index 5533589..1b9ade2 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/marktaskpendingaction.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/marktaskpendingaction.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -26,12 +26,12 @@ export async function dispatchMarkTaskPendingAction ({ action, cache, deviceId } action: MarkTaskPendingAction cache: Cache }) { - const taskInfoUnsafe = await cache.database.childTask.findOne({ + const taskInfoUnsafe = await cache.transaction.legacy.database.childTask.findOne({ where: { familyId: cache.familyId, taskId: action.taskId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['categoryId', 'pendingRequest', 'taskTitle'] }) @@ -45,13 +45,13 @@ export async function dispatchMarkTaskPendingAction ({ action, cache, deviceId } if (taskInfo.pendingRequest !== 0) return // review already requested - const categoryInfoUnsafe = await cache.database.category.findOne({ + const categoryInfoUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: taskInfo.categoryId }, attributes: ['childId'], - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (categoryInfoUnsafe === null) { @@ -60,13 +60,13 @@ export async function dispatchMarkTaskPendingAction ({ action, cache, deviceId } const categoryInfo = { childId: categoryInfoUnsafe.childId } - const deviceInfoUnsafe = await cache.database.device.findOne({ + const deviceInfoUnsafe = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId }, attributes: ['currentUserId'], - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (deviceInfoUnsafe === null) throw new SourceDeviceNotFoundException() @@ -77,33 +77,33 @@ export async function dispatchMarkTaskPendingAction ({ action, cache, deviceId } throw new IllegalStateException({ staticMessage: 'Can not mark task pending for other user than the current user' }) } - const childInfoUnsafe = await cache.database.user.findOne({ + const childInfoUnsafe = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: categoryInfo.childId }, attributes: ['name'], - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (childInfoUnsafe === null) throw new SourceUserNotFoundException() const childInfo = { name: childInfoUnsafe.name } - await cache.database.childTask.update({ pendingRequest: 1 }, { + await cache.transaction.legacy.database.childTask.update({ pendingRequest: 1 }, { where: { familyId: cache.familyId, taskId: action.taskId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedTasks.add(taskInfo.categoryId) cache.incrementTriggeredSyncLevel(1) // parents are not faster reachable await sendTaskDoneMails({ - database: cache.database, - transaction: cache.transaction, + database: cache.transaction.legacy.database, + transaction: cache.transaction.legacy.transaction, familyId: cache.familyId, childName: childInfo.name, taskTitle: taskInfo.taskTitle diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/ping.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/ping.ts index cf40ca2..2eb0e74 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/ping.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/ping.ts @@ -33,25 +33,25 @@ export async function dispatchPingAction ({ action, cache, deviceId }: { else throw new Error() // delete any previous ping/pong - await cache.database.ping.destroy({ + await cache.transaction.legacy.database.ping.destroy({ where: { familyId: cache.familyId, receiverDeviceId: action.deviceId, senderDeviceId: deviceId, type: type }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) // insert - await cache.database.ping.create({ + await cache.transaction.legacy.database.ping.create({ familyId: cache.familyId, receiverDeviceId: action.deviceId, senderDeviceId: deviceId, type, token: action.token }, { - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) // notify @@ -60,14 +60,14 @@ export async function dispatchPingAction ({ action, cache, deviceId }: { // handle deleting if (action.event === 'pong' || action.event === 'clear') { - await cache.database.ping.destroy({ + await cache.transaction.legacy.database.ping.destroy({ where: { familyId: cache.familyId, receiverDeviceId: deviceId, senderDeviceId: action.deviceId, token: action.token }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) } } diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/replytokeyrequest.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/replytokeyrequest.ts index 33f522f..e165143 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/replytokeyrequest.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/replytokeyrequest.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -26,13 +26,13 @@ export async function dispatchReplyToKeyRequestAction ({ deviceId, action, cache cache: Cache eventHandler: EventHandler }) { - const requestUnsafe = await cache.database.keyRequest.findOne({ + const requestUnsafe = await cache.transaction.legacy.database.keyRequest.findOne({ where: { familyId: cache.familyId, serverSequenceNumber: action.requestServerSequenceNumber.toString(10) }, attributes: ['senderDeviceId', 'senderSequenceNumber'], - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!requestUnsafe) { @@ -46,14 +46,14 @@ export async function dispatchReplyToKeyRequestAction ({ deviceId, action, cache senderSequenceNumber: requestUnsafe.senderSequenceNumber } - const oldReplyCounter = await cache.database.keyResponse.count({ + const oldReplyCounter = await cache.transaction.legacy.database.keyResponse.count({ where: { familyId: cache.familyId, receiverDeviceId: request.senderDeviceId, requestServerSequenceNumber: action.requestServerSequenceNumber.toString(10), senderDeviceId: deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (oldReplyCounter !== 0) { @@ -62,12 +62,12 @@ export async function dispatchReplyToKeyRequestAction ({ deviceId, action, cache return } - const deviceEntryUnsafe = await cache.database.device.findOne({ + const deviceEntryUnsafe = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId: request.senderDeviceId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['nextKeyReplySequenceNumber'] }) @@ -81,17 +81,17 @@ export async function dispatchReplyToKeyRequestAction ({ deviceId, action, cache nextKeyReplySequenceNumber: deviceEntryUnsafe.nextKeyReplySequenceNumber } - await cache.database.device.update({ + await cache.transaction.legacy.database.device.update({ nextKeyReplySequenceNumber: (parseInt(deviceEntry.nextKeyReplySequenceNumber) + 1).toString(10) }, { where: { familyId: cache.familyId, deviceId: request.senderDeviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) - await cache.database.keyResponse.create({ + await cache.transaction.legacy.database.keyResponse.create({ familyId: cache.familyId, receiverDeviceId: request.senderDeviceId, requestServerSequenceNumber: action.requestServerSequenceNumber.toString(10), @@ -102,7 +102,7 @@ export async function dispatchReplyToKeyRequestAction ({ deviceId, action, cache encryptedKey: action.encryptedKey, signature: action.signature }, { - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.incrementTargetedTriggeredSyncLevel(request.senderDeviceId, 2) diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/sendkeyrequest.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/sendkeyrequest.ts index a79b1f2..35199ee 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/sendkeyrequest.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/sendkeyrequest.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -24,11 +24,11 @@ export async function dispatchSendKeyRequestAction ({ action, cache, deviceId }: action: SendKeyRequestAction cache: Cache }) { - const familyEntryUnsafe = await cache.database.family.findOne({ + const familyEntryUnsafe = await cache.transaction.legacy.database.family.findOne({ where: { familyId: cache.familyId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['nextServerKeyRequestSeq'] }) @@ -38,16 +38,16 @@ export async function dispatchSendKeyRequestAction ({ action, cache, deviceId }: const serverSequenceNumber = familyEntryUnsafe.nextServerKeyRequestSeq - await cache.database.family.update({ + await cache.transaction.legacy.database.family.update({ nextServerKeyRequestSeq: (parseInt(serverSequenceNumber, 10) + 1).toString(10) }, { where: { familyId: cache.familyId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) - await cache.database.keyRequest.destroy({ + await cache.transaction.legacy.database.keyRequest.destroy({ where: { familyId: cache.familyId, senderDeviceId: deviceId, @@ -55,10 +55,10 @@ export async function dispatchSendKeyRequestAction ({ action, cache, deviceId }: deviceId: action.deviceId || null, categoryId: action.categoryId || null }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) - await cache.database.keyRequest.create({ + await cache.transaction.legacy.database.keyRequest.create({ familyId: cache.familyId, serverSequenceNumber: serverSequenceNumber, senderDeviceId: deviceId, @@ -69,7 +69,7 @@ export async function dispatchSendKeyRequestAction ({ action, cache, deviceId }: tempKey: action.tempKey, signature: action.signature }, { - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.incrementTriggeredSyncLevel(2) diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/signoutatdevice.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/signoutatdevice.ts index d300581..0163c46 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/signoutatdevice.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/signoutatdevice.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -30,12 +30,12 @@ export async function dispatchSignOutAtDevice ({ deviceId, cache }: { throw new PremiumVersionMissingException() } - const deviceEntry = await cache.database.device.findOne({ + const deviceEntry = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!deviceEntry) { diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/trieddisablingdeviceadmin.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/trieddisablingdeviceadmin.ts index dfde422..104b901 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/trieddisablingdeviceadmin.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/trieddisablingdeviceadmin.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -26,12 +26,12 @@ export async function dispatchTriedDisablingDeviceAdmin ({ deviceId, cache }: { action: TriedDisablingDeviceAdminAction cache: Cache }) { - const deviceEntry = await cache.database.device.findOne({ + const deviceEntry = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (deviceEntry === null) { @@ -43,7 +43,7 @@ export async function dispatchTriedDisablingDeviceAdmin ({ deviceId, cache }: { if (!deviceEntry.triedDisablingDeviceAdmin) { deviceEntry.triedDisablingDeviceAdmin = true - await deviceEntry.save({ transaction: cache.transaction }) + await deviceEntry.save({ transaction: cache.transaction.legacy.transaction }) cache.invalidiateDeviceList = true cache.incrementTriggeredSyncLevel(1) @@ -51,7 +51,6 @@ export async function dispatchTriedDisablingDeviceAdmin ({ deviceId, cache }: { if (!hadManipulationBefore) { await sendManipulationWarnings({ - database: cache.database, transaction: cache.transaction, deviceName: deviceEntry.name, familyId: cache.familyId diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/updatedevicestatus.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/updatedevicestatus.ts index 070ac7c..7a9d98a 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/updatedevicestatus.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/updatedevicestatus.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2023 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -30,12 +30,12 @@ export async function dispatchUpdateDeviceStatus ({ deviceId, action, cache }: { action: UpdateDeviceStatusAction cache: Cache }) { - const deviceEntry = await cache.database.device.findOne({ + const deviceEntry = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!deviceEntry) { @@ -175,12 +175,11 @@ export async function dispatchUpdateDeviceStatus ({ deviceId, action, cache }: { } } - await deviceEntry.save({ transaction: cache.transaction }) + await deviceEntry.save({ transaction: cache.transaction.legacy.transaction }) if (hasDeviceManipulation(deviceEntry)) { if (!hadManipulationBefore) { await sendManipulationWarnings({ - database: cache.database, transaction: cache.transaction, deviceName: deviceEntry.name, familyId: cache.familyId diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/updateinstalledapps.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/updateinstalledapps.ts index fae4520..36dbb1c 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/updateinstalledapps.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/updateinstalledapps.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -26,13 +26,13 @@ export async function dispatchUpdateInstalledApps ({ deviceId, action, cache }: cache: Cache }) { async function upsert({ type, data }: { type: number, data: Buffer }) { - await cache.database.encryptedAppList.upsert({ + await cache.transaction.legacy.database.encryptedAppList.upsert({ familyId: cache.familyId, deviceId, type, version: generateVersionId(), data - }, { transaction: cache.transaction }) + }, { transaction: cache.transaction.legacy.transaction }) } if (action.base) { diff --git a/src/function/sync/apply-actions/dispatch-app-logic-action/uploaddevicepublickey.ts b/src/function/sync/apply-actions/dispatch-app-logic-action/uploaddevicepublickey.ts index 0ac9b90..a54a3fc 100644 --- a/src/function/sync/apply-actions/dispatch-app-logic-action/uploaddevicepublickey.ts +++ b/src/function/sync/apply-actions/dispatch-app-logic-action/uploaddevicepublickey.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -26,12 +26,12 @@ export async function dispatchUploadDevicePublicKeyAction ({ deviceId, action, c cache: Cache eventHandler: EventHandler }) { - const deviceEntry = await cache.database.device.findOne({ + const deviceEntry = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (deviceEntry === null) { @@ -39,7 +39,7 @@ export async function dispatchUploadDevicePublicKeyAction ({ deviceId, action, c } else if (deviceEntry.publicKey === null) { deviceEntry.publicKey = action.key - await deviceEntry.save({ transaction: cache.transaction }) + await deviceEntry.save({ transaction: cache.transaction.legacy.transaction }) cache.invalidiateDeviceList = true cache.incrementTriggeredSyncLevel(2) diff --git a/src/function/sync/apply-actions/dispatch-child-action/childchangepassword.ts b/src/function/sync/apply-actions/dispatch-child-action/childchangepassword.ts index dcfdd4d..359631f 100644 --- a/src/function/sync/apply-actions/dispatch-child-action/childchangepassword.ts +++ b/src/function/sync/apply-actions/dispatch-child-action/childchangepassword.ts @@ -25,13 +25,13 @@ export const dispatchChildChangePassword = async ({ action, childUserId, cache } childUserId: string cache: Cache }) => { - const childEntry = await cache.database.user.findOne({ + const childEntry = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: childUserId, type: 'child' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!childEntry) { @@ -44,7 +44,7 @@ export const dispatchChildChangePassword = async ({ action, childUserId, cache } childEntry.secondPasswordSalt = newPassword.secondSalt childEntry.secondPasswordHash = newPassword.secondHash - await childEntry.save({ transaction: cache.transaction }) + await childEntry.save({ transaction: cache.transaction.legacy.transaction }) { const clear = cache.getSecondPasswordHashOfChild.cache.clear diff --git a/src/function/sync/apply-actions/dispatch-child-action/childsignin.ts b/src/function/sync/apply-actions/dispatch-child-action/childsignin.ts index 1704572..a14c5e1 100644 --- a/src/function/sync/apply-actions/dispatch-child-action/childsignin.ts +++ b/src/function/sync/apply-actions/dispatch-child-action/childsignin.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -39,13 +39,13 @@ export const dispatchChildSignIn = async ({ deviceId, childUserId, cache }: { cache }) - const userEntryUnsafe = await cache.database.user.findOne({ + const userEntryUnsafe = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, type: 'child', userId: childUserId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: [ 'currentDevice' ] @@ -58,7 +58,7 @@ export const dispatchChildSignIn = async ({ deviceId, childUserId, cache }: { if (userEntryUnsafe.currentDevice === deviceId) { // unassign to prevent way aroundprimary device rule - await cache.database.user.update({ + await cache.transaction.legacy.database.user.update({ currentDevice: '' }, { where: { @@ -66,7 +66,7 @@ export const dispatchChildSignIn = async ({ deviceId, childUserId, cache }: { type: 'child', userId: childUserId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.invalidiateUserList = true diff --git a/src/function/sync/apply-actions/dispatch-helper/parent-action.ts b/src/function/sync/apply-actions/dispatch-helper/parent-action.ts index d293d52..146af86 100644 --- a/src/function/sync/apply-actions/dispatch-helper/parent-action.ts +++ b/src/function/sync/apply-actions/dispatch-helper/parent-action.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -45,14 +45,14 @@ export async function dispatchParentAction ({ parser: parseParentAction, applier: async (parsedAction) => { if (isChildLimitAdding) { - const deviceEntryUnsafe = await cache.database.device.findOne({ + const deviceEntryUnsafe = await cache.transaction.legacy.database.device.findOne({ attributes: ['currentUserId'], where: { familyId: cache.familyId, deviceId, currentUserId: action.userId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!deviceEntryUnsafe) { @@ -67,14 +67,14 @@ export async function dispatchParentAction ({ }) } - const deviceUserEntryUnsafe = await cache.database.user.findOne({ + const deviceUserEntryUnsafe = await cache.transaction.legacy.database.user.findOne({ attributes: ['flags'], where: { familyId: cache.familyId, userId: deviceUserId, type: 'child' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!deviceUserEntryUnsafe) { diff --git a/src/function/sync/apply-actions/dispatch-parent-action/addcategoryapps.ts b/src/function/sync/apply-actions/dispatch-parent-action/addcategoryapps.ts index e6b8b72..401cbcc 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/addcategoryapps.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/addcategoryapps.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -29,12 +29,12 @@ export async function dispatchAddCategoryApps ({ action, cache, fromChildSelfLim cache: Cache fromChildSelfLimitAddChildUserId: string | null }) { - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['childId'] }) @@ -50,13 +50,13 @@ export async function dispatchAddCategoryApps ({ action, cache, fromChildSelfLim } } - const categoriesOfSameChild = (await cache.database.category.findAll({ + const categoriesOfSameChild = (await cache.transaction.legacy.database.category.findAll({ where: { familyId: cache.familyId, childId }, attributes: ['categoryId', 'parentCategoryId'], - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction })).map((item) => ({ categoryId: item.categoryId, parentCategoryId: item.parentCategoryId @@ -64,7 +64,7 @@ export async function dispatchAddCategoryApps ({ action, cache, fromChildSelfLim const userCategoryIds = categoriesOfSameChild.map((item) => item.categoryId) - const oldCategories = (await cache.database.categoryApp.findAll({ + const oldCategories = (await cache.transaction.legacy.database.categoryApp.findAll({ attributes: [ 'categoryId' ], group: [ 'categoryId' ], where: { @@ -76,7 +76,7 @@ export async function dispatchAddCategoryApps ({ action, cache, fromChildSelfLim [Sequelize.Op.in]: action.packageNames } }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction })).map((item) => item.categoryId) if (fromChildSelfLimitAddChildUserId !== null) { @@ -92,13 +92,13 @@ export async function dispatchAddCategoryApps ({ action, cache, fromChildSelfLim try { const parentCategoriesOfTargetCategory = getCategoryWithParentCategories(categoriesOfSameChild, action.categoryId) - const userEntryUnsafe = await cache.database.user.findOne({ + const userEntryUnsafe = await cache.transaction.legacy.database.user.findOne({ attributes: [ 'categoryForNotAssignedApps' ], where: { familyId: cache.familyId, userId: fromChildSelfLimitAddChildUserId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!userEntryUnsafe) { @@ -111,7 +111,7 @@ export async function dispatchAddCategoryApps ({ action, cache, fromChildSelfLim parentCategoriesOfTargetCategory.indexOf(validatedDefaultCategoryId) !== -1 const assertCanAddApp = async (packageName: string, isApp: boolean) => { - const categoryAppEntryUnsafe = await cache.database.categoryApp.findOne({ + const categoryAppEntryUnsafe = await cache.transaction.legacy.database.categoryApp.findOne({ attributes: [ 'categoryId' ], where: { familyId: cache.familyId, @@ -120,7 +120,7 @@ export async function dispatchAddCategoryApps ({ action, cache, fromChildSelfLim }, packageName: packageName }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) const categoryAppEntry = categoryAppEntryUnsafe ? { categoryId: categoryAppEntryUnsafe.categoryId } : null @@ -162,7 +162,7 @@ export async function dispatchAddCategoryApps ({ action, cache, fromChildSelfLim } if (oldCategories.length > 0) { - await cache.database.categoryApp.destroy({ + await cache.transaction.legacy.database.categoryApp.destroy({ where: { familyId: cache.familyId, categoryId: { @@ -172,18 +172,18 @@ export async function dispatchAddCategoryApps ({ action, cache, fromChildSelfLim [Sequelize.Op.in]: action.packageNames } }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) } - await cache.database.categoryApp.bulkCreate( + await cache.transaction.legacy.database.categoryApp.bulkCreate( action.packageNames.map((packageName): CategoryAppAttributes => ({ familyId: cache.familyId, categoryId: action.categoryId, packageName })), { - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction } ) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/addcategorynetworkid.ts b/src/function/sync/apply-actions/dispatch-parent-action/addcategorynetworkid.ts index 4425600..8e1410e 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/addcategorynetworkid.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/addcategorynetworkid.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -25,12 +25,12 @@ export async function dispatchAddCategoryNetworkId ({ action, cache }: { action: AddCategoryNetworkIdAction cache: Cache }) { - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['childId'] }) @@ -38,12 +38,12 @@ export async function dispatchAddCategoryNetworkId ({ action, cache }: { throw new MissingCategoryException() } - const count = await cache.database.categoryNetworkId.count({ + const count = await cache.transaction.legacy.database.categoryNetworkId.count({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (count + 1 > maxNetworkIdsPerCategory) { @@ -52,13 +52,13 @@ export async function dispatchAddCategoryNetworkId ({ action, cache }: { }) } - const hasOldItem = (await cache.database.categoryNetworkId.count({ + const hasOldItem = (await cache.transaction.legacy.database.categoryNetworkId.count({ where: { familyId: cache.familyId, categoryId: action.categoryId, networkItemId: action.itemId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction })) !== 0 if (hasOldItem) { @@ -67,12 +67,12 @@ export async function dispatchAddCategoryNetworkId ({ action, cache }: { }) } - await cache.database.categoryNetworkId.create({ + await cache.transaction.legacy.database.categoryNetworkId.create({ familyId: cache.familyId, categoryId: action.categoryId, networkItemId: action.itemId, hashedNetworkId: action.hashedNetworkId - }, { transaction: cache.transaction }) + }, { transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedBaseData.add(action.categoryId) cache.incrementTriggeredSyncLevel(2) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/addu2fkey.ts b/src/function/sync/apply-actions/dispatch-parent-action/addu2fkey.ts index 0d0a877..9bce987 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/addu2fkey.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/addu2fkey.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -25,16 +25,16 @@ export async function dispatchAddU2f ({ action, cache, parentUserId }: { cache: Cache parentUserId: string }) { - const counter = await cache.database.u2fKey.count({ + const counter = await cache.transaction.legacy.database.u2fKey.count({ where: { familyId: cache.familyId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (counter >= 16) throw new LimitReachedException({ type: 'u2f keys' }) - await cache.database.u2fKey.create({ + await cache.transaction.legacy.database.u2fKey.create({ familyId: cache.familyId, keyId: getU2fKeyId({ keyHandle: action.keyHandle, publicKey: action.publicKey }), userId: parentUserId, @@ -42,7 +42,7 @@ export async function dispatchAddU2f ({ action, cache, parentUserId }: { keyHandle: action.keyHandle, publicKey: action.publicKey, nextCounter: '0' - }, { transaction: cache.transaction }) + }, { transaction: cache.transaction.legacy.transaction }) cache.invalidateU2fList = true cache.incrementTriggeredSyncLevel(1) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/adduser.ts b/src/function/sync/apply-actions/dispatch-parent-action/adduser.ts index 995a3fa..715b258 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/adduser.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/adduser.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -28,7 +28,7 @@ export async function dispatchAddUser ({ action, cache }: { await decryptParentPassword({ cache, password: action.password }) : null - await cache.database.user.create({ + await cache.transaction.legacy.database.user.create({ familyId: cache.familyId, userId: action.userId, type: action.userType, @@ -45,7 +45,7 @@ export async function dispatchAddUser ({ action, cache }: { mailNotificationFlags: 0, blockedTimes: '', flags: '0' - }, { transaction: cache.transaction }) + }, { transaction: cache.transaction.legacy.transaction }) cache.invalidiateUserList = true cache.incrementTriggeredSyncLevel(1) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/changeparentpassword.ts b/src/function/sync/apply-actions/dispatch-parent-action/changeparentpassword.ts index c83f81f..5cd8ede 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/changeparentpassword.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/changeparentpassword.ts @@ -24,13 +24,13 @@ export async function dispatchChangeParentPassword ({ action, cache }: { action: ChangeParentPasswordAction cache: Cache }) { - const parentEntry = await cache.database.user.findOne({ + const parentEntry = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.parentUserId, type: 'parent' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!parentEntry) { @@ -51,7 +51,7 @@ export async function dispatchChangeParentPassword ({ action, cache }: { parentEntry.secondPasswordSalt = action.newPasswordSecondSalt parentEntry.secondPasswordHash = newSecondPasswordHash - await parentEntry.save({ transaction: cache.transaction }) + await parentEntry.save({ transaction: cache.transaction.legacy.transaction }) { const clear = cache.getSecondPasswordHashOfParent.cache.clear diff --git a/src/function/sync/apply-actions/dispatch-parent-action/createcategory.ts b/src/function/sync/apply-actions/dispatch-parent-action/createcategory.ts index 8acf060..ca84ed9 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/createcategory.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/createcategory.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -33,21 +33,21 @@ export async function dispatchCreateCategory ({ action, cache, fromChildSelfLimi } // check that the child exists - const childEntry = await cache.database.user.findOne({ + const childEntry = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.childId, type: 'child' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!childEntry) { throw new MissingUserException() } - const oldMaxSort: number = await cache.database.category.max('sort', { - transaction: cache.transaction, + const oldMaxSort: number = await cache.transaction.legacy.database.category.max('sort', { + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, childId: action.childId @@ -58,7 +58,7 @@ export async function dispatchCreateCategory ({ action, cache, fromChildSelfLimi const sort = Number.isSafeInteger(oldMaxSort + 1) ? (oldMaxSort + 1) : 0 // no version number needs to be updated - await cache.database.category.create({ + await cache.transaction.legacy.database.category.create({ familyId: cache.familyId, categoryId: action.categoryId, childId: action.childId, @@ -82,7 +82,7 @@ export async function dispatchCreateCategory ({ action, cache, fromChildSelfLimi minBatteryMobile: 0, flags: '0', blockNotificationDelay: '0' - }, { transaction: cache.transaction }) + }, { transaction: cache.transaction.legacy.transaction }) // update the cache cache.doesCategoryExist.cache.set(action.categoryId, true) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/createtimelimitrule.ts b/src/function/sync/apply-actions/dispatch-parent-action/createtimelimitrule.ts index 6796b42..2d67a08 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/createtimelimitrule.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/createtimelimitrule.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2024 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -25,12 +25,12 @@ export async function dispatchCreateTimeLimitRule ({ action, cache, fromChildSel cache: Cache fromChildSelfLimitAddChildUserId: string | null }) { - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.rule.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['childId'] }) @@ -44,7 +44,7 @@ export async function dispatchCreateTimeLimitRule ({ action, cache, fromChildSel } } - await cache.database.timelimitRule.create({ + await cache.transaction.legacy.database.timelimitRule.create({ familyId: cache.familyId, ruleId: action.rule.ruleId, categoryId: action.rule.categoryId, @@ -57,7 +57,7 @@ export async function dispatchCreateTimeLimitRule ({ action, cache, fromChildSel sessionPauseMilliseconds: action.rule.sessionPauseMilliseconds, perDay: action.rule.perDay ? 1 : 0, expiresAt: action.rule.expiresAt ? action.rule.expiresAt.toString() : null - }, { transaction: cache.transaction }) + }, { transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedTimeLimitRules.add(action.rule.categoryId) cache.incrementTriggeredSyncLevel(2) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/deletecategory.ts b/src/function/sync/apply-actions/dispatch-parent-action/deletecategory.ts index cafce98..6e9552f 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/deletecategory.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/deletecategory.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,59 +23,59 @@ export async function dispatchDeleteCategory ({ action, cache }: { action: DeleteCategoryAction cache: Cache }) { - const { familyId, transaction } = cache + const { familyId } = cache const { categoryId } = action - const categoryEntry = await cache.database.category.findOne({ + const categoryEntry = await cache.transaction.legacy.database.category.findOne({ where: { familyId, categoryId }, - transaction + transaction: cache.transaction.legacy.transaction }) if (!categoryEntry) { throw new MissingCategoryException() } - await cache.database.timelimitRule.destroy({ + await cache.transaction.legacy.database.timelimitRule.destroy({ where: { familyId, categoryId }, - transaction + transaction: cache.transaction.legacy.transaction }) - await cache.database.usedTime.destroy({ + await cache.transaction.legacy.database.usedTime.destroy({ where: { familyId, categoryId }, - transaction + transaction: cache.transaction.legacy.transaction }) - await cache.database.categoryApp.destroy({ + await cache.transaction.legacy.database.categoryApp.destroy({ where: { familyId, categoryId }, - transaction + transaction: cache.transaction.legacy.transaction }) - const [affectedUserRows] = await cache.database.user.update({ + const [affectedUserRows] = await cache.transaction.legacy.database.user.update({ categoryForNotAssignedApps: '' }, { where: { familyId, categoryForNotAssignedApps: categoryId }, - transaction + transaction: cache.transaction.legacy.transaction }) - await cache.database.category.destroy({ + await cache.transaction.legacy.database.category.destroy({ where: { familyId, categoryId }, - transaction + transaction: cache.transaction.legacy.transaction }) // update the cache diff --git a/src/function/sync/apply-actions/dispatch-parent-action/deletechildtaskaction.ts b/src/function/sync/apply-actions/dispatch-parent-action/deletechildtaskaction.ts index f8f5077..63fa072 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/deletechildtaskaction.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/deletechildtaskaction.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,12 +23,12 @@ export async function dispatchDeleteChildTaskAction ({ action, cache }: { action: DeleteChildTaskAction cache: Cache }) { - const taskInfoUnsafe = await cache.database.childTask.findOne({ + const taskInfoUnsafe = await cache.transaction.legacy.database.childTask.findOne({ where: { familyId: cache.familyId, taskId: action.taskId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['categoryId'] }) @@ -36,12 +36,12 @@ export async function dispatchDeleteChildTaskAction ({ action, cache }: { const taskInfo = { categoryId: taskInfoUnsafe.categoryId } - await cache.database.childTask.destroy({ + await cache.transaction.legacy.database.childTask.destroy({ where: { familyId: cache.familyId, taskId: action.taskId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedTasks.add(taskInfo.categoryId) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/deletetimelimitrule.ts b/src/function/sync/apply-actions/dispatch-parent-action/deletetimelimitrule.ts index 9419b4a..1c29a40 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/deletetimelimitrule.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/deletetimelimitrule.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,19 +23,19 @@ export async function dispatchDeleteTimeLimitRule ({ action, cache }: { action: DeleteTimeLimitRuleAction cache: Cache }) { - const ruleEntry = await cache.database.timelimitRule.findOne({ + const ruleEntry = await cache.transaction.legacy.database.timelimitRule.findOne({ where: { familyId: cache.familyId, ruleId: action.ruleId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!ruleEntry) { throw new MissingRuleException() } - await ruleEntry.destroy({ transaction: cache.transaction }) + await ruleEntry.destroy({ transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedTimeLimitRules.add(ruleEntry.categoryId) cache.incrementTriggeredSyncLevel(2) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/ignoremanipulation.ts b/src/function/sync/apply-actions/dispatch-parent-action/ignoremanipulation.ts index e592bca..ff9c5d7 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/ignoremanipulation.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/ignoremanipulation.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,12 +23,12 @@ export async function dispatchIgnoreManipulation ({ action, cache }: { action: IgnoreManipulationAction cache: Cache }) { - const deviceEntry = await cache.database.device.findOne({ + const deviceEntry = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId: action.deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (deviceEntry === null) { @@ -85,7 +85,7 @@ export async function dispatchIgnoreManipulation ({ action, cache }: { deviceEntry.manipulationFlags = deviceEntry.manipulationFlags & (~action.ignoreManipulationFlags) } - await deviceEntry.save({ transaction: cache.transaction }) + await deviceEntry.save({ transaction: cache.transaction.legacy.transaction }) cache.invalidiateDeviceList = true cache.incrementTriggeredSyncLevel(1) cache.incrementTargetedTriggeredSyncLevel(action.deviceId, 2) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/incrementcategoryextratime.ts b/src/function/sync/apply-actions/dispatch-parent-action/incrementcategoryextratime.ts index 359260e..f44f6ba 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/incrementcategoryextratime.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/incrementcategoryextratime.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -38,18 +38,18 @@ export async function dispatchIncrementCategoryExtraTime ({ action, cache }: { category.extraTimeDay = action.day - await category.save({ transaction: cache.transaction }) + await category.save({ transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedBaseData.add(category.categoryId) cache.incrementTriggeredSyncLevel(2) } - const categoryEntry = await cache.database.category.findOne({ + const categoryEntry = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!categoryEntry) { @@ -59,12 +59,12 @@ export async function dispatchIncrementCategoryExtraTime ({ action, cache }: { await handleCategory(categoryEntry) if (categoryEntry.parentCategoryId !== '') { - const parentCategoryEntry = await cache.database.category.findOne({ + const parentCategoryEntry = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: categoryEntry.parentCategoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (parentCategoryEntry) { diff --git a/src/function/sync/apply-actions/dispatch-parent-action/removecategoryapps.ts b/src/function/sync/apply-actions/dispatch-parent-action/removecategoryapps.ts index 91d2d4f..b5c0f49 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/removecategoryapps.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/removecategoryapps.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -24,7 +24,7 @@ export async function dispatchRemoveCategoryApps ({ action, cache }: { action: RemoveCategoryAppsAction cache: Cache }) { - const affectedRows = await cache.database.categoryApp.destroy({ + const affectedRows = await cache.transaction.legacy.database.categoryApp.destroy({ where: { familyId: cache.familyId, categoryId: action.categoryId, @@ -32,7 +32,7 @@ export async function dispatchRemoveCategoryApps ({ action, cache }: { [Sequelize.Op.in]: action.packageNames } }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (affectedRows !== action.packageNames.length) { diff --git a/src/function/sync/apply-actions/dispatch-parent-action/removeu2fkey.ts b/src/function/sync/apply-actions/dispatch-parent-action/removeu2fkey.ts index 964090d..5660797 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/removeu2fkey.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/removeu2fkey.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -31,7 +31,7 @@ export async function dispatchRemoveU2f ({ action, cache, parentUserId, authenti throw new ApplyActionUnacceptableAuthMethodException() } - await cache.database.u2fKey.destroy({ + await cache.transaction.legacy.database.u2fKey.destroy({ where: { familyId: cache.familyId, keyId: getU2fKeyId({ keyHandle: action.keyHandle, publicKey: action.publicKey }), @@ -39,7 +39,7 @@ export async function dispatchRemoveU2f ({ action, cache, parentUserId, authenti keyHandle: action.keyHandle, publicKey: action.publicKey }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.invalidateU2fList = true diff --git a/src/function/sync/apply-actions/dispatch-parent-action/removeuser.ts b/src/function/sync/apply-actions/dispatch-parent-action/removeuser.ts index 1e09eb5..feffb3f 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/removeuser.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/removeuser.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -30,12 +30,12 @@ export async function dispatchRemoveUser ({ action, cache, parentUserId }: { cache: Cache parentUserId: string }) { - const user = await cache.database.user.findOne({ + const user = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.userId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!user) { @@ -60,8 +60,8 @@ export async function dispatchRemoveUser ({ action, cache, parentUserId }: { } if (user.mail !== '') { - const usersWithLinkedMail = await cache.database.user.count({ - transaction: cache.transaction, + const usersWithLinkedMail = await cache.transaction.legacy.database.user.count({ + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, type: 'parent', @@ -76,16 +76,16 @@ export async function dispatchRemoveUser ({ action, cache, parentUserId }: { } } - const usersWithLimitLoginCategories = (await cache.database.userLimitLoginCategory.findAll({ - transaction: cache.transaction, + const usersWithLimitLoginCategories = (await cache.transaction.legacy.database.userLimitLoginCategory.findAll({ + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId }, attributes: ['userId'] })).map((item) => item.userId) - const allParentUserIds = (await cache.database.user.findAll({ - transaction: cache.transaction, + const allParentUserIds = (await cache.transaction.legacy.database.user.findAll({ + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, type: 'parent' @@ -101,56 +101,56 @@ export async function dispatchRemoveUser ({ action, cache, parentUserId }: { } if (user.type === 'child') { - const categories = await cache.database.category.findAll({ + const categories = await cache.transaction.legacy.database.category.findAll({ where: { familyId: cache.familyId, childId: action.userId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) - await cache.database.categoryApp.destroy({ + await cache.transaction.legacy.database.categoryApp.destroy({ where: { familyId: cache.familyId, categoryId: { [Sequelize.Op.in]: categories.map((category) => category.categoryId) } }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) - await cache.database.timelimitRule.destroy({ + await cache.transaction.legacy.database.timelimitRule.destroy({ where: { familyId: cache.familyId, categoryId: { [Sequelize.Op.in]: categories.map((category) => category.categoryId) } }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) - await cache.database.usedTime.destroy({ + await cache.transaction.legacy.database.usedTime.destroy({ where: { familyId: cache.familyId, categoryId: { [Sequelize.Op.in]: categories.map((category) => category.categoryId) } }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) - await cache.database.category.destroy({ + await cache.transaction.legacy.database.category.destroy({ where: { familyId: cache.familyId, categoryId: { [Sequelize.Op.in]: categories.map((category) => category.categoryId) } }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) } - const [updatedDevices1] = await cache.database.device.update({ + const [updatedDevices1] = await cache.transaction.legacy.database.device.update({ currentUserId: '', isUserKeptSignedIn: false }, { @@ -158,24 +158,24 @@ export async function dispatchRemoveUser ({ action, cache, parentUserId }: { familyId: cache.familyId, currentUserId: action.userId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) - const [updatedDevices2] = await cache.database.device.update({ + const [updatedDevices2] = await cache.transaction.legacy.database.device.update({ defaultUserId: '' }, { where: { familyId: cache.familyId, defaultUserId: action.userId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (updatedDevices1 > 0 || updatedDevices2 > 0) { cache.invalidiateDeviceList = true } - await user.destroy({ transaction: cache.transaction }) + await user.destroy({ transaction: cache.transaction.legacy.transaction }) cache.invalidiateUserList = true cache.incrementTriggeredSyncLevel(2) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/renamechild.ts b/src/function/sync/apply-actions/dispatch-parent-action/renamechild.ts index 95689b7..f47b64a 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/renamechild.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/renamechild.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,20 +23,20 @@ export async function dispatchRenameChild ({ action, cache }: { action: RenameChildAction cache: Cache }) { - const oldItem = await cache.database.user.findOne({ + const oldItem = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.childId, type: 'child' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!oldItem) { throw new MissingUserException() } - await cache.database.user.update({ + await cache.transaction.legacy.database.user.update({ name: action.newName }, { where: { @@ -44,7 +44,7 @@ export async function dispatchRenameChild ({ action, cache }: { userId: action.childId, type: 'child' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.invalidiateUserList = true diff --git a/src/function/sync/apply-actions/dispatch-parent-action/resetcategorynetworkids.ts b/src/function/sync/apply-actions/dispatch-parent-action/resetcategorynetworkids.ts index aeaf013..79cf77a 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/resetcategorynetworkids.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/resetcategorynetworkids.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,12 +23,12 @@ export async function dispatchResetCategoryNetworkIds ({ action, cache }: { action: ResetCategoryNetworkIdsAction cache: Cache }) { - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['childId'] }) @@ -36,12 +36,12 @@ export async function dispatchResetCategoryNetworkIds ({ action, cache }: { throw new MissingCategoryException() } - await cache.database.categoryNetworkId.destroy({ + await cache.transaction.legacy.database.categoryNetworkId.destroy({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedBaseData.add(action.categoryId) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/reviewchildtaskaction.ts b/src/function/sync/apply-actions/dispatch-parent-action/reviewchildtaskaction.ts index 0b6adf3..992cd52 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/reviewchildtaskaction.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/reviewchildtaskaction.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -29,12 +29,12 @@ export async function dispatchReviewChildTaskAction ({ action, cache }: { throw new PremiumVersionMissingException() } - const taskInfo = await cache.database.childTask.findOne({ + const taskInfo = await cache.transaction.legacy.database.childTask.findOne({ where: { familyId: cache.familyId, taskId: action.taskId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (taskInfo === null) throw new MissingTaskException() @@ -42,13 +42,13 @@ export async function dispatchReviewChildTaskAction ({ action, cache }: { if (taskInfo.pendingRequest === 0) throw new IllegalStateException({ staticMessage: 'no task review pending' }) if (action.ok) { - const categoryInfoUnsafe = await cache.database.category.findOne({ + const categoryInfoUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: taskInfo.categoryId }, attributes: ['extraTimeInMillis', 'extraTimeDay'], - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (categoryInfoUnsafe === null) { @@ -64,7 +64,7 @@ export async function dispatchReviewChildTaskAction ({ action, cache }: { action.day !== undefined && categoryInfo.extraTimeDay !== action.day if (resetDayBoundExtraTime) { - await cache.database.category.update({ + await cache.transaction.legacy.database.category.update({ extraTimeInMillis: taskInfo.extraTimeDuration, extraTimeDay: -1 }, { @@ -72,23 +72,23 @@ export async function dispatchReviewChildTaskAction ({ action, cache }: { familyId: cache.familyId, categoryId: taskInfo.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) } else { - await cache.database.category.update({ + await cache.transaction.legacy.database.category.update({ extraTimeInMillis: categoryInfo.extraTimeInMillis + taskInfo.extraTimeDuration }, { where: { familyId: cache.familyId, categoryId: taskInfo.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) } cache.categoriesWithModifiedBaseData.add(taskInfo.categoryId) - await cache.database.childTask.update({ + await cache.transaction.legacy.database.childTask.update({ pendingRequest: 0, lastGrantTimestamp: action.time.toString(10) }, { @@ -96,19 +96,19 @@ export async function dispatchReviewChildTaskAction ({ action, cache }: { familyId: cache.familyId, taskId: action.taskId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.incrementTriggeredSyncLevel(2) } else { - await cache.database.childTask.update({ + await cache.transaction.legacy.database.childTask.update({ pendingRequest: 0 }, { where: { familyId: cache.familyId, taskId: action.taskId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) } diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setcategoryextratime.ts b/src/function/sync/apply-actions/dispatch-parent-action/setcategoryextratime.ts index 6905588..0d19a8e 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setcategoryextratime.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setcategoryextratime.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -28,19 +28,19 @@ export async function dispatchSetCategoryExtraTime ({ action, cache }: { throw new PremiumVersionMissingException() } - const oldItem = await cache.database.category.findOne({ + const oldItem = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!oldItem) { throw new MissingCategoryException() } - await cache.database.category.update({ + await cache.transaction.legacy.database.category.update({ extraTimeInMillis: action.newExtraTime, extraTimeDay: action.day }, { @@ -48,7 +48,7 @@ export async function dispatchSetCategoryExtraTime ({ action, cache }: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedBaseData.add(action.categoryId) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setcategoryforunassignedapps.ts b/src/function/sync/apply-actions/dispatch-parent-action/setcategoryforunassignedapps.ts index 21afdbf..3a8b775 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setcategoryforunassignedapps.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setcategoryforunassignedapps.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -24,13 +24,13 @@ export async function dispatchSetCategoryForUnassignedApps ({ action, cache }: { action: SetCategoryForUnassignedAppsAction cache: Cache }) { - const oldUserEntry = await cache.database.user.findOne({ + const oldUserEntry = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.childId, type: 'child' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!oldUserEntry) { @@ -40,13 +40,13 @@ export async function dispatchSetCategoryForUnassignedApps ({ action, cache }: { if (action.categoryId === '') { // nothing to check } else { - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ attributes: ['childId'], where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!categoryEntryUnsafe) { @@ -66,7 +66,7 @@ export async function dispatchSetCategoryForUnassignedApps ({ action, cache }: { } } - await cache.database.user.update({ + await cache.transaction.legacy.database.user.update({ categoryForNotAssignedApps: action.categoryId }, { where: { @@ -74,7 +74,7 @@ export async function dispatchSetCategoryForUnassignedApps ({ action, cache }: { userId: action.childId, type: 'child' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.invalidiateUserList = true diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setchildpassword.ts b/src/function/sync/apply-actions/dispatch-parent-action/setchildpassword.ts index b5b520c..f8fb7dc 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setchildpassword.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setchildpassword.ts @@ -24,13 +24,13 @@ export async function dispatchSetChildPassword ({ action, cache }: { action: SetChildPasswordAction cache: Cache }) { - const childEntry = await cache.database.user.findOne({ + const childEntry = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.childUserId, type: 'child' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!childEntry) { @@ -43,7 +43,7 @@ export async function dispatchSetChildPassword ({ action, cache }: { childEntry.secondPasswordSalt = newPassword.secondSalt childEntry.secondPasswordHash = newPassword.secondHash - await childEntry.save({ transaction: cache.transaction }) + await childEntry.save({ transaction: cache.transaction.legacy.transaction }) { const clear = cache.getSecondPasswordHashOfChild.cache.clear diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setconsiderrebootmanipulation.ts b/src/function/sync/apply-actions/dispatch-parent-action/setconsiderrebootmanipulation.ts index 19b4ae7..da16887 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setconsiderrebootmanipulation.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setconsiderrebootmanipulation.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,8 +23,8 @@ export async function dispatchSetConsiderRebootManipulation ({ action, cache }: action: SetConsiderRebootManipulationAction cache: Cache }) { - const oldDevice = await cache.database.device.findOne({ - transaction: cache.transaction, + const oldDevice = await cache.transaction.legacy.database.device.findOne({ + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, deviceId: action.deviceId @@ -35,10 +35,10 @@ export async function dispatchSetConsiderRebootManipulation ({ action, cache }: throw new MissingDeviceException() } - await cache.database.device.update({ + await cache.transaction.legacy.database.device.update({ considerRebootManipulation: action.enable }, { - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, deviceId: action.deviceId diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setdevicedefaultuser.ts b/src/function/sync/apply-actions/dispatch-parent-action/setdevicedefaultuser.ts index e1478bb..7452619 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setdevicedefaultuser.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setdevicedefaultuser.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -31,8 +31,8 @@ export async function dispatchSetDeviceDefaultUser ({ action, cache }: { } } - const oldDeviceItem = await cache.database.device.findOne({ - transaction: cache.transaction, + const oldDeviceItem = await cache.transaction.legacy.database.device.findOne({ + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, deviceId: action.deviceId @@ -43,10 +43,10 @@ export async function dispatchSetDeviceDefaultUser ({ action, cache }: { throw new MissingDeviceException() } - await cache.database.device.update({ + await cache.transaction.legacy.database.device.update({ defaultUserId: action.defaultUserId }, { - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, deviceId: action.deviceId diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setdevicedefaultusertimeout.ts b/src/function/sync/apply-actions/dispatch-parent-action/setdevicedefaultusertimeout.ts index d7c43f3..ae6346c 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setdevicedefaultusertimeout.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setdevicedefaultusertimeout.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,8 +23,8 @@ export async function dispatchSetDeviceDefaultUserTimeout ({ action, cache }: { action: SetDeviceDefaultUserTimeoutAction cache: Cache }) { - const oldDeviceItem = await cache.database.device.findOne({ - transaction: cache.transaction, + const oldDeviceItem = await cache.transaction.legacy.database.device.findOne({ + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, deviceId: action.deviceId @@ -35,10 +35,10 @@ export async function dispatchSetDeviceDefaultUserTimeout ({ action, cache }: { throw new MissingDeviceException() } - await cache.database.device.update({ + await cache.transaction.legacy.database.device.update({ defaultUserTimeout: action.timeout }, { - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, deviceId: action.deviceId diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setdeviceuser.ts b/src/function/sync/apply-actions/dispatch-parent-action/setdeviceuser.ts index e365efd..b839345 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setdeviceuser.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setdeviceuser.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -31,19 +31,19 @@ export async function dispatchSetDeviceUser ({ action, cache }: { } } - const oldDeviceItem = await cache.database.device.findOne({ + const oldDeviceItem = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId: action.deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!oldDeviceItem) { throw new MissingDeviceException() } - await cache.database.device.update({ + await cache.transaction.legacy.database.device.update({ currentUserId: action.userId, isUserKeptSignedIn: false }, { @@ -51,7 +51,7 @@ export async function dispatchSetDeviceUser ({ action, cache }: { familyId: cache.familyId, deviceId: action.deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.invalidiateDeviceList = true diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setkeepsignedin.ts b/src/function/sync/apply-actions/dispatch-parent-action/setkeepsignedin.ts index 319b01a..bb032fc 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setkeepsignedin.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setkeepsignedin.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -32,12 +32,12 @@ export async function dispatchSetKeepSignedIn ({ action, cache, parentUserId }: throw new SourceUserNotFoundException() } - const deviceEntry = await cache.database.device.findOne({ + const deviceEntry = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId: action.deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!deviceEntry) { @@ -50,7 +50,7 @@ export async function dispatchSetKeepSignedIn ({ action, cache, parentUserId }: } } - const [affectedRows] = await cache.database.device.update({ + const [affectedRows] = await cache.transaction.legacy.database.device.update({ isUserKeptSignedIn: action.keepSignedIn }, { where: { @@ -58,7 +58,7 @@ export async function dispatchSetKeepSignedIn ({ action, cache, parentUserId }: deviceId: action.deviceId, currentUserId: deviceEntry.currentUserId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (affectedRows !== 0) { diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setparentcategory.ts b/src/function/sync/apply-actions/dispatch-parent-action/setparentcategory.ts index 1f5e345..7c8fe0c 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setparentcategory.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setparentcategory.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -27,12 +27,12 @@ export async function dispatchSetParentCategory ({ action, cache, fromChildSelfL cache: Cache fromChildSelfLimitAddChildUserId: string | null }) { - const categoryEntry = await cache.database.category.findOne({ + const categoryEntry = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!categoryEntry) { @@ -46,13 +46,13 @@ export async function dispatchSetParentCategory ({ action, cache, fromChildSelfL } if (action.parentCategory !== '') { - const categoriesByUserId = (await cache.database.category.findAll({ + const categoriesByUserId = (await cache.transaction.legacy.database.category.findAll({ where: { familyId: cache.familyId, childId: categoryEntry.childId }, attributes: ['categoryId', 'parentCategoryId'], - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction })).map((item) => ({ categoryId: item.categoryId, parentCategoryId: item.parentCategoryId @@ -107,14 +107,14 @@ export async function dispatchSetParentCategory ({ action, cache, fromChildSelfL } } - await cache.database.category.update({ + await cache.transaction.legacy.database.category.update({ parentCategoryId: action.parentCategory }, { where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedBaseData.add(action.categoryId) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setrelaxprimarydevice.ts b/src/function/sync/apply-actions/dispatch-parent-action/setrelaxprimarydevice.ts index 34b462e..4c197f8 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setrelaxprimarydevice.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setrelaxprimarydevice.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,8 +23,8 @@ export async function dispatchSetRelaxPrimaryDevice ({ action, cache }: { action: SetRelaxPrimaryDeviceAction cache: Cache }) { - const oldUser = cache.database.user.findOne({ - transaction: cache.transaction, + const oldUser = cache.transaction.legacy.database.user.findOne({ + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, userId: action.userId, @@ -36,10 +36,10 @@ export async function dispatchSetRelaxPrimaryDevice ({ action, cache }: { throw new MissingUserException() } - await cache.database.user.update({ + await cache.transaction.legacy.database.user.update({ relaxPrimaryDeviceRule: action.relax }, { - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, userId: action.userId, diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setsenddeviceconnected.ts b/src/function/sync/apply-actions/dispatch-parent-action/setsenddeviceconnected.ts index 9bb7aa7..519c579 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setsenddeviceconnected.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setsenddeviceconnected.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -30,10 +30,10 @@ export async function dispatchSetSendDeviceConnected ({ action, cache, sourceDev }) } - await cache.database.device.update({ + await cache.transaction.legacy.database.device.update({ showDeviceConnected: action.enable }, { - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, deviceId: action.deviceId diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setuserdisablelmitsuntil.ts b/src/function/sync/apply-actions/dispatch-parent-action/setuserdisablelmitsuntil.ts index ede6514..a4270b7 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setuserdisablelmitsuntil.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setuserdisablelmitsuntil.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -30,20 +30,20 @@ export async function dispatchUserSetDisableLimitsUntil ({ action, cache }: { } } - const oldUser = await cache.database.user.findOne({ + const oldUser = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.childId, type: 'child' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!oldUser) { throw new MissingUserException() } - await cache.database.user.update({ + await cache.transaction.legacy.database.user.update({ disableTimelimitsUntil: action.timestamp.toString(10) }, { where: { @@ -51,7 +51,7 @@ export async function dispatchUserSetDisableLimitsUntil ({ action, cache }: { userId: action.childId, type: 'child' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.invalidiateUserList = true diff --git a/src/function/sync/apply-actions/dispatch-parent-action/setusertimezone.ts b/src/function/sync/apply-actions/dispatch-parent-action/setusertimezone.ts index c68787f..e49c1f5 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/setusertimezone.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/setusertimezone.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,22 +23,22 @@ export async function dispatchSetUserTimezone ({ action, cache }: { action: SetUserTimezoneAction cache: Cache }) { - const oldUser = await cache.database.user.findOne({ + const oldUser = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.userId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!oldUser) { throw new MissingUserException() } - await cache.database.user.update({ + await cache.transaction.legacy.database.user.update({ timeZone: action.timezone }, { - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, userId: action.userId diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorybatterylimit.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorybatterylimit.ts index 24abf1c..0bb3ff1 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorybatterylimit.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorybatterylimit.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,12 +23,12 @@ export async function dispatchUpdateCategoryBatteryLimit ({ action, cache }: { action: UpdateCategoryBatteryLimitAction cache: Cache }) { - const categoryEntry = await cache.database.category.findOne({ + const categoryEntry = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!categoryEntry) { @@ -43,7 +43,7 @@ export async function dispatchUpdateCategoryBatteryLimit ({ action, cache }: { categoryEntry.minBatteryMobile = action.mobileLimit } - await categoryEntry.save({ transaction: cache.transaction }) + await categoryEntry.save({ transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedBaseData.add(action.categoryId) cache.incrementTriggeredSyncLevel(2) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryblockallnotifications.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryblockallnotifications.ts index 4554a62..3d5b33e 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryblockallnotifications.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryblockallnotifications.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -25,12 +25,12 @@ export async function dispatchUpdateCategoryBlockAllNotifications ({ action, cac cache: Cache fromChildSelfLimitAddChildUserId: string | null }) { - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['childId', 'blockAllNotifications'] }) @@ -57,7 +57,7 @@ export async function dispatchUpdateCategoryBlockAllNotifications ({ action, cac } } - const [affectedRows] = await cache.database.category.update(action.blockDelay === undefined ? { + const [affectedRows] = await cache.transaction.legacy.database.category.update(action.blockDelay === undefined ? { blockAllNotifications: action.blocked } : { blockAllNotifications: action.blocked, @@ -67,7 +67,7 @@ export async function dispatchUpdateCategoryBlockAllNotifications ({ action, cac familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (affectedRows !== 0) { diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryblockedtimes.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryblockedtimes.ts index c51a7a4..e886f5a 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryblockedtimes.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryblockedtimes.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -26,12 +26,12 @@ export async function dispatchUpdateCategoryBlockedTimes ({ action, cache, fromC cache: Cache fromChildSelfLimitAddChildUserId: string | null }) { - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['childId', 'blockedMinutesInWeek'] }) @@ -59,14 +59,14 @@ export async function dispatchUpdateCategoryBlockedTimes ({ action, cache, fromC }) } - await cache.database.category.update({ + await cache.transaction.legacy.database.category.update({ blockedMinutesInWeek: action.blockedTimes }, { where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedBaseData.add(action.categoryId) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorydisablelimits.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorydisablelimits.ts index b7f917a..c434a7f 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorydisablelimits.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorydisablelimits.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -36,12 +36,12 @@ export async function dispatchUpdateCategoryDisableLimits ({ action, cache, from } } - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['childId'] }) @@ -59,14 +59,14 @@ export async function dispatchUpdateCategoryDisableLimits ({ action, cache, from } } - const [affectedRows] = await cache.database.category.update({ + const [affectedRows] = await cache.transaction.legacy.database.category.update({ disableLimitsUntil: action.endTime.toString(10) }, { where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (affectedRows !== 0) { diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryflags.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryflags.ts index fb2a456..975b4bb 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryflags.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatecategoryflags.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -24,12 +24,12 @@ export async function dispatchUpdateCategoryFlagsAction ({ action, cache }: { action: UpdateCategoryFlagsAction cache: Cache }) { - const categoryEntry = await cache.database.category.findOne({ + const categoryEntry = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!categoryEntry) { @@ -46,7 +46,7 @@ export async function dispatchUpdateCategoryFlagsAction ({ action, cache }: { categoryEntry.flags = newFlags.toString(10) - await categoryEntry.save({ transaction: cache.transaction }) + await categoryEntry.save({ transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedBaseData.add(action.categoryId) cache.incrementTriggeredSyncLevel(2) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorysorting.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorysorting.ts index 2b5369c..5e5a2b8 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorysorting.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorysorting.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -30,10 +30,10 @@ export async function dispatchUpdateCategorySorting ({ action, cache }: { for (let i = 0; i < action.categoryIds.length; i++) { const categoryId = action.categoryIds[i] - await cache.database.category.update({ + await cache.transaction.legacy.database.category.update({ sort: i }, { - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, categoryId diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytemporarilyblocked.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytemporarilyblocked.ts index 9672cfb..cb8d523 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytemporarilyblocked.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytemporarilyblocked.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -32,12 +32,12 @@ export async function dispatchUpdateCategoryTemporarilyBlocked ({ action, cache, } } - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['childId', 'temporarilyBlocked', 'temporarilyBlockedEndTime'] }) @@ -67,7 +67,7 @@ export async function dispatchUpdateCategoryTemporarilyBlocked ({ action, cache, } } - const [affectedRows] = await cache.database.category.update({ + const [affectedRows] = await cache.transaction.legacy.database.category.update({ temporarilyBlocked: action.blocked, temporarilyBlockedEndTime: action.blocked ? (action.endTime ?? 0).toString(10) : '0' }, { @@ -75,7 +75,7 @@ export async function dispatchUpdateCategoryTemporarilyBlocked ({ action, cache, familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (affectedRows !== 0) { diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytimewarnings.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytimewarnings.ts index 1c936e7..08a1439 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytimewarnings.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytimewarnings.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,12 +23,12 @@ export async function dispatchUpdateCategoryTimeWarnings ({ action, cache }: { action: UpdateCategoryTimeWarningsAction cache: Cache }) { - const categoryEntry = await cache.database.category.findOne({ + const categoryEntry = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!categoryEntry) { @@ -41,26 +41,26 @@ export async function dispatchUpdateCategoryTimeWarnings ({ action, cache }: { categoryEntry.timeWarningFlags &= ~action.flags } - await categoryEntry.save({ transaction: cache.transaction }) + await categoryEntry.save({ transaction: cache.transaction.legacy.transaction }) if (action.minutes !== undefined) { if (action.enable) { - await cache.database.categoryTimeWarning.create({ + await cache.transaction.legacy.database.categoryTimeWarning.create({ familyId: cache.familyId, categoryId: action.categoryId, minutes: action.minutes }, { - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, ignoreDuplicates: true }) } else { - await cache.database.categoryTimeWarning.destroy({ + await cache.transaction.legacy.database.categoryTimeWarning.destroy({ where: { familyId: cache.familyId, categoryId: action.categoryId, minutes: action.minutes }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) } } diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytitle.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytitle.ts index d1e42d0..9bcb0ae 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytitle.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatecategorytitle.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,26 +23,26 @@ export async function dispatchUpdateCategoryTitle ({ action, cache }: { action: UpdateCategoryTitleAction cache: Cache }) { - const oldCategory = await cache.database.category.findOne({ + const oldCategory = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!oldCategory) { throw new MissingCategoryException() } - const [affectedRows] = await cache.database.category.update({ + const [affectedRows] = await cache.transaction.legacy.database.category.update({ title: action.newTitle }, { where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (affectedRows !== 0) { diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatechildtaskaction.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatechildtaskaction.ts index f416140..9ca3629 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatechildtaskaction.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatechildtaskaction.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -24,23 +24,23 @@ export async function dispatchUpdateChildTaskAction ({ action, cache }: { action: UpdateChildTaskAction cache: Cache }) { - const categoryInfoUnsafe = await cache.database.category.findOne({ + const categoryInfoUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, attributes: ['childId'], - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (categoryInfoUnsafe === null) throw new MissingCategoryException() - const taskInfo = await cache.database.childTask.findOne({ + const taskInfo = await cache.transaction.legacy.database.childTask.findOne({ where: { familyId: cache.familyId, taskId: action.taskId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) const notFound = taskInfo === null @@ -56,7 +56,7 @@ export async function dispatchUpdateChildTaskAction ({ action, cache }: { } if (taskInfo === null) { - await cache.database.childTask.create({ + await cache.transaction.legacy.database.childTask.create({ familyId: cache.familyId, taskId: action.taskId, categoryId: action.categoryId, @@ -65,12 +65,12 @@ export async function dispatchUpdateChildTaskAction ({ action, cache }: { pendingRequest: 0, lastGrantTimestamp: '0' }, { - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedTasks.add(action.categoryId) } else { - await cache.database.childTask.update({ + await cache.transaction.legacy.database.childTask.update({ taskTitle: action.taskTitle, categoryId: action.categoryId, extraTimeDuration: action.extraTimeDuration @@ -79,7 +79,7 @@ export async function dispatchUpdateChildTaskAction ({ action, cache }: { familyId: cache.familyId, taskId: action.taskId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedTasks.add(taskInfo.categoryId) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatedevicename.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatedevicename.ts index bd607f1..e9e487f 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatedevicename.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatedevicename.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,26 +23,26 @@ export async function dispatchUpdateDeviceName ({ action, cache }: { action: UpdateDeviceNameAction cache: Cache }) { - const oldDevice = await cache.database.device.findOne({ + const oldDevice = await cache.transaction.legacy.database.device.findOne({ where: { familyId: cache.familyId, deviceId: action.deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!oldDevice) { throw new MissingDeviceException() } - const [affectedRows] = await cache.database.device.update({ + const [affectedRows] = await cache.transaction.legacy.database.device.update({ name: action.name }, { where: { familyId: cache.familyId, deviceId: action.deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (affectedRows !== 0) { diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updateenableactivitylevelblocking.ts b/src/function/sync/apply-actions/dispatch-parent-action/updateenableactivitylevelblocking.ts index 7f451cc..f184222 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updateenableactivitylevelblocking.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updateenableactivitylevelblocking.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,8 +23,8 @@ export async function dispatchUpdateEnableActivityLevelBlocking ({ action, cache action: UpdateEnableActivityLevelBlockingAction cache: Cache }) { - const oldDevice = await cache.database.device.findOne({ - transaction: cache.transaction, + const oldDevice = await cache.transaction.legacy.database.device.findOne({ + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, deviceId: action.deviceId @@ -35,10 +35,10 @@ export async function dispatchUpdateEnableActivityLevelBlocking ({ action, cache throw new MissingDeviceException() } - await cache.database.device.update({ + await cache.transaction.legacy.database.device.update({ activityLevelBlocking: action.enable }, { - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, deviceId: action.deviceId diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatenetworktimeverification.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatenetworktimeverification.ts index 73f558c..fe7e159 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatenetworktimeverification.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatenetworktimeverification.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,8 +23,8 @@ export async function dispatchUpdateNetworkTimeVerification ({ action, cache }: action: UpdateNetworkTimeVerificationAction cache: Cache }) { - const oldDevice = await cache.database.device.findOne({ - transaction: cache.transaction, + const oldDevice = await cache.transaction.legacy.database.device.findOne({ + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, deviceId: action.deviceId @@ -35,14 +35,14 @@ export async function dispatchUpdateNetworkTimeVerification ({ action, cache }: throw new MissingDeviceException() } - await cache.database.device.update({ + await cache.transaction.legacy.database.device.update({ networkTime: action.mode }, { where: { familyId: cache.familyId, deviceId: action.deviceId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) cache.invalidiateDeviceList = true diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updateparentnotificationflags.ts b/src/function/sync/apply-actions/dispatch-parent-action/updateparentnotificationflags.ts index 90ff047..a5acc3e 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updateparentnotificationflags.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updateparentnotificationflags.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -23,13 +23,13 @@ export async function dispatchUpdateParentNotificationFlags ({ action, cache }: action: UpdateParentNotificationFlagsAction cache: Cache }) { - const parentEntry = await cache.database.user.findOne({ + const parentEntry = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.parentId, type: 'parent' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!parentEntry) { @@ -42,7 +42,7 @@ export async function dispatchUpdateParentNotificationFlags ({ action, cache }: parentEntry.mailNotificationFlags &= ~action.flags } - await parentEntry.save({ transaction: cache.transaction }) + await parentEntry.save({ transaction: cache.transaction.legacy.transaction }) cache.invalidiateUserList = true cache.incrementTriggeredSyncLevel(1) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updatetimelimitrule.ts b/src/function/sync/apply-actions/dispatch-parent-action/updatetimelimitrule.ts index 8a57d71..33896f7 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updatetimelimitrule.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updatetimelimitrule.ts @@ -29,12 +29,12 @@ export async function dispatchUpdateTimelimitRule ({ cache: Cache fromChildSelfLimitAddChildUserId: string | null }) { - const ruleEntry = await cache.database.timelimitRule.findOne({ + const ruleEntry = await cache.transaction.legacy.database.timelimitRule.findOne({ where: { familyId: cache.familyId, ruleId: action.ruleId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!ruleEntry) { @@ -42,12 +42,12 @@ export async function dispatchUpdateTimelimitRule ({ } if (fromChildSelfLimitAddChildUserId != null) { - const categoryEntryUnsafe = await cache.database.category.findOne({ + const categoryEntryUnsafe = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: ruleEntry.categoryId }, - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, attributes: ['childId'] }) @@ -103,7 +103,7 @@ export async function dispatchUpdateTimelimitRule ({ ruleEntry.perDay = action.perDay ? 1 : 0 ruleEntry.expiresAt = action.expiresAt ? action.expiresAt.toString() : null - await ruleEntry.save({ transaction: cache.transaction }) + await ruleEntry.save({ transaction: cache.transaction.legacy.transaction }) cache.categoriesWithModifiedTimeLimitRules.add(ruleEntry.categoryId) cache.incrementTriggeredSyncLevel(2) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updateuserflags.ts b/src/function/sync/apply-actions/dispatch-parent-action/updateuserflags.ts index c8127ec..b73bddd 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updateuserflags.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updateuserflags.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -24,12 +24,12 @@ export async function dispatchUpdateUserFlagsAction ({ action, cache }: { action: UpdateUserFlagsAction cache: Cache }) { - const userEntry = await cache.database.user.findOne({ + const userEntry = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.userId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!userEntry) { @@ -46,7 +46,7 @@ export async function dispatchUpdateUserFlagsAction ({ action, cache }: { userEntry.flags = newFlags.toString(10) - await userEntry.save({ transaction: cache.transaction }) + await userEntry.save({ transaction: cache.transaction.legacy.transaction }) cache.invalidiateUserList = true cache.incrementTriggeredSyncLevel(1) diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updateuserlimitlogincategory.ts b/src/function/sync/apply-actions/dispatch-parent-action/updateuserlimitlogincategory.ts index be1d88c..4d2ce00 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updateuserlimitlogincategory.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updateuserlimitlogincategory.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -25,13 +25,13 @@ export async function dispatchUpdateUserLimitLoginCategoryAction ({ action, cach cache: Cache parentUserId: string }) { - const userEntry = await cache.database.user.findOne({ + const userEntry = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.userId, type: 'parent' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!userEntry) { @@ -44,34 +44,34 @@ export async function dispatchUpdateUserLimitLoginCategoryAction ({ action, cach }) } - await cache.database.userLimitLoginCategory.destroy({ + await cache.transaction.legacy.database.userLimitLoginCategory.destroy({ where: { familyId: cache.familyId, userId: action.userId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (action.categoryId !== undefined) { - const categoryEntry = await cache.database.category.findOne({ + const categoryEntry = await cache.transaction.legacy.database.category.findOne({ where: { familyId: cache.familyId, categoryId: action.categoryId }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!categoryEntry) { throw new MissingCategoryException() } - await cache.database.userLimitLoginCategory.create({ + await cache.transaction.legacy.database.userLimitLoginCategory.create({ familyId: cache.familyId, userId: action.userId, categoryId: action.categoryId, preBlockDuration: 0 }, { - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) } diff --git a/src/function/sync/apply-actions/dispatch-parent-action/updateuserlimitloginpreblockduration.ts b/src/function/sync/apply-actions/dispatch-parent-action/updateuserlimitloginpreblockduration.ts index 4eed512..aedaa72 100644 --- a/src/function/sync/apply-actions/dispatch-parent-action/updateuserlimitloginpreblockduration.ts +++ b/src/function/sync/apply-actions/dispatch-parent-action/updateuserlimitloginpreblockduration.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -25,13 +25,13 @@ export async function dispatchUpdateUserLimitPreBlockDuration ({ action, cache, cache: Cache parentUserId: string }) { - const userEntry = await cache.database.user.findOne({ + const userEntry = await cache.transaction.legacy.database.user.findOne({ where: { familyId: cache.familyId, userId: action.userId, type: 'parent' }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!userEntry) { @@ -44,8 +44,8 @@ export async function dispatchUpdateUserLimitPreBlockDuration ({ action, cache, }) } - const preBlockItem = await cache.database.userLimitLoginCategory.findOne({ - transaction: cache.transaction, + const preBlockItem = await cache.transaction.legacy.database.userLimitLoginCategory.findOne({ + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, userId: action.userId @@ -58,10 +58,10 @@ export async function dispatchUpdateUserLimitPreBlockDuration ({ action, cache, }) } - await cache.database.userLimitLoginCategory.update({ + await cache.transaction.legacy.database.userLimitLoginCategory.update({ preBlockDuration: action.preBlockDuration }, { - transaction: cache.transaction, + transaction: cache.transaction.legacy.transaction, where: { familyId: cache.familyId, userId: action.userId diff --git a/src/function/sync/apply-actions/index.ts b/src/function/sync/apply-actions/index.ts index 67949a9..daa6a4c 100644 --- a/src/function/sync/apply-actions/index.ts +++ b/src/function/sync/apply-actions/index.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -18,7 +18,8 @@ import { BadRequest } from 'http-errors' import { ClientPushChangesRequest } from '../../../api/schema' import { VisibleConnectedDevicesManager } from '../../../connected-devices' -import { Database, shouldRetryWithException } from '../../../database' +import { SimpleDatabase } from '../../../database/simple' +import { shouldRetryWithException } from '../../../database' import { EventHandler } from '../../../monitoring/eventhandler' import { WebsocketApi } from '../../../websocket' import { notifyClientsAboutChangesDelayed } from '../../websocket' @@ -31,7 +32,7 @@ import { SequenceNumberRepeatedException } from './exception/sequence' import { assertActionIntegrity } from './integrity' export const applyActionsFromDevice = async ({ database, request, websocket, connectedDevicesManager, eventHandler }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi request: ClientPushChangesRequest connectedDevicesManager: VisibleConnectedDevicesManager @@ -47,12 +48,11 @@ export const applyActionsFromDevice = async ({ database, request, websocket, con } return database.transaction(async (transaction) => { - const baseInfo = await getApplyActionBaseInfo({ database, transaction, deviceAuthToken: request.deviceAuthToken }) + const baseInfo = await getApplyActionBaseInfo({ transaction, deviceAuthToken: request.deviceAuthToken }) const cache = new Cache({ - database, - hasFullVersion: baseInfo.hasFullVersion, transaction, + hasFullVersion: baseInfo.hasFullVersion, familyId: baseInfo.familyId, deviceId: baseInfo.deviceId, connectedDevicesManager @@ -112,7 +112,7 @@ export const applyActionsFromDevice = async ({ database, request, websocket, con } }) } catch (ex) { - if (shouldRetryWithException(database, ex)) { + if (shouldRetryWithException(transaction.legacy.database, ex)) { eventHandler.countEvent('applyActionsFromDevice got exception which should cause retry') throw ex @@ -132,14 +132,14 @@ export const applyActionsFromDevice = async ({ database, request, websocket, con if (nextSequenceNumber !== baseInfo.nextSequenceNumber) { eventHandler.countEvent('applyActionsFromDevice updateSequenceNumber') - await database.device.update({ + await transaction.legacy.database.device.update({ nextSequenceNumber }, { where: { familyId: baseInfo.familyId, deviceId: baseInfo.deviceId }, - transaction + transaction: transaction.legacy.transaction }) } @@ -149,18 +149,17 @@ export const applyActionsFromDevice = async ({ database, request, websocket, con familyId: baseInfo.familyId, sourceDeviceId: baseInfo.deviceId, websocket, - database, transaction, generalLevel: cache.triggeredSyncLevel, targetedLevels: cache.targetedTriggeredSyncLevels }) if (cache.triggeredSyncLevel === 2) { - transaction.afterCommit(() => { + transaction.enqueueAfterCommit(() => { eventHandler.countEvent('applyActionsFromDevice areChangesImportant') }) } else if ([...cache.targetedTriggeredSyncLevels.entries()].some((entry) => entry[1] === 2)) { - transaction.afterCommit(() => { + transaction.enqueueAfterCommit(() => { eventHandler.countEvent('applyActionsFromDevice areChangesImportantTargeted') }) } diff --git a/src/function/sync/apply-actions/integrity.ts b/src/function/sync/apply-actions/integrity.ts index 087f075..4cc4461 100644 --- a/src/function/sync/apply-actions/integrity.ts +++ b/src/function/sync/apply-actions/integrity.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -37,7 +37,7 @@ export async function assertActionIntegrity ({ action, cache, deviceId }: { }> { if (action.type === 'parent') { if (action.integrity === 'device') { - const deviceEntryUnsafe = await cache.database.device.findOne({ + const deviceEntryUnsafe = await cache.transaction.legacy.database.device.findOne({ attributes: ['currentUserId'], where: { familyId: cache.familyId, @@ -45,7 +45,7 @@ export async function assertActionIntegrity ({ action, cache, deviceId }: { currentUserId: action.userId, isUserKeptSignedIn: true }, - transaction: cache.transaction + transaction: cache.transaction.legacy.transaction }) if (!deviceEntryUnsafe) { @@ -74,7 +74,6 @@ export async function assertActionIntegrity ({ action, cache, deviceId }: { hasFullVersion: cache.hasFullVersion, familyId: cache.familyId, deviceId, - database: cache.database, transaction: cache.transaction, calculateHmac: (secret) => calculateActionHmac({ action, diff --git a/src/function/sync/get-server-data-status/category/assigned-apps.ts b/src/function/sync/get-server-data-status/category/assigned-apps.ts index 885472b..284c9ef 100644 --- a/src/function/sync/get-server-data-status/category/assigned-apps.ts +++ b/src/function/sync/get-server-data-status/category/assigned-apps.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,21 +16,20 @@ */ import * as Sequelize from 'sequelize' -import { Database, Transaction } from '../../../../database' +import { SimpleDatabaseTransaction } from '../../../../database/simple' import { ServerUpdatedCategoryAssignedApps } from '../../../../object/serverdatastatus' import { FamilyEntry } from '../family-entry' import { ServerCategoryVersions } from './diff' export async function getCategoryAssignedApps ({ - database, transaction, categoryIdsToSyncAssignedApps, familyEntry, serverCategoriesVersions + transaction, categoryIdsToSyncAssignedApps, familyEntry, serverCategoriesVersions }: { - database: Database - transaction: Transaction + transaction: SimpleDatabaseTransaction categoryIdsToSyncAssignedApps: Array familyEntry: FamilyEntry serverCategoriesVersions: ServerCategoryVersions }): Promise> { - const dataForSyncing = (await database.categoryApp.findAll({ + const dataForSyncing = (await transaction.legacy.database.categoryApp.findAll({ where: { familyId: familyEntry.familyId, categoryId: { @@ -38,7 +37,7 @@ export async function getCategoryAssignedApps ({ } }, attributes: ['categoryId', 'packageName'], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ categoryId: item.categoryId, packageName: item.packageName diff --git a/src/function/sync/get-server-data-status/category/base-data.ts b/src/function/sync/get-server-data-status/category/base-data.ts index 696c2c4..29c5df3 100644 --- a/src/function/sync/get-server-data-status/category/base-data.ts +++ b/src/function/sync/get-server-data-status/category/base-data.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,19 +16,18 @@ */ import * as Sequelize from 'sequelize' -import { Database, Transaction } from '../../../../database' +import { SimpleDatabaseTransaction } from '../../../../database/simple' import { ServerUpdatedCategoryBaseData } from '../../../../object/serverdatastatus' import { FamilyEntry } from '../family-entry' export async function getCategoryBaseDatas ({ - database, transaction, categoryIdsToSyncBaseData, familyEntry + transaction, categoryIdsToSyncBaseData, familyEntry }: { - database: Database - transaction: Transaction + transaction: SimpleDatabaseTransaction categoryIdsToSyncBaseData: Array familyEntry: FamilyEntry }): Promise> { - const dataForSyncing = (await database.category.findAll({ + const dataForSyncing = (await transaction.legacy.database.category.findAll({ where: { familyId: familyEntry.familyId, categoryId: { @@ -55,7 +54,7 @@ export async function getCategoryBaseDatas ({ 'flags', 'blockNotificationDelay' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ categoryId: item.categoryId, childId: item.childId, @@ -77,7 +76,7 @@ export async function getCategoryBaseDatas ({ blockNotificationDelay: item.blockNotificationDelay })) - const networkIdsForSyncing = (await database.categoryNetworkId.findAll({ + const networkIdsForSyncing = (await transaction.legacy.database.categoryNetworkId.findAll({ where: { familyId: familyEntry.familyId, categoryId: { @@ -89,14 +88,14 @@ export async function getCategoryBaseDatas ({ 'networkItemId', 'hashedNetworkId' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ categoryId: item.categoryId, networkItemId: item.networkItemId, hashedNetworkId: item.hashedNetworkId })) - const additionalTimeWarningsForSyncing = (await database.categoryTimeWarning.findAll({ + const additionalTimeWarningsForSyncing = (await transaction.legacy.database.categoryTimeWarning.findAll({ where: { familyId: familyEntry.familyId, categoryId: { @@ -107,7 +106,7 @@ export async function getCategoryBaseDatas ({ 'categoryId', 'minutes' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ categoryId: item.categoryId, minutes: item.minutes diff --git a/src/function/sync/get-server-data-status/category/diff.ts b/src/function/sync/get-server-data-status/category/diff.ts index ae3e17c..67490d0 100644 --- a/src/function/sync/get-server-data-status/category/diff.ts +++ b/src/function/sync/get-server-data-status/category/diff.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,19 +16,17 @@ */ import { difference, intersection } from 'lodash' -import * as Sequelize from 'sequelize' -import { Database } from '../../../../database' +import { SimpleDatabaseTransaction } from '../../../../database/simple' import { ClientDataStatusCategories } from '../../../../object/clientdatastatus' import { GetServerDataStatusIllegalStateException } from '../exception' import { FamilyEntry } from '../family-entry' -export async function getCategoryDataToSync ({ database, transaction, familyEntry, categoriesStatus }: { - database: Database - transaction: Sequelize.Transaction +export async function getCategoryDataToSync ({ transaction, familyEntry, categoriesStatus }: { + transaction: SimpleDatabaseTransaction familyEntry: FamilyEntry categoriesStatus: ClientDataStatusCategories }): Promise { - const serverCategoriesVersions: Array = (await database.category.findAll({ + const serverCategoriesVersions: Array = (await transaction.legacy.database.category.findAll({ where: { familyId: familyEntry.familyId }, @@ -40,7 +38,7 @@ export async function getCategoryDataToSync ({ database, transaction, familyEntr 'usedTimesVersion', 'taskListVersion' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ categoryId: item.categoryId, baseVersion: item.baseVersion, diff --git a/src/function/sync/get-server-data-status/category/rules.ts b/src/function/sync/get-server-data-status/category/rules.ts index 4405081..21b0dab 100644 --- a/src/function/sync/get-server-data-status/category/rules.ts +++ b/src/function/sync/get-server-data-status/category/rules.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2024 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,19 +16,18 @@ */ import * as Sequelize from 'sequelize' -import { Database, Transaction } from '../../../../database' +import { SimpleDatabaseTransaction } from '../../../../database/simple' import { ServerUpdatedTimeLimitRules } from '../../../../object/serverdatastatus' import { FamilyEntry } from '../family-entry' import { ServerCategoryVersions } from './diff' -export async function getRules ({ database, transaction, categoryIdsToSyncRules, familyEntry, serverCategoriesVersions }: { - database: Database - transaction: Transaction +export async function getRules ({ transaction, categoryIdsToSyncRules, familyEntry, serverCategoriesVersions }: { + transaction: SimpleDatabaseTransaction categoryIdsToSyncRules: Array familyEntry: FamilyEntry serverCategoriesVersions: ServerCategoryVersions }): Promise> { - const dataForSyncing = (await database.timelimitRule.findAll({ + const dataForSyncing = (await transaction.legacy.database.timelimitRule.findAll({ where: { familyId: familyEntry.familyId, categoryId: { @@ -48,7 +47,7 @@ export async function getRules ({ database, transaction, categoryIdsToSyncRules, 'perDay', 'expiresAt' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ ruleId: item.ruleId, categoryId: item.categoryId, diff --git a/src/function/sync/get-server-data-status/category/tasks.ts b/src/function/sync/get-server-data-status/category/tasks.ts index f8cbd49..32f9576 100644 --- a/src/function/sync/get-server-data-status/category/tasks.ts +++ b/src/function/sync/get-server-data-status/category/tasks.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,22 +16,21 @@ */ import * as Sequelize from 'sequelize' -import { Database, Transaction } from '../../../../database' +import { SimpleDatabaseTransaction } from '../../../../database/simple' import { ServerUpdatedCategoryTask, ServerUpdatedCategoryTasks } from '../../../../object/serverdatastatus' import { FamilyEntry } from '../family-entry' import { ServerCategoryVersions } from './diff' export async function getTasks ({ - database, transaction, categoryIdsToSyncTasks, familyEntry, + transaction, categoryIdsToSyncTasks, familyEntry, serverCategoriesVersions }: { - database: Database - transaction: Transaction + transaction: SimpleDatabaseTransaction categoryIdsToSyncTasks: Array familyEntry: FamilyEntry serverCategoriesVersions: ServerCategoryVersions }): Promise> { - const dataToSync = (await database.childTask.findAll({ + const dataToSync = (await transaction.legacy.database.childTask.findAll({ where: { familyId: familyEntry.familyId, categoryId: { @@ -46,7 +45,7 @@ export async function getTasks ({ 'pendingRequest', 'lastGrantTimestamp' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ taskId: item.taskId, categoryId: item.categoryId, diff --git a/src/function/sync/get-server-data-status/category/used-times.ts b/src/function/sync/get-server-data-status/category/used-times.ts index 24e482c..126ddb1 100644 --- a/src/function/sync/get-server-data-status/category/used-times.ts +++ b/src/function/sync/get-server-data-status/category/used-times.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,24 +16,23 @@ */ import * as Sequelize from 'sequelize' -import { Database, Transaction } from '../../../../database' +import { SimpleDatabaseTransaction } from '../../../../database/simple' import { ServerUpdatedCategoryUsedTimes } from '../../../../object/serverdatastatus' import { MinuteOfDay } from '../../../../util/minuteofday' import { FamilyEntry } from '../family-entry' import { ServerCategoryVersions } from './diff' export async function getUsedTimes ({ - database, transaction, categoryIdsToSyncUsedTimes, familyEntry, + transaction, categoryIdsToSyncUsedTimes, familyEntry, serverCategoriesVersions, clientLevel }: { - database: Database - transaction: Transaction + transaction: SimpleDatabaseTransaction categoryIdsToSyncUsedTimes: Array familyEntry: FamilyEntry serverCategoriesVersions: ServerCategoryVersions clientLevel: number | null }): Promise> { - const usedTimesForSyncing = (await database.usedTime.findAll({ + const usedTimesForSyncing = (await transaction.legacy.database.usedTime.findAll({ where: { familyId: familyEntry.familyId, categoryId: { @@ -47,7 +46,7 @@ export async function getUsedTimes ({ attributes: [ 'categoryId', 'dayOfEpoch', 'usedTime', 'startMinuteOfDay', 'endMinuteOfDay' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ categoryId: item.categoryId, dayOfEpoch: item.dayOfEpoch, @@ -56,7 +55,7 @@ export async function getUsedTimes ({ endMinuteOfDay: item.endMinuteOfDay })) - const sessionDurationsForSyncing = (await database.sessionDuration.findAll({ + const sessionDurationsForSyncing = (await transaction.legacy.database.sessionDuration.findAll({ where: { familyId: familyEntry.familyId, categoryId: { @@ -72,7 +71,7 @@ export async function getUsedTimes ({ 'lastUsage', 'lastSessionDuration' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ categoryId: item.categoryId, maxSessionDuration: item.maxSessionDuration, diff --git a/src/function/sync/get-server-data-status/device-detail.ts b/src/function/sync/get-server-data-status/device-detail.ts index 8e9211d..9b9a749 100644 --- a/src/function/sync/get-server-data-status/device-detail.ts +++ b/src/function/sync/get-server-data-status/device-detail.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,24 +16,23 @@ */ import * as Sequelize from 'sequelize' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { ClientDataStatusDevicesExtended } from '../../../object/clientdatastatus' import { ServerExtendedDeviceData, ServerCryptContainer } from '../../../object/serverdatastatus' import { FamilyEntry } from './family-entry' import { types } from '../../../database/encryptedapplist' -export async function getDeviceDetailList ({ database, transaction, familyEntry, devicesDetail }: { - database: Database - transaction: Sequelize.Transaction +export async function getDeviceDetailList ({ transaction, familyEntry, devicesDetail }: { + transaction: SimpleDatabaseTransaction familyEntry: FamilyEntry devicesDetail: ClientDataStatusDevicesExtended }): Promise | null> { - const serverEncryptedAppsVersions = (await database.encryptedAppList.findAll({ + const serverEncryptedAppsVersions = (await transaction.legacy.database.encryptedAppList.findAll({ where: { familyId: familyEntry.familyId, }, attributes: ['deviceId', 'type', 'version'], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ deviceId: item.deviceId, type: item.type, @@ -59,7 +58,7 @@ export async function getDeviceDetailList ({ database, transaction, familyEntry, if (updatedDeviceIds.length === 0) return null - const updatedBaseApps = devicesWithChangedBaseApps.length === 0 ? [] : (await database.encryptedAppList.findAll({ + const updatedBaseApps = devicesWithChangedBaseApps.length === 0 ? [] : (await transaction.legacy.database.encryptedAppList.findAll({ where: { familyId: familyEntry.familyId, deviceId: { @@ -72,14 +71,14 @@ export async function getDeviceDetailList ({ database, transaction, familyEntry, 'version', 'data' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ deviceId: item.deviceId, version: item.version, data: item.data })) - const updatedDiffApps = devicesWithChangedDiffApps.length === 0 ? [] : (await database.encryptedAppList.findAll({ + const updatedDiffApps = devicesWithChangedDiffApps.length === 0 ? [] : (await transaction.legacy.database.encryptedAppList.findAll({ where: { familyId: familyEntry.familyId, deviceId: { @@ -92,7 +91,7 @@ export async function getDeviceDetailList ({ database, transaction, familyEntry, 'version', 'data' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ deviceId: item.deviceId, version: item.version, diff --git a/src/function/sync/get-server-data-status/device-list.ts b/src/function/sync/get-server-data-status/device-list.ts index dbe2e16..933ea01 100644 --- a/src/function/sync/get-server-data-status/device-list.ts +++ b/src/function/sync/get-server-data-status/device-list.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,21 +15,19 @@ * along with this program. If not, see . */ -import * as Sequelize from 'sequelize' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { ServerDeviceList } from '../../../object/serverdatastatus' import { FamilyEntry } from './family-entry' -export async function getDeviceList ({ database, transaction, familyEntry }: { - database: Database - transaction: Sequelize.Transaction +export async function getDeviceList ({ transaction, familyEntry }: { + transaction: SimpleDatabaseTransaction familyEntry: FamilyEntry }): Promise { - const devices = (await database.device.findAll({ + const devices = (await transaction.legacy.database.device.findAll({ where: { familyId: familyEntry.familyId }, - transaction + transaction: transaction.legacy.transaction })) return { diff --git a/src/function/sync/get-server-data-status/dh-keys.ts b/src/function/sync/get-server-data-status/dh-keys.ts index 7ff3f15..7266dfb 100644 --- a/src/function/sync/get-server-data-status/dh-keys.ts +++ b/src/function/sync/get-server-data-status/dh-keys.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,8 +15,7 @@ * along with this program. If not, see . */ -import * as Sequelize from 'sequelize' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { config, calculateExpireTime } from '../../../database/devicedhkey' import { ServerDhKey } from '../../../object/serverdatastatus' import { generateVersionId } from '../../../util/token' @@ -25,21 +24,20 @@ import { generateDhKeypair } from '../../../function/dh' import { FamilyEntry } from './family-entry' export async function getDeviceDhKeys ({ - database, transaction, familyEntry, deviceId, lastVersionId, eventHandler + transaction, familyEntry, deviceId, lastVersionId, eventHandler }: { - database: Database - transaction: Sequelize.Transaction + transaction: SimpleDatabaseTransaction familyEntry: FamilyEntry deviceId: string lastVersionId: string | null eventHandler: EventHandler }): Promise { - const savedData = await database.deviceDhKey.findAll({ + const savedData = await transaction.legacy.database.deviceDhKey.findAll({ where: { familyId: familyEntry.familyId, deviceId }, - transaction + transaction: transaction.legacy.transaction }) const now = BigInt(Date.now()) @@ -72,19 +70,19 @@ export async function getDeviceDhKeys ({ } }, { index: 0, item: savedData[0] }) - await database.deviceDhKey.destroy({ + await transaction.legacy.database.deviceDhKey.destroy({ where: { familyId: familyEntry.familyId, deviceId, version: elementToRemove.item.version }, - transaction + transaction: transaction.legacy.transaction }) savedData.splice(elementToRemove.index, 1) } - await database.deviceDhKey.update({ + await transaction.legacy.database.deviceDhKey.update({ expireAt: calculateExpireTime(now).toString(10) }, { where: { @@ -92,7 +90,7 @@ export async function getDeviceDhKeys ({ deviceId, expireAt: null }, - transaction + transaction: transaction.legacy.transaction }) const newItemCreatedAt = (now - now % BigInt(config.generationTimeRounding)) @@ -105,7 +103,7 @@ export async function getDeviceDhKeys ({ const newItemCreatedAtSubsequence = newItemExistingSubsequenceValues.reduce((max, item) => Math.max(max, item + 1), 0) - await database.deviceDhKey.create({ + await transaction.legacy.database.deviceDhKey.create({ familyId: familyEntry.familyId, deviceId, version: newVersion, @@ -114,7 +112,7 @@ export async function getDeviceDhKeys ({ expireAt: null, publicKey: newKeypair.publicKey, privateKey: newKeypair.privateKey - }, { transaction }) + }, { transaction: transaction.legacy.transaction }) return { k: newKeypair.publicKey.toString('base64'), diff --git a/src/function/sync/get-server-data-status/family-entry.ts b/src/function/sync/get-server-data-status/family-entry.ts index ad0bdc8..0d240ab 100644 --- a/src/function/sync/get-server-data-status/family-entry.ts +++ b/src/function/sync/get-server-data-status/family-entry.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,8 +15,7 @@ * along with this program. If not, see . */ -import * as Sequelize from 'sequelize' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { GetServerDataStatusIllegalStateException } from './exception' export interface FamilyEntry { @@ -28,12 +27,11 @@ export interface FamilyEntry { u2fKeysVersion: string } -export async function getFamilyEntry ({ database, familyId, transaction }: { - database: Database +export async function getFamilyEntry ({ transaction, familyId }: { + transaction: SimpleDatabaseTransaction familyId: string - transaction: Sequelize.Transaction }): Promise { - const familyEntryUnsafe = await database.family.findOne({ + const familyEntryUnsafe = await transaction.legacy.database.family.findOne({ where: { familyId }, @@ -44,7 +42,7 @@ export async function getFamilyEntry ({ database, familyId, transaction }: { 'fullVersionUntil', 'u2fKeysVersion' ], - transaction + transaction: transaction.legacy.transaction }) if (!familyEntryUnsafe) { diff --git a/src/function/sync/get-server-data-status/index.ts b/src/function/sync/get-server-data-status/index.ts index 7d54575..a910ff2 100644 --- a/src/function/sync/get-server-data-status/index.ts +++ b/src/function/sync/get-server-data-status/index.ts @@ -15,9 +15,8 @@ * along with this program. If not, see . */ -import * as Sequelize from 'sequelize' import { config } from '../../../config' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { getStatusMessage } from '../../../function/statusmessage' import { ClientDataStatus } from '../../../object/clientdatastatus' import { ServerDataStatus } from '../../../object/serverdatastatus' @@ -38,18 +37,17 @@ import { getKeyResponses } from './key-responses' import { getU2f } from './u2f' export const generateServerDataStatus = async ({ - database, clientStatus, familyId, deviceId, transaction, eventHandler + transaction, clientStatus, familyId, deviceId, eventHandler }: { - database: Database + transaction: SimpleDatabaseTransaction clientStatus: ClientDataStatus familyId: string deviceId: string - transaction: Sequelize.Transaction eventHandler: EventHandler }): Promise => { const clientLevel = clientStatus.clientLevel || 0 - const familyEntry = await getFamilyEntry({ database, familyId, transaction }) + const familyEntry = await getFamilyEntry({ familyId, transaction }) const doesClientSupportTasks = clientLevel >= 3 const doesClientSupportCryptoApps = clientLevel >= 4 const doesClientSupportDh = clientLevel >= 5 @@ -58,7 +56,7 @@ export const generateServerDataStatus = async ({ const isClient750OrNewer = clientLevel >= 8 // first release in the post gplay time const message: string | undefined = - await getStatusMessage({ database, transaction }) || + await getStatusMessage({ transaction }) || getCampaign({ familyId, isClient750OrNewer }) || undefined @@ -71,14 +69,14 @@ export const generateServerDataStatus = async ({ } if (familyEntry.deviceListVersion !== clientStatus.devices) { - result.devices = await getDeviceList({ database, transaction, familyEntry }) + result.devices = await getDeviceList({ transaction, familyEntry }) } if (familyEntry.userListVersion !== clientStatus.users) { - result.users = await getUserList({ database, transaction, familyEntry }) + result.users = await getUserList({ transaction, familyEntry }) } - const categoryDataToSync = await getCategoryDataToSync({ database, transaction, familyEntry, categoriesStatus: clientStatus.categories }) + const categoryDataToSync = await getCategoryDataToSync({ transaction, familyEntry, categoriesStatus: clientStatus.categories }) if (categoryDataToSync.removedCategoryIds.length > 0) { result.rmCategories = categoryDataToSync.removedCategoryIds @@ -86,14 +84,14 @@ export const generateServerDataStatus = async ({ if (categoryDataToSync.categoryIdsToSyncBaseData.length > 0) { result.categoryBase = await getCategoryBaseDatas({ - database, transaction, familyEntry, + transaction, familyEntry, categoryIdsToSyncBaseData: categoryDataToSync.categoryIdsToSyncBaseData }) } if (categoryDataToSync.categoryIdsToSyncAssignedApps.length > 0) { result.categoryApp = await getCategoryAssignedApps({ - database, transaction, familyEntry, + transaction, familyEntry, serverCategoriesVersions: categoryDataToSync.serverCategoriesVersions, categoryIdsToSyncAssignedApps: categoryDataToSync.categoryIdsToSyncAssignedApps }) @@ -101,7 +99,7 @@ export const generateServerDataStatus = async ({ if (categoryDataToSync.categoryIdsToSyncRules.length > 0) { result.rules = await getRules({ - database, transaction, familyEntry, + transaction, familyEntry, serverCategoriesVersions: categoryDataToSync.serverCategoriesVersions, categoryIdsToSyncRules: categoryDataToSync.categoryIdsToSyncRules }) @@ -109,7 +107,7 @@ export const generateServerDataStatus = async ({ if (categoryDataToSync.categoryIdsToSyncUsedTimes.length > 0) { result.usedTimes = await getUsedTimes({ - database, transaction, familyEntry, + transaction, familyEntry, serverCategoriesVersions: categoryDataToSync.serverCategoriesVersions, categoryIdsToSyncUsedTimes: categoryDataToSync.categoryIdsToSyncUsedTimes, clientLevel: clientStatus.clientLevel || null @@ -118,7 +116,7 @@ export const generateServerDataStatus = async ({ if (categoryDataToSync.categoryIdsToSyncTasks.length > 0 && doesClientSupportTasks) { result.tasks = await getTasks({ - database, transaction, familyEntry, + transaction, familyEntry, serverCategoriesVersions: categoryDataToSync.serverCategoriesVersions, categoryIdsToSyncTasks: categoryDataToSync.categoryIdsToSyncTasks }) @@ -126,14 +124,12 @@ export const generateServerDataStatus = async ({ if (doesClientSupportCryptoApps) { result.devices2 = await getDeviceDetailList({ - database, transaction, familyEntry, devicesDetail: clientStatus.devicesDetail || {} }) || undefined result.krq = await getKeyRequests({ - database, transaction, familyEntry, deviceId, @@ -141,7 +137,6 @@ export const generateServerDataStatus = async ({ }) || undefined result.kr = await getKeyResponses({ - database, transaction, familyEntry, deviceId, @@ -151,7 +146,6 @@ export const generateServerDataStatus = async ({ if (doesClientSupportDh) { result.dh = await getDeviceDhKeys({ - database, transaction, familyEntry, deviceId, @@ -162,7 +156,6 @@ export const generateServerDataStatus = async ({ if (doesClientSupportU2f) { result.u2f = await getU2f({ - database, transaction, familyEntry, lastVersionId: clientStatus.u2f || null @@ -171,7 +164,6 @@ export const generateServerDataStatus = async ({ if (doesClientSupportPing) { result.pings = await getPings({ - database, transaction, familyEntry, deviceId diff --git a/src/function/sync/get-server-data-status/key-requests.ts b/src/function/sync/get-server-data-status/key-requests.ts index a7184d3..337a08e 100644 --- a/src/function/sync/get-server-data-status/key-requests.ts +++ b/src/function/sync/get-server-data-status/key-requests.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,18 +16,17 @@ */ import * as Sequelize from 'sequelize' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { ServerKeyRequest } from '../../../object/serverdatastatus' import { FamilyEntry } from './family-entry' -export async function getKeyRequests ({ database, transaction, familyEntry, lastSeenRequestIndex, deviceId }: { - database: Database - transaction: Sequelize.Transaction +export async function getKeyRequests ({ transaction, familyEntry, lastSeenRequestIndex, deviceId }: { + transaction: SimpleDatabaseTransaction familyEntry: FamilyEntry lastSeenRequestIndex: number | null deviceId: string }): Promise | null> { - const data = await database.keyRequest.findAll({ + const data = await transaction.legacy.database.keyRequest.findAll({ where: { familyId: familyEntry.familyId, senderDeviceId: { @@ -39,7 +38,7 @@ export async function getKeyRequests ({ database, transaction, familyEntry, last } }) }, - transaction, + transaction: transaction.legacy.transaction, limit: 32 }) diff --git a/src/function/sync/get-server-data-status/key-responses.ts b/src/function/sync/get-server-data-status/key-responses.ts index b029454..39c7ea9 100644 --- a/src/function/sync/get-server-data-status/key-responses.ts +++ b/src/function/sync/get-server-data-status/key-responses.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,19 +16,18 @@ */ import * as Sequelize from 'sequelize' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { ServerKeyResponse } from '../../../object/serverdatastatus' import { FamilyEntry } from './family-entry' -export async function getKeyResponses ({ database, transaction, familyEntry, lastSeenRequestIndex, deviceId }: { - database: Database - transaction: Sequelize.Transaction +export async function getKeyResponses ({ transaction, familyEntry, lastSeenRequestIndex, deviceId }: { + transaction: SimpleDatabaseTransaction familyEntry: FamilyEntry lastSeenRequestIndex: number | null deviceId: string }): Promise | null> { if (lastSeenRequestIndex !== null) { - await database.keyResponse.destroy({ + await transaction.legacy.database.keyResponse.destroy({ where: { familyId: familyEntry.familyId, receiverDeviceId: deviceId, @@ -36,17 +35,17 @@ export async function getKeyResponses ({ database, transaction, familyEntry, las [Sequelize.Op.lte]: lastSeenRequestIndex.toString(10) } }, - transaction + transaction: transaction.legacy.transaction }) } - const data = await database.keyResponse.findAll({ + const data = await transaction.legacy.database.keyResponse.findAll({ where: { familyId: familyEntry.familyId, receiverDeviceId: deviceId, }, order: [['replyServerSequenceNumber', 'ASC']], - transaction, + transaction: transaction.legacy.transaction, limit: 32 }) diff --git a/src/function/sync/get-server-data-status/pings.ts b/src/function/sync/get-server-data-status/pings.ts index 426e540..d9e723a 100644 --- a/src/function/sync/get-server-data-status/pings.ts +++ b/src/function/sync/get-server-data-status/pings.ts @@ -15,27 +15,25 @@ * along with this program. If not, see . */ -import * as Sequelize from 'sequelize' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { types as pingTypes } from '../../../database/ping' import { ServerPing } from '../../../object/serverdatastatus' import { FamilyEntry } from './family-entry' export async function getPings ({ - database, transaction, familyEntry, deviceId + transaction, familyEntry, deviceId }: { - database: Database - transaction: Sequelize.Transaction + transaction: SimpleDatabaseTransaction familyEntry: FamilyEntry deviceId: string }): Promise> { - const savedData = await database.ping.findAll({ + const savedData = await transaction.legacy.database.ping.findAll({ where: { familyId: familyEntry.familyId, receiverDeviceId: deviceId, }, attributes: ['senderDeviceId', 'type', 'token'], - transaction + transaction: transaction.legacy.transaction }) return savedData.map((row) => ({ diff --git a/src/function/sync/get-server-data-status/u2f.ts b/src/function/sync/get-server-data-status/u2f.ts index 515aa94..51bc304 100644 --- a/src/function/sync/get-server-data-status/u2f.ts +++ b/src/function/sync/get-server-data-status/u2f.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,26 +15,24 @@ * along with this program. If not, see . */ -import * as Sequelize from 'sequelize' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { U2fData } from '../../../object/serverdatastatus' import { FamilyEntry } from './family-entry' export async function getU2f ({ - database, transaction, familyEntry, lastVersionId + transaction, familyEntry, lastVersionId }: { - database: Database - transaction: Sequelize.Transaction + transaction: SimpleDatabaseTransaction familyEntry: FamilyEntry lastVersionId: string | null }): Promise { if (lastVersionId === familyEntry.u2fKeysVersion) return null - const savedData = await database.u2fKey.findAll({ + const savedData = await transaction.legacy.database.u2fKey.findAll({ where: { familyId: familyEntry.familyId }, - transaction + transaction: transaction.legacy.transaction }) return { diff --git a/src/function/sync/get-server-data-status/user-list.ts b/src/function/sync/get-server-data-status/user-list.ts index 35063c1..8142825 100644 --- a/src/function/sync/get-server-data-status/user-list.ts +++ b/src/function/sync/get-server-data-status/user-list.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,17 +15,15 @@ * along with this program. If not, see . */ -import * as Sequelize from 'sequelize' -import { Database } from '../../../database' +import { SimpleDatabaseTransaction } from '../../../database/simple' import { ServerUserList } from '../../../object/serverdatastatus' import { FamilyEntry } from './family-entry' -export async function getUserList ({ database, transaction, familyEntry }: { - database: Database - transaction: Sequelize.Transaction +export async function getUserList ({ transaction, familyEntry }: { + transaction: SimpleDatabaseTransaction familyEntry: FamilyEntry }): Promise { - const users = (await database.user.findAll({ + const users = (await transaction.legacy.database.user.findAll({ where: { familyId: familyEntry.familyId }, @@ -44,7 +42,7 @@ export async function getUserList ({ database, transaction, familyEntry }: { 'mailNotificationFlags', 'flags' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ userId: item.userId, name: item.name, @@ -61,7 +59,7 @@ export async function getUserList ({ database, transaction, familyEntry }: { flags: item.flags })) - const limitLoginCategories = (await database.userLimitLoginCategory.findAll({ + const limitLoginCategories = (await transaction.legacy.database.userLimitLoginCategory.findAll({ where: { familyId: familyEntry.familyId }, @@ -70,7 +68,7 @@ export async function getUserList ({ database, transaction, familyEntry }: { 'categoryId', 'preBlockDuration' ], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ userId: item.userId, categoryId: item.categoryId, diff --git a/src/function/u2f/index.ts b/src/function/u2f/index.ts index 8052c4b..6c3ed83 100644 --- a/src/function/u2f/index.ts +++ b/src/function/u2f/index.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,9 +16,8 @@ */ import { createHash, timingSafeEqual } from 'crypto' -import * as Sequelize from 'sequelize' import { getSharedSecret, SharedSecretException } from '../dh' -import { Database } from '../../database' +import { SimpleDatabaseTransaction} from '../../database/simple' import { intToBuffer } from '../../util/binary-number' import { isU2fSignatureValid, calculateApplicationId } from '../../util/u2fsignature' @@ -35,7 +34,6 @@ export async function validateU2fIntegrity({ hasFullVersion, familyId, deviceId, - database, transaction, calculateHmac }: { @@ -43,8 +41,7 @@ export async function validateU2fIntegrity({ hasFullVersion: boolean familyId: string deviceId: string - database: Database - transaction: Sequelize.Transaction + transaction: SimpleDatabaseTransaction calculateHmac: (secret: Buffer) => Buffer }) { if (!integrity.startsWith('u2f:')) throw new IntegrityMalformedException() @@ -69,7 +66,6 @@ export async function validateU2fIntegrity({ const sharedSecret = await (async () => { try { return await getSharedSecret({ - database, transaction, familyId, deviceId, @@ -88,12 +84,12 @@ export async function validateU2fIntegrity({ throw new HmacMismatchException() } - const keyDescriptorUnsafe = await database.u2fKey.findOne({ + const keyDescriptorUnsafe = await transaction.legacy.database.u2fKey.findOne({ where: { familyId, keyId: u2fKeyId }, - transaction, + transaction: transaction.legacy.transaction, attributes: ['publicKey', 'userId'] }) @@ -132,14 +128,14 @@ export async function validateU2fIntegrity({ // values; if this becomes necassary in the future, then it does not // require any client modification to add it - await database.u2fKey.update({ + await transaction.legacy.database.u2fKey.update({ nextCounter: (u2fCounter + 1).toString(10) }, { where: { familyId, keyId: u2fKeyId }, - transaction + transaction: transaction.legacy.transaction }) return { diff --git a/src/function/warningmail/manipulation.ts b/src/function/warningmail/manipulation.ts index b43d3d2..12fc24e 100644 --- a/src/function/warningmail/manipulation.ts +++ b/src/function/warningmail/manipulation.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,23 +15,22 @@ * along with this program. If not, see . */ -import { Database, Transaction } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' import { mailNotificationFlags } from '../../database/user' import { sendManipulationWarningMail } from '../../util/mail' import { canSendWarningMail } from '../../util/ratelimit-warningmail' -export const sendManipulationWarnings = async ({ database, familyId, deviceName, transaction }: { - database: Database +export const sendManipulationWarnings = async ({ transaction, familyId, deviceName }: { + transaction: SimpleDatabaseTransaction familyId: string deviceName: string - transaction: Transaction }) => { - const parentEntries = await database.user.findAll({ + const parentEntries = await transaction.legacy.database.user.findAll({ where: { familyId, type: 'parent' }, - transaction + transaction: transaction.legacy.transaction }) const targetMailAddresses = parentEntries @@ -39,7 +38,7 @@ export const sendManipulationWarnings = async ({ database, familyId, deviceName, .filter((item) => (item.mailNotificationFlags & mailNotificationFlags.warnings) === mailNotificationFlags.warnings) .map((item) => item.mail) - transaction.afterCommit(async () => { + transaction.enqueueAfterCommit(async () => { await Promise.all( targetMailAddresses.map(async (receiver) => { if (await canSendWarningMail(receiver)) { diff --git a/src/function/warningmail/uninstall.ts b/src/function/warningmail/uninstall.ts index 49eae29..8940c59 100644 --- a/src/function/warningmail/uninstall.ts +++ b/src/function/warningmail/uninstall.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2020 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,23 +15,22 @@ * along with this program. If not, see . */ -import { Database, Transaction } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' import { mailNotificationFlags } from '../../database/user' import { sendUninstallWarningMail } from '../../util/mail' import { canSendWarningMail } from '../../util/ratelimit-warningmail' -export const sendUninstallWarnings = async ({ database, familyId, deviceName, transaction }: { - database: Database +export const sendUninstallWarnings = async ({ familyId, deviceName, transaction }: { + transaction: SimpleDatabaseTransaction familyId: string deviceName: string - transaction: Transaction }) => { - const parentEntries = await database.user.findAll({ + const parentEntries = await transaction.legacy.database.user.findAll({ where: { familyId, type: 'parent' }, - transaction + transaction: transaction.legacy.transaction }) const targetMailAddresses = parentEntries @@ -39,7 +38,7 @@ export const sendUninstallWarnings = async ({ database, familyId, deviceName, tr .filter((item) => (item.mailNotificationFlags & mailNotificationFlags.warnings) === mailNotificationFlags.warnings) .map((item) => item.mail) - transaction.afterCommit(async () => { + transaction.enqueueAfterCommit(async () => { await Promise.all( targetMailAddresses.map(async (receiver) => { if (await canSendWarningMail(receiver)) { diff --git a/src/function/websocket/index.ts b/src/function/websocket/index.ts index 8564103..b22c463 100644 --- a/src/function/websocket/index.ts +++ b/src/function/websocket/index.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,33 +15,32 @@ * along with this program. If not, see . */ -import { Database, Transaction } from '../../database' +import { SimpleDatabaseTransaction } from '../../database/simple' import { WebsocketApi } from '../../websocket' export const notifyClientsAboutChangesDelayed = async ({ - familyId, sourceDeviceId, database, + familyId, sourceDeviceId, websocket, transaction, generalLevel, targetedLevels }: { familyId: string sourceDeviceId: string | null // this device will not get an push - database: Database + transaction: SimpleDatabaseTransaction websocket: WebsocketApi - transaction: Transaction generalLevel: 0 | 1 | 2 targetedLevels: Map }) => { - const relatedDeviceEntries = (await database.device.findAll({ + const relatedDeviceEntries = (await transaction.legacy.database.device.findAll({ where: { familyId }, attributes: ['deviceId', 'deviceAuthToken'], - transaction + transaction: transaction.legacy.transaction })).map((item) => ({ deviceId: item.deviceId, deviceAuthToken: item.deviceAuthToken })) - transaction.afterCommit(() => { + transaction.enqueueAfterCommit(() => { for (const deviceEntry of relatedDeviceEntries) { if (deviceEntry.deviceId === sourceDeviceId) continue diff --git a/src/index.ts b/src/index.ts index 1ce7084..6beadad 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -21,6 +21,7 @@ import { createApi } from './api' import { config } from './config' import { VisibleConnectedDevicesManager } from './connected-devices' import { assertNestedTransactionsAreWorking, assertSerializeableTransactionsAreWorking, defaultDatabase, defaultUmzug } from './database' +import { fromLegacy as createSimpleDatabase } from './database/simple' import { EventHandler } from './monitoring/eventhandler' import { InMemoryEventHandler } from './monitoring/inmemoryeventhandler' import { createWebsocketHandler } from './websocket' @@ -28,11 +29,13 @@ import { initWorkers } from './worker' async function main () { await defaultUmzug.up() - const database = defaultDatabase + const legacyDatabase = defaultDatabase const eventHandler: EventHandler = new InMemoryEventHandler() - await assertNestedTransactionsAreWorking(database) - await assertSerializeableTransactionsAreWorking(database) + await assertNestedTransactionsAreWorking(legacyDatabase) + await assertSerializeableTransactionsAreWorking(legacyDatabase) + + const database = createSimpleDatabase(legacyDatabase) const connectedDevicesManager = new VisibleConnectedDevicesManager({ database diff --git a/src/websocket/index.ts b/src/websocket/index.ts index af1d358..15d67f6 100644 --- a/src/websocket/index.ts +++ b/src/websocket/index.ts @@ -18,12 +18,12 @@ import { EventEmitter } from 'events' import { Server } from 'socket.io' import { ConnectedDevicesManager, VisibleConnectedDevicesManager } from '../connected-devices' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { deviceByAuthTokenRoom } from './rooms' export const createWebsocketHandler = ({ connectedDevicesManager, database }: { connectedDevicesManager: VisibleConnectedDevicesManager - database: Database + database: SimpleDatabase }): { websocketServer: Server websocketApi: WebsocketApi @@ -64,7 +64,7 @@ export const createWebsocketHandler = ({ connectedDevicesManager, database }: { socket.on('disconnect', () => events.removeListener(eventTriggerImportantSyncForAll, importantSyncForAllListener)) ;(async () => { - const deviceEntryUnsafe = await database.device.findOne({ + const deviceEntryUnsafe = await database.legacy.device.findOne({ where: { deviceAuthToken }, diff --git a/src/worker/delete-deprecated-purchases.ts b/src/worker/delete-deprecated-purchases.ts index 35928d5..626bbe2 100644 --- a/src/worker/delete-deprecated-purchases.ts +++ b/src/worker/delete-deprecated-purchases.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,12 +16,12 @@ */ import * as Sequelize from 'sequelize' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { notifyClientsAboutChangesDelayed } from '../function/websocket' import { WebsocketApi } from '../websocket' export function initDeleteDeprecatedPurchasesWorker ({ database, websocket }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi }) { function doWorkSafe () { @@ -44,11 +44,11 @@ export function initDeleteDeprecatedPurchasesWorker ({ database, websocket }: { } async function deleteDeprecatedPurchases ({ database, websocket }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi }) { await database.transaction(async (transaction) => { - const affectedFamilyIds = (await database.family.findAll({ + const affectedFamilyIds = (await transaction.legacy.database.family.findAll({ where: { hasFullVersion: true, fullVersionUntil: { @@ -56,11 +56,11 @@ async function deleteDeprecatedPurchases ({ database, websocket }: { } }, attributes: ['familyId'], - transaction, + transaction: transaction.legacy.transaction, limit: 100 })).map((item) => item.familyId) - await database.family.update({ + await transaction.legacy.database.family.update({ hasFullVersion: false }, { where: { @@ -68,14 +68,13 @@ async function deleteDeprecatedPurchases ({ database, websocket }: { [Sequelize.Op.in]: affectedFamilyIds } }, - transaction + transaction: transaction.legacy.transaction }) for (const familyId of affectedFamilyIds) { await notifyClientsAboutChangesDelayed({ familyId, sourceDeviceId: null, - database, websocket, generalLevel: 2, targetedLevels: new Map(), diff --git a/src/worker/delete-old-families.ts b/src/worker/delete-old-families.ts index 101a615..c7924bb 100644 --- a/src/worker/delete-old-families.ts +++ b/src/worker/delete-old-families.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2021 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,11 +15,11 @@ * along with this program. If not, see . */ -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { deleteOldFamilies } from '../function/cleanup/delete-old-families' export function initDeleteOldFamiliesWorker ({ database }: { - database: Database + database: SimpleDatabase }) { function doWorkSafe () { console.log('deleting old families now') diff --git a/src/worker/delete-old-tokens.ts b/src/worker/delete-old-tokens.ts index ac2f901..f338782 100644 --- a/src/worker/delete-old-tokens.ts +++ b/src/worker/delete-old-tokens.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2022 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -16,10 +16,10 @@ */ import * as Sequelize from 'sequelize' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' export function initDeleteOldTokensWorker ({ database }: { - database: Database + database: SimpleDatabase }) { function doWorkSafe () { console.log('deleting old tokens now') @@ -41,42 +41,43 @@ export function initDeleteOldTokensWorker ({ database }: { } async function deleteOldTokens ({ database }: { - database: Database + database: SimpleDatabase }) { await database.transaction(async (transaction) => { - await database.authtoken.destroy({ + await transaction.legacy.database.authtoken.destroy({ where: { createdAt: { [Sequelize.Op.lt]: (Date.now() - 1000 * 60 * 60 * 3 /* 3 hours */).toString() } }, - transaction + transaction: transaction.legacy.transaction }) - await database.addDeviceToken.destroy({ + await transaction.legacy.database.addDeviceToken.destroy({ where: { createdAt: { [Sequelize.Op.lt]: (Date.now() - 1000 * 60 * 60 * 3 /* 3 hours */).toString() } }, - transaction + transaction: transaction.legacy.transaction }) - await database.mailLoginToken.destroy({ + await transaction.legacy.database.mailLoginToken.destroy({ where: { createdAt: { [Sequelize.Op.lt]: (Date.now() - 1000 * 60 * 60 * 3 /* 3 hours */).toString() } }, - transaction + transaction: transaction.legacy.transaction }) - }) - await database.deviceDhKey.destroy({ - where: { - expireAt: { - [Sequelize.Op.lt]: Date.now().toString() - } - } + await transaction.legacy.database.deviceDhKey.destroy({ + where: { + expireAt: { + [Sequelize.Op.lt]: Date.now().toString() + } + }, + transaction: transaction.legacy.transaction + }) }) } diff --git a/src/worker/delete-old-used-times.ts b/src/worker/delete-old-used-times.ts index ca47d5c..6080a85 100644 --- a/src/worker/delete-old-used-times.ts +++ b/src/worker/delete-old-used-times.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 - 2021 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -17,11 +17,11 @@ import { uniqBy } from 'lodash' import * as Sequelize from 'sequelize' -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { generateVersionId } from '../util/token' export function initDeleteOldUsedTimesWorker ({ database }: { - database: Database + database: SimpleDatabase }) { function doWorkSafe () { console.log('deleting old used times now') @@ -43,14 +43,14 @@ export function initDeleteOldUsedTimesWorker ({ database }: { } async function deleteOldUsedTimes ({ database }: { - database: Database + database: SimpleDatabase }) { const now = Date.now() await database.transaction(async (transaction) => { // get matching categories - const categoriesToCleanUpOne = (await database.usedTime.findAll({ - transaction, + const categoriesToCleanUpOne = (await transaction.legacy.database.usedTime.findAll({ + transaction: transaction.legacy.transaction, where: { lastUpdate: { [Sequelize.Op.lt]: (now - 1000 * 60 * 60 * 24 * 10 /* 10 days */).toString() @@ -67,8 +67,8 @@ async function deleteOldUsedTimes ({ database }: { categoryId: item.categoryId })) - const categoriesToCleanUpTwo = (await database.sessionDuration.findAll({ - transaction, + const categoriesToCleanUpTwo = (await transaction.legacy.database.sessionDuration.findAll({ + transaction: transaction.legacy.transaction, where: { roundedLastUpdate: { [Sequelize.Op.lt]: (now - 1000 * 60 * 60 * 24 * 3 /* 3 days */).toString() @@ -91,8 +91,8 @@ async function deleteOldUsedTimes ({ database }: { if (distinctCategoriesToCleanUp.length > 0) { // delete old items of matching categories - await database.usedTime.destroy({ - transaction, + await transaction.legacy.database.usedTime.destroy({ + transaction: transaction.legacy.transaction, where: { [Sequelize.Op.or]: ( distinctCategoriesToCleanUp @@ -103,8 +103,8 @@ async function deleteOldUsedTimes ({ database }: { } }) - await database.sessionDuration.destroy({ - transaction, + await transaction.legacy.database.sessionDuration.destroy({ + transaction: transaction.legacy.transaction, where: { [Sequelize.Op.or]: ( distinctCategoriesToCleanUp @@ -116,10 +116,10 @@ async function deleteOldUsedTimes ({ database }: { }) // invalidiate categories - await database.category.update({ + await transaction.legacy.database.category.update({ usedTimesVersion: generateVersionId() }, { - transaction, + transaction: transaction.legacy.transaction, where: { [Sequelize.Op.or]: ( distinctCategoriesToCleanUp diff --git a/src/worker/index.ts b/src/worker/index.ts index 2adaca8..32d1222 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -1,6 +1,6 @@ /* * server component for the TimeLimit App - * Copyright (C) 2019 Jonas Lochmann + * Copyright (C) 2019 - 2026 Jonas Lochmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -import { Database } from '../database' +import { SimpleDatabase } from '../database/simple' import { WebsocketApi } from '../websocket' import { initDeleteDeprecatedPurchasesWorker } from './delete-deprecated-purchases' import { initDeleteOldFamiliesWorker } from './delete-old-families' @@ -23,7 +23,7 @@ import { initDeleteOldTokensWorker } from './delete-old-tokens' import { initDeleteOldUsedTimesWorker } from './delete-old-used-times' export function initWorkers ({ database, websocket }: { - database: Database + database: SimpleDatabase websocket: WebsocketApi }) { initDeleteDeprecatedPurchasesWorker({ database, websocket })