-
Notifications
You must be signed in to change notification settings - Fork 20
/
rswebui.js
345 lines (308 loc) · 8.6 KB
/
rswebui.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
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
const m = require('mithril');
const RsEventsType = {
NONE: 0, // Used internally to detect invalid event type passed
// @see RsBroadcastDiscovery
BROADCAST_DISCOVERY: 1,
// @see RsDiscPendingPgpReceivedEvent
GOSSIP_DISCOVERY: 2,
// @see AuthSSL
AUTHSSL_CONNECTION_AUTENTICATION: 3,
// @see pqissl
PEER_CONNECTION: 4,
// @see RsGxsChanges, used also in @see RsGxsBroadcast
GXS_CHANGES: 5,
// Emitted when a peer state changes, @see RsPeers
PEER_STATE_CHANGED: 6,
// @see RsMailStatusEvent
MAIL_STATUS: 7,
// @see RsGxsCircleEvent
GXS_CIRCLES: 8,
// @see RsGxsChannelEvent
GXS_CHANNELS: 9,
// @see RsGxsForumEvent
GXS_FORUMS: 10,
// @see RsGxsPostedEvent
GXS_POSTED: 11,
// @see RsGxsPostedEvent
GXS_IDENTITY: 12,
// @see RsFiles @deprecated
SHARED_DIRECTORIES: 13,
// @see RsFiles
FILE_TRANSFER: 14,
// @see RsMsgs
CHAT_MESSAGE: 15,
// @see rspeers.h
NETWORK: 16,
// @see RsMailTagEvent
MAIL_TAG: 17,
/** Emitted to update library clients about file hashing being completed */
FILE_HASHING_COMPLETED: 20,
// @see rspeers.h
TOR_MANAGER: 21,
// @see rsfriendserver.h
FRIEND_SERVER: 22,
// _MAX //used internally, keep last
};
const API_URL = 'http://127.0.0.1:9092';
const loginKey = {
username: '',
passwd: '',
isVerified: false,
url: API_URL,
};
// Make this as object property?
function setKeys(username, password, url = API_URL, verified = true) {
loginKey.username = username;
loginKey.passwd = password;
loginKey.url = url;
loginKey.isVerified = verified;
}
function rsJsonApiRequest(
path,
data = {},
callback = () => {},
async = true,
headers = {},
handleDeserialize = JSON.parse,
handleSerialize = JSON.stringify,
config = null
) {
headers['Accept'] = 'application/json';
if (loginKey.isVerified) {
headers['Authorization'] = 'Basic ' + btoa(loginKey.username + ':' + loginKey.passwd);
}
// NOTE: After upgrading to mithrilv2, options.extract is no longer required
// since the status will become part of return value and then
// handleDeserialize can also be simply passed as options.deserialize
return m
.request({
method: 'POST',
url: loginKey.url + path,
async,
extract: (xhr) => {
// Empty string is not valid json and fails on parse
const response = xhr.responseText || '""';
return {
status: xhr.status,
statusText: xhr.statusText,
body: handleDeserialize(response),
};
},
serialize: handleSerialize,
headers,
body: data,
config,
})
.then((result) => {
if (result.status === 200) {
callback(result.body, true);
} else {
loginKey.isVerified = false;
callback(result, false);
m.route.set('/');
}
return result;
})
.catch(function (e) {
callback(e, false);
console.error('Error: While sending request for path:', path, '\ninfo:', e);
m.route.set('/');
});
}
function setBackgroundTask(task, interval, taskInScope) {
// Always use bound(.bind) function when accsssing outside objects
// to avoid loss of scope
task();
let taskId = setTimeout(function caller() {
if (taskInScope()) {
task();
taskId = setTimeout(caller, interval);
} else {
clearTimeout(taskId);
}
}, interval);
return taskId;
}
function computeIfMissing(map, key, missing = () => ({})) {
if (!Object.prototype.hasOwnProperty.call(map, key)) {
map[key] = missing();
}
return map[key];
}
function deeperIfExist(map, key, action) {
if (Object.prototype.hasOwnProperty.call(map, key)) {
action(map[key]);
return true;
} else {
return false;
}
}
const eventQueue = {
events: {
[RsEventsType.CHAT_MESSAGE]: {
// Chat-Messages
types: {
// #define RS_CHAT_TYPE_PUBLIC 1
// #define RS_CHAT_TYPE_PRIVATE 2
2: (chatId) => chatId.distant_chat_id, // distant chat (initiate? -> todo accept)
// #define RS_CHAT_TYPE_LOBBY 3
3: (chatId) => chatId.lobby_id.xstr64, // lobby_id
// #define RS_CHAT_TYPE_DISTANT 4
},
messages: {},
chatMessages: (chatId, owner, action) => {
if (
!deeperIfExist(owner.types, chatId.type, (keyfn) =>
action(
computeIfMissing(
computeIfMissing(owner.messages, chatId.type),
keyfn(chatId),
() => []
)
)
)
) {
console.info('unknown chat event', chatId);
}
},
handler: (event, owner) =>
owner.chatMessages(event.mChatMessage.chat_id, owner, (r) => {
console.info('adding chat', r, event.mChatMessage);
r.push(event.mChatMessage);
owner.notify(event.mChatMessage);
}),
notify: () => {},
},
[RsEventsType.GXS_CIRCLES]: {
// Circles (ignore in the meantime)
handler: (event, owner) => {},
},
},
handler: (event) => {
if (!deeperIfExist(eventQueue.events, event.mType, (owner) => owner.handler(event, owner))) {
console.info('unhandled event', event);
}
},
};
const userList = {
users: [],
userMap: {},
loadUsers: () => {
rsJsonApiRequest('/rsIdentity/getIdentitiesSummaries', {}, (list) => {
if (list !== undefined) {
console.info('loading ' + list.ids.length + ' users ...');
userList.users = list.ids;
userList.userMap = list.ids.reduce((a, c) => {
a[c.mGroupId] = c.mGroupName;
return a;
}, {});
}
});
},
username: (id) => {
return userList.userMap[id] || id;
},
};
/*
path,
data = {},
callback = () => {},
async = true,
headers = {},
handleDeserialize = JSON.parse,
handleSerialize = JSON.stringify
config
*/
function startEventQueue(
info,
loginHeader = {},
displayAuthError = () => {},
displayErrorMessage = () => {},
successful = () => {}
) {
return rsJsonApiRequest(
'/rsEvents/registerEventsHandler',
{},
(data, success) => {
if (success) {
// unused
} else if (data.status === 401) {
displayAuthError('Incorrect login/password.');
} else if (data.status === 0) {
displayErrorMessage([
'Retroshare-jsonapi not available.',
m('br'),
'Please fix host and/or port.',
]);
} else {
displayErrorMessage('Login failed: HTTP ' + data.status + ' ' + data.statusText);
}
},
true,
loginHeader,
JSON.parse,
JSON.stringify,
(xhr, args, url) => {
let lastIndex = 0;
xhr.onprogress = (ev) => {
const currIndex = xhr.responseText.length;
if (currIndex > lastIndex) {
const parts = xhr.responseText.substring(lastIndex, currIndex);
lastIndex = currIndex;
parts
.trim()
.split('\n\n')
.filter((e) => e.startsWith('data: {'))
.map((e) => e.substr(6))
.map(JSON.parse)
.forEach((data) => {
if (Object.prototype.hasOwnProperty.call(data, 'retval')) {
console.info(
info + ' [' + data.retval.errorCategory + '] ' + data.retval.errorMessage
);
data.retval.errorNumber === 0
? successful()
: displayErrorMessage(
`${info} failed: [${data.retval.errorCategory}] ${data.retval.errorMessage}`
);
} else if (Object.prototype.hasOwnProperty.call(data, 'event')) {
data.event.queueSize = currIndex;
eventQueue.handler(data.event);
}
});
if (currIndex > 1e5) {
// max 100 kB eventQueue
startEventQueue('restart queue');
xhr.abort();
}
}
};
return xhr;
}
);
}
function logon(loginHeader, displayAuthError, displayErrorMessage, successful) {
startEventQueue('login', loginHeader, displayAuthError, displayErrorMessage, () => {
successful();
userList.loadUsers();
});
}
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
module.exports = {
rsJsonApiRequest,
setKeys,
setBackgroundTask,
logon,
events: eventQueue.events,
RsEventsType,
userList,
loginKey,
formatBytes,
};