signal-desktop/ts/sql/Server.ts

5612 lines
132 KiB
TypeScript
Raw Normal View History

2023-01-03 19:55:46 +00:00
// Copyright 2020 Signal Messenger, LLC
2020-10-30 20:34:04 +00:00
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable camelcase */
import { mkdirSync } from 'fs';
import { join } from 'path';
import rimraf from 'rimraf';
import { randomBytes } from 'crypto';
2022-12-14 20:48:36 +00:00
import type { Database, Statement } from '@signalapp/better-sqlite3';
import SQL from '@signalapp/better-sqlite3';
import pProps from 'p-props';
import type { Dictionary } from 'lodash';
import {
forEach,
fromPairs,
groupBy,
isBoolean,
isNil,
isNumber,
isString,
last,
map,
mapValues,
omit,
2021-05-07 21:50:14 +00:00
pick,
} from 'lodash';
import * as Errors from '../types/errors';
import { ReadStatus } from '../messages/MessageReadStatus';
import type { GroupV2MemberType } from '../model-types.d';
import type { ReactionType } from '../types/Reactions';
import { STORAGE_UI_KEYS } from '../types/StorageUIKeys';
2021-10-26 22:59:08 +00:00
import { UUID } from '../types/UUID';
import type { UUIDStringType } from '../types/UUID';
import type { StoredJob } from '../jobs/types';
import { assertDev, assertSync, strictAssert } from '../util/assert';
import { combineNames } from '../util/combineNames';
import { consoleLogger } from '../util/consoleLogger';
2021-07-09 19:36:10 +00:00
import { dropNull } from '../util/dropNull';
import { isNormalNumber } from '../util/isNormalNumber';
2021-04-29 23:02:27 +00:00
import { isNotNil } from '../util/isNotNil';
import { missingCaseError } from '../util/missingCaseError';
import { parseIntOrThrow } from '../util/parseIntOrThrow';
import * as durations from '../util/durations';
import { formatCountForLogging } from '../logging/formatCountForLogging';
import type { ConversationColorType, CustomColorType } from '../types/Colors';
import { RemoveAllConfiguration } from '../types/RemoveAllConfiguration';
2021-11-02 23:01:13 +00:00
import type { BadgeType, BadgeImageType } from '../badges/types';
import { parseBadgeCategory } from '../badges/BadgeCategory';
import { parseBadgeImageTheme } from '../badges/BadgeImageTheme';
import type { LoggerType } from '../types/Logging';
import * as log from '../logging/log';
2021-10-26 22:59:08 +00:00
import type { EmptyQuery, ArrayQuery, Query, JSONRows } from './util';
import {
jsonToObject,
objectToJSON,
batchMultiVarQuery,
getCountFromTable,
removeById,
removeAllFromTable,
getAllFromTable,
getById,
bulkAdd,
createOrUpdate,
setUserVersion,
getUserVersion,
getSchemaVersion,
} from './util';
import { updateSchema } from './migrations';
import type {
2022-07-28 16:35:29 +00:00
StoredAllItemsType,
AttachmentDownloadJobType,
ConversationMetricsType,
ConversationType,
2021-08-31 21:35:01 +00:00
DeleteSentProtoRecipientOptionsType,
2022-08-15 21:53:33 +00:00
DeleteSentProtoRecipientResultType,
EmojiType,
2022-11-28 17:19:48 +00:00
GetAllStoriesResultType,
2022-07-28 16:35:29 +00:00
GetConversationRangeCenteredOnMessageResultType,
GetKnownMessageAttachmentsResultType,
2022-07-28 16:35:29 +00:00
GetUnreadByConversationAndMarkReadResultType,
IdentityKeyIdType,
2022-07-28 16:35:29 +00:00
StoredIdentityKeyType,
2022-08-03 17:10:49 +00:00
InstalledStickerPackType,
ItemKeyType,
2022-07-28 16:35:29 +00:00
StoredItemType,
ConversationMessageStatsType,
MessageAttachmentsCursorType,
MessageMetricsType,
MessageType,
MessageTypeUnhydrated,
PreKeyIdType,
2022-07-28 16:35:29 +00:00
ReactionResultType,
StoredPreKeyType,
ServerSearchResultMessageType,
SenderKeyIdType,
SenderKeyType,
SentMessageDBType,
SentMessagesType,
SentProtoType,
SentProtoWithMessageIdsType,
SentRecipientsDBType,
SentRecipientsType,
ServerInterface,
SessionIdType,
SessionType,
SignedPreKeyIdType,
2022-07-28 16:35:29 +00:00
StoredSignedPreKeyType,
2022-08-03 17:10:49 +00:00
StickerPackInfoType,
StickerPackStatusType,
StickerPackType,
StickerType,
StoryDistributionMemberType,
StoryDistributionType,
StoryDistributionWithMembersType,
StoryReadType,
2022-08-03 17:10:49 +00:00
UninstalledStickerPackType,
UnprocessedType,
UnprocessedUpdateType,
} from './Interface';
import { SeenStatus } from '../MessageSeenStatus';
type ConversationRow = Readonly<{
json: string;
profileLastFetchedAt: null | number;
}>;
type ConversationRows = Array<ConversationRow>;
type StickerRow = Readonly<{
id: number;
packId: string;
emoji: string | null;
height: number;
isCoverOnly: number;
lastUsed: number;
path: string;
width: number;
}>;
// Because we can't force this module to conform to an interface, we narrow our exports
// to this one default export, which does conform to the interface.
// Note: In Javascript, you need to access the .default property when requiring it
// https://github.com/microsoft/TypeScript/issues/420
const dataInterface: ServerInterface = {
close,
removeDB,
removeIndexedDBFiles,
2018-10-18 01:01:21 +00:00
createOrUpdateIdentityKey,
getIdentityKeyById,
bulkAddIdentityKeys,
removeIdentityKeyById,
removeAllIdentityKeys,
getAllIdentityKeys,
2018-10-18 01:01:21 +00:00
createOrUpdatePreKey,
getPreKeyById,
bulkAddPreKeys,
removePreKeyById,
2022-07-28 16:35:29 +00:00
removePreKeysByUuid,
2018-10-18 01:01:21 +00:00
removeAllPreKeys,
getAllPreKeys,
2018-10-18 01:01:21 +00:00
createOrUpdateSignedPreKey,
getSignedPreKeyById,
bulkAddSignedPreKeys,
removeSignedPreKeyById,
2022-07-28 16:35:29 +00:00
removeSignedPreKeysByUuid,
2018-10-18 01:01:21 +00:00
removeAllSignedPreKeys,
getAllSignedPreKeys,
2018-10-18 01:01:21 +00:00
createOrUpdateItem,
getItemById,
removeItemById,
removeAllItems,
getAllItems,
2018-10-18 01:01:21 +00:00
createOrUpdateSenderKey,
getSenderKeyById,
removeAllSenderKeys,
getAllSenderKeys,
2021-05-25 22:40:04 +00:00
removeSenderKeyById,
insertSentProto,
deleteSentProtosOlderThan,
deleteSentProtoByMessageId,
insertProtoRecipients,
deleteSentProtoRecipient,
getSentProtoByRecipient,
removeAllSentProtos,
getAllSentProtos,
_getAllSentProtoRecipients,
_getAllSentProtoMessageIds,
2018-10-18 01:01:21 +00:00
createOrUpdateSession,
2019-09-26 19:56:31 +00:00
createOrUpdateSessions,
commitDecryptResult,
2018-10-18 01:01:21 +00:00
bulkAddSessions,
removeSessionById,
removeSessionsByConversation,
removeSessionsByUUID,
2018-10-18 01:01:21 +00:00
removeAllSessions,
getAllSessions,
2018-10-18 01:01:21 +00:00
eraseStorageServiceStateFromConversations,
2018-09-21 01:47:19 +00:00
getConversationCount,
saveConversation,
saveConversations,
getConversationById,
updateConversation,
2019-09-26 19:56:31 +00:00
updateConversations,
2018-09-21 01:47:19 +00:00
removeConversation,
_removeAllConversations,
updateAllConversationColors,
2022-07-08 20:46:25 +00:00
removeAllProfileKeyCredentials,
2018-09-21 01:47:19 +00:00
getAllConversations,
getAllConversationIds,
2021-10-26 22:59:08 +00:00
getAllGroupsInvolvingUuid,
2019-01-14 21:47:19 +00:00
searchMessages,
searchMessagesInConversation,
2018-09-21 01:47:19 +00:00
getMessageCount,
2022-03-29 01:10:08 +00:00
getStoryCount,
saveMessage,
saveMessages,
removeMessage,
2021-01-13 00:42:15 +00:00
removeMessages,
getUnreadByConversationAndMarkRead,
getUnreadReactionsAndMarkRead,
markReactionAsRead,
addReaction,
removeReactionFromConversation,
_getAllReactions,
_removeAllReactions,
getMessageBySender,
getMessageById,
getMessagesById,
_getAllMessages,
_removeAllMessages,
getAllMessageIds,
getMessagesBySentAt,
getExpiredMessages,
getMessagesUnexpectedlyMissingExpirationStartTimestamp,
2021-06-16 22:20:17 +00:00
getSoonestMessageExpiry,
getNextTapToViewMessageTimestampToAgeOut,
2019-06-26 19:33:13 +00:00
getTapToViewMessagesNeedingErase,
getOlderMessagesByConversation,
getAllStories,
getNewerMessagesByConversation,
getTotalUnreadForConversation,
getMessageMetricsForConversation,
getConversationRangeCenteredOnMessage,
getConversationMessageStats,
getLastConversationMessage,
2023-01-10 00:52:01 +00:00
getCallHistoryMessageByCallId,
hasGroupCallHistoryMessage,
migrateConversationMessages,
getUnprocessedCount,
getUnprocessedByIdsAndIncrementAttempts,
getAllUnprocessedIds,
updateUnprocessedWithData,
2019-09-26 19:56:31 +00:00
updateUnprocessedsWithData,
getUnprocessedById,
removeUnprocessed,
removeAllUnprocessed,
getAttachmentDownloadJobById,
getNextAttachmentDownloadJobs,
saveAttachmentDownloadJob,
resetAttachmentDownloadPending,
setAttachmentDownloadJobPending,
removeAttachmentDownloadJob,
removeAllAttachmentDownloadJobs,
createOrUpdateStickerPack,
updateStickerPackStatus,
2022-08-03 17:10:49 +00:00
updateStickerPackInfo,
createOrUpdateSticker,
updateStickerLastUsed,
addStickerPackReference,
deleteStickerPackReference,
getStickerCount,
deleteStickerPack,
getAllStickerPacks,
2022-08-03 17:10:49 +00:00
addUninstalledStickerPack,
removeUninstalledStickerPack,
getInstalledStickerPacks,
getUninstalledStickerPacks,
installStickerPack,
uninstallStickerPack,
getStickerPackInfo,
getAllStickers,
getRecentStickers,
2021-01-27 22:39:45 +00:00
clearAllErrorStickerPackAttempts,
2019-05-24 23:58:27 +00:00
updateEmojiUsage,
getRecentEmojis,
2021-11-02 23:01:13 +00:00
getAllBadges,
updateOrCreateBadges,
badgeImageFileDownloaded,
_getAllStoryDistributions,
_getAllStoryDistributionMembers,
_deleteAllStoryDistributions,
createNewStoryDistribution,
getAllStoryDistributionsWithMembers,
2022-03-04 21:14:52 +00:00
getStoryDistributionWithMembers,
modifyStoryDistribution,
modifyStoryDistributionMembers,
2022-07-01 00:52:03 +00:00
modifyStoryDistributionWithMembers,
deleteStoryDistribution,
_getAllStoryReads,
_deleteAllStoryReads,
addNewStoryRead,
getLastStoryReadsForAuthor,
2022-03-29 01:10:08 +00:00
countStoryReadsByConversation,
removeAll,
2018-10-18 01:01:21 +00:00
removeAllConfiguration,
getMessagesNeedingUpgrade,
getMessagesWithVisualMediaAttachments,
getMessagesWithFileAttachments,
getMessageServerGuidsForSpam,
2021-04-29 23:02:27 +00:00
getJobsInQueue,
insertJob,
deleteJob,
wasGroupCallRingPreviouslyCanceled,
processGroupCallRingCancellation,
cleanExpiredGroupCallRingCancellations,
2021-08-20 16:06:15 +00:00
2021-09-15 18:45:22 +00:00
getMaxMessageCounter,
getStatisticsForLogging,
// Server-only
initialize,
2021-03-04 21:44:57 +00:00
initializeRenderer,
getKnownMessageAttachments,
finishGetKnownMessageAttachments,
getKnownConversationAttachments,
removeKnownStickers,
2019-08-07 00:40:25 +00:00
removeKnownDraftAttachments,
2021-11-02 23:01:13 +00:00
getAllBadgeImageFileLocalPaths,
};
export default dataInterface;
2021-10-26 22:59:08 +00:00
type DatabaseQueryCache = Map<string, Statement<Array<unknown>>>;
const statementCache = new WeakMap<Database, DatabaseQueryCache>();
2022-11-14 19:35:37 +00:00
function prepare<T extends Array<unknown> | Record<string, unknown>>(
db: Database,
query: string,
{ pluck = false }: { pluck?: boolean } = {}
2022-11-14 19:35:37 +00:00
): Statement<T> {
let dbCache = statementCache.get(db);
if (!dbCache) {
dbCache = new Map();
statementCache.set(db, dbCache);
}
const cacheKey = `${pluck}:${query}`;
let result = dbCache.get(cacheKey) as Statement<T>;
if (!result) {
result = db.prepare<T>(query);
if (pluck === true) {
result.pluck();
}
dbCache.set(cacheKey, result);
}
return result;
}
function rowToConversation(row: ConversationRow): ConversationType {
const parsedJson = JSON.parse(row.json);
let profileLastFetchedAt: undefined | number;
if (isNormalNumber(row.profileLastFetchedAt)) {
profileLastFetchedAt = row.profileLastFetchedAt;
} else {
assertDev(
isNil(row.profileLastFetchedAt),
'profileLastFetchedAt contained invalid data; defaulting to undefined'
);
profileLastFetchedAt = undefined;
}
return {
...parsedJson,
profileLastFetchedAt,
};
}
function rowToSticker(row: StickerRow): StickerType {
return {
...row,
isCoverOnly: Boolean(row.isCoverOnly),
2021-07-09 19:36:10 +00:00
emoji: dropNull(row.emoji),
};
2021-10-26 22:59:08 +00:00
}
2021-10-26 22:59:08 +00:00
function isRenderer() {
if (typeof process === 'undefined' || !process) {
return true;
}
2021-10-26 22:59:08 +00:00
return process.type === 'renderer';
}
2021-10-26 22:59:08 +00:00
function keyDatabase(db: Database, key: string): void {
// https://www.zetetic.net/sqlcipher/sqlcipher-api/#key
db.pragma(`key = "x'${key}'"`);
}
2021-10-26 22:59:08 +00:00
function switchToWAL(db: Database): void {
// https://sqlite.org/wal.html
db.pragma('journal_mode = WAL');
db.pragma('synchronous = FULL');
}
2021-10-26 22:59:08 +00:00
function migrateSchemaVersion(db: Database): void {
const userVersion = getUserVersion(db);
if (userVersion > 0) {
return;
}
2021-10-26 22:59:08 +00:00
const schemaVersion = getSchemaVersion(db);
const newUserVersion = schemaVersion > 18 ? 16 : schemaVersion;
logger.info(
'migrateSchemaVersion: Migrating from schema_version ' +
`${schemaVersion} to user_version ${newUserVersion}`
);
2021-10-26 22:59:08 +00:00
setUserVersion(db, newUserVersion);
}
2021-10-26 22:59:08 +00:00
function openAndMigrateDatabase(filePath: string, key: string) {
let db: Database | undefined;
2021-10-26 22:59:08 +00:00
// First, we try to open the database without any cipher changes
try {
db = new SQL(filePath);
keyDatabase(db, key);
switchToWAL(db);
migrateSchemaVersion(db);
2021-10-26 22:59:08 +00:00
return db;
} catch (error) {
if (db) {
db.close();
}
2021-10-26 22:59:08 +00:00
logger.info('migrateDatabase: Migration without cipher change failed');
}
2021-10-26 22:59:08 +00:00
// If that fails, we try to open the database with 3.x compatibility to extract the
// user_version (previously stored in schema_version, blown away by cipher_migrate).
db = new SQL(filePath);
keyDatabase(db, key);
2021-10-26 22:59:08 +00:00
// https://www.zetetic.net/blog/2018/11/30/sqlcipher-400-release/#compatability-sqlcipher-4-0-0
db.pragma('cipher_compatibility = 3');
migrateSchemaVersion(db);
db.close();
2021-10-26 22:59:08 +00:00
// After migrating user_version -> schema_version, we reopen database, because we can't
// migrate to the latest ciphers after we've modified the defaults.
db = new SQL(filePath);
keyDatabase(db, key);
2021-10-26 22:59:08 +00:00
db.pragma('cipher_migrate');
switchToWAL(db);
2021-10-26 22:59:08 +00:00
return db;
}
2021-10-26 22:59:08 +00:00
const INVALID_KEY = /[^0-9A-Fa-f]/;
function openAndSetUpSQLCipher(filePath: string, { key }: { key: string }) {
const match = INVALID_KEY.exec(key);
if (match) {
throw new Error(`setupSQLCipher: key '${key}' is not valid`);
}
2021-10-26 22:59:08 +00:00
const db = openAndMigrateDatabase(filePath, key);
// Because foreign key support is not enabled by default!
db.pragma('foreign_keys = ON');
2021-10-26 22:59:08 +00:00
return db;
}
let globalInstance: Database | undefined;
let logger = consoleLogger;
let globalInstanceRenderer: Database | undefined;
let databaseFilePath: string | undefined;
let indexedDBPath: string | undefined;
2023-01-18 22:12:33 +00:00
SQL.setLogHandler((code, value) => {
logger.warn(`Database log code=${code}: ${value}`);
});
async function initialize({
configDir,
key,
logger: suppliedLogger,
}: {
configDir: string;
key: string;
logger: LoggerType;
2021-10-26 22:59:08 +00:00
}): Promise<void> {
if (globalInstance) {
throw new Error('Cannot initialize more than once!');
}
if (!isString(configDir)) {
throw new Error('initialize: configDir is required!');
}
if (!isString(key)) {
throw new Error('initialize: key is required!');
}
logger = suppliedLogger;
indexedDBPath = join(configDir, 'IndexedDB');
const dbDir = join(configDir, 'sql');
mkdirSync(dbDir, { recursive: true });
databaseFilePath = join(dbDir, 'db.sqlite');
let db: Database | undefined;
2019-08-19 22:26:45 +00:00
try {
db = openAndSetUpSQLCipher(databaseFilePath, { key });
// For profiling use:
// db.pragma('cipher_profile=\'sqlcipher.log\'');
2021-10-26 22:59:08 +00:00
updateSchema(db, logger);
2019-08-19 22:26:45 +00:00
// At this point we can allow general access to the database
globalInstance = db;
2019-08-19 22:26:45 +00:00
// test database
2021-10-26 22:59:08 +00:00
getMessageCountSync();
} catch (error) {
logger.error('Database startup error:', error.stack);
if (db) {
db.close();
}
2021-03-04 21:44:57 +00:00
throw error;
}
}
2021-03-04 21:44:57 +00:00
async function initializeRenderer({
configDir,
key,
}: {
configDir: string;
key: string;
2021-10-26 22:59:08 +00:00
}): Promise<void> {
2021-03-04 21:44:57 +00:00
if (!isRenderer()) {
throw new Error('Cannot call from main process.');
}
if (globalInstanceRenderer) {
throw new Error('Cannot initialize more than once!');
}
if (!isString(configDir)) {
throw new Error('initialize: configDir is required!');
}
if (!isString(key)) {
throw new Error('initialize: key is required!');
}
if (!indexedDBPath) {
indexedDBPath = join(configDir, 'IndexedDB');
}
2021-03-04 21:44:57 +00:00
const dbDir = join(configDir, 'sql');
if (!databaseFilePath) {
databaseFilePath = join(dbDir, 'db.sqlite');
}
let promisified: Database | undefined;
2021-03-04 21:44:57 +00:00
try {
promisified = openAndSetUpSQLCipher(databaseFilePath, { key });
2021-03-04 21:44:57 +00:00
// At this point we can allow general access to the database
globalInstanceRenderer = promisified;
// test database
2021-10-26 22:59:08 +00:00
getMessageCountSync();
2021-03-04 21:44:57 +00:00
} catch (error) {
log.error('Database startup error:', error.stack);
2021-03-04 21:44:57 +00:00
throw error;
}
}
async function close(): Promise<void> {
2021-08-18 16:52:48 +00:00
for (const dbRef of [globalInstanceRenderer, globalInstance]) {
2021-08-17 21:55:34 +00:00
// SQLLite documentation suggests that we run `PRAGMA optimize` right
// before closing the database connection.
2021-08-18 16:52:48 +00:00
dbRef?.pragma('optimize');
2021-08-17 21:55:34 +00:00
2021-08-18 16:52:48 +00:00
dbRef?.close();
2021-08-17 21:55:34 +00:00
}
2021-04-06 17:29:22 +00:00
2021-08-18 16:52:48 +00:00
globalInstance = undefined;
globalInstanceRenderer = undefined;
}
async function removeDB(): Promise<void> {
if (globalInstance) {
try {
globalInstance.close();
} catch (error) {
logger.error('removeDB: Failed to close database:', error.stack);
}
globalInstance = undefined;
}
if (!databaseFilePath) {
throw new Error(
'removeDB: Cannot erase database without a databaseFilePath!'
);
}
logger.warn('removeDB: Removing all database files');
rimraf.sync(databaseFilePath);
rimraf.sync(`${databaseFilePath}-shm`);
rimraf.sync(`${databaseFilePath}-wal`);
}
async function removeIndexedDBFiles(): Promise<void> {
if (!indexedDBPath) {
throw new Error(
'removeIndexedDBFiles: Need to initialize and set indexedDBPath first!'
);
}
const pattern = join(indexedDBPath, '*.leveldb');
rimraf.sync(pattern);
indexedDBPath = undefined;
}
function getInstance(): Database {
2021-03-04 21:44:57 +00:00
if (isRenderer()) {
if (!globalInstanceRenderer) {
throw new Error('getInstance: globalInstanceRenderer not set!');
}
return globalInstanceRenderer;
}
if (!globalInstance) {
throw new Error('getInstance: globalInstance not set!');
}
return globalInstance;
}
2018-10-18 01:01:21 +00:00
const IDENTITY_KEYS_TABLE = 'identityKeys';
2022-07-28 16:35:29 +00:00
async function createOrUpdateIdentityKey(
data: StoredIdentityKeyType
): Promise<void> {
2021-10-26 22:59:08 +00:00
return createOrUpdate(getInstance(), IDENTITY_KEYS_TABLE, data);
2018-10-18 01:01:21 +00:00
}
async function getIdentityKeyById(
id: IdentityKeyIdType
2022-07-28 16:35:29 +00:00
): Promise<StoredIdentityKeyType | undefined> {
2021-10-26 22:59:08 +00:00
return getById(getInstance(), IDENTITY_KEYS_TABLE, id);
2018-10-18 01:01:21 +00:00
}
2021-10-26 22:59:08 +00:00
async function bulkAddIdentityKeys(
2022-07-28 16:35:29 +00:00
array: Array<StoredIdentityKeyType>
2021-10-26 22:59:08 +00:00
): Promise<void> {
return bulkAdd(getInstance(), IDENTITY_KEYS_TABLE, array);
2018-10-18 01:01:21 +00:00
}
async function removeIdentityKeyById(id: IdentityKeyIdType): Promise<void> {
2021-10-26 22:59:08 +00:00
return removeById(getInstance(), IDENTITY_KEYS_TABLE, id);
2018-10-18 01:01:21 +00:00
}
2021-10-26 22:59:08 +00:00
async function removeAllIdentityKeys(): Promise<void> {
return removeAllFromTable(getInstance(), IDENTITY_KEYS_TABLE);
2018-10-18 01:01:21 +00:00
}
2022-07-28 16:35:29 +00:00
async function getAllIdentityKeys(): Promise<Array<StoredIdentityKeyType>> {
2021-10-26 22:59:08 +00:00
return getAllFromTable(getInstance(), IDENTITY_KEYS_TABLE);
}
2018-10-18 01:01:21 +00:00
const PRE_KEYS_TABLE = 'preKeys';
2022-07-28 16:35:29 +00:00
async function createOrUpdatePreKey(data: StoredPreKeyType): Promise<void> {
2021-10-26 22:59:08 +00:00
return createOrUpdate(getInstance(), PRE_KEYS_TABLE, data);
2018-10-18 01:01:21 +00:00
}
async function getPreKeyById(
id: PreKeyIdType
2022-07-28 16:35:29 +00:00
): Promise<StoredPreKeyType | undefined> {
2021-10-26 22:59:08 +00:00
return getById(getInstance(), PRE_KEYS_TABLE, id);
2018-10-18 01:01:21 +00:00
}
2022-07-28 16:35:29 +00:00
async function bulkAddPreKeys(array: Array<StoredPreKeyType>): Promise<void> {
2021-10-26 22:59:08 +00:00
return bulkAdd(getInstance(), PRE_KEYS_TABLE, array);
2018-10-18 01:01:21 +00:00
}
async function removePreKeyById(id: PreKeyIdType): Promise<void> {
2021-10-26 22:59:08 +00:00
return removeById(getInstance(), PRE_KEYS_TABLE, id);
2018-10-18 01:01:21 +00:00
}
2022-07-28 16:35:29 +00:00
async function removePreKeysByUuid(uuid: UUIDStringType): Promise<void> {
const db = getInstance();
db.prepare<Query>('DELETE FROM preKeys WHERE ourUuid IS $uuid;').run({
uuid,
});
}
2021-10-26 22:59:08 +00:00
async function removeAllPreKeys(): Promise<void> {
return removeAllFromTable(getInstance(), PRE_KEYS_TABLE);
2018-10-18 01:01:21 +00:00
}
2022-07-28 16:35:29 +00:00
async function getAllPreKeys(): Promise<Array<StoredPreKeyType>> {
2021-10-26 22:59:08 +00:00
return getAllFromTable(getInstance(), PRE_KEYS_TABLE);
}
2018-10-18 01:01:21 +00:00
const SIGNED_PRE_KEYS_TABLE = 'signedPreKeys';
2021-10-26 22:59:08 +00:00
async function createOrUpdateSignedPreKey(
2022-07-28 16:35:29 +00:00
data: StoredSignedPreKeyType
2021-10-26 22:59:08 +00:00
): Promise<void> {
return createOrUpdate(getInstance(), SIGNED_PRE_KEYS_TABLE, data);
2018-10-18 01:01:21 +00:00
}
async function getSignedPreKeyById(
id: SignedPreKeyIdType
2022-07-28 16:35:29 +00:00
): Promise<StoredSignedPreKeyType | undefined> {
2021-10-26 22:59:08 +00:00
return getById(getInstance(), SIGNED_PRE_KEYS_TABLE, id);
2018-10-18 01:01:21 +00:00
}
2021-10-26 22:59:08 +00:00
async function bulkAddSignedPreKeys(
2022-07-28 16:35:29 +00:00
array: Array<StoredSignedPreKeyType>
2021-10-26 22:59:08 +00:00
): Promise<void> {
return bulkAdd(getInstance(), SIGNED_PRE_KEYS_TABLE, array);
2018-10-18 01:01:21 +00:00
}
async function removeSignedPreKeyById(id: SignedPreKeyIdType): Promise<void> {
2021-10-26 22:59:08 +00:00
return removeById(getInstance(), SIGNED_PRE_KEYS_TABLE, id);
2018-10-18 01:01:21 +00:00
}
2022-07-28 16:35:29 +00:00
async function removeSignedPreKeysByUuid(uuid: UUIDStringType): Promise<void> {
const db = getInstance();
db.prepare<Query>('DELETE FROM signedPreKeys WHERE ourUuid IS $uuid;').run({
uuid,
});
}
2021-10-26 22:59:08 +00:00
async function removeAllSignedPreKeys(): Promise<void> {
return removeAllFromTable(getInstance(), SIGNED_PRE_KEYS_TABLE);
2018-10-18 01:01:21 +00:00
}
2022-07-28 16:35:29 +00:00
async function getAllSignedPreKeys(): Promise<Array<StoredSignedPreKeyType>> {
const db = getInstance();
const rows: JSONRows = db
.prepare<EmptyQuery>(
`
SELECT json
FROM signedPreKeys
ORDER BY id ASC;
`
)
.all();
return rows.map(row => jsonToObject(row.json));
}
2018-10-18 01:01:21 +00:00
const ITEMS_TABLE = 'items';
2021-10-26 22:59:08 +00:00
async function createOrUpdateItem<K extends ItemKeyType>(
2022-07-28 16:35:29 +00:00
data: StoredItemType<K>
): Promise<void> {
2021-10-26 22:59:08 +00:00
return createOrUpdate(getInstance(), ITEMS_TABLE, data);
2018-10-18 01:01:21 +00:00
}
async function getItemById<K extends ItemKeyType>(
id: K
2022-07-28 16:35:29 +00:00
): Promise<StoredItemType<K> | undefined> {
2021-10-26 22:59:08 +00:00
return getById(getInstance(), ITEMS_TABLE, id);
2018-10-18 01:01:21 +00:00
}
2022-07-28 16:35:29 +00:00
async function getAllItems(): Promise<StoredAllItemsType> {
const db = getInstance();
const rows: JSONRows = db
.prepare<EmptyQuery>('SELECT json FROM items ORDER BY id ASC;')
.all();
2021-10-26 22:59:08 +00:00
type RawItemType = { id: ItemKeyType; value: unknown };
const items = rows.map(row => jsonToObject<RawItemType>(row.json));
2021-10-26 22:59:08 +00:00
const result: Record<ItemKeyType, unknown> = Object.create(null);
for (const { id, value } of items) {
2021-10-26 22:59:08 +00:00
result[id] = value;
}
2022-07-28 16:35:29 +00:00
return result as unknown as StoredAllItemsType;
2018-10-18 01:01:21 +00:00
}
async function removeItemById(id: ItemKeyType): Promise<void> {
2021-10-26 22:59:08 +00:00
return removeById(getInstance(), ITEMS_TABLE, id);
2018-10-18 01:01:21 +00:00
}
2021-10-26 22:59:08 +00:00
async function removeAllItems(): Promise<void> {
return removeAllFromTable(getInstance(), ITEMS_TABLE);
2018-10-18 01:01:21 +00:00
}
async function createOrUpdateSenderKey(key: SenderKeyType): Promise<void> {
createOrUpdateSenderKeySync(key);
}
function createOrUpdateSenderKeySync(key: SenderKeyType): void {
const db = getInstance();
prepare(
db,
`
INSERT OR REPLACE INTO senderKeys (
id,
senderId,
distributionId,
data,
lastUpdatedDate
) values (
$id,
$senderId,
$distributionId,
$data,
$lastUpdatedDate
)
`
).run(key);
}
async function getSenderKeyById(
id: SenderKeyIdType
): Promise<SenderKeyType | undefined> {
const db = getInstance();
const row = prepare(db, 'SELECT * FROM senderKeys WHERE id = $id').get({
id,
});
return row;
}
async function removeAllSenderKeys(): Promise<void> {
const db = getInstance();
prepare<EmptyQuery>(db, 'DELETE FROM senderKeys').run();
}
async function getAllSenderKeys(): Promise<Array<SenderKeyType>> {
const db = getInstance();
const rows = prepare<EmptyQuery>(db, 'SELECT * FROM senderKeys').all();
return rows;
}
async function removeSenderKeyById(id: SenderKeyIdType): Promise<void> {
2021-05-25 22:40:04 +00:00
const db = getInstance();
prepare(db, 'DELETE FROM senderKeys WHERE id = $id').run({ id });
}
async function insertSentProto(
proto: SentProtoType,
options: {
recipients: SentRecipientsType;
messageIds: SentMessagesType;
}
): Promise<number> {
const db = getInstance();
const { recipients, messageIds } = options;
// Note: we use `pluck` in this function to fetch only the first column of returned row.
return db.transaction(() => {
// 1. Insert the payload, fetching its primary key id
const info = prepare(
db,
`
INSERT INTO sendLogPayloads (
contentHint,
proto,
timestamp,
2022-08-15 21:53:33 +00:00
urgent,
hasPniSignatureMessage
) VALUES (
$contentHint,
$proto,
$timestamp,
2022-08-15 21:53:33 +00:00
$urgent,
$hasPniSignatureMessage
);
`
).run({
...proto,
urgent: proto.urgent ? 1 : 0,
2022-08-15 21:53:33 +00:00
hasPniSignatureMessage: proto.hasPniSignatureMessage ? 1 : 0,
});
const id = parseIntOrThrow(
info.lastInsertRowid,
'insertSentProto/lastInsertRowid'
);
// 2. Insert a record for each recipient device.
const recipientStatement = prepare(
db,
`
INSERT INTO sendLogRecipients (
payloadId,
recipientUuid,
deviceId
) VALUES (
$id,
$recipientUuid,
$deviceId
);
`
);
const recipientUuids = Object.keys(recipients);
for (const recipientUuid of recipientUuids) {
const deviceIds = recipients[recipientUuid];
for (const deviceId of deviceIds) {
recipientStatement.run({
id,
recipientUuid,
deviceId,
});
}
}
// 2. Insert a record for each message referenced by this payload.
const messageStatement = prepare(
db,
`
INSERT INTO sendLogMessageIds (
payloadId,
messageId
) VALUES (
$id,
$messageId
);
`
);
for (const messageId of new Set(messageIds)) {
messageStatement.run({
id,
messageId,
});
}
return id;
})();
}
async function deleteSentProtosOlderThan(timestamp: number): Promise<void> {
const db = getInstance();
prepare(
db,
`
DELETE FROM sendLogPayloads
WHERE
timestamp IS NULL OR
timestamp < $timestamp;
`
).run({
timestamp,
});
}
async function deleteSentProtoByMessageId(messageId: string): Promise<void> {
const db = getInstance();
prepare(
db,
`
DELETE FROM sendLogPayloads WHERE id IN (
SELECT payloadId FROM sendLogMessageIds
WHERE messageId = $messageId
);
`
).run({
messageId,
});
}
async function insertProtoRecipients({
id,
recipientUuid,
deviceIds,
}: {
id: number;
recipientUuid: string;
deviceIds: Array<number>;
}): Promise<void> {
const db = getInstance();
db.transaction(() => {
const statement = prepare(
db,
`
INSERT INTO sendLogRecipients (
payloadId,
recipientUuid,
deviceId
) VALUES (
$id,
$recipientUuid,
$deviceId
);
`
);
for (const deviceId of deviceIds) {
statement.run({
id,
recipientUuid,
deviceId,
});
}
})();
}
2021-08-31 21:35:01 +00:00
async function deleteSentProtoRecipient(
options:
| DeleteSentProtoRecipientOptionsType
| ReadonlyArray<DeleteSentProtoRecipientOptionsType>
2022-08-15 21:53:33 +00:00
): Promise<DeleteSentProtoRecipientResultType> {
const db = getInstance();
2021-08-31 21:35:01 +00:00
const items = Array.isArray(options) ? options : [options];
// Note: we use `pluck` in this function to fetch only the first column of
// returned row.
2022-08-15 21:53:33 +00:00
return db.transaction(() => {
const successfulPhoneNumberShares = new Array<string>();
2021-08-31 21:35:01 +00:00
for (const item of items) {
const { timestamp, recipientUuid, deviceId } = item;
2021-08-31 21:35:01 +00:00
// 1. Figure out what payload we're talking about.
const rows = prepare(
db,
`
2022-08-15 21:53:33 +00:00
SELECT sendLogPayloads.id, sendLogPayloads.hasPniSignatureMessage
FROM sendLogPayloads
2021-08-31 21:35:01 +00:00
INNER JOIN sendLogRecipients
ON sendLogRecipients.payloadId = sendLogPayloads.id
WHERE
sendLogPayloads.timestamp = $timestamp AND
sendLogRecipients.recipientUuid = $recipientUuid AND
sendLogRecipients.deviceId = $deviceId;
`
).all({ timestamp, recipientUuid, deviceId });
if (!rows.length) {
continue;
}
if (rows.length > 1) {
logger.warn(
2021-08-31 21:35:01 +00:00
'deleteSentProtoRecipient: More than one payload matches ' +
`recipient and timestamp ${timestamp}. Using the first.`
);
}
2022-08-15 21:53:33 +00:00
const { id, hasPniSignatureMessage } = rows[0];
2021-08-31 21:35:01 +00:00
// 2. Delete the recipient/device combination in question.
prepare(
db,
`
DELETE FROM sendLogRecipients
WHERE
payloadId = $id AND
recipientUuid = $recipientUuid AND
deviceId = $deviceId;
`
).run({ id, recipientUuid, deviceId });
2021-08-31 21:35:01 +00:00
// 3. See how many more recipient devices there were for this payload.
2022-08-15 21:53:33 +00:00
const remainingDevices = prepare(
db,
`
2023-01-17 21:07:21 +00:00
SELECT count(1) FROM sendLogRecipients
2022-08-15 21:53:33 +00:00
WHERE payloadId = $id AND recipientUuid = $recipientUuid;
`,
{ pluck: true }
).get({ id, recipientUuid });
2022-08-15 21:53:33 +00:00
// 4. If there are no remaining devices for this recipient and we included
// the pni signature in the proto - return the recipient to the caller.
if (remainingDevices === 0 && hasPniSignatureMessage) {
logger.info(
'deleteSentProtoRecipient: ' +
`Successfully shared phone number with ${recipientUuid} ` +
`through message ${timestamp}`
);
successfulPhoneNumberShares.push(recipientUuid);
}
strictAssert(
isNumber(remainingDevices),
'deleteSentProtoRecipient: select count() returned non-number!'
);
// 5. See how many more recipients there were for this payload.
const remainingTotal = prepare(
2021-08-31 21:35:01 +00:00
db,
'SELECT count(1) FROM sendLogRecipients WHERE payloadId = $id;',
{ pluck: true }
).get({ id });
2022-08-15 21:53:33 +00:00
strictAssert(
isNumber(remainingTotal),
'deleteSentProtoRecipient: select count() returned non-number!'
);
2022-08-15 21:53:33 +00:00
if (remainingTotal > 0) {
2021-08-31 21:35:01 +00:00
continue;
}
2022-08-15 21:53:33 +00:00
// 6. Delete the entire payload if there are no more recipients left.
logger.info(
2021-08-31 21:35:01 +00:00
'deleteSentProtoRecipient: ' +
`Deleting proto payload for timestamp ${timestamp}`
);
2022-08-15 21:53:33 +00:00
2021-08-31 21:35:01 +00:00
prepare(db, 'DELETE FROM sendLogPayloads WHERE id = $id;').run({
id,
});
}
2022-08-15 21:53:33 +00:00
return { successfulPhoneNumberShares };
})();
}
async function getSentProtoByRecipient({
now,
recipientUuid,
timestamp,
}: {
now: number;
recipientUuid: string;
timestamp: number;
}): Promise<SentProtoWithMessageIdsType | undefined> {
const db = getInstance();
const HOUR = 1000 * 60 * 60;
const oneDayAgo = now - HOUR * 24;
await deleteSentProtosOlderThan(oneDayAgo);
const row = prepare(
db,
`
SELECT
sendLogPayloads.*,
GROUP_CONCAT(DISTINCT sendLogMessageIds.messageId) AS messageIds
FROM sendLogPayloads
INNER JOIN sendLogRecipients ON sendLogRecipients.payloadId = sendLogPayloads.id
LEFT JOIN sendLogMessageIds ON sendLogMessageIds.payloadId = sendLogPayloads.id
WHERE
sendLogPayloads.timestamp = $timestamp AND
sendLogRecipients.recipientUuid = $recipientUuid
GROUP BY sendLogPayloads.id;
`
).get({
timestamp,
recipientUuid,
});
if (!row) {
return undefined;
}
const { messageIds } = row;
return {
...row,
urgent: isNumber(row.urgent) ? Boolean(row.urgent) : true,
2022-08-15 21:53:33 +00:00
hasPniSignatureMessage: isNumber(row.hasPniSignatureMessage)
? Boolean(row.hasPniSignatureMessage)
: true,
messageIds: messageIds ? messageIds.split(',') : [],
};
}
async function removeAllSentProtos(): Promise<void> {
const db = getInstance();
prepare<EmptyQuery>(db, 'DELETE FROM sendLogPayloads;').run();
}
async function getAllSentProtos(): Promise<Array<SentProtoType>> {
const db = getInstance();
const rows = prepare<EmptyQuery>(db, 'SELECT * FROM sendLogPayloads;').all();
return rows.map(row => ({
...row,
urgent: isNumber(row.urgent) ? Boolean(row.urgent) : true,
2022-08-15 21:53:33 +00:00
hasPniSignatureMessage: isNumber(row.hasPniSignatureMessage)
? Boolean(row.hasPniSignatureMessage)
: true,
}));
}
async function _getAllSentProtoRecipients(): Promise<
Array<SentRecipientsDBType>
> {
const db = getInstance();
const rows = prepare<EmptyQuery>(
db,
'SELECT * FROM sendLogRecipients;'
).all();
return rows;
}
async function _getAllSentProtoMessageIds(): Promise<Array<SentMessageDBType>> {
const db = getInstance();
const rows = prepare<EmptyQuery>(
db,
'SELECT * FROM sendLogMessageIds;'
).all();
return rows;
}
2018-10-18 01:01:21 +00:00
const SESSIONS_TABLE = 'sessions';
function createOrUpdateSessionSync(data: SessionType): void {
const db = getInstance();
const { id, conversationId, ourUuid, uuid } = data;
2018-10-18 01:01:21 +00:00
if (!id) {
throw new Error(
'createOrUpdateSession: Provided data did not have a truthy id'
);
}
if (!conversationId) {
2018-10-18 01:01:21 +00:00
throw new Error(
'createOrUpdateSession: Provided data did not have a truthy conversationId'
2018-10-18 01:01:21 +00:00
);
}
prepare(
db,
`
INSERT OR REPLACE INTO sessions (
2018-10-18 01:01:21 +00:00
id,
conversationId,
ourUuid,
uuid,
2018-10-18 01:01:21 +00:00
json
) values (
$id,
$conversationId,
$ourUuid,
$uuid,
2018-10-18 01:01:21 +00:00
$json
)
`
).run({
id,
conversationId,
ourUuid,
uuid,
json: objectToJSON(data),
});
2018-10-18 01:01:21 +00:00
}
async function createOrUpdateSession(data: SessionType): Promise<void> {
return createOrUpdateSessionSync(data);
}
async function createOrUpdateSessions(
array: Array<SessionType>
): Promise<void> {
const db = getInstance();
2019-09-26 19:56:31 +00:00
db.transaction(() => {
for (const item of array) {
assertSync(createOrUpdateSessionSync(item));
}
})();
2019-09-26 19:56:31 +00:00
}
async function commitDecryptResult({
senderKeys,
sessions,
unprocessed,
}: {
senderKeys: Array<SenderKeyType>;
sessions: Array<SessionType>;
unprocessed: Array<UnprocessedType>;
}): Promise<void> {
const db = getInstance();
db.transaction(() => {
for (const item of senderKeys) {
assertSync(createOrUpdateSenderKeySync(item));
}
for (const item of sessions) {
2021-05-24 21:30:56 +00:00
assertSync(createOrUpdateSessionSync(item));
}
for (const item of unprocessed) {
2021-05-24 21:30:56 +00:00
assertSync(saveUnprocessedSync(item));
}
})();
}
2021-10-26 22:59:08 +00:00
async function bulkAddSessions(array: Array<SessionType>): Promise<void> {
return bulkAdd(getInstance(), SESSIONS_TABLE, array);
2018-10-18 01:01:21 +00:00
}
async function removeSessionById(id: SessionIdType): Promise<void> {
2021-10-26 22:59:08 +00:00
return removeById(getInstance(), SESSIONS_TABLE, id);
2018-10-18 01:01:21 +00:00
}
async function removeSessionsByConversation(
conversationId: string
): Promise<void> {
const db = getInstance();
db.prepare<Query>(
`
DELETE FROM sessions
WHERE conversationId = $conversationId;
`
).run({
conversationId,
2018-10-18 01:01:21 +00:00
});
}
async function removeSessionsByUUID(uuid: UUIDStringType): Promise<void> {
const db = getInstance();
db.prepare<Query>(
`
DELETE FROM sessions
WHERE uuid = $uuid;
`
).run({
uuid,
});
}
2021-10-26 22:59:08 +00:00
async function removeAllSessions(): Promise<void> {
return removeAllFromTable(getInstance(), SESSIONS_TABLE);
}
2021-10-26 22:59:08 +00:00
async function getAllSessions(): Promise<Array<SessionType>> {
return getAllFromTable(getInstance(), SESSIONS_TABLE);
2018-10-18 01:01:21 +00:00
}
2021-10-26 22:59:08 +00:00
// Conversations
2018-10-18 01:01:21 +00:00
2021-10-26 22:59:08 +00:00
async function getConversationCount(): Promise<number> {
return getCountFromTable(getInstance(), 'conversations');
2018-10-18 01:01:21 +00:00
}
2021-10-26 22:59:08 +00:00
function getConversationMembersList({ members, membersV2 }: ConversationType) {
if (membersV2) {
return membersV2.map((item: GroupV2MemberType) => item.uuid).join(' ');
2018-10-18 01:01:21 +00:00
}
2021-10-26 22:59:08 +00:00
if (members) {
return members.join(' ');
2018-09-21 01:47:19 +00:00
}
2021-10-26 22:59:08 +00:00
return null;
2018-09-21 01:47:19 +00:00
}
function saveConversationSync(
data: ConversationType,
db = getInstance()
): void {
const {
active_at,
e164,
groupId,
id,
name,
profileFamilyName,
profileName,
profileLastFetchedAt,
type,
uuid,
} = data;
2018-09-21 01:47:19 +00:00
2021-10-26 22:59:08 +00:00
const membersList = getConversationMembersList(data);
2020-09-09 02:25:05 +00:00
db.prepare<Query>(
`
INSERT INTO conversations (
id,
json,
e164,
uuid,
groupId,
active_at,
type,
members,
name,
profileName,
profileFamilyName,
profileFullName,
profileLastFetchedAt
) values (
$id,
$json,
$e164,
$uuid,
$groupId,
$active_at,
$type,
$members,
$name,
$profileName,
$profileFamilyName,
$profileFullName,
$profileLastFetchedAt
);
`
).run({
2018-09-21 01:47:19 +00:00
id,
json: objectToJSON(
omit(data, ['profileLastFetchedAt', 'unblurredAvatarPath'])
),
2018-09-21 01:47:19 +00:00
e164: e164 || null,
uuid: uuid || null,
groupId: groupId || null,
active_at: active_at || null,
2018-09-21 01:47:19 +00:00
type,
members: membersList,
name: name || null,
profileName: profileName || null,
profileFamilyName: profileFamilyName || null,
profileFullName: combineNames(profileName, profileFamilyName) || null,
profileLastFetchedAt: profileLastFetchedAt || null,
});
2018-09-21 01:47:19 +00:00
}
async function saveConversation(
data: ConversationType,
db = getInstance()
): Promise<void> {
return saveConversationSync(data, db);
}
async function saveConversations(
arrayOfConversations: Array<ConversationType>
): Promise<void> {
const db = getInstance();
2018-09-21 01:47:19 +00:00
db.transaction(() => {
for (const conversation of arrayOfConversations) {
assertSync(saveConversationSync(conversation));
}
})();
2018-09-21 01:47:19 +00:00
}
2021-10-26 22:59:08 +00:00
function updateConversationSync(
data: ConversationType,
db = getInstance()
): void {
const {
id,
active_at,
type,
name,
profileName,
profileFamilyName,
profileLastFetchedAt,
e164,
uuid,
} = data;
2018-09-21 01:47:19 +00:00
2021-10-26 22:59:08 +00:00
const membersList = getConversationMembersList(data);
2020-09-09 02:25:05 +00:00
db.prepare(
`
UPDATE conversations SET
json = $json,
e164 = $e164,
uuid = $uuid,
active_at = $active_at,
type = $type,
members = $members,
name = $name,
profileName = $profileName,
profileFamilyName = $profileFamilyName,
profileFullName = $profileFullName,
profileLastFetchedAt = $profileLastFetchedAt
WHERE id = $id;
`
).run({
id,
json: objectToJSON(
omit(data, ['profileLastFetchedAt', 'unblurredAvatarPath'])
),
e164: e164 || null,
uuid: uuid || null,
active_at: active_at || null,
type,
members: membersList,
name: name || null,
profileName: profileName || null,
profileFamilyName: profileFamilyName || null,
profileFullName: combineNames(profileName, profileFamilyName) || null,
profileLastFetchedAt: profileLastFetchedAt || null,
});
2018-09-21 01:47:19 +00:00
}
2021-03-04 21:44:57 +00:00
async function updateConversation(data: ConversationType): Promise<void> {
return updateConversationSync(data);
}
async function updateConversations(
array: Array<ConversationType>
): Promise<void> {
const db = getInstance();
2019-09-26 19:56:31 +00:00
db.transaction(() => {
for (const item of array) {
assertSync(updateConversationSync(item));
}
})();
2019-09-26 19:56:31 +00:00
}
2018-09-21 01:47:19 +00:00
function removeConversationsSync(ids: ReadonlyArray<string>): void {
const db = getInstance();
// Our node interface doesn't seem to allow you to replace one single ? with an array
db.prepare<ArrayQuery>(
`
DELETE FROM conversations
WHERE id IN ( ${ids.map(() => '?').join(', ')} );
`
).run(ids);
}
async function removeConversation(id: Array<string> | string): Promise<void> {
2021-10-26 22:59:08 +00:00
const db = getInstance();
2018-09-21 01:47:19 +00:00
if (!Array.isArray(id)) {
db.prepare<Query>('DELETE FROM conversations WHERE id = $id;').run({
id,
});
2018-09-21 01:47:19 +00:00
return;
}
if (!id.length) {
throw new Error('removeConversation: No ids to delete!');
}
2021-10-26 22:59:08 +00:00
batchMultiVarQuery(db, id, removeConversationsSync);
2018-09-21 01:47:19 +00:00
}
async function _removeAllConversations(): Promise<void> {
const db = getInstance();
db.prepare<EmptyQuery>('DELETE from conversations;').run();
}
async function getConversationById(
id: string
): Promise<ConversationType | undefined> {
const db = getInstance();
const row: { json: string } = db
.prepare<Query>('SELECT json FROM conversations WHERE id = $id;')
.get({ id });
2018-09-21 01:47:19 +00:00
if (!row) {
return undefined;
2018-09-21 01:47:19 +00:00
}
return jsonToObject(row.json);
}
async function eraseStorageServiceStateFromConversations(): Promise<void> {
const db = getInstance();
db.prepare<EmptyQuery>(
`
UPDATE conversations
SET
json = json_remove(json, '$.storageID', '$.needsStorageServiceSync', '$.unknownFields', '$.storageProfileKey');
`
).run();
}
2021-10-26 22:59:08 +00:00
function getAllConversationsSync(db = getInstance()): Array<ConversationType> {
const rows: ConversationRows = db
.prepare<EmptyQuery>(
`
SELECT json, profileLastFetchedAt
FROM conversations
ORDER BY id ASC;
`
)
.all();
return rows.map(row => rowToConversation(row));
2018-09-21 01:47:19 +00:00
}
2021-10-26 22:59:08 +00:00
async function getAllConversations(): Promise<Array<ConversationType>> {
return getAllConversationsSync();
}
async function getAllConversationIds(): Promise<Array<string>> {
const db = getInstance();
const rows: Array<{ id: string }> = db
.prepare<EmptyQuery>(
`
SELECT id FROM conversations ORDER BY id ASC;
`
)
.all();
return rows.map(row => row.id);
2018-09-21 01:47:19 +00:00
}
2021-10-26 22:59:08 +00:00
async function getAllGroupsInvolvingUuid(
uuid: UUIDStringType
): Promise<Array<ConversationType>> {
const db = getInstance();
const rows: ConversationRows = db
.prepare<Query>(
`
SELECT json, profileLastFetchedAt
FROM conversations WHERE
type = 'group' AND
2021-10-26 22:59:08 +00:00
members LIKE $uuid
ORDER BY id ASC;
`
)
.all({
2021-10-26 22:59:08 +00:00
uuid: `%${uuid}%`,
});
2018-09-21 01:47:19 +00:00
return rows.map(row => rowToConversation(row));
2018-09-21 01:47:19 +00:00
}
async function searchMessages(
query: string,
params: { limit?: number; conversationId?: string } = {}
): Promise<Array<ServerSearchResultMessageType>> {
const { limit = 500, conversationId } = params;
const db = getInstance();
// sqlite queries with a join on a virtual table (like FTS5) are de-optimized
// and can't use indices for ordering results. Instead an in-memory index of
// the join rows is sorted on the fly, and this becomes substantially
// slower when there are large columns in it (like `messages.json`).
//
// Thus here we take an indirect approach and store `rowid`s in a temporary
// table for all messages that match the FTS query. Then we create another
// table to sort and limit the results, and finally join on it when fetch
// the snippets and json. The benefit of this is that the `ORDER BY` and
// `LIMIT` happen without virtual table and are thus covered by
// `messages_searchOrder` index.
return db.transaction(() => {
db.exec(
`
CREATE TEMP TABLE tmp_results(rowid INTEGER PRIMARY KEY ASC);
CREATE TEMP TABLE tmp_filtered_results(rowid INTEGER PRIMARY KEY ASC);
`
);
db.prepare<Query>(
`
INSERT INTO tmp_results (rowid)
SELECT
rowid
FROM
messages_fts
WHERE
messages_fts.body MATCH $query;
`
).run({ query });
2019-01-14 21:47:19 +00:00
if (conversationId === undefined) {
db.prepare<Query>(
`
INSERT INTO tmp_filtered_results (rowid)
SELECT
tmp_results.rowid
FROM
tmp_results
INNER JOIN
messages ON messages.rowid = tmp_results.rowid
ORDER BY messages.received_at DESC, messages.sent_at DESC
LIMIT $limit;
`
).run({ limit });
} else {
db.prepare<Query>(
`
INSERT INTO tmp_filtered_results (rowid)
SELECT
tmp_results.rowid
FROM
tmp_results
INNER JOIN
messages ON messages.rowid = tmp_results.rowid
WHERE
messages.conversationId = $conversationId
ORDER BY messages.received_at DESC, messages.sent_at DESC
LIMIT $limit;
`
).run({ conversationId, limit });
}
// The `MATCH` is necessary in order to for `snippet()` helper function to
// give us the right results. We can't call `snippet()` in the query above
// because it would bloat the temporary table with text data and we want
// to keep its size minimal for `ORDER BY` + `LIMIT` to be fast.
const result = db
.prepare<Query>(
`
SELECT
messages.json,
snippet(messages_fts, -1, '<<left>>', '<<right>>', '...', 10)
AS snippet
FROM tmp_filtered_results
INNER JOIN messages_fts
ON messages_fts.rowid = tmp_filtered_results.rowid
INNER JOIN messages
ON messages.rowid = tmp_filtered_results.rowid
WHERE
messages_fts.body MATCH $query
ORDER BY messages.received_at DESC, messages.sent_at DESC;
`
)
.all({ query });
db.exec(
`
DROP TABLE tmp_results;
DROP TABLE tmp_filtered_results;
`
);
return result;
})();
2019-01-14 21:47:19 +00:00
}
async function searchMessagesInConversation(
query: string,
conversationId: string,
{ limit = 100 }: { limit?: number } = {}
): Promise<Array<ServerSearchResultMessageType>> {
return searchMessages(query, { conversationId, limit });
2019-01-14 21:47:19 +00:00
}
2021-10-26 22:59:08 +00:00
function getMessageCountSync(
conversationId?: string,
db = getInstance()
): number {
if (conversationId === undefined) {
2021-10-26 22:59:08 +00:00
return getCountFromTable(db, 'messages');
}
2021-10-26 22:59:08 +00:00
const count = db
.prepare<Query>(
`
2023-01-17 21:07:21 +00:00
SELECT count(1)
FROM messages
WHERE conversationId = $conversationId;
`
)
2021-10-26 22:59:08 +00:00
.pluck()
.get({ conversationId });
2021-10-26 22:59:08 +00:00
return count;
}
2022-03-29 01:10:08 +00:00
async function getStoryCount(conversationId: string): Promise<number> {
const db = getInstance();
return db
.prepare<Query>(
`
2023-01-17 21:07:21 +00:00
SELECT count(1)
2022-03-29 01:10:08 +00:00
FROM messages
WHERE conversationId = $conversationId AND isStory = 1;
`
)
.pluck()
.get({ conversationId });
}
2021-10-26 22:59:08 +00:00
async function getMessageCount(conversationId?: string): Promise<number> {
return getMessageCountSync(conversationId);
}
// Note: we really only use this in 1:1 conversations, where story replies are always
// shown, so this has no need to be story-aware.
function hasUserInitiatedMessages(conversationId: string): boolean {
const db = getInstance();
2022-11-28 17:19:48 +00:00
const exists: number = db
.prepare<Query>(
`
2022-11-28 17:19:48 +00:00
SELECT EXISTS(
SELECT 1 FROM messages
2023-01-17 21:07:21 +00:00
INDEXED BY message_user_initiated
2022-11-28 17:19:48 +00:00
WHERE
2023-01-17 21:07:21 +00:00
conversationId IS $conversationId AND
isUserInitiatedMessage IS 1
2022-11-28 17:19:48 +00:00
);
`
)
2022-11-28 17:19:48 +00:00
.pluck()
.get({ conversationId });
2022-11-28 17:19:48 +00:00
return exists !== 0;
}
function saveMessageSync(
data: MessageType,
2021-10-26 22:59:08 +00:00
options: {
alreadyInTransaction?: boolean;
2021-10-26 22:59:08 +00:00
db?: Database;
2021-12-20 21:04:02 +00:00
forceSave?: boolean;
jobToInsert?: StoredJob;
ourUuid: UUIDStringType;
}
): string {
2021-10-26 22:59:08 +00:00
const {
alreadyInTransaction,
db = getInstance(),
2021-12-20 21:04:02 +00:00
forceSave,
jobToInsert,
ourUuid,
2021-10-26 22:59:08 +00:00
} = options;
if (!alreadyInTransaction) {
return db.transaction(() => {
return assertSync(
saveMessageSync(data, {
...options,
alreadyInTransaction: true,
})
);
})();
}
const {
2019-01-14 21:47:19 +00:00
body,
conversationId,
2021-12-20 21:04:02 +00:00
groupV2Change,
hasAttachments,
hasFileAttachments,
hasVisualMediaAttachments,
id,
2019-06-26 19:33:13 +00:00
isErased,
2019-08-05 20:53:15 +00:00
isViewOnce,
received_at,
schemaVersion,
sent_at,
serverGuid,
source,
sourceUuid,
sourceDevice,
storyId,
type,
readStatus,
expireTimer,
expirationStartTimestamp,
attachments,
} = data;
let { seenStatus } = data;
if (attachments) {
strictAssert(
attachments.every(attachment => !attachment.data),
'Attempting to save a hydrated message'
);
}
if (readStatus === ReadStatus.Unread && seenStatus !== SeenStatus.Unseen) {
log.warn(
`saveMessage: Message ${id}/${type} is unread but had seenStatus=${seenStatus}. Forcing to UnseenStatus.Unseen.`
);
// eslint-disable-next-line no-param-reassign
data = {
...data,
seenStatus: SeenStatus.Unseen,
};
seenStatus = SeenStatus.Unseen;
}
const payload = {
id,
json: objectToJSON(data),
body: body || null,
conversationId,
expirationStartTimestamp: expirationStartTimestamp || null,
expireTimer: expireTimer || null,
hasAttachments: hasAttachments ? 1 : 0,
hasFileAttachments: hasFileAttachments ? 1 : 0,
hasVisualMediaAttachments: hasVisualMediaAttachments ? 1 : 0,
2021-12-20 21:04:02 +00:00
isChangeCreatedByUs: groupV2Change?.from === ourUuid ? 1 : 0,
isErased: isErased ? 1 : 0,
isViewOnce: isViewOnce ? 1 : 0,
received_at: received_at || null,
schemaVersion: schemaVersion || 0,
serverGuid: serverGuid || null,
sent_at: sent_at || null,
source: source || null,
sourceUuid: sourceUuid || null,
sourceDevice: sourceDevice || null,
storyId: storyId || null,
type: type || null,
readStatus: readStatus ?? null,
seenStatus: seenStatus ?? SeenStatus.NotApplicable,
};
if (id && !forceSave) {
prepare(
db,
`
UPDATE messages SET
id = $id,
json = $json,
body = $body,
conversationId = $conversationId,
expirationStartTimestamp = $expirationStartTimestamp,
expireTimer = $expireTimer,
hasAttachments = $hasAttachments,
hasFileAttachments = $hasFileAttachments,
hasVisualMediaAttachments = $hasVisualMediaAttachments,
2021-12-20 21:04:02 +00:00
isChangeCreatedByUs = $isChangeCreatedByUs,
isErased = $isErased,
isViewOnce = $isViewOnce,
received_at = $received_at,
schemaVersion = $schemaVersion,
serverGuid = $serverGuid,
sent_at = $sent_at,
source = $source,
sourceUuid = $sourceUuid,
sourceDevice = $sourceDevice,
storyId = $storyId,
type = $type,
readStatus = $readStatus,
seenStatus = $seenStatus
WHERE id = $id;
`
).run(payload);
if (jobToInsert) {
insertJobSync(db, jobToInsert);
}
return id;
}
const toCreate = {
...data,
2021-10-26 22:59:08 +00:00
id: id || UUID.generate().toString(),
};
prepare(
db,
`
INSERT INTO messages (
id,
json,
body,
conversationId,
expirationStartTimestamp,
expireTimer,
hasAttachments,
hasFileAttachments,
hasVisualMediaAttachments,
2021-12-20 21:04:02 +00:00
isChangeCreatedByUs,
isErased,
isViewOnce,
received_at,
schemaVersion,
serverGuid,
sent_at,
source,
sourceUuid,
sourceDevice,
storyId,
type,
readStatus,
seenStatus
) values (
$id,
$json,
$body,
$conversationId,
$expirationStartTimestamp,
$expireTimer,
$hasAttachments,
$hasFileAttachments,
$hasVisualMediaAttachments,
2021-12-20 21:04:02 +00:00
$isChangeCreatedByUs,
$isErased,
$isViewOnce,
$received_at,
$schemaVersion,
$serverGuid,
$sent_at,
$source,
$sourceUuid,
$sourceDevice,
$storyId,
$type,
$readStatus,
$seenStatus
2021-07-09 21:38:51 +00:00
);
`
).run({
...payload,
id: toCreate.id,
json: objectToJSON(toCreate),
});
if (jobToInsert) {
insertJobSync(db, jobToInsert);
}
return toCreate.id;
}
async function saveMessage(
data: MessageType,
2021-12-20 21:04:02 +00:00
options: {
jobToInsert?: StoredJob;
forceSave?: boolean;
alreadyInTransaction?: boolean;
2021-12-20 21:04:02 +00:00
ourUuid: UUIDStringType;
}
): Promise<string> {
return saveMessageSync(data, options);
}
async function saveMessages(
arrayOfMessages: ReadonlyArray<MessageType>,
2021-12-20 21:04:02 +00:00
options: { forceSave?: boolean; ourUuid: UUIDStringType }
): Promise<void> {
const db = getInstance();
db.transaction(() => {
for (const message of arrayOfMessages) {
assertSync(
2021-12-20 21:04:02 +00:00
saveMessageSync(message, { ...options, alreadyInTransaction: true })
);
}
})();
}
async function removeMessage(id: string): Promise<void> {
const db = getInstance();
2021-02-04 20:46:55 +00:00
db.prepare<Query>('DELETE FROM messages WHERE id = $id;').run({ id });
2021-01-13 00:42:15 +00:00
}
function removeMessagesSync(ids: ReadonlyArray<string>): void {
2021-01-13 00:42:15 +00:00
const db = getInstance();
2021-02-04 20:46:55 +00:00
db.prepare<ArrayQuery>(
`
DELETE FROM messages
WHERE id IN ( ${ids.map(() => '?').join(', ')} );
`
).run(ids);
}
async function removeMessages(ids: ReadonlyArray<string>): Promise<void> {
2021-10-26 22:59:08 +00:00
batchMultiVarQuery(getInstance(), ids, removeMessagesSync);
}
async function getMessageById(id: string): Promise<MessageType | undefined> {
const db = getInstance();
2022-02-16 18:36:21 +00:00
return getMessageByIdSync(db, id);
}
export function getMessageByIdSync(
db: Database,
id: string
): MessageType | undefined {
const row = db
.prepare<Query>('SELECT json FROM messages WHERE id = $id;')
.get({
id,
});
if (!row) {
return undefined;
}
return jsonToObject(row.json);
}
async function getMessagesById(
messageIds: Array<string>
): Promise<Array<MessageType>> {
const db = getInstance();
return batchMultiVarQuery(
2021-10-26 22:59:08 +00:00
db,
messageIds,
(batch: ReadonlyArray<string>): Array<MessageType> => {
const query = db.prepare<ArrayQuery>(
`SELECT json FROM messages WHERE id IN (${Array(batch.length)
.fill('?')
.join(',')});`
);
const rows: JSONRows = query.all(batch);
return rows.map(row => jsonToObject(row.json));
}
);
}
async function _getAllMessages(): Promise<Array<MessageType>> {
const db = getInstance();
const rows: JSONRows = db
.prepare<EmptyQuery>('SELECT json FROM messages ORDER BY id ASC;')
.all();
return rows.map(row => jsonToObject(row.json));
2018-09-21 01:47:19 +00:00
}
async function _removeAllMessages(): Promise<void> {
const db = getInstance();
2023-01-26 23:53:22 +00:00
db.exec(`
DELETE FROM messages;
INSERT INTO messages_fts(messages_fts) VALUES('optimize');
`);
}
2018-09-21 01:47:19 +00:00
async function getAllMessageIds(): Promise<Array<string>> {
const db = getInstance();
const rows: Array<{ id: string }> = db
.prepare<EmptyQuery>('SELECT id FROM messages ORDER BY id ASC;')
.all();
return rows.map(row => row.id);
}
async function getMessageBySender({
source,
sourceUuid,
sourceDevice,
sent_at,
}: {
source?: string;
sourceUuid?: UUIDStringType;
sourceDevice?: number;
sent_at: number;
}): Promise<MessageType | undefined> {
const db = getInstance();
const rows: JSONRows = prepare(
db,
`
SELECT json FROM messages WHERE
(source = $source OR sourceUuid = $sourceUuid) AND
sourceDevice = $sourceDevice AND
sent_at = $sent_at
LIMIT 2;
`
).all({
source: source || null,
sourceUuid: sourceUuid || null,
sourceDevice: sourceDevice || null,
sent_at,
});
if (rows.length > 1) {
log.warn('getMessageBySender: More than one message found for', {
sent_at,
source,
sourceUuid,
sourceDevice,
});
}
if (rows.length < 1) {
return undefined;
}
return jsonToObject(rows[0].json);
}
2022-04-20 23:33:38 +00:00
export function _storyIdPredicate(
storyId: string | undefined,
includeStoryReplies: boolean
2022-04-20 23:33:38 +00:00
): string {
// This is unintuitive, but 'including story replies' means that we need replies to
// lots of different stories. So, we remove the storyId check with a clause that will
// always be true. We don't just return TRUE because we want to use our passed-in
// $storyId parameter.
if (includeStoryReplies && storyId === undefined) {
return '$storyId IS NULL';
}
2023-01-01 11:41:40 +00:00
// In contrast to: replies to a specific story
return 'storyId IS $storyId';
}
async function getUnreadByConversationAndMarkRead({
conversationId,
includeStoryReplies,
newestUnreadAt,
storyId,
readAt,
now = Date.now(),
}: {
conversationId: string;
includeStoryReplies: boolean;
newestUnreadAt: number;
storyId?: UUIDStringType;
readAt?: number;
now?: number;
2022-07-28 16:35:29 +00:00
}): Promise<GetUnreadByConversationAndMarkReadResultType> {
const db = getInstance();
return db.transaction(() => {
const expirationStartTimestamp = Math.min(now, readAt ?? Infinity);
2021-06-16 22:20:17 +00:00
db.prepare<Query>(
`
UPDATE messages
2021-06-29 16:45:31 +00:00
INDEXED BY expiring_message_by_conversation_and_received_at
2021-06-16 22:20:17 +00:00
SET
expirationStartTimestamp = $expirationStartTimestamp,
json = json_patch(json, $jsonPatch)
WHERE
conversationId = $conversationId AND
(${_storyIdPredicate(storyId, includeStoryReplies)}) AND
isStory IS 0 AND
type IS 'incoming' AND
2021-06-16 22:20:17 +00:00
(
expirationStartTimestamp IS NULL OR
expirationStartTimestamp > $expirationStartTimestamp
) AND
2021-12-20 21:04:02 +00:00
expireTimer > 0 AND
received_at <= $newestUnreadAt;
2021-06-16 22:20:17 +00:00
`
).run({
conversationId,
expirationStartTimestamp,
jsonPatch: JSON.stringify({ expirationStartTimestamp }),
newestUnreadAt,
storyId: storyId || null,
2021-06-16 22:20:17 +00:00
});
const rows = db
.prepare<Query>(
`
2021-06-29 16:45:31 +00:00
SELECT id, json FROM messages
WHERE
conversationId = $conversationId AND
seenStatus = ${SeenStatus.Unseen} AND
isStory = 0 AND
(${_storyIdPredicate(storyId, includeStoryReplies)}) AND
received_at <= $newestUnreadAt
ORDER BY received_at DESC, sent_at DESC;
`
)
.all({
conversationId,
newestUnreadAt,
storyId: storyId || null,
});
2021-05-07 21:50:14 +00:00
db.prepare<Query>(
`
UPDATE messages
SET
readStatus = ${ReadStatus.Read},
seenStatus = ${SeenStatus.Seen},
2021-05-07 21:50:14 +00:00
json = json_patch(json, $jsonPatch)
WHERE
conversationId = $conversationId AND
seenStatus = ${SeenStatus.Unseen} AND
isStory = 0 AND
(${_storyIdPredicate(storyId, includeStoryReplies)}) AND
received_at <= $newestUnreadAt;
`
2021-05-07 21:50:14 +00:00
).run({
conversationId,
jsonPatch: JSON.stringify({
readStatus: ReadStatus.Read,
seenStatus: SeenStatus.Seen,
}),
newestUnreadAt,
storyId: storyId || null,
2021-05-07 21:50:14 +00:00
});
return rows.map(row => {
2021-10-26 22:59:08 +00:00
const json = jsonToObject<MessageType>(row.json);
return {
originalReadStatus: json.readStatus,
readStatus: ReadStatus.Read,
seenStatus: SeenStatus.Seen,
2021-06-16 22:20:17 +00:00
...pick(json, [
'expirationStartTimestamp',
'id',
'sent_at',
'source',
'sourceUuid',
'type',
]),
};
});
})();
}
async function getUnreadReactionsAndMarkRead({
conversationId,
newestUnreadAt,
storyId,
}: {
conversationId: string;
newestUnreadAt: number;
storyId?: UUIDStringType;
}): Promise<Array<ReactionResultType>> {
const db = getInstance();
return db.transaction(() => {
const unreadMessages: Array<ReactionResultType> = db
.prepare<Query>(
`
2021-12-21 20:01:09 +00:00
SELECT reactions.rowid, targetAuthorUuid, targetTimestamp, messageId
FROM reactions
2023-01-17 21:07:21 +00:00
INDEXED BY reactions_unread
JOIN messages on messages.id IS reactions.messageId
WHERE
2023-01-17 21:07:21 +00:00
reactions.conversationId IS $conversationId AND
reactions.unread > 0 AND
messages.received_at <= $newestUnreadAt AND
messages.storyId IS $storyId
ORDER BY messageReceivedAt DESC;
`
)
.all({
conversationId,
newestUnreadAt,
storyId: storyId || null,
});
const idsToUpdate = unreadMessages.map(item => item.rowid);
batchMultiVarQuery(db, idsToUpdate, (ids: ReadonlyArray<number>): void => {
db.prepare<ArrayQuery>(
`
2023-01-17 21:07:21 +00:00
UPDATE reactions
SET unread = 0
WHERE rowid IN ( ${ids.map(() => '?').join(', ')} );
`
).run(ids);
});
return unreadMessages;
})();
}
async function markReactionAsRead(
targetAuthorUuid: string,
targetTimestamp: number
): Promise<ReactionType | undefined> {
const db = getInstance();
return db.transaction(() => {
const readReaction = db
.prepare(
`
SELECT *
FROM reactions
WHERE
targetAuthorUuid = $targetAuthorUuid AND
targetTimestamp = $targetTimestamp AND
unread = 1
ORDER BY rowId DESC
LIMIT 1;
`
)
.get({
targetAuthorUuid,
targetTimestamp,
});
db.prepare(
`
UPDATE reactions SET
unread = 0 WHERE
targetAuthorUuid = $targetAuthorUuid AND
targetTimestamp = $targetTimestamp;
`
).run({
targetAuthorUuid,
targetTimestamp,
});
return readReaction;
})();
}
async function addReaction({
conversationId,
emoji,
fromId,
messageId,
messageReceivedAt,
targetAuthorUuid,
targetTimestamp,
}: ReactionType): Promise<void> {
const db = getInstance();
await db
.prepare(
`INSERT INTO reactions (
conversationId,
emoji,
fromId,
messageId,
messageReceivedAt,
targetAuthorUuid,
targetTimestamp,
unread
) VALUES (
$conversationId,
$emoji,
$fromId,
$messageId,
$messageReceivedAt,
$targetAuthorUuid,
$targetTimestamp,
$unread
);`
)
.run({
conversationId,
emoji,
fromId,
messageId,
messageReceivedAt,
targetAuthorUuid,
targetTimestamp,
unread: 1,
});
}
async function removeReactionFromConversation({
emoji,
fromId,
targetAuthorUuid,
targetTimestamp,
}: {
emoji: string;
fromId: string;
targetAuthorUuid: string;
targetTimestamp: number;
}): Promise<void> {
const db = getInstance();
await db
.prepare(
`DELETE FROM reactions WHERE
emoji = $emoji AND
fromId = $fromId AND
targetAuthorUuid = $targetAuthorUuid AND
targetTimestamp = $targetTimestamp;`
)
.run({
emoji,
fromId,
targetAuthorUuid,
targetTimestamp,
});
}
async function _getAllReactions(): Promise<Array<ReactionType>> {
const db = getInstance();
return db.prepare<EmptyQuery>('SELECT * from reactions;').all();
}
async function _removeAllReactions(): Promise<void> {
const db = getInstance();
db.prepare<EmptyQuery>('DELETE from reactions;').run();
}
async function getOlderMessagesByConversation(
conversationId: string,
options: {
includeStoryReplies: boolean;
limit?: number;
messageId?: string;
receivedAt?: number;
sentAt?: number;
storyId: string | undefined;
}
): Promise<Array<MessageTypeUnhydrated>> {
return getOlderMessagesByConversationSync(conversationId, options);
}
function getOlderMessagesByConversationSync(
conversationId: string,
{
includeStoryReplies,
limit = 100,
messageId,
receivedAt = Number.MAX_VALUE,
sentAt = Number.MAX_VALUE,
storyId,
}: {
includeStoryReplies: boolean;
limit?: number;
messageId?: string;
receivedAt?: number;
sentAt?: number;
storyId: string | undefined;
}
): Array<MessageTypeUnhydrated> {
const db = getInstance();
return db
.prepare<Query>(
`
SELECT json FROM messages WHERE
conversationId = $conversationId AND
($messageId IS NULL OR id IS NOT $messageId) AND
isStory IS 0 AND
(${_storyIdPredicate(storyId, includeStoryReplies)}) AND
(
(received_at = $received_at AND sent_at < $sent_at) OR
received_at < $received_at
)
ORDER BY received_at DESC, sent_at DESC
LIMIT $limit;
`
)
.all({
conversationId,
limit,
messageId: messageId || null,
received_at: receivedAt,
sent_at: sentAt,
storyId: storyId || null,
})
.reverse();
}
async function getAllStories({
conversationId,
sourceUuid,
}: {
conversationId?: string;
2022-07-08 20:46:25 +00:00
sourceUuid?: UUIDStringType;
2022-11-28 17:19:48 +00:00
}): Promise<GetAllStoriesResultType> {
const db = getInstance();
2022-11-28 17:19:48 +00:00
const rows: ReadonlyArray<{
json: string;
hasReplies: number;
hasRepliesFromSelf: number;
}> = db
.prepare<Query>(
`
2022-11-28 17:19:48 +00:00
SELECT
json,
(SELECT EXISTS(
SELECT 1
FROM messages as replies
WHERE replies.storyId IS messages.id
)) as hasReplies,
(SELECT EXISTS(
SELECT 1
FROM messages AS selfReplies
WHERE
selfReplies.storyId IS messages.id AND
selfReplies.type IS 'outgoing'
)) as hasRepliesFromSelf
FROM messages
WHERE
type IS 'story' AND
($conversationId IS NULL OR conversationId IS $conversationId) AND
($sourceUuid IS NULL OR sourceUuid IS $sourceUuid)
ORDER BY received_at ASC, sent_at ASC;
`
)
.all({
conversationId: conversationId || null,
sourceUuid: sourceUuid || null,
});
2022-11-28 17:19:48 +00:00
return rows.map(row => ({
...jsonToObject(row.json),
hasReplies: row.hasReplies !== 0,
hasRepliesFromSelf: row.hasRepliesFromSelf !== 0,
}));
}
async function getNewerMessagesByConversation(
conversationId: string,
options: {
includeStoryReplies: boolean;
limit?: number;
receivedAt?: number;
sentAt?: number;
storyId: UUIDStringType | undefined;
}
): Promise<Array<MessageTypeUnhydrated>> {
return getNewerMessagesByConversationSync(conversationId, options);
}
function getNewerMessagesByConversationSync(
conversationId: string,
{
includeStoryReplies,
limit = 100,
receivedAt = 0,
sentAt = 0,
storyId,
}: {
includeStoryReplies: boolean;
limit?: number;
receivedAt?: number;
sentAt?: number;
storyId: UUIDStringType | undefined;
}
): Array<MessageTypeUnhydrated> {
const db = getInstance();
const rows: JSONRows = db
.prepare<Query>(
`
SELECT json FROM messages WHERE
conversationId = $conversationId AND
isStory IS 0 AND
(${_storyIdPredicate(storyId, includeStoryReplies)}) AND
(
(received_at = $received_at AND sent_at > $sent_at) OR
received_at > $received_at
)
ORDER BY received_at ASC, sent_at ASC
LIMIT $limit;
`
)
.all({
conversationId,
limit,
received_at: receivedAt,
sent_at: sentAt,
storyId: storyId || null,
});
2021-07-09 21:38:51 +00:00
return rows;
}
function getOldestMessageForConversation(
conversationId: string,
{
storyId,
includeStoryReplies,
}: {
storyId?: UUIDStringType;
includeStoryReplies: boolean;
}
): MessageMetricsType | undefined {
const db = getInstance();
const row = db
.prepare<Query>(
`
2023-01-27 17:47:24 +00:00
SELECT received_at, sent_at, id FROM messages WHERE
conversationId = $conversationId AND
isStory IS 0 AND
(${_storyIdPredicate(storyId, includeStoryReplies)})
ORDER BY received_at ASC, sent_at ASC
LIMIT 1;
`
)
.get({
conversationId,
storyId: storyId || null,
});
if (!row) {
return undefined;
}
return row;
}
function getNewestMessageForConversation(
conversationId: string,
{
storyId,
includeStoryReplies,
}: {
storyId?: UUIDStringType;
includeStoryReplies: boolean;
}
): MessageMetricsType | undefined {
const db = getInstance();
const row = db
.prepare<Query>(
`
2023-01-27 17:47:24 +00:00
SELECT received_at, sent_at, id FROM messages WHERE
conversationId = $conversationId AND
isStory IS 0 AND
(${_storyIdPredicate(storyId, includeStoryReplies)})
ORDER BY received_at DESC, sent_at DESC
LIMIT 1;
`
)
.get({
conversationId,
storyId: storyId || null,
});
if (!row) {
return undefined;
}
return row;
}
2020-08-07 00:50:54 +00:00
function getLastConversationActivity({
conversationId,
includeStoryReplies,
2021-10-26 22:59:08 +00:00
ourUuid,
}: {
conversationId: string;
includeStoryReplies: boolean;
2021-10-26 22:59:08 +00:00
ourUuid: UUIDStringType;
}): MessageType | undefined {
2020-08-07 00:50:54 +00:00
const db = getInstance();
const row = prepare(
db,
`
SELECT json FROM messages
2023-01-17 21:07:21 +00:00
INDEXED BY messages_activity
WHERE
2023-01-17 21:07:21 +00:00
conversationId IS $conversationId AND
2021-12-20 21:04:02 +00:00
shouldAffectActivity IS 1 AND
isTimerChangeFromSync IS 0 AND
${includeStoryReplies ? '' : 'storyId IS NULL AND'}
2021-12-20 21:04:02 +00:00
isGroupLeaveEventFromOther IS 0
ORDER BY received_at DESC, sent_at DESC
LIMIT 1;
`
).get({
conversationId,
2021-10-26 22:59:08 +00:00
ourUuid,
});
2020-08-07 00:50:54 +00:00
if (!row) {
return undefined;
2020-08-07 00:50:54 +00:00
}
return jsonToObject(row.json);
2020-08-07 00:50:54 +00:00
}
function getLastConversationPreview({
conversationId,
includeStoryReplies,
}: {
conversationId: string;
includeStoryReplies: boolean;
}): MessageType | undefined {
type Row = Readonly<{
json: string;
}>;
2020-08-07 00:50:54 +00:00
const db = getInstance();
2023-01-27 17:47:24 +00:00
const index = includeStoryReplies
? 'messages_preview'
: 'messages_preview_without_story';
const row: Row | undefined = prepare(
db,
`
2023-01-27 17:47:24 +00:00
SELECT json FROM (
SELECT json, expiresAt FROM messages
INDEXED BY ${index}
WHERE
conversationId IS $conversationId AND
shouldAffectPreview IS 1 AND
isGroupLeaveEventFromOther IS 0
${includeStoryReplies ? '' : 'AND storyId IS NULL'}
ORDER BY received_at DESC, sent_at DESC
)
WHERE likely(expiresAt > $now)
LIMIT 1
`
).get({
conversationId,
now: Date.now(),
});
2020-08-07 00:50:54 +00:00
return row ? jsonToObject(row.json) : undefined;
2020-08-07 00:50:54 +00:00
}
async function getConversationMessageStats({
conversationId,
includeStoryReplies,
2021-10-26 22:59:08 +00:00
ourUuid,
}: {
conversationId: string;
includeStoryReplies: boolean;
2021-10-26 22:59:08 +00:00
ourUuid: UUIDStringType;
}): Promise<ConversationMessageStatsType> {
const db = getInstance();
return db.transaction(() => {
return {
activity: getLastConversationActivity({
conversationId,
includeStoryReplies,
2021-10-26 22:59:08 +00:00
ourUuid,
}),
preview: getLastConversationPreview({
conversationId,
includeStoryReplies,
}),
hasUserInitiatedMessages: hasUserInitiatedMessages(conversationId),
};
})();
}
async function getLastConversationMessage({
conversationId,
}: {
conversationId: string;
}): Promise<MessageType | undefined> {
const db = getInstance();
const row = db
.prepare<Query>(
`
2023-01-27 17:47:24 +00:00
SELECT json FROM messages WHERE
conversationId = $conversationId
ORDER BY received_at DESC, sent_at DESC
LIMIT 1;
`
)
.get({
conversationId,
});
if (!row) {
return undefined;
}
return jsonToObject(row.json);
}
function getOldestUnseenMessageForConversation(
conversationId: string,
{
storyId,
includeStoryReplies,
}: {
storyId?: UUIDStringType;
includeStoryReplies: boolean;
}
): MessageMetricsType | undefined {
const db = getInstance();
const row = db
.prepare<Query>(
`
2023-01-27 17:47:24 +00:00
SELECT received_at, sent_at, id FROM messages WHERE
conversationId = $conversationId AND
seenStatus = ${SeenStatus.Unseen} AND
isStory IS 0 AND
(${_storyIdPredicate(storyId, includeStoryReplies)})
ORDER BY received_at ASC, sent_at ASC
LIMIT 1;
`
)
.get({
conversationId,
storyId: storyId || null,
});
if (!row) {
return undefined;
}
return row;
}
async function getTotalUnreadForConversation(
conversationId: string,
options: {
storyId: UUIDStringType | undefined;
includeStoryReplies: boolean;
}
): Promise<number> {
return getTotalUnreadForConversationSync(conversationId, options);
}
function getTotalUnreadForConversationSync(
conversationId: string,
{
storyId,
includeStoryReplies,
}: {
storyId: UUIDStringType | undefined;
includeStoryReplies: boolean;
}
): number {
const db = getInstance();
const row = db
.prepare<Query>(
`
2023-01-17 21:07:21 +00:00
SELECT count(1)
FROM messages
WHERE
conversationId = $conversationId AND
readStatus = ${ReadStatus.Unread} AND
isStory IS 0 AND
(${_storyIdPredicate(storyId, includeStoryReplies)})
`
)
2023-01-17 21:07:21 +00:00
.pluck()
.get({
conversationId,
storyId: storyId || null,
});
2023-01-17 21:07:21 +00:00
return row;
}
function getTotalUnseenForConversationSync(
conversationId: string,
{
storyId,
includeStoryReplies,
}: {
storyId?: UUIDStringType;
includeStoryReplies: boolean;
}
): number {
const db = getInstance();
const row = db
.prepare<Query>(
`
2023-01-17 21:07:21 +00:00
SELECT count(1)
FROM messages
WHERE
conversationId = $conversationId AND
seenStatus = ${SeenStatus.Unseen} AND
isStory IS 0 AND
(${_storyIdPredicate(storyId, includeStoryReplies)})
`
)
2023-01-17 21:07:21 +00:00
.pluck()
.get({
conversationId,
storyId: storyId || null,
});
2023-01-17 21:07:21 +00:00
return row;
}
async function getMessageMetricsForConversation(
conversationId: string,
options: {
storyId?: UUIDStringType;
includeStoryReplies: boolean;
}
): Promise<ConversationMetricsType> {
return getMessageMetricsForConversationSync(conversationId, options);
}
function getMessageMetricsForConversationSync(
conversationId: string,
options: {
storyId?: UUIDStringType;
includeStoryReplies: boolean;
}
): ConversationMetricsType {
const oldest = getOldestMessageForConversation(conversationId, options);
const newest = getNewestMessageForConversation(conversationId, options);
const oldestUnseen = getOldestUnseenMessageForConversation(
conversationId,
options
);
const totalUnseen = getTotalUnseenForConversationSync(
conversationId,
options
);
return {
oldest: oldest ? pick(oldest, ['received_at', 'sent_at', 'id']) : undefined,
newest: newest ? pick(newest, ['received_at', 'sent_at', 'id']) : undefined,
oldestUnseen: oldestUnseen
? pick(oldestUnseen, ['received_at', 'sent_at', 'id'])
: undefined,
totalUnseen,
};
}
async function getConversationRangeCenteredOnMessage({
conversationId,
includeStoryReplies,
limit,
messageId,
receivedAt,
sentAt,
storyId,
}: {
conversationId: string;
includeStoryReplies: boolean;
limit?: number;
messageId: string;
receivedAt: number;
sentAt?: number;
storyId: UUIDStringType | undefined;
2022-07-28 16:35:29 +00:00
}): Promise<
GetConversationRangeCenteredOnMessageResultType<MessageTypeUnhydrated>
> {
const db = getInstance();
return db.transaction(() => {
return {
older: getOlderMessagesByConversationSync(conversationId, {
includeStoryReplies,
limit,
messageId,
receivedAt,
sentAt,
storyId,
}),
newer: getNewerMessagesByConversationSync(conversationId, {
includeStoryReplies,
limit,
receivedAt,
sentAt,
storyId,
}),
metrics: getMessageMetricsForConversationSync(conversationId, {
storyId,
includeStoryReplies,
}),
};
})();
}
2023-01-10 00:52:01 +00:00
async function getCallHistoryMessageByCallId(
conversationId: string,
callId: string
): Promise<string | void> {
const db = getInstance();
const id: string | void = db
.prepare<Query>(
`
SELECT id
FROM messages
WHERE conversationId = $conversationId
AND type = 'call-history'
AND callMode = 'Direct'
AND callId = $callId
`
)
.pluck()
.get({
conversationId,
callId,
});
return id;
}
async function hasGroupCallHistoryMessage(
conversationId: string,
eraId: string
): Promise<boolean> {
const db = getInstance();
2022-11-28 17:19:48 +00:00
const exists: number = db
.prepare<Query>(
`
2022-11-28 17:19:48 +00:00
SELECT EXISTS(
SELECT 1 FROM messages
WHERE conversationId = $conversationId
AND type = 'call-history'
AND json_extract(json, '$.callHistoryDetails.callMode') = 'Group'
AND json_extract(json, '$.callHistoryDetails.eraId') = $eraId
);
`
)
2022-11-28 17:19:48 +00:00
.pluck()
.get({
conversationId,
eraId,
});
2022-11-28 17:19:48 +00:00
return exists !== 0;
}
async function migrateConversationMessages(
obsoleteId: string,
currentId: string
): Promise<void> {
const db = getInstance();
db.prepare<Query>(
`
UPDATE messages SET
conversationId = $currentId,
json = json_set(json, '$.conversationId', $currentId)
WHERE conversationId = $obsoleteId;
`
).run({
obsoleteId,
currentId,
});
}
async function getMessagesBySentAt(
sentAt: number
): Promise<Array<MessageType>> {
const db = getInstance();
const rows: JSONRows = db
.prepare<Query>(
`
SELECT json FROM messages
WHERE sent_at = $sent_at
ORDER BY received_at DESC, sent_at DESC;
`
)
.all({
sent_at: sentAt,
});
return rows.map(row => jsonToObject(row.json));
}
async function getExpiredMessages(): Promise<Array<MessageType>> {
const db = getInstance();
const now = Date.now();
const rows: JSONRows = db
.prepare<Query>(
`
SELECT json FROM messages WHERE
2021-06-16 22:20:17 +00:00
expiresAt <= $now
ORDER BY expiresAt ASC;
`
)
2021-06-16 22:20:17 +00:00
.all({ now });
return rows.map(row => jsonToObject(row.json));
}
async function getMessagesUnexpectedlyMissingExpirationStartTimestamp(): Promise<
2021-06-16 22:20:17 +00:00
Array<MessageType>
> {
const db = getInstance();
const rows: JSONRows = db
.prepare<EmptyQuery>(
`
SELECT json FROM messages
INDEXED BY messages_unexpectedly_missing_expiration_start_timestamp
WHERE
expireTimer > 0 AND
2021-06-16 22:20:17 +00:00
expirationStartTimestamp IS NULL AND
(
type IS 'outgoing' OR
(type IS 'incoming' AND (
readStatus = ${ReadStatus.Read} OR
readStatus = ${ReadStatus.Viewed} OR
readStatus IS NULL
))
);
`
)
.all();
return rows.map(row => jsonToObject(row.json));
}
2021-06-16 22:20:17 +00:00
async function getSoonestMessageExpiry(): Promise<undefined | number> {
const db = getInstance();
2021-06-16 22:20:17 +00:00
// Note: we use `pluck` to only get the first column.
const result: null | number = db
.prepare<EmptyQuery>(
`
2021-06-16 22:20:17 +00:00
SELECT MIN(expiresAt)
FROM messages;
`
)
2021-06-16 22:20:17 +00:00
.pluck(true)
.get();
2023-01-27 17:47:24 +00:00
if (result != null && result >= Number.MAX_SAFE_INTEGER) {
return undefined;
}
2021-06-16 22:20:17 +00:00
return result || undefined;
}
async function getNextTapToViewMessageTimestampToAgeOut(): Promise<
undefined | number
> {
const db = getInstance();
const row = db
.prepare<EmptyQuery>(
`
SELECT json FROM messages
WHERE
isViewOnce = 1
AND (isErased IS NULL OR isErased != 1)
ORDER BY received_at ASC, sent_at ASC
LIMIT 1;
`
)
.get();
2019-06-26 19:33:13 +00:00
if (!row) {
return undefined;
2019-06-26 19:33:13 +00:00
}
2021-10-26 22:59:08 +00:00
const data = jsonToObject<MessageType>(row.json);
const result = data.received_at_ms || data.received_at;
return isNormalNumber(result) ? result : undefined;
2019-06-26 19:33:13 +00:00
}
async function getTapToViewMessagesNeedingErase(): Promise<Array<MessageType>> {
const db = getInstance();
2019-06-26 19:33:13 +00:00
const THIRTY_DAYS_AGO = Date.now() - 30 * 24 * 60 * 60 * 1000;
const rows: JSONRows = db
.prepare<Query>(
`
SELECT json
FROM messages
WHERE
isViewOnce = 1
AND (isErased IS NULL OR isErased != 1)
AND received_at <= $THIRTY_DAYS_AGO
ORDER BY received_at ASC, sent_at ASC;
`
)
.all({
THIRTY_DAYS_AGO,
});
2019-06-26 19:33:13 +00:00
return rows.map(row => jsonToObject(row.json));
2019-06-26 19:33:13 +00:00
}
2021-09-17 23:11:24 +00:00
const MAX_UNPROCESSED_ATTEMPTS = 3;
function saveUnprocessedSync(data: UnprocessedType): string {
const db = getInstance();
const {
id,
timestamp,
receivedAtCounter,
version,
attempts,
envelope,
source,
sourceUuid,
sourceDevice,
serverGuid,
serverTimestamp,
decrypted,
urgent,
story,
} = data;
if (!id) {
2021-05-27 15:45:45 +00:00
throw new Error('saveUnprocessedSync: id was falsey');
}
if (attempts > MAX_UNPROCESSED_ATTEMPTS) {
logger.warn(
`saveUnprocessedSync: not saving ${id} due to exhausted attempts`
);
2021-09-17 23:11:24 +00:00
removeUnprocessedSync(id);
return id;
}
prepare(
db,
`
INSERT OR REPLACE INTO unprocessed (
id,
timestamp,
receivedAtCounter,
version,
attempts,
envelope,
source,
sourceUuid,
sourceDevice,
serverGuid,
serverTimestamp,
decrypted,
urgent,
story
) values (
$id,
$timestamp,
$receivedAtCounter,
$version,
$attempts,
$envelope,
$source,
$sourceUuid,
$sourceDevice,
$serverGuid,
$serverTimestamp,
$decrypted,
$urgent,
$story
);
`
).run({
id,
timestamp,
receivedAtCounter: receivedAtCounter ?? null,
version,
attempts,
envelope: envelope || null,
source: source || null,
sourceUuid: sourceUuid || null,
sourceDevice: sourceDevice || null,
serverGuid: serverGuid || null,
serverTimestamp: serverTimestamp || null,
decrypted: decrypted || null,
urgent: urgent || !isBoolean(urgent) ? 1 : 0,
story: story ? 1 : 0,
});
return id;
}
function updateUnprocessedWithDataSync(
id: string,
data: UnprocessedUpdateType
): void {
const db = getInstance();
const {
source,
sourceUuid,
sourceDevice,
serverGuid,
serverTimestamp,
decrypted,
} = data;
prepare(
db,
`
UPDATE unprocessed SET
source = $source,
sourceUuid = $sourceUuid,
sourceDevice = $sourceDevice,
serverGuid = $serverGuid,
serverTimestamp = $serverTimestamp,
decrypted = $decrypted
WHERE id = $id;
`
).run({
id,
source: source || null,
sourceUuid: sourceUuid || null,
sourceDevice: sourceDevice || null,
serverGuid: serverGuid || null,
serverTimestamp: serverTimestamp || null,
decrypted: decrypted || null,
});
}
async function updateUnprocessedWithData(
id: string,
data: UnprocessedUpdateType
): Promise<void> {
return updateUnprocessedWithDataSync(id, data);
}
async function updateUnprocessedsWithData(
arrayOfUnprocessed: Array<{ id: string; data: UnprocessedUpdateType }>
): Promise<void> {
const db = getInstance();
2019-09-26 19:56:31 +00:00
db.transaction(() => {
for (const { id, data } of arrayOfUnprocessed) {
assertSync(updateUnprocessedWithDataSync(id, data));
}
})();
2019-09-26 19:56:31 +00:00
}
async function getUnprocessedById(
id: string
): Promise<UnprocessedType | undefined> {
const db = getInstance();
const row = db
.prepare<Query>('SELECT * FROM unprocessed WHERE id = $id;')
.get({
id,
});
return {
...row,
urgent: isNumber(row.urgent) ? Boolean(row.urgent) : true,
story: Boolean(row.story),
};
}
async function getUnprocessedCount(): Promise<number> {
2021-10-26 22:59:08 +00:00
return getCountFromTable(getInstance(), 'unprocessed');
}
async function getAllUnprocessedIds(): Promise<Array<string>> {
log.info('getAllUnprocessedIds');
const db = getInstance();
2021-12-14 01:25:44 +00:00
return db.transaction(() => {
// cleanup first
const { changes: deletedStaleCount } = db
.prepare<Query>('DELETE FROM unprocessed WHERE timestamp < $monthAgo')
.run({
monthAgo: Date.now() - durations.MONTH,
});
2021-12-14 01:25:44 +00:00
if (deletedStaleCount !== 0) {
logger.warn(
'getAllUnprocessedAndIncrementAttempts: ' +
`deleting ${deletedStaleCount} old unprocessed envelopes`
);
}
2021-12-14 01:25:44 +00:00
const { changes: deletedInvalidCount } = db
.prepare<Query>(
`
DELETE FROM unprocessed
WHERE attempts >= $MAX_UNPROCESSED_ATTEMPTS
`
)
.run({ MAX_UNPROCESSED_ATTEMPTS });
if (deletedInvalidCount !== 0) {
logger.warn(
'getAllUnprocessedAndIncrementAttempts: ' +
`deleting ${deletedInvalidCount} invalid unprocessed envelopes`
);
}
return db
.prepare<EmptyQuery>(
`
SELECT id
FROM unprocessed
ORDER BY receivedAtCounter ASC
`
)
.pluck()
.all();
})();
}
async function getUnprocessedByIdsAndIncrementAttempts(
ids: ReadonlyArray<string>
): Promise<Array<UnprocessedType>> {
log.info('getUnprocessedByIdsAndIncrementAttempts', { totalIds: ids.length });
const db = getInstance();
batchMultiVarQuery(db, ids, batch => {
return db
.prepare<ArrayQuery>(
`
UPDATE unprocessed
SET attempts = attempts + 1
WHERE id IN (${batch.map(() => '?').join(', ')})
`
)
.run(batch);
});
return batchMultiVarQuery(db, ids, batch => {
return db
.prepare<ArrayQuery>(
`
SELECT *
FROM unprocessed
WHERE id IN (${batch.map(() => '?').join(', ')})
ORDER BY receivedAtCounter ASC;
`
)
.all(batch)
.map(row => ({
...row,
urgent: isNumber(row.urgent) ? Boolean(row.urgent) : true,
story: Boolean(row.story),
}));
});
}
function removeUnprocessedsSync(ids: ReadonlyArray<string>): void {
log.info('removeUnprocessedsSync', { totalIds: ids.length });
const db = getInstance();
db.prepare<ArrayQuery>(
`
DELETE FROM unprocessed
WHERE id IN ( ${ids.map(() => '?').join(', ')} );
`
).run(ids);
}
2021-09-17 23:11:24 +00:00
function removeUnprocessedSync(id: string | Array<string>): void {
log.info('removeUnprocessedSync', { id });
2021-10-26 22:59:08 +00:00
const db = getInstance();
2021-10-26 22:59:08 +00:00
if (!Array.isArray(id)) {
prepare(db, 'DELETE FROM unprocessed WHERE id = $id;').run({ id });
return;
}
// This can happen normally due to flushing of `cacheRemoveBatcher` in
// MessageReceiver.
if (!id.length) {
return;
}
2021-10-26 22:59:08 +00:00
assertSync(batchMultiVarQuery(db, id, removeUnprocessedsSync));
2021-09-17 23:11:24 +00:00
}
async function removeUnprocessed(id: string | Array<string>): Promise<void> {
removeUnprocessedSync(id);
}
async function removeAllUnprocessed(): Promise<void> {
const db = getInstance();
db.prepare<EmptyQuery>('DELETE FROM unprocessed;').run();
}
// Attachment Downloads
const ATTACHMENT_DOWNLOADS_TABLE = 'attachment_downloads';
async function getAttachmentDownloadJobById(
id: string
): Promise<AttachmentDownloadJobType | undefined> {
return getById(getInstance(), ATTACHMENT_DOWNLOADS_TABLE, id);
}
async function getNextAttachmentDownloadJobs(
limit?: number,
options: { timestamp?: number } = {}
): Promise<Array<AttachmentDownloadJobType>> {
const db = getInstance();
const timestamp =
options && options.timestamp ? options.timestamp : Date.now();
const rows: Array<{ json: string; id: string }> = db
.prepare<Query>(
`
SELECT id, json
FROM attachment_downloads
2021-06-01 17:13:10 +00:00
WHERE pending = 0 AND timestamp <= $timestamp
ORDER BY timestamp DESC
LIMIT $limit;
`
)
.all({
limit: limit || 3,
timestamp,
});
const INNER_ERROR = 'jsonToObject error';
try {
return rows.map(row => {
try {
return jsonToObject(row.json);
} catch (error) {
logger.error(
`getNextAttachmentDownloadJobs: Error with job '${row.id}', deleting. ` +
`JSON: '${row.json}' ` +
`Error: ${Errors.toLogFormat(error)}`
);
removeAttachmentDownloadJobSync(row.id);
throw new Error(INNER_ERROR);
}
});
} catch (error) {
if ('message' in error && error.message === INNER_ERROR) {
return getNextAttachmentDownloadJobs(limit, { timestamp });
}
throw error;
}
}
async function saveAttachmentDownloadJob(
job: AttachmentDownloadJobType
): Promise<void> {
const db = getInstance();
const { id, pending, timestamp } = job;
if (!id) {
throw new Error(
'saveAttachmentDownloadJob: Provided job did not have a truthy id'
);
}
db.prepare<Query>(
`
INSERT OR REPLACE INTO attachment_downloads (
id,
pending,
timestamp,
json
) values (
$id,
$pending,
$timestamp,
$json
)
`
).run({
id,
pending,
timestamp,
json: objectToJSON(job),
});
}
async function setAttachmentDownloadJobPending(
id: string,
pending: boolean
): Promise<void> {
const db = getInstance();
db.prepare<Query>(
`
UPDATE attachment_downloads
SET pending = $pending
WHERE id = $id;
`
).run({
id,
pending: pending ? 1 : 0,
});
}
async function resetAttachmentDownloadPending(): Promise<void> {
const db = getInstance();
db.prepare<EmptyQuery>(
`
UPDATE attachment_downloads
SET pending = 0
WHERE pending != 0;
`
).run();
}
function removeAttachmentDownloadJobSync(id: string): void {
2021-10-26 22:59:08 +00:00
return removeById(getInstance(), ATTACHMENT_DOWNLOADS_TABLE, id);
}
async function removeAttachmentDownloadJob(id: string): Promise<void> {
return removeAttachmentDownloadJobSync(id);
}
2021-10-26 22:59:08 +00:00
async function removeAllAttachmentDownloadJobs(): Promise<void> {
return removeAllFromTable(getInstance(), ATTACHMENT_DOWNLOADS_TABLE);
}
// Stickers
async function createOrUpdateStickerPack(pack: StickerPackType): Promise<void> {
const db = getInstance();
const {
attemptedStatus,
author,
coverStickerId,
createdAt,
downloadAttempts,
id,
installedAt,
key,
lastUsed,
status,
stickerCount,
title,
2022-08-03 17:10:49 +00:00
storageID,
storageVersion,
storageUnknownFields,
storageNeedsSync,
} = pack;
if (!id) {
throw new Error(
'createOrUpdateStickerPack: Provided data did not have a truthy id'
);
}
2022-08-03 17:10:49 +00:00
let { position } = pack;
// Assign default position
if (!isNumber(position)) {
position = db
.prepare<EmptyQuery>(
`
SELECT IFNULL(MAX(position) + 1, 0)
FROM sticker_packs
`
)
.pluck()
.get();
}
const row = db
.prepare<Query>(
`
SELECT id
FROM sticker_packs
WHERE id = $id;
`
)
2022-08-03 17:10:49 +00:00
.get({ id });
const payload = {
2021-07-09 19:36:10 +00:00
attemptedStatus: attemptedStatus ?? null,
author,
coverStickerId,
createdAt: createdAt || Date.now(),
downloadAttempts: downloadAttempts || 1,
id,
2021-07-09 19:36:10 +00:00
installedAt: installedAt ?? null,
key,
lastUsed: lastUsed || null,
status,
stickerCount,
title,
2022-08-03 17:10:49 +00:00
position: position ?? 0,
storageID: storageID ?? null,
storageVersion: storageVersion ?? null,
storageUnknownFields: storageUnknownFields ?? null,
storageNeedsSync: storageNeedsSync ? 1 : 0,
};
2022-08-03 17:10:49 +00:00
if (row) {
db.prepare<Query>(
`
UPDATE sticker_packs SET
attemptedStatus = $attemptedStatus,
author = $author,
coverStickerId = $coverStickerId,
createdAt = $createdAt,
downloadAttempts = $downloadAttempts,
installedAt = $installedAt,
key = $key,
lastUsed = $lastUsed,
status = $status,
stickerCount = $stickerCount,
2022-08-03 17:10:49 +00:00
title = $title,
position = $position,
storageID = $storageID,
storageVersion = $storageVersion,
storageUnknownFields = $storageUnknownFields,
storageNeedsSync = $storageNeedsSync
WHERE id = $id;
`
).run(payload);
return;
}
db.prepare<Query>(
`
INSERT INTO sticker_packs (
attemptedStatus,
author,
coverStickerId,
createdAt,
downloadAttempts,
id,
installedAt,
key,
lastUsed,
status,
stickerCount,
2022-08-03 17:10:49 +00:00
title,
position,
storageID,
storageVersion,
storageUnknownFields,
storageNeedsSync
) values (
$attemptedStatus,
$author,
$coverStickerId,
$createdAt,
$downloadAttempts,
$id,
$installedAt,
$key,
$lastUsed,
$status,
$stickerCount,
2022-08-03 17:10:49 +00:00
$title,
$position,
$storageID,
$storageVersion,
$storageUnknownFields,
$storageNeedsSync
)
`
).run(payload);
}
2022-08-03 17:10:49 +00:00
function updateStickerPackStatusSync(
id: string,
status: StickerPackStatusType,
options?: { timestamp: number }
2022-08-03 17:10:49 +00:00
): void {
const db = getInstance();
const timestamp = options ? options.timestamp || Date.now() : Date.now();
const installedAt = status === 'installed' ? timestamp : null;
db.prepare<Query>(
`
UPDATE sticker_packs
SET status = $status, installedAt = $installedAt
WHERE id = $id;
`
).run({
id,
status,
installedAt,
});
}
2022-08-03 17:10:49 +00:00
async function updateStickerPackStatus(
id: string,
status: StickerPackStatusType,
options?: { timestamp: number }
): Promise<void> {
return updateStickerPackStatusSync(id, status, options);
}
async function updateStickerPackInfo({
id,
storageID,
storageVersion,
storageUnknownFields,
storageNeedsSync,
uninstalledAt,
}: StickerPackInfoType): Promise<void> {
const db = getInstance();
if (uninstalledAt) {
db.prepare<Query>(
`
UPDATE uninstalled_sticker_packs
SET
storageID = $storageID,
storageVersion = $storageVersion,
storageUnknownFields = $storageUnknownFields,
storageNeedsSync = $storageNeedsSync
WHERE id = $id;
`
).run({
id,
storageID: storageID ?? null,
storageVersion: storageVersion ?? null,
storageUnknownFields: storageUnknownFields ?? null,
storageNeedsSync: storageNeedsSync ? 1 : 0,
});
} else {
db.prepare<Query>(
`
UPDATE sticker_packs
SET
storageID = $storageID,
storageVersion = $storageVersion,
storageUnknownFields = $storageUnknownFields,
storageNeedsSync = $storageNeedsSync
WHERE id = $id;
`
).run({
id,
storageID: storageID ?? null,
storageVersion: storageVersion ?? null,
storageUnknownFields: storageUnknownFields ?? null,
storageNeedsSync: storageNeedsSync ? 1 : 0,
});
}
}
2021-01-27 22:39:45 +00:00
async function clearAllErrorStickerPackAttempts(): Promise<void> {
const db = getInstance();
db.prepare<EmptyQuery>(
`
UPDATE sticker_packs
SET downloadAttempts = 0
WHERE status = 'error';
`
).run();
2021-01-27 22:39:45 +00:00
}
async function createOrUpdateSticker(sticker: StickerType): Promise<void> {
const db = getInstance();
2021-11-11 22:43:05 +00:00
const { emoji, height, id, isCoverOnly, lastUsed, packId, path, width } =
sticker;
if (!isNumber(id)) {
throw new Error(
'createOrUpdateSticker: Provided data did not have a numeric id'
);
}
if (!packId) {
throw new Error(
'createOrUpdateSticker: Provided data did not have a truthy id'
);
}
db.prepare<Query>(
`
INSERT OR REPLACE INTO stickers (
emoji,
height,
id,
isCoverOnly,
lastUsed,
packId,
path,
width
) values (
$emoji,
$height,
$id,
$isCoverOnly,
$lastUsed,
$packId,
$path,
$width
)
`
).run({
2021-07-09 19:36:10 +00:00
emoji: emoji ?? null,
height,
id,
isCoverOnly: isCoverOnly ? 1 : 0,
lastUsed: lastUsed || null,
packId,
path,
width,
});
}
async function updateStickerLastUsed(
packId: string,
stickerId: number,
lastUsed: number
): Promise<void> {
const db = getInstance();
db.prepare<Query>(
`
UPDATE stickers
SET lastUsed = $lastUsed
WHERE id = $id AND packId = $packId;
`
).run({
id: stickerId,
packId,
lastUsed,
});
db.prepare<Query>(
`
UPDATE sticker_packs
SET lastUsed = $lastUsed
WHERE id = $id;
`
).run({
id: packId,
lastUsed,
});
}
async function addStickerPackReference(
messageId: string,
packId: string
): Promise<void> {
const db = getInstance();
if (!messageId) {
throw new Error(
'addStickerPackReference: Provided data did not have a truthy messageId'
);
}
if (!packId) {
throw new Error(
'addStickerPackReference: Provided data did not have a truthy packId'
);
}
db.prepare<Query>(
`
INSERT OR REPLACE INTO sticker_references (
messageId,
packId
) values (
$messageId,
$packId
)
`
2021-04-09 00:50:25 +00:00
).run({
messageId,
packId,
});
}
async function deleteStickerPackReference(
messageId: string,
packId: string
): Promise<ReadonlyArray<string> | undefined> {
const db = getInstance();
if (!messageId) {
throw new Error(
'addStickerPackReference: Provided data did not have a truthy messageId'
);
}
if (!packId) {
throw new Error(
'addStickerPackReference: Provided data did not have a truthy packId'
);
}
return db
.transaction(() => {
// We use an immediate transaction here to immediately acquire an exclusive lock,
// which would normally only happen when we did our first write.
// We need this to ensure that our five queries are all atomic, with no
// other changes happening while we do it:
// 1. Delete our target messageId/packId references
// 2. Check the number of references still pointing at packId
// 3. If that number is zero, get pack from sticker_packs database
// 4. If it's not installed, then grab all of its sticker paths
// 5. If it's not installed, then sticker pack (which cascades to all
// stickers and references)
db.prepare<Query>(
`
DELETE FROM sticker_references
WHERE messageId = $messageId AND packId = $packId;
`
).run({
messageId,
packId,
});
2023-01-17 21:07:21 +00:00
const count = db
.prepare<Query>(
`
2023-01-17 21:07:21 +00:00
SELECT count(1) FROM sticker_references
WHERE packId = $packId;
`
)
2023-01-17 21:07:21 +00:00
.pluck()
.get({ packId });
if (count > 0) {
return undefined;
}
const packRow: { status: StickerPackStatusType } = db
.prepare<Query>(
`
SELECT status FROM sticker_packs
WHERE id = $packId;
`
)
.get({ packId });
if (!packRow) {
logger.warn('deleteStickerPackReference: did not find referenced pack');
return undefined;
}
const { status } = packRow;
if (status === 'installed') {
return undefined;
}
const stickerPathRows: Array<{ path: string }> = db
.prepare<Query>(
`
SELECT path FROM stickers
WHERE packId = $packId;
`
)
.all({
packId,
});
db.prepare<Query>(
`
DELETE FROM sticker_packs
WHERE id = $packId;
`
).run({
packId,
});
return (stickerPathRows || []).map(row => row.path);
})
.immediate();
}
async function deleteStickerPack(packId: string): Promise<Array<string>> {
const db = getInstance();
if (!packId) {
throw new Error(
'deleteStickerPack: Provided data did not have a truthy packId'
);
}
return db
.transaction(() => {
// We use an immediate transaction here to immediately acquire an exclusive lock,
// which would normally only happen when we did our first write.
// We need this to ensure that our two queries are atomic, with no other changes
// happening while we do it:
// 1. Grab all of target pack's sticker paths
// 2. Delete sticker pack (which cascades to all stickers and references)
const stickerPathRows: Array<{ path: string }> = db
.prepare<Query>(
`
SELECT path FROM stickers
WHERE packId = $packId;
`
)
.all({
packId,
});
db.prepare<Query>(
`
DELETE FROM sticker_packs
WHERE id = $packId;
`
).run({ packId });
return (stickerPathRows || []).map(row => row.path);
})
.immediate();
}
async function getStickerCount(): Promise<number> {
2021-10-26 22:59:08 +00:00
return getCountFromTable(getInstance(), 'stickers');
}
async function getAllStickerPacks(): Promise<Array<StickerPackType>> {
const db = getInstance();
const rows = db
.prepare<EmptyQuery>(
`
SELECT * FROM sticker_packs
2022-08-03 17:10:49 +00:00
ORDER BY position ASC, id ASC
`
)
.all();
return rows || [];
}
function addUninstalledStickerPackSync(pack: UninstalledStickerPackType): void {
const db = getInstance();
db.prepare<Query>(
`
INSERT OR REPLACE INTO uninstalled_sticker_packs
(
id, uninstalledAt, storageID, storageVersion, storageUnknownFields,
storageNeedsSync
)
VALUES
(
$id, $uninstalledAt, $storageID, $storageVersion, $unknownFields,
$storageNeedsSync
)
`
).run({
id: pack.id,
uninstalledAt: pack.uninstalledAt,
storageID: pack.storageID ?? null,
storageVersion: pack.storageVersion ?? null,
unknownFields: pack.storageUnknownFields ?? null,
storageNeedsSync: pack.storageNeedsSync ? 1 : 0,
});
}
async function addUninstalledStickerPack(
pack: UninstalledStickerPackType
): Promise<void> {
return addUninstalledStickerPackSync(pack);
}
function removeUninstalledStickerPackSync(packId: string): void {
const db = getInstance();
db.prepare<Query>(
'DELETE FROM uninstalled_sticker_packs WHERE id IS $id'
).run({ id: packId });
}
async function removeUninstalledStickerPack(packId: string): Promise<void> {
return removeUninstalledStickerPackSync(packId);
}
async function getUninstalledStickerPacks(): Promise<
Array<UninstalledStickerPackType>
> {
const db = getInstance();
const rows = db
.prepare<EmptyQuery>(
'SELECT * FROM uninstalled_sticker_packs ORDER BY id ASC'
)
.all();
return rows || [];
}
async function getInstalledStickerPacks(): Promise<Array<StickerPackType>> {
const db = getInstance();
// If sticker pack has a storageID - it is being downloaded and about to be
// installed so we better sync it back to storage service if asked.
const rows = db
.prepare<EmptyQuery>(
`
SELECT *
FROM sticker_packs
WHERE
2023-01-18 22:12:33 +00:00
status IS 'installed' OR
2022-08-03 17:10:49 +00:00
storageID IS NOT NULL
ORDER BY id ASC
`
)
.all();
return rows || [];
}
2022-08-03 17:10:49 +00:00
async function getStickerPackInfo(
packId: string
): Promise<StickerPackInfoType | undefined> {
const db = getInstance();
return db.transaction(() => {
const uninstalled = db
.prepare<Query>(
`
SELECT * FROM uninstalled_sticker_packs
WHERE id IS $packId
`
)
.get({ packId });
if (uninstalled) {
return uninstalled as UninstalledStickerPackType;
}
const installed = db
.prepare<Query>(
`
SELECT
id, key, position, storageID, storageVersion, storageUnknownFields
FROM sticker_packs
WHERE id IS $packId
`
)
.get({ packId });
if (installed) {
return installed as InstalledStickerPackType;
}
return undefined;
})();
}
async function installStickerPack(
packId: string,
timestamp: number
): Promise<void> {
const db = getInstance();
return db.transaction(() => {
const status = 'installed';
updateStickerPackStatusSync(packId, status, { timestamp });
removeUninstalledStickerPackSync(packId);
})();
}
async function uninstallStickerPack(
packId: string,
timestamp: number
): Promise<void> {
const db = getInstance();
return db.transaction(() => {
const status = 'downloaded';
updateStickerPackStatusSync(packId, status);
db.prepare<Query>(
`
UPDATE sticker_packs SET
storageID = NULL,
storageVersion = NULL,
storageUnknownFields = NULL,
storageNeedsSync = 0
WHERE id = $packId;
`
).run({ packId });
addUninstalledStickerPackSync({
id: packId,
uninstalledAt: timestamp,
storageNeedsSync: true,
});
})();
}
async function getAllStickers(): Promise<Array<StickerType>> {
const db = getInstance();
const rows = db
.prepare<EmptyQuery>(
`
SELECT * FROM stickers
ORDER BY packId ASC, id ASC
`
)
.all();
return (rows || []).map(row => rowToSticker(row));
}
async function getRecentStickers({ limit }: { limit?: number } = {}): Promise<
Array<StickerType>
> {
const db = getInstance();
// Note: we avoid 'IS NOT NULL' here because it does seem to bypass our index
const rows = db
.prepare<Query>(
`
SELECT stickers.* FROM stickers
JOIN sticker_packs on stickers.packId = sticker_packs.id
WHERE stickers.lastUsed > 0 AND sticker_packs.status = 'installed'
ORDER BY stickers.lastUsed DESC
LIMIT $limit
`
)
.all({
limit: limit || 24,
});
return (rows || []).map(row => rowToSticker(row));
}
2019-05-24 23:58:27 +00:00
// Emojis
async function updateEmojiUsage(
shortName: string,
timeUsed: number = Date.now()
): Promise<void> {
const db = getInstance();
2019-05-24 23:58:27 +00:00
db.transaction(() => {
const rows = db
.prepare<Query>(
`
SELECT * FROM emojis
WHERE shortName = $shortName;
`
)
.get({
shortName,
});
if (rows) {
db.prepare<Query>(
`
UPDATE emojis
SET lastUsage = $timeUsed
WHERE shortName = $shortName;
`
).run({ shortName, timeUsed });
} else {
db.prepare<Query>(
`
INSERT INTO emojis(shortName, lastUsage)
VALUES ($shortName, $timeUsed);
`
).run({ shortName, timeUsed });
2019-05-24 23:58:27 +00:00
}
})();
2019-05-24 23:58:27 +00:00
}
async function getRecentEmojis(limit = 32): Promise<Array<EmojiType>> {
const db = getInstance();
const rows = db
.prepare<Query>(
`
SELECT *
FROM emojis
ORDER BY lastUsage DESC
LIMIT $limit;
`
)
.all({ limit });
2019-05-24 23:58:27 +00:00
return rows || [];
}
2021-11-02 23:01:13 +00:00
async function getAllBadges(): Promise<Array<BadgeType>> {
const db = getInstance();
const [badgeRows, badgeImageFileRows] = db.transaction(() => [
db.prepare<EmptyQuery>('SELECT * FROM badges').all(),
db.prepare<EmptyQuery>('SELECT * FROM badgeImageFiles').all(),
])();
const badgeImagesByBadge = new Map<
string,
Array<undefined | BadgeImageType>
>();
for (const badgeImageFileRow of badgeImageFileRows) {
const { badgeId, order, localPath, url, theme } = badgeImageFileRow;
const badgeImages = badgeImagesByBadge.get(badgeId) || [];
badgeImages[order] = {
...(badgeImages[order] || {}),
[parseBadgeImageTheme(theme)]: {
localPath: dropNull(localPath),
url,
},
};
badgeImagesByBadge.set(badgeId, badgeImages);
}
return badgeRows.map(badgeRow => ({
id: badgeRow.id,
category: parseBadgeCategory(badgeRow.category),
name: badgeRow.name,
descriptionTemplate: badgeRow.descriptionTemplate,
images: (badgeImagesByBadge.get(badgeRow.id) || []).filter(isNotNil),
}));
}
// This should match the logic in the badges Redux reducer.
async function updateOrCreateBadges(
badges: ReadonlyArray<BadgeType>
): Promise<void> {
const db = getInstance();
const insertBadge = prepare<Query>(
db,
`
INSERT OR REPLACE INTO badges (
id,
category,
name,
descriptionTemplate
) VALUES (
$id,
$category,
$name,
$descriptionTemplate
);
`
);
const getImageFilesForBadge = prepare<Query>(
db,
'SELECT url, localPath FROM badgeImageFiles WHERE badgeId = $badgeId'
);
const insertBadgeImageFile = prepare<Query>(
db,
`
INSERT INTO badgeImageFiles (
badgeId,
'order',
url,
localPath,
theme
) VALUES (
$badgeId,
$order,
$url,
$localPath,
$theme
);
`
);
db.transaction(() => {
badges.forEach(badge => {
const { id: badgeId } = badge;
const oldLocalPaths = new Map<string, string>();
for (const { url, localPath } of getImageFilesForBadge.all({ badgeId })) {
if (localPath) {
oldLocalPaths.set(url, localPath);
}
}
insertBadge.run({
id: badgeId,
category: badge.category,
name: badge.name,
descriptionTemplate: badge.descriptionTemplate,
});
for (const [order, image] of badge.images.entries()) {
for (const [theme, imageFile] of Object.entries(image)) {
insertBadgeImageFile.run({
badgeId,
localPath:
imageFile.localPath || oldLocalPaths.get(imageFile.url) || null,
order,
theme,
url: imageFile.url,
});
}
}
});
})();
}
async function badgeImageFileDownloaded(
url: string,
localPath: string
): Promise<void> {
const db = getInstance();
prepare<Query>(
db,
'UPDATE badgeImageFiles SET localPath = $localPath WHERE url = $url'
).run({ url, localPath });
}
async function getAllBadgeImageFileLocalPaths(): Promise<Set<string>> {
const db = getInstance();
const localPaths = db
.prepare<EmptyQuery>(
'SELECT localPath FROM badgeImageFiles WHERE localPath IS NOT NULL'
)
.pluck()
.all();
return new Set(localPaths);
}
type StoryDistributionForDatabase = Readonly<
{
2022-07-01 00:52:03 +00:00
allowsReplies: 0 | 1;
deletedAtTimestamp: number | null;
isBlockList: 0 | 1;
senderKeyInfoJson: string | null;
storageID: string | null;
storageVersion: number | null;
2022-07-01 00:52:03 +00:00
storageNeedsSync: 0 | 1;
} & Omit<
StoryDistributionType,
| 'allowsReplies'
| 'deletedAtTimestamp'
| 'isBlockList'
| 'senderKeyInfo'
| 'storageID'
| 'storageVersion'
2022-07-01 00:52:03 +00:00
| 'storageNeedsSync'
>
>;
function hydrateStoryDistribution(
fromDatabase: StoryDistributionForDatabase
): StoryDistributionType {
return {
...omit(fromDatabase, 'senderKeyInfoJson'),
2022-07-01 00:52:03 +00:00
allowsReplies: Boolean(fromDatabase.allowsReplies),
deletedAtTimestamp: fromDatabase.deletedAtTimestamp || undefined,
isBlockList: Boolean(fromDatabase.isBlockList),
senderKeyInfo: fromDatabase.senderKeyInfoJson
? JSON.parse(fromDatabase.senderKeyInfoJson)
: undefined,
storageID: fromDatabase.storageID || undefined,
storageVersion: fromDatabase.storageVersion || undefined,
2022-07-01 00:52:03 +00:00
storageNeedsSync: Boolean(fromDatabase.storageNeedsSync),
storageUnknownFields: fromDatabase.storageUnknownFields || undefined,
};
}
function freezeStoryDistribution(
story: StoryDistributionType
): StoryDistributionForDatabase {
return {
...omit(story, 'senderKeyInfo'),
2022-07-01 00:52:03 +00:00
allowsReplies: story.allowsReplies ? 1 : 0,
deletedAtTimestamp: story.deletedAtTimestamp || null,
isBlockList: story.isBlockList ? 1 : 0,
senderKeyInfoJson: story.senderKeyInfo
? JSON.stringify(story.senderKeyInfo)
: null,
storageID: story.storageID || null,
storageVersion: story.storageVersion || null,
2022-07-01 00:52:03 +00:00
storageNeedsSync: story.storageNeedsSync ? 1 : 0,
storageUnknownFields: story.storageUnknownFields || null,
};
}
async function _getAllStoryDistributions(): Promise<
Array<StoryDistributionType>
> {
const db = getInstance();
const storyDistributions = db
.prepare<EmptyQuery>('SELECT * FROM storyDistributions;')
.all();
return storyDistributions.map(hydrateStoryDistribution);
}
async function _getAllStoryDistributionMembers(): Promise<
Array<StoryDistributionMemberType>
> {
const db = getInstance();
return db
.prepare<EmptyQuery>('SELECT * FROM storyDistributionMembers;')
.all();
}
async function _deleteAllStoryDistributions(): Promise<void> {
const db = getInstance();
db.prepare<EmptyQuery>('DELETE FROM storyDistributions;').run();
}
async function createNewStoryDistribution(
distribution: StoryDistributionWithMembersType
): Promise<void> {
strictAssert(
distribution.name,
'Distribution list does not have a valid name'
);
const db = getInstance();
db.transaction(() => {
const payload = freezeStoryDistribution(distribution);
prepare(
db,
`
INSERT INTO storyDistributions(
id,
name,
2022-07-01 00:52:03 +00:00
deletedAtTimestamp,
allowsReplies,
isBlockList,
senderKeyInfoJson,
storageID,
storageVersion,
storageUnknownFields,
storageNeedsSync
) VALUES (
$id,
$name,
2022-07-01 00:52:03 +00:00
$deletedAtTimestamp,
$allowsReplies,
$isBlockList,
$senderKeyInfoJson,
$storageID,
$storageVersion,
$storageUnknownFields,
$storageNeedsSync
);
`
).run(payload);
const { id: listId, members } = distribution;
const memberInsertStatement = prepare(
db,
`
INSERT OR REPLACE INTO storyDistributionMembers (
listId,
uuid
) VALUES (
$listId,
$uuid
);
`
);
for (const uuid of members) {
memberInsertStatement.run({
listId,
uuid,
});
}
})();
}
async function getAllStoryDistributionsWithMembers(): Promise<
Array<StoryDistributionWithMembersType>
> {
const allDistributions = await _getAllStoryDistributions();
const allMembers = await _getAllStoryDistributionMembers();
const byListId = groupBy(allMembers, member => member.listId);
return allDistributions.map(list => ({
...list,
members: (byListId[list.id] || []).map(member => member.uuid),
}));
}
2022-03-04 21:14:52 +00:00
async function getStoryDistributionWithMembers(
id: string
): Promise<StoryDistributionWithMembersType | undefined> {
const db = getInstance();
const storyDistribution: StoryDistributionForDatabase | undefined = prepare(
2022-03-04 21:14:52 +00:00
db,
'SELECT * FROM storyDistributions WHERE id = $id;'
).get({
id,
});
if (!storyDistribution) {
return undefined;
}
const members = prepare(
db,
'SELECT * FROM storyDistributionMembers WHERE listId = $id;'
).all({
id,
});
return {
...hydrateStoryDistribution(storyDistribution),
2022-03-04 21:14:52 +00:00
members: members.map(({ uuid }) => uuid),
};
}
2022-07-01 00:52:03 +00:00
function modifyStoryDistributionSync(
db: Database,
payload: StoryDistributionForDatabase
): void {
if (payload.deletedAtTimestamp) {
strictAssert(
!payload.name,
'Attempt to delete distribution list but still has a name'
);
} else {
strictAssert(
payload.name,
'Cannot clear distribution list name without deletedAtTimestamp set'
);
}
prepare(
db,
`
UPDATE storyDistributions
SET
name = $name,
2022-07-01 00:52:03 +00:00
deletedAtTimestamp = $deletedAtTimestamp,
allowsReplies = $allowsReplies,
isBlockList = $isBlockList,
senderKeyInfoJson = $senderKeyInfoJson,
storageID = $storageID,
storageVersion = $storageVersion,
storageUnknownFields = $storageUnknownFields,
storageNeedsSync = $storageNeedsSync
WHERE id = $id
`
).run(payload);
}
2022-07-01 00:52:03 +00:00
function modifyStoryDistributionMembersSync(
db: Database,
listId: string,
{
toAdd,
toRemove,
}: { toAdd: Array<UUIDStringType>; toRemove: Array<UUIDStringType> }
2022-07-01 00:52:03 +00:00
) {
const memberInsertStatement = prepare(
db,
`
INSERT OR REPLACE INTO storyDistributionMembers (
listId,
uuid
) VALUES (
$listId,
$uuid
);
`
);
2022-07-01 00:52:03 +00:00
for (const uuid of toAdd) {
memberInsertStatement.run({
listId,
uuid,
});
}
batchMultiVarQuery(db, toRemove, (uuids: ReadonlyArray<UUIDStringType>) => {
2022-07-01 00:52:03 +00:00
db.prepare<ArrayQuery>(
`
2022-07-01 00:52:03 +00:00
DELETE FROM storyDistributionMembers
WHERE listId = ? AND uuid IN ( ${uuids.map(() => '?').join(', ')} );
`
2022-07-01 00:52:03 +00:00
).run([listId, ...uuids]);
});
}
async function modifyStoryDistributionWithMembers(
distribution: StoryDistributionType,
{
toAdd,
toRemove,
}: { toAdd: Array<UUIDStringType>; toRemove: Array<UUIDStringType> }
): Promise<void> {
const payload = freezeStoryDistribution(distribution);
const db = getInstance();
2022-07-01 00:52:03 +00:00
if (toAdd.length || toRemove.length) {
db.transaction(() => {
modifyStoryDistributionSync(db, payload);
modifyStoryDistributionMembersSync(db, payload.id, { toAdd, toRemove });
})();
} else {
modifyStoryDistributionSync(db, payload);
}
}
async function modifyStoryDistribution(
distribution: StoryDistributionType
): Promise<void> {
const payload = freezeStoryDistribution(distribution);
const db = getInstance();
modifyStoryDistributionSync(db, payload);
}
async function modifyStoryDistributionMembers(
listId: string,
{
toAdd,
toRemove,
}: { toAdd: Array<UUIDStringType>; toRemove: Array<UUIDStringType> }
): Promise<void> {
const db = getInstance();
2022-07-01 00:52:03 +00:00
db.transaction(() => {
modifyStoryDistributionMembersSync(db, listId, { toAdd, toRemove });
})();
}
async function deleteStoryDistribution(id: UUIDStringType): Promise<void> {
const db = getInstance();
db.prepare<Query>('DELETE FROM storyDistributions WHERE id = $id;').run({
id,
});
}
async function _getAllStoryReads(): Promise<Array<StoryReadType>> {
const db = getInstance();
return db.prepare<EmptyQuery>('SELECT * FROM storyReads;').all();
}
async function _deleteAllStoryReads(): Promise<void> {
const db = getInstance();
db.prepare<EmptyQuery>('DELETE FROM storyReads;').run();
}
async function addNewStoryRead(read: StoryReadType): Promise<void> {
const db = getInstance();
prepare(
db,
`
INSERT OR REPLACE INTO storyReads(
authorId,
conversationId,
storyId,
storyReadDate
) VALUES (
$authorId,
$conversationId,
$storyId,
$storyReadDate
);
`
).run(read);
}
async function getLastStoryReadsForAuthor({
authorId,
conversationId,
limit: initialLimit,
}: {
authorId: UUIDStringType;
conversationId?: UUIDStringType;
limit?: number;
}): Promise<Array<StoryReadType>> {
const limit = initialLimit || 5;
const db = getInstance();
return db
.prepare<Query>(
`
SELECT * FROM storyReads
WHERE
authorId = $authorId AND
($conversationId IS NULL OR conversationId = $conversationId)
ORDER BY storyReadDate DESC
LIMIT $limit;
`
)
.all({
authorId,
conversationId: conversationId || null,
limit,
});
}
2022-03-29 01:10:08 +00:00
async function countStoryReadsByConversation(
conversationId: string
): Promise<number> {
const db = getInstance();
return db
.prepare<Query>(
`
2023-01-17 21:07:21 +00:00
SELECT count(1) FROM storyReads
2022-03-29 01:10:08 +00:00
WHERE conversationId = $conversationId;
`
)
.pluck()
.get({ conversationId });
}
2018-10-18 01:01:21 +00:00
// All data in database
async function removeAll(): Promise<void> {
const db = getInstance();
db.transaction(() => {
db.exec(`
DELETE FROM attachment_downloads;
2021-11-02 23:01:13 +00:00
DELETE FROM badgeImageFiles;
DELETE FROM badges;
DELETE FROM conversations;
DELETE FROM emojis;
DELETE FROM groupCallRingCancellations;
DELETE FROM identityKeys;
DELETE FROM items;
DELETE FROM jobs;
DELETE FROM messages_fts;
DELETE FROM messages;
DELETE FROM preKeys;
DELETE FROM reactions;
DELETE FROM senderKeys;
DELETE FROM sendLogMessageIds;
DELETE FROM sendLogPayloads;
DELETE FROM sendLogRecipients;
DELETE FROM sessions;
DELETE FROM signedPreKeys;
DELETE FROM sticker_packs;
DELETE FROM sticker_references;
DELETE FROM stickers;
DELETE FROM storyDistributionMembers;
DELETE FROM storyDistributions;
DELETE FROM storyReads;
DELETE FROM unprocessed;
DELETE FROM uninstalled_sticker_packs;
2023-01-26 23:53:22 +00:00
INSERT INTO messages_fts(messages_fts) VALUES('optimize');
`);
})();
2018-10-18 01:01:21 +00:00
}
// Anything that isn't user-visible data
async function removeAllConfiguration(
mode = RemoveAllConfiguration.Full
): Promise<void> {
const db = getInstance();
2018-10-18 01:01:21 +00:00
db.transaction(() => {
2021-05-27 20:47:39 +00:00
db.exec(
2021-05-25 22:40:04 +00:00
`
DELETE FROM identityKeys;
DELETE FROM jobs;
DELETE FROM preKeys;
DELETE FROM senderKeys;
DELETE FROM sendLogMessageIds;
DELETE FROM sendLogPayloads;
DELETE FROM sendLogRecipients;
DELETE FROM sessions;
DELETE FROM signedPreKeys;
DELETE FROM unprocessed;
`
2021-05-27 20:47:39 +00:00
);
if (mode === RemoveAllConfiguration.Full) {
db.exec(
`
DELETE FROM items;
`
);
} else if (mode === RemoveAllConfiguration.Soft) {
const itemIds: ReadonlyArray<string> = db
.prepare<EmptyQuery>('SELECT id FROM items')
.pluck(true)
.all();
const allowedSet = new Set<string>(STORAGE_UI_KEYS);
for (const id of itemIds) {
if (!allowedSet.has(id)) {
2021-10-26 22:59:08 +00:00
removeById(db, 'items', id);
}
}
} else {
throw missingCaseError(mode);
}
db.exec(
"UPDATE conversations SET json = json_remove(json, '$.senderKeyInfo');"
2021-05-27 20:47:39 +00:00
);
})();
}
const MAX_MESSAGE_MIGRATION_ATTEMPTS = 5;
async function getMessagesNeedingUpgrade(
limit: number,
{ maxVersion }: { maxVersion: number }
): Promise<Array<MessageType>> {
const db = getInstance();
const rows: JSONRows = db
.prepare<Query>(
`
SELECT json
FROM messages
WHERE
(schemaVersion IS NULL OR schemaVersion < $maxVersion) AND
IFNULL(
json_extract(json, '$.schemaMigrationAttempts'),
0
) < $maxAttempts
LIMIT $limit;
`
)
.all({
maxVersion,
maxAttempts: MAX_MESSAGE_MIGRATION_ATTEMPTS,
limit,
});
return rows.map(row => jsonToObject(row.json));
}
async function getMessagesWithVisualMediaAttachments(
conversationId: string,
{ limit }: { limit: number }
): Promise<Array<MessageType>> {
const db = getInstance();
const rows: JSONRows = db
.prepare<Query>(
`
SELECT json FROM messages WHERE
isStory IS 0 AND
storyId IS NULL AND
conversationId = $conversationId AND
hasVisualMediaAttachments = 1
ORDER BY received_at DESC, sent_at DESC
LIMIT $limit;
`
)
.all({
conversationId,
limit,
});
return rows.map(row => jsonToObject(row.json));
}
async function getMessagesWithFileAttachments(
conversationId: string,
{ limit }: { limit: number }
): Promise<Array<MessageType>> {
const db = getInstance();
const rows = db
.prepare<Query>(
`
SELECT json FROM messages WHERE
isStory IS 0 AND
storyId IS NULL AND
conversationId = $conversationId AND
hasFileAttachments = 1
ORDER BY received_at DESC, sent_at DESC
LIMIT $limit;
`
)
.all({
conversationId,
limit,
});
return map(rows, row => jsonToObject(row.json));
}
async function getMessageServerGuidsForSpam(
conversationId: string
): Promise<Array<string>> {
const db = getInstance();
// The server's maximum is 3, which is why you see `LIMIT 3` in this query. Note that we
// use `pluck` here to only get the first column!
return db
.prepare<Query>(
`
SELECT serverGuid
FROM messages
WHERE conversationId = $conversationId
AND type = 'incoming'
AND serverGuid IS NOT NULL
ORDER BY received_at DESC, sent_at DESC
LIMIT 3;
`
)
.pluck(true)
.all({ conversationId });
}
function getExternalFilesForMessage(message: MessageType): Array<string> {
const { attachments, contact, quote, preview, sticker } = message;
const files: Array<string> = [];
forEach(attachments, attachment => {
const { path: file, thumbnail, screenshot } = attachment;
if (file) {
files.push(file);
}
if (thumbnail && thumbnail.path) {
files.push(thumbnail.path);
}
if (screenshot && screenshot.path) {
files.push(screenshot.path);
}
});
if (quote && quote.attachments && quote.attachments.length) {
forEach(quote.attachments, attachment => {
const { thumbnail } = attachment;
if (thumbnail && thumbnail.path) {
files.push(thumbnail.path);
}
});
}
if (contact && contact.length) {
forEach(contact, item => {
const { avatar } = item;
if (avatar && avatar.avatar && avatar.avatar.path) {
files.push(avatar.avatar.path);
}
});
}
2019-01-16 03:03:56 +00:00
if (preview && preview.length) {
forEach(preview, item => {
const { image } = item;
if (image && image.path) {
files.push(image.path);
}
});
}
if (sticker && sticker.data && sticker.data.path) {
files.push(sticker.data.path);
if (sticker.data.thumbnail && sticker.data.thumbnail.path) {
files.push(sticker.data.thumbnail.path);
}
}
return files;
}
function getExternalFilesForConversation(
conversation: Pick<ConversationType, 'avatar' | 'profileAvatar'>
): Array<string> {
2018-09-21 01:47:19 +00:00
const { avatar, profileAvatar } = conversation;
const files: Array<string> = [];
2018-09-21 01:47:19 +00:00
if (avatar && avatar.path) {
files.push(avatar.path);
}
if (profileAvatar && profileAvatar.path) {
files.push(profileAvatar.path);
}
return files;
}
function getExternalDraftFilesForConversation(
conversation: Pick<ConversationType, 'draftAttachments'>
): Array<string> {
2019-08-07 00:40:25 +00:00
const draftAttachments = conversation.draftAttachments || [];
const files: Array<string> = [];
2019-08-07 00:40:25 +00:00
forEach(draftAttachments, attachment => {
2021-08-30 21:32:56 +00:00
if (attachment.pending) {
return;
}
2019-08-07 00:40:25 +00:00
const { path: file, screenshotPath } = attachment;
if (file) {
files.push(file);
}
if (screenshotPath) {
files.push(screenshotPath);
}
});
return files;
}
async function getKnownMessageAttachments(
cursor?: MessageAttachmentsCursorType
): Promise<GetKnownMessageAttachmentsResultType> {
const db = getInstance();
const result = new Set<string>();
const chunkSize = 1000;
return db.transaction(() => {
let count = cursor?.count ?? 0;
strictAssert(
!cursor?.done,
'getKnownMessageAttachments: iteration cannot be restarted'
);
let runId: string;
if (cursor === undefined) {
runId = randomBytes(8).toString('hex');
const total = getMessageCountSync();
logger.info(
`getKnownMessageAttachments(${runId}): ` +
`Starting iteration through ${total} messages`
);
db.exec(
`
CREATE TEMP TABLE tmp_${runId}_updated_messages
(rowid INTEGER PRIMARY KEY ASC);
INSERT INTO tmp_${runId}_updated_messages (rowid)
SELECT rowid FROM messages;
CREATE TEMP TRIGGER tmp_${runId}_message_updates
UPDATE OF json ON messages
BEGIN
INSERT OR IGNORE INTO tmp_${runId}_updated_messages (rowid)
VALUES (NEW.rowid);
END;
CREATE TEMP TRIGGER tmp_${runId}_message_inserts
AFTER INSERT ON messages
BEGIN
INSERT OR IGNORE INTO tmp_${runId}_updated_messages (rowid)
VALUES (NEW.rowid);
END;
`
);
} else {
({ runId } = cursor);
}
const rowids: Array<number> = db
.prepare<Query>(
`
DELETE FROM tmp_${runId}_updated_messages
RETURNING rowid
LIMIT $chunkSize;
`
)
.pluck()
.all({ chunkSize });
const messages = batchMultiVarQuery(
db,
rowids,
(batch: ReadonlyArray<number>): Array<MessageType> => {
const query = db.prepare<ArrayQuery>(
`SELECT json FROM messages WHERE rowid IN (${Array(batch.length)
.fill('?')
.join(',')});`
);
const rows: JSONRows = query.all(batch);
return rows.map(row => jsonToObject(row.json));
}
);
for (const message of messages) {
const externalFiles = getExternalFilesForMessage(message);
forEach(externalFiles, file => result.add(file));
count += 1;
}
2022-11-17 20:06:19 +00:00
const done = rowids.length < chunkSize;
return {
attachments: Array.from(result),
cursor: { runId, count, done },
};
})();
}
async function finishGetKnownMessageAttachments({
runId,
count,
done,
}: MessageAttachmentsCursorType): Promise<void> {
const db = getInstance();
const logId = `finishGetKnownMessageAttachments(${runId})`;
if (!done) {
logger.warn(`${logId}: iteration not finished`);
}
logger.info(`${logId}: reached the end after processing ${count} messages`);
db.exec(`
DROP TABLE tmp_${runId}_updated_messages;
DROP TRIGGER tmp_${runId}_message_updates;
DROP TRIGGER tmp_${runId}_message_inserts;
`);
}
async function getKnownConversationAttachments(): Promise<Array<string>> {
const db = getInstance();
const result = new Set<string>();
const chunkSize = 500;
2021-10-26 22:59:08 +00:00
let complete = false;
let id = '';
2018-09-21 01:47:19 +00:00
2021-04-14 15:50:45 +00:00
const conversationTotal = await getConversationCount();
logger.info(
'getKnownConversationAttachments: About to iterate through ' +
`${conversationTotal}`
2018-09-21 01:47:19 +00:00
);
2021-10-05 16:36:07 +00:00
const fetchConversations = db.prepare<Query>(
`
SELECT json FROM conversations
WHERE id > $id
ORDER BY id ASC
LIMIT $chunkSize;
`
);
2018-09-21 01:47:19 +00:00
while (!complete) {
2021-10-05 16:36:07 +00:00
const rows = fetchConversations.all({
id,
chunkSize,
});
2018-09-21 01:47:19 +00:00
const conversations: Array<ConversationType> = map(rows, row =>
jsonToObject(row.json)
);
conversations.forEach(conversation => {
2018-09-21 01:47:19 +00:00
const externalFiles = getExternalFilesForConversation(conversation);
externalFiles.forEach(file => result.add(file));
2018-09-21 01:47:19 +00:00
});
const lastMessage: ConversationType | undefined = last(conversations);
2018-09-21 01:47:19 +00:00
if (lastMessage) {
({ id } = lastMessage);
}
complete = conversations.length < chunkSize;
}
logger.info('getKnownConversationAttachments: Done processing');
2018-09-21 01:47:19 +00:00
return Array.from(result);
}
async function removeKnownStickers(
allStickers: ReadonlyArray<string>
): Promise<Array<string>> {
const db = getInstance();
const lookup: Dictionary<boolean> = fromPairs(
map(allStickers, file => [file, true])
);
const chunkSize = 50;
2021-09-07 16:12:26 +00:00
const total = await getStickerCount();
logger.info(
`removeKnownStickers: About to iterate through ${total} stickers`
);
let count = 0;
let complete = false;
let rowid = 0;
while (!complete) {
const rows: Array<{ rowid: number; path: string }> = db
.prepare<Query>(
`
SELECT rowid, path FROM stickers
WHERE rowid > $rowid
ORDER BY rowid ASC
LIMIT $chunkSize;
`
)
.all({
rowid,
chunkSize,
});
const files: Array<string> = rows.map(row => row.path);
files.forEach(file => {
delete lookup[file];
});
const lastSticker = last(rows);
if (lastSticker) {
({ rowid } = lastSticker);
}
complete = rows.length < chunkSize;
count += rows.length;
}
logger.info(`removeKnownStickers: Done processing ${count} stickers`);
return Object.keys(lookup);
}
2019-08-07 00:40:25 +00:00
async function removeKnownDraftAttachments(
allStickers: ReadonlyArray<string>
): Promise<Array<string>> {
const db = getInstance();
const lookup: Dictionary<boolean> = fromPairs(
map(allStickers, file => [file, true])
);
2019-08-07 00:40:25 +00:00
const chunkSize = 50;
2021-04-14 15:50:45 +00:00
const total = await getConversationCount();
logger.info(
2019-08-07 00:40:25 +00:00
`removeKnownDraftAttachments: About to iterate through ${total} conversations`
);
let complete = false;
let count = 0;
// Though conversations.id is a string, this ensures that, when coerced, this
// value is still a string but it's smaller than every other string.
let id: number | string = 0;
2019-08-07 00:40:25 +00:00
while (!complete) {
const rows: JSONRows = db
.prepare<Query>(
`
SELECT json FROM conversations
WHERE id > $id
ORDER BY id ASC
LIMIT $chunkSize;
`
)
.all({
id,
chunkSize,
});
2019-08-07 00:40:25 +00:00
const conversations: Array<ConversationType> = rows.map(row =>
jsonToObject(row.json)
);
conversations.forEach(conversation => {
2019-08-07 00:40:25 +00:00
const externalFiles = getExternalDraftFilesForConversation(conversation);
externalFiles.forEach(file => {
2019-08-07 00:40:25 +00:00
delete lookup[file];
});
});
const lastMessage: ConversationType | undefined = last(conversations);
2019-08-07 00:40:25 +00:00
if (lastMessage) {
({ id } = lastMessage);
}
complete = conversations.length < chunkSize;
count += conversations.length;
}
logger.info(
2019-08-07 00:40:25 +00:00
`removeKnownDraftAttachments: Done processing ${count} conversations`
);
return Object.keys(lookup);
}
2021-04-29 23:02:27 +00:00
async function getJobsInQueue(queueType: string): Promise<Array<StoredJob>> {
const db = getInstance();
2022-02-16 18:36:21 +00:00
return getJobsInQueueSync(db, queueType);
}
2021-04-29 23:02:27 +00:00
2022-02-16 18:36:21 +00:00
export function getJobsInQueueSync(
db: Database,
queueType: string
): Array<StoredJob> {
2021-04-29 23:02:27 +00:00
return db
.prepare<Query>(
`
SELECT id, timestamp, data
FROM jobs
WHERE queueType = $queueType
ORDER BY timestamp;
`
)
.all({ queueType })
.map(row => ({
id: row.id,
queueType,
timestamp: row.timestamp,
data: isNotNil(row.data) ? JSON.parse(row.data) : undefined,
}));
}
2022-02-16 18:36:21 +00:00
export function insertJobSync(db: Database, job: Readonly<StoredJob>): void {
2021-04-29 23:02:27 +00:00
db.prepare<Query>(
`
INSERT INTO jobs
(id, queueType, timestamp, data)
VALUES
($id, $queueType, $timestamp, $data);
`
).run({
id: job.id,
queueType: job.queueType,
timestamp: job.timestamp,
data: isNotNil(job.data) ? JSON.stringify(job.data) : null,
});
}
async function insertJob(job: Readonly<StoredJob>): Promise<void> {
const db = getInstance();
return insertJobSync(db, job);
}
2021-04-29 23:02:27 +00:00
async function deleteJob(id: string): Promise<void> {
const db = getInstance();
db.prepare<Query>('DELETE FROM jobs WHERE id = $id').run({ id });
}
2021-05-28 16:15:17 +00:00
async function wasGroupCallRingPreviouslyCanceled(
2021-08-20 16:06:15 +00:00
ringId: bigint
): Promise<boolean> {
2021-08-20 16:06:15 +00:00
const db = getInstance();
return db
.prepare<Query>(
`
SELECT EXISTS (
SELECT 1 FROM groupCallRingCancellations
WHERE ringId = $ringId
AND createdAt >= $ringsOlderThanThisAreIgnored
2021-08-20 16:06:15 +00:00
);
`
)
.pluck()
.get({
ringId,
ringsOlderThanThisAreIgnored: Date.now() - MAX_GROUP_CALL_RING_AGE,
});
2021-08-20 16:06:15 +00:00
}
async function processGroupCallRingCancellation(ringId: bigint): Promise<void> {
2021-08-20 16:06:15 +00:00
const db = getInstance();
db.prepare<Query>(
`
INSERT INTO groupCallRingCancellations (ringId, createdAt)
VALUES ($ringId, $createdAt)
ON CONFLICT (ringId) DO NOTHING;
2021-08-20 16:06:15 +00:00
`
).run({ ringId, createdAt: Date.now() });
}
// This age, in milliseconds, should be longer than any group call ring duration. Beyond
// that, it doesn't really matter what the value is.
const MAX_GROUP_CALL_RING_AGE = 30 * durations.MINUTE;
2021-08-20 16:06:15 +00:00
async function cleanExpiredGroupCallRingCancellations(): Promise<void> {
2021-08-20 16:06:15 +00:00
const db = getInstance();
db.prepare<Query>(
`
DELETE FROM groupCallRingCancellations
2021-08-20 16:06:15 +00:00
WHERE createdAt < $expiredRingTime;
`
).run({
expiredRingTime: Date.now() - MAX_GROUP_CALL_RING_AGE,
});
}
2021-09-15 18:45:22 +00:00
async function getMaxMessageCounter(): Promise<number | undefined> {
const db = getInstance();
return db
.prepare<EmptyQuery>(
`
SELECT MAX(counter)
FROM
(
SELECT MAX(received_at) AS counter FROM messages
UNION
SELECT MAX(timestamp) AS counter FROM unprocessed
)
`
)
.pluck()
.get();
}
async function getStatisticsForLogging(): Promise<Record<string, string>> {
2021-10-26 22:59:08 +00:00
const db = getInstance();
const counts = await pProps({
messageCount: getMessageCount(),
conversationCount: getConversationCount(),
2021-10-26 22:59:08 +00:00
sessionCount: getCountFromTable(db, 'sessions'),
senderKeyCount: getCountFromTable(db, 'senderKeys'),
});
return mapValues(counts, formatCountForLogging);
}
2021-05-28 16:15:17 +00:00
async function updateAllConversationColors(
conversationColor?: ConversationColorType,
customColorData?: {
id: string;
value: CustomColorType;
}
): Promise<void> {
const db = getInstance();
db.prepare<Query>(
`
UPDATE conversations
SET json = JSON_PATCH(json, $patch);
`
).run({
patch: JSON.stringify({
conversationColor: conversationColor || null,
customColor: customColorData?.value || null,
customColorId: customColorData?.id || null,
}),
});
}
2022-07-08 20:46:25 +00:00
async function removeAllProfileKeyCredentials(): Promise<void> {
const db = getInstance();
db.exec(
`
UPDATE conversations
SET
json = json_remove(json, '$.profileKeyCredential')
`
);
}