1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package main

// What the reader has seen.
//
// Stud.IP has its own idea of it (object_user_visits), written when a page is
// opened on Digicampus and readable only from its HTML pages; campusweb never
// opens those pages, and a reader who reads here never makes them either. So
// campusweb keeps its own: every row of changes is unseen until the reader
// opens what it is about in a browser, or marks it seen. See SEEN in
// campusweb(1) and campusweb(7).

import (
	"database/sql"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"codeberg.org/Profpatsch/Profpatsch/users/Profpatsch/mailtext"
)

// readerOpened says whether a request is a person opening the page in a
// browser, which is what makes what it shows seen.
//
// Not the text rendering: that is how agents and scripts read the mirror,
// and their reading is not the reader's. Not anything a browser fetches on
// its own — a prefetch, or a page elsewhere embedding the URL as an image —
// which Sec-Fetch-Dest and Sec-Purpose tell apart from a navigation. A
// browser that sends neither (an old one, or plain http to a non-local host,
// where they are withheld) counts as a navigation: marking something seen is
// the worst an embedding page could do with it.
func readerOpened(r *http.Request) bool {
	if r.Method != http.MethodGet || mailtext.WantsLLM(r) {
		return false
	}
	if d := r.Header.Get("Sec-Fetch-Dest"); d != "" && d != "document" {
		return false
	}
	for _, h := range []string{"Sec-Purpose", "Purpose", "X-Moz"} {
		if v := strings.ToLower(r.Header.Get(h)); strings.Contains(v, "prefetch") || strings.Contains(v, "prerender") {
			return false
		}
	}
	return true
}

// unseenWhere collects the unseen changes matching where (on changes aliased
// ch), returning how many there are per item id, and marks them seen when
// the reader opened the page. What arrives between the two is not touched:
// only changes up to the newest one read are marked.
func (s *server) unseenWhere(r *http.Request, where string, args ...any) map[string]int {
	rows, err := s.db.Read.Query(`SELECT ch.id, ch.item_id FROM changes ch WHERE ch.seen_at IS NULL AND `+where, args...)
	if err != nil {
		return nil
	}
	out := map[string]int{}
	var maxID int64
	for rows.Next() {
		var id int64
		var item string
		if rows.Scan(&id, &item) == nil {
			out[item]++
			maxID = max(maxID, id)
		}
	}
	rows.Close()
	if maxID > 0 && readerOpened(r) {
		s.db.Write.Exec(`UPDATE changes AS ch SET seen_at = unixepoch() WHERE ch.seen_at IS NULL AND ch.id <= ? AND `+where,
			append([]any{maxID}, args...)...)
	}
	return out
}

// unseenItem is unseenWhere for the changes of one item.
func (s *server) unseenItem(r *http.Request, kind, id string) bool {
	return len(s.unseenWhere(r, `ch.kind = ? AND ch.item_id = ?`, kind, id)) > 0
}

// courseNew is what in one course has unseen changes, by item id, for the
// course page's markers.
type courseNew struct {
	Files       map[string]int
	News        map[string]int
	Events      map[string]int
	Discussions map[string]int
	Pages       map[string]int // wiki and information pages
	Wiki, Info  int            // pages of each kind with unseen changes
	Total       int
}

func courseUnseen(db *sql.DB, courseID string) courseNew {
	n := courseNew{Files: map[string]int{}, News: map[string]int{}, Events: map[string]int{}, Discussions: map[string]int{},
		Pages: map[string]int{}}
	rows, err := db.Query(`SELECT ch.kind, ch.item_id, coalesce(p.discussion_id, '') FROM changes ch
		LEFT JOIN forum_postings p ON ch.kind = 'posting' AND p.id = ch.item_id
		WHERE ch.seen_at IS NULL AND ch.course_id = ?`, courseID)
	if err != nil {
		return n
	}
	defer rows.Close()
	for rows.Next() {
		var kind, id, disc string
		if rows.Scan(&kind, &id, &disc) != nil {
			continue
		}
		n.Total++
		switch kind {
		case "file":
			n.Files[id]++
		case "news":
			n.News[id]++
		case "event":
			n.Events[id]++
		case "posting":
			n.Discussions[disc]++
		case "wiki", "info":
			if n.Pages[id] == 0 {
				if kind == "wiki" {
					n.Wiki++
				} else {
					n.Info++
				}
			}
			n.Pages[id]++
		}
	}
	return n
}

// unseenCount is the number of unseen changes under a semester filter.
func unseenCount(db *sql.DB, f semesterFilter) int {
	where, args := f.changeCond()
	var n int
	db.QueryRow(`SELECT count(*) FROM changes ch WHERE ch.seen_at IS NULL AND `+where, args...).Scan(&n)
	return n
}

// maxChangeID is the newest change, for a "mark seen" form: it marks what the
// page showed, not what arrived after.
func maxChangeID(db *sql.DB) int64 {
	var n int64
	db.QueryRow(`SELECT coalesce(max(id), 0) FROM changes`).Scan(&n)
	return n
}

// handleSeen marks changes seen on request: those of one course, or all of
// them under the semester filter, up to the change id the page was made with.
func (s *server) handleSeen(w http.ResponseWriter, r *http.Request) {
	if !s.sameOrigin(r) {
		http.Error(w, "cross-site request refused", http.StatusForbidden)
		return
	}
	before, err := strconv.ParseInt(r.FormValue("before"), 10, 64)
	if err != nil || before < 1 {
		s.fail(w, r, badRequest("before= must be the newest change id the page showed"))
		return
	}
	where, args := `ch.id <= ?`, []any{before}
	switch course, all := r.FormValue("course"), r.FormValue("all"); {
	case course != "" && all == "":
		where += ` AND ch.course_id = ?`
		args = append(args, course)
	case course == "" && all == "1":
		sem, err := resolveSemester(s.db.Read, r.FormValue("semester"))
		if err != nil {
			s.fail(w, r, badRequest("%v", err))
			return
		}
		cond, cargs := sem.changeCond()
		where += ` AND ` + cond
		args = append(args, cargs...)
	default:
		s.fail(w, r, badRequest("give either course=<id> or all=1"))
		return
	}
	res, err := s.db.Write.Exec(`UPDATE changes AS ch SET seen_at = unixepoch() WHERE ch.seen_at IS NULL AND `+where, args...)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	n, _ := res.RowsAffected()
	if mailtext.WantsLLM(r) {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		fmt.Fprintf(w, "%d change(s) marked seen\n", n)
		return
	}
	back := r.FormValue("back")
	if !strings.HasPrefix(back, "/") || strings.HasPrefix(back, "//") || strings.HasPrefix(back, "/\\") {
		back = "/"
	}
	http.Redirect(w, r, back, http.StatusSeeOther)
}