forked from MrMonkey42/stremio-addon-debrid-search
-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathserverless.js
More file actions
178 lines (153 loc) · 7.02 KB
/
Copy pathserverless.js
File metadata and controls
178 lines (153 loc) · 7.02 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import Router from 'router'
import cors from 'cors'
import rateLimit from "express-rate-limit";
import requestIp from 'request-ip'
import addonInterface from "./addon.js"
import landingTemplate from "./lib/util/landingTemplate.js"
import StreamProvider from './lib/stream-provider.js'
import { decode } from 'urlencode'
import qs from 'querystring'
import { getManifest } from './lib/util/manifest.js'
import { parseConfiguration } from './lib/util/configuration.js'
import { BadTokenError, BadRequestError, AccessDeniedError } from './lib/util/error-codes.js'
import RealDebrid from './lib/real-debrid.js'
const router = new Router();
const limiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 300, // limit each IP to 300 requests per windowMs
headers: false,
keyGenerator: (req) => requestIp.getClientIp(req)
})
router.use(cors())
router.get('/', (_, res) => {
res.redirect('/configure')
res.end();
})
router.get('/:configuration?/configure', async (req, res) => {
const config = parseConfiguration(req.params.configuration)
const host = `${req.protocol}://${req.headers.host}`;
const configValues = { ...config, host };
const landingHTML = await landingTemplate(addonInterface.manifest, configValues)
res.setHeader('content-type', 'text/html')
res.end(landingHTML)
})
router.get('/:configuration?/manifest.json', (req, res) => {
const config = parseConfiguration(req.params.configuration)
const host = `${req.protocol}://${req.headers.host}`;
const configValues = { ...config, host };
// For initial install (no configuration) or when ShowCatalog is explicitly disabled, serve manifest without catalogs
const noCatalogs = Object.keys(config).length === 0 || config.ShowCatalog === false;
// Set proper headers for Stremio compatibility (keeps the CORS fix)
res.setHeader('content-type', 'application/json; charset=utf-8');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.end(JSON.stringify(getManifest(configValues, noCatalogs)))
})
router.get(`/:configuration?/:resource/:type/:id/:extra?.json`, limiter, (req, res, next) => {
console.log(`[DEBUG-ROUTE] Received request: resource=${req.params.resource}, type=${req.params.type}, id=${req.params.id}, config length=${req.params.configuration?.length || 0}`)
const { resource, type, id } = req.params
const config = parseConfiguration(req.params.configuration)
console.log(`[DEBUG-ROUTE] Parsed config providers: ${config.DebridServices?.map(s => s.provider).join(', ') || 'none'}`)
const extra = req.params.extra ? qs.parse(req.url.split('/').pop().slice(0, -5)) : {}
const host = `${req.protocol}://${req.headers.host}`;
const clientIp = requestIp.getClientIp(req);
// Combine all configuration values properly, including clientIp
const fullConfig = { ...config, host, clientIp };
addonInterface.get(resource, type, id, extra, fullConfig)
.then(async (resp) => {
if (fullConfig.DebridProvider === 'RealDebrid' && resp && resp.streams) {
resp.streams = await RealDebrid.validatePersonalStreams(fullConfig.DebridApiKey, resp.streams);
}
let cacheHeaders = {
cacheMaxAge: 'max-age',
staleRevalidate: 'stale-while-revalidate',
staleError: 'stale-if-error'
}
const cacheControl = Object.keys(cacheHeaders)
.map(prop => Number.isInteger(resp[prop]) && cacheHeaders[prop] + '=' + resp[prop])
.filter(val => !!val).join(', ')
res.setHeader('Cache-Control', `${cacheControl}, public`)
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify(resp))
})
.catch(err => {
console.error(err)
handleError(err, res)
})
})
router.get('/resolve/:debridProvider/:debridApiKey/:id/:hostUrl', limiter, (req, res) => {
const clientIp = requestIp.getClientIp(req)
const decodedHostUrl = decode(req.params.hostUrl)
// Validate hostUrl parameter
if (!decodedHostUrl || decodedHostUrl === 'undefined') {
console.error('[RESOLVER] Missing or invalid hostUrl parameter')
return res.status(400).send('Missing or invalid hostUrl parameter')
}
const cacheKey = typeof req.query.cacheKey === 'string' ? req.query.cacheKey : null;
const cacheHash = typeof req.query.cacheHash === 'string' ? req.query.cacheHash : null;
const resolveConfig = {};
if (cacheKey && cacheKey.length < 512) resolveConfig.cacheKey = cacheKey;
if (cacheHash && cacheHash.length < 128) resolveConfig.cacheHash = cacheHash;
StreamProvider.resolveUrl(req.params.debridProvider, req.params.debridApiKey, req.params.id, decodedHostUrl, clientIp, resolveConfig)
.then(url => {
res.redirect(url)
})
.catch(err => {
console.log(err)
handleError(err, res)
})
})
// Handle 3-parameter resolve URLs (compatibility with server.js format)
router.get('/resolve/:debridProvider/:debridApiKey/:url', limiter, (req, res) => {
const { debridProvider, debridApiKey, url } = req.params;
// Validate required parameters
if (!url || url === 'undefined') {
console.error('[RESOLVER] Missing or invalid URL parameter');
return res.status(400).send('Missing or invalid URL parameter');
}
const decodedUrl = decodeURIComponent(url);
const clientIp = requestIp.getClientIp(req);
const cacheKey = typeof req.query.cacheKey === 'string' ? req.query.cacheKey : null;
const cacheHash = typeof req.query.cacheHash === 'string' ? req.query.cacheHash : null;
const resolveConfig = {};
if (cacheKey && cacheKey.length < 512) resolveConfig.cacheKey = cacheKey;
if (cacheHash && cacheHash.length < 128) resolveConfig.cacheHash = cacheHash;
StreamProvider.resolveUrl(debridProvider, debridApiKey, null, decodedUrl, clientIp, resolveConfig)
.then(url => {
if (url) {
res.redirect(url)
} else {
res.status(404).send('Could not resolve link');
}
})
.catch(err => {
console.log(err)
handleError(err, res)
})
})
router.get('/ping', (_, res) => {
res.statusCode = 200
res.end()
})
function handleError(err, res) {
if (err == BadTokenError) {
res.writeHead(401)
res.end(JSON.stringify({ err: 'Bad token' }))
} else if (err == AccessDeniedError) {
res.writeHead(403)
res.end(JSON.stringify({ err: 'Access denied' }))
} else if (err == BadRequestError) {
res.writeHead(400)
res.end(JSON.stringify({ err: 'Bad request' }))
} else {
res.writeHead(500)
res.end(JSON.stringify({ err: 'Server error' }))
}
}
export default function (req, res) {
router(req, res, function () {
res.statusCode = 404;
res.end();
});
}