-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
293 lines (268 loc) · 7.05 KB
/
app.js
File metadata and controls
293 lines (268 loc) · 7.05 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import "./src/env.js"
import express from "express"
import axios from "axios"
import redis from "./src/redis.js"
const app = express()
const port = process.env.PORT || 1188
const maxApiReqFailureTimes = process.env.MAX_API_REQ_FAILURE_TIMES || 3
app.use(express.json())
app.use(express.static("static"))
app.all("/*", async (req, res, next) => {
const authorization = req.header("Authorization") || req.query.password
if (checkAuth(authorization)) {
next()
} else {
forbidden(res)
}
})
const keyPrefix = process.env.PREFIX_KEY
let urlKey = "urls"
if (keyPrefix) {
urlKey = keyPrefix + ":" + urlKey
}
let cacheApis = []
let apiReqFailureTimes = {}
function ok(res, data) {
res.send({
code: 200,
msg: "ok",
data: data,
})
}
function error(res) {
res.status(500).send({
code: 500,
msg: "error",
})
}
function forbidden(res) {
res.status(403).send({
code: 403,
msg: "forbidden",
})
}
function checkAuth(authorization) {
const password = process.env.PASSWORD
if (!password || password === "") {
return true
}
return password === authorization
}
function createApiObj(url, status) {
const obj = {}
obj[url] = status
return obj
}
function checkIgnoreKeywords(url) {
const ignoreKeywords = process.env.IGNORE_KEYWORDS
if (!ignoreKeywords || ignoreKeywords === "") {
return true
}
const keywords = ignoreKeywords.split(",")
for (let keyword of keywords) {
if (url.includes(keyword)) {
return false
}
}
return true
}
async function initialize() {
const apiData = await redis.hgetall(urlKey)
if (apiData) {
cacheApis = [...Object.keys(apiData).filter(key => apiData[key] === "1")]
apiReqFailureTimes = {}
}
}
async function filterApis() {
let apis = cacheApis.filter(url => getApiReqFailureTimes(url) < maxApiReqFailureTimes)
if (apis.length === 0) {
// 重新初始化资源
await initialize()
apis = cacheApis.length === 0 ? [] : [...cacheApis]
}
return apis
}
function checkApiReturn(r, checkValue) {
if (!('data' in r) || !('data' in r.data)) {
return false
}
console.log(`response: ${JSON.stringify(r.data)}`)
const { data } = r.data
return checkValue ? data.includes(checkValue) : data.length > 0
}
function addApiReqFailureTimes(url) {
let times = apiReqFailureTimes[url]
if (!times) {
times = 0
}
times++;
apiReqFailureTimes[url] = times
}
function getApiReqFailureTimes(url) {
let times = apiReqFailureTimes[url]
if (times) {
return times
} else {
apiReqFailureTimes[url] = 0
return 0
}
}
async function checkApi(apis) {
apis = [...new Set(apis)]
const headers = { "Content-Type": "application/json" }
const payload = {
text: "Hello, World!",
source_lang: "EN",
target_lang: "ZH",
}
const promises = apis.map((api) => {
return new Promise((resolve) => {
axios.post(`${api}/translate`, payload, { headers, timeout: 5000 })
.then((res) => {
resolve(createApiObj(api, res.data.data.includes("你好,世界") ? "1" : "0"))
})
.catch((error) => {
resolve(createApiObj(api, "0"))
})
})
})
const results = await Promise.all(promises)
return Object.assign({}, ...results)
}
app.post("/translate", async (req, res) => {
const requestURI = req.path
const apis = await filterApis()
if (apis.length === 0) {
error(res)
return
}
let length = apis.length
while (length > 0) {
const randomIndex = Math.floor(Math.random() * length)
const targetURL = apis[randomIndex]
// 清理 targetURL,确保不包含 "/translate"
const url = new URL(targetURL);
if (url.pathname.endsWith("/translate")) {
url.pathname = url.pathname.substring(0, url.pathname.length - 10); // 移除 "/translate"
targetURL = url.toString();
}
const fullURL = targetURL + requestURI
console.log(`request: ${fullURL}, index: ${randomIndex} ,req: ${JSON.stringify(req.body)}`)
try {
let r = await axios.post(fullURL, req.body, {
headers: { "Content-Type": "application/json" },
timeout: 5000
})
// 验证结果
if (!checkApiReturn(r)) {
throw new Error("api check error")
}
res.send(r.data)
return
} catch (error) {
let reqFailureTimes = getApiReqFailureTimes(targetURL)
console.log(`request failure: ${fullURL}, index: ${randomIndex}, requestFailureTimes: ${reqFailureTimes}`)
if (reqFailureTimes > maxApiReqFailureTimes) {
apis.splice(randomIndex, 1)
} else {
addApiReqFailureTimes(targetURL)
}
}
length--
}
error(res)
})
app.get("/api", async (req, res) => {
try {
const apiData = await redis.hgetall(urlKey) || {}
const result = []
Object.keys(apiData).forEach(key => {
// 如果url在失效列表中且数值大于等于 maxApiReqFailureTimes 则为失效
let reqFailureTimes = getApiReqFailureTimes(key)
let status = reqFailureTimes >= maxApiReqFailureTimes ? "0" : apiData[key]
result.push({
url: key,
status: status,
})
})
result.sort((a, b) => {
return a.url.localeCompare(b.url)
})
ok(res, result)
} catch (e) {
console.log(e)
error(res)
}
})
app.post("/api", async (req, res) => {
try {
let apis = req.body
apis = apis.filter((api) =>
api !== "" &&
api.startsWith("http") &&
!api.includes("api.deeplx.org") &&
checkIgnoreKeywords(api)).map((x) => {
x = x.replace(/\s+/g, '')
if (x.endsWith("/")) {
x = x.substring(0, x.length - 1)
}
if (x.endsWith("/translate")) {
x = x.substring(0, x.length - 10)
}
return x
})
if (apis && apis.length > 0) {
const checkedApiData = await checkApi(apis)
await redis.hset(urlKey, checkedApiData)
await initialize()
}
ok(res, {})
} catch (e) {
console.log(e)
error(res)
}
})
app.post("/clear", async (req, res) => {
try {
const apiData = (await redis.hgetall(urlKey)) || {}
if (JSON.stringify(apiData) !== "{}") {
const apis = Object.keys(apiData)
const checkedApiData = await checkApi(apis)
const filterApiData = {}
Object.keys(checkedApiData).filter(key => checkedApiData[key] === "1").forEach(v => filterApiData[v] = "1")
await redis.del(urlKey)
if (JSON.stringify(filterApiData) === "{}") {
await redis.del(urlKey)
} else {
await redis.hset(urlKey, filterApiData)
}
cacheApis = [...Object.keys(filterApiData)]
}
ok(res, {})
} catch (e) {
console.log(e)
error(res)
}
})
app.post("/checkAuth", async (req, res) => {
const password = process.env.PASSWORD
try {
if (!password || password === "") {
ok(res, { anonymous: true })
return
}
const authorization = req.header("Authorization")
if (password !== authorization) {
forbidden(res)
} else {
ok(res, { anonymous: false })
}
} catch (e) {
console.log(e)
error(res)
}
})
await initialize()
app.listen(port, async () => {
console.log(`Server ready on port ${port}.`)
})