|
| 1 | +import axios from 'axios'; |
| 2 | +// 填入环境变量,或者修改下面的地址,这个地址应该返回一个文本文件,每行一个图片地址 |
| 3 | +const recordURL = process.env.RECORD_URL || 'https://raw.githubusercontents.com/YieldRay/Random-Picture/master/url.csv'; |
| 4 | +/** |
| 5 | + * 有?json则返回json,否则如有?raw直接输出图像否则302跳转 |
| 6 | + * 优先获取123.jpg中的id,其次?id |
| 7 | + * example: |
| 8 | + * https://rand.deno.dev/?id=123 |
| 9 | + * https://rand.deno.dev/3.jpg |
| 10 | + * https://rand.deno.dev/3.png?json |
| 11 | + * https://rand.deno.dev/3.jpeg?raw |
| 12 | + * https://rand.deno.dev/?raw |
| 13 | + */ |
| 14 | + |
| 15 | +const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; |
| 16 | +const imagesArray = ['https://http.cat/503']; |
| 17 | +(async () => { |
| 18 | + const text = await axios.get(recordURL).then(res => res.data); |
| 19 | + console.log(text); |
| 20 | + const imgs = text.split(/\r|\n|\r\n/); |
| 21 | + imagesArray.splice(0, 1, ...imgs); |
| 22 | +})(); |
| 23 | + |
| 24 | +export default async function (req /*: http.IncomingMessage*/, res /*: http.ServerResponse*/) { |
| 25 | + const url = new URL('http://localhost' + req.url); |
| 26 | + if (req.url === '/favicon.ico') { |
| 27 | + res.writeHead(503); |
| 28 | + res.end(); |
| 29 | + return; |
| 30 | + } |
| 31 | + const searchParams = new URLSearchParams(url.search); |
| 32 | + let stringNumber; // 获取id |
| 33 | + const matched = url.pathname.match(/^\/(\d+)\.(?:jpg|jpeg|png|gif|webp)$/); |
| 34 | + if (matched) { |
| 35 | + stringNumber = matched[1]; |
| 36 | + } else { |
| 37 | + stringNumber = searchParams.get('id') ?? ''; |
| 38 | + } |
| 39 | + let id = Number(stringNumber); |
| 40 | + if (stringNumber.length === 0 || Number.isNaN(id)) { |
| 41 | + id = randomNum(0, imagesArray.length - 1); |
| 42 | + } else { |
| 43 | + if (id < 0 || id >= imagesArray.length) id = randomNum(0, imagesArray.length - 1); |
| 44 | + } |
| 45 | + const remoteURL = imagesArray[id]; |
| 46 | + console.log(`send ${id} of ${imagesArray.length} with ${req.url}`); |
| 47 | + // 调整发送格式json/raw/302 |
| 48 | + if (searchParams.has('json')) { |
| 49 | + res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }); |
| 50 | + res.write(JSON.stringify({ url: remoteURL })); |
| 51 | + res.end(); |
| 52 | + } else if (searchParams.has('raw')) { |
| 53 | + console.log(`send raw ${remoteURL}`); |
| 54 | + const response = await axios({ |
| 55 | + method: 'get', |
| 56 | + url: remoteURL, |
| 57 | + responseType: 'stream', |
| 58 | + headers: { |
| 59 | + Referer: 'https://www.pixiv.net/', |
| 60 | + 'User-Agent': 'PixivIOSApp/6.7.1 (iOS 10.3.1; iPhone8,1)', |
| 61 | + }, // 这个Header允许调用pixiv上面的图片 |
| 62 | + }); |
| 63 | + response.data.pipe(res); |
| 64 | + } else { |
| 65 | + res.writeHead(302, { |
| 66 | + Location: remoteURL, |
| 67 | + }); |
| 68 | + res.end(); |
| 69 | + } |
| 70 | +} |
0 commit comments