This repository has been archived by the owner on Oct 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
messages.js
executable file
·5416 lines (4093 loc) · 173 KB
/
messages.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
window.$ = window.jQuery = require('jquery');
const copy = require( 'copy-to-clipboard' );
const notifier = require('node-notifier');
const { openAlias } = require('openalias');
const { desktopCapturer, shell } = require('electron');
const contextMenu = require('electron-context-menu');
const path = require('path');
const emojione = require('emojione');
const complementaryColors = require('complementary-colors');
const {
Address,
AddressPrefix,
Block,
BlockTemplate,
Crypto,
CryptoNote,
LevinPacket,
Transaction
} = require('kryptokrona-utils');
const xkrUtils = new CryptoNote()
const crypto = new Crypto()
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
var sdp_parser = require('./sdp');
const welcome_message = require('./welcome_message');
let current_board = '';
const Datastore = require('nedb');
var en = require('int-encoder');
var WebTorrent = require('webtorrent');
function containsOnlyEmojis(text) {
const onlyEmojis = text.replace(new RegExp('[\u0000-\u1eeff]', 'g'), '')
const visibleChars = text.replace(new RegExp('[\n\r\s]+|( )+', 'g'), '')
return onlyEmojis.length === visibleChars.length
}
var Peer = require('simple-peer')
let listener = () => {}
let endCall = (peer, stream, contact_address) => {
peer.destroy();
stream.getTracks().forEach(function(track) {
track.stop();
});
active_calls[contact_address] = "";
var myvideo = document.getElementById('myvideo');
try {
$('.video-grid .' + contact_address).remove();
} catch (err) {
}
if (!$('.video-grid video').length) {
$('.video-grid').hide();
myvideo.srcObject = stream;
myvideo.pause();
myvideo.srcObject = null;
$('#myvideo').hide();
}
$('otherid').empty();
// $('#caller_menu').css('top','-65px');
// $('#messages_contacts').removeClass('in-call');
// $('#settings').removeClass('in-call');
$('#otherid').unbind('change');
awaiting_callback = false;
$('.' + contact_address).removeClass("rgb").removeClass('online').removeClass("in-call-contact").find('.fa').remove();
$('.' + contact_address + " .lds-ellipsis").remove();
//
//
// $('#video-button').unbind('click').click(function() { startCall(true, true) });
//
// $('#call-button').unbind('click').click(function() { startCall(true, false) });
//
// $('#screen-button').unbind('click').click(function() { startCall(true, true, true) });
}
const {ipcRenderer} = require('electron');
let reply_to_board_message = (hash) => {
current_reply_to = hash;
$('.board_message').removeClass('reply-border-rgb');
$('#boards_message_form').addClass('reply-border-rgb');
$('#boards_message_form').focus();
let nickname = false;
try {
nickname = $('#boards .' + hash + ' .boards_nickname').text();
} catch (err) {
}
let replyto;
if (nickname) {
replyto = nickname;
} else {
replyto = "anonymous"
}
$('#replyto').text('Replying to ' + replyto).fadeIn();
$('#replyto_exit').fadeIn();
let amount = parseInt($('#replyto').width()) + 70;
}
$('#board-menu .trending').click(function() {
print_trending('#');
});
let trendingTags = {};
let print_trending = (tag) => {
trendingTags = {};
let board_title = 'Trending';
let this_board = 'Trends';
$('.current').removeClass('current');
$('#board_title').text(tag);
$('#replyto_exit').click();
if (tag == '#') {
$('#boards_messages .default').fadeIn();
$('#board_title').text('Trending');
$('#active_hugins .tag').remove();
}
board_posters = [];
$('.active_user').remove();
$('.box_header').find('h3').text('Hashtags');
$('#boards_messages').show();
$('#boards .board_message').remove();
let hashtag = new RegExp(tag);
boards_db.find({message : hashtag }).sort({ timestamp: -1 }).limit(50).exec(async function (err,docs){
for (doc in docs.reverse()) {
$('.active_user').remove();
board_posters = [];
let hash = docs[doc].hash;
let pubkey = docs[doc].sender;
let message = docs[doc].message;
let timestamp = docs[doc].timestamp;
let nickname = docs[doc].nickname;
let this_reply = docs[doc].reply;
let board = docs[doc].board;
let words = message.split(' ');
for (word in words) {
try {
if (words[word].substring(0,1) == '#') {
let thisHashtag = words[word];
if (trendingTags[thisHashtag] && tag == '#') {
trendingTags[thisHashtag] += 1;
} else if (tag == '#'){
trendingTags[thisHashtag] = 1;
}
if (doc < 50) {
await print_board_message(hash, pubkey, message, timestamp, board, nickname, this_reply, '#boards_messages');
}
}
} catch (err ){
console.log(err);
return;
}
}
}
await print_hashtags(trendingTags);
});
}
let print_board = (board) => {
$('#boards .board_message').remove();
$('#boards_messages .default').fadeIn();
reactions = {};
board_posters = [];
hugin_nicknames = {};
activeHugins = {};
$('.active_user').remove();
trendingTags = {};
$('#active_hugins .tag').remove();
$('.box_header').find('h3').text('Active users');
boards_db.find({board : board}).sort({ timestamp: -1 }).limit(100).exec(async function (err,docs){
for (doc in docs.reverse()) {
// continue;
let hash = docs[doc].hash;
let pubkey = docs[doc].sender;
let message = docs[doc].message;
let timestamp = docs[doc].timestamp;
let fetching_board = $('.current').attr('invitekey');
let nickname = docs[doc].nickname;
let this_reply = docs[doc].reply;
await print_board_message(hash, pubkey, message, timestamp, fetching_board, nickname, this_reply, '#boards_messages');
// let print_board_message = async (hash, address, message, timestamp, fetching_board, nickname=false, reply=false, selector) => {
}
print_active_hugins();
})
}
let board_posters = [];
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
let print_boards = async () => {
let boards_addresses = rmt.getGlobal('boards_addresses');
for (address in boards_addresses) {
let this_address = boards_addresses[address];
if (this_address[0] == "SEKReX27SM2jE2KGzVLvVKTniMEBe5GSuJbGPma7FDRWUhXXDTysRXy") {
continue;
}
let board_color = intToRGB(hashCode((this_address[1])));
let comp_color = new complementaryColors(rgbToHex(board_color.red, board_color.green, board_color.blue));
let first_color = comp_color.complementary();
console.log('first_color', first_color);
let color = 'rgb(' + first_color[1].r + ',' + first_color[1].g + ',' + first_color[1].b + ')';
if (this_address[0] == "SEKReSxkQgANbzXf4Hc8USCJ8tY9eN9eadYNdbqb5jUG5HEDkb2pZPijE2KGzVLvVKTniMEBe5GSuJbGPma7FDRWUhXXDVSKHWc") {
$('#boards_picker').append('<div class="board_icon rgb" id="home_board" title="Home" invitekey="0b66b223812861ad15e5310b4387f475c414cd7bda76be80be6d3a55199652fc" style=""><i class="fa fa-home"></i></div>');
$('.board_icon').click(function() {
let board_title = $(this).attr('title');
let this_board = $(this).attr('id');
if ($(this).hasClass('current')) {
return;
}
reactions = {};
board_posters = [];
$('.active_user').remove();
current_board = this_board;
$('#board_title').text('Home');
$('#boards_messages').show();
$(this).removeClass('unread_board');
$('#board_title').text(board_title);
$('.current').removeClass('current');
$(this).addClass('current');
$('#replyto_exit').click();
$('#send_payment').addClass('hidden');
print_board("0b66b223812861ad15e5310b4387f475c414cd7bda76be80be6d3a55199652fc");
});
} else {
await dictionary.find({ original: this_address[1] }, function (err,docs){
if (!docs.length == 0) {
let translation = docs[0].translation;
$('#boards_picker').append('<div class="board_icon" inviteKey="' + this_address[1] + '" title="' + translation + '" id="' + this_address[0] + '" style="color:' + color + '; background: rgb(' + board_color.red + ',' + board_color.green + ',' + board_color.blue + ')">' + docs[0].translation.substring(0, 1) + '</div>');
} else {
$('#boards_picker').append('<div class="board_icon" inviteKey="' + this_address[1] + '" title="' + letter_from_spend_key(this_address[1]) + '" id="' + this_address[0] + '" style="color:' + color + '; background: rgb(' + board_color.red + ',' + board_color.green + ',' + board_color.blue + ')">' + letter_from_spend_key(this_address[1]).substring(0, 1) + '</div>');
}
if (this_address[1].substring(59,64) != '00000') {
$('#' + this_address[0]).append('<i class="fa fa-lock"></i>').addClass('private');
}
$('.board_icon').click(function() {
let board_title = $(this).attr('title');
let this_board = $(this).attr('id');
if ($(this).hasClass('current')) {
return;
}
reactions = {};
board_posters = [];
$('.active_user').remove();
current_board = this_board;
if (this_board == "home_board") {
this_board = 'SEKReSxkQgANbzXf4Hc8USCJ8tY9eN9eadYNdbqb5jUG5HEDkb2pZPijE2KGzVLvVKTniMEBe5GSuJbGPma7FDRWUhXXDVSKHWc';
$('#board_title').text('Home');
}
$('#boards_messages').show();
$(this).removeClass('unread_board');
$('#board_title').text(board_title);
// ipcRenderer.send('get-boards', this_board);
$('.current').removeClass('current');
$(this).addClass('current');
$('#replyto_exit').click();
$('#send_payment').addClass('hidden');
let this_invite_key = $(this).attr('invitekey');
if (this_invite_key) {
print_board(this_invite_key);
} else {
print_board("0b66b223812861ad15e5310b4387f475c414cd7bda76be80be6d3a55199652fc");
}
});
});
}
}
return;
}
let parse_sdp = (sdp) => {
let ice_ufrag = '';
let ice_pwd = '';
let fingerprint = '';
let ips = [];
let ports = [];
let ssrcs = [];
let msid = "";
let lines = sdp.sdp.split('\n')
.map(l => l.trim()); // split and remove trailing CR
lines.forEach(function(line) {
if (line.includes('a=fingerprint:') && fingerprint == '') {
let parts = line.substr(14).split(' ');
let hex = line.substr(22).split(':').map(function (h) {
return parseInt(h, 16);
});
fingerprint = btoa(String.fromCharCode.apply(String, hex));
} else if (line.includes('a=ice-ufrag:') && ice_ufrag == '') {
ice_ufrag = line.substr(12);
} else if (line.includes('a=ice-pwd:') && ice_pwd == '') {
ice_pwd = line.substr(10);
} else if (line.includes('a=candidate:')) {
let candidate = line.substr(12).split(" ");
ip = candidate[4]
port = candidate[5]
type = candidate[7]
let hexa = ip.split('.').map(function (h) {
return h.toString(16);
});
let ip_hex = btoa(String.fromCharCode.apply(String, hexa));
if (type == "srflx") {
ip_hex = "!" + ip_hex
} else {
ip_hex = "?" + ip_hex
}
if (!ips.includes(ip_hex)) {
ips = ips.concat(ip_hex)
}
let indexedport = port+ips.indexOf(ip_hex).toString();
ports = ports.concat(en.encode(parseInt(indexedport)));
} else if (line.includes('a=ssrc:')) {
let ssrc = en.encode(line.substr(7).split(" ")[0]);
if (!ssrcs.includes(ssrc)) {
ssrcs = ssrcs.concat(ssrc)
}
} else if (line.includes('a=msid-semantic:')) {
msid = line.substr(16).split(" ")[2];
}
})
return ice_ufrag + "," + ice_pwd + "," + fingerprint + "," + ips.join('&') + "," + ports.join('&') + "," + ssrcs.join('&') + "," + msid;
}
function fromHex(hex,str){
try{
str = decodeURIComponent(hex.replace(/(..)/g,'%$1'))
}
catch(e){
str = hex
// console.log('invalid hex input: ' + hex)
}
return str
}
function trimExtra (extra) {
try {
let payload = fromHex(extra.substring(66));
let payload_json = JSON.parse(payload);
return fromHex(extra.substring(66))
}catch (e) {
return fromHex(Buffer.from(extra.substring(78)).toString())
}
}
let active_calls = {};
function handleError (e) {
console.log(e)
}
let startCall = (audio, video, screenshare=false) => {
let contact_address = $('#recipient_form').val();
if (active_calls[contact_address]) {
console.log('already calling you');
} else {
active_calls[contact_address] = Date.now();
console.log('Calling', active_calls[contact_address]);
}
console.log('Starting call..');
$('#messages_pane').find('audio').remove();
$('#messages_pane').append('<audio autoplay><source src="static/startcall.mp3" type="audio/mpeg"></audio>');
$('.active_contact').removeClass('border-rgb');
// $('#video-button').unbind('click');
//
// $('#call-button').unbind('click');
//
// $('#screen-button').unbind('click');
if (!screenshare) {
// get video/voice stream
navigator.mediaDevices.getUserMedia({
video: video,
audio: audio
}).then(gotMedia).catch(() => {})
} else { desktopCapturer.getSources({ types: ['window', 'screen'] }).then(async sources => {
for (const source of sources) {
if (source.name === 'Entire Screen') {
try {
const screen_stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: source.id,
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720
}
}
});
console.log('Got stream..');
navigator.mediaDevices.getUserMedia({
video: false,
audio: true
}).then( function(stream){gotMedia(stream, screen_stream)}).catch(() => {})
} catch (e) {
handleError(e)
}
return
}
}
}) }
async function gotMedia (stream, screen_stream=false) {
if ( video ) {
var myvideo = document.getElementById('myvideo')
if (screen_stream) {
myvideo.srcObject = screen_stream;
screen_stream.addTrack(stream.getAudioTracks()[0]);
stream = screen_stream;
} else {
myvideo.srcObject = stream;
}
myvideo.play();
$('video').fadeIn();
} else {
}
let peer1 = new Peer({
initiator: true,
stream: stream,
trickle: false,
offerOptions: {offerToReceiveVideo: true, offerToReceiveAudio: true},
sdpTransform: (sdp) => {
return sdp;
// console.log('lol, lmao', sdp);
//
// let sdp_object = {'sdp': sdp};
//
// let parsed_data = `${video ? "Δ" : "Λ"}` + parse_sdp(sdp_object);
// console.log(parsed_data);
// let recovered_data = sdp_parser.expand_sdp_offer(parsed_data);
// console.log(recovered_data);
// return recovered_data.sdp;
}
})
let video_codecs = window.RTCRtpSender.getCapabilities('video');
let custom_codecs = [];
for (codec in video_codecs.codecs) {
let this_codec = video_codecs.codecs[codec];
if (this_codec.mimeType == "video/H264" && this_codec.sdpFmtpLine.substring(0,5) == "level") {
custom_codecs.push(this_codec);
}
}
let transceivers = peer1._pc.getTransceivers()
// select the desired transceiver
if (video) {
transceivers[1].setCodecPreferences(custom_codecs)
}
let first = true;
$('.' + contact_address).addClass("rgb").addClass("in-call-contact").append('<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>');
// $('#messages_contacts').addClass('in-call');
// $('#settings').addClass('in-call');
// $('#caller_menu').fadeIn().css('top','0px');
// $('#caller_menu_type').text('Calling..');
let conversation_display = await get_translation($('#recipient_form').val());
// $('#caller_menu_contact').text(conversation_display);
// let avatar_base64 = get_avatar($('#recipient_form').val());
// $('#caller_menu img').attr('src',"data:image/svg+xml;base64," + avatar_base64);
$('#caller_menu .fa-phone').clone().appendTo('.' + contact_address).click(function(){
endCall(peer1, stream, contact_address);
})
$('#caller_menu .fa-microphone').clone().appendTo('.' + contact_address).click( function() {
$(this).toggleClass('fa-microphone-slash').toggleClass('fa-microphone');
stream.getTracks().forEach(track => track.enabled = !track.enabled);
});
peer1.on('close', () => {
console.log('Connection lost..')
endCall(peer1, stream, contact_address);
$('#messages_pane').find('audio').remove();
$('#messages_pane').append('<audio autoplay><source src="static/endcall.mp3" type="audio/mpeg"></audio>');
})
peer1.on('error', () => {
console.log('Connection lost..')
endCall(peer1, stream, contact_address);
$('#messages_pane').find('audio').remove();
$('#messages_pane').append('<audio autoplay><source src="static/endcall.mp3" type="audio/mpeg"></audio>');
})
peer1.on('stream', stream => {
// got remote video stream, now let's show it in a video tag
let extra_class = "";
if (video) {
extra_class = " video"
}
$('.video-grid').append('<video class="' + contact_address + extra_class + '"></video>').show();
let video_element = document.querySelector('.'+contact_address);
if ('srcObject' in video_element) {
video_element.srcObject = stream
} else {
video_element.src = window.URL.createObjectURL(stream) // for older browsers
}
video_element.play()
})
peer1.on('connect', () => {
$('#messages_pane').append('<audio autoplay><source src="static/startcall.mp3" type="audio/mpeg"></audio>');
$('#caller_menu_type').text(`${video ? 'Video' : 'Voice'}` + ' connected');
$('.' + contact_address + ' .lds-ellipsis').fadeOut().remove();
$('.' + contact_address).addClass('online');
console.log('Connection established;')
});
peer1.on('signal', data => {
console.log('real data:', data);
let parsed_data = `${video ? "Δ" : "Λ"}` + parse_sdp(data);
console.log('parsed data:', parsed_data);
let recovered_data = sdp_parser.expand_sdp_offer(parsed_data);
console.log('recovered data:', recovered_data);
console.log('some other data:', {'type': 'offer', 'sdp':recovered_data});
// peer1._pc.setLocalDescription(recovered_data);
data = recovered_data;
if (!first) {
return
}
sendMessage(parsed_data, true);
awaiting_callback = true;
first = false;
})
$('#otherid').change(function(){
console.log('Got callback');
$('#otherid').unbind('change');
peer1.signal( JSON.parse($('#otherid').val()) );
})
}
}
let answerCall = (msg, contact_address) => {
let video = msg.substring(0,1) == 'Δ';
// $('#messages_contacts').addClass('in-call');
// $('#settings').addClass('in-call');
// get video/voice stream
navigator.mediaDevices.getUserMedia({
video: video,
audio: true
}).then(gotMedia).catch(() => {})
function gotMedia (stream) {
let extra_class = '';
if (video) {
extra_class = ' video'
var myvideo = document.getElementById('myvideo')
myvideo.srcObject = stream;
myvideo.play();
$('video').fadeIn();
}
let peer2 = new Peer({stream: stream, trickle: false})
let video_codecs = window.RTCRtpSender.getCapabilities('video');
let custom_codecs = [];
for (codec in video_codecs.codecs) {
let this_codec = video_codecs.codecs[codec];
if (this_codec.mimeType == "video/H264" && this_codec.sdpFmtpLine.substring(0,5) == "level") {
custom_codecs.push(this_codec);
}
}
let transceivers = peer2._pc.getTransceivers();
// select the desired transceiver
if (video) {
transceivers[1].setCodecPreferences(custom_codecs);
}
// $('#caller_menu .fa-phone').click(function(){
// endCall(peer2, stream);
// })
//
//
// $('#caller_menu .fa-microphone').click( function() {
// $(this).toggleClass('fa-microphone-slash').toggleClass('fa-microphone');
// stream.getTracks().forEach(track => track.enabled = !track.enabled);
// });
$('.' + contact_address).addClass("rgb").addClass("in-call-contact").append('<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>');
$('#caller_menu .fa-phone').clone().appendTo('.' + contact_address).click(function(){
endCall(peer2, stream, contact_address);
})
$('#caller_menu .fa-microphone').clone().appendTo('.' + contact_address).click( function() {
$(this).toggleClass('fa-microphone-slash').toggleClass('fa-microphone');
stream.getTracks().forEach(track => track.enabled = !track.enabled);
});
peer2.on('close', () => {
console.log('Connection lost..')
endCall(peer2, stream, contact_address);
$('#messages_pane').find('audio').remove();
$('#messages_pane').append('<audio autoplay><source src="static/endcall.mp3" type="audio/mpeg"></audio>');
})
peer2.on('error', () => {
console.log('Connection lost..')
endCall(peer2, stream, contact_address);
$('#messages_pane').find('audio').remove();
$('#messages_pane').append('<audio autoplay><source src="static/endcall.mp3" type="audio/mpeg"></audio>');
})
let first = true;
peer2.on('signal', data => {
console.log('initial data:', data);
let parsed_data = `${video ? 'δ' : 'λ'}` + parse_sdp(data);
console.log('parsed data really cool sheet:', parsed_data);
let recovered_data = sdp_parser.expand_sdp_answer(parsed_data);
data = recovered_data;
console.log('recovered data:', recovered_data);
// peer2._pc.setLocalDescription(recovered_data);
if (!first) {
return
}
console.log('Sending answer ', parsed_data);
sendMessage(parsed_data, true);
first = false;
})
let signal = sdp_parser.expand_sdp_offer(msg);
peer2.signal(sdp_parser.expand_sdp_offer(msg));
peer2.on('track', (track, stream) => {
$('#caller_menu_type').text('Setting up link..');
})
peer2.on('connect', () => {
$('#messages_pane').find('audio').remove();
$('#messages_pane').append('<audio autoplay><source src="static/startcall.mp3" type="audio/mpeg"></audio>');
$('#caller_menu_type').text(`${video ? 'Video' : 'Voice'}` + ' connected');
$('.' + contact_address + ' .lds-ellipsis').fadeOut().remove();
$('.' + contact_address).addClass('online');
console.log('Connection established;')
});
peer2.on('stream', stream => {
// got remote video stream, now let's show it in a video tag
console.log('x-class:', extra_class);
$('.video-grid').append('<video class="' + contact_address + extra_class + '"></video>').show();
let video = document.querySelector('.video-grid .'+contact_address);
if ('srcObject' in video) {
video.srcObject = stream
} else {
video.src = window.URL.createObjectURL(stream) // for older browsers
}
video.play();
$('#caller_menu_type').text('Setting up link..');
})
}
}
let parseCall = (msg, sender=false, emitCall=true) => {
switch (msg.substring(0,1)) {
case "Δ":
// Fall through
case "Λ":
// Call offer
if (emitCall) {
// Start ringing sequence
$('#incomingCall').append('<audio autoplay><source src="static/ringtone.mp3" type="audio/mpeg"></audio>');
$('#incomingCall').find('h1').text(`Incoming ${msg.substring(0,1) == "Δ" ? "video" : "audio"} call!`);
$('#incomingCall').show();
let avatar_base64 = get_big_avatar(sender);
$('#incomingCall img').attr('src',"data:image/svg+xml;base64," + avatar_base64);
dictionary.find({ original: sender }, function (err,docs){
if (docs.length == 0) {
$('#incomingCall span').text(sender);
} else {
$('#incomingCall span').text(docs[0].translation);
}
});
// Handle answer/decline
$('#answerCall').unbind('click').click(async function() {
$('#answerCall').unbind('click');
$('#boards').addClass('hidden');
$('#messages_page').removeClass('hidden');
$('.active_contact').removeClass('border-rgb');
$('#new_board').addClass('hidden');
$('#boards_picker').addClass('hidden');
if ($('#recipient_form').text() != sender) {
print_conversation(sender);
$('#currentchat_footer').show();
}
answerCall(msg, sender);
// $('#messages_contacts').addClass('in-call');
// $('#settings').addClass('in-call');
// $('#caller_menu').fadeIn().css('top','0px');
$('#caller_menu_type').text('Connecting..');
let conversation_display = await get_translation($('#recipient_form').val());
$('#caller_menu_contact').text(conversation_display);
$('#incomingCall img').attr('src',"data:image/svg+xml;base64," + avatar_base64);
$('#incomingCall').hide();
$('#incomingCall audio').remove();
})
$('#declineCall').click(function() {
$('#incomingCall').hide();
$('#incomingCall audio').remove();
})
}
return `${msg.substring(0,1) == "Δ" ? "Video" : "Audio"} call started`;
break;
case "δ":
// Fall through
case "λ":
// Answer
if (emitCall) {
$('#otherid').val(JSON.stringify(sdp_parser.expand_sdp_answer(msg)));
$('#otherid').change();
}
return "";
break;
default:
return msg;
}
}
$('#video-button').click(function() { startCall(true, true)});
$('#call-button').click(function() { startCall(true, false)});
$('#screen-button').click(function() { startCall(true, true, true)});
var holder = document.getElementById('messages_pane');
holder.ondragover = () => {
$('#drop-overlay').stop().fadeIn(1);
return false;
};
holder.ondragleave = () => {
$('#drop-overlay').stop().fadeOut();
return false;
};
holder.ondragend = () => {
//$('#drop-overlay').hide();
return false;
};
holder.ondrop = (e) => {
e.preventDefault();
$('#drop-overlay').stop().fadeOut();
if (!$('#recipient_form').val()) { return false; } else {
var client = new WebTorrent();
for (let f of e.dataTransfer.files) {
client.seed(f, function (torrent) {
sendMessage(torrent.magnetURI.split('&tr')[0]);
torrent.on('wire', function (wire) {
$('.' + torrent.magnetURI.split('&')[0].split(":")[3]).find('p').append(' <i class="fa fa-circle-o-notch"></i>');
console.log(torrent.magnetURI);
})
torrent.on('upload', function (uploaded) {
if ( torrent.uploaded == torrent.length ) {
$('.fa-circle-o-notch').removeClass('fa-circle-o-notch').addClass('fa-check-circle-o');
setTimeout(function() {
client.destroy();
}, 60000);
} else {
}
})
})
}
return false;
};
}
function escapeHtml(unsafe) {
return unsafe
// .replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/Δ/g, "Δ")