-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.html
More file actions
610 lines (593 loc) · 33.2 KB
/
Copy pathapp.html
File metadata and controls
610 lines (593 loc) · 33.2 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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="manifest" href="/manifest.webmanifest">
<meta name="theme-color" content="#16181d">
<link rel="icon" href="/icon.svg">
<link rel="apple-touch-icon" href="/icon.svg">
<title>RustDesk Address Book</title><style>
:root{color-scheme:dark}
*{box-sizing:border-box}
body{font:15px/1.4 -apple-system,system-ui,sans-serif;margin:0;background:#16181d;color:#e6e6e6}
header{position:sticky;top:0;z-index:15;background:#16181dee;backdrop-filter:blur(8px);padding:11px 18px;border-bottom:1px solid #2a2d35}
.bar{display:flex;gap:9px;align-items:center}
.brand{font-size:15px;font-weight:650;white-space:nowrap}
.brand small{color:#777;font-weight:400;font-size:12px;margin-left:4px}
#q{flex:1;min-width:120px;padding:8px 12px;border-radius:9px;border:1px solid #333;background:#1f2127;color:#fff;font-size:14px}
.pill{font-size:12px;color:#9aa;white-space:nowrap;background:#22252c;border:1px solid #2c2f37;border-radius:20px;padding:5px 11px}
.pill b{color:#39d353}
button{font:inherit;cursor:pointer;border-radius:9px;border:1px solid #333;background:#262a33;color:#e6e6e6;padding:8px 13px}
button:hover{border-color:#3d76d6}
.btn-primary{background:#2f6fe0;border-color:#2f6fe0;color:#fff;font-weight:600}
.btn-primary:hover{background:#3a7af0}
.iconbtn{padding:8px 11px;font-size:15px;line-height:1}
.iconbtn svg{display:block}
.iconbtn.spin{animation:spin .8s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
main{padding:18px 22px 70px}
section{margin-bottom:26px}
h2{font-size:13px;text-transform:uppercase;letter-spacing:.06em;color:#cfcfcf;border-left:3px solid;padding-left:9px;margin:0 0 12px;display:flex;align-items:center;gap:8px}
h2 small{color:#888;font-weight:400}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:9px}
.peer{position:relative;background:#1f2127;border:1px solid #2c2f37;border-radius:11px;transition:.12s}
.peer:hover{background:#262a33;border-color:#3d76d6;transform:translateY(-1px)}
.peer.alt{border-style:dashed}
.peer.offline{opacity:.5}.peer.offline:hover{opacity:1}
.body{display:flex;flex-direction:column;gap:2px;padding:11px 13px 11px 28px;text-decoration:none;color:inherit}
.st{position:absolute;left:11px;top:14px;width:9px;height:9px;border-radius:50%;background:#555}
.online .st{background:#39d353;box-shadow:0 0 7px #39d35388}
.offline .st{background:#4a4d55}
.alias{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding-right:8px}
.meta{font-size:12px;color:#8b8f99;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding-right:8px}
.tools{position:absolute;top:6px;right:6px;display:flex;gap:1px;opacity:0;transition:.12s;background:#262a33;border-radius:8px}
.peer:hover .tools{opacity:1}
.tools .ico{background:#22252c}
.tools .ico:hover{background:#30343d}
.empty{color:#777;padding:40px 0;text-align:center}
.backdrop{position:fixed;inset:0;background:#000a;display:none;align-items:center;justify-content:center;z-index:20}
.backdrop.show{display:flex}
.modal{background:#1d2027;border:1px solid #353a45;border-radius:14px;padding:22px;width:min(440px,92vw);max-height:90vh;overflow:auto}
.modal h3{margin:0 0 14px}
label{display:block;font-size:12px;color:#9aa;margin:11px 0 4px}
input,select{width:100%;padding:9px 11px;border-radius:8px;border:1px solid #383d47;background:#15171c;color:#fff;font-size:14px}
.hint{font-size:11px;color:#71757f;margin-top:4px}
.err{color:#ff6b6b;font-size:13px;min-height:18px;margin-top:10px}
.actions{display:flex;gap:8px;justify-content:flex-end;margin-top:18px}
.hide{display:none}
#toast{position:fixed;bottom:22px;left:50%;transform:translateX(-50%) translateY(80px);background:#2f6fe0;color:#fff;padding:11px 18px;border-radius:10px;font-size:14px;box-shadow:0 6px 20px #0007;opacity:0;transition:.25s;z-index:30;pointer-events:none}
#toast.show{transform:translateX(-50%) translateY(0);opacity:1}
#toast.warn{background:#444a55}
h2{cursor:default}
.tagname{cursor:default;padding:1px 3px;border-radius:4px}
.cdot{cursor:pointer;border:1px solid #ffffff33}
.htools{display:inline-flex;gap:1px;margin-left:5px;opacity:0;transition:.12s}
section:hover .htools{opacity:1}
.ico{display:inline-flex;align-items:center;justify-content:center;border:none;background:none;color:#9aa;cursor:pointer;padding:3px;border-radius:6px}
.ico:hover{background:#ffffff14;color:#e6e6e6}
.ico.danger:hover{color:#ff7b7b}
.ico svg{display:block}
section.drop>h2{outline:2px dashed #3d76d6;outline-offset:3px;border-radius:6px}
.peer{cursor:grab}
.peer.dragging{opacity:.4}
.peer .body{cursor:inherit}
.depth1>h2{margin-left:18px}.depth2>h2{margin-left:36px}.depth3>h2{margin-left:54px}
.depth1>.grid,.depth2>.grid,.depth3>.grid{margin-left:18px}
.untagged>h2{color:#80858f}
.chev{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:6px;cursor:pointer;color:#aab;font-size:19px;line-height:1;user-select:none;transition:.12s}
.chev:hover{color:#fff;background:#ffffff14}
h2 .cdot{cursor:pointer}
section.collapsed>.grid{display:none}
section.folded{display:none}
section.collapsed>h2{opacity:.82}
#bell{position:relative}
#badge{position:absolute;top:-5px;right:-5px;min-width:16px;height:16px;padding:0 4px;border-radius:8px;background:#e0483d;color:#fff;font-size:10px;font-weight:700;line-height:16px;text-align:center;display:none}
#badge.show{display:block}
/* shared dropdown popovers (notifications + overflow menu) — no #id sets
display, so .pop.hide can reliably hide them */
.pop{position:fixed;top:54px;right:18px;display:flex;flex-direction:column;background:#1d2027;border:1px solid #353a45;border-radius:12px;box-shadow:0 14px 34px #000b;z-index:30;overflow:hidden}
.pop.hide{display:none}
#notif{width:330px;max-height:70vh}
#moremenu{width:222px;padding:6px}
#sortmenu{width:200px;padding:6px}
#cmenu{padding:9px;width:166px;flex-direction:row;flex-wrap:wrap;gap:7px}
.sw{width:26px;height:26px;border-radius:7px;cursor:pointer;border:1px solid #ffffff22;transition:.1s}
.sw:hover{transform:scale(1.12)}
.sw.sel{outline:2px solid #fff;outline-offset:1px}
.sw.custom{display:flex;align-items:center;justify-content:center;background:#2b2f38;font-size:13px}
.mi{display:block;width:100%;text-align:left;background:none;border:none;border-radius:7px;padding:8px 10px;font-size:13px;color:#e6e6e6}
.mi:hover{background:#2b2f38}
.mlabel{font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:#80858f;padding:9px 10px 3px}
.msort.active{color:#fff}
.msort.active::after{content:'✓';color:#39d353;float:right}
.msep{height:1px;background:#2c2f37;margin:6px 4px}
.tips{margin:8px 0 0;padding-left:18px;line-height:1.75;font-size:13.5px;color:#cdd2da}
.tips b{color:#fff}.tips code{background:#15171c;padding:1px 5px;border-radius:4px}
.nhead{display:flex;align-items:center;gap:8px;padding:11px 13px;border-bottom:1px solid #2c2f37;font-weight:600;font-size:14px}
.ntoggles{margin-left:auto;display:flex;gap:5px}
.ntog{font-size:11.5px;padding:4px 8px;background:#262a33}
.ntog.on{background:#2f6fe0;border-color:#2f6fe0;color:#fff}
#nlist{overflow:auto;padding:4px 0}
.nrow{display:flex;align-items:center;gap:8px;padding:8px 13px;font-size:13px}
.nrow .ndot{width:8px;height:8px;border-radius:50%;flex:none}
.nrow.up .ndot{background:#39d353}.nrow.down .ndot{background:#e0483d}
.nrow .nname{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.nrow .nwhen{margin-left:auto;color:#71757f;font-size:11px;white-space:nowrap}
.nempty{color:#71757f;text-align:center;padding:26px 0;font-size:13px}
.nfoot{border-top:1px solid #2c2f37;padding:7px 10px;text-align:right}
.nfoot button{font-size:12px;padding:5px 10px}
</style></head><body>
<header>
<div class="bar">
<div class="brand">RustDesk Address Book <small id="count"></small></div>
<input id="q" placeholder="Search machines…" autofocus>
<span id="live" class="pill" title="Live status">…</span>
<button class="btn-primary" id="add">+ Add machine</button>
<button class="iconbtn" id="sortbtn" title="Sort"><svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><path d="M2.5 4h11M2.5 8h7M2.5 12h3.5"/></svg></button>
<button class="iconbtn" id="resync" title="Re-sync: pull in machines you've connected to since"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg></button>
<button class="iconbtn" id="bell" title="Notifications"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/></svg><span id="badge"></span></button>
<button class="iconbtn" id="menu" title="More">⋯</button>
</div>
</header>
<input type="color" id="colorpick" style="position:fixed;left:-9999px">
<div id="cmenu" class="pop hide"></div>
<div id="sortmenu" class="pop hide">
<div class="mlabel">Sort by</div>
<button class="mi msort" data-v="alias">Display name</button>
<button class="mi msort" data-v="hostname">Hostname</button>
<button class="mi msort" data-v="recent">Recently accessed</button>
</div>
<div id="moremenu" class="pop hide">
<button class="mi" id="m-newtag">+ New tag…</button>
<div class="msep"></div>
<button class="mi" id="m-expand">Expand all groups</button>
<button class="mi" id="m-collapse">Collapse all groups</button>
<div class="msep"></div>
<button class="mi" id="m-help">Tips & shortcuts…</button>
</div>
<div id="notif" class="pop hide">
<div class="nhead">Notifications
<span class="ntoggles">
<button id="t-sound" class="ntog" title="Play a sound on status changes">🔊</button>
<button id="t-desk" class="ntog" title="Show desktop notifications">🖥</button>
</span>
</div>
<div id="nlist"></div>
<div class="nfoot"><button id="nclear">Clear</button></div>
</div>
<div class="backdrop" id="helpback"><div class="modal">
<h3>Tips & shortcuts</h3>
<ul class="tips">
<li><b>Connect</b> — click a machine card.</li>
<li><b>Move to a tag</b> — drag a card onto a tag section.</li>
<li><b>Add to multiple tags</b> — hold <b>⌘ / Ctrl / Alt</b> while dragging.</li>
<li><b>Edit / delete</b> — hover a card or tag for the <b>✎ / 🗑</b> icons.</li>
<li><b>Recolor a tag</b> — click its color dot.</li>
<li><b>Fold a group</b> — click the tag header (or its ▸ chevron).</li>
<li><b>Nest tags</b> — name a tag <code>Parent/Child</code>.</li>
</ul>
<div class="actions"><button class="btn-primary" id="help-ok">Got it</button></div>
</div></div>
<div id="toast"></div>
<main id="main"></main>
<div class="backdrop" id="backdrop"><div class="modal">
<h3 id="m-title">Add machine</h3>
<input type="hidden" id="f-orig">
<label>RustDesk ID *</label><input id="f-id" inputmode="numeric" placeholder="123456789">
<label>Alias (display name)</label><input id="f-alias" placeholder="office-pc">
<div class="row" style="gap:10px">
<div style="flex:1"><label>Hostname</label><input id="f-hostname"></div>
<div style="flex:1"><label>Username</label><input id="f-username"></div>
</div>
<label>Server</label><select id="f-server"></select>
<div id="f-newsrv" class="hide">
<label>New server host</label><input id="f-server-new" placeholder="rustdesk.example.com">
<label>Server key</label><input id="f-key" placeholder="base64 key (blank if server has no key)">
</div>
<label>Tags (comma-separated)</label><input id="f-tags" placeholder="ProCam-SFF">
<div class="hint">Leave tags blank to auto-classify from hostname.</div>
<div class="err" id="f-err"></div>
<div class="actions">
<button id="f-cancel">Cancel</button>
<button class="btn-primary" id="f-save">Save</button>
</div>
</div></div>
<script>
const ORDER=["ProCam-SFF","EliteCam","USV","RaspberryPi","Workstation"];
const KNOWN={"ProCam-SFF":"#1976D2","EliteCam":"#388E3C","USV":"#F57C00","RaspberryPi":"#C2185B","Workstation":"#7B1FA2"};
let book={default_server:"",servers:[],peers:[]}, stat={};
let collapsed=new Set(JSON.parse(localStorage.getItem('rdab_collapsed')||'[]'));
let sortMode=localStorage.getItem('rdab_sort')||'alias';
let confirmed={}, offSince={}, events=[], unseen=0, audioCtx=null;
// Notification sensitivity (asymmetric):
// • ONLINE is alerted immediately — don't miss a shipped station phoning home.
// • OFFLINE must persist this long before alerting, so brief drops / reboots of
// established stations don't spam you (a drop shorter than this is silent and,
// since the station never "confirmed" offline, its return is silent too).
const POLL_MS=10000;
const OFFLINE_GRACE_MS=60000; // ~1 min
let soundOn=localStorage.getItem('rdab_sound')==='1';
let deskOn=localStorage.getItem('rdab_desk')==='1';
const $=s=>document.querySelector(s), el=(t,c)=>{const e=document.createElement(t);if(c)e.className=c;return e;};
function color(tag){if(KNOWN[tag])return KNOWN[tag];let h=0;for(const c of tag)h=(h*31+c.charCodeAt(0))%360;return`hsl(${h},55%,48%)`;}
async function api(method,path,body){
const r=await fetch(path,{method,headers:body?{'Content-Type':'application/json'}:{},
body:body?JSON.stringify(body):undefined,cache:'no-store'});
const j=await r.json().catch(()=>({}));
if(!r.ok)throw new Error(j.error||r.status);return j;
}
const esc=s=>(s==null?'':String(s)).replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
const ICON={
edit:'<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><path d="M12.146.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.468-.325z"/></svg>',
trash:'<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6Z"/><path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/></svg>',
};
function ico(kind,title,onclick,danger){
const b=el('button','ico'+(danger?' danger':''));b.innerHTML=ICON[kind];b.title=title;
b.onclick=onclick;b.draggable=false;return b;
}
function tagColor(t){return (book.tag_colors&&book.tag_colors[t])||color(t);}
function peersWith(t){return book.peers.filter(p=>(p.tags||[]).includes(t));}
function sortPeers(arr){
const by=sortMode;
return arr.slice().sort((a,b)=>{
if(by==='recent') return (b.last||0)-(a.last||0) // most recent first
|| a.alias.toLowerCase().localeCompare(b.alias.toLowerCase());
const ka=(by==='hostname'?a.hostname||a.alias:a.alias).toLowerCase();
const kb=(by==='hostname'?b.hostname||b.alias:b.alias).toLowerCase();
return ka.localeCompare(kb);
});
}
function ago(epoch){
if(!epoch) return 'never';
const s=Date.now()/1000-epoch;
if(s<90) return 'just now';
const m=s/60; if(m<90) return Math.round(m)+'m ago';
const h=m/60; if(h<36) return Math.round(h)+'h ago';
const d=h/24; if(d<14) return Math.round(d)+'d ago';
const w=d/7; if(w<9) return Math.round(w)+'w ago';
return Math.round(d/30.4)+'mo ago';
}
function render(){
const m=$('#main');m.innerHTML='';
$('#count').textContent=`${book.peers.length} machines`;
if(!book.peers.length){m.innerHTML='<div class="empty">No machines yet — click “+ Add machine”.</div>';return;}
// one section per registered tag (hierarchical order from the server)
for(const t of (book.tags||[])) m.appendChild(section(t,peersWith(t),false));
const untagged=book.peers.filter(p=>!(p.tags||[]).length);
if(untagged.length||!(book.tags||[]).length) m.appendChild(section('',untagged,true));
applyStatus();applyFilter();
}
function section(tag,peers,isUntagged){
const depth=isUntagged?0:tag.split('/').length-1;
const leaf=isUntagged?'Untagged':tag.split('/').pop();
const c=isUntagged?'#80858f':tagColor(tag);
const sec=el('section','depth'+Math.min(depth,3)+(isUntagged?' untagged':''));
sec.dataset.tag=tag;sec.dataset.untagged=isUntagged?'1':'';
const h=el('h2');h.style.borderColor=c;
const key=isUntagged?'__untagged__':tag;
const chev=el('span','chev');chev.textContent=collapsed.has(key)?'▸':'▾';chev.title='Collapse / expand';
const dot=el('span','cdot');dot.style.cssText=`width:11px;height:11px;border-radius:50%;background:${c};display:inline-block`;
const name=el('span','tagname');name.textContent=leaf;name.title=isUntagged?'':tag;
const cnt=el('small');cnt.textContent=peers.length;
h.append(chev,dot,name,cnt);
h.onclick=e=>{if(e.target.closest('.cdot,.htools'))return;toggleCollapse(key);};
if(!isUntagged){
dot.title='Recolor';dot.onclick=e=>{e.stopPropagation();pickColor(tag,dot);};
const tools=el('span','htools');
tools.append(
ico('edit','Rename tag',e=>{e.stopPropagation();renameTag(tag);}),
ico('trash','Delete tag',e=>{e.stopPropagation();deleteTag(tag);},true));
h.append(tools);
}
sec.appendChild(h);
const grid=el('div','grid');
sortPeers(peers).forEach(p=>grid.appendChild(card(p,tag)));
sec.appendChild(grid);
// drop target
sec.addEventListener('dragover',e=>{if(!drag)return;e.preventDefault();
e.dataTransfer.dropEffect=addMode(e)?'copy':'move';sec.classList.add('drop');});
sec.addEventListener('dragleave',e=>{if(!sec.contains(e.relatedTarget))sec.classList.remove('drop');});
sec.addEventListener('drop',e=>{e.preventDefault();sec.classList.remove('drop');onDrop(tag,isUntagged,addMode(e));});
return sec;
}
function card(p,inTag){
const alt=p.server&&p.server!==book.default_server;
const d=el('div','peer'+(alt?' alt':''));d.dataset.id=p.id;d.dataset.tag=inTag||'';
d.dataset.s=(p.alias+' '+p.hostname+' '+p.id+' '+(p.tags||[]).join(' ')).toLowerCase();
let sub=`${p.username?p.username+'@':''}${p.hostname||'—'}`;
if(alt)sub+=' · '+p.server;
if((p.tags||[]).length>1)sub+=' · 🏷'+p.tags.length;
if(sortMode==='recent')sub+=' · '+ago(p.last);
const a=el('a','body');a.href=p.link;a.draggable=false;
a.innerHTML=`<span class="st"></span><span class="alias" title="${esc(p.alias)}">${esc(p.alias)}</span><span class="meta" title="${esc(sub)}">${esc(sub)}</span>`;
const tools=el('div','tools');
tools.append(
ico('edit','Edit',e=>{e.preventDefault();openForm(p);}),
ico('trash','Delete',e=>{e.preventDefault();del(p);},true));
d.append(a,tools);
d.draggable=true;
d.addEventListener('dragstart',e=>{drag={id:p.id,from:inTag||''};d.classList.add('dragging');
e.dataTransfer.effectAllowed='copyMove';e.dataTransfer.setData('text/plain',p.id);});
d.addEventListener('dragend',()=>{drag=null;d.classList.remove('dragging');
document.querySelectorAll('.drop').forEach(s=>s.classList.remove('drop'));});
return d;
}
// ---- drag & drop / tag membership ----
let drag=null;
const addMode=e=>e.ctrlKey||e.metaKey||e.altKey;
async function onDrop(targetTag,isUntagged,add){
if(!drag)return;
const {id,from}=drag;
let body;
if(isUntagged){ // dropping onto Untagged just removes the source tag
if(!from)return; body={remove:[from]};
}else if(add){ // ⌘/Ctrl/Alt: add membership, keep existing
if((book.peers.find(p=>p.id===id)?.tags||[]).includes(targetTag))return;
body={add:[targetTag]};
}else{ // plain: move from source tag to target
if(from===targetTag)return;
body={add:[targetTag],remove:from?[from]:[]};
}
try{book=await api('POST','/api/peers/'+encodeURIComponent(id)+'/tags',body);render();}
catch(e){toast('Failed: '+e.message,true);}
}
// ---- tag management ----
async function newTag(){
const name=prompt('New tag name (use Parent/Child for nesting):','');
if(!name)return;
try{book=await api('POST','/api/tags',{name});render();toast('Created “'+name+'”');}
catch(e){toast(e.message,true);}
}
async function renameTag(old){
const next=prompt('Rename tag (renames its sub-tags too):',old);
if(!next||next===old)return;
try{book=await api('PUT','/api/tags',{old,new:next});render();}
catch(e){toast(e.message,true);}
}
async function deleteTag(name){
const kids=(book.tags||[]).filter(t=>t.startsWith(name+'/')).length;
if(!confirm(`Delete tag “${name}”${kids?` and its ${kids} sub-tag(s)`:''}? Machines keep existing; they just lose this label.`))return;
try{book=await api('DELETE','/api/tags',{name});render();}
catch(e){toast(e.message,true);}
}
const SWATCHES=['#1976D2','#0097A7','#388E3C','#7CB342','#D4AC0D','#F57C00',
'#C0392B','#C2185B','#8E44AD','#5C6BC0','#16A085','#607D8B'];
function pickColor(tag,anchor){
const m=$('#cmenu');
if(!m.classList.contains('hide')&&m.dataset.tag===tag){closePops();return;} // click dot again -> close
m.dataset.tag=tag;m.innerHTML='';
const cur=(tagColor(tag)||'').toLowerCase();
SWATCHES.forEach(c=>{
const s=el('div','sw'+(c.toLowerCase()===cur?' sel':''));s.style.background=c;s.title=c;
s.onclick=()=>setColor(tag,c);m.appendChild(s);
});
const cust=el('div','sw custom');cust.textContent='🎨';cust.title='Custom…';
cust.onclick=()=>{const cp=$('#colorpick');cp.value=toHex(tagColor(tag));
cp.onchange=()=>setColor(tag,cp.value);cp.click();};
m.appendChild(cust);
const r=anchor.getBoundingClientRect();
m.style.top=(r.bottom+7)+'px';m.style.left=Math.max(8,r.left-6)+'px';m.style.right='auto';
closePops();m.classList.remove('hide');
}
async function setColor(tag,color){
closePops();
try{book=await api('PUT','/api/tags/color',{name:tag,color});render();}catch(e){toast(e.message,true);}
}
function toHex(c){return /^#[0-9a-f]{6}$/i.test(c||'')?c:'#888888';}
function applyStatus(){
let on=0;
document.querySelectorAll('.peer').forEach(d=>{
const s=stat[d.dataset.id];
d.classList.toggle('online',s===true);d.classList.toggle('offline',s===false);
const dot=d.querySelector('.st');dot.title=s===true?'online':s===false?'offline':'unknown';
if(s===true)on++;
});
const t=new Date().toLocaleTimeString(),live=$('#live');
if(Object.keys(stat).length){live.innerHTML=`<b>${on}</b>/${book.peers.length} online`;live.title='Updated '+t;}
else live.textContent='…';
}
function applyFilter(){
const v=$('#q').value.trim().toLowerCase();
document.querySelectorAll('.peer').forEach(d=>d.classList.toggle('hide',v&&!d.dataset.s.includes(v)));
if(v){ // searching: ignore collapse so matches always show
document.querySelectorAll('section').forEach(s=>{
s.classList.remove('collapsed','folded');
s.classList.toggle('hide',!s.querySelector('.peer:not(.hide)'));
});
}else{
document.querySelectorAll('section').forEach(s=>s.classList.remove('hide'));
applyCollapse();
}
}
function ancestorCollapsed(tag){
const parts=tag.split('/');
for(let i=1;i<parts.length;i++) if(collapsed.has(parts.slice(0,i).join('/'))) return true;
return false;
}
function applyCollapse(){
document.querySelectorAll('section').forEach(s=>{
const un=s.dataset.untagged==='1', tag=s.dataset.tag, key=un?'__untagged__':tag;
s.classList.toggle('collapsed',collapsed.has(key));
s.classList.toggle('folded',!un&&ancestorCollapsed(tag));
const ch=s.querySelector('.chev'); if(ch)ch.textContent=collapsed.has(key)?'▸':'▾';
});
}
function toggleCollapse(key){
collapsed.has(key)?collapsed.delete(key):collapsed.add(key);
localStorage.setItem('rdab_collapsed',JSON.stringify([...collapsed]));
applyCollapse();
}
// ---- form ----
function fillServers(sel){
const s=$('#f-server');s.innerHTML='';
book.servers.forEach(h=>{const o=el('option');o.value=h;o.textContent=h+(h===book.default_server?' (default)':'');s.appendChild(o);});
const o=el('option');o.value='__new__';o.textContent='+ add new server…';s.appendChild(o);
s.value=sel&&book.servers.includes(sel)?sel:book.default_server;
toggleNewSrv();
}
function toggleNewSrv(){$('#f-newsrv').classList.toggle('hide',$('#f-server').value!=='__new__');}
function openForm(p){
$('#m-title').textContent=p?'Edit machine':'Add machine';
$('#f-orig').value=p?p.id:'';
$('#f-id').value=p?p.id:'';$('#f-alias').value=p?p.alias:'';
$('#f-hostname').value=p?p.hostname:'';$('#f-username').value=p?p.username:'';
$('#f-tags').value=p?(p.tags||[]).join(', '):'';
$('#f-server-new').value='';$('#f-key').value='';$('#f-err').textContent='';
fillServers(p?p.server:null);
$('#backdrop').classList.add('show');$('#f-id').focus();
}
function closeForm(){$('#backdrop').classList.remove('show');}
async function saveForm(){
let server=$('#f-server').value;
const payload={
id:$('#f-id').value,alias:$('#f-alias').value,hostname:$('#f-hostname').value,
username:$('#f-username').value,platform:'',tags:$('#f-tags').value,
server:server==='__new__'?$('#f-server-new').value:server,
key:server==='__new__'?$('#f-key').value:undefined,
};
const orig=$('#f-orig').value;
try{
const res=orig?await api('PUT','/api/peers/'+encodeURIComponent(orig),payload)
:await api('POST','/api/peers',payload);
book=res;closeForm();render();refreshStatus();
}catch(e){$('#f-err').textContent=e.message;}
}
async function del(p){
if(!confirm(`Delete “${p.alias}” (${p.id})?`))return;
book=await api('DELETE','/api/peers/'+encodeURIComponent(p.id));render();
}
async function load(){book=await api('GET','/api/book');render();}
async function refreshStatus(){
let next=null;
try{next=await api('GET','/status');}catch(e){}
if(next&&Object.keys(next).length){
processStatus(next);
stat=next; // dots show live (raw) status
}
applyStatus();
}
const aliasOf=id=>{const p=book.peers.find(x=>x.id===id);return p?p.alias:id;};
// confirmed[id] = the last state we alerted on (undefined until a silent baseline).
// Online flips it immediately; offline only after OFFLINE_GRACE_MS of continuous down.
function processStatus(next){
const now=Date.now(), up=[], down=[];
for(const id in next){
if(next[id]){ // reported ONLINE
delete offSince[id];
if(confirmed[id]===false)up.push(id); // real offline -> online: alert now
confirmed[id]=true; // (undefined baseline stays silent)
}else{ // reported OFFLINE
if(offSince[id]===undefined)offSince[id]=now;
if(confirmed[id]===undefined)confirmed[id]=false; // baseline, silent
else if(confirmed[id]===true&&now-offSince[id]>=OFFLINE_GRACE_MS){
down.push(id);confirmed[id]=false; // sustained offline: alert once
}
}
}
if(up.length||down.length)emit(up,down);
}
function emit(up,down){
const now=Date.now()/1000;
[...up.map(id=>[id,true]),...down.map(id=>[id,false])].forEach(([id,on])=>
events.unshift({id,name:aliasOf(id),on,t:now}));
events=events.slice(0,60);
unseen+=up.length+down.length;
if($('#notif').classList.contains('hide'))updateBadge(); else {unseen=0;updateBadge();renderNotif();}
const msg=[up.length?'🟢 '+up.map(aliasOf).join(', ')+' came online':'',
down.length?'🔴 '+down.map(aliasOf).join(', ')+' went offline':''].filter(Boolean).join(' ');
toast(msg,down.length>0&&!up.length);
if(soundOn){if(up.length)beep('up');if(down.length)setTimeout(()=>beep('down'),up.length?260:0);}
if(deskOn)desktopNotify(up.map(aliasOf),down.map(aliasOf));
}
function beep(kind){
try{
audioCtx=audioCtx||new (window.AudioContext||window.webkitAudioContext)();
if(audioCtx.state==='suspended')audioCtx.resume();
const o=audioCtx.createOscillator(),g=audioCtx.createGain(),t=audioCtx.currentTime;
o.type='sine';o.connect(g);g.connect(audioCtx.destination);
if(kind==='up'){o.frequency.setValueAtTime(620,t);o.frequency.exponentialRampToValueAtTime(940,t+0.12);}
else{o.frequency.setValueAtTime(480,t);o.frequency.exponentialRampToValueAtTime(280,t+0.16);}
g.gain.setValueAtTime(0.0001,t);g.gain.exponentialRampToValueAtTime(0.16,t+0.02);
g.gain.exponentialRampToValueAtTime(0.0001,t+0.3);
o.start(t);o.stop(t+0.32);
}catch(e){}
}
function desktopNotify(up,down){
if(!('Notification'in window)||Notification.permission!=='granted')return;
const parts=[];if(up.length)parts.push('Online: '+up.join(', '));if(down.length)parts.push('Offline: '+down.join(', '));
try{new Notification('RustDesk Address Book',{body:parts.join('\n')});}catch(e){}
}
function updateBadge(){
const b=$('#badge');b.textContent=unseen>99?'99+':unseen;b.classList.toggle('show',unseen>0);
if('setAppBadge'in navigator){ // red count on the Dock icon (installed web app)
try{unseen>0?navigator.setAppBadge(unseen):navigator.clearAppBadge();}catch(e){}
}
}
function renderNotif(){
const l=$('#nlist');
if(!events.length){l.innerHTML='<div class="nempty">No status changes yet</div>';return;}
l.innerHTML='';
events.forEach(e=>{
const r=el('div','nrow '+(e.on?'up':'down'));
r.innerHTML=`<span class="ndot"></span><span class="nname">${esc(e.name)}</span>`+
`<span class="nwhen">${e.on?'online':'offline'} · ${ago(e.t)}</span>`;
l.appendChild(r);
});
}
let toastT;
function toast(msg,warn){const t=$('#toast');t.textContent=msg;t.classList.toggle('warn',!!warn);
t.classList.add('show');clearTimeout(toastT);toastT=setTimeout(()=>t.classList.remove('show'),3200);}
async function resync(){
const b=$('#resync');b.disabled=true;b.classList.add('spin');
try{
const r=await api('POST','/api/resync');book=r.book;render();refreshStatus();
const n=r.added.length;
toast(n?`Added ${n}: ${r.added.map(p=>p.alias).join(', ')}`:'Already up to date — no new machines',!n);
}catch(e){toast('Re-sync failed: '+e.message,true);}
finally{b.disabled=false;b.classList.remove('spin');}
}
const POPS=['#notif','#moremenu','#sortmenu','#cmenu'];
function closePops(){POPS.forEach(p=>$(p).classList.add('hide'));}
function togglePop(id){const willOpen=$(id).classList.contains('hide');closePops();if(willOpen)$(id).classList.remove('hide');return willOpen;}
const saveCollapsed=()=>localStorage.setItem('rdab_collapsed',JSON.stringify([...collapsed]));
// ---- overflow menu: sort / collapse / new tag / help ----
function markSort(){document.querySelectorAll('.msort').forEach(b=>b.classList.toggle('active',b.dataset.v===sortMode));}
document.querySelectorAll('.msort').forEach(b=>b.onclick=()=>{
sortMode=b.dataset.v;localStorage.setItem('rdab_sort',sortMode);markSort();render();closePops();});
markSort();
$('#m-expand').onclick=()=>{collapsed.clear();saveCollapsed();applyCollapse();closePops();};
$('#m-collapse').onclick=()=>{[...(book.tags||[]),'__untagged__'].forEach(k=>collapsed.add(k));saveCollapsed();applyCollapse();closePops();};
$('#m-newtag').onclick=()=>{closePops();newTag();};
$('#m-help').onclick=()=>{closePops();$('#helpback').classList.add('show');};
$('#help-ok').onclick=()=>$('#helpback').classList.remove('show');
$('#helpback').addEventListener('mousedown',e=>{if(e.target.id==='helpback')$('#helpback').classList.remove('show');});
// ---- notifications + menu popovers ----
function syncTogs(){$('#t-sound').classList.toggle('on',soundOn);$('#t-desk').classList.toggle('on',deskOn);}
syncTogs();updateBadge();
$('#bell').onclick=e=>{e.stopPropagation();if(togglePop('#notif')){unseen=0;updateBadge();renderNotif();}};
$('#menu').onclick=e=>{e.stopPropagation();togglePop('#moremenu');};
$('#sortbtn').onclick=e=>{e.stopPropagation();togglePop('#sortmenu');};
$('#t-sound').onclick=()=>{soundOn=!soundOn;localStorage.setItem('rdab_sound',soundOn?'1':'0');syncTogs();if(soundOn)beep('up');};
$('#t-desk').onclick=async()=>{
if(!deskOn){
if(!('Notification'in window)){toast('Desktop notifications not supported here',true);return;}
const p=await Notification.requestPermission();
if(p!=='granted'){toast('Desktop notifications blocked by browser',true);return;}
}
deskOn=!deskOn;localStorage.setItem('rdab_desk',deskOn?'1':'0');syncTogs();
};
$('#nclear').onclick=()=>{events=[];unseen=0;updateBadge();renderNotif();};
document.addEventListener('click',e=>{if(!e.target.closest('#notif,#moremenu,#sortmenu,#cmenu,#bell,#menu,#sortbtn'))closePops();});
$('#q').addEventListener('input',applyFilter);
$('#resync').onclick=resync;
$('#add').onclick=()=>openForm(null);
$('#f-cancel').onclick=closeForm;$('#f-save').onclick=saveForm;
$('#f-server').onchange=toggleNewSrv;
let downOnBackdrop=false; // only close if the press STARTED on the backdrop
$('#backdrop').addEventListener('mousedown',e=>{downOnBackdrop=e.target.id==='backdrop';});
$('#backdrop').addEventListener('click',e=>{if(e.target.id==='backdrop'&&downOnBackdrop)closeForm();});
document.addEventListener('keydown',e=>{if(e.key!=='Escape')return;
if($('#backdrop').classList.contains('show'))closeForm();
$('#helpback').classList.remove('show');closePops();});
load().then(refreshStatus);
setInterval(refreshStatus,POLL_MS);
</script></body></html>