-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathChinaTelecom_Multi.js
More file actions
1946 lines (1782 loc) · 68.3 KB
/
Copy pathChinaTelecom_Multi.js
File metadata and controls
1946 lines (1782 loc) · 68.3 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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-green; icon-glyph: phone-square;
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-green; icon-glyph: phone-square;
/*
* @author: 2Ya&脑瓜 (原UI作者)
* @integration: (RSA登录 + 电信官方API)
* @feedback https://t.me/Scriptable_CN
* version: 3.0.0-rsa
* update: 2026-08-02
* 说明:使用 Scripting 版本的登录逻辑(RSA加密+电信官方API,支持多账户)
*
* 📱 Device ID 参数说明:
* Device ID 用于解决部分用户登录失败的问题
* 获取方式:
* 网站1:https://commissions-yields-exception-personally.trycloudflare.com
* 网站2:https://telecom.nufe.ccwu.cc
* 使用步骤:
* 1. 打开上述任一网站
* 2. 使用短信登录授权设备
* 3. 复制显示的设备 ID
* 4. 在脚本设置中填写「设备ID(可选)」
* 5. 若留空则自动生成随机设备ID(可能需要多次尝试)
*/
if (typeof require === 'undefined') require = importModule;
const { DmYY, Runing } = require('./DmYY');
class Widget extends DmYY {
constructor(arg) {
super(arg);
this.name = "China Telecom";
this.en = "ChinaTelecom_2024_Login";
this.logo = "https://raw.githubusercontent.com/anker1209/icon/main/zgdx-big.png";
this.smallLogo = "https://raw.githubusercontent.com/anker1209/icon/main/zgdx.png";
this.Run();
}
version = '3.1.0-multi';
gradient = false;
flowColorHex = "#FF6620";
voiceColorHex = "#78C100";
ringStackSize = 65;
ringTextSize = 14;
feeTextSize = 21;
textSize = 13;
smallPadding = 12;
padding = 10;
logoScale = 0.24;
SCALE = 1;
canvSize = 178;
canvWidth = 18;
canvRadius = 80;
widgetStyle = '1';
currIndex = '1';
format = (str) => {
return parseInt(str) >= 10 ? str : `0${str}`;
};
date = new Date();
arrUpdateTime = [
this.format(this.date.getMonth() + 1),
this.format(this.date.getDate()),
this.format(this.date.getHours()),
this.format(this.date.getMinutes()),
];
fee = {
title: "剩余话费",
icon: 'antenna.radiowaves.left.and.right',
number: '0',
iconColor: new Color('#0C54D9'),
unit: "元",
en: "¥",
};
flow = {
percent: 0,
max: 40,
title: "剩余流量",
number: '0',
unit: "GB",
en: "GB",
icon: "antenna.radiowaves.left.and.right",
iconColor: new Color("#FF6620"),
FGColor: new Color(this.flowColorHex),
BGColor: new Color(this.flowColorHex, 0.2),
colors: [],
};
voice = {
percent: 0,
title: "剩余语音",
number: '0',
unit: "分钟",
en: "MIN",
icon: 'phone.badge.waveform.fill',
iconColor: new Color("#78C100"),
FGColor: new Color(this.voiceColorHex),
BGColor: new Color(this.voiceColorHex, 0.2),
colors: [],
};
point = {
title: "更新时间",
number: `${this.arrUpdateTime[2]}:${this.arrUpdateTime[3]}`,
unit: "",
icon: "arrow.2.circlepath",
iconColor: new Color("fc6d6d"),
};
// ==================== 辅助函数 ====================
_safeN(v) {
const n = typeof v === "number" ? v : parseFloat(v ?? "0");
return Number.isFinite(n) ? n : 0;
}
_formatFlowMB(mb) {
if (!Number.isFinite(mb) || mb <= 0) return { balance: "0", unit: "MB" };
if (mb >= 1024) return { balance: (mb / 1024).toFixed(2), unit: "GB" };
return { balance: Math.floor(mb).toString(), unit: "MB" };
}
_nowHHMM() {
const d = new Date();
return `${d.getHours().toString().padStart(2, "0")}:${d.getMinutes().toString().padStart(2, "0")}`;
}
// ==================== 适配自定义API的数据转换 ====================
_convertToCarrierData(apiData) {
if (!apiData) throw new Error("电信:API 数据为空");
// 话费(分转元)
const balanceFen = this._safeN(apiData.balance);
const remainFee = (balanceFen / 100).toFixed(2);
// 语音
const voiceTotal = this._safeN(apiData.voiceTotal);
const voiceBalance = this._safeN(apiData.voiceBalance);
let voiceUsed = this._safeN(apiData.voiceUsage);
if (voiceUsed === 0 && voiceTotal > 0) {
voiceUsed = voiceTotal - voiceBalance;
}
// 流量(KB转MB)
const flowTotalKB = this._safeN(apiData.flowTotal);
const flowUsedKB = this._safeN(apiData.flowUse);
let flowBalanceKB = 0;
if (apiData.flowItems && apiData.flowItems.length > 0) {
flowBalanceKB = this._safeN(apiData.flowItems[0].balance);
} else {
flowBalanceKB = flowTotalKB - flowUsedKB;
}
const flowTotalMB = flowTotalKB / 1024;
const flowUsedMB = flowUsedKB / 1024;
const flowBalanceMB = flowBalanceKB / 1024;
const flowFmt = this._formatFlowMB(flowBalanceMB);
return {
fee: {
title: "剩余话费",
balance: remainFee,
unit: "元",
},
flow: {
title: "通用流量",
balance: flowFmt.balance,
unit: flowFmt.unit,
used: flowUsedMB,
total: flowTotalMB,
},
otherFlow: undefined,
voice: {
title: "剩余语音",
balance: voiceBalance.toString(),
unit: "分钟",
used: voiceUsed,
total: voiceTotal,
},
updateTime: this._nowHHMM(),
};
}
init = async () => {
try {
const scale = this.getWidgetScaleFactor();
this.SCALE = this.settings.SCALE || scale;
const {
step1,
step2,
logoColor,
flowIconColor,
voiceIconColor,
gradient,
builtInColor,
previewAccount
} = this.settings;
// 多账户支持:读取小组件参数
let param = args.widgetParameter ? args.widgetParameter.toString() : (previewAccount || '1');
if (!['1','2','3','4','5'].includes(param)) param = '1';
this.currIndex = param;
// 读取当前账户的配置
this.widgetStyle = this.settings[`widgetStyle${param}`] || '1';
this.gradient = gradient === 'true';
if (builtInColor === 'true') {
const [feeColor, flowColor, voiceColor] = this.getIconColorSet();
this.fee.iconColor = new Color(feeColor);
this.flow.iconColor = new Color(flowColor);
this.voice.iconColor = new Color(voiceColor);
} else {
this.fee.iconColor = logoColor ? new Color(logoColor) : this.fee.iconColor;
this.flow.iconColor = flowIconColor ? new Color(flowIconColor) : this.flow.iconColor;
this.voice.iconColor = voiceIconColor ? new Color(voiceIconColor) : this.voice.iconColor;
}
this.flowColorHex = step1 || this.flowColorHex;
this.voiceColorHex = step2 || this.voiceColorHex;
this.flow.BGColor = new Color(this.flowColorHex, 0.2);
this.voice.BGColor = new Color(this.voiceColorHex, 0.2);
this.flow.FGColor = new Color(this.flowColorHex);
this.voice.FGColor = new Color(this.voiceColorHex);
const sizeSettings = [
'ringStackSize',
'ringTextSize',
'feeTextSize',
'textSize',
'smallPadding',
'padding',
];
for (const key of sizeSettings) {
this[key] = this.settings[key] ? parseFloat(this.settings[key]) : this[key];
this[key] = this[key] * this.SCALE;
}
if (this.gradient) {
this.flow.colors = this.arrColor();
this.voice.colors = this.arrColor();
this.flow.BGColor = new Color(this.flow.colors[1], 0.2);
this.voice.BGColor = new Color(this.voice.colors[1], 0.2);
this.flow.FGColor = this.gradientColor(this.flow.colors, 360);
this.voice.FGColor = this.gradientColor(this.voice.colors, 360);
this.flowColorHex = this.flow.colors[1];
this.voiceColorHex = this.voice.colors[1];
}
// 从缓存加载数据
if (this.settings.dataSource) {
Object.keys(this.settings.dataSource).forEach((key) => {
if (this[key] && typeof this.settings.dataSource[key] === "object") {
Object.assign(this[key], this.settings.dataSource[key]);
}
});
if (this.settings.dataSource.updateTime) {
this.arrUpdateTime = this.settings.dataSource.updateTime.split(':');
}
}
} catch (e) {
console.error(e);
}
// 多账户检查:检查当前账户的配置
const phoneKey = `telecom_phone${this.currIndex}`;
const passwordKey = `telecom_password${this.currIndex}`;
if (!this.settings[phoneKey] || !this.settings[passwordKey]) {
if (config.runsInApp) {
return this.notify(this.name, `请先为账户${this.currIndex}填写手机号和服务密码`);
}
return;
}
await this.getData();
};
// ==================== RSA 加密(WebView + JSEncrypt) ====================
async rsaEncrypt(text) {
const publicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBkLT15ThVgz6/NOl6s8GNPofd\n" +
"WzWbCkWnkaAm7O2LjkM1H7dMvzkiqdxU02jamGRHLX/ZNMCXHnPcW/sDhiFCBN18\n" +
"qFvy8g6VYb9QtroI09e176s+ZCtiv7hbin2cCTj99iUpnEloZm19lwHyo69u5UMi\n" +
"PMpq0/XKBO8lYhN/gwIDAQAB\n" +
"-----END PUBLIC KEY-----";
const escapedKey = publicKey.replace(/\n/g, "\\n");
const escapedText = text.replace(/"/g, '\\"');
const html = '<!DOCTYPE html><html><head><meta charset="utf-8">' +
'<script src="https://cdn.jsdelivr.net/npm/jsencrypt@3.3.2/bin/jsencrypt.min.js"></script>' +
'</head><body><div id="result"></div><script>' +
'try{' +
'const e=new JSEncrypt();' +
'e.setPublicKey("' + escapedKey + '");' +
'const r=e.encrypt("' + escapedText + '");' +
'document.getElementById("result").innerText=r||"ERROR:encryption_failed";' +
'}catch(e){document.getElementById("result").innerText="ERROR:"+e.message}' +
'</script></body></html>';
const webView = new WebView();
await webView.loadHTML(html);
await webView.waitForLoad();
const result = await webView.evaluateJavaScript('document.getElementById("result").innerText');
if (!result || result.startsWith("ERROR")) {
throw new Error("RSA加密失败: " + (result || "无响应"));
}
return result.trim();
}
transNumber(str, encode = true) {
return [...str].map((c) => String.fromCharCode((c.charCodeAt(0) + (encode ? 2 : -2)) & 0xffff)).join("");
}
getBeijingTimestamp() {
const bjDate = new Date(Date.now() + 8 * 3600 * 1000);
const yyyy = String(bjDate.getFullYear());
const MM = String(bjDate.getMonth() + 1).padStart(2, "0");
const dd = String(bjDate.getDate()).padStart(2, "0");
const HH = String(bjDate.getHours()).padStart(2, "0");
const mm = String(bjDate.getMinutes()).padStart(2, "0");
const ss = String(bjDate.getSeconds()).padStart(2, "0");
return `${yyyy}${MM}${dd}${HH}${mm}${ss}`;
}
async telecomLogin() {
const param = this.currIndex;
const phonenum = this.settings[`telecom_phone${param}`];
const password = this.settings[`telecom_password${param}`];
const deviceid = this.settings[`telecom_deviceid${param}`] || "";
const uuid = String(Math.floor(Math.random() * 9e15 + 1e15));
const ts = this.getBeijingTimestamp();
console.log("🔐 正在生成 RSA 签名...");
const encryptText = `iPhone 14 15.4.0${deviceid || uuid.slice(0, 12)}${phonenum}${ts}${password}0$$$0.`;
const encrypted = await this.rsaEncrypt(encryptText);
const loginBody = {content:{fieldData:{loginType:"4",accountType:"",isChinatelecom:"",systemVersion:"15.4.0",deviceUid:uuid.slice(0,16),phoneNum:this.transNumber(phonenum),authentication:this.transNumber(password),androidId:deviceid?this.transNumber(deviceid):"",loginAuthCipherAsymmertric:encrypted},attach:"iPhone"},headerInfos:{code:"userLoginNormal",clientType:"#12.2.0#channel50#iPhone 14 Pro#",timestamp:ts,shopId:"20002",source:"110003",sourcePassword:"Sid98s",userLoginName:this.transNumber(phonenum)}};
const req = new Request("https://appgologin.189.cn:9031/login/client/userLoginNormal");
req.method = "POST";
req.headers = {"Content-Type":"application/json; charset=UTF-8"};
req.body = JSON.stringify(loginBody);
req.timeoutInterval = 15;
const loginResp = await req.loadString();
const loginData = JSON.parse(loginResp);
if (loginData.responseData?.resultCode !== "0000") throw new Error(loginData.responseData?.resultDesc || "登录失败");
const {token,cityCode,provinceCode} = loginData.responseData.data.loginSuccessResult;
this.settings[`telecom_token${param}`] = token;
this.settings[`telecom_cityCode${param}`] = cityCode;
this.settings[`telecom_provinceCode${param}`] = provinceCode;
this.saveSettings(false);
console.log(`✅ 登录成功 | 省:${provinceCode} 市:${cityCode}`);
return {token,cityCode,provinceCode};
}
async fetchImportantData() {
const param = this.currIndex;
const phonenum = this.settings[`telecom_phone${param}`];
const token = this.settings[`telecom_token${param}`] || "";
const cityCode = this.settings[`telecom_cityCode${param}`] || "";
const provinceCode = this.settings[`telecom_provinceCode${param}`] || "";
const ts = this.getBeijingTimestamp();
const dataBody = {content:{fieldData:{provinceCode,cityCode,shopId:"20002",isChinatelecom:"0",account:this.transNumber(phonenum)},attach:"test"},headerInfos:{code:"qryImportantData",clientType:"#12.2.0#channel50#iPhone 14 Pro#",timestamp:ts,shopId:"20002",source:"110003",sourcePassword:"Sid98s",userLoginName:this.transNumber(phonenum),token}};
const req = new Request("https://appfuwu.189.cn:9021/query/qryImportantData");
req.method = "POST";
req.headers = {"Content-Type":"application/json; charset=UTF-8"};
req.body = JSON.stringify(dataBody);
req.timeoutInterval = 15;
const dataResp = await req.loadString();
return JSON.parse(dataResp);
}
// ==================== getData 方法(电信官方API) ====================
getData = async () => {
const param = this.currIndex;
const phoneKey = `telecom_phone${param}`;
const passwordKey = `telecom_password${param}`;
if (!this.settings[phoneKey] || !this.settings[passwordKey]) {
console.log(`❌ 账户[${param}] 未配置手机号或密码`);
if (config.runsInApp) return this.notify(this.name, `请先为账户${param}填写手机号和服务密码`);
return;
}
const fm = FileManager.local();
const cacheDir = fm.joinPath(fm.documentsDirectory(), "ChinaTelecom_Cache");
const cachePath = fm.joinPath(cacheDir, `account_${param}.json`);
if (!fm.fileExists(cacheDir)) fm.createDirectory(cacheDir, true);
const t0 = Date.now();
console.log(`🚀 电信组件启动 (RSA登录) | 账户${param} | 手机号: ${this.settings[phoneKey].slice(-4)}`);
let cached = null;
let cacheAge = null;
const CACHE_TTL = 30 * 60 * 1000;
if (fm.fileExists(cachePath)) {
const modified = fm.modificationDate(cachePath);
cacheAge = Date.now() - modified.getTime();
if (cacheAge < CACHE_TTL) {
console.log(`🧠 使用缓存数据 | 缓存时间: ${Math.round(cacheAge / 60000)} 分钟前`);
try {
cached = JSON.parse(fm.readString(cachePath));
Object.keys(cached).forEach((key) => {
if (this[key] && typeof cached[key] === "object") {
Object.assign(this[key], cached[key]);
}
});
if (cached.updateTime) {
this.arrUpdateTime = cached.updateTime.split(':');
}
console.log(`✅ 渲染完成 | 来源: 缓存 | 耗时: ${Date.now() - t0}ms`);
return;
} catch (e) {
console.log(`⚠️ 缓存损坏,刷新数据`);
}
} else {
console.log(`🔵 缓存已过期 (${Math.round(cacheAge / 60000)} > 30分)`);
}
}
try {
let dataResp;
try {
console.log("📡 尝试使用缓存 token 获取数据...");
dataResp = await this.fetchImportantData();
if (!dataResp.responseData) throw new Error("Token 失效");
} catch (e) {
console.log("🔄 Token 失效,重新登录...");
await this.telecomLogin();
console.log("✅ 登录成功,重新获取数据...");
dataResp = await this.fetchImportantData();
}
if (!dataResp.responseData) throw new Error(dataResp.headerInfos?.reason || "获取数据失败");
const apiData = dataResp.responseData.data;
const balance = this._safeN(apiData.balanceInfo?.indexBalanceDataInfo?.balance || apiData.balance);
this.fee.number = balance.toFixed(2);
// 根据"过滤定向"设置选择流量数据源
let flowUsed, flowTotal, flowBalance;
if (this.settings.filterOrientateFlow === "true") {
// 过滤定向:只显示通用流量 (commonFlow)
flowUsed = this._safeN(apiData.flowInfo?.commonFlow?.used || 0);
flowBalance = this._safeN(apiData.flowInfo?.commonFlow?.balance || 0);
flowTotal = this._safeN(apiData.flowInfo?.commonFlow?.total || (flowUsed + flowBalance));
console.log("📶 流量模式:仅通用流量(已过滤定向)");
} else {
// 不过滤:显示总流量 (totalAmount)
flowUsed = this._safeN(apiData.flowInfo?.totalAmount?.used || apiData.usedFlux);
flowBalance = this._safeN(apiData.flowInfo?.totalAmount?.balance || 0);
flowTotal = this._safeN(apiData.flowInfo?.totalAmount?.total || (flowUsed + flowBalance));
console.log("📶 流量模式:总流量(包含定向)");
}
const flowTotalMB = flowTotal / 1024;
const flowUsedMB = flowUsed / 1024;
const flowBalanceMB = flowBalance / 1024;
let flowPercent = 0;
if (flowTotalMB > 0) flowPercent = (flowUsedMB / flowTotalMB) * 100;
this.flow.percent = flowPercent.toFixed(2);
console.log(`📊 流量百分比: ${this.flow.percent}% (已用 ${flowUsedMB.toFixed(2)} MB / 总量 ${flowTotalMB.toFixed(2)} MB)`);
// 根据"显示已用"设置选择显示内容
if (this.settings.showUsedFlow === "true") {
// 显示已用流量
this.flow.title = "已用流量";
this.flow.number = (flowUsedMB / 1024).toFixed(2);
this.flow.unit = "GB";
console.log(`📊 显示模式:已用流量 ${this.flow.number} GB`);
} else {
// 显示剩余流量
this.flow.title = "剩余流量";
const flowFmt = this._formatFlowMB(flowBalanceMB);
this.flow.number = flowFmt.balance;
this.flow.unit = flowFmt.unit;
console.log(`📊 显示模式:剩余流量 ${this.flow.number} ${this.flow.unit}`);
}
this.flow.en = this.flow.unit;
console.log("📞 语音原始数据:", JSON.stringify(apiData.voiceInfo?.voiceDataInfo || {}, null, 2));
const voiceTotal = this._safeN(apiData.voiceInfo?.voiceDataInfo?.total || apiData.totalVoice);
const voiceUsed = this._safeN(apiData.voiceInfo?.voiceDataInfo?.used || apiData.usedVoice);
const voiceBalance = this._safeN(apiData.voiceInfo?.voiceDataInfo?.balance || (voiceTotal - voiceUsed));
// 根据"显示已用"设置,语音也要同步显示已用或剩余
if (this.settings.showUsedFlow === "true") {
// 显示已用
this.voice.title = "已用语音";
this.voice.number = voiceUsed.toString();
if (voiceTotal > 0) {
this.voice.percent = ((voiceUsed / voiceTotal) * 100).toFixed(2);
} else {
this.voice.percent = "0";
}
console.log(`📞 语音(已用): ${voiceUsed} 分钟, 百分比: ${this.voice.percent}%`);
} else {
// 显示剩余
this.voice.title = "剩余语音";
this.voice.number = voiceBalance.toString();
if (voiceTotal > 0) {
this.voice.percent = ((voiceBalance / voiceTotal) * 100).toFixed(2);
} else {
this.voice.percent = "0";
}
console.log(`📞 语音(剩余): ${voiceBalance} 分钟, 百分比: ${this.voice.percent}%`);
}
const d = new Date();
this.arrUpdateTime = [d.getMonth()+1,d.getDate(),d.getHours(),d.getMinutes()].map((n)=>n.toString().padStart(2,"0"));
// 保存到独立缓存文件
const cacheData = {fee:{number:this.fee.number},voice:{number:this.voice.number,percent:this.voice.percent},flow:{en:this.flow.en,number:this.flow.number,unit:this.flow.unit,percent:this.flow.percent,title:this.flow.title},updateTime:this.arrUpdateTime.join(":"),_timestamp:Date.now()};
if (fm.fileExists(cachePath)) fm.remove(cachePath);
fm.writeString(cachePath, JSON.stringify(cacheData));
console.log(`✅ 渲染完成 | 来源: 电信官方API | 耗时: ${Date.now()-t0}ms | 话费: ${this.fee.number}元 流量: ${this.flow.number}${this.flow.unit} 语音: ${this.voice.number}分钟`);
} catch (e) {
let errorMessage = e.message || "未知错误";
console.error(`⛔️ 电信渲染异常: ${errorMessage}`);
if (fm.fileExists(cachePath)) {
console.warn("⚠️ 使用过期缓存兜底");
try {
const oldCache = JSON.parse(fm.readString(cachePath));
Object.keys(oldCache).forEach((key) => {
if (this[key] && typeof oldCache[key] === "object") {
Object.assign(this[key], oldCache[key]);
}
});
if (oldCache.updateTime) {
this.arrUpdateTime = oldCache.updateTime.split(':');
}
} catch (e2) {
console.error("缓存读取失败");
}
if (config.runsInApp) this.notify(this.name, "网络连接失败,当前显示缓存数据");
} else {
if (config.runsInApp) this.notify(this.name, `获取失败: ${errorMessage}`);
}
}
};
// ==================== UI 渲染函数(完整保留) ====================
async header(stack) {
const headerStack = stack.addStack();
headerStack.addSpacer();
const logo = headerStack.addImage(await this.$request.get(this.logo, 'IMG'));
logo.imageSize = new Size(415 * this.logoScale * this.SCALE, 125 * this.logoScale * this.SCALE);
headerStack.addSpacer();
stack.addSpacer();
const feeStack = stack.addStack();
feeStack.centerAlignContent();
feeStack.addSpacer();
const feeValue = feeStack.addText(`${this.fee.number}`);
this.unit(feeStack, '元', 5 * this.SCALE, this.widgetColor);
feeValue.font = Font.mediumRoundedSystemFont(this.feeTextSize);
feeValue.textColor = this.widgetColor;
feeStack.addSpacer();
stack.addSpacer();
}
textLayout(stack, data) {
const rowStack = stack.addStack();
rowStack.centerAlignContent();
const icon = SFSymbol.named(data.icon) || SFSymbol.named('phone.fill');
icon.applyHeavyWeight();
let iconElement = rowStack.addImage(icon.image);
iconElement.imageSize = new Size(this.textSize, this.textSize);
iconElement.tintColor = data.iconColor;
rowStack.addSpacer(4 * this.SCALE);
let title = rowStack.addText(data.title);
rowStack.addSpacer();
let number = rowStack.addText(data.number + data.unit);
[title, number].map(t => t.textColor = this.widgetColor);
[title, number].map(t => t.font = Font.systemFont(this.textSize * this.SCALE));
}
async setThirdWidget(widget) {
const amountStack = widget.addStack();
amountStack.centerAlignContent();
const icon = await this.$request.get(this.smallLogo, 'IMG');
if (this.settings.builtInColor === 'true') {
const iconStack = amountStack.addStack();
iconStack.setPadding(4 * this.SCALE, 4 * this.SCALE, 4 * this.SCALE, 4 * this.SCALE);
iconStack.backgroundColor = this.fee.iconColor;
iconStack.cornerRadius = 12 * this.SCALE;
const iconImage = iconStack.addImage(icon);
iconImage.imageSize = new Size(16 * this.SCALE, 16 * this.SCALE);
iconImage.tintColor = Color.white();
} else {
const iconImage = amountStack.addImage(icon);
iconImage.imageSize = new Size(24 * this.SCALE, 24 * this.SCALE);
}
amountStack.addSpacer();
const amountText = amountStack.addText(`${this.fee.number}`);
amountText.font = Font.boldRoundedSystemFont(24 * this.SCALE);
amountText.minimumScaleFactor = 0.5;
amountText.textColor = this.widgetColor;
this.unit(amountStack, '元', 7 * this.SCALE);
widget.addSpacer();
const mainStack = widget.addStack();
this.setRow(mainStack, this.flow, this.flowColorHex);
mainStack.addSpacer();
this.setRow(mainStack, this.voice, this.voiceColorHex);
}
async setForthWidget(widget) {
const bodyStack = widget.addStack();
bodyStack.cornerRadius = 14 * this.SCALE;
bodyStack.layoutVertically();
const headerStack = bodyStack.addStack();
headerStack.setPadding(8 * this.SCALE, 12 * this.SCALE, 0, 12 * this.SCALE);
headerStack.layoutVertically();
const title = headerStack.addText(this.fee.title);
title.font = Font.systemFont(12 * this.SCALE);
title.textColor = this.widgetColor
title.textOpacity = 0.7;
const balanceStack = headerStack.addStack();
const balanceText = balanceStack.addText(`${this.fee.number}`);
balanceText.minimumScaleFactor = 0.5;
balanceText.font = Font.boldRoundedSystemFont(22 * this.SCALE);
const color = this.widgetColor;
balanceText.textColor = color;
this.unit(balanceStack, '元', 5 * this.SCALE, color);
balanceStack.addSpacer();
balanceStack.centerAlignContent();
const icon = await this.$request.get(this.smallLogo, 'IMG');
if (this.settings.builtInColor === 'true') {
const iconStack = balanceStack.addStack();
iconStack.setPadding(4 * this.SCALE, 4 * this.SCALE, 4 * this.SCALE, 4 * this.SCALE);
iconStack.backgroundColor = this.fee.iconColor;
iconStack.cornerRadius = 12 * this.SCALE;
const iconImage = iconStack.addImage(icon);
iconImage.imageSize = new Size(16 * this.SCALE, 16 * this.SCALE);
iconImage.tintColor = Color.white();
} else {
const iconImage = balanceStack.addImage(icon);
iconImage.imageSize = new Size(24 * this.SCALE, 24 * this.SCALE);
}
bodyStack.addSpacer();
const mainStack = bodyStack.addStack();
mainStack.setPadding(8 * this.SCALE, 12 * this.SCALE, 8 * this.SCALE, 12 * this.SCALE);
mainStack.cornerRadius = 14 * this.SCALE;
mainStack.backgroundColor = Color.dynamic(new Color("#E2E2E7", 0.3), new Color("#2C2C2F", 1));
mainStack.layoutVertically();
this.setList(mainStack, this.flow);
mainStack.addSpacer();
this.setList(mainStack, this.voice);
}
setList(stack, data) {
const rowStack = stack.addStack();
rowStack.centerAlignContent();
const lineStack = rowStack.addStack();
lineStack.size = new Size(8 * this.SCALE, 30 * this.SCALE);
lineStack.cornerRadius = 4 * this.SCALE;
lineStack.backgroundColor = data.iconColor;
rowStack.addSpacer(10 * this.SCALE);
const leftStack = rowStack.addStack();
leftStack.layoutVertically();
leftStack.addSpacer(2 * this.SCALE);
const titleStack = leftStack.addStack();
const title = titleStack.addText(data.title);
title.font = Font.systemFont(10 * this.SCALE);
title.textColor = this.widgetColor;
title.textOpacity = 0.5;
const valueStack = leftStack.addStack();
valueStack.centerAlignContent();
const value = valueStack.addText(`${data.number}`);
value.font = Font.semiboldRoundedSystemFont(16 * this.SCALE);
value.textColor = this.widgetColor;
valueStack.addSpacer();
const unitStack = valueStack.addStack();
unitStack.cornerRadius = 4 * this.SCALE;
unitStack.borderWidth = 1;
unitStack.borderColor = data.iconColor;
unitStack.setPadding(1, 3 * this.SCALE, 1, 3 * this.SCALE);
unitStack.size = new Size(30 * this.SCALE, 0)
unitStack.backgroundColor = Color.dynamic(data.iconColor, new Color(data.iconColor.hex, 0.3));
const unit = unitStack.addText(data.en);
unit.font = Font.mediumRoundedSystemFont(10 * this.SCALE);
unit.textColor = Color.dynamic(Color.white(), data.iconColor);
}
setRow(stack, data, color) {
const stackWidth = 68 * this.SCALE;
const rowStack = stack.addStack();
rowStack.layoutVertically();
rowStack.size = new Size(stackWidth, 0);
const image = this.gaugeChart(data, color);
const imageStack = rowStack.addStack();
imageStack.layoutVertically();
imageStack.size = new Size(stackWidth, stackWidth);
imageStack.backgroundImage = image;
imageStack.addSpacer();
const iconStack = imageStack.addStack();
iconStack.addSpacer();
const sfs = SFSymbol.named(data.icon) || SFSymbol.named('phone.fill');
sfs.applyHeavyWeight();
const icon = iconStack.addImage(sfs.image);
icon.imageSize = new Size(22 * this.SCALE, 22 * this.SCALE);
icon.tintColor = new Color(color);
iconStack.addSpacer();
imageStack.addSpacer(8 * this.SCALE);
const unitStack = imageStack.addStack();
unitStack.addSpacer();
const innerStack = unitStack.addStack();
innerStack.size = new Size(32 * this.SCALE, 0);
innerStack.setPadding(1, 1, 1, 1);
innerStack.backgroundColor = new Color(color);
innerStack.cornerRadius = 4 * this.SCALE;
const unit = innerStack.addText(data.en);
unit.font = Font.semiboldRoundedSystemFont(10 * this.SCALE);
unit.textColor = Color.white();
unitStack.addSpacer();
imageStack.addSpacer(4 * this.SCALE);
const infoStack = rowStack.addStack();
infoStack.cornerRadius = 12 * this.SCALE;
infoStack.layoutVertically();
let gradient = new LinearGradient();
gradient.colors = [new Color(color, 0.1), new Color(color, 0.01)];
gradient.locations = [0, 1];
gradient.startPoint = new Point(0, 0);
gradient.endPoint = new Point(0, 1);
infoStack.backgroundGradient = gradient;
const valueStack = infoStack.addStack();
valueStack.size = new Size(stackWidth, 0);
valueStack.setPadding(3 * this.SCALE, 0, 2 * this.SCALE, 0)
const value = valueStack.addText(`${data.number}`);
value.textColor = this.widgetColor;
value.font = Font.semiboldRoundedSystemFont(18 * this.SCALE);
value.centerAlignText();
const titleStack = infoStack.addStack();
titleStack.addSpacer();
const title = titleStack.addText(data.title);
title.font = Font.regularRoundedSystemFont(9 * this.SCALE);
title.textOpacity = 0.5;
titleStack.addSpacer();
}
async small(stack, data, logo = false, en = false) {
const bg = new LinearGradient();
bg.locations = [0, 1];
bg.endPoint = new Point(1, 0)
bg.colors = [
new Color(data.iconColor.hex, 0.1),
new Color(data.iconColor.hex, 0.03)
];
const rowStack = stack.addStack();
rowStack.centerAlignContent();
rowStack.setPadding(5, 8, 5, 8)
rowStack.backgroundGradient = bg;
rowStack.cornerRadius = 12;
const leftStack = rowStack.addStack();
leftStack.layoutVertically();
const titleStack = leftStack.addStack();
const title = titleStack.addText(data.title);
const balanceStack = leftStack.addStack();
balanceStack.centerAlignContent();
const balanceUnit = en ? data.en : ''
const balance = balanceStack.addText(`${data.number} ${balanceUnit}`);
if (!en) this.addChineseUnit(balanceStack, data.unit, data.iconColor, 13 * this.SCALE);
balance.font = Font.semiboldRoundedSystemFont(16 * this.SCALE);
title.textOpacity = 0.5;
title.font = Font.mediumSystemFont(11 * this.SCALE);
[title, balance].map(t => t.textColor = data.iconColor);
rowStack.addSpacer();
let iconImage;
if (logo) {
const icon = await this.$request.get(this.smallLogo, 'IMG');
iconImage = rowStack.addImage(icon);
} else {
const icon = SFSymbol.named(data.icon) || SFSymbol.named('phone.fill');
icon.applyHeavyWeight();
iconImage = rowStack.addImage(icon.image);
};
iconImage.imageSize = new Size(22 * this.SCALE, 22 * this.SCALE);
iconImage.tintColor = data.iconColor;
}
async smallCell(stack, data, logo = false, en = false) {
const bg = new LinearGradient();
const padding = 6 * this.SCALE;
bg.locations = [0, 1];
bg.endPoint = new Point(1, 0)
bg.colors = [
new Color(data.iconColor.hex, 0.03),
new Color(data.iconColor.hex, 0.1)
];
const rowStack = stack.addStack();
rowStack.setPadding(4, 4, 4, 4)
rowStack.backgroundGradient = bg;
rowStack.cornerRadius = 12;
const iconStack = rowStack.addStack();
iconStack.backgroundColor = data.iconColor;
iconStack.setPadding(padding, padding, padding, padding);
iconStack.cornerRadius = 17 * this.SCALE;
let iconImage;
if (logo) {
const icon = await this.$request.get(this.smallLogo, 'IMG');
iconImage = iconStack.addImage(icon);
} else {
const icon = SFSymbol.named(data.icon) || SFSymbol.named('phone.fill');
icon.applyHeavyWeight();
iconImage = iconStack.addImage(icon.image);
};
iconImage.imageSize = new Size(22 * this.SCALE, 22 * this.SCALE);
iconImage.tintColor = new Color('FFFFFF');
rowStack.addSpacer(15);
const rightStack = rowStack.addStack();
rightStack.layoutVertically();
const balanceStack = rightStack.addStack();
balanceStack.centerAlignContent();
const balanceUnit = en ? data.en : ''
const balance = balanceStack.addText(`${data.number} ${balanceUnit}`);
if (!en) this.addChineseUnit(balanceStack, data.unit, data.iconColor, 13 * this.SCALE);
balance.font = Font.semiboldRoundedSystemFont(16 * this.SCALE);
const titleStack = rightStack.addStack();
const title = titleStack.addText(data.title);
title.centerAlignText();
rowStack.addSpacer();
title.textOpacity = 0.5;
title.font = Font.mediumSystemFont(11 * this.SCALE);
[title, balance].map(t => t.textColor = data.iconColor);
}
async mediumCell(canvas, stack, data, color, fee = false, percent) {
const bg = new LinearGradient();
bg.locations = [0, 1];
bg.colors = [
new Color(color, 0.03),
new Color(color, 0.1)
];
const dataStack = stack.addStack();
dataStack.backgroundGradient = bg;
dataStack.cornerRadius = 15;
dataStack.layoutVertically();
dataStack.addSpacer();
const topStack = dataStack.addStack();
topStack.addSpacer();
await this.imageCell(canvas, topStack, data, fee, percent);
topStack.addSpacer();
if (fee) {
dataStack.addSpacer(5);
const updateStack = dataStack.addStack();
updateStack.addSpacer();
updateStack.centerAlignContent();
const updataIcon = SFSymbol.named('arrow.2.circlepath');
updataIcon.applyHeavyWeight();
const updateImg = updateStack.addImage(updataIcon.image);
updateImg.tintColor = new Color(color, 0.6);
updateImg.imageSize = new Size(10, 10);
updateStack.addSpacer(3);
const updateText = updateStack.addText(`${this.arrUpdateTime[2]}:${this.arrUpdateTime[3]}`)
updateText.font = Font.mediumSystemFont(10);
updateText.textColor = new Color(color, 0.6);
updateStack.addSpacer();
}
dataStack.addSpacer();
const numberStack = dataStack.addStack();
numberStack.addSpacer();
const number = numberStack.addText(`${data.number} ${data.en}`);
number.font = Font.semiboldSystemFont(15);
numberStack.addSpacer();
dataStack.addSpacer(3);
const titleStack = dataStack.addStack();
titleStack.addSpacer();
const title = titleStack.addText(data.title);
title.font = Font.mediumSystemFont(11);
title.textOpacity = 0.7;
titleStack.addSpacer();
dataStack.addSpacer(15);
[title, number].map(t => t.textColor = new Color(color));
}
async imageCell(canvas, stack, data, fee, percent) {
const canvaStack = stack.addStack();
canvaStack.layoutVertically();
if (!fee) {
this.drawArc(canvas, data.percent * 3.6, data.FGColor, data.BGColor);
canvaStack.size = new Size(this.ringStackSize, this.ringStackSize);
canvaStack.backgroundImage = canvas.getImage();
this.ringContent(canvaStack, data, percent);
} else {
canvaStack.addSpacer(10);
const smallLogo = await this.$request.get(this.smallLogo, 'IMG');
const logoStack = canvaStack.addStack();
logoStack.size = new Size(40, 40);
logoStack.backgroundImage = smallLogo;
}
}
ringContent(stack, data, percent = false) {
const rowIcon = stack.addStack();
rowIcon.addSpacer();
const icon = SFSymbol.named(data.icon) || SFSymbol.named('phone.fill');
icon.applyHeavyWeight();
const iconElement = rowIcon.addImage(icon.image);
iconElement.tintColor = this.gradient ? new Color(data.colors[1]) : data.FGColor;
iconElement.imageSize = new Size(12, 12);
iconElement.imageOpacity = 0.7;
rowIcon.addSpacer();
stack.addSpacer(1);
const rowNumber = stack.addStack();
rowNumber.addSpacer();
const number = rowNumber.addText(percent ? `${data.percent}` : `${data.number}`);
number.font = percent ? Font.systemFont(this.ringTextSize - 2) : Font.mediumSystemFont(this.ringTextSize);
rowNumber.addSpacer();
const rowUnit = stack.addStack();
rowUnit.addSpacer();
const unit = rowUnit.addText(percent ? '%' : data.unit);
unit.font = Font.boldSystemFont(8);
unit.textOpacity = 0.5;
rowUnit.addSpacer();
if (percent) {
if (this.gradient) {
[unit, number].map(t => t.textColor = new Color(data.colors[1]));
} else {
[unit, number].map(t => t.textColor = data.FGColor);
}
} else {
[unit, number].map(t => t.textColor = this.widgetColor);
}
}
makeCanvas() {
const canvas = new DrawContext();
canvas.opaque = false;
canvas.respectScreenScale = true;
canvas.size = new Size(this.canvSize, this.canvSize);
return canvas;
}
sinDeg(deg) {
return Math.sin((deg * Math.PI) / 180);
}
cosDeg(deg) {
return Math.cos((deg * Math.PI) / 180);
}
drawArc(canvas, deg, fillColor, strokeColor) {
let ctr = new Point(this.canvSize / 2, this.canvSize / 2);
let bgx = ctr.x - this.canvRadius;
let bgy = ctr.y - this.canvRadius;
let bgd = 2 * this.canvRadius;
let bgr = new Rect(bgx, bgy, bgd, bgd)
canvas.setStrokeColor(strokeColor);
canvas.setLineWidth(this.canvWidth);
canvas.strokeEllipse(bgr);
for (let t = 0; t < deg; t++) {
let rect_x = ctr.x + this.canvRadius * this.sinDeg(t) - this.canvWidth / 2;
let rect_y = ctr.y - this.canvRadius * this.cosDeg(t) - this.canvWidth / 2;