71 lines
2.1 KiB
JavaScript
71 lines
2.1 KiB
JavaScript
class Giphy {
|
|
baseUrl = "https://giphy.com";
|
|
|
|
constructor(fetchPath, cheerioPath, browser) {
|
|
this.browser = browser;
|
|
this.type = "image-board";
|
|
}
|
|
|
|
async fetchSearchResult(query = "hello", page = 1, perPage = 48) {
|
|
const url = `${this.baseUrl}/search/${query.trim().replace(/\s+/g, "-")}`;
|
|
|
|
const data = await this.browser.scrape(
|
|
url,
|
|
() => {
|
|
const items = document.querySelectorAll('a[data-giphy-id]');
|
|
const results = [];
|
|
|
|
items.forEach(el => {
|
|
const id = el.getAttribute('data-giphy-id');
|
|
|
|
// solo coger sources válidos
|
|
const srcWebp = el.querySelector('source[type="image/webp"][srcset^="http"]');
|
|
const srcImg = el.querySelector('img');
|
|
|
|
let rawSrc =
|
|
srcWebp?.getAttribute("srcset")?.split(" ")[0] ||
|
|
srcImg?.src ||
|
|
null;
|
|
|
|
// ignorar 1x1 base64
|
|
if (!rawSrc || rawSrc.startsWith("data:")) return;
|
|
|
|
const imgUrl = rawSrc;
|
|
|
|
const alt = srcImg?.getAttribute("alt") || "";
|
|
const tags = alt.trim().split(/\s+/).filter(Boolean);
|
|
|
|
results.push({
|
|
id,
|
|
image: imgUrl,
|
|
sampleImageUrl: imgUrl,
|
|
tags,
|
|
type: "preview"
|
|
});
|
|
});
|
|
|
|
return {
|
|
results,
|
|
hasNextPage: false
|
|
};
|
|
},
|
|
{ waitSelector: 'picture img, a[data-giphy-id] img', scrollToBottom: true, timeout: 15000}
|
|
);
|
|
|
|
return {
|
|
results: data.results,
|
|
hasNextPage: data.hasNextPage,
|
|
page
|
|
};
|
|
}
|
|
|
|
async fetchInfo(id) {
|
|
return {
|
|
id,
|
|
createdAt: Date.now(),
|
|
rating: "Unknown"
|
|
};
|
|
}
|
|
}
|
|
|
|
module.exports = { Giphy }; |