CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/database/postgres/messages.ts
Views: 791
1
/*
2
Compute the number of unread *threads* in the inbox for a given user directly from
3
the database.
4
5
This is one of those things that is HARD, EASY TO BREAK, and MUST BE CORRECT!
6
Otherwise, it will drive a user (me) crazy, where there will be a big counter
7
with a "1" saying "you have one unread message", but it impossible to make
8
that counter go down!
9
*/
10
11
import getPool from "@cocalc/database/pool";
12
import { NUM_MESSAGES, pgBitField } from "@cocalc/util/db-schema/messages";
13
14
export async function updateUnreadMessageCount({ account_id }) {
15
const pool = getPool();
16
17
// have to use a subquery because we want to restrict only to the most recent NUM_MESSAGES messages, since that's
18
// what we provide the user. If they have 300 read messages and message 301 is unread, the count is still 0 -- it's too
19
// old to matter... for the inbox counter.
20
const query = `
21
SELECT COUNT(DISTINCT(thread_id)) AS unread_count
22
FROM (
23
SELECT
24
${pgBitField("read", account_id)},
25
${pgBitField("saved", account_id)},
26
${pgBitField("deleted", account_id)},
27
CASE WHEN thread_id IS NULL OR thread_id = 0 THEN id ELSE thread_id END AS thread_id
28
FROM messages
29
WHERE $1=ANY(to_ids) AND sent IS NOT NULL
30
ORDER BY id DESC
31
LIMIT ${NUM_MESSAGES}
32
) AS subquery
33
WHERE read=false AND saved=false AND deleted=false`;
34
const { rows: counts } = await pool.query(query, [account_id]);
35
36
const { unread_count } = counts[0];
37
await pool.query(
38
"UPDATE accounts SET unread_message_count=$1 WHERE account_id=$2",
39
[unread_count, account_id],
40
);
41
}
42
43