aboutsummaryrefslogtreecommitdiff
path: root/src/utils-common.ts
blob: 341087664e26e5746bea696f11637542cf82c3a7 (plain)
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
"use strict";

export const DATE_FMT = new Intl.DateTimeFormat("de-DE", {
	month: "numeric",
	day: "numeric",
	year: "numeric",
});

export const DATETIME_FMT = new Intl.DateTimeFormat("de-DE", {
	month: "numeric",
	day: "numeric",
	year: "numeric",
	hour: "numeric",
	minute: "numeric",
});

export function dateStringNow() {
	return DATE_FMT.format(new Date());
}

export function datetimeStringNow() {
	return DATETIME_FMT.format(new Date());
}

declare global {
	var M: { cfg: { userId: number; courseId: number } };
}

export function getUserId(): number {
	// M is exported by Moodle
	return globalThis.M.cfg.userId;
}

export function getCourseId(): number {
	// M is exported by Moodle
	return globalThis.M.cfg.courseId;
}

export class CourseLocalStorage {
	static getItem(key: string) {
		return localStorage.getItem(`${key}-${getCourseId()}`);
	}

	static setItem(key: string, val: string) {
		return localStorage.setItem(`${key}-${getCourseId()}`, val);
	}
}

export async function getUserIconUrl(userId: number): Promise<string> {
	let url = CourseLocalStorage.getItem(`bycs-sol-user-icon-${userId}`);
	if (url) return url;

	const userRes = await fetch(`https://lernplattform.bycs.de/user/profile.php?id=${userId}`);
	const userDoc = new DOMParser().parseFromString(await userRes.text(), "text/html");
	const userpicture = userDoc.querySelector(".userpicture");
	if (userpicture === null) {
		return "";
	}

	url = (userpicture as HTMLImageElement).src ?? "";
	CourseLocalStorage.setItem(`bycs-sol-user-icon-${userId}`, url);

	return url;
}

// SplitMix32 implementation taken from:
// https://github.com/bryc/code/blob/master/jshash/PRNGs.md
// We only need a seeded PRNG to choose students to observe.
export function splitmix32(a: number) {
	return function () {
		a |= 0;
		a = (a + 0x9e3779b9) | 0;
		let t = a ^ (a >>> 16);
		t = Math.imul(t, 0x21f0aaad);
		t = t ^ (t >>> 15);
		t = Math.imul(t, 0x735a2d97);
		return ((t = t ^ (t >>> 15)) >>> 0) / 4294967296;
	};
}

const MOODLE_DATE_REGEX = /\w+, (\d+)\. (\w+) (\d+), (\d\d):(\d\d)/;
const MONTHS: { [m: string]: number } = {
	Januar: 1,
	Februar: 2,
	März: 3,
	April: 4,
	Mai: 5,
	Juni: 6,
	Juli: 7,
	August: 8,
	September: 9,
	Oktober: 10,
	November: 11,
	Dezember: 12,
};

export function parseMoodleDate(s: string) {
	const match = MOODLE_DATE_REGEX.exec(s);
	if (!match) {
		return new Date(-1);
	}

	const month = MONTHS[match[2]];
	return new Date(Number(match[3]), month, Number(match[1]), Number(match[4]), Number(match[4]));
}