forked from DogReactor/AigisPlayer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
requestHandler.ts
275 lines (274 loc) · 8.38 KB
/
requestHandler.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
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
import * as stream from 'stream';
import { session, net, app, ipcMain, BrowserWindow } from 'electron';
import * as url from 'url';
import * as path from 'path';
import * as fs from 'fs';
import * as Config from 'electron-config';
import * as log from 'electron-log';
import { parseAL, AL } from 'aigis-fuel';
const config = new Config();
export class Rule {
public Url: Array<string>;
public Method: string;
public Request: boolean;
public Callback: (url: string, response, request?: any) => void;
constructor(
options: { url: string[]; method?: string; request?: any },
callback: (url: string, response, request?: any) => void
) {
this.Url = options.url;
this.Method = options.method || 'ALL';
this.Request = options.request || false;
this.Callback = callback;
}
match(url: string, method: string) {
function checkUrl(value: string) {
if (url.indexOf(value) !== -1) {
return true;
} else {
return false;
}
}
if (this.Url.find(checkUrl) && (this.Method === 'ALL' || this.Method === method)) {
return true;
}
return null;
}
}
let subscription: Array<Rule> = [];
let FileList = {};
let mainFontPath = config.get('fontPath');
let browserWindow: BrowserWindow;
export class RequestHandler {
static setFileList(fileList) {
FileList = fileList;
}
static setFontPath(path: string) {
mainFontPath = path;
}
static Clear() {
subscription = [];
}
static setWin(win) {
browserWindow = win;
}
static Subscribe(
options: { url: Array<string>; method?: string; request?: boolean },
callback: (url: string, response, request?: any) => void
) {
subscription.push(new Rule(options, callback));
}
static async handleData(req, cb) {
// 把hack/hacks改成http/https
const urlObj = url.parse(req.url);
urlObj.protocol = urlObj.protocol === 'hack:' ? 'http:' : 'https:';
req.url = url.format(urlObj);
// 把header里的Origin中的hack/hacks改成http/https
if (req.referrer) {
req.referrer = req.referrer.replace('hack', 'http');
}
if (req.headers['Origin']) {
req.headers['Origin'] = req.headers['Origin'].replace('hack', 'http');
}
// 获取发起请求用session,禁止套娃
const requestSession = session.fromPartition('persist:request');
if (browserWindow) {
browserWindow.webContents.send('request-incoming');
}
// 检查该请求是否订阅
const rule = subscription.find(value => value.match(req.url, req.method));
// 创建可读取流
const readable = new stream.PassThrough();
// 同步cookies
const gameSession = session.fromPartition('persist:game');
const cookies = await gameSession.cookies.get({
url: req.url
});
cookies.forEach(cookie => {
requestSession.cookies.set({ url: req.url, ...cookie });
});
// 判断是否需要进行魔改
let ModifyFilePath = '';
if (req.url.indexOf('://assets.millennium-war.net/') !== -1) {
let modifyFileName = '';
const reqPath = url.parse(req.url).path;
let requestFileName = FileList[reqPath];
if (reqPath.indexOf(mainFontPath) !== -1) {
requestFileName = 'MainFont.aft';
}
if (requestFileName) {
switch (path.extname(requestFileName)) {
case '.atb':
modifyFileName = requestFileName.replace('.atb', '.txt');
break;
case '.aar':
modifyFileName = requestFileName.replace('.aar', '');
break;
default:
modifyFileName = requestFileName;
}
}
const protoablePath = process.env.PORTABLE_EXECUTABLE_DIR;
const userDataPath = app.getPath('userData');
const modPath = protoablePath ? protoablePath + '/mods' : path.join(userDataPath, 'mods');
if (!fs.existsSync(modPath)) {
fs.mkdirSync(modPath);
}
const modifyFilePath = path.join(modPath, modifyFileName);
if (modifyFileName !== '' && fs.existsSync(modifyFilePath)) {
log.info(requestFileName, 'modify by Server');
// AFT和PNG文件直接回传
// 同名文件直接回传
if (fs.existsSync(path.join(modPath, requestFileName))) {
const fileStream = fs.createReadStream(modifyFilePath);
cb({
statusCode: 200,
data: readable
});
fileStream.on('data', chunk => {
readable.push(chunk);
});
fileStream.on('end', () => {
readable.pause();
readable.push(null);
readable.resume();
if (browserWindow) {
browserWindow.webContents.send('response-incoming');
}
});
return;
}
// 其他文件
ModifyFilePath = modifyFilePath;
}
}
// 创建请求
const request = net.request({
method: req.method,
url: req.url,
session: requestSession
// redirect: 'manual'
});
// 允许分片
// request.chunkedEncoding = true;
// 写Header
if (req.referrer) {
request.setHeader('Referer', req.referrer);
}
Object.keys(req.headers).forEach(key => {
request.setHeader(key, req.headers[key]);
});
// 上传数据
if (req.uploadData) {
req.uploadData.forEach(v => {
if (v.bytes) {
request.write(v.bytes);
}
});
}
// 处理301 302
request.on('redirect', (statusCode, method, redirectUrl, responseHeaders) => {
if (false) {
// if (responseHeaders['content-type'] && responseHeaders['content-type'][0].indexOf('text/html') !== -1) {
cb({
statusCode: 200,
headers: responseHeaders,
data: readable
});
readable.push(`
<html>
<head>
<meta http-equiv="refresh" content="0; url=${redirectUrl}">
</head>
</html>
`);
readable.push(null);
if (browserWindow) {
browserWindow.webContents.send('response-incoming');
}
} else {
console.log('from', req.url, 'to', redirectUrl, statusCode);
cb({
statusCode: 200,
headers: responseHeaders,
data: readable
});
readable.push('fuckyou');
readable.push(null);
}
// request.abort();
});
// 处理回复
request.on('response', response => {
const raws: Array<Buffer> = [];
let length = 0;
let time = 10;
const timeout = setTimeout(() => {
time--;
if (time === 0) {
console.log(req.url, 'Time out');
}
}, 1000);
cb({
statusCode: response.statusCode,
headers: response.headers,
data: readable
});
response.on('data', chunk => {
time = 10;
if (!ModifyFilePath) {
readable.push(chunk);
}
if (rule || ModifyFilePath) {
raws.push(chunk);
}
length += chunk.byteLength;
});
response.on('end', () => {
clearTimeout(timeout);
const raw = raws.length !== 0 ? Buffer.concat(raws) : null;
if (!ModifyFilePath) {
// 直接回传
readable.pause();
readable.push(null);
readable.resume();
if (browserWindow) {
browserWindow.webContents.send('response-incoming');
}
} else {
// 魔改文件热封装
const result = parseAL(raw);
const packaged = result.Package(ModifyFilePath);
readable.push(packaged);
readable.pause();
readable.push(null);
readable.resume();
if (browserWindow) {
browserWindow.webContents.send('response-incoming');
}
}
if (rule) {
const _res = raw || Buffer.concat(raws);
const _req = req.uploadData ? req.uploadData[0].bytes : null;
rule.Callback(req.url, _res, _req);
}
});
response.on('error', err => {
clearTimeout(timeout);
readable.push(null);
if (browserWindow) {
browserWindow.webContents.send('error-incoming', req.url, err);
}
log.error(req.url, err, response.statusCode);
});
});
// 处理错误
request.on('error', err => {
log.error(req.url, err);
if (browserWindow) {
browserWindow.webContents.send('error-incoming', req.url, err);
}
});
request.end();
}
}