-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathextension.js
More file actions
424 lines (380 loc) · 12.2 KB
/
Copy pathextension.js
File metadata and controls
424 lines (380 loc) · 12.2 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
// 黄金价格监控扩展
const vscode = require("vscode");
const crypto = require("crypto");
const WebSocket = require("ws");
// 全局变量
let ws = null;
let reconnectAttempts = 0;
let reconnectTimeout;
const MAX_RECONNECT_ATTEMPTS = 5;
// 获取浙商积存金价格
async function fetchZSGoldPrice() {
try {
const response = await fetch(
"https://api.jdjygold.com/gw2/generic/jrm/h5/m/stdLatestPrice?productSku=1961543816",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
Origin: "https://www.jd.com",
Referer: "https://www.jd.com/",
},
body: JSON.stringify({
reqData: { productSku: "1961543816" },
}),
}
);
if (!response.ok) {
throw new Error(`HTTP错误: ${response.status}`);
}
const data = await response.json();
return data.resultData.datas.price;
} catch (error) {
console.error("获取浙商金价失败:", error);
throw error;
}
}
// 获取配置
function getConfig() {
const config = vscode.workspace.getConfiguration("gold");
return {
httpUrl: config.get(
"httpUrl",
"https://api.jdjygold.com/gw/generic/hj/h5/m/latestPrice"
),
httpRefreshInterval: config.get("httpRefreshInterval", 3000),
wsUrl: config.get(
"wsUrl",
"wss://alb-1ko0lowmvacsqia0ij.cn-shenzhen.alb.aliyuncsslb.com:26203"
),
wsReconnectInterval: config.get("wsReconnectInterval", 5000),
};
}
// 节流函数,防止频繁更新
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function () {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function () {
if (Date.now() - lastRan >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
// AES-256-CBC 解密 getDomainInfo 返回的 en_data
function decryptDomainInfo(enDataBase64) {
const encrypted = Buffer.from(enDataBase64, "base64");
// 前 16 字节是 IV,剩余部分是密文
const iv = encrypted.subarray(0, 16);
const ciphertext = encrypted.subarray(16);
const key = Buffer.from(
"JkiBZH1JS2QH2gNpweehCAiUJzOgIwvIqsndqGGgu8E=",
"base64"
);
const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
const decrypted = Buffer.concat([
decipher.update(ciphertext),
decipher.final(),
]).toString("utf8");
return JSON.parse(decrypted);
}
// 获取动态WebSocket链接
async function fetchWebSocketUrl() {
try {
const response = await fetch("https://www.jrjr.com/api/getDomainInfo", {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
},
});
if (!response.ok) {
throw new Error(`获取WebSocket链接失败: ${response.status}`);
}
const data = await response.json();
if (data.code !== 0 || !data.data || !data.data.en_data) {
throw new Error("响应数据格式错误");
}
// en_data 为 AES-256-CBC 加密,解密后读取 hq_ws_links
const config = decryptDomainInfo(data.data.en_data);
const wsLinks = config.hq_ws_links;
if (!wsLinks || typeof wsLinks !== "object") {
throw new Error("解密结果中缺少 hq_ws_links");
}
const firstKey = Object.keys(wsLinks)[0];
if (firstKey && wsLinks[firstKey]) {
const wsUrl = wsLinks[firstKey];
console.log("获取到动态WebSocket链接:", wsUrl, `(key: ${firstKey})`);
return wsUrl;
}
throw new Error("hq_ws_links 为空");
} catch (error) {
console.error("获取动态WebSocket链接失败:", error);
throw error;
}
}
// 获取HTTP金价
async function fetchGoldPrice() {
const config = getConfig();
try {
const response = await fetch(config.httpUrl, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
Origin: "https://www.jd.com",
Referer: "https://www.jd.com/",
},
});
if (!response.ok) {
throw new Error(`HTTP错误: ${response.status}`);
}
const data = await response.json();
return data.resultData.datas.price;
} catch (error) {
console.error("获取HTTP金价失败:", error);
throw error;
}
}
// 设置WebSocket连接
async function setupWebSocket(wsStatusBarItem) {
try {
// 关闭已存在的连接
if (ws) {
ws.removeAllListeners();
ws.close();
}
wsStatusBarItem.text = `$(radio-tower) 获取链接中...`;
// 获取动态WebSocket链接
let wsUrl;
try {
wsUrl = await fetchWebSocketUrl();
} catch (error) {
// 如果获取失败,使用配置中的备用链接
const config = getConfig();
wsUrl = config.wsUrl;
console.log("使用备用WebSocket链接:", wsUrl);
}
wsStatusBarItem.text = `$(radio-tower) 连接中...`;
ws = new WebSocket(wsUrl);
ws.on("open", () => {
console.log("WebSocket已连接");
wsStatusBarItem.text = `$(radio-tower) 已连接`;
reconnectAttempts = 0;
if (reconnectTimeout) {
clearTimeout(reconnectTimeout);
reconnectTimeout = null;
}
});
ws.on(
"message",
throttle((message) => {
try {
const data = JSON.parse(message.toString());
if (data && data.length && data[0].symbol === "GOLD") {
const price = data[0].bid; // 使用买入价
wsStatusBarItem.text = `$(radio-tower) ${price}`;
wsStatusBarItem.tooltip = `伦敦金 | 卖出价: ${data[0].ask} | 买入价: ${data[0].bid} | 更新时间: ${new Date().toLocaleTimeString()}`;
}
} catch (error) {
console.error("解析WebSocket消息失败:", error);
}
}, 1000)
);
ws.on("error", (error) => {
console.error("WebSocket错误:", error);
wsStatusBarItem.text = `$(error) WS金价: 错误`;
wsStatusBarItem.tooltip = `错误: ${error.message}`;
});
ws.on("close", () => {
console.log("WebSocket已断开");
wsStatusBarItem.text = `$(circle-slash) WS金价: 已断开`;
// 尝试重连
if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
reconnectAttempts++;
wsStatusBarItem.text = `$(sync~spin) WS金价: 重连中(${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`;
const config = getConfig();
console.log(`尝试重连 ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS}`);
reconnectTimeout = setTimeout(() => {
setupWebSocket(wsStatusBarItem);
}, config.wsReconnectInterval);
} else {
console.log("WebSocket重连失败,达到最大尝试次数");
wsStatusBarItem.text = `$(error) WS金价: 重连失败`;
}
});
} catch (error) {
console.error("设置WebSocket时出错:", error);
wsStatusBarItem.text = `$(error) WS金价: 设置失败`;
wsStatusBarItem.tooltip = `错误: ${error.message}`;
}
}
// 扩展激活时调用
function activate(context) {
console.log('扩展"黄金价格监控"已激活');
// 创建HTTP状态栏项(民生)
const httpStatusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Left,
100
);
httpStatusBarItem.text = `$(cloud) 民生: 加载中...`;
httpStatusBarItem.tooltip = "点击刷新民生金价";
httpStatusBarItem.command = "goldprice.refreshHttp";
httpStatusBarItem.show();
// 创建浙商状态栏项
const zsStatusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Left,
99
);
zsStatusBarItem.text = `$(package) 浙商: 加载中...`;
zsStatusBarItem.tooltip = "点击刷新浙商金价";
zsStatusBarItem.command = "goldprice.refreshZS";
zsStatusBarItem.show();
// 创建WebSocket状态栏项
const wsStatusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Left,
98
);
wsStatusBarItem.text = `$(radio-tower) WS金价: 连接中...`;
wsStatusBarItem.tooltip = "点击重连WebSocket";
wsStatusBarItem.command = "goldprice.refreshWs";
wsStatusBarItem.show();
// 更新HTTP金价显示
async function updateHttpPrice() {
try {
const price = await fetchGoldPrice();
httpStatusBarItem.text = `$(cloud) 民生: ${price}`;
httpStatusBarItem.tooltip = `民生数据 | 更新时间: ${new Date().toLocaleTimeString()}`;
return price;
} catch (error) {
httpStatusBarItem.text = `$(error) 民生: 获取失败`;
httpStatusBarItem.tooltip = `错误: ${error.message}`;
return null;
}
}
// 更新浙商金价显示
async function updateZSPrice() {
try {
const price = await fetchZSGoldPrice();
zsStatusBarItem.text = `$(package) 浙商: ${price}`;
zsStatusBarItem.tooltip = `浙商积存金 | 更新时间: ${new Date().toLocaleTimeString()}`;
return price;
} catch (error) {
zsStatusBarItem.text = `$(error) 浙商: 获取失败`;
zsStatusBarItem.tooltip = `错误: ${error.message}`;
return null;
}
}
// 注册HTTP刷新命令
const refreshHttpCommand = vscode.commands.registerCommand(
"goldprice.refreshHttp",
async () => {
await updateHttpPrice();
}
);
// 注册浙商刷新命令
const refreshZSCommand = vscode.commands.registerCommand(
"goldprice.refreshZS",
async () => {
await updateZSPrice();
}
);
// 注册WebSocket刷新命令
const refreshWsCommand = vscode.commands.registerCommand(
"goldprice.refreshWs",
() => {
reconnectAttempts = 0; // 重置重连计数
setupWebSocket(wsStatusBarItem);
}
);
// 注册刷新所有命令
const refreshAllCommand = vscode.commands.registerCommand(
"goldprice.refresh",
async () => {
await updateHttpPrice();
await updateZSPrice();
reconnectAttempts = 0;
setupWebSocket(wsStatusBarItem);
}
);
// 设置HTTP定时更新
let httpInterval = null;
function setupHttpInterval() {
const config = getConfig();
if (httpInterval) {
clearInterval(httpInterval);
}
httpInterval = setInterval(updateHttpPrice, config.httpRefreshInterval);
}
// 设置浙商定时更新
let zsInterval = null;
function setupZSInterval() {
const config = getConfig();
if (zsInterval) {
clearInterval(zsInterval);
}
zsInterval = setInterval(updateZSPrice, config.httpRefreshInterval);
}
// 监听配置变更
context.subscriptions.push(
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration("gold")) {
setupHttpInterval();
setupZSInterval();
setupWebSocket(wsStatusBarItem);
}
})
);
// 注册资源到订阅中以便自动清理
context.subscriptions.push(httpStatusBarItem);
context.subscriptions.push(zsStatusBarItem);
context.subscriptions.push(wsStatusBarItem);
context.subscriptions.push(refreshHttpCommand);
context.subscriptions.push(refreshZSCommand);
context.subscriptions.push(refreshWsCommand);
context.subscriptions.push(refreshAllCommand);
context.subscriptions.push({
dispose: () => {
if (httpInterval) clearInterval(httpInterval);
if (zsInterval) clearInterval(zsInterval);
if (reconnectTimeout) clearTimeout(reconnectTimeout);
if (ws) ws.close();
},
});
// 首次更新金价并设置定时更新
updateHttpPrice();
updateZSPrice();
setupHttpInterval();
setupZSInterval();
// 设置WebSocket连接
setupWebSocket(wsStatusBarItem);
}
// 扩展停用时调用
function deactivate() {
if (ws) {
ws.close();
ws = null;
}
console.log('扩展"黄金价格监控"已停用');
}
module.exports = {
activate,
deactivate,
};