This repository has been archived by the owner on Dec 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyPublicIpChecker.ts
97 lines (73 loc) · 2.47 KB
/
MyPublicIpChecker.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
import * as https from "https";
import * as Immutable from "immutable";
import { ClientRequest, IncomingMessage } from "http";
const NO_CHANGE = "__nochange__";
export const createMyPublicIpChecker: (key: string, initalIp: string) => MyPublicIpChecker =
(key, initalIp): MyPublicIpChecker => {
switch (key) {
case "ipinfo.io":
return new IpInfoIoChecker(initalIp);
case "whatismypublicip.com":
return new WhatIsMyPublicIpCom(initalIp);
}
};
export abstract class MyPublicIpChecker {
private lastIp: string;
constructor(initialIp: string) {
this.lastIp = initialIp;
}
public abstract getRequestOptions(): https.RequestOptions;
public abstract parseOutput(output: string): string;
public check(): Promise<string> {
return new Promise((resolve, reject) => {
const request = https.request(this.getRequestOptions(), response => {
let output: string = "";
response.on("data", chunk => {
output += chunk;
}).on("end", () => {
const currentIp = this.parseOutput(output);
if (currentIp === this.lastIp) {
resolve(NO_CHANGE);
} else {
this.lastIp = currentIp;
resolve(currentIp);
}
});
})
.on("error", error => {
reject(error);
});
request.setTimeout(1000);
request.end();
});
}
public static isNewIp(maybeNewIp: string): boolean {
return maybeNewIp !== NO_CHANGE;
}
}
class IpInfoIoChecker extends MyPublicIpChecker {
public getRequestOptions(): https.RequestOptions {
return {
protocol: "https:",
host: "ipinfo.io",
path: "/ip",
method: "GET"
};
}
public parseOutput(output: string): string {
return output.trim();
}
}
class WhatIsMyPublicIpCom extends MyPublicIpChecker {
public getRequestOptions(): https.RequestOptions {
return {
protocol: "https:",
host: "whatismypublicip.com",
method: "GET"
};
}
public parseOutput(output: string): string {
const re = /<div id="up_finished">(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*<\/div>/;
return output.replace(re, "$1");
}
}