random-miku-server/index.js

36 lines
1.5 KiB
JavaScript

require("dotenv").config();
var {MongoClient, GridFSBucket} = require("mongodb");
var express = require("express");
var app = express();
app.set("trust proxy", "127.0.0.1");
var dbclient = new MongoClient(process.env.DB_URI);
dbclient.connect().then(async () => {
var db = dbclient.db("mikudb");
var collection = db.collection("illustration_collection");
var bucket = new GridFSBucket(db);
var idlist = require("./idlist.json");
var ipa_lastload_map = {};
let redirectRandom = (req, res) => {
let random_id = idlist[Math.floor(Math.random() * idlist.length)];
res.redirect(`/https://www.pixiv.net/en/artworks/${random_id}`);
};
app.get('/', redirectRandom);
app.get("/https://www.pixiv.net/en/artworks/:id", async (req, res) => {
//if (req.headers["cache-control"] == "max-age=0") { // this indicates a reload in chrome
// but chrome still sends it after redirect
if (ipa_lastload_map[req.ip] == req.params.id && req.query.noredirect == null) {
return redirectRandom(req, res);
} else ipa_lastload_map[req.ip] = req.params.id;
console.log(new Date().toLocaleString(), req.ip, req.params.id);
var asdf = await collection.findOne({_id: req.params.id}, {downloaded_images: 1});
if (!asdf) return res.sendStatus(404);
var filename = Object.keys(asdf.downloaded_images)[0];
res.type(filename.split('.').pop());
res.header("Content-Disposition", `filename=${filename}`);
var gfsid = Object.values(asdf.downloaded_images)[0];
bucket.openDownloadStream(gfsid).pipe(res);
});
app.listen(39);
console.log("server ready");
});