-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtincwebui.ts
executable file
·261 lines (225 loc) · 6.59 KB
/
tincwebui.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
export class TincWebUIError extends Error {
public readonly code: number;
public readonly details: any;
constructor(message: string, code: number, details: any) {
super(code + ': ' + message);
this.code = code;
this.details = details;
}
}
export interface Endpoint {
host: string
port: number
kind: EndpointKind
}
export interface Config {
binding: string
}
export enum EndpointKind {
Local = "local",
Public = "public",
}
// support stuff
interface rpcExecutor {
call(id: number, payload: string): Promise<object>;
}
class wsExecutor {
private socket?: WebSocket;
private connecting = false;
private readonly pendingConnection: Array<() => (void)> = [];
private readonly correlation = new Map<number, [(data: object) => void, (err: object) => void]>();
constructor(private readonly url: string) {
}
async call(id: number, payload: string): Promise<object> {
const conn = await this.connectIfNeeded();
if (this.correlation.has(id)) {
throw new Error(`already exists pending request with id ${id}`);
}
let future = new Promise<object>((resolve, reject) => {
this.correlation.set(id, [resolve, reject]);
});
conn.send(payload);
return (await future);
}
private async connectIfNeeded(): Promise<WebSocket> {
while (this.connecting) {
await new Promise((resolve => {
this.pendingConnection.push(resolve);
}))
}
if (this.socket) {
return this.socket;
}
this.connecting = true;
let socket;
try {
socket = await this.connect();
} finally {
this.connecting = false;
}
socket.onerror = () => {
this.onConnectionFailed();
}
socket.onclose = () => {
this.onConnectionFailed();
}
socket.onmessage = ({data}) => {
let res;
try {
res = JSON.parse(data);
} catch (e) {
console.error("failed parse request:", e);
}
const task = this.correlation.get(res.id);
if (task) {
this.correlation.delete(res.id);
task[0](res);
}
}
this.socket = socket;
let cp = this.pendingConnection;
this.pendingConnection.slice(0, 0);
cp.forEach((f) => f());
return this.socket;
}
private connect(): Promise<WebSocket> {
return new Promise<WebSocket>(((resolve, reject) => {
let socket = new WebSocket(this.url);
let resolved = false;
socket.onopen = () => {
resolved = true;
resolve(socket);
}
socket.onerror = (e) => {
if (!resolved) {
reject(e);
resolved = true;
}
}
socket.onclose = (e) => {
if (!resolved) {
reject(e);
resolved = true;
}
}
}));
}
private onConnectionFailed() {
let sock = this.socket;
this.socket = undefined;
if (sock) {
sock.close();
}
const cp = Array.from(this.correlation.values());
this.correlation.clear();
const err = new Error('connection closed');
cp.forEach((([_, reject]) => {
reject(err);
}))
}
}
class postExecutor {
constructor(private readonly url: string) {
}
async call(id: number, payload: string): Promise<object> {
const fetchParams = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: payload
};
const res = await fetch(this.url, fetchParams);
if (!res.ok) {
throw new Error(res.status + ' ' + res.statusText);
}
return await res.json();
}
}
/**
Operations with tinc-web-boot related to UI
**/
export class TincWebUI {
private __id: number;
private __executor:rpcExecutor;
// Create new API handler to TincWebUI.
constructor(base_url : string = 'ws://127.0.0.1:8686/api/') {
const proto = (new URL(base_url)).protocol;
switch (proto) {
case "ws:":
case "wss:":{
this.__executor=new wsExecutor(base_url);
break
}
case "http:":
case "https:":
default:{
this.__executor = new postExecutor(base_url);
break
}
}
this.__id = 1;
}
/**
Issue and sign token
**/
async issueAccessToken(validDays: number): Promise<string> {
return (await this.__call({
"jsonrpc" : "2.0",
"method" : "TincWebUI.IssueAccessToken",
"id" : this.__next_id(),
"params" : [validDays]
})) as string;
}
/**
Make desktop notification if system supports it
**/
async notify(title: string, message: string): Promise<boolean> {
return (await this.__call({
"jsonrpc" : "2.0",
"method" : "TincWebUI.Notify",
"id" : this.__next_id(),
"params" : [title, message]
})) as boolean;
}
/**
Endpoints list to access web UI
**/
async endpoints(): Promise<Array<Endpoint>> {
return (await this.__call({
"jsonrpc" : "2.0",
"method" : "TincWebUI.Endpoints",
"id" : this.__next_id(),
"params" : []
})) as Array<Endpoint>;
}
/**
Configuration defined for the instance
**/
async configuration(): Promise<Config> {
return (await this.__call({
"jsonrpc" : "2.0",
"method" : "TincWebUI.Configuration",
"id" : this.__next_id(),
"params" : []
})) as Config;
}
private __next_id() {
this.__id += 1;
return this.__id
}
private async __call(req: { id: number, jsonrpc: string, method: string, params: object | Array<any> }): Promise<any> {
const data = await this.__executor.call(req.id, JSON.stringify(req)) as {
error?: {
message: string,
code: number,
data?: any
},
result?:any
}
if (data.error) {
throw new TincWebUIError(data.error.message, data.error.code, data.error.data);
}
return data.result;
}
}