summary refs log tree commit diff
path: root/src/lib.rs
blob: 25f6ea6d57cdf73c3defdc64d4c4d6ecc357e66a (plain) (blame)
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
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # VUW Course scraper
//!
//! This is a simple program capable of parsing VUWs courses from the registry. It cannot correctly
//! parse prerequisites, however.

mod parser;

use std::collections::{HashMap, HashSet};

use parser::{offering, subtitle, title};
use scraper::{CaseSensitivity, ElementRef, Html, Selector};
use serde::{Deserialize, Serialize};
use tracing::{debug, info};

/// Slice used for splitting requirements for parsing.
const SPLIT_SLICE: &[char] = &[';', ','];

/// Alias to the nom error type.
type NomError<'a> = nom::Err<nom::error::Error<&'a str>>;

/// A VUW course, along with all relevant data.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct Course<'a> {
	/// Courses that must be taken at the same time as this course.
	pub corequisites: Vec<&'a str>,

	/// Description of the course.
	pub description: Option<&'a str>,

	/// Whether this course is offered in the upcoming year.
	pub offered: bool,

	/// Amount of points this course is worth.
	pub points: f32,

	/// Courses that must be taken before this course.
	pub prerequisites: Vec<&'a str>,

	/// Courses that cannot be taken if you take this course.
	pub restrictions: Vec<&'a str>,

	/// Subject areas this course belongs to.
	pub subject_areas: HashSet<&'a str>,

	/// Subtitle of this course, its longer name.
	pub subtitle: &'a str,

	/// Timetable of this course, includes trimesters and CRNs.
	pub timetable: Vec<CourseOffering>,

	/// Title of this course, also known as the code.
	pub title: &'a str,
}

impl<'a> Course<'a> {
	/// Parses the course id.
	///
	/// # Errors
	///
	/// This function will return an error if nom fails to parse the course title or subtitle.
	pub fn parse_courseid(&mut self, elem: ElementRef<'a>) -> Result<(), NomError> {
		for child in elem.children().flat_map(|child| child.children()) {
			if let Some(text) = child.value().as_text() {
				self.title = title(text)?.1;
			} else if let Some(text) = child
				.first_child()
				.and_then(|node| node.value().as_text().map(|text| &**text))
			{
				self.subtitle = subtitle(text)?.1;
			}
		}

		Ok(())
	}

	/// Parses the course points, prerequisites, and restrictions from the given element.
	///
	/// # Panics
	///
	/// Panics if parsing fails, or a slice is made in the middle of a character.
	pub fn parse_coursepoints(&mut self, elem: ElementRef<'a>) {
		// Parse course points, prerequisites, and exclusions.
		let details = elem
			.first_child()
			.and_then(|el| el.first_child()?.value().as_text());

		if let Some(details) = details {
			let details_split: Vec<&str> = details.split(" \u{2022} ").take(2).collect();

			info!("{:#?}", &details_split);

			// Occasionally there is extra whitespace here, so this needs to be trimmed.
			let points = details_split.first().expect("split should exist").trim();
			debug!("{:?}", points);

			let points_slice = &points.get(..points.len() - 4).expect("should be at indice");
			info!("{:?}", points_slice);

			let points = points_slice
				.parse::<f32>()
				.expect("should correctly parse points");
			info!("{:?}", points);

			self.points = points;

			if let Some(requirements) = details_split.last().map(|s| s.trim()) {
				if requirements.starts_with("(X)") {
					self.restrictions = requirements
						.get(4..)
						.expect("should be at indice")
						.split(SPLIT_SLICE)
						.map(str::trim)
						.collect::<Vec<&str>>();
				} else if requirements.starts_with("(P)") {
					let requirements = &requirements
						.get(4..)
						.expect("should be at indice")
						.split(" (X) ")
						.collect::<Vec<&str>>();

					self.prerequisites = requirements
						.first()
						.map(|s| {
							s.split(SPLIT_SLICE)
								.map(str::trim)
								.filter(|s| !s.is_empty())
								.collect::<Vec<&str>>()
						})
						.unwrap_or_default();

					if requirements.len() > 1 {
						self.restrictions = requirements
							.last()
							.map(|s| s.split(SPLIT_SLICE).map(str::trim).collect::<Vec<&str>>())
							.unwrap_or_default();
					}
				} else if details_split.len() > 1 {
					// Prevent the points from being dumped into requirements if they're the only
					// item.
					self.prerequisites = vec![requirements];
				}

				info!("{requirements}");
			}
		}
	}

	/// Parses the course timetable.
	///
	/// # Errors
	///
	/// This function will return an error if nom fails to parse the timetable from the provided
	/// data.
	pub fn parse_timetable(&mut self, elem: ElementRef<'a>) -> Result<(), NomError> {
		// Parse timetable / CRNs.
		let details = elem
			.first_child()
			.and_then(|el| el.first_child()?.value().as_text());

		if let Some(details) = details {
			info!("{:#?}", &details);

			self.timetable.push(offering(details)?.1);
		}

		Ok(())
	}
}

impl Default for Course<'_> {
	fn default() -> Self {
		Self {
			corequisites: Vec::default(),
			description: Option::default(),
			offered: true,
			points: f32::default(),
			prerequisites: Vec::default(),
			restrictions: Vec::default(),
			subject_areas: HashSet::default(),
			subtitle: "",
			timetable: Vec::default(),
			title: "",
		}
	}
}

/// A course offering, includes the CRN and [`Trimester`].
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[non_exhaustive]
pub struct CourseOffering {
	/// Reference number for this coursem e.g. 11723.
	pub course_reference_number: u16,

	/// Trimester this course is offered in.
	pub trimester: Trimester,
}

impl CourseOffering {
	/// Creates a new [`CourseOffering`].
	#[must_use]
	pub const fn new(course_reference_number: u16, trimester: Trimester) -> Self {
		Self {
			course_reference_number,
			trimester,
		}
	}
}

/// Trimester information Victoria University of Wellington offers.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, PartialOrd, Ord, Serialize)]
pub enum Trimester {
	/// Trimester one.
	One,

	/// Trimester two.
	Two,

	/// Trimester three.
	Three,

	/// Block dates. See course page for more information.
	BlockDates,

	/// Part year. See course page for more information.
	PartYear,

	/// Trimesters one and two.
	OneTwo,

	/// Trimesters two and three.
	TwoThree,

	/// Trimesters three and one.
	ThreeOne,

	/// Trimesters one, two, and three.
	FullYear,
}

impl TryFrom<&str> for Trimester {
	type Error = &'static str;

	fn try_from(value: &str) -> Result<Self, Self::Error> {
		match value {
			"1/3" => Ok(Self::One),
			"2/3" => Ok(Self::Two),
			"3/3" => Ok(Self::Three),
			"block dates/3" => Ok(Self::BlockDates),
			"part year/3" => Ok(Self::PartYear),
			"1+2/3" => Ok(Self::OneTwo),
			"2+3/3" => Ok(Self::TwoThree),
			"3+1/3" => Ok(Self::ThreeOne),
			"1+2+3/3" | "2+3+1/3" | "3+1+2/3" | "full year" => Ok(Self::FullYear),
			_ => Err("Invalid trimester."),
		}
	}
}

/// Parses a [`Html`] document into a [`HashMap`] of courses.
///
/// # Panics
///
/// Panics if [`Selector`] fails to parse.
#[must_use]
pub fn parse_document(document: &Html) -> HashMap<&str, Course<'_>> {
	let mut course_map: HashMap<&str, Course> = HashMap::new();

	let mut subject_area = "";
	let mut working_course = Course::default();

	// PERF: Could we gain a meaningful speed boost by splitting this into chunks of each course?
	for elem in document.select(&Selector::parse("p").expect("selector should always be valid")) {
		let elem_value = elem.value();

		if elem_value.has_class("courseid", CaseSensitivity::CaseSensitive) {
			course_map
				.entry(working_course.title)
				.and_modify(|c| {
					c.subject_areas.insert(subject_area);
				})
				.or_insert(working_course);
			working_course = Course::default();
			working_course.subject_areas.insert(subject_area);

			working_course
				.parse_courseid(elem)
				.expect("could not parse courseid");
		} else if elem_value.has_class("notoffered", CaseSensitivity::CaseSensitive) {
			working_course.offered = false;
		} else if elem_value.has_class("subjectarea", CaseSensitivity::CaseSensitive) {
			if let Some(subject_area_name) = elem.first_child().and_then(|child| {
				child
					.first_child()
					.and_then(|nexted_child| nexted_child.value().as_text())
			}) {
				subject_area = &**subject_area_name;
			}
		} else if elem_value.has_class("subjectsbody", CaseSensitivity::CaseSensitive) {
			let description = elem
				.first_child()
				.and_then(|el| el.first_child()?.value().as_text())
				.map(|t| &**t);

			working_course.description = description;
		} else if elem_value.has_class("timetable", CaseSensitivity::CaseSensitive) {
			working_course
				.parse_timetable(elem)
				.expect("could not parse timetable");
		} else if elem_value.has_class("coursepoints", CaseSensitivity::CaseSensitive) {
			working_course.parse_coursepoints(elem);
		}
	}

	course_map.remove("");

	course_map
}