-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoptions.js
More file actions
2006 lines (1689 loc) · 65.6 KB
/
Copy pathoptions.js
File metadata and controls
2006 lines (1689 loc) · 65.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
// ProxyMaster Options Script
class OptionsManager {
constructor() {
this.profiles = {};
this.currentProfile = null;
this.rules = [];
this.editingProfile = null;
this.editingRuleIndex = null;
this.rulesListenerAdded = false;
this.profilesListenerAdded = false;
this.v2rayManager = null;
this.subscriptions = [];
this.selectedNode = null;
this.init();
}
async init() {
// 初始化V2Ray管理器
if (typeof V2RaySubscriptionManager !== 'undefined') {
this.v2rayManager = new V2RaySubscriptionManager();
await this.loadV2RayData();
}
await this.loadData();
this.setupEventListeners();
this.setupButtonListeners();
this.renderProfiles();
this.renderRules();
this.renderV2RaySubscriptions();
this.updateStats();
this.loadSettings();
this.handleUrlHash(); // 处理URL锚点
// 初始化性能报告功能
if (typeof PerformanceMonitor !== 'undefined' && typeof PerformanceCharts !== 'undefined') {
await this.initPerformanceReports();
}
}
async loadData() {
try {
const response = await chrome.runtime.sendMessage({ action: 'getProfiles' });
this.profiles = response.profiles || {};
this.currentProfile = response.currentProfile || 'direct';
const rulesResult = await chrome.storage.sync.get(['autoSwitchRules']);
this.rules = rulesResult.autoSwitchRules || [];
} catch (error) {
console.error('Failed to load data:', error);
this.showToast(chrome.i18n.getMessage('loadFailed'), 'error');
}
}
setupEventListeners() {
// 标签页切换
document.querySelectorAll('.nav-tab').forEach(tab => {
tab.addEventListener('click', () => {
this.switchTab(tab.dataset.tab);
});
});
// 监听浏览器前进/后退按钮
window.addEventListener('hashchange', () => {
this.handleUrlHash();
});
// 配置表单提交
document.getElementById('profileForm').addEventListener('submit', (e) => {
e.preventDefault();
this.saveProfile();
});
// 规则表单提交
document.getElementById('ruleForm').addEventListener('submit', (e) => {
e.preventDefault();
this.saveRule();
});
// 规则类型变化时更新帮助文本
document.getElementById('ruleType').addEventListener('change', (e) => {
this.updatePatternHelp(e.target.value);
});
// 协议类型变化时切换配置字段
document.getElementById('profileProtocol').addEventListener('change', (e) => {
this.toggleProtocolFields(e.target.value);
});
// 模态框外部点击关闭
document.querySelectorAll('.modal').forEach(modal => {
modal.addEventListener('click', (e) => {
if (e.target === modal) {
this.closeModal(modal.id);
}
});
});
}
setupButtonListeners() {
// 新建配置按钮
document.getElementById('addProfileBtn')?.addEventListener('click', () => {
this.showAddProfileModal();
});
// 新建规则按钮
document.getElementById('addRuleBtn')?.addEventListener('click', () => {
this.showAddRuleModal();
});
// 导出配置按钮
document.getElementById('exportBtn')?.addEventListener('click', () => {
this.exportData();
});
// 导入配置按钮
document.getElementById('importBtn')?.addEventListener('click', () => {
this.importData();
});
// 清除数据按钮
document.getElementById('clearDataBtn')?.addEventListener('click', () => {
this.clearAllData();
});
// 保存设置按钮
document.getElementById('saveSettingsBtn')?.addEventListener('click', () => {
this.saveSettings();
});
// 模态框关闭按钮
document.getElementById('closeProfileModalBtn')?.addEventListener('click', () => {
this.closeModal('addProfileModal');
});
document.getElementById('cancelProfileBtn')?.addEventListener('click', () => {
this.closeModal('addProfileModal');
});
// 规则模态框关闭按钮
document.getElementById('closeRuleModalBtn')?.addEventListener('click', () => {
this.closeModal('addRuleModal');
});
document.getElementById('cancelRuleBtn')?.addEventListener('click', () => {
this.closeModal('addRuleModal');
});
// V2Ray订阅相关按钮
document.getElementById('addSubscriptionBtn')?.addEventListener('click', () => {
this.showAddSubscriptionModal();
});
document.getElementById('closeSubscriptionModalBtn')?.addEventListener('click', () => {
this.closeModal('addSubscriptionModal');
});
document.getElementById('cancelSubscriptionBtn')?.addEventListener('click', () => {
this.closeModal('addSubscriptionModal');
});
document.getElementById('closeNodeDetailModalBtn')?.addEventListener('click', () => {
this.closeModal('nodeDetailModal');
});
// V2Ray订阅表单提交
document.getElementById('subscriptionForm')?.addEventListener('submit', (e) => {
e.preventDefault();
this.addSubscription();
});
// 订阅添加方式切换
document.querySelectorAll('input[name="addMethod"]').forEach(radio => {
radio.addEventListener('change', (e) => {
this.toggleSubscriptionInputMethod(e.target.value);
});
});
}
switchTab(tabName) {
// 更新标签按钮状态
document.querySelectorAll('.nav-tab').forEach(tab => {
tab.classList.remove('active');
});
document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
// 显示对应内容
document.querySelectorAll('.tab-content').forEach(content => {
content.classList.remove('active');
});
document.getElementById(tabName).classList.add('active');
}
// 处理URL锚点,自动跳转到对应标签页
handleUrlHash() {
const hash = window.location.hash.substring(1); // 移除 # 号
console.log('Current URL hash:', hash);
// 定义锚点到标签页的映射
const hashToTab = {
'auto-switch': 'rules',
'rules': 'rules',
'profiles': 'profiles',
'v2ray': 'v2ray',
'stats': 'stats',
'settings': 'settings',
'new-profile': 'profiles'
};
if (hash && hashToTab[hash]) {
console.log(`Switching to tab: ${hashToTab[hash]} based on hash: ${hash}`);
this.switchTab(hashToTab[hash]);
// 如果是新建配置的锚点,自动打开新建配置模态框
if (hash === 'new-profile') {
setTimeout(() => {
this.showAddProfileModal();
}, 100);
}
} else {
// 默认显示第一个标签页(代理配置)
this.switchTab('profiles');
}
}
renderProfiles() {
const profileList = document.getElementById('profileList');
profileList.innerHTML = '';
if (Object.keys(this.profiles).length === 0) {
profileList.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">🔧</div>
<h4>还没有代理配置</h4>
<p>点击"新建配置"按钮开始添加你的第一个代理服务器</p>
</div>
`;
return;
}
Object.entries(this.profiles).forEach(([name, profile]) => {
if (name === 'direct') return; // 跳过直连配置
const isActive = name === this.currentProfile;
const profileElement = document.createElement('div');
profileElement.className = `profile-item ${isActive ? 'active' : ''}`;
profileElement.innerHTML = `
<div style="display: flex; align-items: center;">
<div class="status-indicator ${isActive ? '' : 'inactive'}"></div>
<div class="profile-info">
<h4>${profile.displayName || profile.name}</h4>
<p>${profile.protocol?.toUpperCase() || 'HTTP'}://${profile.host}:${profile.port}</p>
</div>
</div>
<div class="profile-actions">
<button class="btn btn-primary" data-action="switch" data-profile="${name}">
${isActive ? '当前' : '切换'}
</button>
<button class="btn btn-secondary" data-action="edit" data-profile="${name}">编辑</button>
<button class="btn btn-danger" data-action="delete" data-profile="${name}">删除</button>
</div>
`;
profileList.appendChild(profileElement);
});
// 只在第一次渲染时添加事件委托
if (!this.profilesListenerAdded) {
profileList.addEventListener('click', (e) => {
const button = e.target.closest('button[data-action]');
if (!button) return;
const action = button.dataset.action;
const profileName = button.dataset.profile;
switch (action) {
case 'switch':
this.switchToProfile(profileName);
break;
case 'edit':
this.editProfile(profileName);
break;
case 'delete':
this.deleteProfile(profileName);
break;
}
});
this.profilesListenerAdded = true;
}
}
renderRules() {
const rulesList = document.getElementById('rulesList');
rulesList.innerHTML = '';
if (this.rules.length === 0) {
rulesList.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">🔄</div>
<h4>还没有自动切换规则</h4>
<p>添加规则让ProxyMaster自动为不同网站选择合适的代理</p>
</div>
`;
return;
}
this.rules.forEach((rule, index) => {
const ruleElement = document.createElement('div');
ruleElement.className = `profile-item ${rule.enabled ? '' : 'inactive'}`;
const typeNames = {
'domain': '域名',
'url': 'URL',
'wildcard': '通配符',
'regex': '正则'
};
const profileName = rule.profile === 'direct' ? chrome.i18n.getMessage('direct') :
(this.profiles[rule.profile]?.displayName || rule.profile);
ruleElement.innerHTML = `
<div style="display: flex; align-items: center;">
<div class="status-indicator ${rule.enabled ? '' : 'inactive'}"></div>
<div class="profile-info">
<h4>${rule.name || rule.pattern}</h4>
<p>${typeNames[rule.type] || rule.type}: ${rule.pattern}</p>
<p style="font-size: 12px; color: #888;">代理: ${profileName} | 优先级: ${rule.priority}</p>
</div>
</div>
<div class="profile-actions">
<button class="btn btn-secondary" data-action="toggle-rule" data-index="${index}">
${rule.enabled ? '禁用' : '启用'}
</button>
<button class="btn btn-secondary" data-action="edit-rule" data-index="${index}">编辑</button>
<button class="btn btn-danger" data-action="delete-rule" data-index="${index}">删除</button>
</div>
`;
rulesList.appendChild(ruleElement);
});
// 只在第一次渲染时添加事件委托
if (!this.rulesListenerAdded) {
rulesList.addEventListener('click', (e) => {
const button = e.target.closest('button[data-action]');
if (!button) return;
const action = button.dataset.action;
const index = parseInt(button.dataset.index);
switch (action) {
case 'toggle-rule':
this.toggleRule(index);
break;
case 'edit-rule':
this.editRule(index);
break;
case 'delete-rule':
this.deleteRule(index);
break;
}
});
this.rulesListenerAdded = true;
}
}
async updateStats() {
try {
const stats = await chrome.runtime.sendMessage({ action: 'getPerformanceStats' });
// 计算统计数据
const totalRequests = Object.values(stats).reduce((sum, stat) => sum + stat.requests, 0);
const activeProfiles = Object.keys(this.profiles).length;
document.getElementById('totalRequests').textContent = this.formatNumber(totalRequests);
document.getElementById('activeProfiles').textContent = activeProfiles;
// 从存储中获取切换次数
const result = await chrome.storage.local.get(['totalSwitchCount']);
document.getElementById('totalSwitches').textContent = this.formatNumber(result.totalSwitchCount || 0);
// 计算平均响应时间(模拟数据)
document.getElementById('avgResponseTime').textContent = '120ms';
} catch (error) {
console.error('Failed to update stats:', error);
}
}
formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
} else if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
}
return num.toString();
}
async switchToProfile(profileName) {
try {
const response = await chrome.runtime.sendMessage({
action: 'switchProfile',
profileName: profileName
});
if (response.success) {
this.currentProfile = profileName;
this.renderProfiles();
this.showToast(`已切换到: ${this.profiles[profileName]?.displayName || profileName}`, 'success');
} else {
this.showToast('切换失败', 'error');
}
} catch (error) {
console.error('Failed to switch profile:', error);
this.showToast('切换失败', 'error');
}
}
async saveProfile() {
const protocol = document.getElementById('profileProtocol').value;
const isV2RayProtocol = ['vmess', 'vless', 'trojan', 'shadowsocks'].includes(protocol);
// 获取基本表单数据
const name = document.getElementById('profileName').value.trim();
const displayName = document.getElementById('profileDisplayName').value.trim();
let host, port, profile;
if (isV2RayProtocol) {
// V2Ray协议配置
host = document.getElementById('v2rayHost').value.trim();
port = document.getElementById('v2rayPort').value;
const id = document.getElementById('v2rayId').value.trim();
const network = document.getElementById('v2rayNetwork').value;
const tls = document.getElementById('v2rayTls').checked;
// 验证必填字段
if (!name) {
this.showToast('请输入配置名称', 'error');
return;
}
if (!host) {
this.showToast('请输入服务器地址', 'error');
return;
}
if (!port || isNaN(port) || port < 1 || port > 65535) {
this.showToast('请输入有效的端口号 (1-65535)', 'error');
return;
}
if (!id) {
this.showToast('请输入用户ID或密码', 'error');
return;
}
// 构建V2Ray配置
profile = {
name: name,
displayName: displayName || name,
protocol: protocol,
host: host,
port: parseInt(port),
type: 'v2ray',
v2rayConfig: {
id: id,
network: network,
tls: tls
}
};
// 添加协议特定配置
if (protocol === 'vmess') {
const alterId = parseInt(document.getElementById('v2rayAlterId').value) || 0;
profile.v2rayConfig.alterId = alterId;
profile.v2rayConfig.security = 'auto';
} else if (protocol === 'shadowsocks') {
const method = document.getElementById('v2rayMethod').value;
profile.v2rayConfig.method = method;
profile.v2rayConfig.password = id; // 对于SS,id字段存储密码
} else if (protocol === 'trojan') {
profile.v2rayConfig.password = id;
}
// 添加WebSocket配置
if (network === 'ws') {
const wsPath = document.getElementById('v2rayWsPath').value.trim();
profile.v2rayConfig.wsPath = wsPath || '/';
}
// 对于需要客户端的协议,设置本地代理
if (['vmess', 'vless'].includes(protocol)) {
profile.requiresClient = true;
profile.localProxy = {
host: '127.0.0.1',
port: 1080,
protocol: 'socks5'
};
}
} else {
// 传统代理协议配置
host = document.getElementById('profileHost').value.trim();
port = document.getElementById('profilePort').value;
const username = document.getElementById('profileUsername').value.trim();
const password = document.getElementById('profilePassword').value;
// 验证必填字段
if (!name) {
this.showToast('请输入配置名称', 'error');
return;
}
if (!host) {
this.showToast('请输入服务器地址', 'error');
return;
}
if (!port || isNaN(port) || port < 1 || port > 65535) {
this.showToast('请输入有效的端口号 (1-65535)', 'error');
return;
}
profile = {
name: name,
displayName: displayName || name,
protocol: protocol,
host: host,
port: parseInt(port),
};
if (username && password) {
profile.auth = { username, password };
}
}
// 检查配置名称是否已存在(编辑模式下跳过此检查)
if (!this.editingProfile && this.profiles[name]) {
this.showToast('配置名称已存在,请使用其他名称', 'error');
return;
}
try {
console.log('Saving profile:', profile);
const response = await chrome.runtime.sendMessage({
action: 'addProfile',
profile: profile
});
console.log('Save response:', response);
if (response && response.success) {
this.profiles[profile.name] = profile;
this.renderProfiles();
this.closeModal('addProfileModal');
const action = this.editingProfile ? '更新' : '保存';
this.showToast(`配置${action}成功`, 'success');
// 重置编辑模式
this.editingProfile = null;
document.getElementById('profileName').disabled = false;
document.getElementById('profileForm').reset();
} else {
this.showToast(response?.error || '保存失败', 'error');
}
} catch (error) {
console.error('Failed to save profile:', error);
this.showToast('保存失败: ' + error.message, 'error');
}
}
async deleteProfile(profileName) {
if (!confirm(`确定要删除配置 "${profileName}" 吗?`)) {
return;
}
try {
const response = await chrome.runtime.sendMessage({
action: 'deleteProfile',
profileName: profileName
});
if (response.success) {
delete this.profiles[profileName];
this.renderProfiles();
this.showToast('配置删除成功', 'success');
} else {
this.showToast('删除失败', 'error');
}
} catch (error) {
console.error('Failed to delete profile:', error);
this.showToast('删除失败', 'error');
}
}
async toggleRule(index) {
if (index < 0 || index >= this.rules.length) return;
this.rules[index].enabled = !this.rules[index].enabled;
try {
await chrome.storage.sync.set({ autoSwitchRules: this.rules });
// 通知background script更新规则
await chrome.runtime.sendMessage({
action: 'updateRules',
rules: this.rules
});
this.renderRules();
this.showToast(`规则已${this.rules[index].enabled ? '启用' : '禁用'}`, 'success');
} catch (error) {
console.error('Failed to toggle rule:', error);
this.showToast('操作失败', 'error');
}
}
async deleteRule(index) {
if (!confirm('确定要删除这条规则吗?')) {
return;
}
this.rules.splice(index, 1);
try {
await chrome.storage.sync.set({ autoSwitchRules: this.rules });
// 通知background script更新规则
await chrome.runtime.sendMessage({
action: 'updateRules',
rules: this.rules
});
this.renderRules();
this.showToast('规则删除成功', 'success');
} catch (error) {
console.error('Failed to delete rule:', error);
this.showToast('删除失败', 'error');
}
}
async loadSettings() {
try {
const result = await chrome.storage.sync.get([
'enableNotifications',
'enableAutoSwitch',
'enableAutoFallback',
'enablePerformanceMonitoring'
]);
document.getElementById('enableNotifications').checked = result.enableNotifications !== false;
document.getElementById('enableAutoSwitch').checked = result.enableAutoSwitch !== false;
document.getElementById('enableAutoFallback').checked = result.enableAutoFallback !== false;
document.getElementById('enablePerformanceMonitoring').checked = result.enablePerformanceMonitoring !== false;
} catch (error) {
console.error('Failed to load settings:', error);
}
}
async saveSettings() {
const settings = {
enableNotifications: document.getElementById('enableNotifications').checked,
enableAutoSwitch: document.getElementById('enableAutoSwitch').checked,
enableAutoFallback: document.getElementById('enableAutoFallback').checked,
enablePerformanceMonitoring: document.getElementById('enablePerformanceMonitoring').checked
};
try {
await chrome.storage.sync.set(settings);
this.showToast('设置保存成功', 'success');
} catch (error) {
console.error('Failed to save settings:', error);
this.showToast('保存失败', 'error');
}
}
async exportData() {
try {
// 获取当前设置
const settings = await chrome.storage.sync.get([
'enableNotifications',
'enableAutoSwitch',
'enableAutoFallback',
'enablePerformanceMonitoring'
]);
const data = {
// 基本信息
version: chrome.runtime.getManifest().version,
exportTime: new Date().toISOString(),
// 代理配置
profiles: this.profiles,
// 自动切换规则
autoSwitchRules: this.rules,
// 扩展设置
settings: {
enableNotifications: settings.enableNotifications !== false,
enableAutoSwitch: settings.enableAutoSwitch !== false,
enableAutoFallback: settings.enableAutoFallback !== false,
enablePerformanceMonitoring: settings.enablePerformanceMonitoring !== false
},
// 统计信息
statistics: {
profileCount: Object.keys(this.profiles).length,
ruleCount: this.rules.length,
enabledRuleCount: this.rules.filter(rule => rule.enabled).length
}
};
console.log('Exporting data:', data);
const jsonString = JSON.stringify(data, null, 2);
const blob = new Blob([jsonString], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `proxymaster-config-${new Date().toISOString().split('T')[0]}.json`;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
this.showToast(`配置导出成功 - ${data.statistics.profileCount}个配置, ${data.statistics.ruleCount}个规则`, 'success');
} catch (error) {
console.error('Export failed:', error);
this.showToast('导出失败: ' + error.message, 'error');
}
}
importData() {
try {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.style.display = 'none';
input.name = 'importFile';
input.onchange = async (e) => {
const file = e.target.files[0];
if (!file) {
console.log('No file selected');
return;
}
console.log('Selected file:', file.name, file.size, 'bytes');
const reader = new FileReader();
reader.onload = async (e) => {
try {
const jsonText = e.target.result;
console.log('File content:', jsonText);
const data = JSON.parse(jsonText);
console.log('Parsed data:', data);
if (!data || typeof data !== 'object') {
throw new Error('无效的配置文件格式');
}
let importedProfiles = 0;
let importedRules = 0;
let importedSettings = false;
// 导入代理配置
if (data.profiles && typeof data.profiles === 'object') {
// 合并配置,避免覆盖现有配置
Object.entries(data.profiles).forEach(([name, profile]) => {
if (name !== 'direct' && profile && typeof profile === 'object') {
this.profiles[name] = profile;
importedProfiles++;
}
});
}
// 导入自动切换规则
const rules = data.autoSwitchRules;
if (rules && Array.isArray(rules)) {
// 合并规则
rules.forEach(rule => {
if (rule && typeof rule === 'object') {
this.rules.push(rule);
importedRules++;
}
});
}
// 导入设置(如果存在)
if (data.settings && typeof data.settings === 'object') {
await chrome.storage.sync.set(data.settings);
await this.loadSettings(); // 重新加载设置到界面
importedSettings = true;
}
// 保存到存储
await chrome.storage.sync.set({
profiles: this.profiles,
autoSwitchRules: this.rules
});
// 通知background script更新
await chrome.runtime.sendMessage({
action: 'reloadProfiles'
});
this.renderProfiles();
this.renderRules();
let message = `导入成功: ${importedProfiles}个配置, ${importedRules}个规则`;
if (importedSettings) {
message += ', 扩展设置';
}
this.showToast(message, 'success');
} catch (error) {
console.error('Failed to import data:', error);
this.showToast('导入失败: ' + error.message, 'error');
}
};
reader.onerror = () => {
console.error('File read error');
this.showToast('文件读取失败', 'error');
};
reader.readAsText(file);
};
document.body.appendChild(input);
input.click();
document.body.removeChild(input);
} catch (error) {
console.error('Import setup failed:', error);
this.showToast('导入功能初始化失败', 'error');
}
}
async clearAllData() {
if (!confirm('确定要清除所有数据吗?此操作不可恢复!')) {
return;
}
try {
await chrome.storage.sync.clear();
await chrome.storage.local.clear();
this.profiles = {};
this.rules = [];
this.currentProfile = 'direct';
this.renderProfiles();
this.renderRules();
this.updateStats();
this.showToast('所有数据已清除', 'success');
} catch (error) {
console.error('Failed to clear data:', error);
this.showToast('清除失败', 'error');
}
}
showAddProfileModal() {
// 重置编辑模式
this.editingProfile = null;
// 启用配置名称输入框
document.getElementById('profileName').disabled = false;
// 恢复模态框标题
document.querySelector('#addProfileModal .modal-header h3').textContent = '新建代理配置';
// 重置表单
document.getElementById('profileForm').reset();
// 重置协议字段显示(默认显示传统代理字段)
this.toggleProtocolFields('http');
// 显示模态框
document.getElementById('addProfileModal').classList.add('show');
}
showAddRuleModal() {
// 重置编辑模式
this.editingRuleIndex = null;
// 恢复模态框标题
document.querySelector('#addRuleModal .modal-header h3').textContent = '新建自动切换规则';
// 更新代理配置选项
this.updateRuleProfileOptions();
// 显示模态框
document.getElementById('addRuleModal').classList.add('show');
// 重置表单
document.getElementById('ruleForm').reset();
document.getElementById('rulePriority').value = '100';
// 更新帮助文本
this.updatePatternHelp('domain');
}
closeModal(modalId) {
document.getElementById(modalId).classList.remove('show');
}
editProfile(profileName) {
const profile = this.profiles[profileName];
if (!profile) {
this.showToast('配置不存在', 'error');
return;
}
// 填充基本表单数据
document.getElementById('profileName').value = profileName;
document.getElementById('profileDisplayName').value = profile.displayName || '';
document.getElementById('profileProtocol').value = profile.protocol || 'http';
// 根据协议类型填充不同的字段
const isV2RayProtocol = ['vmess', 'vless', 'trojan', 'shadowsocks'].includes(profile.protocol);
if (isV2RayProtocol && profile.v2rayConfig) {
// V2Ray协议配置
document.getElementById('v2rayHost').value = profile.host || '';
document.getElementById('v2rayPort').value = profile.port || '';
document.getElementById('v2rayId').value = profile.v2rayConfig.id || profile.v2rayConfig.password || '';
document.getElementById('v2rayNetwork').value = profile.v2rayConfig.network || 'tcp';
document.getElementById('v2rayTls').checked = profile.v2rayConfig.tls || false;
// 协议特定字段
if (profile.protocol === 'vmess') {
document.getElementById('v2rayAlterId').value = profile.v2rayConfig.alterId || 0;
} else if (profile.protocol === 'shadowsocks') {
document.getElementById('v2rayMethod').value = profile.v2rayConfig.method || 'aes-256-gcm';
}
// WebSocket配置
if (profile.v2rayConfig.network === 'ws') {
document.getElementById('v2rayWsPath').value = profile.v2rayConfig.wsPath || '/';
}
} else {
// 传统代理协议配置
document.getElementById('profileHost').value = profile.host || '';
document.getElementById('profilePort').value = profile.port || '';
document.getElementById('profileUsername').value = profile.auth?.username || '';
document.getElementById('profilePassword').value = profile.auth?.password || '';
}
// 切换字段显示
this.toggleProtocolFields(profile.protocol || 'http');
// 设置编辑模式
this.editingProfile = profileName;
// 禁用配置名称输入框(编辑时不允许修改名称)
document.getElementById('profileName').disabled = true;
// 更改模态框标题
document.querySelector('#addProfileModal .modal-header h3').textContent = '编辑代理配置';
// 显示模态框
document.getElementById('addProfileModal').classList.add('show');
}
editRule(index) {
const rule = this.rules[index];
if (!rule) {
this.showToast('规则不存在', 'error');
return;
}
// 设置编辑模式
this.editingRuleIndex = index;
// 先更新代理配置选项
this.updateRuleProfileOptions();
// 然后填充表单数据
document.getElementById('ruleName').value = rule.name || '';
document.getElementById('ruleType').value = rule.type || 'domain';
document.getElementById('rulePattern').value = rule.pattern || '';
document.getElementById('ruleProfile').value = rule.profile || '';
document.getElementById('rulePriority').value = rule.priority || 100;
// 更新帮助文本
this.updatePatternHelp(rule.type || 'domain');
// 更改模态框标题
document.querySelector('#addRuleModal .modal-header h3').textContent = '编辑自动切换规则';
// 显示模态框
document.getElementById('addRuleModal').classList.add('show');
}
updateRuleProfileOptions() {
const select = document.getElementById('ruleProfile');
// 清空现有选项,保留默认选项
select.innerHTML = `
<option value="">${chrome.i18n.getMessage('selectProxy')}</option>
<option value="direct">${chrome.i18n.getMessage('direct')}</option>