webrtcapichat.html
73.6 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
<!--
AIfeng/2024-12-19
WebRTC API Chat - 数字人对话页面
功能:支持文字、语音输入与数字人实时对话,包含完整的对话记录功能
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<title>WebRTC 数字人</title>
<style>
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
display: flex;
height: 100vh;
}
/* 侧边栏样式 */
#sidebar {
width: 300px;
min-width: 300px;
max-width: 300px;
background-color: #f8f9fa;
padding: 20px;
box-shadow: 0 0 15px rgba(0,0,0,0.1);
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 15px;
transition: all 0.4s ease;
position: fixed;
top: 0;
left: 0;
height: 100vh;
border-radius: 0 10px 10px 0;
z-index: 50;
}
/* 收缩状态的侧边栏 */
#sidebar.collapsed {
width: 0;
min-width: 0;
padding: 0;
margin-left: 0;
opacity: 0;
transform: translateX(-100%);
}
/* 收缩状态下隐藏内容 */
#sidebar.collapsed > div {
display: none;
}
/* 切换按钮样式 */
#sidebar-toggle {
position: fixed;
bottom: 20px;
left: 20px;
width: 48px;
height: 48px;
background-color: #4285f4;
color: white;
border: none;
border-radius: 50%;
display: flex !important;
align-items: center;
justify-content: center;
cursor: pointer;
z-index: 1002 !important;
font-size: 20px;
box-shadow: 0 3px 8px rgba(0,0,0,0.2);
transition: all 0.3s ease;
opacity: 1 !important;
visibility: visible !important;
}
/* 主内容区域样式 */
#main-content {
margin-left: 300px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #f0f0f0;
overflow: visible;
transition: all 0.4s ease;
position: relative;
padding: 10px;
box-sizing: border-box;
min-height: 100vh;
width: calc(100vw - 300px);
}
/* 侧边栏收缩时主内容区域样式 */
#sidebar.collapsed ~ #main-content {
margin-left: 0;
width: 100vw;
}
/* 按钮样式 */
button {
padding: 8px 16px;
margin: 5px 0;
cursor: pointer;
border: none;
border-radius: 4px;
background-color: #4285f4;
color: white;
font-weight: bold;
}
button:hover {
background-color: #3367d6;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
/* 表单样式 */
.form-group {
margin-bottom: 15px;
width: 100%;
}
.form-control {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
/* 媒体区域样式 */
#media {
width: 100%;
max-width: 1080px;
height: 100%;
max-height: 90vh; /* 限制最大高度为视口高度的90% */
position: relative;
overflow: hidden;
background-color: #000;
margin: 0 auto; /* 居中显示 */
box-sizing: border-box; /* 确保padding不会增加宽度 */
aspect-ratio: 9/16; /* 设置宽高比为9:16(竖屏) */
display: block !important; /* 确保始终显示 */
z-index: 20; /* 提高z-index确保可见 */
}
#media h2 {
position: absolute;
top: 10px;
left: 10px;
color: white;
margin: 0;
z-index: 10;
background-color: rgba(0,0,0,0.5);
padding: 5px 10px;
border-radius: 4px;
}
video {
width: 100%;
height: 100%;
object-fit: contain; /* 保持视频比例 */
position: absolute;
top: 0;
left: 0;
max-width: 100%; /* 确保不超出容器 */
max-height: 100%; /* 确保不超出容器 */
}
/* 确保侧边栏收缩时视频元素本身也可见 */
#sidebar.collapsed ~ #main-content #video,
#sidebar.collapsed + #main-content #video {
display: block !important;
visibility: visible !important;
opacity: 1 !important;
}
/* 侧边栏收缩时媒体区域全屏显示 */
#sidebar.collapsed ~ #main-content #media {
width: 100vw;
height: 100vh;
max-width: none;
max-height: none;
aspect-ratio: unset;
margin: 0;
padding: 0;
border-radius: 0;
}
/* 侧边栏收缩时主内容区域调整 */
#sidebar.collapsed ~ #main-content {
padding: 0;
background-color: #000;
}
.option {
display: flex;
align-items: center;
margin-bottom: 8px;
}
.section-title {
font-weight: bold;
margin-bottom: 12px;
border-bottom: 1px solid #e0e0e0;
padding-bottom: 8px;
color: #4285f4;
font-size: 16px;
letter-spacing: 0.5px;
}
/* 美化表单控件 */
.form-control:focus {
outline: none;
border-color: #4285f4;
box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
}
/* 侧边栏内部元素样式优化 */
#sidebar > div {
background-color: white;
padding: 15px;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}
/* 聊天消息样式 */
#chatOverlay {
font-family: 'Microsoft YaHei', Arial, sans-serif;
}
#chatOverlay .message {
display: flex;
margin-bottom: 12px;
max-width: 100%;
animation: fadeInUp 0.3s ease-out;
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
#chatOverlay .message.right {
justify-content: flex-end;
}
#chatOverlay .message.left {
justify-content: flex-start;
}
#chatOverlay .avatar {
width: 28px;
height: 28px;
border-radius: 50%;
margin: 0 6px;
flex-shrink: 0;
border: 1px solid rgba(255,255,255,0.2);
background-color: rgba(255,255,255,0.5);
}
#chatOverlay .text-container {
background-color: rgba(255,255,255,0.5);
border-radius: 12px;
padding: 8px 12px;
max-width: 75%;
color: #333;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
position: relative;
}
#chatOverlay .message.right .text-container {
background-color: rgba(66,133,244,0.5);
color: white;
}
/* 数字人回复样式 - 根据模式区分 */
#chatOverlay .message.left .text-container {
background-color: rgba(248,249,250,0.5);
border-left: 3px solid #4285f4;
}
/* Echo模式 - 回音重复 */
#chatOverlay .message.left.mode-echo .text-container {
background-color: rgba(255,235,59,0.5);
border-left: 3px solid #FFC107;
color: #333;
}
/* Chat模式 - 大模型回复 */
#chatOverlay .message.left.mode-chat .text-container {
background-color: rgba(76,175,80,0.5);
border-left: 3px solid #4CAF50;
color: white;
}
/* Audio模式 - 语音识别回复 */
#chatOverlay .message.left.mode-audio .text-container {
background-color: rgba(156,39,176,0.5);
border-left: 3px solid #9C27B0;
color: white;
}
/* Plaintext模式 - 纯文本 */
#chatOverlay .message.left.mode-plaintext .text-container {
background-color: rgba(96,125,139,0.5);
border-left: 3px solid #607D8B;
color: white;
}
#chatOverlay .source-tag {
font-size: 8px;
color: #666;
background-color: rgba(66,133,244,0.1);
padding: 1px 4px;
border-radius: 6px;
margin-bottom: 3px;
display: inline-block;
font-weight: 500;
letter-spacing: 0.2px;
}
#chatOverlay .message.right .source-tag {
background-color: rgba(255,255,255,0.2);
color: rgba(255,255,255,0.9);
}
/* 不同模式的source-tag样式 */
#chatOverlay .message.left.mode-echo .source-tag {
background-color: rgba(255,193,7,0.2);
color: #E65100;
}
#chatOverlay .message.left.mode-chat .source-tag {
background-color: rgba(76,175,80,0.2);
color: #1B5E20;
}
#chatOverlay .message.left.mode-audio .source-tag {
background-color: rgba(156,39,176,0.2);
color: #4A148C;
}
#chatOverlay .message.left.mode-plaintext .source-tag {
background-color: rgba(96,125,139,0.2);
color: #263238;
}
#chatOverlay .text {
line-height: 1.3;
word-wrap: break-word;
margin-bottom: 3px;
font-size: 13px;
}
#chatOverlay .time {
font-size: 9px;
color: #999;
text-align: right;
margin-top: 3px;
opacity: 0.7;
}
#chatOverlay .message.right .time {
color: rgba(255,255,255,0.7);
}
/* 简化的聊天框头部 - 图标化 */
#chatOverlay .chat-header {
background-color: rgba(0,0,0,0.4);
color: rgba(255,255,255,0.9);
padding: 3px 8px;
border-radius: 0 0 8px 8px;
font-size: 10px;
font-weight: normal;
text-align: center;
margin: 0 -8px -8px -8px;
border-top: 1px solid rgba(255,255,255,0.15);
backdrop-filter: blur(8px);
position: relative;
flex-shrink: 0;
}
/* 清空按钮 */
#chatOverlay .clear-chat {
position: absolute;
top: 0px;
right: 15px;
background: none;
border: none;
color: rgba(255,255,255,0.6);
cursor: pointer;
font-size: 12px;
padding: 1px;
border-radius: 2px;
transition: all 0.2s;
}
#chatOverlay .clear-chat:hover {
background-color: rgba(255,255,255,0.1);
color: rgba(255,255,255,0.9);
}
/* 响应式适配 */
@media (max-width: 2560px) {
#chatOverlay {
width: min(800px, 40vw) !important;
height: 270px !important;
}
}
/* 响应式适配 */
@media (max-width: 2160px) {
#chatOverlay {
width: min(800px, 40vw) !important;
height: 270px !important;
}
}
/* 响应式适配 */
@media (max-width: 1200px) {
#chatOverlay {
width: min(600px, 40vw) !important;
height: 180px !important;
}
}
@media (max-width: 768px) {
#chatOverlay {
width: min(300px, 40vw) !important;
height: 160px !important;
bottom: 10px !important;
right: 10px !important;
}
}
@media (max-width: 480px) {
#chatOverlay {
width: min(200px, 45vw) !important;
height: 140px !important;
}
}
</style>
</head>
<body>
<!-- 侧边栏切换按钮 (Moved to be a direct child of body) -->
<button id="sidebar-toggle">≪</button>
<!-- 侧边栏 -->
<div id="sidebar">
<div>
<div class="section-title">连接控制</div>
<div class="option">
<input id="use-stun" type="checkbox"/>
<label for="use-stun">使用 STUN 服务器</label>
</div>
<button id="start" onclick="start()">开始连接</button>
<button id="stop" style="display: none" onclick="stop()">停止连接</button>
</div>
<div>
<div class="section-title">录制控制</div>
<button class="btn btn-primary" id="btn_start_record">开始录制</button>
<button class="btn btn-primary" id="btn_stop_record" disabled>停止录制</button>
</div>
<div>
<div class="section-title">文本输入</div>
<input type="hidden" id="sessionid" value="0">
<div class="form-group">
<label for="current-sessionid">当前会话ID</label>
<div class="input-group">
<input type="text" class="form-control" id="current-sessionid" readonly placeholder="未连接">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="clear-session-btn" title="清除会话ID,重新连接">重置</button>
</div>
</div>
</div>
<form class="form-inline" id="echo-form">
<div class="form-group">
<label for="message-type">消息类型</label>
<select class="form-control" id="message-type">
<option value="chat">智能对话</option>
<option value="echo">回音模式</option>
</select>
</div>
<div class="form-group">
<label for="message">输入文本</label>
<textarea rows="3" class="form-control" id="message">test</textarea>
</div>
<button type="submit" class="btn btn-default">发送</button>
</form>
</div>
<div>
<div class="section-title">对话框配置</div>
<div class="option">
<input id="show-chat-overlay" type="checkbox" checked/>
<label for="show-chat-overlay">显示对话框</label>
</div>
<div class="form-group">
<label for="chat-overlay-opacity">对话框透明度</label>
<input type="range" class="form-control" id="chat-overlay-opacity" min="10" max="90" value="50" step="10">
<small class="form-text text-muted">当前: <span id="opacity-value">50</span>%</small>
</div>
<div class="form-group">
<label for="message-opacity">消息框透明度</label>
<input type="range" class="form-control" id="message-opacity" min="10" max="90" value="50" step="10">
<small class="form-text text-muted">当前: <span id="message-opacity-value">50</span>%</small>
</div>
<button id="reset-chat-config" class="btn btn-secondary">重置配置</button>
</div>
<div>
<div class="section-title">本地存储设置</div>
<div class="option">
<input id="enable-storage" type="checkbox" checked/>
<label for="enable-storage">启用本地聊天记录</label>
</div>
<button id="load-history" class="btn btn-secondary">加载历史记录</button>
<button id="clear-storage" class="btn btn-danger">清理本地记录</button>
<button id="view-history" class="btn btn-info">查看历史记录</button>
</div>
<div>
<div class="section-title">控制服务器配置</div>
<div class="option">
<input id="enable-control-ws" type="checkbox" checked/>
<label for="enable-control-ws">启用控制服务器连接</label>
</div>
<div class="form-group">
<label for="control-ws-host">控制服务器主机</label>
<input type="text" class="form-control" id="control-ws-host" placeholder="默认: 127.0.0.1">
</div>
<div class="form-group">
<label for="control-ws-port">控制服务器端口</label>
<input type="text" class="form-control" id="control-ws-port" placeholder="默认: 10002">
</div>
<button id="save-control-ws-config" class="btn btn-default">保存控制配置</button>
<button id="reset-control-ws-config" class="btn btn-default">重置控制配置</button>
<button id="connect-control-ws" class="btn btn-default">连接控制服务器</button>
<button id="disconnect-control-ws" class="btn btn-default" disabled>断开控制服务器</button>
</div>
<div>
<div class="section-title">聊天服务器配置</div>
<div class="form-group">
<label for="chat-ws-host">聊天服务器主机</label>
<input type="text" class="form-control" id="chat-ws-host" placeholder="默认: localhost">
</div>
<div class="form-group">
<label for="chat-ws-port">聊天服务器端口</label>
<input type="text" class="form-control" id="chat-ws-port" placeholder="默认: 8010">
</div>
<button id="save-chat-ws-config" class="btn btn-default">保存聊天配置</button>
<button id="reset-chat-ws-config" class="btn btn-default">重置聊天配置</button>
</div>
</div>
<!-- 主内容区域 -->
<div id="main-content">
<input type="hidden" id="username" value="User">
<div id="media">
<h2>艺云展陈</h2>
<audio id="audio" autoplay="true"></audio>
<video id="video" autoplay="true" playsinline="true"></video>
</div>
<!-- 聊天消息显示区域 -->
<div id="chatOverlay" style="position: absolute; bottom: 15px; right: 15px; width: min(320px, 30vw); height: 200px; overflow: hidden; background-color: rgba(0,0,0,0.5); border-radius: 12px; padding: 8px; color: white; z-index: 1005; backdrop-filter: blur(15px); border: 1px solid rgba(255,255,255,0.08); display: flex; flex-direction: column;">
<div id="chatMessages" style="overflow: hidden; flex: 1; margin-bottom: 3px; display: flex; flex-direction: column; justify-content: flex-end; position: relative; cursor: pointer;">
<!-- 消息将在这里动态添加 -->
</div>
<div class="chat-header">
💬 对话
<button class="clear-chat" onclick="toggleChatOverlay()" title="隐藏对话框">−</button>
</div>
</div>
</div>
<script src="client.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.1/dist/sockjs.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
// Function to update toggle button icon based on sidebar state
function updateToggleButtonState() {
var sidebarIsCollapsed = $('#sidebar').hasClass('collapsed');
var toggleButton = $('#sidebar-toggle');
if (sidebarIsCollapsed) {
toggleButton.html('≫');
} else {
toggleButton.html('≪');
}
}
// Initial state setup for the toggle button
updateToggleButtonState();
// Load saved WebSocket configuration or set defaults
function loadWsConfig() {
// 控制服务器配置
var savedControlHost = localStorage.getItem('controlWsHost');
var savedControlPort = localStorage.getItem('controlWsPort');
var enableControlWs = localStorage.getItem('enableControlWs');
if (savedControlHost) {
$('#control-ws-host').val(savedControlHost);
} else {
$('#control-ws-host').val('127.0.0.1'); // Default host
}
if (savedControlPort) {
$('#control-ws-port').val(savedControlPort);
} else {
$('#control-ws-port').val('10002'); // Default port
}
// 设置控制服务器开关状态
if (enableControlWs !== null) {
$('#enable-control-ws').prop('checked', enableControlWs === 'true');
}
// 聊天服务器配置
var savedChatHost = localStorage.getItem('chatWsHost');
var savedChatPort = localStorage.getItem('chatWsPort');
if (savedChatHost) {
$('#chat-ws-host').val(savedChatHost);
} else {
$('#chat-ws-host').val('localhost'); // Default host
}
if (savedChatPort) {
$('#chat-ws-port').val(savedChatPort);
} else {
$('#chat-ws-port').val('8010'); // Default port
}
// 初始化控制服务器连接按钮状态
$('#connect-control-ws').prop('disabled', false);
$('#disconnect-control-ws').prop('disabled', true);
}
loadWsConfig(); // Load config on document ready
// 初始化聊天滚轮支持
initChatWheelSupport();
// 侧边栏切换功能
$('#sidebar-toggle').click(function() {
$('#sidebar').toggleClass('collapsed');
updateToggleButtonState();
});
// Note: The original '#expand-sidebar'.click handler was part of the replaced block.
// If an element with id #expand-sidebar exists and needs to control the sidebar,
// its click handler should be re-implemented similar to this:
// $('#expand-sidebar').click(function() {
// if ($('#sidebar').hasClass('collapsed')) {
// $('#sidebar').removeClass('collapsed');
// updateToggleButtonState();
// }
// });
// 控制服务器配置保存和重置
$('#save-control-ws-config').click(function() {
var controlHost = $('#control-ws-host').val().trim();
var controlPort = $('#control-ws-port').val().trim();
var enableControl = $('#enable-control-ws').prop('checked');
if (!controlHost) {
alert('控制服务器主机不能为空。');
$('#control-ws-host').focus();
return;
}
if (!controlPort) {
alert('控制服务器端口不能为空。');
$('#control-ws-port').focus();
return;
}
localStorage.setItem('controlWsHost', controlHost);
localStorage.setItem('controlWsPort', controlPort);
localStorage.setItem('enableControlWs', enableControl.toString());
var originalText = $(this).text();
$(this).text('已保存!').prop('disabled', true);
setTimeout(function() {
$('#save-control-ws-config').text(originalText).prop('disabled', false);
}, 1500);
console.log('控制服务器配置已保存: Host - ' + controlHost + ', Port - ' + controlPort + ', Enabled - ' + enableControl);
});
// 聊天服务器配置保存
$('#save-chat-ws-config').click(function() {
var chatHost = $('#chat-ws-host').val().trim();
var chatPort = $('#chat-ws-port').val().trim();
if (!chatHost) {
alert('聊天服务器主机不能为空。');
$('#chat-ws-host').focus();
return;
}
if (!chatPort) {
alert('聊天服务器端口不能为空。');
$('#chat-ws-port').focus();
return;
}
localStorage.setItem('chatWsHost', chatHost);
localStorage.setItem('chatWsPort', chatPort);
var originalText = $(this).text();
$(this).text('已保存!').prop('disabled', true);
setTimeout(function() {
$('#save-chat-ws-config').text(originalText).prop('disabled', false);
}, 1500);
console.log('聊天服务器配置已保存: Host - ' + chatHost + ', Port - ' + chatPort);
});
// 控制服务器配置重置
$('#reset-control-ws-config').click(function() {
$('#control-ws-host').val('127.0.0.1');
$('#control-ws-port').val('10002');
$('#enable-control-ws').prop('checked', true);
var originalText = $(this).text();
$(this).text('已重置!').prop('disabled', true);
setTimeout(function() {
$('#reset-control-ws-config').text(originalText).prop('disabled', false);
}, 1500);
console.log('控制服务器配置已重置为默认值');
});
// 聊天服务器配置重置
$('#reset-chat-ws-config').click(function() {
$('#chat-ws-host').val('localhost');
$('#chat-ws-port').val('8010');
var originalText = $(this).text();
$(this).text('已重置!').prop('disabled', true);
setTimeout(function() {
$('#reset-chat-ws-config').text(originalText).prop('disabled', false);
}, 1500);
console.log('聊天服务器配置已重置为默认值');
});
// 控制服务器连接管理
var controlWs = null;
$('#connect-control-ws').click(function() {
if (!$('#enable-control-ws').prop('checked')) {
alert('请先启用控制服务器连接');
return;
}
var controlHost = $('#control-ws-host').val().trim() || '127.0.0.1';
var controlPort = $('#control-ws-port').val().trim() || '10002';
var controlWsUrl = 'ws://' + controlHost + ':' + controlPort + '/ws';
console.log('连接控制服务器:', controlWsUrl);
controlWs = new WebSocket(controlWsUrl);
controlWs.onopen = function() {
console.log('控制服务器连接成功');
$('#connect-control-ws').prop('disabled', true);
$('#disconnect-control-ws').prop('disabled', false);
};
controlWs.onclose = function() {
console.log('控制服务器连接关闭');
$('#connect-control-ws').prop('disabled', false);
$('#disconnect-control-ws').prop('disabled', true);
};
controlWs.onerror = function(error) {
console.error('控制服务器连接错误:', error);
alert('控制服务器连接失败');
};
});
$('#disconnect-control-ws').click(function() {
if (controlWs) {
controlWs.close();
controlWs = null;
}
});
// 控制服务器开关状态变化处理
$('#enable-control-ws').change(function() {
var enabled = $(this).prop('checked');
localStorage.setItem('enableControlWs', enabled.toString());
if (!enabled && controlWs) {
controlWs.close();
controlWs = null;
}
});
// Old WebSocket code commented out
// var host = window.location.hostname
// var ws = new WebSocket("ws://"+host+":8000/humanecho");
// //document.getElementsByTagName("video")[0].setAttribute("src", aa["video"]);
// ws.onopen = function() {
// console.log('Connected');
// };
// ws.onmessage = function(e) {
// console.log('Received: ' + e.data);
// data = e
// var vid = JSON.parse(data.data);
// console.log(typeof(vid),vid)
// //document.getElementsByTagName("video")[0].setAttribute("src", vid["video"]);
// };
// ws.onclose = function(e) {
// console.log('Closed');
// };
$('#echo-form').on('submit', function(e) {
e.preventDefault();
var message = $('#message').val().trim();
if (!message) return;
console.log('Sending: ' + message);
console.log('sessionid: ', document.getElementById('sessionid').value);
// 保存最后一条用户消息用于模式判断
localStorage.setItem('lastUserMessage', message);
// 获取选择的消息类型,默认为chat
var messageType = document.getElementById('message-type') ? document.getElementById('message-type').value : 'chat';
// 发送消息到服务器,不再直接添加到界面,等待WebSocket推送
var requestData = {
text: message,
type: messageType,
interrupt: true,
sessionid: parseInt(document.getElementById('sessionid').value),
};
console.log('准备发送HTTP请求到/human:', requestData);
console.log('当前WebSocket连接状态:', ws ? ws.readyState : 'WebSocket未初始化');
fetch('/human', {
body: JSON.stringify(requestData),
headers: {
'Content-Type': 'application/json',
'X-Request-Source': 'web'
},
method: 'POST'
}).then(response => {
console.log('HTTP响应状态:', response.status);
return response.json();
}).then(data => {
console.log('/human接口响应:', data);
if (data.code !== 0) {
console.error('服务器处理失败:', data.message || data.msg);
}
// 所有消息显示都通过WebSocket推送,不再从HTTP响应获取数据
}).catch(error => {
console.error('发送消息错误:', error);
// 网络错误时添加错误消息到界面
addMessage(`网络错误: ${error.message}`, 'left', '系统错误', 'error');
});
$('#message').val('');
});
// 本地存储设置事件处理
$('#enable-storage').change(function() {
const enabled = $(this).is(':checked');
ChatStorage.setStorageEnabled(enabled);
console.log('本地存储已', enabled ? '启用' : '禁用');
});
$('#load-history').click(function() {
loadChatHistory();
alert('历史记录已加载!');
});
$('#clear-storage').click(function() {
if (confirm('确定要清理所有本地聊天记录吗?此操作不可恢复!')) {
ChatStorage.clearStorage();
const chatMessages = document.getElementById("chatMessages");
if (chatMessages) {
chatMessages.innerHTML = '';
}
alert('本地记录已清理!');
}
});
$('#view-history').click(function() {
const dates = ChatStorage.getAllDates();
if (dates.length === 0) {
alert('暂无历史记录');
return;
}
let historyHtml = '<div style="max-height: 400px; overflow-y: auto; padding: 10px;">';
historyHtml += '<h3>聊天记录</h3>';
dates.forEach(date => {
const dateHistory = ChatStorage.getDateHistory(date);
historyHtml += `<h4>${date} (${dateHistory.length}条消息)</h4>`;
dateHistory.forEach(msg => {
const time = new Date(msg.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
const sourceIcon = msg.type === 'right' ? '👤' : '🤖';
historyHtml += `<div style="margin: 5px 0; padding: 5px; border-left: 3px solid ${msg.type === 'right' ? '#4285f4' : '#4CAF50'}; background: #f9f9f9;">`;
historyHtml += `<small>${sourceIcon} ${time} - 会话${msg.sessionId}</small><br>`;
historyHtml += `<span>${msg.text}</span>`;
historyHtml += '</div>';
});
});
historyHtml += '</div>';
// 创建模态框显示历史记录
const modal = document.createElement('div');
modal.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center;';
const content = document.createElement('div');
content.style.cssText = 'background: white; border-radius: 8px; max-width: 80%; max-height: 80%; overflow: hidden;';
content.innerHTML = historyHtml + '<div style="text-align: center; padding: 10px;"><button onclick="this.closest(\'div\').parentElement.remove()" style="padding: 8px 16px; background: #4285f4; color: white; border: none; border-radius: 4px; cursor: pointer;">关闭</button></div>';
modal.appendChild(content);
document.body.appendChild(modal);
// 点击背景关闭
modal.addEventListener('click', function(e) {
if (e.target === modal) {
modal.remove();
}
});
});
// 页面加载时初始化存储设置
$(document).ready(function() {
const storageEnabled = ChatStorage.isStorageEnabled();
$('#enable-storage').prop('checked', storageEnabled);
// 自动加载历史记录
if (storageEnabled) {
setTimeout(loadChatHistory, 1000); // 延迟1秒加载,确保页面完全加载
}
// 初始化对话框配置
loadChatOverlayConfig();
// 对话框显示/隐藏开关
$('#show-chat-overlay').change(function() {
const chatOverlay = document.getElementById('chatOverlay');
if (this.checked) {
chatOverlay.style.display = 'flex';
localStorage.setItem('chatOverlayVisible', 'true');
} else {
chatOverlay.style.display = 'none';
localStorage.setItem('chatOverlayVisible', 'false');
}
});
// 对话框透明度滑块
$('#chat-overlay-opacity').on('input', function() {
const opacity = this.value;
$('#opacity-value').text(opacity);
updateChatOverlayOpacity(parseInt(opacity));
});
// 消息框透明度滑块
$('#message-opacity').on('input', function() {
const opacity = this.value;
$('#message-opacity-value').text(opacity);
updateMessageOpacity(parseInt(opacity));
});
// 重置对话框配置
$('#reset-chat-config').click(function() {
// 重置为默认值
$('#show-chat-overlay').prop('checked', true);
$('#chat-overlay-opacity').val(50);
$('#opacity-value').text('50');
$('#message-opacity').val(50);
$('#message-opacity-value').text('50');
// 应用默认设置
document.getElementById('chatOverlay').style.display = 'flex';
updateChatOverlayOpacity(50);
updateMessageOpacity(50);
// 清除本地存储
localStorage.removeItem('chatOverlayVisible');
localStorage.removeItem('chatOverlayOpacity');
localStorage.removeItem('messageOpacity');
// 提示用户
const originalText = $(this).text();
$(this).text('已重置!').prop('disabled', true);
setTimeout(() => {
$(this).text(originalText).prop('disabled', false);
}, 1500);
});
});
$('#btn_start_record').click(function() {
console.log('Starting recording...');
fetch('/record', {
body: JSON.stringify({
type: 'start_record',
sessionid: parseInt(document.getElementById('sessionid').value),
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
}).then(function(response) {
if (response.ok) {
console.log('Recording started.');
$('#btn_start_record').prop('disabled', true);
$('#btn_stop_record').prop('disabled', false);
} else {
console.error('Failed to start recording.');
}
}).catch(function(error) {
console.error('Error:', error);
});
});
$('#btn_stop_record').click(function() {
console.log('Stopping recording...');
fetch('/record', {
body: JSON.stringify({
type: 'end_record',
sessionid: parseInt(document.getElementById('sessionid').value),
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
}).then(function(response) {
if (response.ok) {
console.log('Recording stopped.');
$('#btn_start_record').prop('disabled', false);
$('#btn_stop_record').prop('disabled', true);
} else {
console.error('Failed to stop recording.');
}
}).catch(function(error) {
console.error('Error:', error);
});
});
// WebSocket connection to Fay digital avatar (port 10002)
var ws;
var reconnectInterval = 5000; // 初始重连间隔为5秒
var reconnectAttempts = 0;
var maxReconnectInterval = 60000; // 最大重连间隔为60秒
var isReconnecting = false; // 标记是否正在重连中
function generateUsername() {
var username = 'User';
// + Math.floor(Math.random() * 10000)
return username;
}
function setUsername() {
var storedUsername = localStorage.getItem('username');
// console.log("当前存有的username:"+storedUsername);
if (!storedUsername) {
storedUsername = generateUsername();
localStorage.setItem('username', storedUsername);
}
$('#username').val(storedUsername); // Use the username as the session ID
}
setUsername();
// 页面加载时恢复聊天记录
function loadChatHistory() {
const recentMessages = ChatStorage.loadRecentMessages();
const chatMessages = document.getElementById("chatMessages");
if (chatMessages && recentMessages.length > 0) {
// 清空现有消息
chatMessages.innerHTML = '';
// 添加历史消息
recentMessages.forEach(msg => {
addMessage(msg.text, msg.type, msg.source, msg.mode, msg.modelInfo || '', msg.requestSource || '');
});
console.log(`已加载 ${recentMessages.length} 条历史消息`);
}
}
// 本地存储管理
const ChatStorage = {
// 获取存储设置
isStorageEnabled: function() {
return localStorage.getItem('chatStorageEnabled') !== 'false';
},
// 设置存储开关
setStorageEnabled: function(enabled) {
localStorage.setItem('chatStorageEnabled', enabled.toString());
},
// 保存消息到本地存储
saveMessage: function(messageData) {
if (!this.isStorageEnabled()) return;
const sessionId = document.getElementById('sessionid').value;
const storageKey = `chat_history_${sessionId}`;
let history = JSON.parse(localStorage.getItem(storageKey) || '[]');
// 添加新消息
history.push({
...messageData,
timestamp: new Date().toISOString(),
date: new Date().toDateString()
});
// 保存到localStorage
localStorage.setItem(storageKey, JSON.stringify(history));
// 同时保存到按日期分组的存储中
this.saveToDateStorage(messageData);
},
// 按日期保存消息
saveToDateStorage: function(messageData) {
const today = new Date().toDateString();
const dateKey = `chat_date_${today.replace(/\s+/g, '_')}`;
let dateHistory = JSON.parse(localStorage.getItem(dateKey) || '[]');
dateHistory.push({
...messageData,
timestamp: new Date().toISOString(),
sessionId: document.getElementById('sessionid').value
});
localStorage.setItem(dateKey, JSON.stringify(dateHistory));
},
// 加载最近12条消息
loadRecentMessages: function() {
if (!this.isStorageEnabled()) return [];
const sessionId = document.getElementById('sessionid').value;
const storageKey = `chat_history_${sessionId}`;
const history = JSON.parse(localStorage.getItem(storageKey) || '[]');
// 返回最后12条消息
return history.slice(-12);
},
// 获取所有日期的聊天记录
getAllDates: function() {
const dates = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith('chat_date_')) {
const date = key.replace('chat_date_', '').replace(/_/g, ' ');
dates.push(date);
}
}
return dates.sort((a, b) => new Date(b) - new Date(a));
},
// 获取指定日期的聊天记录
getDateHistory: function(date) {
const dateKey = `chat_date_${date.replace(/\s+/g, '_')}`;
return JSON.parse(localStorage.getItem(dateKey) || '[]');
},
// 清理本地记录
clearStorage: function() {
const keys = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && (key.startsWith('chat_history_') || key.startsWith('chat_date_'))) {
keys.push(key);
}
}
keys.forEach(key => localStorage.removeItem(key));
}
};
// 全局 addMessage 函数定义
function addMessage(text, type = "right", source = "", mode = "", modelInfo = "", requestSource = "") {
const chatMessages = document.getElementById("chatMessages");
if (!chatMessages) {
console.error('聊天消息容器不存在');
return;
}
// 创建消息数据对象
const messageData = {
text: text,
type: type,
source: source,
mode: mode,
modelInfo: modelInfo,
requestSource: requestSource
};
// 保存到本地存储
ChatStorage.saveMessage(messageData);
const messageDiv = document.createElement("div");
messageDiv.classList.add("message", type);
// 为左侧消息添加模式类
if (type === "left" && mode) {
messageDiv.classList.add("mode-" + mode);
}
const avatar = document.createElement("div");
avatar.classList.add("avatar");
avatar.style.width = "28px";
avatar.style.height = "28px";
avatar.style.borderRadius = "50%";
avatar.style.display = "flex";
avatar.style.alignItems = "center";
avatar.style.justifyContent = "center";
avatar.style.fontSize = "12px";
avatar.style.fontWeight = "bold";
avatar.style.color = "white";
avatar.style.border = "1px solid rgba(255,255,255,0.2)";
if (type === "right") {
avatar.style.backgroundColor = "#4285f4";
avatar.textContent = "👤";
} else {
// 根据模式设置不同的头像和颜色
switch(mode) {
case "echo":
avatar.style.backgroundColor = "#FFC107";
avatar.textContent = "🔄";
break;
case "chat":
avatar.style.backgroundColor = "#4CAF50";
avatar.textContent = "🤖";
break;
case "audio":
avatar.style.backgroundColor = "#9C27B0";
avatar.textContent = "🎤";
break;
case "plaintext":
avatar.style.backgroundColor = "#607D8B";
avatar.textContent = "📝";
break;
default:
avatar.style.backgroundColor = "#34a853";
avatar.textContent = "🤖";
}
}
const textContainer = document.createElement("div");
textContainer.classList.add("text-container");
// 添加来源标签
if (source) {
const sourceTag = document.createElement("div");
sourceTag.classList.add("source-tag");
// 根据模式显示不同的标签文本
let tagText = source;
if (type === "right") {
// 用户消息,显示请求来源
if (requestSource) {
tagText = requestSource === 'web' ? "🌐 网页" : requestSource === 'api' ? "🔗 API" : "👤 用户";
} else {
tagText = "👤 用户";
}
} else {
// 数字人回复,显示模式和模型信息
switch(mode) {
case "echo":
tagText = "🔄 回音";
break;
case "chat":
tagText = modelInfo ? `🤖 ${modelInfo}` : "🤖 智能";
break;
case "audio":
tagText = "🎤 语音";
break;
case "plaintext":
tagText = "📝 文本";
break;
default:
tagText = "🤖 数字人";
}
}
sourceTag.textContent = tagText;
textContainer.appendChild(sourceTag);
}
const textDiv = document.createElement("div");
textDiv.classList.add("text");
textDiv.textContent = text;
textContainer.appendChild(textDiv);
const timeDiv = document.createElement("div");
timeDiv.classList.add("time");
const now = new Date();
timeDiv.textContent = now.toLocaleTimeString('zh-CN', { hour12: false });
textContainer.appendChild(timeDiv);
if (type === "right") {
messageDiv.appendChild(textContainer);
messageDiv.appendChild(avatar);
} else {
messageDiv.appendChild(avatar);
messageDiv.appendChild(textContainer);
}
chatMessages.appendChild(messageDiv);
// 限制消息数量,只保留最新的12条消息
const messages = chatMessages.children;
const maxMessages = 12;
while (messages.length > maxMessages) {
chatMessages.removeChild(messages[0]);
}
// 显示聊天区域(如果之前隐藏)
const chatOverlay = document.getElementById("chatOverlay");
if (chatOverlay) {
chatOverlay.style.display = "flex";
}
// 保存聊天记录
saveChatHistory();
}
// 清空聊天记录函数
function clearChatHistory() {
const chatMessages = document.getElementById("chatMessages");
if (chatMessages) {
chatMessages.innerHTML = "";
}
localStorage.removeItem('chatHistory');
}
// 切换对话框显示/隐藏
function toggleChatOverlay() {
const chatOverlay = document.getElementById('chatOverlay');
const showCheckbox = document.getElementById('show-chat-overlay');
if (chatOverlay.style.display === 'none') {
chatOverlay.style.display = 'flex';
showCheckbox.checked = true;
localStorage.setItem('chatOverlayVisible', 'true');
} else {
chatOverlay.style.display = 'none';
showCheckbox.checked = false;
localStorage.setItem('chatOverlayVisible', 'false');
}
}
// 更新对话框透明度
function updateChatOverlayOpacity(opacity) {
const chatOverlay = document.getElementById('chatOverlay');
const newBgColor = `rgba(0,0,0,${opacity / 100})`;
chatOverlay.style.backgroundColor = newBgColor;
localStorage.setItem('chatOverlayOpacity', opacity);
}
// 更新消息框透明度
function updateMessageOpacity(opacity) {
const style = document.createElement('style');
style.id = 'dynamic-message-opacity';
// 移除旧的样式
const oldStyle = document.getElementById('dynamic-message-opacity');
if (oldStyle) {
oldStyle.remove();
}
style.innerHTML = `
#chatOverlay .text-container {
background-color: rgba(255,255,255,${opacity / 100}) !important;
}
#chatOverlay .message.right .text-container {
background-color: rgba(66,133,244,${opacity / 100}) !important;
}
#chatOverlay .message.left .text-container {
background-color: rgba(248,249,250,${opacity / 100}) !important;
}
#chatOverlay .message.left.mode-echo .text-container {
background-color: rgba(255,235,59,${opacity / 100}) !important;
}
#chatOverlay .message.left.mode-chat .text-container {
background-color: rgba(76,175,80,${opacity / 100}) !important;
}
#chatOverlay .message.left.mode-audio .text-container {
background-color: rgba(156,39,176,${opacity / 100}) !important;
}
#chatOverlay .message.left.mode-plaintext .text-container {
background-color: rgba(96,125,139,${opacity / 100}) !important;
}
#chatOverlay .avatar {
background-color: rgba(255,255,255,${opacity / 100}) !important;
}
`;
document.head.appendChild(style);
localStorage.setItem('messageOpacity', opacity);
}
// 加载对话框配置
function loadChatOverlayConfig() {
// 加载显示状态
const isVisible = localStorage.getItem('chatOverlayVisible');
if (isVisible === 'false') {
document.getElementById('chatOverlay').style.display = 'none';
document.getElementById('show-chat-overlay').checked = false;
}
// 加载透明度设置
const overlayOpacity = localStorage.getItem('chatOverlayOpacity') || '50';
const messageOpacity = localStorage.getItem('messageOpacity') || '50';
document.getElementById('chat-overlay-opacity').value = overlayOpacity;
document.getElementById('opacity-value').textContent = overlayOpacity;
updateChatOverlayOpacity(parseInt(overlayOpacity));
document.getElementById('message-opacity').value = messageOpacity;
document.getElementById('message-opacity-value').textContent = messageOpacity;
updateMessageOpacity(parseInt(messageOpacity));
}
// 初始化聊天滚轮支持
function initChatWheelSupport() {
const chatMessages = document.getElementById("chatMessages");
const chatOverlay = document.getElementById("chatOverlay");
if (!chatMessages || !chatOverlay) return;
let scrollPosition = 0; // 当前滚动位置
const scrollStep = 25; // 每次滚动的像素数
let isScrolling = false; // 防止滚动冲突
let lastWheelTime = 0; // 上次滚轮事件时间
const throttleDelay = 16; // 约60fps的节流延迟
// 节流函数
function throttle(func, delay) {
return function(...args) {
const now = Date.now();
if (now - lastWheelTime >= delay) {
lastWheelTime = now;
func.apply(this, args);
}
};
}
// 滚轮处理函数
function handleWheel(e) {
e.preventDefault();
e.stopPropagation();
if (isScrolling) return;
const messages = chatMessages.children;
if (messages.length === 0) return;
// 计算总内容高度
let totalHeight = 0;
for (let i = 0; i < messages.length; i++) {
totalHeight += messages[i].offsetHeight + 12; // 12px是margin-bottom
}
const containerHeight = chatMessages.offsetHeight;
const maxScroll = Math.max(0, totalHeight - containerHeight);
// 如果内容不超出容器,不需要滚动
if (maxScroll <= 0) return;
isScrolling = true;
// 根据滚轮方向和强度调整滚动位置
const delta = Math.sign(e.deltaY) * scrollStep;
const newPosition = Math.max(0, Math.min(scrollPosition + delta, maxScroll));
if (newPosition !== scrollPosition) {
scrollPosition = newPosition;
// 应用滚动效果
chatMessages.style.transform = `translateY(-${scrollPosition}px)`;
chatMessages.style.transition = 'transform 0.08s ease-out';
// 清除过渡效果和滚动锁定
setTimeout(() => {
chatMessages.style.transition = '';
isScrolling = false;
}, 80);
} else {
isScrolling = false;
}
}
// 使用节流的滚轮处理函数
const throttledWheelHandler = throttle(handleWheel, throttleDelay);
// 同时在chatMessages和chatOverlay上绑定事件,提高响应性
chatMessages.addEventListener('wheel', throttledWheelHandler, { passive: false });
chatOverlay.addEventListener('wheel', throttledWheelHandler, { passive: false });
// 当新消息添加时,自动滚动到底部
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
// 重置滚动位置到底部
scrollPosition = 0;
chatMessages.style.transform = 'translateY(0)';
chatMessages.style.transition = '';
}
});
});
observer.observe(chatMessages, { childList: true });
// 返回清理函数
return function cleanup() {
chatMessages.removeEventListener('wheel', throttledWheelHandler);
chatOverlay.removeEventListener('wheel', throttledWheelHandler);
observer.disconnect();
};
}
// 保存聊天记录到本地存储
function saveChatHistory() {
const chatMessages = document.getElementById("chatMessages");
if (chatMessages) {
localStorage.setItem('chatHistory', chatMessages.innerHTML);
}
}
// 从本地存储加载聊天记录
function loadChatHistory() {
const savedHistory = localStorage.getItem('chatHistory');
const chatMessages = document.getElementById("chatMessages");
if (savedHistory && chatMessages) {
chatMessages.innerHTML = savedHistory;
// 自动滚动到底部
chatMessages.scrollTop = chatMessages.scrollHeight;
}
}
function connectWebSocket() {
var host = window.location.hostname;
// 获取聊天服务器WebSocket地址,优先使用配置值,否则使用当前主机名
var chatWsHost = localStorage.getItem('chatWsHost') || host;
var chatWsPort = localStorage.getItem('chatWsPort') || '8010'; // 聊天服务器端口
var wsProtocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
var wsUrl = wsProtocol + chatWsHost + ':' + chatWsPort + '/ws'; // 聊天服务器WebSocket路径
console.log('Connecting to WebSocket server:', wsUrl);
ws = new WebSocket(wsUrl);
ws.onopen = function() {
console.log('Connected to WebSocket server');
console.log('WebSocket URL:', ws.url);
console.log('WebSocket readyState:', ws.readyState);
reconnectAttempts = 0; // 重置重连次数
reconnectInterval = 5000; // 重置重连间隔
// 等待sessionid设置完成后再发送登录消息
function attemptLogin(retryCount = 0) {
var sessionid = parseInt(document.getElementById('sessionid').value) || 0;
if (sessionid === 0 && retryCount < 20) {
console.log(`等待sessionid设置,重试次数: ${retryCount + 1}/20`);
setTimeout(() => attemptLogin(retryCount + 1), 200);
return;
}
if (sessionid === 0) {
console.error('sessionid仍为0,WebRTC连接可能失败,使用默认值继续');
// 即使sessionid为0也尝试连接,但会在日志中标记
}
var loginMessage = {
type: 'login',
sessionid: sessionid,
username: $('#username').val() || 'User'
};
console.log('发送登录消息:', loginMessage);
console.log('当前sessionid值:', sessionid);
console.log('sessionid元素值:', document.getElementById('sessionid').value);
ws.send(JSON.stringify(loginMessage));
console.log('登录消息已发送:', JSON.stringify(loginMessage));
// 更新显示的sessionId
if (sessionid !== 0) {
document.getElementById('current-sessionid').value = sessionid;
document.getElementById('current-sessionid').placeholder = '已连接';
}
}
// 开始尝试登录
attemptLogin();
// 发送心跳检测
setInterval(function() {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({type: 'ping'}));
}
}, 30000); // 每30秒发送一次心跳
};
ws.onmessage = function(e) {
console.log('WebSocket原始消息:', e.data);
console.log('WebSocket连接状态:', ws.readyState);
var messageData = JSON.parse(e.data);
console.log('解析后的消息数据:', messageData);
// 处理聊天消息推送
if (messageData.type === 'chat_message') {
var data = messageData.data;
console.log('收到聊天消息推送:', data);
console.log('消息sessionid:', data.sessionid);
console.log('当前页面sessionid:', document.getElementById('sessionid').value);
// 根据消息来源确定显示位置
var position = data.source === '用户' ? 'right' : 'left';
var messageType = data.message_type || 'chat';
var modelInfo = data.model_info || '';
var requestSource = data.request_source || '';
console.log('准备添加消息到界面:', {
content: data.content,
position: position,
source: data.source,
messageType: messageType,
modelInfo: modelInfo,
requestSource: requestSource
});
// 添加消息到聊天界面
addMessage(data.content, position, data.source, messageType, modelInfo, requestSource);
return;
}
// 处理登录成功消息
if (messageData.type === 'login_success') {
console.log('WebSocket登录成功:', messageData.message);
console.log('登录成功的sessionid:', messageData.sessionid);
return;
}
// 处理心跳响应
if (messageData.type === 'pong') {
console.log('收到心跳响应');
return;
}
// 处理服务器推送的聊天消息
if (messageData.type === 'chat_message') {
console.log('收到聊天消息:', messageData);
var messageContent = messageData.content || messageData.message || '';
var messageType = messageData.message_type || 'text';
var sender = messageData.sender || 'unknown';
var sessionId = messageData.session_id;
var modelInfo = messageData.model_info || '';
var requestSource = messageData.request_source || '';
var timestamp = messageData.timestamp || new Date().toISOString();
// 判断消息方向和样式
var alignment = 'left';
var senderLabel = '数字人回复';
var messageMode = messageType;
if (sender === '用户' || sender === 'user' || sender === 'human') {
alignment = 'right';
senderLabel = '用户';
if (messageType === 'audio') {
senderLabel = '用户语音';
messageContent = '[语音输入]';
}
} else if (sender === 'AI助手' || sender === 'ai' || sender === 'assistant') {
alignment = 'left';
senderLabel = modelInfo ? `AI回复(${modelInfo})` : 'AI回复';
} else if (sender === '回音') {
alignment = 'left';
senderLabel = modelInfo ? `回音模式(${modelInfo})` : '回音模式';
} else if (sender === '系统错误') {
alignment = 'left';
senderLabel = '系统错误';
messageMode = 'error';
}
// 添加消息到界面
addMessage(messageContent, alignment, senderLabel, messageMode, modelInfo, requestSource);
// 保存到本地存储
if (document.getElementById('enableStorage').checked) {
saveChatHistory({
content: messageContent,
alignment: alignment,
sender: senderLabel,
mode: messageMode,
modelInfo: modelInfo,
requestSource: requestSource,
timestamp: timestamp,
sessionId: sessionId
});
}
return;
}
if (messageData.Data && messageData.Data.Key) {
if(messageData.Data.Key == "audio"){
var value = messageData.Data.HttpValue;
console.log('Value:', value);
// 发送语音文件到服务器处理,不再直接添加到界面,等待WebSocket推送
fetch('/humanaudio', {
body: JSON.stringify({
file_url: value,
sessionid:parseInt(document.getElementById('sessionid').value),
}),
headers: {
'Content-Type': 'application/json',
'X-Request-Source': 'web'
},
method: 'POST'
});
}else if (messageData.Data.Key == "text") {
var reply = messageData.Data.Value;
console.log('收到text消息,内容:', reply);
// 将text类型消息推送到服务器,由数字人服务通过TTS合成语音并播放
// 使用原始的消息类型,而不是固定的echo
var originalType = messageData.Data.Type || 'echo';
fetch('/human', {
body: JSON.stringify({
text: reply,
type: originalType,
interrupt: true,
sessionid: parseInt(document.getElementById('sessionid').value),
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
}).then(response => response.json()).then(data => {
console.log('/human接口响应(文本消息):', data);
if (data.code !== 0) {
console.error('服务器处理失败:', data.message || data.msg);
}
// 所有消息显示都通过WebSocket推送,不再从HTTP响应获取数据
}).catch(error => {
console.error('发送文本消息错误:', error);
addMessage(`网络错误: ${error.message}`, 'left', '系统错误', 'error');
});
}else if (messageData.Data.Key == "plaintext") {
// 处理纯文本消息类型
var textContent = messageData.Data.Value;
console.log('收到纯文本消息:', textContent);
// 使用浏览器的语音合成API进行本地语音合成
if (window.speechSynthesis) {
console.log('使用本地语音合成播放文本:', textContent);
var utterance = new SpeechSynthesisUtterance(textContent);
utterance.lang = 'zh-CN'; // 设置语言为中文
utterance.rate = 1.0; // 设置语速
utterance.pitch = 1.0; // 设置音高
utterance.volume = 1.0; // 设置音量
speechSynthesis.speak(utterance);
}
}
}
};
ws.onclose = function(e) {
console.log('WebSocket connection closed');
attemptReconnect();
};
ws.onerror = function(e) {
console.error('WebSocket error:', e);
ws.close(); // 关闭连接并尝试重连
};
}
function attemptReconnect() {
if (isReconnecting) return; // 防止多次重连
isReconnecting = true;
reconnectAttempts++;
// 使用指数退避算法计算下一次重连间隔
var currentInterval = Math.min(reconnectInterval * Math.pow(1.5, reconnectAttempts - 1), maxReconnectInterval);
console.log('Attempting to reconnect... (Attempt ' + reconnectAttempts + ', 间隔: ' + currentInterval/1000 + '秒)');
if(document.getElementById('is_open') && parseInt(document.getElementById('is_open').value) == 1){
stop()
}
setTimeout(function() {
isReconnecting = false;
connectWebSocket();
}, currentInterval);
}
// SessionId管理功能
function saveSessionId(sessionId) {
localStorage.setItem('currentSessionId', sessionId);
document.getElementById('current-sessionid').value = sessionId;
console.log('SessionId已保存到本地存储:', sessionId);
}
function restoreSessionId() {
var savedSessionId = localStorage.getItem('currentSessionId');
if (savedSessionId && savedSessionId !== '0') {
document.getElementById('sessionid').value = savedSessionId;
document.getElementById('current-sessionid').value = savedSessionId;
console.log('已恢复SessionId:', savedSessionId);
return savedSessionId;
}
return null;
}
function clearSessionId() {
localStorage.removeItem('currentSessionId');
document.getElementById('sessionid').value = '0';
document.getElementById('current-sessionid').value = '';
document.getElementById('current-sessionid').placeholder = '未连接';
console.log('SessionId已清除');
}
// 绑定重置会话按钮事件
document.getElementById('clear-session-btn').addEventListener('click', function() {
if (confirm('确定要重置会话ID吗?这将断开当前连接并清除会话记录。')) {
// 清除sessionId
clearSessionId();
// 断开WebSocket连接
if (ws && ws.readyState === WebSocket.OPEN) {
ws.close();
}
// 停止WebRTC连接
if (typeof stop === 'function') {
stop();
}
console.log('会话已重置,可以重新连接');
alert('会话已重置,请重新点击"开始"按钮建立新连接');
}
});
// 页面初始化时尝试恢复sessionId
var restoredSessionId = restoreSessionId();
// 如果恢复了sessionId,尝试重新连接WebSocket
if (restoredSessionId && typeof connectWebSocket === 'function') {
console.log('检测到已保存的SessionId,尝试重新连接WebSocket...');
// 延迟一点时间确保页面完全加载
setTimeout(function() {
connectWebSocket();
}, 1000);
}
// 注意:WebSocket连接现在由WebRTC连接建立后触发
// connectWebSocket(); // 移除自动连接,改为在获得sessionid后连接
// 加载聊天记录
loadChatHistory();
// 添加页面可见性变化监听,当页面从隐藏变为可见时尝试重连
document.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'visible') {
// 页面变为可见状态,检查WebSocket连接
if (!ws || ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {
console.log('页面可见,检测到WebSocket未连接,尝试重连...');
// 重置重连计数和间隔,立即尝试重连
reconnectAttempts = 0;
reconnectInterval = 5000;
connectWebSocket();
}
}
});
});
</script>
</body>
</html>