Starchik1 commited on
Commit
76ff551
·
verified ·
1 Parent(s): ae6d795

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +1248 -18
index.html CHANGED
@@ -1,19 +1,1249 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
19
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  <!doctype html>
2
+ <html lang="ru">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>LocalDrop — локальная передача файлов</title>
7
+ <style>
8
+ :root{
9
+ --bg:#f8fafc;--text:#0f172a;--muted:#64748b;--muted-2:#94a3b8;--label:#475569;
10
+ --heading-hover:#1e293b;--card-bg:#ffffff;--border:#e2e8f0;--border-soft:#f1f5f9;
11
+ --input-bg:#f8fafc;--input-text:#1e293b;--code-bg:#f8fafc;
12
+ --accent:#0ea5e9;--accent-soft-bg:#f0f9ff;--accent-soft-border:#7dd3fc;
13
+ --green:#10b981;--green-soft-bg:#ecfdf5;--green-soft-border:#6ee7b7;--green-strong:#059669;
14
+ --amber:#f59e0b;--red:#ef4444;--red-hover:#fb7185;
15
+ --shadow-sm:rgba(15,23,42,.05);--shadow-md:rgba(15,23,42,.10);--shadow-lg:rgba(15,23,42,.25);
16
+ --overlay-bg:rgba(15,23,42,.45);--switch-track:#e2e8f0;--switch-thumb:#ffffff;
17
+ --disabled-bg:#e2e8f0;--disabled-text:#94a3b8;--peer-chip-text:#334155;--remove-color:#cbd5e1;
18
+ font-family:Inter,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
19
+ color:var(--text);background:var(--bg);font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased
20
+ }
21
+ [data-theme="dark"]{
22
+ --bg:#0a0f1c;--text:#e5e9f0;--muted:#8b96a8;--muted-2:#606b7d;--label:#c3cad6;
23
+ --heading-hover:#ffffff;--card-bg:#131b2c;--border:#25324a;--border-soft:#1c2536;
24
+ --input-bg:#0f1727;--input-text:#e5e9f0;--code-bg:#0f1727;
25
+ --accent:#38bdf8;--accent-soft-bg:#0f2438;--accent-soft-border:#1c4966;
26
+ --green:#34d399;--green-soft-bg:#0d2a20;--green-soft-border:#155e42;--green-strong:#34d399;
27
+ --amber:#fbbf24;--red:#f87171;--red-hover:#fca5a5;
28
+ --shadow-sm:rgba(0,0,0,.3);--shadow-md:rgba(0,0,0,.4);--shadow-lg:rgba(0,0,0,.5);
29
+ --overlay-bg:rgba(0,0,0,.6);--switch-track:#28334a;--switch-thumb:#e5e9f0;
30
+ --disabled-bg:#1c2536;--disabled-text:#5b6577;--peer-chip-text:#c3cad6;--remove-color:#3d4b64;
31
+ }
32
+ *{box-sizing:border-box}
33
+ body{margin:0;min-width:320px;min-height:100vh;background:var(--bg);color:var(--text);transition:background .2s,color .2s}
34
+ .app-shell{min-height:100vh}
35
+ .screen{position:relative;min-height:100vh;width:min(100% - 32px,672px);margin:0 auto;padding:24px 0}
36
+ .icon-button{position:absolute;top:24px;right:0;width:40px;height:40px;border-radius:12px;border:1px solid var(--border);background:var(--card-bg);display:grid;place-items:center;color:var(--muted);cursor:pointer;transition:.2s;padding:0}
37
+ .icon-button:hover{color:var(--accent);border-color:var(--accent-soft-border)}
38
+ .icon-button svg{width:20px;height:20px}
39
+ .home{display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center}
40
+ .brand{margin-bottom:48px}
41
+ .brand-row{display:flex;align-items:center;justify-content:center;gap:12px;margin-bottom:16px}
42
+ .logo{width:48px;height:48px;border-radius:18px;background:var(--accent);display:grid;place-items:center;color:white;box-shadow:0 12px 28px rgba(14,165,233,.3)}
43
+ .logo svg,.tile-icon svg,.icon svg{width:28px;height:28px}
44
+ h1{font-size:30px;line-height:36px;margin:0;font-weight:800;letter-spacing:-.025em}
45
+ h2{font-size:24px;line-height:32px;margin:0;font-weight:800}
46
+ .muted{color:var(--muted)}
47
+ .brand p{font-size:18px;line-height:28px;max-width:430px;margin:0}
48
+ .tiles{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px;width:100%;max-width:576px}
49
+ .tile{position:relative;display:flex;flex-direction:column;align-items:center;gap:16px;padding:32px;border:1px solid var(--border);border-radius:28px;background:var(--card-bg);box-shadow:0 1px 2px var(--shadow-sm);cursor:pointer;transition:.2s;color:inherit;font:inherit}
50
+ .tile:hover{transform:translateY(-4px);box-shadow:0 20px 32px var(--shadow-md)}
51
+ .tile:focus-visible,.button:focus-visible,.back:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible{outline:3px solid rgba(14,165,233,.35);outline-offset:2px}
52
+ .tile-icon{width:64px;height:64px;border-radius:18px;display:grid;place-items:center}
53
+ .tile.send:hover{border-color:var(--accent-soft-border)}
54
+ .tile.receive:hover{border-color:var(--green-soft-border)}
55
+ .tile.send .tile-icon{background:var(--accent-soft-bg);color:var(--accent)}
56
+ .tile.receive .tile-icon{background:var(--green-soft-bg);color:var(--green)}
57
+ .tile-title{font-size:20px;font-weight:700;margin-bottom:4px}
58
+ .tile-desc,.tiny{font-size:14px;color:var(--muted)}
59
+ .footnote{margin-top:24px;font-size:12px;color:var(--muted-2);max-width:430px}
60
+ .back{display:inline-flex;align-items:center;gap:8px;border:0;background:transparent;color:var(--muted);font-weight:600;font-size:14px;padding:0;margin-bottom:24px;cursor:pointer}
61
+ .back:hover{color:var(--heading-hover)}
62
+ .header{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:24px}
63
+ .badge{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:700}
64
+ .dot{width:8px;height:8px;border-radius:999px;background:currentColor}
65
+ .idle{color:var(--muted-2)}
66
+ .waiting{color:var(--amber)}
67
+ .signaling,.connecting{color:var(--accent)}
68
+ .connected,.done{color:var(--green)}
69
+ .error,.disconnected{color:var(--red)}
70
+ .pulse{animation:pulse 1.4s ease-in-out infinite}
71
+ @keyframes pulse{50%{opacity:.35}}
72
+ .card{background:var(--card-bg);border:1px solid var(--border-soft);border-radius:28px;box-shadow:0 1px 2px var(--shadow-sm);padding:24px;margin-bottom:20px}
73
+ .settings-card{width:100%;max-width:576px;margin-top:20px;text-align:left}
74
+ .settings-card>*:first-child{margin-top:0}
75
+ .section-title{font-size:12px;font-weight:800;color:var(--muted-2);text-transform:uppercase;letter-spacing:.04em;margin-bottom:14px}
76
+ .field-group{display:flex;flex-direction:column;gap:8px;margin:8px 0 10px}
77
+ .field-group .plain-input{margin:0}
78
+ .center{text-align:center}
79
+ .code-row{display:flex;justify-content:center;gap:8px;margin:12px 0}
80
+ .code-char{width:44px;height:56px;display:grid;place-items:center;border:1px solid var(--border);border-radius:12px;background:var(--code-bg);font-size:24px;font-weight:800}
81
+ .drop{border:2px dashed var(--border);border-radius:28px;padding:40px;display:flex;flex-direction:column;align-items:center;gap:12px;cursor:pointer;transition:.2s;margin-bottom:20px}
82
+ .drop:hover,.drop.drag{border-color:var(--accent);background:var(--accent-soft-bg)}
83
+ .hidden{display:none!important}
84
+ .queue,.files{display:flex;flex-direction:column;gap:12px;margin-bottom:20px}
85
+ .file-row{display:flex;align-items:center;gap:12px;background:var(--card-bg);border:1px solid var(--border-soft);border-radius:18px;padding:12px;box-shadow:0 1px 2px var(--shadow-sm)}
86
+ .file-main{min-width:0;flex:1}
87
+ .file-name{font-size:14px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
88
+ .remove{border:0;background:transparent;color:var(--remove-color);font-size:22px;cursor:pointer}
89
+ .remove:hover{color:var(--red-hover)}
90
+ .button{width:100%;border:0;border-radius:18px;padding:16px 18px;color:white;font-weight:800;font-size:16px;cursor:pointer;transition:.2s;display:inline-flex;align-items:center;justify-content:center;gap:8px;margin-top:14px}
91
+ .button.sky{background:var(--accent);box-shadow:0 14px 28px rgba(14,165,233,.28)}
92
+ .button.green{background:var(--green);box-shadow:0 14px 28px rgba(16,185,129,.28)}
93
+ .button:hover:not(:disabled){filter:brightness(.96);transform:translateY(-1px)}
94
+ .button:disabled{background:var(--disabled-bg);color:var(--disabled-text);box-shadow:none;cursor:not-allowed}
95
+ input,textarea,select{width:100%;border:2px solid var(--border);background:var(--input-bg);color:var(--input-text);font:inherit;padding:12px;border-radius:16px;transition:border-color .2s}
96
+ #roomInput{text-align:center;font-size:30px;font-weight:800;letter-spacing:.22em;text-transform:uppercase;margin-top:20px}
97
+ .plain-input{text-align:left;font-size:14px;font-weight:500;letter-spacing:0;text-transform:none;margin:8px 0 10px}
98
+ .field-label{display:block;font-size:13px;font-weight:800;color:var(--label)}
99
+ .field-divider{height:1px;background:var(--border-soft);margin:18px 0}
100
+ .check-row{display:flex;align-items:center;gap:10px;font-size:14px;font-weight:700;color:var(--label);margin:8px 0 10px}
101
+ .check-row input{width:18px;height:18px;margin:0;accent-color:var(--accent)}
102
+ .switch-row{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:14px 0;cursor:pointer}
103
+ .switch-label{display:flex;flex-direction:column;gap:2px}
104
+ .switch{position:relative;display:inline-block;width:44px;height:26px;flex:0 0 auto}
105
+ .switch input{opacity:0;width:0;height:0;position:absolute}
106
+ .switch-slider{position:absolute;inset:0;background:var(--switch-track);transition:.2s;border-radius:999px}
107
+ .switch-slider:before{content:"";position:absolute;height:20px;width:20px;left:3px;top:3px;background:var(--switch-thumb);transition:.2s;border-radius:50%;box-shadow:0 1px 2px var(--shadow-sm)}
108
+ .switch input:checked+.switch-slider{background:var(--green)}
109
+ .switch input:checked+.switch-slider:before{transform:translateX(18px)}
110
+ .switch input:focus-visible+.switch-slider{outline:3px solid rgba(14,165,233,.35);outline-offset:2px}
111
+ .peer-list{display:flex;flex-direction:column;gap:8px;margin-top:10px}
112
+ .peer-button{text-align:left}
113
+ .peer-quick{margin-top:20px;padding-top:16px;border-top:1px solid var(--border-soft)}
114
+ .peer-quick-label{font-size:12px;font-weight:800;color:var(--muted-2);text-transform:uppercase;letter-spacing:.04em;margin-bottom:10px}
115
+ .peer-chips{display:flex;flex-wrap:wrap;gap:8px;justify-content:center}
116
+ .peer-chip{border:1px solid var(--border);background:var(--input-bg);color:var(--peer-chip-text);border-radius:999px;padding:8px 16px;font-size:13px;font-weight:700;cursor:pointer;transition:.15s}
117
+ .peer-chip:hover{background:var(--accent-soft-bg);border-color:var(--accent-soft-border);color:var(--accent)}
118
+ .advanced-settings{margin-top:10px}
119
+ .advanced-settings summary{cursor:pointer;font-size:13px;font-weight:800;color:var(--muted)}
120
+ .small-button{border:1px solid var(--border);background:var(--card-bg);color:var(--label);border-radius:12px;padding:9px 12px;font-weight:700;cursor:pointer}
121
+ .small-button:hover{background:var(--input-bg)}
122
+ .small-button:disabled{opacity:.5;cursor:not-allowed;pointer-events:none}
123
+ .settings-card .small-button{width:100%;margin:4px 0 10px}
124
+ .progress{height:6px;background:var(--border-soft);border-radius:999px;overflow:hidden;margin-top:10px}
125
+ .bar{height:100%;width:0;background:linear-gradient(90deg,#38bdf8,#0ea5e9);border-radius:999px}
126
+ .done .bar{width:100%;background:#34d399}
127
+ .download{color:var(--green-strong);text-decoration:none;font-weight:800;font-size:13px;background:var(--green-soft-bg);padding:7px 10px;border-radius:12px}
128
+ .status-text{font-size:12px;color:var(--muted);margin-top:6px;text-align:right}
129
+ .notice{font-size:13px;line-height:20px;color:var(--muted);background:var(--input-bg);border-radius:16px;padding:12px;margin-bottom:20px}
130
+ .error-box{color:var(--red);font-size:14px;margin-top:8px}
131
+ .invite-overlay{position:fixed;inset:0;background:var(--overlay-bg);display:flex;align-items:center;justify-content:center;padding:20px;z-index:50}
132
+ .invite-card{background:var(--card-bg);border-radius:28px;padding:28px;max-width:360px;width:100%;text-align:center;box-shadow:0 20px 60px var(--shadow-lg)}
133
+ .invite-card h3{margin:0 0 8px;font-size:20px;font-weight:800}
134
+ .invite-actions{display:flex;flex-direction:column;gap:10px;margin-top:18px}
135
+ .invite-actions .button{margin-top:0}
136
+ .invite-actions .small-button{width:100%}
137
+ @media(max-width:640px){
138
+ .tiles{grid-template-columns:1fr}
139
+ .screen{width:min(100% - 24px,672px)}
140
+ .header{align-items:flex-start;flex-direction:column}
141
+ .code-char{width:38px;height:50px}
142
+ .small-button{width:100%}
143
+ }
144
+
145
+ </style>
146
+ </head>
147
+ <body>
148
+ <main id="app" class="app-shell"></main>
149
+ <script>
150
+ const CHUNK_SIZE = 64 * 1024;
151
+ const ICE_SERVERS = [
152
+ { urls: 'stun:stun.l.google.com:19302' },
153
+ { urls: 'stun:stun1.l.google.com:19302' },
154
+ { urls: 'stun:stun.cloudflare.com:3478' },
155
+ { urls: 'stun:stun.nextcloud.com:443' },
156
+ { urls: 'stun:stun.sipgate.net:3478' },
157
+ { urls: 'stun:stun.ekiga.net:3478' }
158
+ ];
159
+ const DEFAULT_SIGNAL_URL = 'wss://test.mosquitto.org:8081/mqtt';
160
+ const SIGNAL_RELAYS = [
161
+ 'wss://test.mosquitto.org:8081/mqtt',
162
+ 'wss://broker.emqx.io:8084/mqtt',
163
+ 'wss://broker.hivemq.com:8884/mqtt',
164
+ 'wss://public.mqtthq.com:8084/mqtt'
165
+ ];
166
+ const SIGNAL_TOPIC_PREFIX = 'localdrop/v2';
167
+ const SETTINGS_KEY = 'localdrop.settings.v2';
168
+
169
+ const TRANSLATIONS = {
170
+ ru: {
171
+ pageTitle: 'LocalDrop — локальная передача файлов',
172
+ appSubtitle: 'Передавайте файлы между устройствами по 6-значному коду.',
173
+ tileSendTitle: 'Отправить',
174
+ tileSendDesc: 'Создать код и ждать получателя',
175
+ tileReceiveTitle: 'Получить',
176
+ tileReceiveDesc: 'Ввести код и подключиться',
177
+ homeFootnote: 'После первого подключения устройства запомнят друг друга.',
178
+ settingsTitle: 'Настройки',
179
+ sectionDevice: 'Устройство',
180
+ deviceNameLabel: 'Имя этого устройства',
181
+ rememberLabel: 'Запомнить это устройство',
182
+ rememberTiny: 'Сохраняет настройки и список устройств в этом браузере.',
183
+ resetPeersButton: 'Сбросить сохранённые подключения',
184
+ resetPeersTiny: 'Забыть список запомненных устройств для быстрой отправки.',
185
+ resetPeersEmpty: 'Нет сохранённых устройств.',
186
+ resetPeersConfirm: 'Забыть все сохранённые устройства?',
187
+ resetPeersDone: 'Список сохранённых устройств очищен.',
188
+ sectionReceiving: 'Приём файлов',
189
+ autoAcceptLabel: 'Подключаться без подтверждения',
190
+ autoAcceptTiny: 'Запомненные устройства подключаются сразу, без запроса.',
191
+ autoDownloadLabel: 'Скачивать файлы автоматически',
192
+ autoDownloadTiny: 'Иначе — кнопка «Скачать» рядом с файлом.',
193
+ sectionAppearance: 'Оформление',
194
+ darkThemeLabel: 'Тёмная тема',
195
+ darkThemeTiny: 'Переключить оформление приложения.',
196
+ languageLabel: 'Язык',
197
+ languageTiny: 'Язык интерфейса приложения.',
198
+ langRu: 'Русский',
199
+ langEn: 'English',
200
+ sectionConnection: 'Соединение',
201
+ stunLabel: 'STUN-сервер',
202
+ stunAuto: 'Автоматически (перебрать все)',
203
+ stunTiny: 'Помогает найти прямой путь между устройствами.',
204
+ turnLabel: 'TURN-сервер (для передачи не в одной сети)',
205
+ turnTiny: 'Нужен, если получатель в другой сети (мобильный интернет, VPN, строгий NAT) и прямое соединение невозможно.',
206
+ turnUsernamePlaceholder: 'Логин',
207
+ turnPasswordPlaceholder: 'Пароль',
208
+ fillTestTurnButton: 'Подставить бесплатный тестовый TURN',
209
+ fillTestTurnTiny: 'Тестовый сервер общий и не для постоянного использования — лучше завести свой (coturn, Metered, Twilio, Xirsys).',
210
+ advancedSummary: 'Дополнительно',
211
+ relayTiny: 'Relay для авто-поиска устройств. При недоступности используются резервные серверы.',
212
+ settingsFootnote: 'Изменения сохраняются автоматически.',
213
+ backButton: 'Назад',
214
+ sendTitle: 'Отправить файлы',
215
+ sendCodeHint: 'Код комнаты — введите его на устройстве получателя',
216
+ sendDirectHint: 'Отправляем приглашение на {name}.',
217
+ sendManualHint: 'Получатель подключится автоматически после ввода кода.',
218
+ quickSendLabel: 'Быстрая отправка',
219
+ searchingStatus: 'Запускаем поиск...',
220
+ dropTitle: 'Перетащите файлы сюда',
221
+ dropSubtitle: 'или нажмите для выбора',
222
+ waitingReceiverButton: 'Ожидание получателя...',
223
+ sendFilesButton: 'Отправить файлы',
224
+ inviteSentStatus: 'Приглашение отправлено на {name}.',
225
+ waitingCodeStatus: 'Ждём получателя по коду.',
226
+ localModeStatus: 'Локальный режим — работает только между вкладками этого браузера.',
227
+ receiveTitle: 'Получить файлы',
228
+ receiveHint: 'Введите код с экрана отправителя.',
229
+ connectButton: 'Подключиться',
230
+ waitingCodeInputStatus: 'Ожидание кода комнаты.',
231
+ deviceLabel: 'Устройство:',
232
+ establishingStatus: 'Устанавливаем соединение...',
233
+ connectedToStatus: 'Подключено к {name}. Ждём файлы...',
234
+ incomingTransferTitle: 'Входящая передача',
235
+ incomingTransferDesc: '{name} хочет отправить вам файлы.',
236
+ declineButton: 'Отклонить',
237
+ unknownDevice: 'Неизвестное устройство',
238
+ rememberedDevice: 'Запомненное устройство',
239
+ codeErrorStatus: 'Код должен состоять из 6 символов.',
240
+ roomFoundStatus: 'Комната найдена, ждём подключения.',
241
+ localModeReceiveStatus: 'Локальный режим — только между вкладками этого браузера.',
242
+ doneStatusText: 'Готово',
243
+ downloadLink: 'Скачать',
244
+ badgeIdle: 'Не подключено',
245
+ badgeWaiting: 'Ожидание получателя...',
246
+ badgeSignaling: 'Авто-поиск...',
247
+ badgeConnecting: 'Подключение...',
248
+ badgeConnected: 'Подключено',
249
+ badgeDone: 'Передача завершена',
250
+ badgeDisconnected: 'Соединение прервано',
251
+ badgeError: 'Ошибка соединения',
252
+ settingsButtonTitle: 'Настройки',
253
+ signalTimeout: 'Таймаут подключения: {url}',
254
+ signalConnError: 'Ошибка подключения: {url}',
255
+ signalClosed: 'Соединение закрыто: {url}',
256
+ signalAllFailed: 'Не удалось подключиться ни к одному signaling relay',
257
+ byteUnits: ['Б', 'КБ', 'МБ', 'ГБ']
258
+ },
259
+ en: {
260
+ pageTitle: 'LocalDrop — local file transfer',
261
+ appSubtitle: 'Send files between devices using a 6-character code.',
262
+ tileSendTitle: 'Send',
263
+ tileSendDesc: 'Create a code and wait for a receiver',
264
+ tileReceiveTitle: 'Receive',
265
+ tileReceiveDesc: 'Enter a code and connect',
266
+ homeFootnote: 'After the first connection, devices will remember each other.',
267
+ settingsTitle: 'Settings',
268
+ sectionDevice: 'Device',
269
+ deviceNameLabel: 'Name of this device',
270
+ rememberLabel: 'Remember this device',
271
+ rememberTiny: 'Saves settings and the device list in this browser.',
272
+ resetPeersButton: 'Reset saved connections',
273
+ resetPeersTiny: 'Forget the list of remembered devices used for quick sending.',
274
+ resetPeersEmpty: 'No saved devices yet.',
275
+ resetPeersConfirm: 'Forget all saved devices?',
276
+ resetPeersDone: 'Saved devices list cleared.',
277
+ sectionReceiving: 'Receiving files',
278
+ autoAcceptLabel: 'Connect without confirmation',
279
+ autoAcceptTiny: 'Remembered devices connect right away, without asking.',
280
+ autoDownloadLabel: 'Download files automatically',
281
+ autoDownloadTiny: 'Otherwise use the "Download" button next to the file.',
282
+ sectionAppearance: 'Appearance',
283
+ darkThemeLabel: 'Dark theme',
284
+ darkThemeTiny: 'Switch the app’s appearance.',
285
+ languageLabel: 'Language',
286
+ languageTiny: 'Interface language.',
287
+ langRu: 'Русский',
288
+ langEn: 'English',
289
+ sectionConnection: 'Connection',
290
+ stunLabel: 'STUN server',
291
+ stunAuto: 'Automatic (try all)',
292
+ stunTiny: 'Helps find a direct path between devices.',
293
+ turnLabel: 'TURN server (for transfers across networks)',
294
+ turnTiny: 'Needed if the receiver is on a different network (mobile data, VPN, strict NAT) and a direct connection isn’t possible.',
295
+ turnUsernamePlaceholder: 'Username',
296
+ turnPasswordPlaceholder: 'Password',
297
+ fillTestTurnButton: 'Fill in a free test TURN server',
298
+ fillTestTurnTiny: 'The test server is shared and not for permanent use — better to set up your own (coturn, Metered, Twilio, Xirsys).',
299
+ advancedSummary: 'Advanced',
300
+ relayTiny: 'Relay used for device discovery. Backup servers are tried automatically if it’s unavailable.',
301
+ settingsFootnote: 'Changes are saved automatically.',
302
+ backButton: 'Back',
303
+ sendTitle: 'Send files',
304
+ sendCodeHint: 'Room code — enter it on the receiver’s device',
305
+ sendDirectHint: 'Sending an invite to {name}.',
306
+ sendManualHint: 'The receiver will connect automatically once they enter the code.',
307
+ quickSendLabel: 'Quick send',
308
+ searchingStatus: 'Starting search...',
309
+ dropTitle: 'Drag files here',
310
+ dropSubtitle: 'or click to choose',
311
+ waitingReceiverButton: 'Waiting for receiver...',
312
+ sendFilesButton: 'Send files',
313
+ inviteSentStatus: 'Invite sent to {name}.',
314
+ waitingCodeStatus: 'Waiting for the receiver to enter the code.',
315
+ localModeStatus: 'Local mode — only works between tabs in this browser.',
316
+ receiveTitle: 'Receive files',
317
+ receiveHint: 'Enter the code from the sender’s screen.',
318
+ connectButton: 'Connect',
319
+ waitingCodeInputStatus: 'Waiting for a room code.',
320
+ deviceLabel: 'Device:',
321
+ establishingStatus: 'Establishing connection...',
322
+ connectedToStatus: 'Connected to {name}. Waiting for files...',
323
+ incomingTransferTitle: 'Incoming transfer',
324
+ incomingTransferDesc: '{name} wants to send you files.',
325
+ declineButton: 'Decline',
326
+ unknownDevice: 'Unknown device',
327
+ rememberedDevice: 'Remembered device',
328
+ codeErrorStatus: 'The code must be 6 characters long.',
329
+ roomFoundStatus: 'Room found, waiting to connect.',
330
+ localModeReceiveStatus: 'Local mode — only between tabs in this browser.',
331
+ doneStatusText: 'Done',
332
+ downloadLink: 'Download',
333
+ badgeIdle: 'Not connected',
334
+ badgeWaiting: 'Waiting for receiver...',
335
+ badgeSignaling: 'Searching...',
336
+ badgeConnecting: 'Connecting...',
337
+ badgeConnected: 'Connected',
338
+ badgeDone: 'Transfer complete',
339
+ badgeDisconnected: 'Connection lost',
340
+ badgeError: 'Connection error',
341
+ settingsButtonTitle: 'Settings',
342
+ signalTimeout: 'Connection timeout: {url}',
343
+ signalConnError: 'Connection error: {url}',
344
+ signalClosed: 'Connection closed: {url}',
345
+ signalAllFailed: 'Could not connect to any signaling relay',
346
+ byteUnits: ['B', 'KB', 'MB', 'GB']
347
+ }
348
+ };
349
+
350
+ const $ = (selector, root = document) => root.querySelector(selector);
351
+ const app = $('#app');
352
+
353
+ let pc = null;
354
+ let channel = null;
355
+ let signaling = null;
356
+ let deviceListener = null;
357
+ let queued = [];
358
+ let transfers = new Map();
359
+ let receiveBuffers = new Map();
360
+ let connectionState = 'idle';
361
+ let currentRole = null;
362
+
363
+ const icons = {
364
+ share: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.6 13.5 6.8 4M15.4 6.5l-6.8 4"/></svg>',
365
+ down: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 10l5 5 5-5"/><path d="M12 15V3"/></svg>',
366
+ back: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m12 19-7-7 7-7"/><path d="M19 12H5"/></svg>',
367
+ upload: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M16 16l-4-4-4 4"/><path d="M12 12v9"/><path d="M20.4 18.4A5 5 0 0 0 18 9h-1.3A8 8 0 1 0 4 16.3"/></svg>',
368
+ hash: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 9h16M4 15h16M10 3 8 21M16 3l-2 18"/></svg>',
369
+ send: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>',
370
+ gear: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z"/></svg>'
371
+ };
372
+
373
+ function detectLang() {
374
+ return (navigator.language || '').toLowerCase().startsWith('ru') ? 'ru' : 'en';
375
+ }
376
+
377
+ function t(key, vars = {}) {
378
+ const lang = loadSettings().lang === 'en' ? 'en' : 'ru';
379
+ const dict = TRANSLATIONS[lang] || TRANSLATIONS.ru;
380
+ let str = dict[key] ?? TRANSLATIONS.ru[key] ?? key;
381
+ Object.entries(vars).forEach(([k, v]) => { str = str.replaceAll(`{${k}}`, v); });
382
+ return str;
383
+ }
384
+
385
+ function defaultDeviceName() {
386
+ const platform = navigator.userAgentData?.platform || navigator.platform || 'device';
387
+ return detectLang() === 'en' ? `My ${platform}` : `Моё ${platform}`;
388
+ }
389
+
390
+ function effectiveTheme(settings) {
391
+ if (settings.theme === 'dark' || settings.theme === 'light') return settings.theme;
392
+ return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
393
+ }
394
+
395
+ function applyPreferences(settings) {
396
+ document.documentElement.setAttribute('data-theme', effectiveTheme(settings));
397
+ document.documentElement.lang = settings.lang === 'en' ? 'en' : 'ru';
398
+ document.title = t('pageTitle');
399
+ }
400
+
401
+ function loadSettings() {
402
+ try {
403
+ const saved = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}');
404
+ return {
405
+ remember: true,
406
+ deviceId: saved.deviceId || crypto.randomUUID(),
407
+ deviceName: saved.deviceName || defaultDeviceName(),
408
+ peers: Array.isArray(saved.peers) ? saved.peers : [],
409
+ ...saved,
410
+ signalUrl: saved.signalUrl || DEFAULT_SIGNAL_URL,
411
+ stunServer: saved.stunServer || 'auto',
412
+ turnUrl: saved.turnUrl || '',
413
+ turnUsername: saved.turnUsername || '',
414
+ turnCredential: saved.turnCredential || '',
415
+ autoAccept: saved.autoAccept || false,
416
+ autoDownload: saved.autoDownload ?? true,
417
+ theme: saved.theme || 'auto',
418
+ lang: saved.lang || detectLang()
419
+ };
420
+ } catch {
421
+ return {
422
+ remember: true, deviceId: crypto.randomUUID(), deviceName: defaultDeviceName(), peers: [],
423
+ signalUrl: DEFAULT_SIGNAL_URL, stunServer: 'auto', turnUrl: '', turnUsername: '', turnCredential: '',
424
+ autoAccept: false, autoDownload: true, theme: 'auto', lang: detectLang()
425
+ };
426
+ }
427
+ }
428
+
429
+ function saveSettings(settings) {
430
+ if (settings.remember) {
431
+ localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
432
+ } else {
433
+ localStorage.removeItem(SETTINGS_KEY);
434
+ }
435
+ }
436
+
437
+ function savePeer(peer) {
438
+ if (!peer?.deviceId) return;
439
+ const settings = loadSettings();
440
+ const nextPeer = { id: peer.deviceId, name: peer.deviceName || t('rememberedDevice'), lastSeen: Date.now() };
441
+ settings.peers = [nextPeer, ...settings.peers.filter((item) => item.id !== nextPeer.id)].slice(0, 8);
442
+ saveSettings(settings);
443
+ }
444
+
445
+ function localPeerInfo() {
446
+ const settings = loadSettings();
447
+ return { deviceId: settings.deviceId, deviceName: settings.deviceName };
448
+ }
449
+
450
+ function escapeHtml(value) {
451
+ return String(value).replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]));
452
+ }
453
+
454
+ function formatBytes(bytes) {
455
+ const units = t('byteUnits');
456
+ if (!bytes) return `0 ${units[0]}`;
457
+ const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
458
+ return `${(bytes / 1024 ** index).toFixed(index ? 1 : 0)} ${units[index]}`;
459
+ }
460
+
461
+ function generateRoomCode() {
462
+ return Math.random().toString(36).replace(/[^a-z0-9]/gi, '').slice(2, 8).toUpperCase().padEnd(6, 'X');
463
+ }
464
+
465
+ function badge() {
466
+ const labels = {
467
+ idle: t('badgeIdle'),
468
+ waiting: t('badgeWaiting'),
469
+ signaling: t('badgeSignaling'),
470
+ connecting: t('badgeConnecting'),
471
+ connected: t('badgeConnected'),
472
+ done: t('badgeDone'),
473
+ disconnected: t('badgeDisconnected'),
474
+ error: t('badgeError')
475
+ };
476
+ const pulse = ['waiting', 'signaling', 'connecting'].includes(connectionState) ? ' pulse' : '';
477
+ return `<div class="badge ${connectionState}"><span class="dot${pulse}"></span>${labels[connectionState]}</div>`;
478
+ }
479
+
480
+ function setConnectionState(nextState) {
481
+ connectionState = nextState;
482
+ const current = $('.badge');
483
+ if (current) current.outerHTML = badge();
484
+ }
485
+
486
+ function showStatus(message, type = 'notice') {
487
+ const status = $('#status');
488
+ if (status) {
489
+ status.className = type;
490
+ status.textContent = message;
491
+ }
492
+ }
493
+
494
+ function encodeText(value) {
495
+ return new TextEncoder().encode(value);
496
+ }
497
+
498
+ function decodeText(value) {
499
+ return new TextDecoder().decode(value);
500
+ }
501
+
502
+ function encodeRemainingLength(length) {
503
+ const bytes = [];
504
+ do {
505
+ let byte = length % 128;
506
+ length = Math.floor(length / 128);
507
+ if (length > 0) byte |= 128;
508
+ bytes.push(byte);
509
+ } while (length > 0);
510
+ return bytes;
511
+ }
512
+
513
+ function mqttString(value) {
514
+ const bytes = encodeText(value);
515
+ return [bytes.length >> 8, bytes.length & 255, ...bytes];
516
+ }
517
+
518
+ function mqttPacket(type, body = []) {
519
+ return new Uint8Array([type, ...encodeRemainingLength(body.length), ...body]);
520
+ }
521
+
522
+ class LocalSignaling {
523
+ constructor({ roomCode, role, signalUrl, onSignal }) {
524
+ this.roomCode = roomCode;
525
+ this.role = role;
526
+ this.signalUrl = signalUrl || DEFAULT_SIGNAL_URL;
527
+ this.onSignal = onSignal;
528
+ this.clientId = crypto.randomUUID();
529
+ this.topic = `${SIGNAL_TOPIC_PREFIX}/${roomCode.toLowerCase()}`;
530
+ this.channel = null;
531
+ this.socket = null;
532
+ this.ready = false;
533
+ this.queue = [];
534
+ this.keepAliveTimer = null;
535
+ this.packetId = 1;
536
+ }
537
+
538
+ connect() {
539
+ if (this.signalUrl === 'browser') return this.connectBroadcastChannel();
540
+ const preferred = this.signalUrl || DEFAULT_SIGNAL_URL;
541
+ const candidates = [preferred, ...SIGNAL_RELAYS.filter((url) => url !== preferred)];
542
+ return this.connectWithFallback(candidates);
543
+ }
544
+
545
+ async connectWithFallback(candidates) {
546
+ let lastError;
547
+ for (const url of candidates) {
548
+ try {
549
+ const result = await this.connectMqttWebSocket(url);
550
+ this.signalUrl = url;
551
+ return result;
552
+ } catch (error) {
553
+ lastError = error;
554
+ console.warn(`Signaling relay unavailable (${url}):`, error.message);
555
+ }
556
+ }
557
+ throw lastError || new Error(t('signalAllFailed'));
558
+ }
559
+
560
+ connectBroadcastChannel() {
561
+ this.channel = new BroadcastChannel(`localdrop:${this.roomCode}`);
562
+ this.channel.onmessage = (event) => this.receive(event.data);
563
+ this.ready = true;
564
+ this.flush();
565
+ return Promise.resolve('browser');
566
+ }
567
+
568
+ connectMqttWebSocket(url) {
569
+ return new Promise((resolve, reject) => {
570
+ let settled = false;
571
+ const settle = (fn, arg) => { if (!settled) { settled = true; clearTimeout(timeout); fn(arg); } };
572
+ const timeout = setTimeout(() => {
573
+ settle(reject, new Error(t('signalTimeout', { url })));
574
+ this.socket?.close();
575
+ }, 6000);
576
+
577
+ this.socket = new WebSocket(url, 'mqtt');
578
+ this.socket.binaryType = 'arraybuffer';
579
+
580
+ this.socket.onopen = () => {
581
+ const clientId = `localdrop-${this.clientId.slice(0, 18)}`;
582
+ const variableHeader = [...mqttString('MQTT'), 4, 2, 0, 60];
583
+ const payload = mqttString(clientId);
584
+ this.socket.send(mqttPacket(0x10, [...variableHeader, ...payload]));
585
+ };
586
+
587
+ this.socket.onmessage = (event) => {
588
+ const result = this.handleMqttPacket(new Uint8Array(event.data));
589
+ if (result === 'ready') settle(resolve, 'network');
590
+ };
591
+
592
+ this.socket.onerror = () => settle(reject, new Error(t('signalConnError', { url })));
593
+ this.socket.onclose = () => {
594
+ clearInterval(this.keepAliveTimer);
595
+ if (!settled) { settle(reject, new Error(t('signalClosed', { url }))); return; }
596
+ if (connectionState !== 'connected' && connectionState !== 'idle') setConnectionState('error');
597
+ };
598
+ });
599
+ }
600
+
601
+ handleMqttPacket(packet) {
602
+ const type = packet[0] >> 4;
603
+ let multiplier = 1;
604
+ let value = 0;
605
+ let offset = 1;
606
+ let encodedByte;
607
+
608
+ do {
609
+ encodedByte = packet[offset++];
610
+ value += (encodedByte & 127) * multiplier;
611
+ multiplier *= 128;
612
+ } while ((encodedByte & 128) !== 0);
613
+
614
+ if (type === 2) {
615
+ this.subscribe();
616
+ this.keepAliveTimer = setInterval(() => this.socket?.send(mqttPacket(0xc0)), 30000);
617
+ }
618
+
619
+ if (type === 9) {
620
+ this.ready = true;
621
+ this.sendRaw('join', {});
622
+ this.flush();
623
+ return 'ready';
624
+ }
625
+
626
+ if (type === 3) {
627
+ const topicLength = (packet[offset] << 8) + packet[offset + 1];
628
+ offset += 2;
629
+ const topic = decodeText(packet.slice(offset, offset + topicLength));
630
+ offset += topicLength;
631
+ if (topic !== this.topic) return null;
632
+
633
+ try {
634
+ this.receive(JSON.parse(decodeText(packet.slice(offset))));
635
+ } catch (error) {
636
+ console.warn('Signal parse error:', error);
637
+ }
638
+ }
639
+
640
+ return null;
641
+ }
642
+
643
+ subscribe() {
644
+ const id = this.packetId++;
645
+ const body = [id >> 8, id & 255, ...mqttString(this.topic), 0];
646
+ this.socket.send(mqttPacket(0x82, body));
647
+ }
648
+
649
+ send(type, payload) {
650
+ if (!this.ready) {
651
+ this.queue.push({ type, payload });
652
+ return;
653
+ }
654
+ this.sendRaw(type, payload);
655
+ }
656
+
657
+ sendRaw(type, payload) {
658
+ const message = { room: this.roomCode, from: this.role, clientId: this.clientId, type, payload };
659
+ if (this.socket?.readyState === WebSocket.OPEN) {
660
+ const payloadBytes = encodeText(JSON.stringify(message));
661
+ this.socket.send(mqttPacket(0x30, [...mqttString(this.topic), ...payloadBytes]));
662
+ }
663
+ if (this.channel) this.channel.postMessage(message);
664
+ }
665
+
666
+ flush() {
667
+ this.queue.splice(0).forEach((message) => this.sendRaw(message.type, message.payload));
668
+ }
669
+
670
+ receive(message) {
671
+ if (!message || message.room !== this.roomCode || message.clientId === this.clientId) return;
672
+ if (message.from === this.role) return;
673
+ this.onSignal(message.type, message.payload);
674
+ }
675
+
676
+ close() {
677
+ clearInterval(this.keepAliveTimer);
678
+ this.channel?.close();
679
+ this.socket?.close();
680
+ }
681
+ }
682
+
683
+ function reset() {
684
+ signaling?.close();
685
+ deviceListener?.close();
686
+ channel?.close();
687
+ pc?.close();
688
+ signaling = null;
689
+ deviceListener = null;
690
+ channel = null;
691
+ pc = null;
692
+ queued = [];
693
+ transfers.clear();
694
+ receiveBuffers.clear();
695
+ connectionState = 'idle';
696
+ currentRole = null;
697
+ }
698
+
699
+
700
+ function waitForIceGathering() {
701
+ return new Promise((resolve) => {
702
+ if (!pc || pc.iceGatheringState === 'complete') {
703
+ resolve();
704
+ return;
705
+ }
706
+
707
+ const finish = () => {
708
+ if (pc.iceGatheringState === 'complete') {
709
+ pc.removeEventListener('icegatheringstatechange', finish);
710
+ resolve();
711
+ }
712
+ };
713
+
714
+ pc.addEventListener('icegatheringstatechange', finish);
715
+ setTimeout(resolve, 2500);
716
+ });
717
+ }
718
+
719
+ function getIceServers() {
720
+ const settings = loadSettings();
721
+ const servers = settings.stunServer && settings.stunServer !== 'auto' ? [{ urls: settings.stunServer }] : [...ICE_SERVERS];
722
+ if (settings.turnUrl) {
723
+ servers.push({
724
+ urls: settings.turnUrl,
725
+ username: settings.turnUsername || undefined,
726
+ credential: settings.turnCredential || undefined
727
+ });
728
+ }
729
+ return servers;
730
+ }
731
+
732
+ function createPeerConnection() {
733
+ pc = new RTCPeerConnection({ iceServers: getIceServers() });
734
+
735
+ pc.onicecandidate = (event) => {
736
+ if (event.candidate) signaling?.send('ice-candidate', event.candidate.toJSON());
737
+ };
738
+
739
+ pc.onconnectionstatechange = () => {
740
+ const state = pc.connectionState;
741
+ if (state === 'connected') {
742
+ setConnectionState('connected');
743
+ return;
744
+ }
745
+ // Data is still flowing fine — ignore transient ICE-level blips (common over TURN/relay)
746
+ // that don't actually affect the already-open data channel.
747
+ if (channel?.readyState === 'open') return;
748
+ if (state === 'disconnected') {
749
+ setTimeout(() => {
750
+ if (pc.connectionState === 'disconnected' && channel?.readyState !== 'open') {
751
+ setConnectionState(allTransfersDone() ? 'done' : 'disconnected');
752
+ }
753
+ }, 4000);
754
+ return;
755
+ }
756
+ if (state === 'failed') setConnectionState(allTransfersDone() ? 'done' : 'error');
757
+ if (state === 'closed') setConnectionState(allTransfersDone() ? 'done' : 'disconnected');
758
+ };
759
+
760
+ return pc;
761
+ }
762
+
763
+ function setupDataChannel(nextChannel) {
764
+ channel = nextChannel;
765
+ channel.binaryType = 'arraybuffer';
766
+ channel.onopen = () => {
767
+ setConnectionState('connected');
768
+ channel.send(JSON.stringify({ kind: 'peer-info', ...localPeerInfo() }));
769
+ const sendButton = $('#sendFiles');
770
+ if (sendButton) {
771
+ sendButton.disabled = false;
772
+ sendButton.innerHTML = `${icons.send} ${t('sendFilesButton')}`;
773
+ }
774
+ };
775
+ channel.onclose = () => setConnectionState(allTransfersDone() ? 'done' : 'disconnected');
776
+ channel.onmessage = (event) => handleDataMessage(event.data);
777
+ }
778
+
779
+ function allTransfersDone() {
780
+ if (transfers.size === 0) return false;
781
+ return [...transfers.values()].every((file) => file.status === 'done');
782
+ }
783
+
784
+ async function handleSignal(type, payload) {
785
+ if (currentRole === 'sender') {
786
+ if (type === 'receiver-ready') {
787
+ if (!pc?.localDescription) return;
788
+ signaling.send('offer', { sdp: pc.localDescription.sdp, type: pc.localDescription.type });
789
+ setConnectionState('connecting');
790
+ }
791
+
792
+ if (type === 'answer') {
793
+ await pc.setRemoteDescription(payload);
794
+ setConnectionState('connecting');
795
+ }
796
+ }
797
+
798
+ if (currentRole === 'receiver' && type === 'offer') {
799
+ createPeerConnection();
800
+ pc.ondatachannel = (event) => setupDataChannel(event.channel);
801
+ await pc.setRemoteDescription(payload);
802
+ const answer = await pc.createAnswer();
803
+ await pc.setLocalDescription(answer);
804
+ await waitForIceGathering();
805
+ signaling.send('answer', { sdp: pc.localDescription.sdp, type: pc.localDescription.type });
806
+ setConnectionState('connecting');
807
+ }
808
+
809
+ if (type === 'ice-candidate' && pc) {
810
+ try {
811
+ await pc.addIceCandidate(payload);
812
+ } catch (error) {
813
+ console.warn('ICE candidate error:', error);
814
+ }
815
+ }
816
+ }
817
+
818
+ function renderHome() {
819
+ reset();
820
+ const settings = loadSettings();
821
+ applyPreferences(settings);
822
+ app.innerHTML = `
823
+ <section class="screen home">
824
+ <button class="icon-button settings-trigger" id="openSettings" aria-label="${t('settingsButtonTitle')}" title="${t('settingsButtonTitle')}">${icons.gear}</button>
825
+ <div class="brand">
826
+ <div class="brand-row"><div class="logo">${icons.share}</div><h1>LocalDrop</h1></div>
827
+ <p class="muted">${t('appSubtitle')}</p>
828
+ </div>
829
+ <div class="tiles">
830
+ <button class="tile send" id="send"><div class="tile-icon">${icons.share}</div><div><div class="tile-title">${t('tileSendTitle')}</div><div class="tile-desc">${t('tileSendDesc')}</div></div></button>
831
+ <button class="tile receive" id="receive"><div class="tile-icon">${icons.down}</div><div><div class="tile-title">${t('tileReceiveTitle')}</div><div class="tile-desc">${t('tileReceiveDesc')}</div></div></button>
832
+ </div>
833
+ <p class="footnote">${t('homeFootnote')}</p>
834
+ </section>`;
835
+
836
+ $('#send').onclick = () => renderSend(loadSettings());
837
+ $('#receive').onclick = () => renderReceive(loadSettings());
838
+ $('#openSettings').onclick = () => renderSettings(loadSettings());
839
+ startDeviceListener(settings);
840
+ }
841
+
842
+ function renderSettings(settings) {
843
+ renderLayout(t('settingsTitle'), `
844
+ <div class="card settings-card">
845
+ <div class="section-title">${t('sectionDevice')}</div>
846
+ <label class="field-label" for="deviceName">${t('deviceNameLabel')}</label>
847
+ <input id="deviceName" class="plain-input" type="text" value="${escapeHtml(settings.deviceName)}" />
848
+ <label class="switch-row">
849
+ <span class="switch-label">
850
+ <span class="field-label">${t('rememberLabel')}</span>
851
+ <span class="tiny">${t('rememberTiny')}</span>
852
+ </span>
853
+ <span class="switch"><input id="remember" type="checkbox" ${settings.remember ? 'checked' : ''} /><span class="switch-slider"></span></span>
854
+ </label>
855
+ <div class="field-divider"></div>
856
+ <button type="button" class="small-button" id="resetPeers" ${settings.peers.length ? '' : 'disabled'}>${t('resetPeersButton')}</button>
857
+ <p class="tiny">${settings.peers.length ? t('resetPeersTiny') : t('resetPeersEmpty')}</p>
858
+ </div>
859
+
860
+ <div class="card settings-card">
861
+ <div class="section-title">${t('sectionReceiving')}</div>
862
+ <label class="switch-row">
863
+ <span class="switch-label">
864
+ <span class="field-label">${t('autoAcceptLabel')}</span>
865
+ <span class="tiny">${t('autoAcceptTiny')}</span>
866
+ </span>
867
+ <span class="switch"><input id="autoAccept" type="checkbox" ${settings.autoAccept ? 'checked' : ''} /><span class="switch-slider"></span></span>
868
+ </label>
869
+ <label class="switch-row">
870
+ <span class="switch-label">
871
+ <span class="field-label">${t('autoDownloadLabel')}</span>
872
+ <span class="tiny">${t('autoDownloadTiny')}</span>
873
+ </span>
874
+ <span class="switch"><input id="autoDownload" type="checkbox" ${settings.autoDownload ? 'checked' : ''} /><span class="switch-slider"></span></span>
875
+ </label>
876
+ </div>
877
+
878
+ <div class="card settings-card">
879
+ <div class="section-title">${t('sectionAppearance')}</div>
880
+ <label class="switch-row">
881
+ <span class="switch-label">
882
+ <span class="field-label">${t('darkThemeLabel')}</span>
883
+ <span class="tiny">${t('darkThemeTiny')}</span>
884
+ </span>
885
+ <span class="switch"><input id="darkTheme" type="checkbox" ${effectiveTheme(settings) === 'dark' ? 'checked' : ''} /><span class="switch-slider"></span></span>
886
+ </label>
887
+ <label class="field-label" for="language">${t('languageLabel')}</label>
888
+ <select id="language" class="plain-input">
889
+ <option value="ru" ${settings.lang === 'ru' ? 'selected' : ''}>${t('langRu')}</option>
890
+ <option value="en" ${settings.lang === 'en' ? 'selected' : ''}>${t('langEn')}</option>
891
+ </select>
892
+ <p class="tiny">${t('languageTiny')}</p>
893
+ </div>
894
+
895
+ <div class="card settings-card">
896
+ <div class="section-title">${t('sectionConnection')}</div>
897
+ <label class="field-label" for="stunServer">${t('stunLabel')}</label>
898
+ <select id="stunServer" class="plain-input">
899
+ <option value="auto" ${settings.stunServer === 'auto' ? 'selected' : ''}>${t('stunAuto')}</option>
900
+ ${ICE_SERVERS.map((server) => `<option value="${server.urls}" ${settings.stunServer === server.urls ? 'selected' : ''}>${server.urls.replace('stun:', '')}</option>`).join('')}
901
+ </select>
902
+ <p class="tiny">${t('stunTiny')}</p>
903
+
904
+ <div class="field-divider"></div>
905
+
906
+ <label class="field-label" for="turnUrl">${t('turnLabel')}</label>
907
+ <p class="tiny">${t('turnTiny')}</p>
908
+ <div class="field-group">
909
+ <input id="turnUrl" class="plain-input" type="text" value="${escapeHtml(settings.turnUrl)}" placeholder="turn:relay.example.com:3478" />
910
+ <input id="turnUsername" class="plain-input" type="text" value="${escapeHtml(settings.turnUsername)}" placeholder="${t('turnUsernamePlaceholder')}" />
911
+ <input id="turnCredential" class="plain-input" type="password" value="${escapeHtml(settings.turnCredential)}" placeholder="${t('turnPasswordPlaceholder')}" />
912
+ </div>
913
+ <button type="button" class="small-button" id="fillTestTurn">${t('fillTestTurnButton')}</button>
914
+ <p class="tiny">${t('fillTestTurnTiny')}</p>
915
+
916
+ <div class="field-divider"></div>
917
+
918
+ <details class="advanced-settings"><summary>${t('advancedSummary')}</summary><input id="signalUrl" class="plain-input" type="url" value="${escapeHtml(settings.signalUrl)}" placeholder="wss://test.mosquitto.org:8081/mqtt" /><p class="tiny">${t('relayTiny')}</p></details>
919
+ </div>
920
+ <p class="footnote">${t('settingsFootnote')}</p>`);
921
+
922
+ const persist = () => saveSettings({
923
+ ...loadSettings(),
924
+ deviceName: ($('#deviceName').value || settings.deviceName).trim(),
925
+ remember: $('#remember').checked,
926
+ autoAccept: $('#autoAccept').checked,
927
+ autoDownload: $('#autoDownload').checked,
928
+ theme: $('#darkTheme').checked ? 'dark' : 'light',
929
+ stunServer: $('#stunServer').value,
930
+ turnUrl: $('#turnUrl').value.trim(),
931
+ turnUsername: $('#turnUsername').value.trim(),
932
+ turnCredential: $('#turnCredential').value.trim(),
933
+ signalUrl: ($('#signalUrl').value || DEFAULT_SIGNAL_URL).trim()
934
+ });
935
+
936
+ $('#deviceName').onchange = persist;
937
+ $('#remember').onchange = persist;
938
+ $('#autoAccept').onchange = persist;
939
+ $('#autoDownload').onchange = persist;
940
+ $('#darkTheme').onchange = () => { persist(); applyPreferences(loadSettings()); };
941
+ $('#language').onchange = () => {
942
+ saveSettings({ ...loadSettings(), lang: $('#language').value });
943
+ renderSettings(loadSettings());
944
+ };
945
+ $('#stunServer').onchange = persist;
946
+ $('#turnUrl').onchange = persist;
947
+ $('#turnUsername').onchange = persist;
948
+ $('#turnCredential').onchange = persist;
949
+ $('#signalUrl').onchange = persist;
950
+ $('#fillTestTurn').onclick = () => {
951
+ $('#turnUrl').value = 'turn:openrelay.metered.ca:80';
952
+ $('#turnUsername').value = 'openrelayproject';
953
+ $('#turnCredential').value = 'openrelayproject';
954
+ persist();
955
+ };
956
+ $('#resetPeers').onclick = () => {
957
+ if (!settings.peers.length) return;
958
+ if (!confirm(t('resetPeersConfirm'))) return;
959
+ saveSettings({ ...loadSettings(), peers: [] });
960
+ renderSettings(loadSettings());
961
+ };
962
+ }
963
+
964
+ function renderLayout(title, body) {
965
+ applyPreferences(loadSettings());
966
+ app.innerHTML = `
967
+ <section class="screen">
968
+ <button class="back" id="back">${icons.back} ${t('backButton')}</button>
969
+ <div class="header"><h2>${title}</h2>${badge()}</div>
970
+ ${body}
971
+ </section>`;
972
+ $('#back').onclick = () => {
973
+ reset();
974
+ renderHome();
975
+ };
976
+ }
977
+
978
+ async function renderSend(settings, directPeer = null) {
979
+ reset();
980
+ currentRole = 'sender';
981
+ const roomCode = generateRoomCode();
982
+
983
+ renderLayout(t('sendTitle'), `
984
+ <div class="card center">
985
+ <p class="muted">${t('sendCodeHint')}</p>
986
+ <div class="code-row">${roomCode.split('').map((char) => `<span class="code-char">${char}</span>`).join('')}</div>
987
+ <p class="tiny">${directPeer ? t('sendDirectHint', { name: escapeHtml(directPeer.name) }) : t('sendManualHint')}</p>
988
+ ${!directPeer && settings.peers.length ? `<div class="peer-quick"><div class="peer-quick-label">${t('quickSendLabel')}</div><div class="peer-chips">${settings.peers.map((peer) => `<button class="peer-chip" data-peer="${peer.id}">${escapeHtml(peer.name)}</button>`).join('')}</div></div>` : ''}
989
+ </div>
990
+ <div id="status" class="notice">${t('searchingStatus')}</div>
991
+ <div class="drop" id="drop"><div class="icon">${icons.upload}</div><b>${t('dropTitle')}</b><span class="tiny">${t('dropSubtitle')}</span><input class="hidden" id="file" type="file" multiple></div>
992
+ <div class="queue" id="queue"></div>
993
+ <button class="button sky" id="sendFiles" disabled>${icons.send} ${t('waitingReceiverButton')}</button>
994
+ <div class="files" id="files"></div>`);
995
+
996
+ try {
997
+ signaling = new LocalSignaling({ roomCode, role: 'sender', signalUrl: settings.signalUrl, onSignal: handleSignal });
998
+ const mode = await signaling.connect();
999
+ createPeerConnection();
1000
+ setupDataChannel(pc.createDataChannel('files', { ordered: true }));
1001
+ await pc.setLocalDescription(await pc.createOffer());
1002
+ await waitForIceGathering();
1003
+ setConnectionState('waiting');
1004
+ if (directPeer) await sendDirectInvite(settings, directPeer, roomCode);
1005
+ showStatus(directPeer ? t('inviteSentStatus', { name: directPeer.name }) : (mode === 'network' ? t('waitingCodeStatus') : t('localModeStatus')));
1006
+ } catch (error) {
1007
+ setConnectionState('error');
1008
+ showStatus(error.message, 'error-box');
1009
+ }
1010
+
1011
+ const fileInput = $('#file');
1012
+ const drop = $('#drop');
1013
+ drop.onclick = () => fileInput.click();
1014
+ drop.ondragover = (event) => { event.preventDefault(); drop.classList.add('drag'); };
1015
+ drop.ondragleave = () => drop.classList.remove('drag');
1016
+ drop.ondrop = (event) => { event.preventDefault(); drop.classList.remove('drag'); addFiles(event.dataTransfer.files); };
1017
+ fileInput.onchange = (event) => addFiles(event.target.files);
1018
+ $('#sendFiles').onclick = sendFiles;
1019
+ document.querySelectorAll('[data-peer]').forEach((button) => {
1020
+ button.onclick = () => {
1021
+ const peer = settings.peers.find((item) => item.id === button.dataset.peer);
1022
+ renderSend(settings, peer);
1023
+ };
1024
+ });
1025
+ }
1026
+
1027
+ function renderReceive(settings, autoRoomCode = '', peerName = '') {
1028
+ reset();
1029
+ currentRole = 'receiver';
1030
+
1031
+ if (autoRoomCode && peerName) {
1032
+ renderLayout(t('receiveTitle'), `
1033
+ <div class="card center">
1034
+ <div class="tile-icon" style="margin:0 auto 16px;background:var(--green-soft-bg);color:var(--green)">${icons.down}</div>
1035
+ <p class="muted">${t('deviceLabel')} <b>${escapeHtml(peerName)}</b></p>
1036
+ <div id="status" class="notice">${t('establishingStatus')}</div>
1037
+ </div>
1038
+ <div class="files" id="files"></div>`);
1039
+ joinRoom(settings, autoRoomCode);
1040
+ return;
1041
+ }
1042
+
1043
+ renderLayout(t('receiveTitle'), `
1044
+ <div class="card center">
1045
+ <div class="tile-icon" style="margin:0 auto 16px;background:var(--green-soft-bg);color:var(--green)">${icons.hash}</div>
1046
+ <p class="muted">${t('receiveHint')}</p>
1047
+ <input id="roomInput" type="text" value="${autoRoomCode}" placeholder="XXXXXX" maxlength="6" autocomplete="one-time-code" />
1048
+ <button class="button green" id="join">${t('connectButton')}</button>
1049
+ <div id="status" class="notice">${t('waitingCodeInputStatus')}</div>
1050
+ </div>
1051
+ <div class="files" id="files"></div>`);
1052
+
1053
+ const input = $('#roomInput');
1054
+ input.oninput = () => { input.value = input.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 6); };
1055
+ input.onkeydown = (event) => { if (event.key === 'Enter') joinRoom(settings); };
1056
+ $('#join').onclick = () => joinRoom(settings);
1057
+ if (autoRoomCode) joinRoom(settings, autoRoomCode);
1058
+ }
1059
+
1060
+ async function sendDirectInvite(settings, peer, roomCode) {
1061
+ const direct = new LocalSignaling({ roomCode: peer.id, role: 'sender', signalUrl: settings.signalUrl, onSignal: () => {} });
1062
+ await direct.connect();
1063
+ direct.send('direct-invite', { roomCode, from: localPeerInfo() });
1064
+ setTimeout(() => direct.close(), 1200);
1065
+ }
1066
+
1067
+ async function startDeviceListener(settings) {
1068
+ if (!settings.remember) return;
1069
+ try {
1070
+ deviceListener = new LocalSignaling({
1071
+ roomCode: settings.deviceId,
1072
+ role: 'device',
1073
+ signalUrl: settings.signalUrl,
1074
+ onSignal: (type, payload) => {
1075
+ if (type !== 'direct-invite' || !payload?.roomCode) return;
1076
+ document.querySelector('.invite-overlay')?.remove();
1077
+ if (loadSettings().autoAccept) {
1078
+ if (payload.from) savePeer(payload.from);
1079
+ renderReceive(loadSettings(), payload.roomCode, payload.from?.deviceName || t('unknownDevice'));
1080
+ return;
1081
+ }
1082
+ showIncomingInvite(payload);
1083
+ }
1084
+ });
1085
+ await deviceListener.connect();
1086
+ } catch (error) {
1087
+ console.warn('Device listener error:', error);
1088
+ }
1089
+ }
1090
+
1091
+ function showIncomingInvite(payload) {
1092
+ const name = payload.from?.deviceName || t('unknownDevice');
1093
+ const overlay = document.createElement('div');
1094
+ overlay.className = 'invite-overlay';
1095
+ overlay.innerHTML = `
1096
+ <div class="invite-card">
1097
+ <div class="tile-icon" style="margin:0 auto 16px;background:var(--accent-soft-bg);color:var(--accent)">${icons.down}</div>
1098
+ <h3>${t('incomingTransferTitle')}</h3>
1099
+ <p class="muted">${t('incomingTransferDesc', { name: escapeHtml(name) })}</p>
1100
+ <div class="invite-actions">
1101
+ <button class="button green" id="acceptInvite">${t('connectButton')}</button>
1102
+ <button class="small-button" id="declineInvite">${t('declineButton')}</button>
1103
+ </div>
1104
+ </div>`;
1105
+ document.body.appendChild(overlay);
1106
+ $('#acceptInvite', overlay).onclick = () => {
1107
+ overlay.remove();
1108
+ if (payload.from) savePeer(payload.from);
1109
+ renderReceive(loadSettings(), payload.roomCode, name);
1110
+ };
1111
+ $('#declineInvite', overlay).onclick = () => overlay.remove();
1112
+ }
1113
+
1114
+ async function joinRoom(settings, forcedRoomCode = '') {
1115
+ const roomCode = (forcedRoomCode || $('#roomInput').value).trim().toUpperCase();
1116
+ if (roomCode.length !== 6) {
1117
+ showStatus(t('codeErrorStatus'), 'error-box');
1118
+ return;
1119
+ }
1120
+
1121
+ try {
1122
+ setConnectionState('signaling');
1123
+ signaling = new LocalSignaling({ roomCode, role: 'receiver', signalUrl: settings.signalUrl, onSignal: handleSignal });
1124
+ const mode = await signaling.connect();
1125
+ signaling.send('receiver-ready', {});
1126
+ showStatus(mode === 'network' ? t('roomFoundStatus') : t('localModeReceiveStatus'));
1127
+ } catch (error) {
1128
+ setConnectionState('error');
1129
+ showStatus(error.message, 'error-box');
1130
+ }
1131
+ }
1132
+
1133
+ function addFiles(fileList) {
1134
+ queued.push(...Array.from(fileList || []).map((file) => ({
1135
+ id: crypto.randomUUID(),
1136
+ file,
1137
+ name: file.name,
1138
+ size: file.size,
1139
+ type: file.type,
1140
+ transferred: 0,
1141
+ status: 'queued'
1142
+ })));
1143
+ renderQueue();
1144
+ }
1145
+
1146
+ function renderQueue() {
1147
+ const queue = $('#queue');
1148
+ if (!queue) return;
1149
+ queue.innerHTML = queued.map((file) => `
1150
+ <div class="file-row">
1151
+ <div class="file-main"><div class="file-name">${file.name}</div><div class="tiny">${formatBytes(file.size)}</div></div>
1152
+ <button class="remove" data-id="${file.id}">×</button>
1153
+ </div>`).join('');
1154
+ queue.querySelectorAll('.remove').forEach((button) => {
1155
+ button.onclick = () => {
1156
+ queued = queued.filter((file) => file.id !== button.dataset.id);
1157
+ renderQueue();
1158
+ };
1159
+ });
1160
+ }
1161
+
1162
+ async function sendFiles() {
1163
+ if (!channel || channel.readyState !== 'open') return;
1164
+
1165
+ for (const file of queued) {
1166
+ transfers.set(file.id, { ...file, status: 'transferring' });
1167
+ renderTransfers(false);
1168
+ channel.send(JSON.stringify({ kind: 'meta', id: file.id, name: file.name, size: file.size, type: file.type }));
1169
+
1170
+ for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
1171
+ while (channel.bufferedAmount > 8 * 1024 * 1024) await new Promise((resolve) => setTimeout(resolve, 20));
1172
+ channel.send(await file.file.slice(offset, offset + CHUNK_SIZE).arrayBuffer());
1173
+ transfers.get(file.id).transferred = Math.min(offset + CHUNK_SIZE, file.size);
1174
+ renderTransfers(false);
1175
+ }
1176
+
1177
+ channel.send(JSON.stringify({ kind: 'done', id: file.id }));
1178
+ transfers.get(file.id).status = 'done';
1179
+ renderTransfers(false);
1180
+ }
1181
+ }
1182
+
1183
+ function renderTransfers(showDownloads = true) {
1184
+ const files = $('#files');
1185
+ if (!files) return;
1186
+ files.innerHTML = [...transfers.values()].map((file) => {
1187
+ const percent = file.size ? Math.round((file.transferred / file.size) * 100) : 100;
1188
+ return `
1189
+ <div class="file-row ${file.status === 'done' ? 'done' : ''}">
1190
+ <div class="file-main">
1191
+ <div class="file-name">${file.name}</div>
1192
+ <div class="tiny">${formatBytes(file.size)}</div>
1193
+ <div class="progress"><div class="bar" style="width:${percent}%"></div></div>
1194
+ <div class="status-text">${file.status === 'done' ? t('doneStatusText') : `${percent}%`}</div>
1195
+ </div>
1196
+ ${showDownloads && file.url ? `<a class="download" href="${file.url}" download="${file.name}">${t('downloadLink')}</a>` : ''}
1197
+ </div>`;
1198
+ }).join('');
1199
+ }
1200
+
1201
+ function handleDataMessage(data) {
1202
+ if (typeof data === 'string') {
1203
+ const message = JSON.parse(data);
1204
+
1205
+ if (message.kind === 'peer-info') {
1206
+ savePeer(message);
1207
+ if (currentRole === 'receiver' && message.deviceName) {
1208
+ showStatus(t('connectedToStatus', { name: message.deviceName }), 'notice');
1209
+ }
1210
+ return;
1211
+ }
1212
+
1213
+ if (message.kind === 'meta') {
1214
+ receiveBuffers.set(message.id, { ...message, chunks: [], received: 0 });
1215
+ transfers.set(message.id, { id: message.id, name: message.name, size: message.size, type: message.type, transferred: 0, status: 'transferring' });
1216
+ renderTransfers(true);
1217
+ }
1218
+
1219
+ if (message.kind === 'done') {
1220
+ const received = receiveBuffers.get(message.id);
1221
+ const blob = new Blob(received.chunks, { type: received.type || 'application/octet-stream' });
1222
+ const url = URL.createObjectURL(blob);
1223
+ transfers.set(message.id, { ...transfers.get(message.id), transferred: received.size, status: 'done', url });
1224
+ renderTransfers(true);
1225
+ if (loadSettings().autoDownload) {
1226
+ const link = document.createElement('a');
1227
+ link.href = url;
1228
+ link.download = received.name;
1229
+ link.click();
1230
+ }
1231
+ }
1232
+
1233
+ return;
1234
+ }
1235
+
1236
+ const active = [...receiveBuffers.values()].find((file) => file.received < file.size);
1237
+ if (!active) return;
1238
+ active.chunks.push(data);
1239
+ active.received += data.byteLength;
1240
+ const transfer = transfers.get(active.id);
1241
+ transfer.transferred = Math.min(active.received, active.size);
1242
+ renderTransfers(true);
1243
+ }
1244
+
1245
+ renderHome();
1246
+
1247
+ </script>
1248
+ </body>
1249
+ </html>