/
media.ts
52 lines (42 loc) 路 1.37 KB
/
media.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// @ts-nocheck
import got from '@/utils/got';
import { config } from '@/config';
const { getDomain } = require('tldts');
const { refererMap } = require('./referer-map');
export default async (ctx) => {
if (!config.feature.mediaProxyKey) {
throw new Error('Internal media proxy is disabled.');
}
const key = ctx.req.param('key');
if (key !== config.feature.mediaProxyKey) {
throw new Error('Invalid media proxy key.');
}
const url = decodeURIComponent(ctx.req.param('url'));
const requestUrl = new URL(url);
const { hostname, origin } = requestUrl;
const domain = getDomain(hostname);
let referer = refererMap.get(domain);
referer ||= origin;
const { headers } = await got.head(url, {
headers: {
referer,
},
});
const cacheControl = headers['cache-control'];
const contentType = headers['content-type'];
const contentLength = headers['content-length'];
if (!contentType.startsWith('image/') || headers.server === 'RSSHub') {
return ctx.redirect(url);
}
ctx.set({
'cache-control': cacheControl || `public, max-age=${config.cache.contentExpire}`,
'content-length': contentLength,
'content-type': contentType,
server: 'RSSHub',
});
ctx.body = await got.stream(url, {
headers: {
referer,
},
});
};