-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
593 lines (450 loc) · 17.7 KB
/
Copy pathindex.html
File metadata and controls
593 lines (450 loc) · 17.7 KB
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
<html><head>
<script src="/js/eruda.min.js"></script>
<script>eruda.init();</script>
<!-- PWA Headers -->
<link rel="manifest" href="manifest.json">
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="application-name" content="Hullo" />
<meta name="apple-mobile-web-app-title" content="Hullo" />
<meta name="msapplication-starturl" content="/index.html" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- disable browser caching
<meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /><meta http-equiv="expires" content="0" /> <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /> <meta http-equiv="pragma" content="no-cache" />
-->
<!--<script src="/startworker.js"></script>-->
<script src="/js/jquery.js"></script>
<script src="/lib/pica.min.js"></script>
<script src="/lib/image-blob-reduce.min.js"></script>
<link rel="stylesheet" href="/mystyles.css">
<link id="maintheme" rel="stylesheet" href="/lib/onsen/css/dark-onsen-css-components.css">
<link rel="stylesheet" href="/lib/onsen/css/material-design-iconic-font/css/material-design-iconic-font.css">
<link rel="stylesheet" href="/lib/onsen/css/font_awesome/css/all.css">
<link rel="stylesheet" href="/lib/onsen/css/ionicons/css/ionicons.css">
<link rel="/lib/onsen/css/material-design-iconic-font/css/material-design-iconic-font.css">
<script src="/lib/onsen/js/onsenui.js"></script>
</head>
<body> <!-- ur body is a wonderland -->
<ons-navigator id="myNavigator" page="index.html">
</ons-navigator>
<template id="index.html"> <!-- main view-->
<ons-page id="indexPage" modifier="mystyles">
<ons-toolbar class="toolbar">
<div class="left toolbar__left">
<ons-toolbar-button id="menu_button">
<ons-icon icon="fa-bars"></ons-icon>
</ons-toolbar-button>
<ons-toolbar-button id="roomconfig_button">
<ons-icon icon="fa-star"></ons-icon>
</ons-toolbar-button>
</div>
<div class="center toolbar__center">Hullo</div>
<div class="right toolbar__right"></div>
</ons-toolbar>
<div id="content" class="content" style="overflow:scroll">
<div id="container" class="container"></div>
</div>
<ons-bottom-toolbar modifier="aligned">
<div class="left" style="padding-top:10px;padding-left:20px;float:left">
<ons-input id="input" modifier="material transparent" type="text"></ons-input>
</div>
<div class="center"></div>
<div class="right" style="padding-top:8px;padding-left:20px;float:right">
<ons-toolbar-button icon="fa-plus-circle" onclick= "document.querySelector('#uploader').click()"></ons-toolbar-button>
<ons-toolbar-button icon="fa-paper-plane"></ons-toolbar-button>
</div>
</ons-bottom-toolbar>
<input id="uploader" style="display:none;" type="file">
<div id="result" style="display:none"></div>
</ons-page>
</template>
<script>
function createRoomCallback(){
let vars = ['appID', 'myID', 'roomID', 'password'];
for(let i of vars) {
localStorage.setItem(i,document.querySelector("#"+i).value)
}
var appID = document.querySelector("#appID").value;
var myID = document.querySelector("#myID").value;
var roomID = document.querySelector("#roomID").value;
var password = document.querySelector("#password").value;
document.querySelector("#roomconfig_dialog").hide();
}
</script>
<!-- Dialog -->
<!--this thing is hideous! omg. -->
<ons-dialog style="backgroundColor:#000000" modifer="material" id="roomconfig_dialog" cancelable>
<div style="background:#000000; text-align:left; padding: 10px;">
<p>
To join/create a new room, fill out the fields below:
</p>
<ul class="list">
<li class="list-item">
<div class="list-item__center">
<input id="myID" type="text" class="text-input" placeholder="Choose your screen name">
</div>
</li>
<li class="list-item">
<div class="list-item__center">
<input id="appID" type="text" class="text-input" placeholder="appID">
</div></li>
<li class="list-item">
<div class="list-item__center">
<input id="roomID" type="text" class="text-input" placeholder="roomID">
</div></li>
<li class="list-item">
<div class="list-item__center">
<input id="password" type="text" class="text-input" placeholder="Encryption password">
</div></li>
</ul>
<p><ons-button id="Save" onclick="createRoomCallback()">Save</ons-button>
<script>document.querySelector("#Save").removeAttribute("ripple")</script>
<ons-button id="Cancel" onclick="document.querySelector('#roomconfig_dialog').hide()">Cancel</ons-button>
<script>document.querySelector("#Cancel").removeAttribute("ripple")</script>
</p>
</div>
</ons-dialog>
<script>
// "Controllers" area.
window.myApp = {};
document.addEventListener('init', function(event) {
var page = event.target;
if (page.id === 'indexPage') {
//theme selector eventually:
document.querySelector("#maintheme").href="lib/onsen/css/dark-onsen-css-components.css";
//click button for config dialog
document.querySelector("#roomconfig_button").addEventListener("click", function() {
//pre-fill current settings
for(let i of ["appID","myID","roomID","password"]) {
document.querySelector("#"+i).value=localStorage.getItem(i)
}
document.querySelector("#roomconfig_dialog").show();
});
//Enter sends input
document.addEventListener('keydown', (event) => {
if (event.keyCode === 13) {
//alert('got ENTER')
send(document.querySelector("#input").value);
document.querySelector("#input").value=""
}
});
} //end of indexPage
}); //end of addEventListener.
</script>
<!--The 'backend' of no-backend -->
<script type='module'>
import {joinRoom} from "/lib/trystero/torrent.js"
import {s as selfId} from "/lib/common/crypto.js"
//set room params from storage
var appID; var roomID; var password; var myID;
if (localStorage.getItem("appID") === null) {
console.log("appID not set")
appID = "welcome"
roomID = "welcome"
} else {
appID = localStorage.appID
myID = localStorage.myID
roomID = localStorage.roomID
password = localStorage.password
}
//join room, set actions
localStorage.visible = "0"
const config = {appId: appID}
const room = joinRoom(config, roomID, password)
const [sendText, getText] = room.makeAction('text')
const [sendReq, recvReq] = room.makeAction('update')
const [sendName, getName] = room.makeAction('name')
function deleteallmsgs(){
//guess what this does
let ar = Reflect.ownKeys(localStorage)
for(let i of ar) {
if(i.includes("text_")){
localStorage.removeItem(i);
};
}
}
window.d = deleteallmsgs
//update others as they join:
recvReq((obj,id) => {
console.log('HIST: req: '+obj.last)
//get all in db matching roomID
let array = Reflect.ownKeys(localStorage).filter(key => key.includes(roomID))
//reduce to ones w newer timestamp than 'last'
//also: sort, descending.
if(array.length > 0) {
let list = array.filter(key => parseInt(key.split("_")[2]) > obj.last).sort((a, b) => a.split("_")[2] - b.split("_")[2]);
//sendit
console.log('HIST: found '+list.length+' items, sending...')
for(let i of list) {
sendText(JSON.parse(localStorage.getItem(i)),id)
}
} else { console.log('HIST: no matches') }
})
function getPrettyTimeStamp() {
var date = new Date();
var m = date.getMonth();
var months =['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
var month = months[m]
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var ampm = hour >= 12 ? 'PM' : 'AM';
hour = hour % 12;
hour = hour ? hour : 12;
minute = minute < 10 ? '0' + minute : minute;
var strTime = month + ' ' + day + ', ' + hour + ':' + minute + ampm;
return strTime;
}
function getpt(timestamp) {
var date = new Date(timestamp * 1000);
var monthNames = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct",
"Nov", "Dec"
];
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = monthNames[monthIndex] + ' ' + day + ', ' + hours + ':' + minutes + ampm + ' ' + year;
return strTime;
}
/////////////////////////////////////////////
/////////////////////////////////////////////
/////////////////////////////////////////////
navigator.serviceWorker.addEventListener("controllerchange", (e) => { console.log("[Service Worker]", e.target.state) });
navigator.serviceWorker.addEventListener("message", (event) => { console.log(event.data) });
navigator.serviceWorker.startMessages();
//notice everything below is inside window.onload.
window.onload = function() {
//EVERY modern browser has serviceWorker, quit the messin around and just mount up.
//note i moved some stuff above onload in hopes of achieving better messaging capability.
if(navigator.serviceWorker) {
navigator.serviceWorker.register('./worker.js')
.then(function() {
return navigator.serviceWorker.ready
})
.then(function(registration) {
registration.update();
window.sw = registration;
sw.active.postMessage('ping')
})
};
//register for noisifications and bg sync
Notification.requestPermission(permission => {
if (permission === 'granted'){
navigator.serviceWorker.ready.then(registration => registration.sync.register('tag').then(() => console.log("Registered background sync"))
.catch(err => console.error("Error registering background sync", err)))
}
else console.error("Permission was not granted.")
})
//check status
navigator.permissions.query({ name: "periodic-background-sync" }).then((status)=>{ console.log(status)})
//*/
//update- why has not a single site of hundreds ive read, described this:
//request ready state which returns the serviceWorker object upon which you access props n methods. still no clue why postMessage is at .active whereas showNotif isnt.
//navigator.serviceWorker.ready.then(sw => sw.showNotification('ello'))
//or navigator.serviceWorker.ready.then(sw => sw.active.postMessage('ping'))
//messaging is still so ridiculous. Constantly moving
//target of FIVE! different places that 'postMessage'
//method exists, and its just a guess every time which
//one will work. Heres the list:
// sw.postMessage
// sw.active.postMessage
// navigator.serviceWorker.postMessage
// navigator.serviceWorker.active.postMessage
// navigator.serviceWorker.controller.postMessage
// _ALL_ of which switch between working, returning
//only 'null' and doing nothing, and 'throwing'. AND on
//top of that, the worker side gives up on being able
//to return responses/forward console.log after a
//while, though it does wake up from stopped state and
//react to the 'ping' onmessage event, visible in the
//chrome://serviceworker-internals page but no longer passed via log() out to console.
//AND YEP! following day, nothing changed, and the init messages that were passing fine yest no longer pass. CHANGED IN MY SLEEP. ... Later on: I wrap the guts of 'log()' in an IEAF async, et voila works again. ..and then later, doesnt again. super DUPER unreliable and super duper impossible and slow to try and debug.
function newCard(obj) {
let data = obj.text
let parent = document.querySelector("#content")
let me = document.createElement("div") //ons-card
me.className="card" //was nothing
if(obj.myID == localStorage.myID) { me.style.backgroundColor = "#424242"
}
let title = document.createElement("div") //title
title.className="card__title" //title
title.style.fontSize = "12px"
if(obj.myID == "announce"){
title.innerHTML=""
me.style.fontStyle = "italic"
obj.pt=""
} else {
title.innerHTML=obj.myID }
let content = document.createElement("div")
content.className="card__content" //content
if(obj.img == true) {
//console.log(obj)
let img = document.createElement("img")
img.src=obj.text
content.appendChild(img)
} else {
content.innerHTML=obj.text
}
let date = document.createElement("div")
date.className="Date"
date.innerHTML=obj.pt
date.style.textAlign = "right";
date.style.fontStyle = "italic";
content.appendChild(date)
me.appendChild(title)
me.appendChild(content)
parent.appendChild(me)
}
//if room = 'welcome', send a card
//about how this prob isnt room you want.
if(roomID == "welcome") {
newCard({text:"Hullo. This is the default, unencrypted waiting room. Click the star in the toolbar to join/create an encrypted room.",myID:"announce"})
}
//We're getting all saved text_ from storage, limited to ones that match roomID. sorting by timestamp. making new 'cards' to display, and finally adding them to the 'visible' list. Enclosed in an IEAF to limit scope.
(function(){
let ar = Reflect.ownKeys(localStorage).filter(i => i.includes("text_") && i.includes(roomID)).sort((a, b) => a.split("_")[2] - b.split("_")[2]);
//console.log(ar.length);
ar.forEach(i => {
let timestamp = i.split("_")[2]
if(i.includes("text_")) {
let item = JSON.parse(localStorage.getItem(i));
if(item.text != "") {
newCard(item);
localStorage.visible += "," + timestamp;
} else { localStorage.removeItem(i) }
}
});
})();
//take these out later:
window.sendText = sendText
function send(msg, img = false) {
if (localStorage.myID === undefined) {
let myID = "unnamed";
} else {
let myID = localStorage.myID
}
newCard({
text: msg,
pt: getPrettyTimeStamp(),
myID: myID,
img: img
})
let lt = Date.now()
let obj = {
text: msg,
myID: myID,
roomID: roomID,
pt: getPrettyTimeStamp(),
lt: lt,
img: img
}
localStorage.setItem('text_' + obj.roomID + '_' + obj.lt, JSON.stringify(obj))
for (let id of room.getPeers()) {
if (id != 0) {
//console.log('sending ['+msg+'] to id: '+id)
sendText(obj, id)
}
}
} //end of send
//take these out later
window.room = room
window.config = config
window.send = send
//somebody joined. announce and
//hit them up for msg history
function joincallback(thisPeer) {
// introduce ourselves
sendName(localStorage.myID, thisPeer)
//request to update room history from new peer:
//get msg in storage w most recent timestamp
//TODO: this is bad logic. if 'we' send a msg before seeing missed ones, it becomes our most recent stamp and unseen msgs remain unrequested.
let array = Reflect.ownKeys(localStorage)
var highest = array.reduce(function(prev, current) {
var currentRoomID = current.split("_")[1];
var currentTimestamp = current.split("_")[2];
if (currentRoomID === roomID && currentTimestamp > prev.split("_")[2]) {
return current;
} else {
return prev;
}
}, "text_"+roomID+"_0");
//req any messages newer
highest = highest.split("_")[2]
console.log('HIST: sending req: '+highest)
sendReq({lt:Date.now(),last:highest},thisPeer)
}
room.onPeerJoin((thisPeer) => {joincallback(thisPeer)})
// listen for peers naming themselves
const idsToNames = {}
getName((name, peerId) => {
idsToNames[peerId] = name
//announce
newCard({text:"Peering with "+name+" ["+peerId+"]...",pt:getPrettyTimeStamp(), myID:"announce"})
})
room.onPeerLeave(peerId => {
//announce
nombre = idsToNames[peerId] ? idsToNames[peerId] : 'unknown'
newCard({text:nombre+" ["+peerID+"] leaves...",pt:getPrettyTimeStamp(), myID:"announce"})
});
//we received a msg
getText((obj, peerId) => {
//are we currently in the room this message is addressed to?
if(obj.roomID == roomID) {
let TS = localStorage.visible.split(",")
let NEW = obj.lt.toString()
//if we havent already seen this:
if (TS.indexOf(NEW) === -1) {
localStorage.visible = localStorage.visible+","+NEW
//update display
newCard(obj)
//save hist
localStorage.setItem('text_'+obj.roomID+'_'+NEW,JSON.stringify(obj))
}
}
}); //end of getText
// handle image uploads
(function () {
var reducer = new window.ImageBlobReduce({
pica: window.ImageBlobReduce.pica({
features: [ 'js', 'wasm', 'ww' ] })
});
document.getElementById('uploader').addEventListener('change', function () {
reducer
.toBlob(
document.querySelector('input[type=file]').files[0],
{
max: 330,
unsharpAmount: 80,
unsharpRadius: 0.6,
unsharpThreshold: 2
}
)
.then(function (blob) {
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function(e) {
let dURL = reader.result;
localStorage.setItem('last_durl',dURL)
send(dURL,true)
}
});
});
})();
//doesnt work.
//document.querySelector('.page--mystyles__background').style['background-image']='url('+localStorage.getItem("last_durl")+')'
} //end of window.onload
</script>
</body>
</html>