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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
package main

import (
	"database/sql"
	_ "embed"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"net/url"
	"regexp"
	"slices"
	"sort"
	"strconv"
	"strings"
	"time"

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

// ============================================================================
// Forge notification templates
// ============================================================================

//go:embed templates/forge.html
var forgeTmplSrc string

//go:embed templates/forge_repo.html
var forgeRepoTmplSrc string

var (
	forgeTmpl     = template.Must(template.New("forge").Funcs(accountTmplFuncs).Parse(forgeTmplSrc))
	forgeRepoTmpl = template.Must(template.New("forgerepo").Funcs(accountTmplFuncs).Parse(forgeRepoTmplSrc))
)

// ============================================================================
// Forge data types
// ============================================================================

// forgePageData is passed to templates/forge.html. The template took a bare
// slice until the text-view link needed a URL alongside it.
type forgePageData struct {
	Repos      []forgeRepoEntry
	LLMViewURL string
}

// forgeRepoPageData is passed to templates/forge_repo.html.
type forgeRepoPageData struct {
	Repo string
	// RepoEscaped is the same name path-escaped, for the alternate link, which
	// names the route rather than the current URL and so cannot reuse
	// LLMViewURL.
	RepoEscaped string
	Threads     []forgeThread
	LLMViewURL  string
}

// forgeRepoEntry is one row in the forge repo listing.
type forgeRepoEntry struct {
	Repo        string // e.g. "NixOS/nixpkgs"
	RepoEscaped string // url.PathEscape(Repo)
	LastSeen    time.Time
	Count       int
}

// forgeMsgRow is one message in a forge repo view.
type forgeMsgRow struct {
	ID        int64
	Subject   string
	Date      time.Time
	Reason    string // x-github-reason value, e.g. "pull", "issue"
	Sender    string // x-github-sender value, e.g. "octocat"
	IsNew     bool   // true if sender was inactive in this repo for >90 days before this message
	GapToPrev string // human-readable gap since sender's last message, e.g. "1y5m23d", "" if first

	// SizeHint annotates what reading this message costs, like " (~4K)", or ""
	// when the size is not known. Only the text rendering prints it; the HTML
	// view frames bodies itself and never asks the reader to decide.
	SizeHint string
}

// formatGap formats a duration as a compact human-readable string like "1y5m23d".
func formatGap(d time.Duration) string {
	if d <= 0 {
		return ""
	}
	totalDays := int(d.Hours() / 24)
	years := totalDays / 365
	days := totalDays % 365
	months := days / 30
	days = days % 30

	s := ""
	if years > 0 {
		s += fmt.Sprintf("%dy", years)
	}
	if months > 0 {
		s += fmt.Sprintf("%dm", months)
	}
	if days > 0 || s == "" {
		s += fmt.Sprintf("%dd", days)
	}
	return s
}

// involvementRank maps x-github-reason values to a priority score.
// Higher = more directly involved. A thread displays the highest rank any of
// its messages carries, so what this orders is which one line of a thread's
// summary is worth reading first.
//
// The ranking is by what the message asks of the reader, not by how close to
// the thread they are. A review request and a mention are both somebody waiting
// on an answer; your_activity and ci_activity are reports about things that
// already happened, and rank below subscribed rather than above it despite
// naming the reader directly — a notification that cannot be acted on should
// not outrank one that can.
//
// Every value the forges emit is listed, including the ones that rank zero.
// Absence and a rank of zero are the same number in Go, so an unlisted value is
// indistinguishable from a deliberate bottom rank, and the map is the only
// place that distinction can be recorded.
var involvementRank = map[string]int{
	// Somebody is waiting on the reader.
	"security_alert":   8, // a vulnerability in a repo the reader can fix
	"author":           7, // the reader opened the thread
	"assign":           6,
	"review_requested": 5,
	"mention":          4,
	"team_mention":     4, // as above, addressed to a team the reader is in
	"comment":          3, // the reader has spoken in the thread before
	"manual":           2, // the reader subscribed to this thread specifically
	"state_change":     1,
	// Merely watching: the notification reports what somebody else did.
	"subscribed": 0,
	"pull":       0, // Forgejo/Gitea say what the thread is, not why it arrived
	"issue":      0,
	"push":       0,
	// Reports about the reader that ask nothing of them.
	"your_activity": 0,
	"ci_activity":   0,
}

// forgeThread groups messages belonging to the same issue/PR.
type forgeThread struct {
	Num             int    // issue/PR number, 0 if unknown
	Title           string // clean title, or first subject if unparseable
	URL             string // link to the issue/PR on the forge, e.g. https://github.com/NixOS/nixpkgs/issues/123
	LastDate        time.Time
	Involvement     string          // highest x-github-reason across all messages
	Participants    []string        // unique x-github-sender values, in order of first appearance
	NewParticipants map[string]bool // senders who have at least one "new" message in this thread
	Messages        []forgeMsgRow

	// Count is how many messages the thread holds, which is not len(Messages)
	// once the text rendering has capped the list; Omitted is the difference.
	// Both are zero-cost in the HTML view, which shows every message.
	Count   int
	Omitted int
}

// capMessages trims each thread to its n most recent messages, recording how
// many were left out so the rendering can say so.
//
// A thread is unbounded in a way the thread count is not: one ghc-proposals
// discussion in this archive is 473 messages under a single subject, so paging
// threads alone would still hand a client a page of thousands of lines. Paging
// the messages *within* a thread instead would be worse than a cap: the entries
// are notifications about one discussion, and a reader who wants all of them
// wants the discussion, which is on the forge and is what the thread URL is
// for.
//
// The threads are modified in place, on the already-paged slice, so this costs
// nothing on the threads nobody asked for.
func capMessages(threads []forgeThread, n int) {
	for i := range threads {
		t := &threads[i]
		t.Count = len(t.Messages)
		if n >= 0 && t.Count > n {
			t.Messages = t.Messages[:n]
			t.Omitted = t.Count - n
		}
	}
}

// forgeThreadURL constructs the URL for an issue/PR given the forge host,
// repo (e.g. "NixOS/nixpkgs") and number. GitHub redirects /issues/N to
// /pull/N if needed, so we always use /issues/.
// Codeberg/Forgejo use /issues/ for both.
func forgeThreadURL(host, repo string, num int) string {
	if num == 0 {
		return ""
	}
	switch host {
	case "github.com":
		return fmt.Sprintf("https://github.com/%s/issues/%d", repo, num)
	case "codeberg.org":
		return fmt.Sprintf("https://codeberg.org/%s/issues/%d", repo, num)
	default:
		// Generic Gitea/Forgejo: host is the full domain.
		return fmt.Sprintf("https://%s/%s/issues/%d", host, repo, num)
	}
}

// forgeHeaderName is the header used to identify forge notifications.
// Present on messages from GitHub, Codeberg (Forgejo/Gitea) and compatible
// forges. Used to exclude forge messages from the contacts view.
const forgeHeaderName = "x-github-sender"

// forgeSubjectRe matches subjects like:
//
//	[org/repo] Some title (PR #123)
//	Re: [org/repo] Some title (Issue #456)
var forgeSubjectRe = regexp.MustCompile(`(?:Re: )?\[[^\]]+\] (.+?)\s*\([^)]*#(\d+)\)\s*$`)

// parseForgeSubject extracts (threadTitle, threadNum) from a forge notification
// subject line. Returns ("", 0) if the subject doesn't match.
func parseForgeSubject(subject string) (title string, num int) {
	m := forgeSubjectRe.FindStringSubmatch(subject)
	if m == nil {
		return "", 0
	}
	n := 0
	fmt.Sscanf(m[2], "%d", &n)
	return m[1], n
}

// ============================================================================
// Forge HTTP handlers
// ============================================================================

func (s *server) handleForge(w http.ResponseWriter, r *http.Request) {
	rows, err := s.db.Read.Query(`
		SELECT
		  TRIM(SUBSTR(mh.value, 1,
		    CASE WHEN INSTR(mh.value, '<') > 0
		         THEN INSTR(mh.value, '<') - 1
		         ELSE LENGTH(mh.value) + 1 END
		  )) AS repo,
		  COUNT(DISTINCT mh.message_id) AS msg_count,
		  MAX(m.date) AS last_date
		FROM message_headers mh
		JOIN messages m ON m.id = mh.message_id
		WHERE mh.name = 'list-id'
		  AND mh.message_id IN (
		    SELECT message_id FROM message_headers WHERE name = ?
		  )
		GROUP BY repo
		ORDER BY last_date DESC
	`, forgeHeaderName)
	if err != nil {
		http.Error(w, fmt.Sprintf("db error: %v", err), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	var repos []forgeRepoEntry
	for rows.Next() {
		var e forgeRepoEntry
		var unixDate int64
		if err := rows.Scan(&e.Repo, &e.Count, &unixDate); err != nil {
			http.Error(w, fmt.Sprintf("scan: %v", err), http.StatusInternalServerError)
			return
		}
		e.Repo = strings.TrimSpace(e.Repo)
		e.RepoEscaped = url.PathEscape(e.Repo)
		e.LastSeen = time.Unix(unixDate, 0)
		repos = append(repos, e)
	}
	if err := rows.Err(); err != nil {
		http.Error(w, fmt.Sprintf("rows: %v", err), http.StatusInternalServerError)
		return
	}

	if mailtext.WantsLLM(r) {
		// A repo listing is one line and one link per repo, and there are
		// hundreds; page it like every other listing so that a single request
		// stays a page rather than a file.
		p := mailtext.ParsePaging(r, len(repos), mailtext.DefaultLimit)
		writeLLM(w, r, forgeLLMTmpl, forgeLLMData{
			Repos:       mailtext.SlicePage(repos, p),
			Paging:      p,
			HTMLViewURL: mailtext.HTMLViewURL(r),
		})
		return
	}

	mailtext.SetAlternate(w, r.URL.Path)
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := forgeTmpl.Execute(w, forgePageData{
		Repos:      repos,
		LLMViewURL: mailtext.LLMViewURL(r),
	}); err != nil {
		log.Printf("forge template: %v", err)
	}
}

func (s *server) handleForgeRepo(w http.ResponseWriter, r *http.Request) {
	repo := strings.TrimSpace(r.PathValue("repo"))
	if repo == "" {
		// A bare /forge/ is a truncated URL rather than a request for a
		// repository named "", and the listing is where it was heading.
		http.Redirect(w, r, "/forge", http.StatusFound)
		return
	}

	// Extract the forge host from the list-id value, e.g. "github.com" from
	// "nixpkgs.NixOS.github.com". The list-id looks like "org/repo <sub.host>".
	forgeHost := ""
	{
		var listID string
		_ = s.db.Read.QueryRow(`
			SELECT value FROM message_headers
			WHERE name = 'list-id'
			  AND TRIM(SUBSTR(value, 1,
			        CASE WHEN INSTR(value, '<') > 0
			             THEN INSTR(value, '<') - 1
			             ELSE LENGTH(value) + 1 END
			      )) = ?
			LIMIT 1`, repo).Scan(&listID)
		// listID looks like "NixOS/nixpkgs <nixpkgs.NixOS.github.com>"
		// Extract the host inside < >, then take the last two dot-separated parts.
		if i := strings.Index(listID, "<"); i >= 0 {
			sub := strings.TrimRight(listID[i+1:], ">")
			parts := strings.Split(sub, ".")
			if len(parts) >= 2 {
				forgeHost = parts[len(parts)-2] + "." + parts[len(parts)-1]
			}
		}
	}

	// Find all message IDs for this repo via list-id, joined with sender/reason.
	//
	// The size columns come along on the same row, so the text rendering can
	// annotate what following a link costs without a second query; see
	// mailtext.SizeHint.
	rows, err := s.db.Read.Query(`
		SELECT
		  m.id, m.subject, m.date,
		  (SELECT value FROM message_headers
		   WHERE message_id = m.id AND name = 'x-github-reason' LIMIT 1) AS reason,
		  (SELECT value FROM message_headers
		   WHERE message_id = m.id AND name = ? LIMIT 1) AS sender,
		  LENGTH(m.display_part), m.rfc822_size
		FROM messages m
		JOIN message_headers mh_list ON mh_list.message_id = m.id
		WHERE mh_list.name = 'list-id'
		  AND TRIM(SUBSTR(mh_list.value, 1,
		    CASE WHEN INSTR(mh_list.value, '<') > 0
		         THEN INSTR(mh_list.value, '<') - 1
		         ELSE LENGTH(mh_list.value) + 1 END
		  )) = ?
		ORDER BY m.date DESC
	`, forgeHeaderName, repo)
	if err != nil {
		http.Error(w, fmt.Sprintf("db error: %v", err), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	var msgs []forgeMsgRow
	for rows.Next() {
		var msg forgeMsgRow
		var unixDate int64
		var reason, sender sql.NullString
		var partLen, rawSize sql.NullInt64
		if err := rows.Scan(&msg.ID, &msg.Subject, &unixDate, &reason, &sender,
			&partLen, &rawSize); err != nil {
			http.Error(w, fmt.Sprintf("scan: %v", err), http.StatusInternalServerError)
			return
		}
		msg.Date = time.Unix(unixDate, 0)
		msg.Reason = reason.String
		msg.Sender = sender.String
		msg.SizeHint = mailtext.SizeHint(partLen.Int64, rawSize.Int64)
		msgs = append(msgs, msg)
	}
	if err := rows.Err(); err != nil {
		http.Error(w, fmt.Sprintf("rows: %v", err), http.StatusInternalServerError)
		return
	}

	// A repo no message names is not a repo, and answers 404 rather than an
	// empty listing — the same rule /contact/{addr} follows, for the same
	// reason: this page mints links out of the name it was handed, so rendering
	// one for a repo nothing was sent from turns a typed URL into hyperlinks
	// that appear to come from mailweb.
	if len(msgs) == 0 {
		http.NotFound(w, r)
		return
	}

	// Group into threads by issue/PR number.
	// threadOrder tracks insertion order so we can sort threads by num DESC.
	type threadKey struct {
		num   int
		title string
	}
	byNum := make(map[int]*forgeThread)
	var threadNums []int
	for _, msg := range msgs {
		title, num := parseForgeSubject(msg.Subject)
		t, ok := byNum[num]
		if !ok {
			if title == "" {
				title = msg.Subject
			}
			t = &forgeThread{
				Num:   num,
				Title: title,
				URL:   forgeThreadURL(forgeHost, repo, num),
			}
			byNum[num] = t
			threadNums = append(threadNums, num)
		}
		t.Messages = append(t.Messages, msg)
		if msg.Date.After(t.LastDate) {
			t.LastDate = msg.Date
		}
		// Track max involvement level across messages.
		if involvementRank[msg.Reason] > involvementRank[t.Involvement] {
			t.Involvement = msg.Reason
		}
		// Track unique participants in order of first appearance.
		if msg.Sender != "" {
			found := slices.Contains(t.Participants, msg.Sender)
			if !found {
				t.Participants = append(t.Participants, msg.Sender)
			}
		}
	}

	// Sort threads by most recent message first.
	sort.Slice(threadNums, func(i, j int) bool {
		return byNum[threadNums[i]].LastDate.After(byNum[threadNums[j]].LastDate)
	})

	threads := make([]forgeThread, 0, len(threadNums))
	for _, num := range threadNums {
		t := byNum[num]
		// Within each thread, sort reverse chronologically (most recent first).
		sort.Slice(t.Messages, func(i, j int) bool {
			return t.Messages[i].Date.After(t.Messages[j].Date)
		})
		threads = append(threads, *t)
	}

	// Mark which messages are from a "new" sender — someone who hadn't posted
	// in this repo for >90 days before this specific message.
	newMsgs, err := markNewMessages(s.db.Read, repo, 90*24*time.Hour)
	if err != nil {
		log.Printf("forge: markNewMessages: %v", err)
		// Non-fatal — render without new-sender highlighting.
	}
	for i := range threads {
		threads[i].NewParticipants = make(map[string]bool)
		for j := range threads[i].Messages {
			a := newMsgs[threads[i].Messages[j].ID]
			threads[i].Messages[j].IsNew = a.isNew
			threads[i].Messages[j].GapToPrev = a.gap
			if a.isNew && threads[i].Messages[j].Sender != "" {
				threads[i].NewParticipants[threads[i].Messages[j].Sender] = true
			}
		}
	}

	if mailtext.WantsLLM(r) {
		// Bounded in both dimensions: threads per page, and messages per
		// thread. Either alone leaves a page unbounded — see capMessages.
		p := mailtext.ParsePaging(r, len(threads), mailtext.DefaultLimit)
		paged := mailtext.SlicePage(threads, p)
		limit := forgeMsgLimit(r)
		capMessages(paged, limit)
		writeLLM(w, r, forgeRepoLLMTmpl, forgeRepoLLMData{
			Repo:        repo,
			Threads:     paged,
			MsgLimit:    limit,
			Paging:      p,
			HTMLViewURL: mailtext.HTMLViewURL(r),
		})
		return
	}

	mailtext.SetAlternate(w, r.URL.Path)
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := forgeRepoTmpl.Execute(w, forgeRepoPageData{
		Repo:        repo,
		RepoEscaped: url.PathEscape(repo),
		Threads:     threads,
		LLMViewURL:  mailtext.LLMViewURL(r),
	}); err != nil {
		log.Printf("forge repo template: %v", err)
	}
}

// defaultForgeMsgLimit is how many of a thread's messages the text rendering
// lists. Five is enough to see who is currently talking and how recently,
// which is what a thread summary is for; the discussion itself lives on the
// forge, one link away.
const defaultForgeMsgLimit = 5

// forgeMsgLimit reads ?msgs=N, the per-thread message cap. A negative value
// means no cap, so that a reader who does want a whole thread can ask for it
// without guessing a number larger than the biggest thread.
func forgeMsgLimit(r *http.Request) int {
	v := r.URL.Query().Get("msgs")
	if v == "" {
		return defaultForgeMsgLimit
	}
	n, err := strconv.Atoi(v)
	if err != nil {
		return defaultForgeMsgLimit
	}
	if n < 0 {
		return -1
	}
	return n
}

type msgActivity struct {
	isNew bool
	gap   string // formatted gap to sender's previous message, "" if first
}

// markNewMessages uses a LAG window function to find, for each message in the
// repo, the sender's previous message date in the same repo. If the gap is
// greater than threshold (or they have no prior message), the message is
// marked as "new". The gap to the previous message is also returned.
func markNewMessages(db *sql.DB, repo string, threshold time.Duration) (map[int64]msgActivity, error) {
	const repoExpr = `TRIM(SUBSTR(mh_list.value, 1,
		        CASE WHEN INSTR(mh_list.value, '<') > 0
		             THEN INSTR(mh_list.value, '<') - 1
		             ELSE LENGTH(mh_list.value) + 1 END
		      ))`
	rows, err := db.Query(`
		SELECT id, date, prev_date FROM (
		  SELECT
		    m.id,
		    m.date,
		    LAG(m.date) OVER (
		      PARTITION BY mh_sender.value
		      ORDER BY m.date
		    ) AS prev_date
		  FROM messages m
		  JOIN message_headers mh_sender ON mh_sender.message_id = m.id
		  JOIN message_headers mh_list   ON mh_list.message_id   = m.id
		  WHERE mh_sender.name = 'x-github-sender'
		    AND mh_list.name   = 'list-id'
		    AND `+repoExpr+` = ?
		)`, repo)
	if err != nil {
		return nil, fmt.Errorf("query: %w", err)
	}
	defer rows.Close()

	result := make(map[int64]msgActivity)
	for rows.Next() {
		var id, date int64
		var prevDate sql.NullInt64
		if err := rows.Scan(&id, &date, &prevDate); err != nil {
			return nil, fmt.Errorf("scan: %w", err)
		}
		var gap string
		isNew := !prevDate.Valid
		if prevDate.Valid {
			diff := time.Duration(date-prevDate.Int64) * time.Second
			gap = formatGap(diff)
			isNew = diff > threshold
		}
		result[id] = msgActivity{isNew: isNew, gap: gap}
	}
	return result, rows.Err()
}