forked from MizuhaHimuraki/github-name-mapper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
417 lines (354 loc) · 11.6 KB
/
Copy pathbackground.js
File metadata and controls
417 lines (354 loc) · 11.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
// GitHub Name Mapper - Background Service Worker
const ALARM_NAME = 'daily-update';
const VERSION_CHECK_ALARM = 'version-check';
const GITHUB_REPO = 'MizuhaHimuraki/github-name-mapper';
const DEFAULT_CONFIG = {
enabled: true,
autoUpdate: true,
jsonUrl: '',
lastUpdate: null,
developers: [],
localRules: [],
// 版本更新相关
latestVersion: null,
lastVersionCheck: null,
dismissedVersion: null,
// 功能开关
featureReplace: true, // 识别用户(替换用户名)
featureHighlight: true, // 识别用户高亮(文字)
featureAvatarHighlight: true, // 识别用户高亮(头像)
featureMention: true, // @@ 快速补全
// 调试模式
debug: false
};
// 初始化
chrome.runtime.onInstalled.addListener(async () => {
const config = await getConfig();
// 合并配置,保留现有数据(如 localRules),只添加缺失的默认值
const mergedConfig = { ...DEFAULT_CONFIG, ...config };
// 确保数组字段不被覆盖为空数组
if (config.localRules && config.localRules.length > 0) {
mergedConfig.localRules = config.localRules;
}
if (config.developers && config.developers.length > 0) {
mergedConfig.developers = config.developers;
}
await saveConfig(mergedConfig);
// 设置每日更新定时器
if (mergedConfig.autoUpdate) {
setupDailyAlarm();
}
// 设置版本检查定时器(每12小时检查一次)
setupVersionCheckAlarm();
// 安装/更新后立即检查一次版本
checkForUpdates();
});
// 定时器触发
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === ALARM_NAME) {
const config = await getConfig();
if (config.autoUpdate && config.jsonUrl) {
await fetchAndUpdateData(config.jsonUrl);
}
} else if (alarm.name === VERSION_CHECK_ALARM) {
await checkForUpdates();
}
});
// 监听来自 popup 或 options 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
handleMessage(request, sender, sendResponse);
return true; // 保持消息通道开放
});
async function handleMessage(request, sender, sendResponse) {
try {
switch (request.action) {
case 'getConfig':
const config = await getConfig();
sendResponse({ success: true, data: config });
break;
case 'saveConfig':
await saveConfig(request.config);
// 更新定时器设置
if (request.config.autoUpdate) {
setupDailyAlarm();
} else {
chrome.alarms.clear(ALARM_NAME);
}
sendResponse({ success: true });
break;
case 'fetchData':
const result = await fetchAndUpdateData(request.url);
sendResponse(result);
break;
case 'getDevelopers':
const devConfig = await getConfig();
// 合并远程数据和本地规则
const allDevelopers = [...devConfig.developers, ...devConfig.localRules];
sendResponse({ success: true, data: allDevelopers });
break;
case 'addLocalRule':
await addLocalRule(request.rule);
sendResponse({ success: true });
break;
case 'removeLocalRule':
await removeLocalRule(request.index);
sendResponse({ success: true });
break;
case 'updateLocalRule':
await updateLocalRule(request.index, request.rule);
sendResponse({ success: true });
break;
case 'importLocalRules':
{
const mode = request.mode || 'merge';
const result = await importLocalRules(request.rules, mode);
sendResponse({ success: true, ...result });
}
break;
case 'toggle':
const currentConfig = await getConfig();
currentConfig.enabled = request.enabled;
await saveConfig(currentConfig);
sendResponse({ success: true });
break;
case 'checkUpdate':
const updateInfo = await checkForUpdates();
sendResponse(updateInfo);
break;
case 'getUpdateInfo':
const updateConfig = await getConfig();
const currentVersion = chrome.runtime.getManifest().version;
sendResponse({
success: true,
currentVersion,
latestVersion: updateConfig.latestVersion,
hasUpdate: updateConfig.latestVersion && compareVersions(updateConfig.latestVersion, currentVersion) > 0,
dismissed: updateConfig.dismissedVersion === updateConfig.latestVersion,
downloadUrl: `https://github.com/${GITHUB_REPO}/releases/latest`
});
break;
case 'dismissUpdate':
const dismissConfig = await getConfig();
dismissConfig.dismissedVersion = dismissConfig.latestVersion;
await saveConfig(dismissConfig);
sendResponse({ success: true });
break;
default:
sendResponse({ success: false, error: 'Unknown action' });
}
} catch (error) {
console.error('Message handling error:', error);
sendResponse({ success: false, error: error.message });
}
}
// 获取配置
async function getConfig() {
return new Promise((resolve) => {
chrome.storage.local.get('config', (result) => {
resolve(result.config || DEFAULT_CONFIG);
});
});
}
// 保存配置
async function saveConfig(config) {
return new Promise((resolve) => {
chrome.storage.local.set({ config }, resolve);
});
}
// 设置每日定时器
function setupDailyAlarm() {
// 每24小时触发一次
chrome.alarms.create(ALARM_NAME, {
periodInMinutes: 24 * 60
});
}
// 设置版本检查定时器
function setupVersionCheckAlarm() {
// 每12小时检查一次
chrome.alarms.create(VERSION_CHECK_ALARM, {
periodInMinutes: 12 * 60
});
}
// 检查 GitHub 最新版本
async function checkForUpdates() {
try {
const response = await fetch(
`https://api.github.com/repos/${GITHUB_REPO}/releases/latest`,
{
headers: {
'Accept': 'application/vnd.github.v3+json'
}
}
);
if (!response.ok) {
console.log('Version check failed:', response.status);
return { success: false, error: `HTTP ${response.status}` };
}
const data = await response.json();
const latestVersion = data.tag_name.replace(/^v/, '');
const currentVersion = chrome.runtime.getManifest().version;
const config = await getConfig();
config.latestVersion = latestVersion;
config.lastVersionCheck = new Date().toISOString();
await saveConfig(config);
const hasUpdate = compareVersions(latestVersion, currentVersion) > 0;
console.log(`Version check: current=${currentVersion}, latest=${latestVersion}, hasUpdate=${hasUpdate}`);
return {
success: true,
currentVersion,
latestVersion,
hasUpdate,
downloadUrl: data.html_url,
releaseNotes: data.body
};
} catch (error) {
console.error('Version check error:', error);
return { success: false, error: error.message };
}
}
// 版本号比较 (返回 1: a > b, -1: a < b, 0: a = b)
function compareVersions(a, b) {
const partsA = a.split('.').map(Number);
const partsB = b.split('.').map(Number);
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const numA = partsA[i] || 0;
const numB = partsB[i] || 0;
if (numA > numB) return 1;
if (numA < numB) return -1;
}
return 0;
}
// 获取远程数据并更新
async function fetchAndUpdateData(url) {
if (!url) {
return { success: false, error: '请先配置 JSON URL' };
}
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
// 支持新格式: { data: { list: [...] } } 和旧格式: { developers: [...] }
let rawDevelopers;
if (data.data && Array.isArray(data.data.list)) {
rawDevelopers = data.data.list;
} else {
throw new Error('JSON 格式错误: 缺少 data.list 数组');
}
// 转换并验证数据格式
const validDevelopers = rawDevelopers
.map(dev => ({
// 新格式字段映射: account -> github_name, nickname -> nick, email -> github_acc
github_name: dev.account || dev.github_name,
nick: dev.nickname || dev.nick,
domain: dev.domain,
github_acc: dev.email || dev.github_acc
}))
.filter(dev => dev.github_name && (dev.nick || dev.domain));
const config = await getConfig();
config.developers = validDevelopers;
config.lastUpdate = new Date().toISOString();
await saveConfig(config);
// 通知所有 GitHub 标签页更新
notifyTabs();
return {
success: true,
count: validDevelopers.length,
lastUpdate: config.lastUpdate
};
} catch (error) {
console.error('Fetch error:', error);
return { success: false, error: error.message };
}
}
// 添加本地规则
async function addLocalRule(rule) {
const config = await getConfig();
config.localRules.push({
...rule,
isLocal: true,
createdAt: new Date().toISOString()
});
await saveConfig(config);
notifyTabs();
}
// 删除本地规则
async function removeLocalRule(index) {
const config = await getConfig();
config.localRules.splice(index, 1);
await saveConfig(config);
notifyTabs();
}
// 更新本地规则
async function updateLocalRule(index, rule) {
const config = await getConfig();
config.localRules[index] = {
...config.localRules[index],
...rule,
updatedAt: new Date().toISOString()
};
await saveConfig(config);
notifyTabs();
}
function normalizeImportedLocalRule(rule) {
if (!rule || typeof rule !== 'object') return null;
// 兼容多种字段名
const githubName = (rule.github_name || rule.account || rule.githubName || '').toString().trim();
const nick = (rule.nick || rule.nickname || '').toString().trim();
const domain = (rule.domain || '').toString().trim();
const githubAcc = (rule.github_acc || rule.email || rule.githubAcc || '').toString().trim();
if (!githubName || !nick) return null;
return {
domain,
nick,
github_name: githubName,
github_acc: githubAcc,
isLocal: true,
createdAt: (rule.createdAt || new Date().toISOString())
};
}
function localRuleSignature(rule) {
const domain = (rule.domain || '').toString().trim();
const nick = (rule.nick || '').toString().trim();
const githubName = (rule.github_name || '').toString().trim();
const githubAcc = (rule.github_acc || '').toString().trim();
return `${domain}\n${nick}\n${githubName}\n${githubAcc}`;
}
async function importLocalRules(rules, mode = 'merge') {
const list = Array.isArray(rules) ? rules : [];
const normalized = list
.map(normalizeImportedLocalRule)
.filter(Boolean);
const config = await getConfig();
if (mode === 'replace') {
config.localRules = normalized;
await saveConfig(config);
notifyTabs();
return { importedCount: normalized.length, totalLocalRules: config.localRules.length };
}
const existing = Array.isArray(config.localRules) ? config.localRules : [];
const seen = new Set(existing.map(localRuleSignature));
let importedCount = 0;
for (const rule of normalized) {
const sig = localRuleSignature(rule);
if (seen.has(sig)) continue;
seen.add(sig);
existing.push(rule);
importedCount += 1;
}
config.localRules = existing;
await saveConfig(config);
notifyTabs();
return { importedCount, totalLocalRules: config.localRules.length };
}
// 通知所有 GitHub 标签页更新
function notifyTabs() {
chrome.tabs.query({ url: ['https://github.com/*', 'https://*.github.com/*'] }, (tabs) => {
tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, { action: 'refresh' }).catch(() => {
// 忽略无法连接的标签页
});
});
});
}