UNPKG

@animepaste/bangumi

Version:
110 lines (104 loc) 2.91 kB
'use strict'; const axios = require('axios'); function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } const axios__default = /*#__PURE__*/_interopDefaultCompat(axios); const _BgmClient = class { constructor(bangumis = []) { this.api = axios__default.create({ baseURL: _BgmClient.baseURL, timeout: 10 * 1e3 }); this.bangumis = new Map(bangumis.map((bgm) => [bgm.bgmId, bgm])); } /** * See https://github.com/bangumi/api/blob/master/docs-raw/user%20agent.md */ setupUserAgent() { this.api = axios__default.create({ baseURL: _BgmClient.baseURL, timeout: 10 * 1e3, headers: { "User-Agent": "XLorPaste/AnimePaste (https://github.com/XLorPaste/AnimePaste)" } }); } async fetchRawCalendar() { const { data } = await this.api.get("/calendar"); return data; } async fetchRawSubject(bgmId) { for (let i = 0, time = 1; i <= _BgmClient.maxRetry; i++, time *= 2) { try { const { data } = await this.api.get(`/v0/subjects/${bgmId}`); return data; } catch (err) { if (axios__default.isAxiosError(err)) { const { response } = err; if (response?.status === 404) { return void 0; } } if (i === _BgmClient.maxRetry) { throw err; } await sleep(time); } } throw new Error("unreachable"); } async fetchCalendar() { const data = await this.fetchRawCalendar(); return data.map((d) => ({ weekday: d.weekday, bangumis: d.items.map((d2) => ({ // TODO: make typecheck pass ...this.bangumis.get(String(d2.id)), bgmId: String(d2.id), title: d2.name, titleCN: d2.name_cn, type: "tv", begin: d2.air_date, bgm: { summary: d2.summary, images: d2.images, eps: d2.eps, rating: d2.rating } })) })); } async fetchSubject(bgm) { const id = typeof bgm === "string" ? bgm : bgm.bgmId; const subject = await this.fetchRawSubject(id); if (!subject) { throw new Error(`${id} is not found`); } return { bgmId: id, type: "tv", begin: subject.date, ...typeof bgm === "string" ? void 0 : bgm, title: subject.name, titleCN: subject.name_cn, bgm: { summary: subject.summary, images: subject.images, eps: subject.total_episodes ?? subject.eps, rating: subject.rating, subject: { infobox: subject.infobox, tags: subject.tags } } }; } }; let BgmClient = _BgmClient; BgmClient.baseURL = "https://api.bgm.tv"; BgmClient.maxRetry = 5; function sleep(second = 1) { return new Promise((res) => { setTimeout(() => res(), second * 1e3); }); } exports.BgmClient = BgmClient;