You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
114 lines
2.5 KiB
114 lines
2.5 KiB
const xhr = require("xmlhttprequest").XMLHttpRequest;
|
|
|
|
const API_URL = "https://lolibooru.moe/post/index.json";
|
|
|
|
/*function nodes_of(page, path) {
|
|
|
|
const document = parse5.parse(page);
|
|
const xhtml = xmlser.serializeToString(document);
|
|
const doc = new dom().parseFromString(xhtml);
|
|
const select = xpath.useNamespace({"x": "http://www.w3.org/1999/xhtml"});
|
|
return select(path, doc);
|
|
}
|
|
|
|
function nodes(url, path, cb) {
|
|
|
|
const x = new xhr();
|
|
|
|
x.onreadystatechange = function() {
|
|
if(this.readyState===4) {
|
|
cb(nodes_of(this.responseText, path));
|
|
}
|
|
};
|
|
|
|
x.open("GET", url);
|
|
x.send();
|
|
}*/
|
|
|
|
function query(limit, page, _tags) {
|
|
if(_tags)
|
|
{
|
|
var tags = _tags.join(" ");
|
|
}
|
|
return API_URL + "?limit="+limit+"&page="+page+(tags?"&tags="+encodeURIComponent(tags):"");
|
|
}
|
|
|
|
function rin(range) {
|
|
return Math.floor(Math.random() * (range-1));
|
|
}
|
|
|
|
function getLoli(puts, number, range, page, tags, cb) {
|
|
var x = new xhr();
|
|
|
|
if(number==0) {
|
|
puts("Number was 0, returning");
|
|
cb([]);
|
|
return;
|
|
}
|
|
|
|
x.onreadystatechange = function() {
|
|
if(this.readyState===4) {
|
|
let response = JSON.parse(this.responseText);
|
|
if(response) {
|
|
puts("Response okay");
|
|
if(number==1) {
|
|
let r = rin(range);
|
|
puts("Running on single (index "+r+")");
|
|
cb([response[r]]);
|
|
}
|
|
else {
|
|
let resp = Array.from({length: number}, (value,key) => key);
|
|
puts("Proto resp "+number+ " ar "+ JSON.stringify(resp));
|
|
for(let i = (number-1);i>=1;i--)
|
|
{
|
|
let v = resp[i];
|
|
let j = rin(i);
|
|
resp[i] = resp[j];
|
|
resp[j] = v;
|
|
}
|
|
puts("Running on multiple (indecies "+ resp.join(", ")+")");
|
|
cb(resp.map(v => response[v]));
|
|
}
|
|
} else {
|
|
puts("Invalid response");
|
|
cb.error = "Invalid JSON from server";
|
|
cb();
|
|
}
|
|
}
|
|
};
|
|
|
|
x.open("GET", query(range, page, tags));
|
|
x.send();
|
|
}
|
|
|
|
function randomiseWith(puts, number, range, maxPage, tags, cb) {
|
|
let page = Math.floor(Math.random() * (range-1));
|
|
puts("Using page "+page);
|
|
if(number > range || number<0) {
|
|
cb.error = "Invalid range";
|
|
cb();
|
|
}
|
|
else
|
|
getLoli(puts, number,range, page, tags, cb);
|
|
}
|
|
|
|
function Config() {
|
|
this.range = 5;
|
|
this.page = 150;
|
|
this.tags = undefined;
|
|
this.number = 1;
|
|
this.debug = function(){};
|
|
}
|
|
|
|
var cfg = new Config();
|
|
exports.defaultConfig = cfg;
|
|
exports.Config = Config;
|
|
|
|
function randomise(cb, conf) {
|
|
if(!conf)
|
|
return randomise(cb, cfg);
|
|
conf.debug("Calling with params "+JSON.stringify(conf));
|
|
randomiseWith(conf.debug, conf.number, conf.range, conf.page, conf.tags, cb);
|
|
}
|
|
exports.randomise = randomise;
|