2024-04-21 08:26:29 +03:00
|
|
|
import axios from "axios";
|
|
|
|
import { JSDOM } from "jsdom";
|
2024-06-03 04:12:05 +03:00
|
|
|
import { requestWebPage } from "@main/helpers";
|
2024-04-21 08:26:29 +03:00
|
|
|
import { HowLongToBeatCategory } from "@types";
|
2024-06-03 04:12:05 +03:00
|
|
|
import { formatName } from "@shared";
|
2024-04-21 08:26:29 +03:00
|
|
|
|
|
|
|
export interface HowLongToBeatResult {
|
|
|
|
game_id: number;
|
|
|
|
profile_steam: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface HowLongToBeatSearchResponse {
|
|
|
|
data: HowLongToBeatResult[];
|
|
|
|
}
|
|
|
|
|
|
|
|
export const searchHowLongToBeat = async (gameName: string) => {
|
|
|
|
const response = await axios.post(
|
|
|
|
"https://howlongtobeat.com/api/search",
|
|
|
|
{
|
|
|
|
searchType: "games",
|
|
|
|
searchTerms: formatName(gameName).split(" "),
|
|
|
|
searchPage: 1,
|
|
|
|
size: 100,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
headers: {
|
|
|
|
"User-Agent":
|
|
|
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
|
|
|
|
Referer: "https://howlongtobeat.com/",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
return response.data as HowLongToBeatSearchResponse;
|
|
|
|
};
|
|
|
|
|
2024-05-03 12:13:07 +03:00
|
|
|
const parseListItems = ($lis: Element[]) => {
|
|
|
|
return $lis.map(($li) => {
|
|
|
|
const title = $li.querySelector("h4")?.textContent;
|
|
|
|
const [, accuracyClassName] = Array.from(($li as HTMLElement).classList);
|
|
|
|
|
|
|
|
const accuracy = accuracyClassName.split("time_").at(1);
|
|
|
|
|
|
|
|
return {
|
|
|
|
title: title ?? "",
|
|
|
|
duration: $li.querySelector("h5")?.textContent ?? "",
|
|
|
|
accuracy: accuracy ?? "",
|
|
|
|
};
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2024-04-21 08:26:29 +03:00
|
|
|
export const getHowLongToBeatGame = async (
|
|
|
|
id: string
|
|
|
|
): Promise<HowLongToBeatCategory[]> => {
|
|
|
|
const response = await requestWebPage(`https://howlongtobeat.com/game/${id}`);
|
|
|
|
|
|
|
|
const { window } = new JSDOM(response);
|
|
|
|
const { document } = window;
|
|
|
|
|
|
|
|
const $ul = document.querySelector(".shadow_shadow ul");
|
2024-05-03 12:13:07 +03:00
|
|
|
if (!$ul) return [];
|
|
|
|
|
2024-04-21 08:26:29 +03:00
|
|
|
const $lis = Array.from($ul.children);
|
|
|
|
|
2024-05-03 12:13:07 +03:00
|
|
|
const [$firstLi] = $lis;
|
2024-04-21 08:26:29 +03:00
|
|
|
|
2024-05-03 12:13:07 +03:00
|
|
|
if ($firstLi.tagName === "DIV") {
|
|
|
|
const $pcData = $lis.find(($li) => $li.textContent?.includes("PC"));
|
|
|
|
return parseListItems(Array.from($pcData?.querySelectorAll("li") ?? []));
|
|
|
|
}
|
2024-04-21 08:26:29 +03:00
|
|
|
|
2024-05-03 12:13:07 +03:00
|
|
|
return parseListItems($lis);
|
2024-04-21 08:26:29 +03:00
|
|
|
};
|