Skip to content

Commit

Permalink
new API, support node.js
Browse files Browse the repository at this point in the history
  • Loading branch information
YieldRay committed Mar 25, 2022
1 parent 8e5fdd4 commit 1ea0613
Show file tree
Hide file tree
Showing 6 changed files with 220 additions and 273 deletions.
65 changes: 42 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,57 @@
# Random-Picture

通过随机发送`url.csv`文件中给出的图床链接来实现一个随机图片 API
通过随机发送`url.csv`文件中给出的图床链接来实现一个随机图片 API
本仓库含 php(vercel), node.js(vercel), deno(deno.dev) 版本,API 一致

## 演示地址:
## 演示

<https://miku.x10.mx/> _(无稳定性保证)_
<https://random-picture.vercel.app/> _(部署到 vercel,访问此地址查看使用说明)_
- <https://random-picture.vercel.app/> _(vercel 演示)_
- <https://random-picture.vercel.app/api/> _(vercel, php 版本)_
- <https://random-picture.vercel.app/random.jpg>
- <https://random-picture.vercel.app/api/?json>
- <https://random-picture.vercel.app/api/node/> _(vercel, nodejs 版本)_
- <https://random-picture.vercel.app/api/node/?json>

- <https://rand.deno.dev/> (deno 版本)
- <https://rand.deno.dev/?json>
- <https://rand.deno.dev/?raw>
- <https://rand.deno.dev/?id=3>
- <https://rand.deno.dev/3.jpg>
- <https://rand.deno.dev/random.png?raw>

> 演示图片来自<https://www.pixiv.net/users/8236670>
## 部署到 Vercel
## php 部署到 Vercel

fork 后,修改自己仓库的 `url.csv`,然后在 Vercel 平台上导入自己的项目
fork 后,修改自己仓库的 `url.csv`,然后在 Vercel 平台上导入自己的项目
你也可以直接修改<https://github.com/YieldRay/Random-Picture/blob/master/url.csv>来创建 fork
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/git?s=https%3A%2F%2Fgithub.com%2FYieldRay%2FRandom-Picture)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/git?s=https%3A%2F%2Fgithub.com%2FYieldRay%2FRandom-Picture)
php 版本也可以直接上传到虚拟主机

## node.js 部署到 Vercel

![env.png](https://s2.loli.net/2022/03/25/ocECsXr2v1aKShG.png)
部署到 vercel 后设置环境变量 `RECORD_URL` 为图片地址,或直接修改源码给定位置
如果你已经 frok 了本项目,环境变量填入`https://raw.githubusercontents.com/YieldRay/Random-Picture/master/url.csv`即可
**注意将用户名换为你自己的 Github 用户名**
当然你也可以自行托管此文本,但是每次修改需要重新部署才能获取到更新后的地址
如果出错请切换到 node.js >= 14

## 部署到虚拟主机
nodejs 及 deno 版本每次部署时将图床地址读入内存,因此 API 不宜托管过多图床链接

上传至虚拟主机即可
## deno 部署到 deno.dev

Deno 版本需要你能够托管一个文本文件,并获取这个文本文件的网址。下面托管在 Github

登录<https://dash.deno.com/>
![deno.png](https://s2.loli.net/2022/03/20/tLITdUB4kWHe7VO.png)
点击 `New Playground`
![deno2.png](https://s2.loli.net/2022/03/20/h53uRYrnmQxwAz1.png)
进入<https://github.com/YieldRay/Random-Picture/blob/master/test/deno.ts>
或者复制<https://github.com/YieldRay/Random-Picture/raw/master/test/deno.ts>所有代码
删除编辑器所有原有代码,再将复制的代码粘贴,最后点击 `✔ Saved & Deployed` 即可

## 伪静态
## php 伪静态

伪静态是可选的。
开启伪静态后支持以<https://example.net/:id.png>形式访问
Expand All @@ -34,16 +66,3 @@ location / {
}
}
```

## Deno 版本

Deno 版本需要你能够托管一个文本文件,并获取这个文本文件的网址
下面托管在 Github

登录<https://dash.deno.com/>
![deno.png](https://s2.loli.net/2022/03/20/tLITdUB4kWHe7VO.png)
点击 `New Playground`
![deno2.png](https://s2.loli.net/2022/03/20/h53uRYrnmQxwAz1.png)
进入<https://github.com/YieldRay/Random-Picture/blob/master/test/deno.ts>
或者复制<https://github.com/YieldRay/Random-Picture/raw/master/test/deno.ts>所有代码
删除编辑器所有原有代码,再将复制的代码粘贴,最后点击 `✔ Saved & Deployed` 即可
111 changes: 35 additions & 76 deletions api/index.php
Original file line number Diff line number Diff line change
@@ -1,95 +1,54 @@
<?php
const ALLOW_OUTPUT = false; // 修改以开启
const ERROR_IMG = [
404 => 'https://http.cat/404',
503 => 'https://http.cat/503'
];

const ALLOW_RAW_OUTPUT = true;
// 是否开启 ?raw 选项,可能会消耗服务器较多流量

function has_query($query)
{
return isset($_GET[$query]);
}
if (file_exists('../url.csv')) {
$url = file('../url.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$imgs_array = file('../url.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
} else {
$url = file('http://' . $_SERVER['HTTP_HOST'] . '/url.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$imgs_array = file('http://' . $_SERVER['HTTP_HOST'] . '/url.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}

if (empty($url[0])) {
$code = 503;
$target_url = ERROR_IMG[503];
if (count($imgs_array) == 0) {
$imgs_array = ['https://http.cat/503'];
}


$id = $_REQUEST['id'];
$type = $_REQUEST['type'];
$length = count($url);
$final_id = array_rand($url);
$is_idValid = false;

if (isset($id)) {
$id = 0;
if (is_numeric($_GET['id'])) {
header('Cache-Control: public, max-age=86400');
if (is_numeric($id)) {
settype($id, 'integer');
if ($is_idValid = is_int($id)) {
$final_id = $id; // id是整数
}
global $id;
$id = $_GET['id'];
settype($id, 'int');
$len = count($imgs_array);
if ($id >= $len || $id < 0) {
$id = array_rand($imgs_array);
}
} else {
header('Cache-Control: no-cache');
$id = array_rand($imgs_array);
}



if (!$code && $is_idValid && $final_id > $length) {
// 超过最大数
$code = 404;
$target_url = ERROR_IMG[404];
} else {
$code = 200;
$target_url = $url[$final_id];
if (has_query('json')) {
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo json_encode(['id' => $id, 'url' => $imgs_array[$id]]);
exit();
}

/**
* Variables for OUTPUT
* $code
* $target_url final url
* $length amount of images
*/
header('Access-Control-Max-Age: 86400'); // 1day
header('Access-Control-Allow-Origin: *');

switch ($type) {
case 'length':
echo $length;
break;
case 'json':
$result = [
'code' => $code,
'url' => $target_url
];
header('Content-Type: text/json');
echo json_encode($result);
break;
case 'JSON':
$result = [
'code' => $code,
'url' => $target_url
];
$imageInfo = getimagesize($target_url);
$imageSize = get_headers($target_url, 1)['Content-Length'];
$result['width'] = $imageInfo[0];
$result['height'] = $imageInfo[1];
$result['mime'] = $imageInfo['mime'];
$result['size'] = $imageSize;
header('Content-Type: text/json');
echo json_encode($result);
break;
case 'output':
header($header);
if (ALLOW_OUTPUT) {
header('Content-Type: image/png');
echo file_get_contents($target_url);
} else {
die('disabled');
}
break;
default:
header('Location: ' . $target_url);
if (has_query('raw')) {
if (!ALLOW_RAW_OUTPUT) {
header('HTTP/1.1 403 Forbidden');
exit();
}
header('Content-Type: image/png');
echo file_get_contents($imgs_array[$id]);
exit();
} else {
header('Location: ' . $imgs_array[$id]);
}
30 changes: 16 additions & 14 deletions test/node.mjs → api/node.mjs
Original file line number Diff line number Diff line change
@@ -1,23 +1,15 @@
import axios from 'axios';
// 填入环境变量,或者修改下面的地址,这个地址应该返回一个文本文件,每行一个图片地址
const recordURL = process.env.RECORD_URL || 'https://raw.githubusercontents.com/YieldRay/Random-Picture/master/url.csv';
/**
* 有?json则返回json,否则如有?raw直接输出图像否则302跳转
* 优先获取123.jpg中的id,其次?id
* example:
* https://rand.deno.dev/?id=123
* https://rand.deno.dev/3.jpg
* https://rand.deno.dev/3.png?json
* https://rand.deno.dev/3.jpeg?raw
* https://rand.deno.dev/?raw
*/

/*
* Program Start
*/
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const imagesArray = ['https://http.cat/503'];
(async () => {
const text = await axios.get(recordURL).then(res => res.data);
console.log(text);
const imgs = text.split(/\r|\n|\r\n/);
const imgs = text.split(/\r|\n|\r\n/).filter(item => item.length > 5);
imagesArray.splice(0, 1, ...imgs);
})();

Expand Down Expand Up @@ -46,8 +38,12 @@ export default async function (req /*: http.IncomingMessage*/, res /*: http.Serv
console.log(`send ${id} of ${imagesArray.length} with ${req.url}`);
// 调整发送格式json/raw/302
if (searchParams.has('json')) {
res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
res.write(JSON.stringify({ url: remoteURL }));
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-cache',
});
res.write(JSON.stringify({ id, url: remoteURL }));
res.end();
} else if (searchParams.has('raw')) {
console.log(`send raw ${remoteURL}`);
Expand All @@ -60,10 +56,16 @@ export default async function (req /*: http.IncomingMessage*/, res /*: http.Serv
'User-Agent': 'PixivIOSApp/6.7.1 (iOS 10.3.1; iPhone8,1)',
}, // 这个Header允许调用pixiv上面的图片
});
res.writeHead(200, {
'Content-Type': response.headers['content-type'],
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-cache',
});
response.data.pipe(res);
} else {
res.writeHead(302, {
Location: remoteURL,
'Cache-Control': 'no-cache',
});
res.end();
}
Expand Down
Loading

0 comments on commit 1ea0613

Please sign in to comment.