From 8826dd276fe4a5ccab2b074d77191b81b265e528 Mon Sep 17 00:00:00 2001 From: Ritesh Ghosh Date: Sun, 17 Dec 2023 19:41:22 +0530 Subject: [PATCH] feat(estimatedSchedule): add `estimatedSchedule` parser --- src/parsers/estimatedSchedule.ts | 67 ++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/parsers/estimatedSchedule.ts diff --git a/src/parsers/estimatedSchedule.ts b/src/parsers/estimatedSchedule.ts new file mode 100644 index 0000000..b700054 --- /dev/null +++ b/src/parsers/estimatedSchedule.ts @@ -0,0 +1,67 @@ +import { + SRC_HOME_URL, + SRC_AJAX_URL, + USER_AGENT_HEADER, + ACCEPT_ENCODING_HEADER, +} from "../utils/index.js"; +import axios, { AxiosError } from "axios"; +import createHttpError, { type HttpError } from "http-errors"; +import { load, type CheerioAPI, type SelectorType } from "cheerio"; +import { type ScrapedEstimatedSchedule } from "../models/parsers/index.js"; + +// /anime/schedule?date=${date} +async function scrapeEstimatedSchedule( + date: string +): Promise { + const res: ScrapedEstimatedSchedule = { + scheduledAnimes: [], + }; + + try { + const estScheduleURL = + `${SRC_AJAX_URL}/schedule/list?tzOffset=-330&date=${date}` as const; + + const mainPage = await axios.get(estScheduleURL, { + headers: { + Accept: "*/*", + Referer: SRC_HOME_URL, + "User-Agent": USER_AGENT_HEADER, + "X-Requested-With": "XMLHttpRequest", + "Accept-Encoding": ACCEPT_ENCODING_HEADER, + }, + }); + + const $: CheerioAPI = load(mainPage?.data?.html); + + const selector: SelectorType = "li"; + + if ($(selector)?.text()?.trim()?.includes("No data to display")) { + return res; + } + + $(selector).each((_, el) => { + res.scheduledAnimes.push({ + id: $(el)?.find("a")?.attr("href")?.slice(1)?.trim() || null, + time: $(el)?.find("a .time")?.text()?.trim() || null, + name: $(el)?.find("a .film-name.dynamic-name")?.text()?.trim() || null, + jname: + $(el) + ?.find("a .film-name.dynamic-name") + ?.attr("data-jname") + ?.trim() || null, + }); + }); + + return res; + } catch (err: any) { + if (err instanceof AxiosError) { + throw createHttpError( + err?.response?.status || 500, + err?.response?.statusText || "Something went wrong" + ); + } + throw createHttpError.InternalServerError(err?.message); + } +} + +export default scrapeEstimatedSchedule;