startpage-engine/ext/wallhaven.js
2022-03-27 17:14:49 -04:00

50 lines
1.7 KiB
JavaScript

const axios = require("axios");
const cheerio = require("cheerio");
const fs = require("fs");
exports.search = function(q, cb) {
axios({
url: `https://wallhaven.cc/search?q=${q}&categories=110&atleast=1920x1080&purity=100&sorting=relevance&order=desc&page=2`,
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Referer": `https://wallhaven.cc`,
"Upgrade-Insecure-Requests": "1",
"DNT": "1"
}
}).then(function(res) {
var $ = cheerio.load(res.data);
var max = $(".thumb-sfw img").length;
var h = Math.floor(Math.random() * (max - 0 + 1) + 0);
if (h == max) h = h - 1;
var th = $(".thumb-sfw img")[h].attribs["data-src"];
cb(null, smalltoFull(th, isPng($(".thumb-sfw")[h])))
}).catch(function(err) {
cb(err, null);
})
}
function smalltoFull(url, isPng) {
var as = url.split("/small/")[1].split("/")[0];
var id = url.split(`${as}/`)[1].split(".")[0];
var ext = url.split(".")[url.split(".").length - 1];
if (isPng) ext = "png";
return `https://w.wallhaven.cc/full/${as}/wallhaven-${id}.${ext}`;
}
function isPng(element) {
for (var c in element.children) {
if (element.children[c].attribs && element.children[c].attribs.class == "thumb-info") {
for (var d in element.children[c].children) {
if (element.children[c].children[d].attribs && element.children[c].children[d].attribs.class == "png") {
return true;
}
}
} else {
continue;
}
}
return false;
}