-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
2261 lines (1944 loc) · 76.6 KB
/
renderer.js
File metadata and controls
2261 lines (1944 loc) · 76.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
// 全局变量
let currentSite = null;
let monitorInterval = null;
let monitorStartTime = null;
let lastFetchTime = null; // 记录上一次获取日志的时间
let allLogs = [];
let stats = {
totalRequests: 0,
uniqueIps: new Set(),
errorRequests: 0
};
// DOM元素
// 创建隐藏的输入框(用于兼容现有逻辑)
const createHiddenInputs = () => {
const uaBlacklist = document.createElement('input');
uaBlacklist.type = 'hidden';
uaBlacklist.id = 'ua-blacklist';
document.body.appendChild(uaBlacklist);
const ipBlacklist = document.createElement('input');
ipBlacklist.type = 'hidden';
ipBlacklist.id = 'ip-blacklist';
document.body.appendChild(ipBlacklist);
const refreshInterval = document.createElement('input');
refreshInterval.type = 'hidden';
refreshInterval.id = 'refresh-interval';
refreshInterval.value = '5';
document.body.appendChild(refreshInterval);
const maxRows = document.createElement('input');
maxRows.type = 'hidden';
maxRows.id = 'max-rows';
maxRows.value = '1000';
document.body.appendChild(maxRows);
const ipFilter = document.createElement('input');
ipFilter.type = 'hidden';
ipFilter.id = 'ip-filter';
document.body.appendChild(ipFilter);
};
createHiddenInputs();
const elements = {
siteSelect: document.getElementById('site-select'),
refreshInterval: document.getElementById('refresh-interval'),
uaFilter: document.getElementById('ua-filter'),
uaBlacklist: document.getElementById('ua-blacklist'),
ipBlacklist: document.getElementById('ip-blacklist'),
ipFilter: document.getElementById('ip-filter'),
pathFilter: document.getElementById('path-filter'),
statusFilter: document.getElementById('status-filter'),
maxRows: document.getElementById('max-rows'),
filterAbnormalRequests: document.getElementById('filter-abnormal-requests'),
toggleMonitor: document.getElementById('toggle-monitor'),
clearLogs: document.getElementById('clear-logs'),
exportLogs: document.getElementById('export-logs'),
settingsBtn: document.getElementById('settings-btn'),
searchLogs: document.getElementById('search-logs'),
autoScroll: document.getElementById('auto-scroll'),
logTbody: document.getElementById('log-tbody'),
logTable: document.getElementById('log-table'),
noLogs: document.getElementById('no-logs'),
alertSound: document.getElementById('alert-sound'),
currentTime: document.getElementById('current-time'),
connectionStatus: document.getElementById('connection-status'),
totalRequests: document.getElementById('total-requests'),
uniqueIps: document.getElementById('unique-ips'),
errorRequests: document.getElementById('error-requests'),
monitorDuration: document.getElementById('monitor-duration'),
// 模态框元素
settingsModal: document.getElementById('settings-modal'),
modalRefreshInterval: document.getElementById('modal-refresh-interval'),
modalMaxRows: document.getElementById('modal-max-rows'),
modalIpFilter: document.getElementById('modal-ip-filter'),
uaBlacklistInput: document.getElementById('ua-blacklist-input'),
ipBlacklistInput: document.getElementById('ip-blacklist-input'),
addUaBlacklist: document.getElementById('add-ua-blacklist'),
addIpBlacklist: document.getElementById('add-ip-blacklist'),
uaBlacklistTags: document.getElementById('ua-blacklist-tags'),
ipBlacklistTags: document.getElementById('ip-blacklist-tags'),
saveSettings: document.getElementById('save-settings'),
cancelSettings: document.getElementById('cancel-settings'),
closeModal: document.querySelector('.close'),
// 站点管理元素
siteManageBtn: document.getElementById('site-manage-btn'),
siteManageModal: document.getElementById('site-manage-modal'),
currentSiteName: document.getElementById('current-site-name'),
refreshRedirects: document.getElementById('refresh-redirects'),
redirectList: document.getElementById('redirect-list'),
closeSiteManage: document.getElementById('close-site-manage'),
closeSiteManageModal: document.querySelector('.close-site-manage')
};
// 检查是否在Electron环境中
const isElectron = window.electron !== undefined;
// 配置管理
async function loadConfig() {
if (isElectron) {
const config = await window.electron.loadConfig();
elements.refreshInterval.value = config.refreshInterval || 5;
elements.uaFilter.value = config.uaFilter || '';
elements.uaBlacklist.value = config.uaBlacklist || '';
elements.ipBlacklist.value = config.ipBlacklist || '';
elements.maxRows.value = config.maxDisplayRows || 1000;
elements.ipFilter.value = config.ipFilter || '';
elements.filterAbnormalRequests.checked = config.filterAbnormalRequests || false;
}
}
async function saveConfig() {
if (isElectron) {
const config = {
refreshInterval: parseInt(elements.refreshInterval.value),
uaFilter: elements.uaFilter.value,
uaBlacklist: elements.uaBlacklist.value,
ipBlacklist: elements.ipBlacklist.value,
maxDisplayRows: parseInt(elements.maxRows.value),
ipFilter: elements.ipFilter.value,
filterAbnormalRequests: elements.filterAbnormalRequests.checked
};
await window.electron.saveConfig(config);
}
}
// 初始化
document.addEventListener('DOMContentLoaded', async () => {
await loadConfig();
loadSites();
updateCurrentTime();
setInterval(updateCurrentTime, 1000);
// 绑定事件
elements.toggleMonitor.addEventListener('click', toggleMonitoring);
elements.clearLogs.addEventListener('click', clearLogs);
elements.exportLogs.addEventListener('click', exportLogs);
elements.searchLogs.addEventListener('input', filterLogs);
elements.pathFilter.addEventListener('input', filterLogs);
elements.statusFilter.addEventListener('change', filterLogs);
// 设置按钮事件
elements.settingsBtn.addEventListener('click', openSettingsModal);
elements.closeModal.addEventListener('click', closeSettingsModal);
elements.cancelSettings.addEventListener('click', closeSettingsModal);
elements.saveSettings.addEventListener('click', saveSettingsDialog);
// 黑名单添加按钮事件
elements.addUaBlacklist.addEventListener('click', () => addBlacklistItem('ua'));
elements.addIpBlacklist.addEventListener('click', () => addBlacklistItem('ip'));
elements.uaBlacklistInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') addBlacklistItem('ua');
});
elements.ipBlacklistInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') addBlacklistItem('ip');
});
// 清空API配置按钮事件
const clearApiBtn = document.getElementById('clear-api-config');
if (clearApiBtn) {
clearApiBtn.addEventListener('click', clearApiConfig);
}
// 点击模态框外部关闭
window.addEventListener('click', (event) => {
if (event.target === elements.settingsModal) {
closeSettingsModal();
}
if (event.target === elements.siteManageModal) {
closeSiteManageModal();
}
});
// 站点管理事件
elements.siteManageBtn.addEventListener('click', openSiteManageModal);
elements.closeSiteManage.addEventListener('click', closeSiteManageModal);
elements.closeSiteManageModal.addEventListener('click', closeSiteManageModal);
elements.refreshRedirects.addEventListener('click', loadRedirects);
// 配置变化时保存
elements.refreshInterval.addEventListener('change', saveConfig);
elements.uaFilter.addEventListener('change', saveConfig);
elements.maxRows.addEventListener('change', saveConfig);
// 异常请求过滤变化时重新过滤并保存配置
elements.filterAbnormalRequests.addEventListener('change', () => {
filterLogs();
saveConfig();
});
// 站点选择变化时设置当前站点
elements.siteSelect.addEventListener('change', () => {
currentSite = elements.siteSelect.value;
});
// 请求通知权限
if ('Notification' in window && Notification.permission === 'default') {
Notification.requestPermission();
}
// 初始化音频上下文(用户交互后激活)
document.addEventListener('click', function initAudio() {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
audioContext.resume();
document.removeEventListener('click', initAudio);
}, { once: true });
// 初始化tooltip功能
initTooltips();
// 初始化双击复制功能
initDoubleClickCopy();
});
// 更新当前时间
function updateCurrentTime() {
const now = new Date();
elements.currentTime.textContent = now.toLocaleString('zh-CN');
}
// 加载站点列表
async function loadSites() {
try {
const result = await window.electron.api.getSiteList();
if (result.success && result.data) {
elements.siteSelect.innerHTML = '<option value="">请选择站点...</option>';
result.data.forEach(site => {
const option = document.createElement('option');
option.value = site.name;
option.textContent = `${site.name} (${site.ps})`;
elements.siteSelect.appendChild(option);
});
} else {
showError('获取站点列表失败');
}
} catch (error) {
showError('错误:' + error.message);
updateConnectionStatus(false);
}
}
// 切换监控状态
function toggleMonitoring() {
if (monitorInterval) {
stopMonitoring();
} else {
startMonitoring();
}
}
// 开始监控
function startMonitoring() {
if (!currentSite) {
alert('请先选择一个站点');
return;
}
// 切换站点时清空之前的日志
allLogs = [];
processedLogs.clear(); // 清空已处理日志集合
elements.logTbody.innerHTML = '';
stats = {
totalRequests: 0,
uniqueIps: new Set(),
errorRequests: 0
};
updateStatsDisplay();
lastFetchTime = null; // 重置最后获取时间
monitorStartTime = Date.now();
// 更新按钮状态
elements.toggleMonitor.textContent = '停止监控';
elements.toggleMonitor.classList.remove('btn-primary');
elements.toggleMonitor.classList.add('btn-danger');
elements.siteSelect.disabled = true;
// 立即获取一次日志
fetchLogs();
// 设置定时刷新
const interval = parseInt(elements.refreshInterval.value) || 5;
monitorInterval = setInterval(fetchLogs, interval * 1000);
// 更新监控时长
updateMonitorDuration();
setInterval(updateMonitorDuration, 1000);
}
// 停止监控
function stopMonitoring() {
if (monitorInterval) {
clearInterval(monitorInterval);
monitorInterval = null;
}
// 更新按钮状态
elements.toggleMonitor.textContent = '开始监控';
elements.toggleMonitor.classList.remove('btn-danger');
elements.toggleMonitor.classList.add('btn-primary');
elements.siteSelect.disabled = false;
monitorStartTime = null;
}
// 记录已经处理过的日志(用于去重)
const processedLogs = new Set();
// 生成日志的唯一标识
function getLogKey(log) {
return `${log.ip}_${log.time}_${log.url}_${log.status}_${log.userAgent || ''}`;
}
// 稳定的日志排序函数
function stableLogSort(a, b) {
const timeA = parseLogTime(a.time);
const timeB = parseLogTime(b.time);
// 首先按时间排序
if (timeA !== timeB) {
return timeA - timeB;
}
// 时间相同时,按IP排序
if (a.ip !== b.ip) {
return a.ip.localeCompare(b.ip);
}
// IP也相同时,按URL排序
if (a.url !== b.url) {
return a.url.localeCompare(b.url);
}
// URL也相同时,按状态码排序
if (a.status !== b.status) {
return a.status.localeCompare(b.status);
}
// 最后按User-Agent排序
return (a.userAgent || '').localeCompare(b.userAgent || '');
}
// 获取日志
async function fetchLogs() {
if (!currentSite) return;
try {
const result = await window.electron.api.getSiteLogs(currentSite);
if (result.success && result.data) {
processLogs(result.data);
updateConnectionStatus(true);
} else {
showError('获取日志失败: ' + (result.error || '未知错误'));
updateConnectionStatus(false);
}
} catch (error) {
showError('错误:' + error.message);
updateConnectionStatus(false);
}
}
// 处理日志数据
function processLogs(newLogs) {
const uaKeywords = elements.uaFilter.value.split(',').map(k => k.trim()).filter(k => k);
const uaBlacklist = elements.uaBlacklist.value.split(',').map(k => k.trim()).filter(k => k);
const ipBlacklist = elements.ipBlacklist.value.split(',').map(k => k.trim()).filter(k => k);
const maxRows = parseInt(elements.maxRows.value) || 1000;
let hasNewAlerts = false;
const currentFetchTime = new Date();
console.log('收到日志数量:', newLogs.length);
console.log('当前已有日志:', allLogs.length);
console.log('最大显示行数:', maxRows);
// 先过滤掉黑名单中的日志
const filteredLogs = newLogs.filter(log => {
// 过滤异常请求
if (elements.filterAbnormalRequests.checked) {
const method = log.method || '';
const validMethods = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH'];
if (!method || method === '-' || !validMethods.includes(method.toUpperCase())) {
return false;
}
}
// IP黑名单过滤
if (ipBlacklist.length > 0 && log.ip) {
const isBlacklisted = ipBlacklist.some(ip => {
return log.ip === ip || log.ip.startsWith(ip);
});
if (isBlacklisted) {
return false;
}
}
// UA黑名单过滤
if (uaBlacklist.length > 0 && log.userAgent) {
const ua = log.userAgent.toLowerCase();
const isBlacklisted = uaBlacklist.some(keyword => {
const keywordLower = keyword.toLowerCase();
return ua.includes(keywordLower);
});
if (isBlacklisted) {
return false;
}
}
return true;
});
console.log(`过滤后日志数量: ${filteredLogs.length}`);
// 第一次加载或者切换站点时
if (allLogs.length === 0 && processedLogs.size === 0) {
// 清空DOM
elements.logTbody.innerHTML = '';
// 使用稳定排序函数
const sortedLogs = filteredLogs.sort(stableLogSort);
// 如果日志数量超过最大显示数,只取最新的
let logsToAdd = sortedLogs;
if (sortedLogs.length > maxRows) {
logsToAdd = sortedLogs.slice(-maxRows); // 取最后的maxRows条
console.log(`初始加载:日志数量超过最大显示数,只显示最新的 ${maxRows} 条`);
}
// 添加日志到内存和DOM
logsToAdd.forEach(log => {
const logKey = getLogKey(log);
processedLogs.add(logKey);
allLogs.push(log);
updateStats(log);
// 检查UA监控
let shouldHighlight = false;
if (uaKeywords.length > 0 && log.userAgent) {
const ua = log.userAgent.toLowerCase();
const matched = uaKeywords.some(keyword => {
const keywordLower = keyword.toLowerCase();
return ua.includes(keywordLower);
});
if (matched) {
shouldHighlight = true;
}
}
addLogRow(log, false, shouldHighlight);
});
} else {
// 增量更新模式
// 创建一个包含所有日志(旧的+新的)的数组
const allLogsMap = new Map();
// 先添加已有的日志
allLogs.forEach(log => {
const logKey = getLogKey(log);
allLogsMap.set(logKey, log);
});
// 添加新的日志(会覆盖重复的)
const reallyNewLogs = [];
filteredLogs.forEach(log => {
const logKey = getLogKey(log);
if (!allLogsMap.has(logKey)) {
reallyNewLogs.push(log);
}
allLogsMap.set(logKey, log);
});
console.log(`发现 ${reallyNewLogs.length} 条真正的新日志`);
// 记录是否应该滚动(有新日志且不是空状态)
const shouldScroll = reallyNewLogs.length > 0 && elements.autoScroll.checked && processedLogs.size > reallyNewLogs.length;
// 转换为数组并使用稳定排序函数
const allLogsSorted = Array.from(allLogsMap.values()).sort(stableLogSort);
// 只保留最新的maxRows条
let finalLogs = allLogsSorted;
if (allLogsSorted.length > maxRows) {
finalLogs = allLogsSorted.slice(-maxRows);
console.log(`总日志数超过限制,只保留最新的 ${maxRows} 条`);
}
// 完全重建显示
elements.logTbody.innerHTML = '';
allLogs = [];
processedLogs.clear();
// 重新添加所有需要显示的日志
finalLogs.forEach(log => {
const logKey = getLogKey(log);
processedLogs.add(logKey);
allLogs.push(log);
// 判断是否是新日志
const isNewLog = reallyNewLogs.some(newLog => getLogKey(newLog) === logKey);
// 检查UA监控
let shouldHighlight = false;
if (uaKeywords.length > 0 && log.userAgent) {
const ua = log.userAgent.toLowerCase();
const matched = uaKeywords.some(keyword => {
const keywordLower = keyword.toLowerCase();
return ua.includes(keywordLower);
});
if (matched) {
shouldHighlight = true;
if (isNewLog) {
hasNewAlerts = true;
console.log('新的匹配日志,将触发提示音');
}
}
}
addLogRow(log, isNewLog, shouldHighlight);
});
// 重新计算统计信息
stats = {
totalRequests: 0,
uniqueIps: new Set(),
errorRequests: 0
};
allLogs.forEach(log => updateStats(log));
// 在所有日志渲染完成后执行滚动
if (shouldScroll) {
console.log('触发自动滚动');
setTimeout(() => {
const lastRow = elements.logTbody.lastElementChild;
if (lastRow) {
lastRow.scrollIntoView({ behavior: 'smooth', block: 'end' });
}
}, 100);
}
}
// 更新最后获取时间
lastFetchTime = currentFetchTime;
// 播放提示音
if (hasNewAlerts) {
playAlertSound();
}
// 更新UI
updateNoLogsDisplay();
filterLogs();
}
// 已移除enforceMaxRows函数,因为现在在processLogs中直接处理
// 更新统计信息
function updateStats(log) {
stats.totalRequests++;
stats.uniqueIps.add(log.ip);
const status = parseInt(log.status);
if (status >= 400) {
stats.errorRequests++;
}
elements.totalRequests.textContent = stats.totalRequests;
elements.uniqueIps.textContent = stats.uniqueIps.size;
elements.errorRequests.textContent = stats.errorRequests;
}
// 创建带tooltip的单元格内容
function createTooltipCell(text, maxLength) {
if (!text || text === '-' || text.length <= maxLength) {
return text || '-';
}
const truncated = truncate(text, maxLength);
return `<span class="tooltip-container" data-tooltip="${escapeHtml(text)}">${escapeHtml(truncated)}</span>`;
}
// 转义HTML特殊字符
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// 初始化tooltip
function initTooltips() {
let currentTooltip = null;
document.addEventListener('mouseover', (e) => {
const tooltipContainer = e.target.closest('.tooltip-container');
if (tooltipContainer) {
const text = tooltipContainer.getAttribute('data-tooltip');
if (text) {
// 移除之前的tooltip
if (currentTooltip) {
currentTooltip.remove();
}
// 创建tooltip wrapper
const wrapper = document.createElement('div');
wrapper.className = 'tooltip-wrapper';
// 创建tooltip内容
const tooltip = document.createElement('div');
tooltip.className = 'tooltip-popup';
tooltip.textContent = text;
wrapper.appendChild(tooltip);
// 添加到body
document.body.appendChild(wrapper);
// 计算位置
const containerRect = tooltipContainer.getBoundingClientRect();
// 设置初始位置(在元素上方居中)
let left = containerRect.left + (containerRect.width / 2);
let top = containerRect.top;
wrapper.style.left = left + 'px';
wrapper.style.top = top + 'px';
// 获取tooltip尺寸
const wrapperRect = wrapper.getBoundingClientRect();
// 调整水平位置
left = left - (wrapperRect.width / 2);
// 确保不超出左边界
if (left < 5) {
left = 5;
}
// 确保不超出右边界
else if (left + wrapperRect.width > window.innerWidth - 5) {
left = window.innerWidth - wrapperRect.width - 5;
}
// 默认显示在上方
top = containerRect.top - wrapperRect.height;
// 如果超出顶部,显示在下方
if (top < 5) {
top = containerRect.bottom;
wrapper.classList.add('bottom');
}
wrapper.style.left = left + 'px';
wrapper.style.top = top + 'px';
// 显示tooltip
setTimeout(() => {
tooltip.classList.add('show');
}, 10);
currentTooltip = wrapper;
}
}
});
document.addEventListener('mouseout', (e) => {
const tooltipContainer = e.target.closest('.tooltip-container');
if (tooltipContainer && currentTooltip) {
const tooltip = currentTooltip.querySelector('.tooltip-popup');
if (tooltip) {
tooltip.classList.remove('show');
}
setTimeout(() => {
if (currentTooltip) {
currentTooltip.remove();
currentTooltip = null;
}
}, 300);
}
});
}
// 初始化双击复制功能
function initDoubleClickCopy() {
// 创建复制提示
let copyTooltip = null;
document.addEventListener('dblclick', (e) => {
const td = e.target.closest('td');
if (td && td.closest('#log-table')) {
// 获取单元格文本内容
let textToCopy = '';
// 检查是否有tooltip容器(包含完整内容)
const tooltipContainer = td.querySelector('.tooltip-container');
if (tooltipContainer) {
textToCopy = tooltipContainer.getAttribute('data-tooltip');
} else {
textToCopy = td.textContent.trim();
}
// 复制到剪贴板
if (textToCopy) {
// 使用现代剪贴板API
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(textToCopy).then(() => {
showCopyTooltip(e.pageX, e.pageY, '已复制到剪贴板');
}).catch(err => {
// 降级到旧方法
fallbackCopyTextToClipboard(textToCopy);
showCopyTooltip(e.pageX, e.pageY, '已复制到剪贴板');
});
} else {
// 使用旧方法
fallbackCopyTextToClipboard(textToCopy);
showCopyTooltip(e.pageX, e.pageY, '已复制到剪贴板');
}
}
}
});
// 降级复制方法
function fallbackCopyTextToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
} catch (err) {
console.error('复制失败:', err);
}
document.body.removeChild(textArea);
}
// 显示复制提示
function showCopyTooltip(x, y, message) {
// 移除之前的提示
if (copyTooltip) {
copyTooltip.remove();
}
// 创建新提示
copyTooltip = document.createElement('div');
copyTooltip.className = 'copy-tooltip';
copyTooltip.textContent = message;
copyTooltip.style.left = x + 'px';
copyTooltip.style.top = (y - 30) + 'px';
document.body.appendChild(copyTooltip);
// 添加显示类
setTimeout(() => {
copyTooltip.classList.add('show');
}, 10);
// 1.5秒后移除
setTimeout(() => {
if (copyTooltip) {
copyTooltip.classList.remove('show');
setTimeout(() => {
if (copyTooltip) {
copyTooltip.remove();
copyTooltip = null;
}
}, 300);
}
}, 1500);
}
}
// 添加日志行
function addLogRow(log, isNew = false, isAlert = false) {
const tr = document.createElement('tr');
if (isNew) {
tr.classList.add('log-highlight');
setTimeout(() => tr.classList.remove('log-highlight'), 2000);
}
// UA监控匹配的特殊高亮
if (isAlert) {
tr.style.backgroundColor = '#ffeaa7';
tr.style.fontWeight = 'bold';
tr.style.border = '2px solid #fdcb6e';
console.log('添加高亮行:', log.userAgent);
}
const statusClass = `status-${Math.floor(parseInt(log.status) / 100)}00`;
// 将日志时间转换为北京时间显示
const beijingTime = parseLogTime(log.time);
const formattedTime = formatDateTime(beijingTime);
// 限制请求方式最多4个字母
const method = log.method.length > 4 ? log.method.substring(0, 4) : log.method;
tr.innerHTML = `
<td title="${log.time}">${formattedTime}</td>
<td>${log.ip}</td>
<td>${method}</td>
<td class="url">${createTooltipCell(log.url, 50)}</td>
<td class="${statusClass}">${log.status}</td>
<td>${formatSize(log.size)}</td>
<td class="user-agent" ${isAlert ? 'style="color: #ff6348;"' : ''}>${createTooltipCell(log.userAgent, 50)}</td>
<td class="referer">${createTooltipCell(log.referer, 50)}</td>
`;
tr.dataset.log = JSON.stringify(log);
elements.logTbody.appendChild(tr);
// 只在IP列添加右键菜单事件
const ipCell = tr.querySelector('td:nth-child(2)'); // IP列是第二列
ipCell.addEventListener('contextmenu', (e) => {
e.preventDefault();
showContextMenu(e, log);
});
}
// 显示右键菜单
function showContextMenu(event, log) {
// 移除旧的菜单
const oldMenu = document.querySelector('.context-menu');
if (oldMenu) {
oldMenu.remove();
}
// 创建右键菜单
const menu = document.createElement('div');
menu.className = 'context-menu';
menu.innerHTML = `
<div class="menu-item" data-action="add-ip-blacklist">添加到IP黑名单</div>
<div class="menu-item" data-action="block-ip">禁用IP访问(防火墙)</div>
`;
// 设置菜单位置
menu.style.left = event.pageX + 'px';
menu.style.top = event.pageY + 'px';
document.body.appendChild(menu);
// 菜单项点击事件
menu.addEventListener('click', async (e) => {
const item = e.target.closest('.menu-item');
if (!item) return;
const action = item.dataset.action;
switch (action) {
case 'add-ip-blacklist':
addIpToBlacklist(log.ip);
break;
case 'block-ip':
await blockIpWithFirewall(log.ip);
break;
}
menu.remove();
});
// 点击其他地方关闭菜单
setTimeout(() => {
document.addEventListener('click', function closeMenu() {
menu.remove();
document.removeEventListener('click', closeMenu);
});
}, 0);
}
// 添加IP到黑名单
function addIpToBlacklist(ip) {
const currentBlacklist = elements.ipBlacklist.value.split(',').map(i => i.trim()).filter(i => i);
if (!currentBlacklist.includes(ip)) {
currentBlacklist.push(ip);
elements.ipBlacklist.value = currentBlacklist.join(', ');
saveConfig();
filterLogs();
showToast(`IP ${ip} 已添加到黑名单`);
} else {
showToast(`IP ${ip} 已在黑名单中`);
}
}
// 通过防火墙禁用IP
async function blockIpWithFirewall(ip) {
if (!confirm(`确定要在防火墙中禁用IP ${ip} 的访问吗?`)) {
return;
}
try {
const result = await window.electron.api.request({
endpoint: 'addFirewallRule',
data: {
ip: ip,
brief: `从日志监控添加 - ${new Date().toLocaleString()}`
}
});
if (result.success) {
showToast(`已成功禁用IP ${ip} 的访问`);
} else {
alert(`禁用IP失败: ${result.error?.message || '未知错误'}`);
}
} catch (error) {
console.error('防火墙操作失败:', error);
alert(`防火墙操作失败: ${error.message}`);
}
}
// 复制到剪贴板
function copyToClipboard(text) {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).catch(err => {
console.error('复制失败:', err);
});
} else {
// 降级方案
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
}
// 显示提示消息
function showToast(message) {
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.classList.add('show');
}, 10);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => {
toast.remove();
}, 300);
}, 2000);
}
// 过滤日志
function filterLogs() {
const searchTerm = elements.searchLogs.value.toLowerCase();
const pathFilter = elements.pathFilter.value.toLowerCase();
const ipFilter = elements.ipFilter.value.toLowerCase();
const statusFilter = elements.statusFilter.value;
const uaBlacklist = elements.uaBlacklist.value.split(',').map(k => k.trim()).filter(k => k);
const ipBlacklist = elements.ipBlacklist.value.split(',').map(k => k.trim()).filter(k => k);
const rows = elements.logTbody.querySelectorAll('tr');
rows.forEach(row => {
const log = JSON.parse(row.dataset.log);
let show = true;
// 过滤异常请求
if (elements.filterAbnormalRequests.checked) {
const method = log.method || '';
const validMethods = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH'];
if (!method || method === '-' || !validMethods.includes(method.toUpperCase())) {
show = false;
}
}
// 搜索过滤
if (searchTerm) {
const searchableText = Object.values(log).join(' ').toLowerCase();
show = show && searchableText.includes(searchTerm);
}
// 路径过滤
if (pathFilter) {
show = show && log.url.toLowerCase().includes(pathFilter);
}
// IP过滤
if (ipFilter) {
show = show && log.ip.toLowerCase().includes(ipFilter);
}
// 状态码过滤
if (statusFilter) {
show = show && log.status.startsWith(statusFilter);
}
// IP黑名单过滤
if (ipBlacklist.length > 0 && log.ip) {
const isBlacklisted = ipBlacklist.some(ip => {
return log.ip === ip || log.ip.startsWith(ip);