@@ -55,7 +55,15 @@ func (s *Server) handleChannels(c *gin.Context) {
5555 for _, u := range s.hub.roster() {
5656 users[u.ID] = u.Username
5757 }
58- rows, err := s.db.Query(`SELECT id, type, name, position, permanent FROM channels ORDER BY position, id`)
58+ rows, err := s.db.Query(
59+ `SELECT c.id, c.type, c.name, c.position, c.permanent,
60+ (SELECT COUNT(*) FROM messages m
61+ WHERE m.channel_id = c.id AND m.user_id != ?
62+ AND m.id > COALESCE((SELECT r.last_read_message_id FROM read_state r
63+ WHERE r.user_id = ? AND r.channel_id = c.id), 0))
64+ FROM channels c ORDER BY c.position, c.id`,
65+ user.ID, user.ID,
66+ )
5967 if err != nil {
6068 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
6169 return
@@ -64,7 +72,7 @@ func (s *Server) handleChannels(c *gin.Context) {
6472 channels := []Channel{}
6573 for rows.Next() {
6674 var ch Channel
67- if err := rows.Scan(&ch.ID, &ch.Type, &ch.Name, &ch.Position, &ch.Permanent); err != nil {
75+ if err := rows.Scan(&ch.ID, &ch.Type, &ch.Name, &ch.Position, &ch.Permanent, &ch.Unread); err != nil {
6876 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
6977 return
7078 }
@@ -87,6 +95,39 @@ func (s *Server) handleChannels(c *gin.Context) {
8795 c.JSON(http.StatusOK, channels)
8896 }
8997
98+// handleMarkRead advances the caller's read cursor for a channel to the latest
99+// message, clearing its unread count for every device they use.
100+func (s *Server) handleMarkRead(c *gin.Context) {
101+ channelID, err := strconv.ParseInt(c.Param("id"), 10, 64)
102+ if err != nil {
103+ c.JSON(http.StatusBadRequest, gin.H{"error": "bad channel"})
104+ return
105+ }
106+ user := c.MustGet("user").(User)
107+ if _, _, ok := s.checkTextOrDM(c, channelID, user.ID); !ok {
108+ return
109+ }
110+ var lastID int64
111+ if err := s.db.QueryRow(
112+ `SELECT COALESCE(MAX(id), 0) FROM messages WHERE channel_id = ?`, channelID,
113+ ).Scan(&lastID); err != nil {
114+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
115+ return
116+ }
117+ if _, err := s.db.Exec(
118+ `INSERT INTO read_state (user_id, channel_id, last_read_message_id, updated_at)
119+ VALUES (?, ?, ?, ?)
120+ ON CONFLICT(user_id, channel_id) DO UPDATE SET
121+ last_read_message_id = MAX(last_read_message_id, excluded.last_read_message_id),
122+ updated_at = excluded.updated_at`,
123+ user.ID, channelID, lastID, time.Now().Unix(),
124+ ); err != nil {
125+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
126+ return
127+ }
128+ c.Status(http.StatusNoContent)
129+}
130+
90131 type createChannelRequest struct {
91132 Type string `json:"type"`
92133 Name string `json:"name"`