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
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"io"
	"log"
	"mime"
	"net/http"
	"path"
	"strconv"
	"strings"
	"time"

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

func (s *server) routes() *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /{$}", s.handleIndex)
	mux.HandleFunc("GET /semesters", s.handleSemesters)
	mux.HandleFunc("GET /courses", s.handleCourses)
	mux.HandleFunc("GET /course/{id}", s.handleCourse)
	mux.HandleFunc("GET /course/{id}/forum", s.handleForum)
	mux.HandleFunc("GET /folder/{id}", s.handleFolder)
	mux.HandleFunc("GET /file/{id}", s.handleFile)
	mux.HandleFunc("GET /file/{id}/content", s.handleContent)
	mux.HandleFunc("GET /file/{id}/inline", s.handleInline)
	mux.HandleFunc("GET /file/{id}/version/{n}/inline", s.handleInline)
	mux.HandleFunc("GET /file/{id}/version/{n}", s.handleContent)
	mux.HandleFunc("GET /file/{id}/version/{n}/annotated", s.handleAnnotated)
	mux.HandleFunc("GET /file/{id}/version/{n}/image/{k}", s.handleDocImage)
	// Provenance: derived versions and claims; see derived.go, claims.go.
	mux.HandleFunc("POST /file/{id}/version/{n}/derived", s.handleDerive)
	mux.HandleFunc("GET /derived/{k}", s.handleDerived)
	mux.HandleFunc("GET /derived/{k}/text", s.handleDerivedText)
	mux.HandleFunc("POST /derived/{k}/withdraw", s.handleWithdrawDerived)
	// Own files; see ownfiles.go.
	mux.HandleFunc("POST /course/{id}/own", s.handleAddOwn)
	mux.HandleFunc("POST /file/{id}/version", s.handleOwnVersion)
	mux.HandleFunc("POST /file/{id}/withdraw", s.handleWithdrawOwn)
	mux.HandleFunc("POST /course/{id}/claims", s.handleClaims)
	mux.HandleFunc("POST /claim/{id}/withdraw", s.handleWithdrawClaim)
	mux.HandleFunc("GET /source/{kind}/{id}", s.handleSource)
	// The viewer frame's own routes, authorised by their URL; see frame.go.
	mux.HandleFunc("GET /frame/{cap}/pdf", s.framed(s.handleFramePDF))
	mux.HandleFunc("POST /frame/{cap}/notes", s.framed(s.handleFrameNotes))
	mux.HandleFunc("GET /news/{id}", s.handleNews)
	mux.HandleFunc("GET /messages", s.handleMessages)
	mux.HandleFunc("GET /msg/{id}", s.handleMessage)
	mux.HandleFunc("GET /discussion/{id}", s.handleDiscussion)
	mux.HandleFunc("GET /posting/{id}", s.handlePosting)
	mux.HandleFunc("GET /page/{id}", s.handlePage)
	mux.HandleFunc("GET /dates", s.handleDates)
	mux.HandleFunc("GET /status", s.handleStatus)
	mux.HandleFunc("GET /login", s.handleLoginForm)
	mux.HandleFunc("POST /login", s.handleLogin)
	mux.HandleFunc("POST /sync", s.handleSync)
	mux.HandleFunc("POST /seen", s.handleSeen)
	mux.HandleFunc("GET "+pdfjs.Prefix, pdfjs.Handler(s.db.Read))
	return mux
}

// sameOrigin refuses a POST that a browser says came from another site.
// campusweb has no authentication, so any page could otherwise post a cookie
// of its choosing to /login and swap the account under the mirror.
func (s *server) sameOrigin(r *http.Request) bool {
	if site := r.Header.Get("Sec-Fetch-Site"); site != "" && site != "same-origin" && site != "none" {
		return false
	}
	want := "http://" + r.Host
	if s.origin != "" {
		want = s.origin
	}
	if o := r.Header.Get("Origin"); o != "" && o != "null" && o != want {
		return false
	}
	return true
}

func (s *server) chrome(r *http.Request, title string) (chrome, error) {
	c := chrome{Title: title, Path: r.URL.Path, LLMURL: mailtext.LLMViewURL(r), Session: s.c.current(), Base: s.c.base}
	if c.Session == nil {
		var died int64
		s.db.Read.QueryRow(`SELECT coalesce(max(died_at),0) FROM sessions`).Scan(&died)
		c.DeadSince = unixOrZero(died)
	}
	c.Running, _ = s.sync.state()
	var last int64
	s.db.Read.QueryRow(`SELECT coalesce(max(finished_at),0) FROM sync_runs WHERE error IS NULL`).Scan(&last)
	c.LastSync = unixOrZero(last)
	sem, err := resolveSemester(s.db.Read, r.URL.Query().Get("semester"))
	if err != nil {
		return c, err
	}
	c.Semester = sem
	c.Unseen = unseenCount(s.db.Read, sem)
	c.Before = maxChangeID(s.db.Read)
	c.Back = r.URL.RequestURI()
	c.Semesters, err = semesters(s.db.Read)
	return c, err
}

// fail answers an error in the representation asked for.
func (s *server) fail(w http.ResponseWriter, r *http.Request, err error) {
	status := http.StatusInternalServerError
	switch {
	case errors.Is(err, errNotFound):
		status = http.StatusNotFound
	case errors.Is(err, errBadRequest):
		status = http.StatusBadRequest
	}
	if status == http.StatusInternalServerError {
		log.Printf("%s %s: %v", r.Method, r.URL.Path, err)
	}
	c := chrome{Title: "error", Path: r.URL.Path, Session: s.c.current(), Base: s.c.base}
	s.render(w, r, "error", struct {
		chrome
		Status  int
		Message string
	}{c, status, err.Error()}, status)
}

var errBadRequest = errors.New("bad request")

func badRequest(format string, args ...any) error {
	return fmt.Errorf("%w: %s", errBadRequest, fmt.Sprintf(format, args...))
}

// ============================================================================
// The feed
// ============================================================================

func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) {
	c, err := s.chrome(r, "what's new")
	if err != nil {
		s.fail(w, r, badRequest("%v", err))
		return
	}
	dr, err := mailtext.ParseDateRange(r)
	if err != nil {
		s.fail(w, r, badRequest("%v", err))
		return
	}
	limit := 100
	onlyUnseen := r.URL.Query().Get("unseen") == "1"
	pg := mailtext.ParsePaging(r, 0, limit)
	items, total, err := changes(s.db.Read, c.Semester, onlyUnseen, dr.Since, dr.Until, pg.Limit, pg.Offset)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	pg = mailtext.ParsePaging(r, total, limit)
	// The unseen ones on top, whatever the range, unless they are the list.
	var unseen []changeRow
	if !onlyUnseen && pg.Offset == 0 {
		unseen, _, err = changes(s.db.Read, c.Semester, true, time.Time{}, time.Time{}, 50, 0)
		if err != nil {
			s.fail(w, r, err)
			return
		}
	}
	attachDiffs(s.db.Read, items)
	attachDiffs(s.db.Read, unseen)
	var upcoming []eventRow
	cond, args := c.Semester.cond()
	now := time.Now()
	upcoming, err = eventsQuery(s.db.Read, `e.gone_at IS NULL AND e.end >= ? AND e.start < ?
		AND EXISTS (SELECT 1 FROM courses c WHERE c.id = e.course_id AND c.gone_at IS NULL AND `+cond+`)`,
		append([]any{now.Unix(), now.Add(7 * 24 * time.Hour).Unix()}, args...)...)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	upcoming, err = withClaims(s.db.Read, upcoming, `course_id IN (SELECT c.id FROM courses c WHERE c.gone_at IS NULL AND `+cond+`)`,
		args, now, now.Add(7*24*time.Hour))
	if err != nil {
		s.fail(w, r, err)
		return
	}
	s.render(w, r, "index", struct {
		chrome
		Range         string
		OnlyUnseen    bool
		UnseenChanges []changeRow
		Changes       []changeRow
		Total         int
		Paging        mailtext.Paging
		Upcoming      []eventRow
	}{c, dr.Describe(), onlyUnseen, unseen, items, total, pg, upcoming}, http.StatusOK)
}

// ============================================================================
// Semesters and courses
// ============================================================================

func (s *server) handleSemesters(w http.ResponseWriter, r *http.Request) {
	c, err := s.chrome(r, "semesters")
	if err != nil {
		s.fail(w, r, badRequest("%v", err))
		return
	}
	s.render(w, r, "semesters", c, http.StatusOK)
}

func (s *server) handleCourses(w http.ResponseWriter, r *http.Request) {
	c, err := s.chrome(r, "courses")
	if err != nil {
		s.fail(w, r, badRequest("%v", err))
		return
	}
	cs, err := courses(s.db.Read, c.Semester)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	s.render(w, r, "courses", struct {
		chrome
		Courses []courseRow
	}{c, cs}, http.StatusOK)
}

func (s *server) handleCourse(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	co, err := course(s.db.Read, id)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	c, err := s.chrome(r, co.Title)
	if err != nil {
		s.fail(w, r, badRequest("%v", err))
		return
	}
	withGone := r.URL.Query().Get("gone") == "1"
	tree, err := folderTree(s.db.Read, id, withGone)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	news, err := newsList(s.db.Read, id)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	dates, err := eventsQuery(s.db.Read, `e.course_id = ? AND e.gone_at IS NULL`, id)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	dates, err = withClaims(s.db.Read, dates, `course_id = ?`, []any{id}, time.Time{}, time.Time{})
	if err != nil {
		s.fail(w, r, err)
		return
	}
	facts, err := courseFacts(s.db.Read, id)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	details, err := courseDetails(s.db.Read, id)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	discs, err := discussions(s.db.Read, id)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	info, err := coursePages(s.db.Read, id, "info")
	if err != nil {
		s.fail(w, r, err)
		return
	}
	wiki, err := coursePages(s.db.Read, id, "wiki")
	if err != nil {
		s.fail(w, r, err)
		return
	}
	own, err := ownFiles(s.db.Read, id)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	var gone int
	s.db.Read.QueryRow(`SELECT count(*) FROM files WHERE course_id = ? AND gone_at IS NOT NULL`, id).Scan(&gone)
	// Counted before the dates are marked: the page says what was new.
	unseen := courseUnseen(s.db.Read, id)
	// The dates are read in full on this page, and have no page of their own.
	s.unseenWhere(r, `ch.kind = 'event' AND ch.course_id = ?`, id)
	var next *eventRow
	for i := range dates {
		if dates[i].End.After(time.Now()) && !dates[i].Cancelled && !dates[i].Unmatched {
			next = &dates[i]
			break
		}
	}
	s.render(w, r, "course", struct {
		chrome
		Course      courseRow
		Folders     []*folderNode
		Own         []fileRow
		WithGone    bool
		GoneFiles   int
		News        []newsRow
		Dates       []eventRow
		Next        *eventRow
		Discussions []discussionRow
		Info        []pageRow
		Wiki        []pageRow
		New         courseNew
		Facts       []claimView
		Details     []courseDetail
	}{c, co, tree, own, withGone, gone, news, dates, next, discs, info, wiki, unseen, facts, details}, http.StatusOK)
}

// handlePage shows a wiki or information page: its newest text, or with
// ?version=n an older one, and the list of versions.
func (s *server) handlePage(w http.ResponseWriter, r *http.Request) {
	p, err := pageByID(s.db.Read, r.PathValue("id"))
	if err != nil {
		s.fail(w, r, err)
		return
	}
	vs, err := pageVersions(s.db.Read, p.ID)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	if len(vs) == 0 {
		s.fail(w, r, fmt.Errorf("%w: no text of this page is stored", errNotFound))
		return
	}
	pick := func(param string) (pageVersionRow, bool) {
		q := r.URL.Query().Get(param)
		n, err := strconv.Atoi(q)
		for _, v := range vs {
			if err == nil && v.N == n {
				return v, true
			}
		}
		return pageVersionRow{}, false
	}
	shown := vs[0]
	var diff *pageDiff
	switch q := r.URL.Query(); {
	case q.Get("diff") != "":
		// ?diff=n: version n against the one before it, and version n's
		// text below.
		v, ok := pick("diff")
		if !ok {
			s.fail(w, r, badRequest("no version %q of this page", q.Get("diff")))
			return
		}
		shown = v
		diff = versionDiff(s.db.Read, p.ID, v.N, 3)
	case q.Get("version") != "":
		v, ok := pick("version")
		if !ok {
			s.fail(w, r, badRequest("no version %q of this page", q.Get("version")))
			return
		}
		shown = v
	}
	// The siblings, for moving between the pages of the course.
	siblings, err := coursePages(s.db.Read, p.CourseID, p.Kind)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	s.unseenItem(r, p.Kind, p.ID)
	c, _ := s.chrome(r, p.Name)
	s.render(w, r, "page", struct {
		chrome
		Page     pageRow
		Shown    pageVersionRow
		Diff     *pageDiff
		Latest   int
		Versions []pageVersionRow
		Siblings []pageRow
		Studip   string
	}{c, p, shown, diff, vs[0].N, vs, siblings, p.Studip(s.c.base)}, http.StatusOK)
}

func (s *server) handleFolder(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	var courseID string
	if err := s.db.Read.QueryRow(`SELECT course_id FROM folders WHERE id = ?`, id).Scan(&courseID); err != nil {
		s.fail(w, r, errNotFound)
		return
	}
	co, err := course(s.db.Read, courseID)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	tree, err := folderTree(s.db.Read, courseID, true)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	// The subtree rooted at this folder, depths renumbered from it.
	var sub []*folderNode
	in, base := false, 0
	for _, n := range tree {
		if n.ID == id {
			in, base = true, n.Depth
		} else if in && n.Depth <= base {
			break
		}
		if in {
			cp := *n
			cp.Depth -= base
			sub = append(sub, &cp)
		}
	}
	if len(sub) == 0 {
		s.fail(w, r, errNotFound)
		return
	}
	cited, err := loadClaims(s.db.Read, `source_kind = 'folder' AND source_doc = ?`, id)
	if err == nil {
		cited, err = annotateClaims(s.db.Read, cited)
	}
	if err != nil {
		s.fail(w, r, err)
		return
	}
	c, _ := s.chrome(r, sub[0].Name)
	s.render(w, r, "folder", struct {
		chrome
		Course  courseRow
		Folders []*folderNode
		Cited   []claimView
	}{c, co, sub, cited}, http.StatusOK)
}

// ============================================================================
// Files
// ============================================================================

func (s *server) handleFile(w http.ResponseWriter, r *http.Request) {
	f, err := file(s.db.Read, r.PathValue("id"))
	if err != nil {
		s.fail(w, r, err)
		return
	}
	vs, err := fileVersions(s.db.Read, f.ID)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	notes, err := annotations(s.db.Read, f.ID)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	derived, err := derivations(s.db.Read, f.ID)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	var folder string
	s.db.Read.QueryRow(`SELECT name FROM folders WHERE id = ?`, f.FolderID).Scan(&folder)
	s.unseenItem(r, "file", f.ID)
	c, _ := s.chrome(r, f.Name)

	// Which version the viewer shows: ?version=n if asked, otherwise the
	// newest one with notes on it, otherwise the newest. Notes stay with the
	// version they were made on; see annotations.go.
	shown := 0
	if len(vs) > 0 {
		shown = vs[0].N
		if len(notes) > 0 {
			shown = notes[0].N
		}
	}
	if q := r.URL.Query().Get("version"); q != "" {
		n, err := strconv.Atoi(q)
		ok := false
		for _, v := range vs {
			ok = ok || v.N == n
		}
		if err != nil || !ok {
			s.fail(w, r, badRequest("no version %q of this file", q))
			return
		}
		shown = n
	}
	// ?derived=k shows that derivation's text, and its version.
	pick, err := pickDerived(derived, shown, r.URL.Query().Get("derived"))
	if err != nil {
		s.fail(w, r, err)
		return
	}
	if pick != nil {
		shown = pick.N
	}
	shownDerived := loadDerivedView(s.db.Read, derived, pick)
	// Read from it (its text or its name), or naming it as what they are
	// about: a reading read from the plan.
	cited, err := loadClaims(s.db.Read, `(source_doc = ? OR file_id = ?)`, f.ID, f.ID)
	if err == nil {
		cited, err = annotateClaims(s.db.Read, cited)
	}
	if err != nil {
		s.fail(w, r, err)
		return
	}
	var shownNotes *annotationRow
	for i := range notes {
		if notes[i].N == shown {
			shownNotes = &notes[i]
		}
	}
	latest := 0
	if len(vs) > 0 {
		latest = vs[0].N
	}

	viewer := ""
	if f.Stored() && f.IsPDF() && pdfjs.Available(s.db.Read) {
		// The frame gets capability URLs, not the routes the reader links
		// to: it fetches from an opaque origin, without cookies. frame.go
		// serves the notes if the version has any, else the upstream bytes.
		pdf, notes := s.frameURLs(f.ID, shown)
		viewer = pdfjs.ViewerURLSaving(pdf, notes)
	}
	// A Word document is shown as the text it was converted to when it
	// was stored, a presentation as its slides, with what either leaves out
	// named above it; see render.go.
	var doc *docView
	var shownSum string
	for _, v := range vs {
		if v.N == shown {
			shownSum = v.Sha256
		}
	}
	if f.IsConverted() && shownSum != "" {
		rd, err := loadRender(s.db.Read, shownSum, f.Name, f.Mime)
		if err != nil {
			s.fail(w, r, err)
			return
		}
		doc = &docView{rd, f.ID, shown}
	}
	// An image file is shown as itself, if its bytes are one a browser
	// shows; /inline checks them again.
	image := ""
	if shownSum != "" && !f.IsConverted() && !f.IsPDF() {
		if b, err := s.db.openBytes(shownSum); err == nil {
			if head, err := b.head(sniffLen); err == nil && imageMime(head) != "" {
				image = "/file/" + f.ID + "/version/" + strconv.Itoa(shown) + "/inline"
			}
			b.Close()
		}
	}
	s.render(w, r, "file", struct {
		chrome
		File       fileRow
		Folder     string
		Versions   []versionRow
		Notes      []annotationRow
		Shown      int
		ShownNotes *annotationRow
		Latest     int
		Studip     string
		Viewer     string
		Sandbox    string
		Doc        *docView
		Image      string
		Derived    []derivationRow
		ShownDer   *derivedView
		Cited      []claimView
	}{c, f, folder, vs, notes, shown, shownNotes, latest,
		s.c.base + "/dispatch.php/file/details/" + f.ID, viewer, pdfjs.FrameSandbox, doc, image,
		derived, shownDerived, cited}, http.StatusOK)
}

// handleContent serves stored bytes exactly as fetched. The type is the one
// Stud.IP recorded and the response is an attachment: a lecturer's upload
// rendered in campusweb's origin could read the whole mirror.
func (s *server) handleContent(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	n := 0
	if v := r.PathValue("n"); v != "" {
		var err error
		if n, err = strconv.Atoi(v); err != nil || n < 1 {
			s.fail(w, r, badRequest("version must be a number from 1"))
			return
		}
	}
	f, err := file(s.db.Read, id)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	v, err := version(s.db.Read, id, n)
	if errors.Is(err, errNotFound) {
		msg := "no stored copy of this file"
		if f.FetchError != "" {
			msg += ": " + f.FetchError
		}
		s.fail(w, r, fmt.Errorf("%w: %s", errNotFound, msg))
		return
	}
	if err != nil {
		s.fail(w, r, err)
		return
	}
	ct := f.Mime
	if ct == "" {
		ct = "application/octet-stream"
	}
	w.Header().Set("Content-Type", ct)
	w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": f.Name}))
	w.Header().Set("X-Content-Type-Options", "nosniff")
	w.Header().Set("Content-Security-Policy", "sandbox")
	s.serveBytes(w, r, v.Sha256, versionCache(n))
}

// handleInline shows a PDF in the browser's viewer. Only bytes that are a PDF
// are typed as one, whatever Stud.IP or the filename says.
func (s *server) handleInline(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	n := 0
	if r.PathValue("n") != "" {
		var err error
		if n, err = pathVersion(r); err != nil {
			s.fail(w, r, err)
			return
		}
	}
	f, err := file(s.db.Read, id)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	v, err := version(s.db.Read, id, n)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	b, err := s.db.openBytes(v.Sha256)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	defer b.Close()
	head, err := b.head(sniffLen)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	cache := versionCache(n)
	if m := imageMime(head); m != "" {
		// An image file, typed by its bytes; never SVG. See render.go.
		setImageHeaders(w, m)
		serveOpen(w, r, v.Sha256, cache, b)
		return
	}
	if !pdfjs.LooksLikePDF(head) {
		s.fail(w, r, fmt.Errorf("%w: not a PDF or an image; download it at /file/%s/content", errNotFound, id))
		return
	}
	// Type, nosniff, sandbox, and the CORS wildcard the opaque-origin viewer
	// frame needs to read the document; see pdfjs.SetPDFHeaders.
	pdfjs.SetPDFHeaders(w, f.Name)
	serveOpen(w, r, v.Sha256, cache, b)
}

// versionCache is how long the bytes of version n may be kept: forever when
// the address names the version, revalidated when it means the newest (n 0).
func versionCache(n int) string {
	if n == 0 {
		return cacheRevalidate
	}
	return cacheForever
}

// handleDocImage serves image k of the conversion of one version of a file.
// It is found through that version, so the route reads no blob that is not
// an image of a document the page shows.
func (s *server) handleDocImage(w http.ResponseWriter, r *http.Request) {
	n, err := pathVersion(r)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	k, err := strconv.Atoi(r.PathValue("k"))
	if err != nil {
		s.fail(w, r, badRequest("image must be a number"))
		return
	}
	var ctype, sum string
	err = s.db.Read.QueryRow(`SELECT i.mime, i.image FROM file_versions v
		JOIN render_images i ON i.sha256 = v.sha256
		WHERE v.file_id = ? AND v.n = ? AND i.k = ?`, r.PathValue("id"), n, k).Scan(&ctype, &sum)
	if errors.Is(err, sql.ErrNoRows) {
		s.fail(w, r, fmt.Errorf("%w: no image %d in version %d of this file", errNotFound, k, n))
		return
	}
	if err != nil {
		s.fail(w, r, err)
		return
	}
	setImageHeaders(w, ctype)
	s.serveBytes(w, r, sum, cacheForever)
}

// How long the browser may keep stored bytes. Everything is private: most of
// it is behind the gate, and no shared cache should hold course material.
const (
	// An address that names one content forever: a version, a derivation,
	// an image of a version.
	cacheForever = "private, max-age=31536000, immutable"
	// An address whose content changes – the newest version after a sync,
	// the notes after a save – kept, but revalidated by its ETag each time.
	cacheRevalidate = "private, no-cache"
)

// serveBytes answers the stored bytes whose SHA-256 is sum, read from the
// database a piece at a time (see blobfile.go), with the headers the caller
// set; see serveOpen.
func (s *server) serveBytes(w http.ResponseWriter, r *http.Request, sum, cache string) {
	b, err := s.db.openBytes(sum)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	defer b.Close()
	serveOpen(w, r, sum, cache, b)
}

// serveOpen answers stored bytes, whose SHA-256 is sum, with the headers the
// caller set (Content-Type at least, so nothing is sniffed) and through
// http.ServeContent: conditional requests on the ETag, which as the sum is a
// strong validator, Range and If-Range, and HEAD. Only the ranges asked for
// are read.
//
// Range is what lets pdf.js open a long PDF at the page it shows instead of
// after the whole download. The viewer frame is an opaque origin, so it may
// read only the response headers CORS exposes; without Accept-Ranges and
// Content-Range it would silently fall back to fetching everything. Its
// requests need no preflight: Range of a single range is CORS-safelisted.
func serveOpen(w http.ResponseWriter, r *http.Request, sum, cache string, content io.ReadSeeker) {
	h := w.Header()
	h.Set("ETag", `"`+sum+`"`)
	h.Set("Cache-Control", cache)
	h.Set("Access-Control-Expose-Headers", "Accept-Ranges, Content-Range, Content-Length, Content-Encoding")
	http.ServeContent(w, r, "", time.Time{}, content)
}

// setImageHeaders types a response as an image whose type was found from its
// bytes, and keeps it from doing anything an image does not need to.
func setImageHeaders(w http.ResponseWriter, ctype string) {
	w.Header().Set("Content-Type", ctype)
	w.Header().Set("X-Content-Type-Options", "nosniff")
	if ctype == svgMime {
		// An SVG opened by itself is a document: no script, and nothing
		// fetched from anywhere, its own styles excepted.
		w.Header().Set("Content-Security-Policy", "sandbox; default-src 'none'; style-src 'unsafe-inline'")
	} else {
		w.Header().Set("Content-Security-Policy", "sandbox")
	}
}

// ============================================================================
// News, messages, forum, dates
// ============================================================================

func (s *server) handleNews(w http.ResponseWriter, r *http.Request) {
	n, err := newsItem(s.db.Read, r.PathValue("id"))
	if err != nil {
		s.fail(w, r, err)
		return
	}
	s.unseenItem(r, "news", n.ID)
	c, _ := s.chrome(r, n.Title)
	s.render(w, r, "news", struct {
		chrome
		News newsRow
	}{c, n}, http.StatusOK)
}

func (s *server) handleMessages(w http.ResponseWriter, r *http.Request) {
	box := r.URL.Query().Get("box")
	if box == "" {
		box = "inbox"
	}
	if box != "inbox" && box != "outbox" {
		s.fail(w, r, badRequest("box is inbox or outbox"))
		return
	}
	c, _ := s.chrome(r, box)
	pg := mailtext.ParsePaging(r, 0, mailtext.DefaultLimit)
	ms, total, err := messages(s.db.Read, box, pg.Limit, pg.Offset)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	pg = mailtext.ParsePaging(r, total, mailtext.DefaultLimit)
	s.render(w, r, "messages", struct {
		chrome
		Box      string
		Messages []messageRow
		Total    int
		Paging   mailtext.Paging
	}{c, box, ms, total, pg}, http.StatusOK)
}

func (s *server) handleMessage(w http.ResponseWriter, r *http.Request) {
	m, err := message(s.db.Read, r.PathValue("id"))
	if err != nil {
		s.fail(w, r, err)
		return
	}
	s.unseenItem(r, "message", m.ID)
	c, _ := s.chrome(r, m.Subject)
	s.render(w, r, "message", struct {
		chrome
		Msg messageRow
	}{c, m}, http.StatusOK)
}

func (s *server) handleForum(w http.ResponseWriter, r *http.Request) {
	co, err := course(s.db.Read, r.PathValue("id"))
	if err != nil {
		s.fail(w, r, err)
		return
	}
	ds, err := discussions(s.db.Read, co.ID)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	c, _ := s.chrome(r, "forum: "+co.Title)
	s.render(w, r, "forum", struct {
		chrome
		Course      courseRow
		Discussions []discussionRow
	}{c, co, ds}, http.StatusOK)
}

func (s *server) handleDiscussion(w http.ResponseWriter, r *http.Request) {
	ds, err := discussionsQuery(s.db.Read, `d.id = ?`, r.PathValue("id"))
	if err != nil {
		s.fail(w, r, err)
		return
	}
	if len(ds) == 0 {
		s.fail(w, r, errNotFound)
		return
	}
	ps, err := postings(s.db.Read, ds[0].ID)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	s.unseenWhere(r, `ch.kind = 'posting' AND ch.item_id IN (SELECT id FROM forum_postings WHERE discussion_id = ?)`, ds[0].ID)
	c, _ := s.chrome(r, ds[0].Title)
	s.render(w, r, "discussion", struct {
		chrome
		Discussion discussionRow
		Postings   []postingRow
	}{c, ds[0], ps}, http.StatusOK)
}

func (s *server) handlePosting(w http.ResponseWriter, r *http.Request) {
	var d string
	if err := s.db.Read.QueryRow(`SELECT discussion_id FROM forum_postings WHERE id = ?`, r.PathValue("id")).Scan(&d); err != nil {
		s.fail(w, r, errNotFound)
		return
	}
	http.Redirect(w, r, "/discussion/"+d+"#"+r.PathValue("id"), http.StatusFound)
}

func (s *server) handleDates(w http.ResponseWriter, r *http.Request) {
	c, err := s.chrome(r, "dates")
	if err != nil {
		s.fail(w, r, badRequest("%v", err))
		return
	}
	q := r.URL.Query()
	since, until := time.Now(), time.Now().Add(14*24*time.Hour)
	if q.Get("since") != "" || q.Get("until") != "" {
		dr, err := mailtext.ParseDateRange(r)
		if err != nil {
			s.fail(w, r, badRequest("%v", err))
			return
		}
		if !dr.Since.IsZero() {
			since = dr.Since
		}
		if !dr.Until.IsZero() {
			until = dr.Until
		}
	}
	// "since" is the start of today, not now, so a session running right
	// now is still listed.
	y, m, d := since.Date()
	if q.Get("since") == "" {
		since = time.Date(y, m, d, 0, 0, 0, 0, since.Location())
	}
	cond, args := c.Semester.cond()
	evs, err := eventsQuery(s.db.Read, `e.gone_at IS NULL AND e.end >= ? AND e.start < ?
		AND EXISTS (SELECT 1 FROM courses c WHERE c.id = e.course_id AND `+cond+`)`,
		append([]any{since.Unix(), until.Unix()}, args...)...)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	evs, err = withClaims(s.db.Read, evs, `course_id IN (SELECT c.id FROM courses c WHERE `+cond+`)`, args, since, until)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	s.render(w, r, "dates", struct {
		chrome
		Since, Until time.Time
		Events       []eventRow
	}{c, since, until, evs}, http.StatusOK)
}

// ============================================================================
// Session and sync
// ============================================================================

func (s *server) handleStatus(w http.ResponseWriter, r *http.Request) {
	c, _ := s.chrome(r, "status")
	hist, err := sessionHistory(s.db.Read)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	runs, err := recentRuns(s.db.Read, 15)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	var failing []courseRow
	cs, _ := courses(s.db.Read, semesterFilter{All: true})
	for _, co := range cs {
		if co.SyncError != "" && !co.Left() {
			failing = append(failing, co)
		}
	}
	docs, err := docProblems(s.db.Read)
	if err != nil {
		s.fail(w, r, err)
		return
	}
	_, since := s.sync.state()
	s.render(w, r, "status", struct {
		chrome
		Sessions     []sessionRow
		Runs         []runRow
		RunningSince time.Time
		Totals       totals
		Failing      []courseRow
		Docs         []docProblem
		Poll, Full   time.Duration
	}{c, hist, runs, since, mirrorTotals(s.db.Read), failing, docs, s.poll, s.full}, http.StatusOK)
}

func (s *server) handleLoginForm(w http.ResponseWriter, r *http.Request) {
	c, _ := s.chrome(r, "log in")
	s.render(w, r, "login", struct {
		chrome
		Message string
	}{c, ""}, http.StatusOK)
}

func (s *server) handleLogin(w http.ResponseWriter, r *http.Request) {
	if !s.sameOrigin(r) {
		http.Error(w, "cross-site request refused", http.StatusForbidden)
		return
	}
	c, _ := s.chrome(r, "log in")
	answer := func(status int, msg string) {
		s.render(w, r, "login", struct {
			chrome
			Message string
		}{c, msg}, status)
	}
	cookies, err := parseCookies(r.FormValue("cookie"))
	if err != nil {
		answer(http.StatusBadRequest, err.Error())
		return
	}
	ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
	defer cancel()
	sess, err := s.c.login(ctx, cookies)
	if err != nil {
		answer(http.StatusBadRequest, err.Error())
		return
	}
	log.Printf("logged in as %s (session %d)", sess.Username, sess.ID)
	s.sync.kick()
	if mailtext.WantsLLM(r) {
		c.Session = sess
		answer(http.StatusOK, "logged in as "+sess.Name+" ("+sess.Username+"); a full sync has started")
		return
	}
	http.Redirect(w, r, "/status", http.StatusSeeOther)
}

func (s *server) handleSync(w http.ResponseWriter, r *http.Request) {
	if !s.sameOrigin(r) {
		http.Error(w, "cross-site request refused", http.StatusForbidden)
		return
	}
	if s.c.current() == nil {
		s.fail(w, r, fmt.Errorf("%w: no live session; paste one at /login", errBadRequest))
		return
	}
	s.sync.kick()
	if mailtext.WantsLLM(r) {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(http.StatusAccepted)
		fmt.Fprintln(w, "a full sync is queued; progress at /status")
		return
	}
	http.Redirect(w, r, "/status", http.StatusSeeOther)
}

// filenameExt is used by templates to show a type when Stud.IP gives none.
func filenameExt(name string) string { return strings.TrimPrefix(path.Ext(name), ".") }