Skip to content

Instantly share code, notes, and snippets.

@KrishGarg
Last active December 25, 2022 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KrishGarg/98a0968acccae143ab135dd2a00e14fc to your computer and use it in GitHub Desktop.
Save KrishGarg/98a0968acccae143ab135dd2a00e14fc to your computer and use it in GitHub Desktop.
import cheerio from "cheerio";
import fetch from "node-fetch";
import fs from "fs/promises"
const ALLOWED_CLASSES = {
"REGULAR CLASS-H": "Regular Class",
"MERGE CLASS-H": "Merge Class"
};
const DEFAULT_BATCH = "31216-4846"
const getBatchID = async (batch) => {
const bText = await fs.readFile("/opt/files/batches.json", "utf-8")
const b = JSON.parse(bText)
const reqbatch = b.find((e) => e.batch == batch)
if (!reqbatch) return null;
return reqbatch.id;
}
const parseAndGetTimeTableData = $ => {
let tt = [];
$("table").each((ti, table) => { // ti: table index -> 1 table for each day
$(table)
.find("tr")
.each((i, tr) => {
if (i == 0) return;
if (i == 1) {
const date = $(tr).find("td").get(0).children[0].data;
const day = $(tr).find("td").get(1).children[0].data;
tt[ti] = {
...tt[ti],
date,
day,
};
return;
}
let typeOfClass = $(tr).find("td").get(2).children[0].data;
if (!ALLOWED_CLASSES[typeOfClass]) return;
typeOfClass = ALLOWED_CLASSES[typeOfClass];
const [from, to] = $(tr).find("td").get(3).children[0].data.split("-");
const subject = $(tr).find("td").get(4).children[0].data;
const classDetails = {
subject,
from,
to,
typeOfClass,
};
tt[ti] = {
...tt[ti],
classes: [...(tt[ti].classes || []), classDetails],
};
});
});
tt = tt.filter((el) => el["classes"] && el["classes"].length > 0)
return tt;
}
/**
* @param {NapkinRequest} req
* @param {NapkinResponse} res
*/
const handler = async (req, res) => {
let batchID = DEFAULT_BATCH;
if (req.query) {
const { batchID: queryID, batch } = req.query;
if (batch && !queryID) {
const id = await getBatchID(batch);
if (!id) return res.json({
error: true,
message: "Unknown Batch",
})
batchID = id
}
if (queryID) batchID = queryID;
}
const r = await fetch("https://jaipur.allen.ac.in/Home/GetBatchTimeTable", {
headers: {
accept: "text/html, */*; q=0.01",
"content-type": "application/json; charset=UTF-8",
},
body: JSON.stringify({
batchID,
}),
method: "POST",
});
const ttHtml = await r.text();
if (ttHtml.includes("An error occurred while processing your request")) {
return res.json({
error: true,
message: "There was an error."
})
}
const $ = cheerio.load(ttHtml);
let tt = parseAndGetTimeTableData($);
const batch = $("h2").first().find("span").get(0).children[0].data;
const full = {
batch,
timetable: tt,
};
return res.json(full);
};
export default handler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment