-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.js
75 lines (66 loc) · 1.96 KB
/
proxy.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
var urlParse = require("url").parse,
platform = require("./platform.js"),
observers = [],
path = require("path"),
pacScriptPath = null,
config = {};
function reset() {
config = urlParse("");
config.username = "";
config.password = "";
observers.forEach((fn)=>{fn(config);});
}
module.exports = {
setSaveDir(saveDir) {
pacScriptPath = path.join(saveDir, "proxy-pac.js");
},
setEndpoint(configObj) {
if (!configObj) {return reset();}
// Recover from a bug that saved invalid configuration
if (configObj === "http:///:null") {
configObj = "";
}
if (typeof configObj === "string") {
configObj = urlParse(configObj);
}
if (configObj.username) {
configObj.auth = `${configObj.username}`;
if (configObj.password) {
configObj.auth += `:${configObj.password}`;
}
} else {
if (configObj.auth) {
let [user, ...pass] = configObj.auth.split(":");
configObj.username = user;
configObj.password = pass.join(":");
}
}
if (!configObj.href) {
let authString = configObj.auth,
port = configObj.port;
if (authString) {authString += "@"}
if (port) {port = ":" + port}
configObj.href = `http://${authString || ""}${configObj.hostname || ""}${port || ""}`
}
log.debug("proxy config: " + JSON.stringify(configObj));
config = Object.assign({}, configObj);
module.exports.setPac(config);
observers.forEach((fn)=>{fn(config);});
},
observe(cb) {
observers.push(cb);
},
pacScriptURL() {
return "file://" + pacScriptPath;
},
configuration() {
return config;
},
setPac(configuration) {
let templatePath = path.join(__dirname, "proxy-pac-template.js"),
pacTemplate = platform.readTextFileSync(templatePath, {inASAR: true}),
pacText = pacTemplate.replace("HOSTNAME", configuration.hostname)
.replace("PORT", configuration.port);
platform.writeTextFileSync(pacScriptPath, pacText);
}
};