-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
353 lines (315 loc) · 11 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
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
346
347
348
349
350
351
352
353
$(document).ready(function () {
reload_channels();
$('.btn-subscribe').click(function () {
$('.modal.subscribe .form').form('clear');
$('.modal.subscribe').modal('show');
});
$('.btn-create').click(function () {
$('.modal.create .form').form('clear');
$('.modal.create').modal('show');
});
$('.subscribe.form')
.form({
fields: {
invite: 'regExp[/^\\d+:(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/]'
},
inline: true,
onSuccess: async function(e, params) {
let [id, encodedKey] = params.invite.split(':');
let key = base64decode(encodedKey);
let channel = await view(id);
if (!channel) {
alert('Channel not found');
$('.subscribe.modal').modal('hide');
return;
}
localStorageUpdate('subscribed', [], subscribed => {
if (!subscribed.find(info => info.id === id))
subscribed.push({id, key, name: channel.name});
return subscribed;
});
location.reload();
}
})
.submit(e => e.preventDefault());
$('.subscribe.modal')
.modal({
onApprove: function () {
return $('.subscribe.form').form('validate form');
}
});
$('.create.form')
.form({
fields: {
name: ['minLength[3]', 'maxLength[20]'],
password: ['minLength[8]', 'maxLength[16]']
},
inline: true,
onSuccess: async function (e, params) {
let id = await add_channel(params.name, params.password);
if (!id) {
alert('Cannot create channel');
$('.create.modal').modal('hide');
return;
}
let key = await get_key(id, params.password);
if (!key) {
alert('Cannot receive channel key');
$('.create.modal').modal('hide');
return;
}
localStorageUpdate('maintained', [], maintained => {
maintained.push({id, key, name: params.name});
return maintained;
});
location.reload();
}
})
.submit(e => e.preventDefault());
$('.create.modal')
.modal({
onApprove: function () {
return $('.create.form').form('validate form');
}
});
$('.channels .item').click(function () {
let id = $(this).data('id');
load_posts(id);
$('.channels .item').removeClass('active');
$(this).addClass('active');
let ownerBlock = $('.owner-block');
if ($(this).parents('.channels-maintained').length) {
ownerBlock.show();
ownerBlock.data('id', id);
} else {
ownerBlock.hide();
}
});
$('.item .btn-remove').click(function () {
let id = $(this).closest('.item').data('id');
let collectionName = $(this).data('collection');
localStorageUpdate(collectionName, [], collection => collection.filter(info => info.id !== id));
location.reload();
});
$('.add-post.form')
.form({
fields: {
text: 'empty',
password: ['minLength[8]', 'maxLength[16]']
},
inline: true,
onSuccess: async function (e, values) {
let id = $(this).data('id');
let status = await add_post(id, values.password, values.text);
switch (status) {
case 201:
location.reload();
break;
case 403:
alert('Invalid password');
break;
default:
alert('Cannot add post');
}
}
})
.submit(e => e.preventDefault());
$('.btn-invite').click(function () {
let id = $(this).closest('.owner-block').data('id');
let channel_info = localStorageGet('maintained').find(info => info.id === id);
let encodedKey = base64encode(restoreArray(channel_info.key));
$('.invite-text').text(`${channel_info.id}:${encodedKey}`);
$('.modal.invite').modal('show');
});
$('.change-password.form')
.form({
fields: {
password: ['minLength[8]', 'maxLength[16]'],
new_password: ['minLength[8]', 'maxLength[16]']
},
inline: true,
onSuccess: async function (e, values) {
let id = $(this).data('id');
let status = await change_password(id, values.password, values.new_password);
switch (status) {
case 200:
alert('Password successfully changed');
location.reload();
break;
case 403:
alert('Invalid password');
break;
default:
alert('Password changing failed');
}
if (status !== 200) {
$('.modal.change-password').modal('hide');
}
}
})
.submit(e => e.preventDefault());
$('.change-password.modal')
.modal({
onApprove: function () {
return $('.change-password.form').form('validate form');
}
});
$('.btn-changePassword').click(function () {
let id = $(this).closest('.owner-block').data('id');
$('.change-password.form').data('id', id);
$('.modal.change-password .form').form('clear');
$('.modal.change-password').modal('show');
});
});
function append_channels(container, channels) {
for (let channel of channels) {
let item = $('<a class="item"></a>');
container.append(item);
$(item).text(channel.name);
$(item).append('<i class="icon link trash alternate outline btn-remove"></i>');
$(item).data('id', channel.id);
}
}
function reloadCollection(name) {
let collection = localStorageGet(name) || [];
let container = $(`.channels-${name} .channels-list`);
append_channels(container, collection);
container.find('.btn-remove').data('collection', name);
}
function reload_channels() {
reloadCollection('subscribed');
reloadCollection('maintained');
}
async function load_posts(channel_id) {
let container = $('.posts-list');
container.empty();
let channel_infos = localStorageGet('subscribed') || [];
channel_infos = channel_infos.concat(localStorageGet('maintained') || []);
let channel_info = channel_infos.find(info => info.id === channel_id);
if (!channel_info)
return;
let channel = await view(channel_id);
channel.decrypt(restoreArray(channel_info.key));
for (let post of channel.posts) {
let item = $('<div class="ui segment"><pre></pre></div>');
container.append(item);
$(item).children('pre').text(post);
}
$('.divider').css('visibility', channel.posts.length ? 'visible' : 'hidden');
}
function add_channel(name, password) {
return fetch("/api/add_channel", postOptions({name, password}))
.then(response => response.status === 201 ? response.text() : null)
.then(text => text.split(':')[1])
.catch(e => {
console.error(e);
return false;
});
}
function add_post(channel_id, password, text) {
return fetch(`/api/add_post?channel_id=${channel_id}`, postOptions({password, text}))
.then(response => response.status)
.catch(e => {
console.error(e);
return false;
});
}
function get_key(channel_id, password) {
return fetch(`/api/key?channel_id=${channel_id}`, postOptions({password}))
.then(response => response.status === 200 ? response.arrayBuffer() : null)
.then(buffer => new Uint8Array(buffer))
.catch(e => {
console.error(e);
return false;
});
}
function change_password(channel_id, password, new_password) {
return fetch(`/api/change_password?channel_id=${channel_id}`, postOptions({password, new_password}))
.then(response => response.status)
.catch(e => {
console.error(e);
return false;
});
}
function view(channel_id) {
return fetch(`/api/view?channel_id=${channel_id}`)
.then(response => response.status === 200 ? response.arrayBuffer() : null)
.then(buffer => new Channel(buffer))
.catch(e => {
console.error(e);
return false;
});
}
class Channel {
constructor(buffer) {
this._buffer = buffer;
this._dataview = new DataView(buffer);
this._position = 0;
this.name = this._read_str();
this.posts = [];
while (this._position < buffer.byteLength) {
this.posts.push(this._read_buf());
}
}
decrypt(key) {
this.posts = this.posts.map(post => this._decrypt_post(post, key));
}
_decrypt_post(post, key) {
let resultBytes = [];
for (let i = 0; i < post.length; i++) {
resultBytes[i] = post[i] ^ key[i % key.length];
}
return this._buf_to_str(new Uint8Array(resultBytes));
}
_read_long() {
let result = this._dataview.getUint32(this._position, true);
this._position += 8;
return result;
}
_read_buf() {
let size = this._read_long();
let result = new Uint8Array(this._buffer, this._position, size);
this._position += size;
return result;
}
_read_str() {
return this._buf_to_str(this._read_buf());
}
_buf_to_str(buf) {
return new TextDecoder("utf-8").decode(buf);
}
}
function querystring(obj) {
return Object.keys(obj).map(key => `${key}=${encodeURIComponent(obj[key])}`).join('&');
}
function postOptions(bodyData) {
return {
method: "POST",
body: querystring(bodyData),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
}
function base64decode(base64) {
let raw = atob(base64);
let rawLength = raw.length;
let array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
function base64encode(array) {
return btoa(String.fromCharCode(...array));
}
function restoreArray(obj) {
return new Uint8Array(Object.assign([], obj));
}
function localStorageUpdate(key, default_value, updater) {
let current = JSON.parse(localStorage.getItem(key)) || default_value;
localStorage.setItem(key, JSON.stringify(updater(current)));
}
function localStorageGet(key) {
return JSON.parse(localStorage.getItem(key) || 'null');
}