Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/src/packages/database/postgres/messages.ts
Views: 791
/*1Compute the number of unread *threads* in the inbox for a given user directly from2the database.34This is one of those things that is HARD, EASY TO BREAK, and MUST BE CORRECT!5Otherwise, it will drive a user (me) crazy, where there will be a big counter6with a "1" saying "you have one unread message", but it impossible to make7that counter go down!8*/910import getPool from "@cocalc/database/pool";11import { NUM_MESSAGES, pgBitField } from "@cocalc/util/db-schema/messages";1213export async function updateUnreadMessageCount({ account_id }) {14const pool = getPool();1516// have to use a subquery because we want to restrict only to the most recent NUM_MESSAGES messages, since that's17// what we provide the user. If they have 300 read messages and message 301 is unread, the count is still 0 -- it's too18// old to matter... for the inbox counter.19const query = `20SELECT COUNT(DISTINCT(thread_id)) AS unread_count21FROM (22SELECT23${pgBitField("read", account_id)},24${pgBitField("saved", account_id)},25${pgBitField("deleted", account_id)},26CASE WHEN thread_id IS NULL OR thread_id = 0 THEN id ELSE thread_id END AS thread_id27FROM messages28WHERE $1=ANY(to_ids) AND sent IS NOT NULL29ORDER BY id DESC30LIMIT ${NUM_MESSAGES}31) AS subquery32WHERE read=false AND saved=false AND deleted=false`;33const { rows: counts } = await pool.query(query, [account_id]);3435const { unread_count } = counts[0];36await pool.query(37"UPDATE accounts SET unread_message_count=$1 WHERE account_id=$2",38[unread_count, account_id],39);40}414243