Skip to content

Commit

Permalink
fix javascript style
Browse files Browse the repository at this point in the history
  • Loading branch information
C4illin committed May 3, 2024
1 parent 8ba8f78 commit e74fe00
Show file tree
Hide file tree
Showing 4 changed files with 183 additions and 154 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules/
node_modules/
/lasvecka-node/pnpm-lock.yaml
137 changes: 71 additions & 66 deletions lasvecka-node/calc_date.js
Original file line number Diff line number Diff line change
@@ -1,81 +1,86 @@
const moment = require('moment');
const fs = require('fs');
const scrape = require('./lasveckor_scraper.js');
var dateDict = {};
const moment = require("moment");
const fs = require("node:fs");
const scrape = require("./lasveckor_scraper.js");
let dateDict = {};

// check if data.json exists
if (!fs.existsSync('./data/data.json')) {
scrape().then((res) => {
dateDict = res
});
if (!fs.existsSync("./data/data.json")) {
scrape().then((res) => {
dateDict = res;
});
} else {
dateDict = JSON.parse(fs.readFileSync('./data/data.json'));
dateDict = JSON.parse(fs.readFileSync("./data/data.json"));

//check if it was updated after 1/7 this year and if 1/7 has occured this year
let updated = moment(dateDict["updated"]);
let firstOfJuly = moment().month(6).date(1);
if (updated.isBefore(firstOfJuly) && moment().isAfter(firstOfJuly)) {
scrape().then((res) => {
dateDict = res
});
}
//check if it was updated after 1/7 this year and if 1/7 has occured this year
const updated = moment(dateDict.updated);
const firstOfJuly = moment().month(6).date(1);
if (updated.isBefore(firstOfJuly) && moment().isAfter(firstOfJuly)) {
scrape().then((res) => {
dateDict = res;
});
}
}

function readDatePeriod(currDate) {
let soughtDate = "";
let diff = -1000;
for (let dat in dateDict) {
// if dat is updated, easter_start, easter_end or ord_cont then skip
if (dat === "updated" || dat === "easter_start" || dat === "easter_end" || dat === "ord_cont") {
continue;
}
let deltaT = moment(dat).diff(currDate, 'days');
if (deltaT === 0) {
return { date: dat, type: dateDict[dat] };
} else if (deltaT > diff && deltaT < 0) {
soughtDate = dat;
diff = deltaT;
}
}
return { date: soughtDate, type: dateDict[soughtDate] };
let soughtDate = "";
let diff = -1000;
for (const dat in dateDict) {
// if dat is updated, easter_start, easter_end or ord_cont then skip
if (
dat === "updated" ||
dat === "easter_start" ||
dat === "easter_end" ||
dat === "ord_cont"
) {
continue;
}
const deltaT = moment(dat).diff(currDate, "days");
if (deltaT === 0) {
return { date: dat, type: dateDict[dat] };
}

if (deltaT > diff && deltaT < 0) {
soughtDate = dat;
diff = deltaT;
}
}
return { date: soughtDate, type: dateDict[soughtDate] };
}

function handleEaster(easterStartDiff, easterEndDiff) {
if (easterStartDiff >= 0 && easterEndDiff <= 0) {
return "Självstudier";
} else if (easterEndDiff > 0) {
let weeks = Math.floor(easterEndDiff / 7);
return "Lv " + (weeks + 4);
}
if (easterStartDiff >= 0 && easterEndDiff <= 0) {
return "Självstudier";
}
if (easterEndDiff > 0) {
const weeks = Math.floor(easterEndDiff / 7);
return `Lv ${weeks + 4}`;
}
}

function computeTime() {
// Find date where value is easter_start, easter_end and ord_cont in json file
let EASTER_START = dateDict["easter_start"]
let ORD_CONT = dateDict["ord_cont"]
let currentDate = moment();
let easterEndCheck = currentDate.diff(ORD_CONT, 'days');
let easterStartCheck = currentDate.diff(EASTER_START, 'days');
let { date: dat, type: typ } = readDatePeriod(currentDate);
if (typ === "exam_period") {
let deltaT = currentDate.diff(moment(dat), 'days');
if (deltaT > 7) {
return "Självstudier";
} else {
return "Tentavecka";
}
}
if (easterEndCheck >= 0 || easterStartCheck >= 0) {
return handleEaster(easterStartCheck, easterEndCheck);
} else {
let deltaT = currentDate.diff(moment(dat), 'days');
let weeks = Math.floor(deltaT / 7);
if (weeks > 7) {
return "Självstudier";
} else {
return "LV " + (weeks + 1);
}
}
// Find date where value is easter_start, easter_end and ord_cont in json file
const EASTER_START = dateDict.easter_start;
const ORD_CONT = dateDict.ord_cont;
const currentDate = moment();
const easterEndCheck = currentDate.diff(ORD_CONT, "days");
const easterStartCheck = currentDate.diff(EASTER_START, "days");
const { date: dat, type: typ } = readDatePeriod(currentDate);
if (typ === "exam_period") {
const deltaT = currentDate.diff(moment(dat), "days");
if (deltaT > 7) {
return "Självstudier";
}
return "Tentavecka";
}
if (easterEndCheck >= 0 || easterStartCheck >= 0) {
return handleEaster(easterStartCheck, easterEndCheck);
}
const deltaT = currentDate.diff(moment(dat), "days");
const weeks = Math.floor(deltaT / 7);
if (weeks > 7) {
return "Självstudier";
}
return `LV ${weeks + 1}`;
}

module.exports = computeTime;
module.exports = computeTime;
101 changes: 61 additions & 40 deletions lasvecka-node/index.js
Original file line number Diff line number Diff line change
@@ -1,61 +1,78 @@
const express = require('express');
const moment = require('moment');
const express = require("express");
const moment = require("moment");
const app = express();
const computeTime = require('./calc_date.js');
const computeTime = require("./calc_date.js");
const port = process.env.PORT || 3000;

let studyweek = '';
let studyweekNum = '';
let studyweek = "";
let studyweekNum = "";

function updateStudyWeek() {
studyweek = computeTime();
studyweekNum = studyweek.replace('LV ', '').replace('Självstudier', 'S').replace('Tentavecka', 'T');
return { studyweek, studyweekNum };
studyweek = computeTime();
studyweekNum = studyweek
.replace("LV ", "")
.replace("Självstudier", "S")
.replace("Tentavecka", "T");
return { studyweek, studyweekNum };
}

app.use(express.static('public'));
app.use(express.static("public"));

app.get('/', (req, res) => {
let { studyweek, studyweekNum } = updateStudyWeek();
let week = moment().format('YYYY-[W]WW'); // eg. 2023-W45
let data = { studyweek, week, studyweekNum };
res.send(render(data));
app.get("/", (req, res) => {
const { studyweek, studyweekNum } = updateStudyWeek();
const week = moment().format("YYYY-[W]WW"); // eg. 2023-W45
const data = { studyweek, week, studyweekNum };
res.send(render(data));
});

app.get('/data', (req, res) => {
res.send(computeTime());
app.get("/data", (req, res) => {
res.send(computeTime());
});

app.get('/favicon.ico', (req, res) => {
let studyweek = computeTime();
let studyweekNum = studyweek.replace('LV ', '').replace('Självstudier', 'S').replace('Tentavecka', 'T');
res.sendFile(`${__dirname}/public/icons/${studyweekNum}/favicon.ico`);
app.get("/favicon.ico", (req, res) => {
const studyweek = computeTime();
const studyweekNum = studyweek
.replace("LV ", "")
.replace("Självstudier", "S")
.replace("Tentavecka", "T");
res.sendFile(`${__dirname}/public/icons/${studyweekNum}/favicon.ico`);
});

app.get('/site.webmanifest', (req, res) => {
let studyweek = computeTime();
let studyweekNum = studyweek.replace('LV ', '').replace('Självstudier', 'S').replace('Tentavecka', 'T');
let manifest = {
"name": "läsvecka.nu",
"short_name": "läsvecka.nu",
"icons": [
{ "src": `/icons/${studyweekNum}/android-chrome-192x192.png`, "sizes": "192x192", "type": "image/png" },
{ "src": `/icons/${studyweekNum}/android-chrome-512x512.png`, "sizes": "512x512", "type": "image/png" }
],
"theme_color": "#1c7bb7",
"background_color": "#90c0de",
"display": "standalone"
};
app.get("/site.webmanifest", (req, res) => {
const studyweek = computeTime();
const studyweekNum = studyweek
.replace("LV ", "")
.replace("Självstudier", "S")
.replace("Tentavecka", "T");
const manifest = {
name: "läsvecka.nu",
short_name: "läsvecka.nu",
icons: [
{
src: `/icons/${studyweekNum}/android-chrome-192x192.png`,
sizes: "192x192",
type: "image/png",
},
{
src: `/icons/${studyweekNum}/android-chrome-512x512.png`,
sizes: "512x512",
type: "image/png",
},
],
theme_color: "#1c7bb7",
background_color: "#90c0de",
display: "standalone",
};

res.send(manifest);
res.send(manifest);
});

app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`)
})
console.log(`App listening at http://localhost:${port}`);
});

const render = (data) => {
const html = `
const html = `
<!DOCTYPE html>
<html>
<head>
Expand Down Expand Up @@ -96,5 +113,9 @@ const render = (data) => {
</script>
</body>
</html>`;
return html.replace(/\n/g, '').replace(/\r/g, '').replace(/\t/g, '').replace(/ {2,}/g, '');
}
return html
.replace(/\n/g, "")
.replace(/\r/g, "")
.replace(/\t/g, "")
.replace(/ {2,}/g, "");
};
96 changes: 49 additions & 47 deletions lasvecka-node/lasveckor_scraper.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,53 @@
const fs = require('fs');
const axios = require('axios');
const fs = require("node:fs");
const axios = require("axios");

async function scrape() {
console.log("Scraping data from student.chalmers.se")
let url = "https://www.student.chalmers.se/sp/academic_year_list"

const response = await axios.get(url, { responseType: "arraybuffer" })
let data = response.data.toString('latin1');

data = data.replace(/\n/g, '').replace(/\r/g, '').replace(/\t/g, '');
data = data.match(/<table width="100%" border="0" cellspacing="0" cellpadding="3">(.*?)<\/table>/s)[0]

// some things to make it nicer
data = data.replace(/<\/tr>/g, '\n')
data = data.replace(/<tr align="left">/g, '')
data = data.replace(/<tr align="left" class="fade">/g, '')
data = data.replace(/<td>/g, '')
data = data.replace(/<\/td>/g, '')
data = data.split('\n')

let result = {}
for (let i = 0; i < data.length; i++) {
let line = data[i]
if (line.startsWith('Läsperiod')) {
let date = line.match(/(\d{4}-\d{2}-\d{2})/)[0]
result[date] = "study_period"
} else if (line.startsWith('Tentamensperiod')) {
let date = line.match(/(\d{4}-\d{2}-\d{2})/)[0]
result[date] = "exam_period"
} else if (line.startsWith("Omtentamensperiod påsk")) {
let date1 = line.match(/(\d{4}-\d{2}-\d{2})/)[0]
let date2 = line.match(/(\d{4}-\d{2}-\d{2})/g)[1]
result["easter_start"] = date1
result["easter_end"] = date2

var easter_start = new Date(date1)
// find first monday after easter
while (easter_start.getDay() != 1) {
easter_start.setDate(easter_start.getDate() + 1)
}
result["ord_cont"] = easter_start.toISOString().slice(0, 10)
}
}

result["updated"] = new Date().toISOString().slice(0, 10)
await fs.promises.writeFile('./data/data.json', JSON.stringify(result))
return result
console.log("Scraping data from student.chalmers.se");
const url = "https://www.student.chalmers.se/sp/academic_year_list";

const response = await axios.get(url, { responseType: "arraybuffer" });
let data = response.data.toString("latin1");

data = data.replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "");
data = data.match(
/<table width="100%" border="0" cellspacing="0" cellpadding="3">(.*?)<\/table>/s,
)[0];

// some things to make it nicer
data = data.replace(/<\/tr>/g, "\n");
data = data.replace(/<tr align="left">/g, "");
data = data.replace(/<tr align="left" class="fade">/g, "");
data = data.replace(/<td>/g, "");
data = data.replace(/<\/td>/g, "");
data = data.split("\n");

const result = {};
for (let i = 0; i < data.length; i++) {
const line = data[i];
if (line.startsWith("Läsperiod")) {
const date = line.match(/(\d{4}-\d{2}-\d{2})/)[0];
result[date] = "study_period";
} else if (line.startsWith("Tentamensperiod")) {
const date = line.match(/(\d{4}-\d{2}-\d{2})/)[0];
result[date] = "exam_period";
} else if (line.startsWith("Omtentamensperiod påsk")) {
const date1 = line.match(/(\d{4}-\d{2}-\d{2})/)[0];
const date2 = line.match(/(\d{4}-\d{2}-\d{2})/g)[1];
result.easter_start = date1;
result.easter_end = date2;

const easter_start = new Date(date1);
// find first monday after easter
while (easter_start.getDay() !== 1) {
easter_start.setDate(easter_start.getDate() + 1);
}
result.ord_cont = easter_start.toISOString().slice(0, 10);
}
}

result.updated = new Date().toISOString().slice(0, 10);
await fs.promises.writeFile("./data/data.json", JSON.stringify(result));
return result;
}

module.exports = scrape;
module.exports = scrape;

0 comments on commit e74fe00

Please sign in to comment.