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
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
package main

// Mirroring Stud.IP into the database.
//
// Two kinds of run:
//
//   - a poll, every few minutes: the activity stream since the last poll, the
//     message boxes, and a content sync of every course the stream mentions.
//     It doubles as the keepalive of the session.
//   - a full run, hourly: semesters, the course list, and a content sync of
//     every course still in it. This catches whatever the activity stream does
//     not report, which is more than nothing — it is a feed for people, not a
//     change log.
//
// Nothing here deletes. Something missing from a complete listing gets
// gone_at; something that reappears loses it again. A listing that failed is
// not complete, and marks nothing.

import (
	"context"
	"crypto/sha256"
	"database/sql"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"time"
)

type syncer struct {
	db      *database
	c       *studip
	maxFile int64
	now     func() time.Time

	run     sync.Mutex // one run at a time
	trigger chan struct{}

	mu        sync.Mutex
	running   string // "", "poll", "full"
	runningAt time.Time
}

func newSyncer(db *database, c *studip, maxFile int64) *syncer {
	return &syncer{db: db, c: c, maxFile: maxFile, now: time.Now, trigger: make(chan struct{}, 1)}
}

// kick asks for a full run as soon as possible. Never blocks; a kick while
// one is pending is the same kick.
func (s *syncer) kick() {
	select {
	case s.trigger <- struct{}{}:
	default:
	}
}

func (s *syncer) state() (string, time.Time) {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.running, s.runningAt
}

// loop runs forever: a full run at start and on every kick and every full
// interval, a poll every poll interval in between. Without a live session it
// only waits for a kick, which /login sends.
func (s *syncer) loop(ctx context.Context, poll, full time.Duration) {
	lastFull := time.Time{}
	timer := time.NewTimer(0)
	for {
		kicked := false
		select {
		case <-ctx.Done():
			return
		case <-timer.C:
		case <-s.trigger:
			kicked = true
		}
		if s.c.current() == nil {
			timer.Reset(poll)
			continue
		}
		if kicked || s.now().Sub(lastFull) >= full {
			if err := s.runOnce(ctx, "full"); err == nil || !errors.Is(err, errSessionDied) {
				lastFull = s.now()
			}
		} else {
			s.runOnce(ctx, "poll")
		}
		if !timer.Stop() {
			select {
			case <-timer.C:
			default:
			}
		}
		timer.Reset(poll)
	}
}

func (s *syncer) runOnce(ctx context.Context, kind string) error {
	s.run.Lock()
	defer s.run.Unlock()
	s.mu.Lock()
	s.running, s.runningAt = kind, s.now()
	s.mu.Unlock()
	defer func() {
		s.mu.Lock()
		s.running = ""
		s.mu.Unlock()
	}()

	s.c.mu.Lock()
	s.c.requests = 0
	s.c.mu.Unlock()
	start := s.now()
	res, _ := s.db.Write.Exec(`INSERT INTO sync_runs (kind, started_at) VALUES (?, ?)`, kind, start.Unix())
	runID, _ := res.LastInsertId()

	r := &run{s: s, seq: runID}
	var err error
	if kind == "full" {
		err = r.full(ctx)
	} else {
		err = r.poll(ctx)
	}
	s.c.mu.Lock()
	reqs := s.c.requests
	s.c.mu.Unlock()
	var msg sql.NullString
	if err != nil {
		msg = sql.NullString{String: err.Error(), Valid: true}
		log.Printf("sync %s: %v", kind, err)
	}
	s.db.Write.Exec(`UPDATE sync_runs SET finished_at = ?, requests = ?, downloaded = ?, error = ? WHERE id = ?`,
		s.now().Unix(), reqs, r.downloaded, msg, runID)
	// Keep the run log bounded; it is for /status, not an archive.
	s.db.Write.Exec(`DELETE FROM sync_runs WHERE id < ? - 2000`, runID)
	log.Printf("sync %s: %d requests, %d files downloaded, %s", kind, reqs, r.downloaded, s.now().Sub(start).Round(time.Second))
	return err
}

// run is the state of one sync run.
type run struct {
	s          *syncer
	downloaded int
	// seq is this run's id in sync_runs. Rows record the run that last saw
	// them in last_seen, and a sweep marks gone what a complete listing in
	// this run did not contain (last_seen < seq). A timestamp would not do:
	// two runs within one second would each think the other's rows current.
	seq int64
}

func (r *run) db() *sql.DB { return r.s.db.Write }
func (r *run) now() int64  { return r.s.now().Unix() }

// fatal reports errors that make going on pointless: no session, or the
// context ending. Anything else is one course's or one item's problem.
func fatal(err error) bool {
	return errors.Is(err, errNoSession) || errors.Is(err, errSessionDied) ||
		errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}

// unavailable is a listing a course does not offer: the tool (forum, news,
// files) is switched off there, or closed to this account.
func unavailable(err error) bool {
	var he *httpError
	return errors.As(err, &he) && (he.Status == http.StatusForbidden || he.Status == http.StatusNotFound)
}

func (r *run) full(ctx context.Context) error {
	sess := r.s.c.current()
	if sess == nil {
		return errNoSession
	}
	if err := r.semesters(ctx); err != nil {
		return err
	}
	courses, err := r.courses(ctx, sess.UserID)
	if err != nil {
		return err
	}
	siteOK := true
	if err := r.messages(ctx, sess.UserID); err != nil {
		if fatal(err) {
			return err
		}
		siteOK = false
		log.Printf("messages: %v", err)
	}
	if err := r.news(ctx, "studip", "/studip/news"); err != nil {
		if fatal(err) {
			return err
		}
		siteOK = false
		log.Printf("site news: %v", err)
	}
	// The account's first complete look at its messages and site news is
	// over; from now on what appears there is news. See quiet.
	if siteOK && getState(r.db(), "baselined") == "" {
		setState(r.db(), "baselined", strconv.FormatInt(r.now(), 10))
	}
	// The activity cursor moves on a full run too, so the next poll does not
	// redo what this run has just covered.
	if _, err := r.activities(ctx, sess.UserID); err != nil {
		if fatal(err) {
			return err
		}
		log.Printf("activity stream: %v", err)
	}
	var errs []string
	for _, id := range courses {
		if err := r.course(ctx, id); err != nil {
			if fatal(err) {
				return err
			}
			errs = append(errs, err.Error())
		}
	}
	if len(errs) > 0 {
		return fmt.Errorf("%d course(s) failed: %s", len(errs), strings.Join(errs, "; "))
	}
	return nil
}

func (r *run) poll(ctx context.Context) error {
	sess := r.s.c.current()
	if sess == nil {
		return errNoSession
	}
	touched, err := r.activities(ctx, sess.UserID)
	if err != nil {
		return err
	}
	if err := r.messages(ctx, sess.UserID); err != nil {
		if fatal(err) {
			return err
		}
		log.Printf("messages: %v", err)
	}
	for _, id := range touched {
		var gone sql.NullInt64
		if r.db().QueryRow(`SELECT gone_at FROM courses WHERE id = ?`, id).Scan(&gone) != nil || gone.Valid {
			// A course the mirror does not know (or no longer follows) is
			// the next full run's business: it knows the semester, the title,
			// and whether the account is still in it.
			continue
		}
		if err := r.course(ctx, id); err != nil && fatal(err) {
			return err
		}
	}
	return nil
}

// ============================================================================
// Change log
// ============================================================================

func (r *run) record(kind, id, course, event, title string, date int64) {
	r.recordSeen(kind, id, course, event, title, date, r.quiet(course))
}

// recordSeen records a change that is seen already when seen is set: what a
// first sync finds, or what the reader did themselves.
func (r *run) recordSeen(kind, id, course, event, title string, date int64, seen bool) {
	if date == 0 {
		date = r.now()
	}
	var c sql.NullString
	if course != "" {
		c = sql.NullString{String: course, Valid: true}
	}
	var seenAt sql.NullInt64
	if seen {
		seenAt = sql.NullInt64{Int64: r.now(), Valid: true}
	}
	r.db().Exec(`INSERT INTO changes (observed_at, date, kind, item_id, course_id, event, title, seen_at)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, r.now(), date, kind, id, c, event, title, seenAt)
}

// quiet says whether what is found now is the first sync of its scope — a
// course, or with course "" the account's messages and site news — and so
// is the backlog rather than news. It is recorded, but as seen: the first
// page of a new mirror, or after joining a course, would otherwise be a
// semester's worth of "new". See SEEN in campusweb(1).
func (r *run) quiet(course string) bool {
	if course == "" {
		return getState(r.db(), "baselined") == ""
	}
	var at sql.NullInt64
	r.db().QueryRow(`SELECT baselined_at FROM courses WHERE id = ?`, course).Scan(&at)
	return !at.Valid
}

// sweep marks rows of a table gone that a complete listing no longer
// contained, and records each. scope is the WHERE clause naming what the
// listing covered.
func (r *run) sweep(table, kind, titleCol, courseCol, scope string, since int64, args ...any) {
	q := fmt.Sprintf(`SELECT id, %s, %s FROM %s WHERE gone_at IS NULL AND last_seen < ? AND %s`,
		titleCol, courseCol, table, scope)
	rows, err := r.db().Query(q, append([]any{since}, args...)...)
	if err != nil {
		log.Printf("sweep %s: %v", table, err)
		return
	}
	type gone struct{ id, title, course string }
	var gs []gone
	for rows.Next() {
		var g gone
		var t, c sql.NullString
		rows.Scan(&g.id, &t, &c)
		g.title, g.course = t.String, c.String
		gs = append(gs, g)
	}
	rows.Close()
	for _, g := range gs {
		r.db().Exec(fmt.Sprintf(`UPDATE %s SET gone_at = ? WHERE id = ?`, table), r.now(), g.id)
		r.record(kind, g.id, g.course, "gone", g.title, 0)
	}
}

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

func (r *run) semesters(ctx context.Context) error {
	items, _, err := r.s.c.list(ctx, "/semesters", nil)
	if err != nil {
		return fmt.Errorf("semesters: %w", err)
	}
	for _, it := range items {
		var a struct {
			Title     string `json:"title"`
			Start     string `json:"start"`
			End       string `json:"end"`
			LectStart string `json:"start-of-lectures"`
			LectEnd   string `json:"end-of-lectures"`
			IsCurrent bool   `json:"is-current"`
		}
		if err := it.attrs(&a); err != nil {
			return err
		}
		if _, err := r.db().Exec(`INSERT INTO semesters (id, title, start, end, lect_start, lect_end, is_current)
			VALUES (?, ?, ?, ?, ?, ?, ?)
			ON CONFLICT (id) DO UPDATE SET title = excluded.title, start = excluded.start, end = excluded.end,
				lect_start = excluded.lect_start, lect_end = excluded.lect_end, is_current = excluded.is_current`,
			it.ID, a.Title, parseTime(a.Start), parseTime(a.End), parseTime(a.LectStart), parseTime(a.LectEnd), a.IsCurrent); err != nil {
			return err
		}
	}
	return nil
}

// courses refreshes the course list and returns the ids to sync.
func (r *run) courses(ctx context.Context, userID string) ([]string, error) {
	t0 := r.seq
	items, _, err := r.s.c.list(ctx, "/users/"+url.PathEscape(userID)+"/courses", nil)
	if err != nil {
		return nil, fmt.Errorf("course list: %w", err)
	}
	var ids []string
	for _, it := range items {
		var a struct {
			Number      *string `json:"course-number"`
			Title       string  `json:"title"`
			Subtitle    *string `json:"subtitle"`
			Description *string `json:"description"`
			Location    *string `json:"location"`
			Misc        *string `json:"miscellaneous"`
			Audience    *string `json:"audience"`
			Require     *string `json:"requirements"`
			Teaching    *string `json:"teaching-method"`
			Achievement *string `json:"achievement"`
			Credits     *string `json:"credits"`
		}
		if err := it.attrs(&a); err != nil {
			return nil, err
		}
		var start, end sql.NullString
		if v := it.rel("start-semester"); v != "" {
			start = sql.NullString{String: v, Valid: true}
		}
		if v := it.rel("end-semester"); v != "" {
			end = sql.NullString{String: v, Valid: true}
		}
		if _, err := r.db().Exec(`INSERT INTO courses (id, title, subtitle, number, description, location,
				miscellaneous, audience, requirements, teaching_method, achievement, credits,
				start_semester, end_semester, first_seen, last_seen)
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
			ON CONFLICT (id) DO UPDATE SET title = excluded.title, subtitle = excluded.subtitle,
				number = excluded.number, description = excluded.description, location = excluded.location,
				miscellaneous = excluded.miscellaneous, audience = excluded.audience,
				requirements = excluded.requirements, teaching_method = excluded.teaching_method,
				achievement = excluded.achievement, credits = excluded.credits,
				start_semester = excluded.start_semester, end_semester = excluded.end_semester,
				last_seen = excluded.last_seen, gone_at = NULL`,
			it.ID, a.Title, a.Subtitle, a.Number, a.Description, a.Location,
			a.Misc, a.Audience, a.Require, a.Teaching, a.Achievement, a.Credits,
			start, end, r.now(), r.seq); err != nil {
			return nil, err
		}
		ids = append(ids, it.ID)
	}
	// A course left is kept with everything in it; it is only no longer synced.
	r.db().Exec(`UPDATE courses SET gone_at = ? WHERE gone_at IS NULL AND last_seen < ?`, r.now(), t0)
	return ids, nil
}

// course syncs everything inside one course. Each part fails on its own, so
// a forum that errors does not cost the files.
func (r *run) course(ctx context.Context, id string) error {
	var title string
	r.db().QueryRow(`SELECT title FROM courses WHERE id = ?`, id).Scan(&title)
	parts := []struct {
		name string
		f    func(context.Context, string) error
	}{
		{"files", r.files},
		{"news", func(ctx context.Context, id string) error {
			return r.news(ctx, id, "/courses/"+url.PathEscape(id)+"/news")
		}},
		{"dates", r.events},
		{"forum", r.forum},
		{"wiki", r.wiki},
		{"information pages", r.info},
	}
	var errs []string
	for _, p := range parts {
		if err := p.f(ctx, id); err != nil {
			if fatal(err) {
				return err
			}
			errs = append(errs, p.name+": "+err.Error())
		}
	}
	// The first sync of the course is over, even if a part of it failed:
	// a part that keeps failing must not keep everything else quiet.
	r.db().Exec(`UPDATE courses SET baselined_at = ? WHERE id = ? AND baselined_at IS NULL`, r.now(), id)
	if len(errs) > 0 {
		msg := strings.Join(errs, "; ")
		r.db().Exec(`UPDATE courses SET sync_error = ? WHERE id = ?`, msg, id)
		return fmt.Errorf("%s: %s", title, msg)
	}
	r.db().Exec(`UPDATE courses SET synced_at = ?, sync_error = NULL WHERE id = ?`, r.now(), id)
	return nil
}

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

func (r *run) files(ctx context.Context, course string) error {
	t0 := r.seq
	cpath := "/courses/" + url.PathEscape(course)
	folders, _, err := r.s.c.list(ctx, cpath+"/folders", nil)
	if unavailable(err) {
		return nil
	}
	if err != nil {
		return err
	}
	for _, it := range folders {
		var a struct {
			Type        string  `json:"folder-type"`
			Name        string  `json:"name"`
			Description *string `json:"description"`
			Mkdate      string  `json:"mkdate"`
			Chdate      string  `json:"chdate"`
		}
		if err := it.attrs(&a); err != nil {
			return err
		}
		var parent sql.NullString
		if p := it.rel("parent"); p != "" {
			parent = sql.NullString{String: p, Valid: true}
		}
		if _, err := r.db().Exec(`INSERT INTO folders (id, course_id, parent_id, name, description, folder_type,
				mkdate, chdate, first_seen, last_seen)
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
			ON CONFLICT (id) DO UPDATE SET course_id = excluded.course_id, parent_id = excluded.parent_id,
				name = excluded.name, description = excluded.description, folder_type = excluded.folder_type,
				mkdate = excluded.mkdate, chdate = excluded.chdate, last_seen = excluded.last_seen, gone_at = NULL`,
			it.ID, course, parent, a.Name, a.Description, a.Type, parseTime(a.Mkdate), parseTime(a.Chdate), r.now(), r.seq); err != nil {
			return err
		}
	}
	r.db().Exec(`UPDATE folders SET gone_at = ? WHERE gone_at IS NULL AND last_seen < ? AND course_id = ?`, r.now(), t0, course)

	refs, _, err := r.s.c.list(ctx, cpath+"/file-refs", nil)
	if err != nil {
		return err
	}
	var errs []string
	for _, it := range refs {
		if err := r.file(ctx, course, it); err != nil {
			if fatal(err) {
				return err
			}
			errs = append(errs, err.Error())
		}
	}
	r.sweep("files", "file", "name", "course_id", "course_id = ?", t0, course)
	if len(errs) > 0 {
		return fmt.Errorf("%d file(s) not downloaded: %s", len(errs), strings.Join(errs, "; "))
	}
	return nil
}

func (r *run) file(ctx context.Context, course string, it resource) error {
	var a struct {
		Name         string `json:"name"`
		Description  string `json:"description"`
		Mkdate       string `json:"mkdate"`
		Chdate       string `json:"chdate"`
		Size         int64  `json:"filesize"`
		Mime         string `json:"mime-type"`
		Downloadable bool   `json:"is-downloadable"`
	}
	if err := it.attrs(&a); err != nil {
		return err
	}
	// The owner's name comes along in the relationship's meta, which saves
	// a request per uploader.
	var owner struct {
		Meta struct {
			Name string `json:"name"`
		} `json:"meta"`
	}
	json.Unmarshal(it.Relationships["owner"], &owner)
	mk, ch := parseTime(a.Mkdate), parseTime(a.Chdate)

	var oldCh, oldGone sql.NullInt64
	var oldLink sql.NullString
	err := r.db().QueryRow(`SELECT chdate, gone_at, link_url FROM files WHERE id = ?`, it.ID).Scan(&oldCh, &oldGone, &oldLink)
	isNew := errors.Is(err, sql.ErrNoRows)
	if err != nil && !isNew {
		return err
	}
	if _, err := r.db().Exec(`INSERT INTO files (id, course_id, folder_id, name, description, mime, size, mkdate, chdate,
			owner, downloadable, first_seen, last_seen)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		ON CONFLICT (id) DO UPDATE SET course_id = excluded.course_id, folder_id = excluded.folder_id,
			name = excluded.name, description = excluded.description, mime = excluded.mime, size = excluded.size,
			mkdate = excluded.mkdate, chdate = excluded.chdate, owner = excluded.owner,
			downloadable = excluded.downloadable, last_seen = excluded.last_seen, gone_at = NULL`,
		it.ID, course, it.rel("parent"), a.Name, a.Description, a.Mime, a.Size, mk, ch,
		owner.Meta.Name, a.Downloadable, r.now(), r.seq); err != nil {
		return err
	}
	switch {
	case isNew:
		r.record("file", it.ID, course, "new", a.Name, mk)
	case oldCh.Int64 != ch:
		r.record("file", it.ID, course, "changed", a.Name, ch)
	case oldGone.Valid:
		r.record("file", it.ID, course, "new", a.Name+" (back)", 0)
	}

	// Download when there is no version yet, or the newest one was fetched
	// at another chdate. A file that failed before is retried every run.
	var lastCh sql.NullInt64
	var lastSum string
	var n int
	err = r.db().QueryRow(`SELECT n, chdate, sha256 FROM file_versions WHERE file_id = ? ORDER BY n DESC LIMIT 1`,
		it.ID).Scan(&n, &lastCh, &lastSum)
	if err != nil && !errors.Is(err, sql.ErrNoRows) {
		return err
	}
	if n > 0 && lastCh.Int64 == ch {
		return nil
	}
	if oldLink.Valid && oldCh.Int64 == ch {
		// A link whose target is known and that has not changed.
		return nil
	}
	if !a.Downloadable {
		r.db().Exec(`UPDATE files SET fetch_error = 'Stud.IP does not let this account download it' WHERE id = ?`, it.ID)
		return nil
	}
	if a.Size > r.s.maxFile {
		r.db().Exec(`UPDATE files SET fetch_error = ? WHERE id = ?`,
			fmt.Sprintf("%d bytes, more than --max-file-size", a.Size), it.ID)
		return nil
	}
	data, err := r.s.c.content(ctx, it.ID, r.s.maxFile)
	var he *httpError
	if errors.As(err, &he) && he.Status == http.StatusInternalServerError {
		// Most likely a link, which the JSON:API cannot serve; see
		// linkTarget. Anything else keeps the original error.
		var meta struct {
			DownloadURL string `json:"download-url"`
		}
		json.Unmarshal(it.Meta, &meta)
		if target, lerr := r.s.c.linkTarget(ctx, meta.DownloadURL); lerr == nil && target != "" {
			_, err := r.db().Exec(`UPDATE files SET link_url = ?, fetch_error = NULL WHERE id = ?`, target, it.ID)
			return err
		} else if fatal(lerr) {
			return lerr
		}
	}
	if err != nil {
		if !fatal(err) {
			r.db().Exec(`UPDATE files SET fetch_error = ? WHERE id = ?`, err.Error(), it.ID)
		}
		return fmt.Errorf("%s: %w", a.Name, err)
	}
	sum := sha256.Sum256(data)
	hexsum := hex.EncodeToString(sum[:])
	r.downloaded++
	if hexsum == lastSum {
		// Changed metadata, same bytes: a rename or a new description. The
		// version is the same one; it is now known under this chdate.
		_, err := r.db().Exec(`UPDATE file_versions SET chdate = ? WHERE file_id = ? AND n = ?`, ch, it.ID, n)
		r.db().Exec(`UPDATE files SET fetch_error = NULL WHERE id = ?`, it.ID)
		return err
	}
	tx, err := r.db().Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()
	if _, err := tx.Exec(`INSERT INTO blobs (sha256, size, data) VALUES (?, ?, ?) ON CONFLICT DO NOTHING`,
		hexsum, len(data), data); err != nil {
		return err
	}
	if _, err := tx.Exec(`INSERT INTO file_versions (file_id, n, sha256, size, chdate, fetched_at) VALUES (?, ?, ?, ?, ?, ?)`,
		it.ID, n+1, hexsum, len(data), ch, r.now()); err != nil {
		return err
	}
	if _, err := tx.Exec(`UPDATE files SET fetch_error = NULL WHERE id = ?`, it.ID); err != nil {
		return err
	}
	// A Word document or a presentation is converted as it is stored, so
	// that its page only reads; see render.go. The same content is
	// converted once.
	if converted(a.Name, a.Mime) {
		var have int
		tx.QueryRow(`SELECT count(*) FROM renders WHERE sha256 = ? AND converter = ?`, hexsum, renderConverter).Scan(&have)
		if have == 0 {
			if err := storeRender(tx, hexsum, convertFile(a.Name, a.Mime, data), r.now()); err != nil {
				return err
			}
		}
	}
	return tx.Commit()
}

// ============================================================================
// News
// ============================================================================

// news syncs one range's news: a course, or "studip" for the site-wide ones.
// A news item can be in several ranges, and is only gone from a range it left.
func (r *run) news(ctx context.Context, rangeID, path string) error {
	t0 := r.seq
	items, _, err := r.s.c.list(ctx, path, nil)
	if unavailable(err) {
		return nil
	}
	if err != nil {
		return err
	}
	course := rangeID
	if rangeID == "studip" {
		course = ""
	}
	for _, it := range items {
		var a struct {
			Title    string `json:"title"`
			Content  string `json:"content"`
			Mkdate   string `json:"mkdate"`
			Chdate   string `json:"chdate"`
			PubStart string `json:"publication-start"`
			PubEnd   string `json:"publication-end"`
		}
		if err := it.attrs(&a); err != nil {
			return err
		}
		author := r.userName(ctx, it.rel("author"))
		var oldCh sql.NullInt64
		err := r.db().QueryRow(`SELECT chdate FROM news WHERE id = ?`, it.ID).Scan(&oldCh)
		isNew := errors.Is(err, sql.ErrNoRows)
		mk, ch := parseTime(a.Mkdate), parseTime(a.Chdate)
		if _, err := r.db().Exec(`INSERT INTO news (id, title, content, author, mkdate, chdate, pub_start, pub_end, first_seen)
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
			ON CONFLICT (id) DO UPDATE SET title = excluded.title, content = excluded.content,
				author = excluded.author, mkdate = excluded.mkdate, chdate = excluded.chdate,
				pub_start = excluded.pub_start, pub_end = excluded.pub_end`,
			it.ID, a.Title, a.Content, author, mk, ch, parseTime(a.PubStart), parseTime(a.PubEnd), r.now()); err != nil {
			return err
		}
		if _, err := r.db().Exec(`INSERT INTO news_ranges (news_id, range_id, last_seen) VALUES (?, ?, ?)
			ON CONFLICT DO UPDATE SET last_seen = excluded.last_seen, gone_at = NULL`, it.ID, rangeID, r.seq); err != nil {
			return err
		}
		switch {
		case isNew:
			r.record("news", it.ID, course, "new", a.Title, max(mk, parseTime(a.PubStart)))
		case oldCh.Int64 != ch:
			r.record("news", it.ID, course, "changed", a.Title, ch)
		}
	}
	// News expire by their publication end; that is not a removal worth
	// reporting, so leaving a range is recorded without a change entry.
	r.db().Exec(`UPDATE news_ranges SET gone_at = ? WHERE range_id = ? AND gone_at IS NULL AND last_seen < ?`,
		r.now(), rangeID, t0)
	return nil
}

// ============================================================================
// Messages
// ============================================================================

func (r *run) messages(ctx context.Context, userID string) error {
	for _, box := range []string{"inbox", "outbox"} {
		t0 := r.seq
		// The listing carries the whole body. Fetching a message on its own
		// is what the website does when it is opened, and may mark it read;
		// campusweb never does that.
		items, _, err := r.s.c.list(ctx, "/users/"+url.PathEscape(userID)+"/"+box, nil)
		if err != nil {
			return fmt.Errorf("%s: %w", box, err)
		}
		for _, it := range items {
			var a struct {
				Subject  string `json:"subject"`
				Message  string `json:"message"`
				Mkdate   string `json:"mkdate"`
				Priority string `json:"priority"`
			}
			if err := it.attrs(&a); err != nil {
				return err
			}
			var exists int
			r.db().QueryRow(`SELECT 1 FROM messages WHERE id = ?`, it.ID).Scan(&exists)
			sender := ""
			if box == "inbox" {
				sender = r.userName(ctx, it.rel("sender"))
				if sender == "" {
					sender = "Stud.IP"
				}
			}
			var rcpt []string
			for _, u := range it.rels("recipients") {
				if u == userID {
					continue
				}
				rcpt = append(rcpt, r.userName(ctx, u))
			}
			mk := parseTime(a.Mkdate)
			if _, err := r.db().Exec(`INSERT INTO messages (id, box, subject, body, sender, recipients, mkdate, priority,
					first_seen, last_seen)
				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
				ON CONFLICT (id) DO UPDATE SET subject = excluded.subject, body = excluded.body,
					sender = excluded.sender, recipients = excluded.recipients, last_seen = excluded.last_seen,
					gone_at = NULL`,
				it.ID, box, a.Subject, a.Message, sender, strings.Join(rcpt, ", "), mk, a.Priority, r.now(), r.seq); err != nil {
				return err
			}
			if exists == 0 {
				title := a.Subject
				if box == "outbox" {
					title = "(sent) " + title
				}
				r.record("message", it.ID, "", "new", title, mk)
			}
		}
		// A message deleted on the website is gone there; it stays here, marked.
		r.db().Exec(`UPDATE messages SET gone_at = ? WHERE box = ? AND gone_at IS NULL AND last_seen < ?`, r.now(), box, t0)
	}
	return nil
}

// userName resolves a Stud.IP user id to a name, once per id. "" for no id;
// the id itself when it cannot be resolved, which beats a blank.
func (r *run) userName(ctx context.Context, id string) string {
	if id == "" {
		return ""
	}
	if strings.Contains(id, "%system%") {
		return "Stud.IP"
	}
	var name string
	if r.db().QueryRow(`SELECT name FROM users WHERE id = ?`, id).Scan(&name) == nil {
		return name
	}
	u, err := r.s.c.get(ctx, "/users/"+url.PathEscape(id))
	if err != nil {
		if !fatal(err) {
			log.Printf("user %s: %v", id, err)
		}
		return id
	}
	var a struct {
		Name string `json:"formatted-name"`
	}
	u.attrs(&a)
	if a.Name == "" {
		return id
	}
	r.db().Exec(`INSERT INTO users (id, name, fetched_at) VALUES (?, ?, ?) ON CONFLICT DO UPDATE SET name = excluded.name`,
		id, a.Name, r.now())
	return a.Name
}

// ============================================================================
// Course dates
// ============================================================================

func (r *run) events(ctx context.Context, course string) error {
	t0 := r.seq
	items, _, err := r.s.c.list(ctx, "/courses/"+url.PathEscape(course)+"/events", nil)
	if unavailable(err) {
		return nil
	}
	if err != nil {
		return err
	}
	for _, it := range items {
		var a struct {
			Title       string `json:"title"`
			Description string `json:"description"`
			Start       string `json:"start"`
			End         string `json:"end"`
			Location    string `json:"location"`
			Categories  string `json:"categories"`
			Recurrence  any    `json:"recurrence"`
			Cancelled   bool   `json:"is-cancelled"`
			Chdate      string `json:"chdate"`
		}
		if err := it.attrs(&a); err != nil {
			return err
		}
		rec := ""
		switch v := a.Recurrence.(type) {
		case string:
			rec = v
		case nil:
		default:
			b, _ := json.Marshal(v)
			rec = string(b)
		}
		var old struct {
			start, end int64
			location   string
			cancelled  bool
			gone       bool
		}
		var oldLoc sql.NullString
		err := r.db().QueryRow(`SELECT start, end, location, cancelled, gone_at IS NOT NULL FROM events WHERE id = ?`, it.ID).
			Scan(&old.start, &old.end, &oldLoc, &old.cancelled, &old.gone)
		old.location = oldLoc.String
		isNew := errors.Is(err, sql.ErrNoRows)
		start, end, ch := parseTime(a.Start), parseTime(a.End), parseTime(a.Chdate)
		if _, err := r.db().Exec(`INSERT INTO events (id, course_id, title, description, start, end, location, category,
				recurrence, cancelled, chdate, first_seen, last_seen)
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
			ON CONFLICT (id) DO UPDATE SET title = excluded.title, description = excluded.description,
				start = excluded.start, end = excluded.end, location = excluded.location,
				category = excluded.category, recurrence = excluded.recurrence, cancelled = excluded.cancelled,
				chdate = excluded.chdate, last_seen = excluded.last_seen, gone_at = NULL`,
			it.ID, course, a.Title, a.Description, start, end, a.Location, a.Categories, rec,
			a.Cancelled, ch, r.now(), r.seq); err != nil {
			return err
		}
		if isNew {
			// A course has a dozen dates from the start; those are the
			// course's first sync and quiet. One added later is news.
			r.record("event", it.ID, course, "new", "added: "+eventWhen(start, end, a.Location), ch)
			continue
		}
		if old.gone {
			r.record("event", it.ID, course, "new", "back: "+eventWhen(start, end, a.Location), ch)
			continue
		}
		for _, d := range eventDiff(old.start, old.end, old.location, old.cancelled, start, end, a.Location, a.Cancelled) {
			r.record("event", it.ID, course, "changed", d, ch)
		}
	}
	// A date that disappeared is titled by when it was, since a course's
	// dates mostly share one title. Formatted here rather than by SQLite,
	// whose localtime is not --timezone.
	type goneEvent struct {
		id         string
		start, end int64
		loc        string
	}
	rows, err := r.db().Query(`SELECT id, start, end, coalesce(location,'') FROM events
		WHERE course_id = ? AND gone_at IS NULL AND last_seen < ?`, course, t0)
	if err != nil {
		return err
	}
	var gs []goneEvent
	for rows.Next() {
		var g goneEvent
		rows.Scan(&g.id, &g.start, &g.end, &g.loc)
		gs = append(gs, g)
	}
	rows.Close()
	for _, g := range gs {
		r.db().Exec(`UPDATE events SET gone_at = ? WHERE id = ?`, r.now(), g.id)
		r.record("event", g.id, course, "gone", "removed: "+eventWhen(g.start, g.end, g.loc), 0)
	}
	return nil
}

// eventDiff names what changed about a date, one entry per change, in the
// words the feed shows. Times are in time.Local, which main sets to
// --timezone.
func eventDiff(oStart, oEnd int64, oLoc string, oCancelled bool, start, end int64, loc string, cancelled bool) []string {
	var out []string
	switch {
	case cancelled && !oCancelled:
		return []string{"cancelled: " + eventWhen(start, end, loc)}
	case !cancelled && oCancelled:
		out = append(out, "no longer cancelled: "+eventWhen(start, end, loc))
	}
	switch {
	case oStart != start:
		out = append(out, "moved: "+eventWhen(oStart, oEnd, "")+" → "+eventWhen(start, end, ""))
	case oEnd != end:
		out = append(out, "time: "+eventWhen(oStart, oEnd, "")+" → "+clockOf(end))
	}
	if oLoc != loc {
		out = append(out, "room: "+orDash(oLoc)+" → "+orDash(loc)+" ("+eventWhen(start, end, "")+")")
	}
	return out
}

func eventWhen(start, end int64, loc string) string {
	s := time.Unix(start, 0).In(time.Local)
	w := germanWeekday(s) + " " + s.Format("2006-01-02 15:04")
	if end > start {
		w += "–" + clockOf(end)
	}
	if loc != "" {
		w += " · " + loc
	}
	return w
}

func clockOf(t int64) string { return time.Unix(t, 0).In(time.Local).Format("15:04") }

// ============================================================================
// Forum
// ============================================================================

func (r *run) forum(ctx context.Context, course string) error {
	t0 := r.seq
	topics, _, err := r.s.c.list(ctx, "/courses/"+url.PathEscape(course)+"/forum-topics", nil)
	if unavailable(err) {
		return nil
	}
	if err != nil {
		return err
	}
	complete := true
	for _, tp := range topics {
		var ta struct {
			Name string `json:"name"`
		}
		tp.attrs(&ta)
		discs, _, err := r.s.c.list(ctx, "/forum-topics/"+url.PathEscape(tp.ID)+"/discussions", nil)
		if err != nil {
			if fatal(err) {
				return err
			}
			complete = false
			log.Printf("forum topic %s: %v", tp.ID, err)
			continue
		}
		for _, d := range discs {
			if err := r.discussion(ctx, course, ta.Name, d); err != nil {
				if fatal(err) {
					return err
				}
				complete = false
				log.Printf("forum discussion %s: %v", d.ID, err)
			}
		}
	}
	if complete {
		r.db().Exec(`UPDATE forum_discussions SET gone_at = ? WHERE course_id = ? AND gone_at IS NULL AND last_seen < ?`,
			r.now(), course, t0)
	}
	return nil
}

func (r *run) discussion(ctx context.Context, course, topic string, d resource) error {
	var a struct {
		Title  string `json:"title"`
		Mkdate string `json:"mkdate"`
		Chdate string `json:"chdate"`
	}
	var m struct {
		Postings int    `json:"postings-count"`
		Activity string `json:"recent-activity"`
	}
	if err := d.attrs(&a); err != nil {
		return err
	}
	json.Unmarshal(d.Meta, &m)
	act := parseTime(m.Activity)

	var oldAct, oldPostings sql.NullInt64
	err := r.db().QueryRow(`SELECT activity, postings FROM forum_discussions WHERE id = ?`, d.ID).Scan(&oldAct, &oldPostings)
	unchanged := err == nil && oldAct.Int64 == act && oldPostings.Int64 == int64(m.Postings)
	if _, err := r.db().Exec(`INSERT INTO forum_discussions (id, course_id, topic, title, mkdate, chdate, activity, postings,
			first_seen, last_seen)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		ON CONFLICT (id) DO UPDATE SET topic = excluded.topic, title = excluded.title, chdate = excluded.chdate,
			activity = excluded.activity, postings = excluded.postings, last_seen = excluded.last_seen, gone_at = NULL`,
		d.ID, course, topic, a.Title, parseTime(a.Mkdate), parseTime(a.Chdate), act, m.Postings, r.now(), r.seq); err != nil {
		return err
	}
	if unchanged {
		// Reading postings marks them read on Stud.IP; only do it when
		// there is something new to read.
		return nil
	}
	t0 := r.seq
	q := url.Values{"include": {"author"}}
	posts, included, err := r.s.c.list(ctx, "/forum-discussions/"+url.PathEscape(d.ID)+"/postings", q)
	if err != nil {
		return err
	}
	authors := map[string]string{}
	for _, inc := range included {
		var ia struct {
			Name string `json:"name"`
		}
		inc.attrs(&ia)
		authors[inc.ID] = ia.Name
	}
	for _, p := range posts {
		var pa struct {
			Content   string `json:"content"`
			Anonymous bool   `json:"anonymous"`
			Mkdate    string `json:"mkdate"`
			Chdate    string `json:"chdate"`
		}
		if err := p.attrs(&pa); err != nil {
			return err
		}
		author := authors[p.rel("author")]
		if pa.Anonymous {
			author = "(anonymous)"
		}
		var oldCh sql.NullInt64
		err := r.db().QueryRow(`SELECT chdate FROM forum_postings WHERE id = ?`, p.ID).Scan(&oldCh)
		isNew := errors.Is(err, sql.ErrNoRows)
		mk, ch := parseTime(pa.Mkdate), parseTime(pa.Chdate)
		if _, err := r.db().Exec(`INSERT INTO forum_postings (id, discussion_id, course_id, author, content, mkdate, chdate,
				first_seen, last_seen)
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
			ON CONFLICT (id) DO UPDATE SET author = excluded.author, content = excluded.content,
				chdate = excluded.chdate, last_seen = excluded.last_seen, gone_at = NULL`,
			p.ID, d.ID, course, author, pa.Content, mk, ch, r.now(), r.seq); err != nil {
			return err
		}
		switch {
		case isNew:
			r.record("posting", p.ID, course, "new", a.Title+" — "+author, mk)
		case oldCh.Int64 != ch:
			r.record("posting", p.ID, course, "changed", a.Title+" — "+author, ch)
		}
	}
	r.db().Exec(`UPDATE forum_postings SET gone_at = ? WHERE discussion_id = ? AND gone_at IS NULL AND last_seen < ?`,
		r.now(), d.ID, t0)
	return nil
}

// ============================================================================
// Activity stream
// ============================================================================

// activities reads the stream since the last poll and returns the courses it
// names. The cursor is the newest mkdate seen; the stream is filtered by
// time, so the first poll after a long pause reads the whole gap.
func (r *run) activities(ctx context.Context, userID string) ([]string, error) {
	since, _ := strconv.ParseInt(getState(r.db(), "activity_since"), 10, 64)
	if since == 0 {
		// The first poll needs no history: the first full run has just
		// read everything there is.
		since = r.now() - 14*24*3600
	}
	q := url.Values{"filter[start]": {strconv.FormatInt(since, 10)}}
	items, _, err := r.s.c.list(ctx, "/users/"+url.PathEscape(userID)+"/activitystream", q)
	if err != nil {
		return nil, fmt.Errorf("activity stream: %w", err)
	}
	newest := since
	seen := map[string]bool{}
	var courses []string
	for _, it := range items {
		var a struct {
			Title  string `json:"title"`
			Mkdate string `json:"mkdate"`
			Verb   string `json:"verb"`
			Type   string `json:"activity-type"`
		}
		if err := it.attrs(&a); err != nil {
			return nil, err
		}
		mk := parseTime(a.Mkdate)
		newest = max(newest, mk)
		var obj, ctxRel struct {
			Data *struct {
				Type string `json:"type"`
				ID   string `json:"id"`
			} `json:"data"`
		}
		json.Unmarshal(it.Relationships["object"], &obj)
		json.Unmarshal(it.Relationships["context"], &ctxRel)
		var ot, oi, ct, ci string
		if obj.Data != nil {
			ot, oi = obj.Data.Type, obj.Data.ID
		}
		if ctxRel.Data != nil {
			ct, ci = ctxRel.Data.Type, ctxRel.Data.ID
		}
		r.db().Exec(`INSERT INTO activities (id, mkdate, type, verb, title, object_type, object_id, context_type, context_id)
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING`, it.ID, mk, a.Type, a.Verb, a.Title, ot, oi, ct, ci)
		// Who joined a course is most of the stream and changes nothing
		// campusweb mirrors.
		if ct == "courses" && a.Type != "participants" && !seen[ci] {
			seen[ci] = true
			courses = append(courses, ci)
		}
	}
	// Equal timestamps are possible; re-reading the newest second is
	// harmless (activities are keyed), missing it is not.
	setState(r.db(), "activity_since", strconv.FormatInt(newest, 10))
	return courses, nil
}