-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
223 lines (193 loc) · 6.88 KB
/
index.js
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
'use strict';
const fs = require('fs');
const path = require('path');
const birdAuth = require('bird-auth');
const httpProxy = require('./libs/proxy');
const CONSOLE_COLOR_BLUE = '\x1b[34m%s\x1b[0m';
const CONSOLE_COLOR_YELLOW = '\x1b[33m%s\x1b[0m';
const Uuaper = function (params) {
if (!params) throw new Error('Where you params?');
const {service, cache, target, debug, headers, mock, auth, server, limit} = params;
if (service) {
throw new Error('Uuaper 2.x version is not support 1.x settings, you can `npm install uuaper@1.3.4 --save`.');
}
if (auth && auth.server && /\/login?/.test(auth.server)) {
throw new Error('After 3.4.0 version, [auth.server] configuration needs to use "authorize" instead of "login".');
}
if (cache && typeof cache !== 'string') {
throw new Error('the cache setting must be a path string.');
}
this._options = {
target,
debug: debug || false,
headers: headers || {},
mock,
cache,
auth,
server,
limit
};
if (auth) {
this.onlyProxy = false;
if (debug) {
console.log(CONSOLE_COLOR_BLUE, '===== Auto Get Cookies Mode =====\n');
}
this.getCookie();
} else {
this.onlyProxy = true;
}
const self = this;
if (server) {
const express = require('express');
const app = this.app = express();
app.use(function (req, res, next) {
const exec_start_at = Date.now();
const _send = res.send;
res.send = function () {
res.set('X-Execution-Time', String(Date.now() - exec_start_at));
return _send.apply(res, arguments);
};
next();
});
server.proxyPath.forEach(item => {
app.use(item, function (req, res) {
self.proxyData(req, res);
});
});
app.use(express.static(server.staticPath || __dirname));
app.listen(server.port || 1337, function () {
console.log('Server listening on http://localhost:' + server.port + ', Ctrl + C to stop')
});
return this;
} else {
return function (req, res, next) {
self._options.mock ? self.mockData(req, res, next) : self.proxyData(req, res, next);
}
}
};
Uuaper.client = birdAuth.client;
function dealCookie(options, cookie, cb) {
Uuaper.client.clear_cookies();
Uuaper.client.set_cookies(cookie);
if (options.auth.forwardCookie) {
options.auth.forwardCookie(function (newCookie) {
if (!newCookie) {
throw new Error('where you new auth cookies ?');
}
if (options.debug) {
console.log(CONSOLE_COLOR_YELLOW, 'New Cookie: =======> ', newCookie);
}
cb && cb();
});
} else {
if (options.debug) {
console.log(CONSOLE_COLOR_YELLOW, 'Cookie: =======> ', cookie);
}
cb && cb();
}
}
Uuaper.prototype.getCookie = function (cb) {
const self = this;
if (self._options.auth.getAuth) {
self._options.auth.getAuth(function (cookie) {
if (!cookie) {
throw new Error('where you auth cookies ?');
}
dealCookie(self._options, cookie, cb);
});
} else {
new birdAuth[self._options.auth.authType || 'uuap'](self._options.auth, function (cookie) {
dealCookie(self._options, cookie, cb);
});
}
};
Uuaper.prototype.retry = function (req, res, body) {
const self = this;
this.getCookie(function () {
const options = self._options;
if (!res.headersSent) {
req.headers.cookie = Uuaper.client.get_cookies_string();
}
httpProxy(options.target, {
forwardPath: function (req) {
return req.originalUrl;
},
defaultBody: body
})(req, res, function (e) {
console.log(e);
});
})
};
Uuaper.prototype.proxyData = function (req, res, next) {
const self = this;
const {debug, target, headers, limit, onlyProxy, auth, cache} = self._options;
const tmp = req.originalUrl.match(/\?/i) ? req.originalUrl.match(/(.+)\?{1}/i)[1] : req.originalUrl;
if (debug) {
console.log(CONSOLE_COLOR_YELLOW, req.originalUrl + ' > ' + target + req.originalUrl);
}
req.headers.cookie = Uuaper.client.get_cookies_string() || '';
if (headers) {
for (let item in headers) {
req.headers[item] = headers[item];
}
}
httpProxy(target, {
limit: limit || '10mb',
headers,
forwardPath: function (req) {
return req.originalUrl;
},
intercept: function (resp, data, req, res, body, callback) {
if (!onlyProxy) {
if (auth && auth.retry && auth.retry(resp, data && data.toString())) {
self.retry(req, res, body);
return;
}
const pattern = /(text\/html|application\/json)/g;
if (resp.headers['content-type'] && resp.headers['content-type'].match(pattern)) {
const localData = data.toString();
if (!localData) {
auth && self.retry(req, res, body);
return;
}
if (cache && resp.headers['content-type'].match(/json/g)) {
const filePath = path.join(cache, `${tmp}.json`);
if (!fs.existsSync(filePath)) {
const dirPath = path.dirname(filePath);
fs.mkdirSync(dirPath, {recursive: true});
fs.writeFile(filePath, localData, error => {
if (error) {
console.error(error);
return;
}
});
}
}
}
}
if (resp.headers['set-cookie']) {
Uuaper.client.update_cookies(resp.headers['set-cookie']);
}
callback(null, data);
}
})(req, res, next);
};
Uuaper.prototype.mockData = function (req, res, next) {
const {cache, debug} = this._options;
const tmp = req.originalUrl.match(/\?/i)
? req.originalUrl.match(/(.+)\?{1}/i)[1]
: req.originalUrl;
const filePath = path.join(cache, `${tmp}.json`);
if (fs.existsSync(filePath)) {
fs.readFile(filePath, 'utf-8', function (err, data) {
if (debug) {
console.log(CONSOLE_COLOR_BLUE, tmp + ' > ' + filePath);
}
res.set('X-Uuaper-Type', 'mock');
res.send(data);
});
} else {
this.proxyData(req, res, next);
}
};
module.exports = Uuaper;