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
package main

// A course's text pages: the wiki and the "free information pages".
//
// Both are a name and a text that the lecturer edits in place, which is why
// both keep every text campusweb has seen, numbered like file versions: a
// sign-up list in a wiki is overwritten by the next person who signs up, and
// the old one is gone upstream. See PAGES in campusweb(1).
//
// The wiki comes from the JSON:API, with each page's whole text in the
// listing, so one request per course and run is all it costs.
//
// The information pages ("Freie Informationsseiten", Stud.IP's SCM; the
// lecturer names the tab, so it is called anything from "Infos" to
// "Teilnahme und Prüfung") are in no API. They are read from the website,
// one page per entry, and at most once a day per course, because that is
// scraping and because opening them there marks the tab visited on
// Digicampus. See campusweb(7), "Information pages are read from the
// website".

import (
	"bytes"
	"context"
	"database/sql"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"time"

	"golang.org/x/net/html"
	"golang.org/x/net/html/atom"
)

// infoInterval is how often a course's information pages are read.
const infoInterval = 24 * time.Hour

// quietKind is quiet for one kind of page: the course's first sync, or the
// first look at that kind in a course the mirror already had before
// campusweb read it. col is the courses column that records that look.
func (r *run) quietKind(course, col string) bool {
	if r.quiet(course) {
		return true
	}
	var at sql.NullInt64
	r.db().QueryRow(`SELECT `+col+` FROM courses WHERE id = ?`, course).Scan(&at)
	return !at.Valid
}

// upstreamPage is one page as Stud.IP has it now.
type upstreamPage struct {
	ID, Name, Parent, Author, Content string
	Position                          int
	Chdate                            int64
	Version                           int // the wiki's own count; 0 for info pages
}

// storePage records a page and, when its text differs from the newest one
// stored, a new version, and the change.
func (r *run) storePage(course, kind string, p upstreamPage, quiet bool) error {
	var oldGone sql.NullInt64
	err := r.db().QueryRow(`SELECT gone_at FROM pages WHERE id = ?`, p.ID).Scan(&oldGone)
	isNew := errors.Is(err, sql.ErrNoRows)
	if err != nil && !isNew {
		return err
	}
	nullable := func(s string) sql.NullString { return sql.NullString{String: s, Valid: s != ""} }
	var version sql.NullInt64
	if p.Version > 0 {
		version = sql.NullInt64{Int64: int64(p.Version), Valid: true}
	}
	if _, err := r.db().Exec(`INSERT INTO pages (id, course_id, kind, name, parent_id, position, author, chdate,
			upstream_version, first_seen, last_seen)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		ON CONFLICT (id) DO UPDATE SET course_id = excluded.course_id, name = excluded.name,
			parent_id = excluded.parent_id, position = excluded.position, author = excluded.author,
			chdate = excluded.chdate, upstream_version = excluded.upstream_version,
			last_seen = excluded.last_seen, gone_at = NULL`,
		p.ID, course, kind, p.Name, nullable(p.Parent), p.Position, nullable(p.Author), p.Chdate,
		version, r.now(), r.seq); err != nil {
		return err
	}

	var n int
	var last string
	err = r.db().QueryRow(`SELECT n, content FROM page_versions WHERE page_id = ? ORDER BY n DESC LIMIT 1`, p.ID).Scan(&n, &last)
	if err != nil && !errors.Is(err, sql.ErrNoRows) {
		return err
	}
	changed := n == 0 || last != p.Content
	if changed {
		n++
		if _, err := r.db().Exec(`INSERT INTO page_versions (page_id, n, content, author, chdate, fetched_at)
			VALUES (?, ?, ?, ?, ?, ?)`, p.ID, n, p.Content, nullable(p.Author), p.Chdate, r.now()); err != nil {
			return err
		}
	}
	record := func(event, title string, date int64) {
		if date == 0 {
			date = r.now()
		}
		var seenAt sql.NullInt64
		if quiet {
			seenAt = sql.NullInt64{Int64: r.now(), Valid: true}
		}
		// The version lets the feed show what the change was: version n
		// against the one before it.
		r.db().Exec(`INSERT INTO changes (observed_at, date, kind, item_id, course_id, event, title, seen_at, version)
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, r.now(), date, kind, p.ID, course, event, title, seenAt, n)
	}
	switch {
	case isNew:
		record("new", p.Name, p.Chdate)
	case oldGone.Valid:
		record("new", p.Name+" (back)", 0)
	case changed:
		record("changed", p.Name, p.Chdate)
	}
	return nil
}

// ============================================================================
// Wiki
// ============================================================================

func (r *run) wiki(ctx context.Context, course string) error {
	t0 := r.seq
	quiet := r.quietKind(course, "wiki_baselined_at")
	items, _, err := r.s.c.list(ctx, "/courses/"+url.PathEscape(course)+"/wiki-pages", nil)
	var he *httpError
	switch {
	case errors.As(err, &he) && he.Status == http.StatusNotFound:
		// Stud.IP answers a course without wiki pages with 404, the same as
		// one whose wiki is switched off; both have no pages now.
		items = nil
	case unavailable(err):
		return nil
	case err != nil:
		return err
	}
	for _, it := range items {
		var a struct {
			Name    string `json:"name"`
			Content string `json:"content"`
			Chdate  string `json:"chdate"`
			Version int    `json:"version"`
		}
		if err := it.attrs(&a); err != nil {
			return err
		}
		p := upstreamPage{ID: it.ID, Name: a.Name, Parent: it.rel("parent"), Author: r.userName(ctx, it.rel("author")),
			Content: a.Content, Chdate: parseTime(a.Chdate), Version: a.Version}
		if err := r.storePage(course, "wiki", p, quiet); err != nil {
			return err
		}
	}
	r.sweep("pages", "wiki", "name", "course_id", "course_id = ? AND kind = 'wiki'", t0, course)
	r.db().Exec(`UPDATE courses SET wiki_baselined_at = ? WHERE id = ? AND wiki_baselined_at IS NULL`, r.now(), course)
	return nil
}

// ============================================================================
// Information pages
// ============================================================================

func (r *run) info(ctx context.Context, course string) error {
	var checked sql.NullInt64
	r.db().QueryRow(`SELECT info_checked_at FROM courses WHERE id = ?`, course).Scan(&checked)
	if checked.Valid && r.now()-checked.Int64 < int64(infoInterval/time.Second) {
		return nil
	}
	t0 := r.seq
	quiet := r.quietKind(course, "info_baselined_at")
	cid := "cid=" + url.QueryEscape(course)
	status, body, err := r.s.c.getHTML(ctx, "/dispatch.php/course/scm?"+cid)
	if err != nil {
		return err
	}
	var pages []upstreamPage
	switch {
	case status == http.StatusOK:
		first, links, err := parseInfoPage(body)
		if err != nil {
			return err
		}
		for i, l := range links {
			p := first
			if !l.Active {
				st, b, err := r.s.c.getHTML(ctx, "/dispatch.php/course/scm/"+url.PathEscape(l.ID)+"?"+cid)
				if err != nil {
					return err
				}
				if st != http.StatusOK {
					return &httpError{st, "course/scm/" + l.ID, "information page not readable"}
				}
				if p, _, err = parseInfoPage(b); err != nil {
					return fmt.Errorf("%s: %w", l.Name, err)
				}
			}
			p.ID, p.Position = l.ID, i
			if p.Name == "" {
				p.Name = l.Name
			}
			pages = append(pages, p)
		}
	case noInfoPages(status, body):
		// The course has no such tab.
	case status == http.StatusForbidden || status == http.StatusNotFound:
		return nil
	default:
		return &httpError{status, "/dispatch.php/course/scm", "information pages not readable"}
	}
	for _, p := range pages {
		if err := r.storePage(course, "info", p, quiet); err != nil {
			return err
		}
	}
	r.sweep("pages", "info", "name", "course_id", "course_id = ? AND kind = 'info'", t0, course)
	r.db().Exec(`UPDATE courses SET info_checked_at = ?, info_baselined_at = coalesce(info_baselined_at, ?) WHERE id = ?`,
		r.now(), r.now(), course)
	return nil
}

// noInfoPages recognises Stud.IP's answer for a course without the tab: it
// does not say 404, it fails with 500 on activating a navigation item that
// does not exist.
func noInfoPages(status int, body []byte) bool {
	return status == http.StatusInternalServerError &&
		bytes.Contains(body, []byte("/course/scm")) && bytes.Contains(body, []byte("not found"))
}

// infoLink is one entry of the information pages' menu, in its order.
type infoLink struct {
	ID, Name string
	Active   bool // the entry this page shows
}

var (
	infoLinkID = regexp.MustCompile(`^nav_scm_([0-9a-f]{32})$`)
	// Stud.IP writes the date with strftime('%x, %X') in German.
	infoDate = regexp.MustCompile(`(\d{2})\.(\d{2})\.(\d{4}), (\d{2}):(\d{2}):(\d{2})`)
)

// parseInfoPage reads what campusweb needs from an information page of the
// website: the menu of all entries, and the one entry shown — its title,
// who changed it last and when, and its text, as the HTML Stud.IP renders.
//
// That HTML is Stud.IP's rendering of the lecturer's text, not the text as
// stored; it is kept marked as HTML so that it is shown as text like every
// other piece of course content.
func parseInfoPage(body []byte) (upstreamPage, []infoLink, error) {
	doc, err := html.Parse(bytes.NewReader(body))
	if err != nil {
		return upstreamPage{}, nil, err
	}
	var links []infoLink
	var article *html.Node
	walkHTML(doc, func(n *html.Node) {
		if n.DataAtom == atom.A {
			if m := infoLinkID.FindStringSubmatch(attrOf(n, "id")); m != nil {
				links = append(links, infoLink{ID: m[1], Name: strings.TrimSpace(textOf(n)),
					Active: attrOf(n, "aria-current") == "page" || hasClass(n, "active")})
			}
		}
		if article == nil && n.DataAtom == atom.Article && hasClass(n, "studip") {
			article = n
		}
	})
	var p upstreamPage
	var content *html.Node
	if article != nil {
		walkHTML(article, func(n *html.Node) {
			switch {
			case n.DataAtom == atom.H1 && p.Name == "":
				p.Name = strings.TrimSpace(textOf(n))
			case n.DataAtom == atom.Nav && p.Chdate == 0:
				t := textOf(n)
				if m := infoDate.FindStringSubmatch(t); m != nil {
					d, _ := time.ParseInLocation("02.01.2006 15:04:05", m[1]+"."+m[2]+"."+m[3]+" "+m[4]+":"+m[5]+":"+m[6], time.Local)
					p.Chdate = d.Unix()
				}
				walkHTML(n, func(a *html.Node) {
					if a.DataAtom == atom.A && p.Author == "" && strings.Contains(attrOf(a, "href"), "profile") {
						p.Author = strings.TrimSpace(textOf(a))
					}
				})
			case n.DataAtom == atom.Div && content == nil && hasClass(n, "formatted-content"):
				content = n
			}
		})
	}
	if content != nil {
		var b strings.Builder
		for c := content.FirstChild; c != nil; c = c.NextSibling {
			html.Render(&b, c)
		}
		p.Content = "<!--HTML-->" + b.String()
	}
	switch {
	case len(links) == 0 && content != nil:
		// Text, but no entry it could be the text of: the page is not laid
		// out as campusweb knows it. Better a sync error than a page that
		// is silently missing, or every page marked gone.
		return p, nil, errors.New("information page without its menu; the website's layout has changed")
	case len(links) > 0 && article == nil:
		return p, nil, errors.New("information page without its text; the website's layout has changed")
	}
	if len(links) > 0 {
		active := false
		for _, l := range links {
			active = active || l.Active
		}
		if !active {
			// The tab without an entry shows the first one.
			links[0].Active = true
		}
	}
	return p, links, nil
}

func walkHTML(n *html.Node, f func(*html.Node)) {
	f(n)
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		walkHTML(c, f)
	}
}

func attrOf(n *html.Node, key string) string {
	for _, a := range n.Attr {
		if a.Key == key {
			return a.Val
		}
	}
	return ""
}

func hasClass(n *html.Node, class string) bool {
	return strings.Contains(" "+attrOf(n, "class")+" ", " "+class+" ")
}

func textOf(n *html.Node) string {
	var b strings.Builder
	walkHTML(n, func(c *html.Node) {
		if c.Type == html.TextNode {
			b.WriteString(c.Data)
		}
	})
	return strings.Join(strings.Fields(b.String()), " ")
}