Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1379 lines (1274 loc) · 60.5 KB
/
Copy pathscript.js
File metadata and controls
1379 lines (1274 loc) · 60.5 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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { useState, useEffect, useRef } = React;
// テキスト系MIMEタイプかどうか判定
const isTextFile = (mimeType, fileName) => {
const binaryMimes = [
'application/octet-stream',
'application/zip', 'application/x-zip-compressed', 'application/x-rar-compressed',
'application/x-7z-compressed', 'application/x-tar', 'application/gzip',
'application/x-bzip2', 'application/x-xz', 'application/x-lzip',
'application/x-lzma', 'application/zstd', 'application/x-compress',
'application/pdf', 'application/msword', 'application/vnd.ms-excel',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.oasis.opendocument.text',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.presentation',
'application/epub+zip',
'application/exe', 'application/x-msdownload', 'application/x-msdos-program',
'application/x-elf', 'application/x-mach-binary', 'application/x-sharedlib',
'application/x-executable', 'application/vnd.android.package-archive',
'application/java-archive', 'application/wasm',
'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp',
'image/tiff', 'image/x-icon', 'image/vnd.microsoft.icon', 'image/heic',
'image/heif', 'image/avif', 'image/jp2', 'image/jxl', 'image/x-xcf',
'image/vnd.adobe.photoshop',
'audio/mpeg', 'audio/mp4', 'audio/wav', 'audio/x-wav', 'audio/flac',
'audio/ogg', 'audio/aac', 'audio/x-m4a', 'audio/x-aiff', 'audio/x-ms-wma',
'audio/opus', 'audio/amr',
'video/mp4', 'video/x-msvideo', 'video/quicktime', 'video/x-matroska',
'video/webm', 'video/x-flv', 'video/mpeg', 'video/x-ms-wmv', 'video/3gpp',
'video/ogg', 'video/av1',
'font/ttf', 'font/otf', 'font/woff', 'font/woff2',
'application/x-font-ttf', 'application/x-font-otf',
'application/font-woff', 'application/font-woff2',
'application/x-sqlite3', 'application/vnd.ms-access', 'application/x-dbase',
'application/x-parquet', 'application/x-hdf', 'application/x-netcdf',
'application/x-iso9660-image', 'application/x-raw-disk-image',
'model/stl', 'model/obj', 'model/gltf-binary', 'application/x-fbx', 'application/x-blender',
'application/x-pkcs12', 'application/x-x509-ca-cert', 'application/x-pem-file',
'application/x-deb', 'application/x-rpm', 'application/vnd.snap',
'application/x-apple-diskimage', 'application/x-msmetafile',
];
const binaryExts = [
'.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz',
'.lz', '.lzma', '.zst', '.z', '.tgz', '.tbz2', '.txz',
'.cab', '.lha', '.lzh', '.ace', '.arj',
'.exe', '.dll', '.so', '.dylib', '.bin', '.dat',
'.elf', '.out', '.com', '.msi', '.apk', '.ipa',
'.jar', '.war', '.ear', '.dex',
'.pdf', '.doc', '.docx', '.odt', '.rtf',
'.xls', '.xlsx', '.ods', '.ppt', '.pptx', '.odp',
'.epub', '.mobi', '.azw', '.azw3', '.xps', '.oxps',
'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.ico',
'.tiff', '.tif', '.heic', '.heif', '.avif', '.jp2', '.jxl',
'.psd', '.xcf', '.ai', '.eps', '.raw', '.cr2', '.cr3',
'.nef', '.arw', '.orf', '.rw2', '.dng',
'.mp3', '.wav', '.flac', '.ogg', '.aac', '.m4a',
'.aiff', '.aif', '.wma', '.opus', '.amr', '.mid', '.midi', '.ape', '.wv',
'.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv',
'.wmv', '.mpeg', '.mpg', '.m4v', '.3gp', '.3g2',
'.ts', '.mts', '.m2ts', '.vob', '.ogv', '.rm', '.rmvb',
'.ttf', '.otf', '.woff', '.woff2', '.eot', '.fon', '.pfb', '.pfm',
'.sqlite', '.sqlite3', '.db', '.mdb', '.accdb', '.dbf',
'.parquet', '.feather', '.arrow', '.hdf5', '.h5', '.nc',
'.npy', '.npz', '.pkl', '.joblib', '.pt', '.pth', '.onnx',
'.pb', '.tflite',
'.class', '.pyc', '.pyo', '.pyd', '.o', '.a', '.lib', '.obj',
'.iso', '.img', '.dmg', '.vhd', '.vhdx', '.vmdk', '.qcow2',
'.stl', '.obj', '.glb', '.gltf', '.fbx', '.blend',
'.dae', '.3ds', '.max', '.dwg', '.dxf',
'.pfx', '.p12', '.cer', '.crt', '.der', '.key',
'.deb', '.rpm', '.snap', '.appimage', '.pkg',
'.swf', '.fla', '.wasm', '.wmf', '.emf',
'.pdb', '.idb', '.dump', '.core',
];
if (mimeType) {
if (mimeType.startsWith('image/')) return false;
if (mimeType.startsWith('video/')) return false;
if (mimeType.startsWith('audio/')) return false;
if (binaryMimes.some(m => mimeType.startsWith(m))) return false;
if (mimeType.startsWith('text/')) return true;
if (['application/json', 'application/xml', 'application/javascript',
'application/typescript', 'application/x-sh'].includes(mimeType)) return true;
}
if (fileName) {
const lower = fileName.toLowerCase();
if (binaryExts.some(e => lower.endsWith(e))) return false;
return true;
}
return false;
};
// translations will be loaded from translations.json at runtime
let translations = {};
function App() {
const [peerId, setPeerId] = useState('');
const [remotePeerId, setRemotePeerId] = useState('');
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
const [connectionStatus, setConnectionStatus] = useState('notConnected');
const [isTyping, setIsTyping] = useState(false);
const [notification, setNotification] = useState('');
const [userName, setUserName] = useState('');
const [remoteName, setRemoteName] = useState('');
const [isNameSet, setIsNameSet] = useState(false);
const [language, setLanguage] = useState(localStorage.getItem('language') || 'en');
// スマホ判定
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
// 音声通話関連
const [callStatus, setCallStatus] = useState('idle'); // idle | calling | receiving | ongoing
const [isMuted, setIsMuted] = useState(false);
const [isSpeaker, setIsSpeaker] = useState(false);
const localStreamRef = useRef(null);
const currentCallRef = useRef(null);
const remoteAudioRef = useRef(null);
const peerInstance = useRef(null);
const connRef = useRef(null);
const pendingFileTransfers = useRef({});
const cryptoKey = useRef(null);
const myKeyPair = useRef(null);
const messagesEndRef = useRef(null);
const typingTimeoutRef = useRef(null);
const inputRef = useRef(null);
const fileInputRef = useRef(null);
const [replyTo, setReplyTo] = useState(null);
const [selectedFile, setSelectedFile] = useState(null);
const [fileTransferProgress, setFileTransferProgress] = useState({
sendingCount: 0,
sendingTotal: 0,
receivingCount: 0,
receivingTotal: 0,
sendingFileName: '',
receivingFileName: '',
sendingState: 'idle',
receivingState: 'idle',
});
const [qrDataUrl, setQrDataUrl] = useState('');
const [showQr, setShowQr] = useState(false);
const [activeReactionMsgId, setActiveReactionMsgId] = useState(null);
useEffect(() => {
localStorage.setItem('language', language);
}, [language]);
const t = (key) => ((translations[language] && translations[language][key]) || (translations.en && translations.en[key]) || key);
const showNotification = (msg) => {
setNotification(t(msg));
setTimeout(() => setNotification(''), 3000);
};
const encryptMessageLocal = async (text) => {
if (!cryptoKey.current) { showNotification('noConnection'); return null; }
return encryptMessage(text, cryptoKey.current);
};
const decryptMessageLocal = async (data) => {
if (!cryptoKey.current) { showNotification('noConnection'); return 'Decryption Error'; }
return decryptMessage(data, cryptoKey.current);
};
const encryptFileLocal = async (fileData) => {
if (!cryptoKey.current) { showNotification('noConnection'); return null; }
return encryptFile(fileData, cryptoKey.current);
};
const decryptFileLocal = async (data) => {
if (!cryptoKey.current) { showNotification('noConnection'); return null; }
return decryptFile(data, cryptoKey.current);
};
const arrayBufferToBase64File = (buffer) => {
const bytes = new Uint8Array(buffer);
let binary = '';
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunkSize));
}
return btoa(binary);
};
const createDataUrl = (buffer, mimeType = 'application/octet-stream') => {
const base64 = arrayBufferToBase64File(buffer);
return `data:${mimeType};base64,${base64}`;
};
const getShareUrl = (peerIdToShare) => {
const isFileUrl = window.location.protocol === 'file:';
const baseUrl = isFileUrl
? window.location.href.split('?')[0].split('#')[0]
: `${window.location.origin}${window.location.pathname}`;
return `${baseUrl}?target=${encodeURIComponent(peerIdToShare)}`;
};
const reactionOptions = window.reactionOptions || [
{ code: 'like', symbol: String.fromCodePoint(0x1F44D) },
{ code: 'heart', symbol: String.fromCodePoint(0x2764, 0xFE0F) },
];
const reactionSymbol = window.reactionSymbol || ((code) => code);
const createMessageId = () => {
if (window.createMessageId) return window.createMessageId();
const arr = new Uint8Array(9);
crypto.getRandomValues(arr);
const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
return `${Date.now()}-${hex}`;
};
const sendReaction = (messageId, emoji) => {
if (!messageId || !connRef.current) return;
if (window.sendReaction) {
window.sendReaction(messageId, emoji, userName, connRef.current, setMessages);
}
};
const generateQrCode = async () => {
if (!peerId || !window.QRCode) return;
try {
const url = getShareUrl(peerId);
const dataUrl = await window.QRCode.toDataURL(url, { errorCorrectionLevel: 'H', width: 180, margin: 2 });
setQrDataUrl(dataUrl);
setShowQr(true);
} catch (err) {
console.error('QR code generation failed:', err);
}
};
const generateTransferId = () => {
const arr = new Uint8Array(10);
crypto.getRandomValues(arr);
const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
return `${Date.now()}-${hex}`;
};
const chunkString = (text, size) => {
const chunks = [];
for (let i = 0; i < text.length; i += size) {
chunks.push(text.slice(i, i + size));
}
return chunks;
};
const handleIncomingFileMeta = (data) => {
if (!data.transferId || typeof data.totalChunks !== 'number') return;
pendingFileTransfers.current[data.transferId] = {
fileName: data.fileName || 'unknown',
mimeType: data.mimeType || 'application/octet-stream',
iv: data.iv,
totalChunks: data.totalChunks,
chunks: new Array(data.totalChunks),
receivedChunks: 0,
};
setFileTransferProgress(prev => ({
...prev,
receivingCount: 0,
receivingTotal: data.totalChunks,
receivingFileName: data.fileName || 'unknown',
receivingState: 'receiving',
}));
};
const completeIncomingFileTransfer = async (transferId) => {
const transfer = pendingFileTransfers.current[transferId];
if (!transfer) return;
const encryptedBase64 = transfer.chunks.join('');
const decryptedBuffer = await decryptFileLocal({ iv: transfer.iv, encrypted: encryptedBase64 });
if (!decryptedBuffer) {
showNotification('fileTransferError');
delete pendingFileTransfers.current[transferId];
return;
}
const fileDataUrl = createDataUrl(decryptedBuffer, transfer.mimeType);
const incomingMessage = {
sender: 'remote',
isFile: true,
fileName: transfer.fileName,
mimeType: transfer.mimeType,
fileData: fileDataUrl,
text: transfer.fileName,
timestamp: formatTimestamp(),
};
setMessages(prev => [...prev, incomingMessage]);
setFileTransferProgress(prev => ({
...prev,
receivingCount: transfer.totalChunks,
receivingState: 'received',
}));
delete pendingFileTransfers.current[transferId];
showNotification('fileReceived');
};
const handleIncomingFileChunk = async (data) => {
if (!data.transferId || typeof data.index !== 'number' || typeof data.data !== 'string') return;
const transfer = pendingFileTransfers.current[data.transferId];
if (!transfer) return;
if (!transfer.chunks[data.index]) {
transfer.chunks[data.index] = data.data;
transfer.receivedChunks += 1;
}
setFileTransferProgress(prev => ({
...prev,
receivingCount: transfer.receivedChunks,
}));
if (transfer.receivedChunks >= transfer.totalChunks) {
await completeIncomingFileTransfer(data.transferId);
}
};
const receiveFile = async (data) => {
if (!data || !data.encrypted || !data.iv) {
showNotification('fileTransferError');
return;
}
const decryptedBuffer = await decryptFileLocal(data);
if (!decryptedBuffer) {
showNotification('fileTransferError');
return;
}
const fileDataUrl = createDataUrl(decryptedBuffer, data.mimeType || 'application/octet-stream');
const incomingMessage = {
id: createMessageId(),
sender: 'remote',
isFile: true,
fileName: data.fileName || 'unknown',
mimeType: data.mimeType || 'application/octet-stream',
fileData: fileDataUrl,
text: data.fileName || 'file',
timestamp: formatTimestamp(),
reactions: {},
};
setMessages(prev => [...prev, incomingMessage]);
showNotification('fileReceived');
};
const formatTimestamp = () => {
return new Date().toLocaleString(language === 'zh' ? 'zh-CN' : language, {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit'
});
};
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const target = params.get('target') || params.get('peer');
if (target) setRemotePeerId(target);
}, []);
const handleTyping = () => {
if (connRef.current) {
connRef.current.send({ type: 'typing', user: userName });
if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
typingTimeoutRef.current = setTimeout(() => {
if (connRef.current) connRef.current.send({ type: 'stop-typing' });
}, 2000);
}
};
const cancelReply = () => setReplyTo(null);
const handleFileSelect = async (file) => {
if (!file) return;
if (connRef.current && cryptoKey.current) {
setSelectedFile(file);
setFileTransferProgress(prev => ({
...prev,
sendingCount: 0,
sendingTotal: 0,
sendingFileName: file.name,
sendingState: 'ready',
}));
} else {
showNotification('noConnection');
}
};
const handleFileInputChange = (e) => {
if (e.target.files && e.target.files[0]) handleFileSelect(e.target.files[0]);
};
const handleDragOver = (e) => { e.preventDefault(); e.currentTarget.classList.add('drag-over'); };
const handleDragLeave = (e) => { e.currentTarget.classList.remove('drag-over'); };
const handleDrop = (e) => {
e.preventDefault();
e.currentTarget.classList.remove('drag-over');
if (e.dataTransfer.files && e.dataTransfer.files[0]) handleFileSelect(e.dataTransfer.files[0]);
};
const sendFile = async () => {
if (!selectedFile || !connRef.current || !cryptoKey.current) {
showNotification('noConnection'); return;
}
try {
const base64Data = await fileToBase64(selectedFile);
const encrypted = await encryptFileLocal(base64Data);
if (!encrypted) return;
const transferId = generateTransferId();
const chunks = chunkString(encrypted.encrypted, 16 * 1024);
setFileTransferProgress(prev => ({
...prev,
sendingCount: 0,
sendingTotal: chunks.length,
sendingState: 'sending',
}));
connRef.current.send({
type: 'file-meta',
transferId,
fileName: selectedFile.name,
fileSize: selectedFile.size,
mimeType: selectedFile.type,
iv: encrypted.iv,
totalChunks: chunks.length,
});
for (let index = 0; index < chunks.length; index += 1) {
connRef.current.send({ type: 'file-chunk', transferId, index, data: chunks[index] });
if ((index + 1) % 3 === 0) {
await new Promise((resolve) => setTimeout(resolve, 0));
}
setFileTransferProgress(prev => ({
...prev,
sendingCount: index + 1,
}));
}
const fileBuffer = await selectedFile.arrayBuffer();
const fileDataUrl = createDataUrl(fileBuffer, selectedFile.type || 'application/octet-stream');
setMessages(prev => [...prev, {
id: createMessageId(),
sender: 'local',
isFile: true,
fileName: selectedFile.name,
mimeType: selectedFile.type,
fileData: fileDataUrl,
text: selectedFile.name,
timestamp: formatTimestamp(),
reactions: {},
}]);
setSelectedFile(null);
setFileTransferProgress(prev => ({
...prev,
sendingState: 'sent',
sendingCount: chunks.length,
}));
showNotification('fileSent');
} catch (err) {
console.error('File send error:', err);
showNotification('fileTransferError');
}
};
// -------------------------------------------------------
// 音声通話
// -------------------------------------------------------
const endCallCleanup = () => {
if (!currentCallRef.current && !localStreamRef.current) return;
if (localStreamRef.current) {
localStreamRef.current.getTracks().forEach(t => t.stop());
localStreamRef.current = null;
}
if (remoteAudioRef.current) remoteAudioRef.current.srcObject = null;
currentCallRef.current = null;
setCallStatus('idle');
setIsMuted(false);
setMessages(prev => [...prev, { sender: 'system', text: '通話終了', timestamp: formatTimestamp() }]);
};
const startCall = async () => {
if (!peerInstance.current || !connRef.current) return;
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
localStreamRef.current = stream;
const call = peerInstance.current.call(connRef.current.peer, stream);
currentCallRef.current = call;
setCallStatus('calling');
call.on('stream', (remoteStream) => {
if (remoteAudioRef.current) {
remoteAudioRef.current.srcObject = remoteStream;
remoteAudioRef.current.volume = 1.0;
// AudioContextでゲイン増幅
const audioCtx = new AudioContext();
const source = audioCtx.createMediaStreamSource(remoteStream);
const gainNode = audioCtx.createGain();
gainNode.gain.value = 2.5;
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
remoteAudioRef.current.play().catch(() => { });
}
setCallStatus('ongoing');
setMessages(prev => [...prev, { sender: 'system', text: '通話中...', timestamp: formatTimestamp() }]);
});
call.on('close', () => endCallCleanup());
call.on('error', () => endCallCleanup());
// 相手にシグナルを送る
connRef.current.send({ type: 'call-request', from: userName });
} catch (err) {
console.error('Call error:', err);
setCallStatus('idle');
}
};
const answerCall = async () => {
const call = currentCallRef.current;
if (!call) return;
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
localStreamRef.current = stream;
call.answer(stream);
setCallStatus('ongoing');
call.on('stream', (remoteStream) => {
if (remoteAudioRef.current) {
remoteAudioRef.current.srcObject = remoteStream;
remoteAudioRef.current.volume = 1.0;
const audioCtx = new AudioContext();
const source = audioCtx.createMediaStreamSource(remoteStream);
const gainNode = audioCtx.createGain();
gainNode.gain.value = 2.5;
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
remoteAudioRef.current.play().catch(() => { });
}
setMessages(prev => [...prev, { sender: 'system', text: '通話中...', timestamp: formatTimestamp() }]);
});
call.on('close', () => endCallCleanup());
call.on('error', () => endCallCleanup());
} catch (err) {
console.error('Answer error:', err);
setCallStatus('idle');
}
};
const endCall = () => {
if (currentCallRef.current) currentCallRef.current.close();
if (connRef.current) connRef.current.send({ type: 'call-end' });
endCallCleanup();
};
const rejectCall = () => {
if (currentCallRef.current) currentCallRef.current.close();
if (connRef.current) connRef.current.send({ type: 'call-rejected' });
currentCallRef.current = null;
setCallStatus('idle');
};
const toggleMute = () => {
if (localStreamRef.current) {
const audioTrack = localStreamRef.current.getAudioTracks()[0];
if (audioTrack) {
audioTrack.enabled = !audioTrack.enabled;
setIsMuted(!audioTrack.enabled);
}
}
};
const toggleSpeaker = async () => {
const audio = remoteAudioRef.current;
if (!audio) return;
try {
if (isSpeaker) {
// イヤホン/デフォルトに戻す
if (audio.setSinkId) await audio.setSinkId('');
} else {
// スピーカーに切り替え(setSinkIdが使えればデバイス一覧から選ぶが
// モバイルではspeakerphoneはsinkId指定不要でHTMLAudioElementのsinkId=''で自動)
if (audio.setSinkId) await audio.setSinkId('');
// iOSはsinkId非対応のためAudioContextで代替
if (!audio.setSinkId) {
// iOSではspeakerへの切り替えはplay()で自動的に行われる場合が多い
audio.play().catch(() => { });
}
}
setIsSpeaker(s => !s);
} catch (e) {
console.error('Speaker toggle error:', e);
}
};
// -------------------------------------------------------
// データハンドラ
// -------------------------------------------------------
const handleData = async (data) => {
if (data.type === 'pubkey') {
try {
const remotePubKey = await importPublicKey(data.key);
if (data.needsReply) {
const myPubKeyBase64 = await exportPublicKey(myKeyPair.current);
connRef.current.send({ type: 'pubkey', key: myPubKeyBase64, needsReply: false });
}
cryptoKey.current = await deriveSharedKey(myKeyPair.current.privateKey, remotePubKey);
if (!cryptoKey.current) { showNotification('keyImportFailed'); return; }
setMessages(prev => [...prev, { sender: 'system', text: t('keyReceived'), timestamp: formatTimestamp() }]);
setConnectionStatus('connected');
showNotification('connectionEstablished');
if (userName) connRef.current.send({ type: 'user-info', name: userName });
} catch (e) {
console.error('Key exchange failed:', e);
showNotification('keyImportFailed');
}
} else if (data.type === 'message') {
const decryptedText = await decryptMessageLocal(data);
const incoming = { id: data.id || createMessageId(), sender: 'remote', text: decryptedText, timestamp: formatTimestamp(), reactions: {} };
if (data.replyTo) incoming.replyTo = data.replyTo;
setMessages(prev => [...prev, incoming]);
showNotification('newMessage');
} else if (data.type === 'typing') {
setRemoteName(data.user || t('remoteUser'));
setIsTyping(true);
} else if (data.type === 'stop-typing') {
setIsTyping(false);
} else if (data.type === 'user-info') {
setRemoteName(data.name);
} else if (data.type === 'reaction') {
if (window.applyReactionToMessage) {
window.applyReactionToMessage(data.messageId, data.code, data.from, setMessages);
}
} else if (data.type === 'file-meta') {
handleIncomingFileMeta(data);
} else if (data.type === 'file-chunk') {
handleIncomingFileChunk(data);
} else if (data.type === 'file-data') {
receiveFile(data);
} else if (data.type === 'call-request') {
// call-requestを受け取った時点ではPeerJSのcallイベントはすでに発火済みのはず
setCallStatus('receiving');
} else if (data.type === 'call-end' || data.type === 'call-rejected') {
endCallCleanup();
}
};
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
useEffect(() => {
const generateShortId = () => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const arr = new Uint8Array(6);
crypto.getRandomValues(arr);
let id = '';
for (let i = 0; i < 6; i++) id += chars[arr[i] % chars.length];
return id;
};
const createPeerWithId = (id) => {
return new Promise((resolve, reject) => {
const peer = new Peer(id, {
config: {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
]
}
});
const onOpen = (openId) => { peer.off('open', onOpen); peer.off('error', onError); resolve({ peer, id: openId }); };
const onError = (err) => { peer.off('open', onOpen); peer.off('error', onError); try { peer.destroy(); } catch (e) { } reject(err); };
peer.on('open', onOpen);
peer.on('error', onError);
});
};
const tryCreatePeer = async (retries = 5) => {
myKeyPair.current = await generateX25519KeyPair();
for (let i = 0; i < retries; i++) {
const id = generateShortId();
try {
const { peer, id: openId } = await createPeerWithId(id);
peerInstance.current = peer;
setPeerId(openId);
setConnectionStatus('peerIdGenerated');
peer.on('connection', (conn) => {
connRef.current = conn;
setConnectionStatus('connecting');
conn.on('data', handleData);
conn.on('close', async () => {
setConnectionStatus('disconnected');
setMessages(prev => [...prev, { sender: 'system', text: t('connectionClosed'), timestamp: formatTimestamp() }]);
connRef.current = null;
cryptoKey.current = null;
myKeyPair.current = await generateX25519KeyPair();
showNotification('connectionClosed');
});
});
// 着信ハンドラ:callオブジェクトをrefに保持
peer.on('call', (call) => {
currentCallRef.current = call;
});
peer.on('error', (err) => {
setMessages(prev => [...prev, { sender: 'system', text: `${t('error')}: ${err.message}`, timestamp: formatTimestamp() }]);
setConnectionStatus('error');
});
return;
} catch (err) {
if (i === retries - 1) {
setConnectionStatus('error');
showNotification('connectionError');
}
}
}
};
tryCreatePeer();
return () => { try { peerInstance.current?.destroy(); } catch (e) { } };
}, []);
const connectToPeer = async () => {
if (!remotePeerId) { showNotification('enterPeerIdPrompt'); return; }
setConnectionStatus('connecting');
const conn = peerInstance.current.connect(remotePeerId);
connRef.current = conn;
conn.on('open', async () => {
setConnectionStatus('connected');
const myPubKeyBase64 = await exportPublicKey(myKeyPair.current);
conn.send({ type: 'pubkey', key: myPubKeyBase64, needsReply: true });
showNotification('connectionEstablished');
conn.on('data', handleData);
conn.on('close', async () => {
setConnectionStatus('disconnected');
setMessages(prev => [...prev, { sender: 'system', text: t('connectionClosed'), timestamp: formatTimestamp() }]);
connRef.current = null;
cryptoKey.current = null;
myKeyPair.current = await generateX25519KeyPair();
showNotification('connectionClosed');
});
});
conn.on('error', (err) => {
setMessages(prev => [...prev, { sender: 'system', text: `${t('connectionError')}: ${err.message}`, timestamp: formatTimestamp() }]);
setConnectionStatus('error');
});
};
const sendMessage = async () => {
if (message && connRef.current && cryptoKey.current) {
const encryptedMessage = await encryptMessageLocal(message);
if (!encryptedMessage) return;
const messageId = createMessageId();
const wrapper = { type: 'message', id: messageId, ...encryptedMessage };
if (replyTo) wrapper.replyTo = { text: replyTo.text, sender: replyTo.sender };
connRef.current.send(wrapper);
setMessages(prev => [...prev, { id: messageId, sender: 'local', text: message, timestamp: formatTimestamp(), replyTo: replyTo ? { text: replyTo.text, sender: replyTo.sender } : undefined, reactions: {} }]);
setMessage('');
setReplyTo(null);
if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
connRef.current.send({ type: 'stop-typing' });
}
} else {
showNotification('noConnection');
}
};
const handleKeyPress = (e) => { if (e.key === 'Enter') sendMessage(); };
const handleMessageChange = (e) => { setMessage(e.target.value); handleTyping(); };
const copyPeerId = () => { navigator.clipboard.writeText(peerId); showNotification('copyPeerId'); };
const disconnect = async () => {
if (connRef.current) {
connRef.current.close();
connRef.current = null;
cryptoKey.current = null;
myKeyPair.current = await generateX25519KeyPair();
setConnectionStatus('disconnected');
showNotification('connectionClosed');
}
};
const handleNameSubmit = () => {
if (userName.trim()) setIsNameSet(true);
else showNotification('enterName');
};
if (!isNameSet) {
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center">
<div className="bg-white rounded-lg shadow-xl p-6 max-w-md w-full">
<h1 className="text-2xl font-bold mb-4 text-center gradient-bg bg-clip-text text-transparent">
{t('enterName')}
</h1>
<input
type="text"
value={userName}
onChange={(e) => setUserName(e.target.value)}
placeholder={t('namePlaceholder')}
className="w-full p-3 border rounded-lg border-gray-300 mb-4"
onKeyPress={(e) => e.key === 'Enter' && handleNameSubmit()}
/>
<div className="mb-4">
<label className="block text-sm font-medium mb-1">{t('language')}</label>
<select
value={language}
onChange={(e) => setLanguage(e.target.value)}
className="w-full p-3 border rounded-lg border-gray-300"
>
<option value="en">English</option>
<option value="ja">日本語</option>
<option value="zh">中文</option>
<option value="hi">हिन्दी</option>
<option value="es">Español</option>
</select>
</div>
<button
onClick={handleNameSubmit}
className="w-full bg-blue-500 text-white px-6 py-3 rounded-lg hover:bg-blue-600 transition-colors"
>
{t('start')}
</button>
</div>
</div>
);
}
return (
<div className={`flex-1 min-h-0 ${isMobile ? 'overflow-auto pb-[calc(120px+env(safe-area-inset-bottom))]' : 'overflow-hidden pb-[44px]'} bg-gradient-to-br from-blue-50 to-indigo-100 flex flex-col`}>
{/* 着信UI */}
{callStatus === 'receiving' && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-60">
<div className="bg-white rounded-2xl shadow-2xl p-8 flex flex-col items-center gap-4 min-w-[260px]">
<div className="text-5xl animate-bounce">📞</div>
<div className="text-lg font-semibold">{remoteName || '相手'}</div>
<div className="text-gray-500 text-sm">着信中...</div>
<div className="flex gap-4 mt-2">
<button
onClick={answerCall}
className="bg-green-500 text-white px-6 py-3 rounded-full hover:bg-green-600 transition-colors font-semibold"
>
応答
</button>
<button
onClick={rejectCall}
className="bg-red-500 text-white px-6 py-3 rounded-full hover:bg-red-600 transition-colors font-semibold"
>
拒否
</button>
</div>
</div>
</div>
)}
{/* 発信中UI */}
{callStatus === 'calling' && (
isMobile ? (
<div className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-gray-900">
<div className="text-white text-xl font-semibold mb-2">{remoteName || '相手'}</div>
<div className="text-gray-400 text-sm mb-12">発信中...</div>
<div className="w-4 h-4 rounded-full bg-yellow-400 animate-ping mb-16"></div>
<button onClick={endCall} className="w-16 h-16 bg-red-500 rounded-full flex items-center justify-center shadow-xl">
<svg width="28" height="28" viewBox="0 0 24 24" fill="white"><path d="M6.6 10.8c1.4 2.8 3.8 5.1 6.6 6.6l2.2-2.2c.3-.3.7-.4 1-.2 1.1.4 2.3.6 3.6.6.6 0 1 .4 1 1V20c0 .6-.4 1-1 1-9.4 0-17-7.6-17-17 0-.6.4-1 1-1h3.5c.6 0 1 .4 1 1 0 1.3.2 2.5.6 3.6.1.3 0 .7-.2 1L6.6 10.8z" transform="rotate(135 12 12)" /></svg>
</button>
</div>
) : (
<div className="fixed bottom-16 right-4 z-40 bg-white rounded-2xl shadow-xl p-4 flex items-center gap-3">
<div className="w-2 h-2 rounded-full bg-yellow-400 animate-pulse"></div>
<span className="text-sm font-medium">発信中...</span>
<button onClick={endCall} className="bg-red-500 text-white px-3 py-1 rounded-full text-xs font-semibold hover:bg-red-600 transition-colors">キャンセル</button>
</div>
)
)}
{/* 通話中UI */}
{callStatus === 'ongoing' && (
isMobile ? (
<div className="fixed inset-0 z-50 flex flex-col items-center justify-between bg-gray-900 py-16 px-8">
<div className="flex flex-col items-center gap-2 mt-8">
<div className="w-20 h-20 rounded-full bg-gray-700 flex items-center justify-center text-3xl text-white font-bold">
{(remoteName || '?')[0].toUpperCase()}
</div>
<div className="text-white text-xl font-semibold mt-2">{remoteName || '相手'}</div>
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-green-400 animate-pulse"></div>
<span className="text-green-400 text-sm">通話中</span>
</div>
</div>
<div className="flex gap-8 items-center mb-4">
<div className="flex flex-col items-center gap-1">
<button
onClick={toggleMute}
className={`w-14 h-14 rounded-full flex items-center justify-center ${isMuted ? 'bg-red-500' : 'bg-gray-700'}`}
>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" />
<path d="M19 10v2a7 7 0 0 1-14 0v-2" />
<line x1="12" y1="19" x2="12" y2="23" />
<line x1="8" y1="23" x2="16" y2="23" />
</svg>
</button>
<span className="text-gray-400 text-xs">{isMuted ? 'ミュート中' : 'ミュート'}</span>
</div>
<div className="flex flex-col items-center gap-1">
<button onClick={endCall} className="w-16 h-16 bg-red-500 rounded-full flex items-center justify-center shadow-xl">
<svg width="28" height="28" viewBox="0 0 24 24" fill="white"><path d="M6.6 10.8c1.4 2.8 3.8 5.1 6.6 6.6l2.2-2.2c.3-.3.7-.4 1-.2 1.1.4 2.3.6 3.6.6.6 0 1 .4 1 1V20c0 .6-.4 1-1 1-9.4 0-17-7.6-17-17 0-.6.4-1 1-1h3.5c.6 0 1 .4 1 1 0 1.3.2 2.5.6 3.6.1.3 0 .7-.2 1L6.6 10.8z" transform="rotate(135 12 12)" /></svg>
</button>
<span className="text-gray-400 text-xs">終了</span>
</div>
<div className="flex flex-col items-center gap-1">
<button
onClick={toggleSpeaker}
className={`w-14 h-14 rounded-full flex items-center justify-center ${isSpeaker ? 'bg-green-600' : 'bg-gray-700'}`}
>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" />
<path d="M19.07 4.93a10 10 0 0 1 0 14.14" />
<path d="M15.54 8.46a5 5 0 0 1 0 7.07" />
</svg>
</button>
<span className="text-gray-400 text-xs">{isSpeaker ? 'スピーカー' : 'イヤホン'}</span>
</div>
</div>
</div>
) : (
<div className="fixed bottom-16 right-4 z-40 bg-white rounded-2xl shadow-xl p-4 flex items-center gap-3">
<div className="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div>
<span className="text-sm font-medium">通話中</span>
<button onClick={toggleMute} className={`px-3 py-1 rounded-full text-xs font-semibold transition-colors ${isMuted ? 'bg-red-100 text-red-600' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
{isMuted ? 'ミュート中' : 'ミュート'}
</button>
<button onClick={endCall} className="bg-red-500 text-white px-3 py-1 rounded-full text-xs font-semibold hover:bg-red-600 transition-colors">終了</button>
</div>
)
)}
{/* リモート音声出力 */}
<audio ref={remoteAudioRef} autoPlay />
{showQr && qrDataUrl && (
<Modal onClose={() => setShowQr(false)}>
<div className="bg-white rounded-3xl p-6 max-w-[90vw] w-[320px] sm:w-[360px] text-center shadow-2xl">
<img src={qrDataUrl} alt="QR Code" className="mx-auto w-56 h-56" />
<button
onClick={() => setShowQr(false)}
className="mt-4 bg-gray-800 text-white px-4 py-2 rounded-xl hover:bg-gray-900 transition-colors"
>
{t('close')}
</button>
</div>
</Modal>
)}
<div className={isMobile ? "max-w-4xl mx-auto w-full p-4 sm:p-6 flex-1 min-h-0 flex flex-col overflow-auto" : "max-w-4xl mx-auto w-full p-4 sm:p-6 overflow-y-auto flex-1"}>
{notification && (
<div className="fixed top-4 right-4 z-50 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg animate-pulse">
{notification}
</div>
)}
{connectionStatus !== 'connected' && (
<div className="bg-white rounded-lg shadow-xl p-6 mb-6">
<div className="flex justify-between items-center mb-4">
<h1 className="text-3xl font-bold gradient-bg bg-clip-text text-transparent">
{t('title')}
</h1>
</div>
<div className="grid grid-cols-1 gap-4">
<div className="grid grid-cols-1 md:grid-cols-[1fr_auto] gap-4 items-start">
<div>
<label className="block text-sm font-medium mb-1">{t('yourPeerId')}</label>
<div className="flex">
<input
type="text"
value={peerId}
readOnly
className="flex-1 p-2 border rounded-l-lg border-gray-300 font-mono text-sm"
/>
<button
onClick={copyPeerId}
disabled={!peerId}
className="bg-indigo-500 text-white px-4 py-2 rounded-none hover:bg-indigo-600 disabled:opacity-50 transition-colors"
>
{t('copy')}
</button>
<button
onClick={generateQrCode}
disabled={!peerId}
className="bg-indigo-500 text-white px-4 py-2 rounded-r-lg hover:bg-indigo-600 disabled:opacity-50 transition-colors"