-
Notifications
You must be signed in to change notification settings - Fork 118
/
lsp环境.js
2446 lines (2230 loc) · 93.2 KB
/
lsp环境.js
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-gray; icon-glyph: user-astronaut;
/**
* 公众号:杂货万事屋
* 很多模板源自于互联网,有侵权的请公众号留言
* Author:LSP
*/
// 当前环境版本号
const VERSION = 20221122
class Base {
constructor(scriptName) {
//=====================
// 设置脚本名字
this.scriptName = scriptName
this.initCommonCacheKey();
//=====================
this.initDefaultValue();
//=====================
// 设置默认间距
this.paddingSetting()
//=====================
// 背景模式
const colorBgMode = this.keyGet(this.colorBgModeKey, 'true');
// 初始化背景模式
this.setColorBgMode(colorBgMode)
//=====================
// 设置刷新时间
let refreshTimeCache = this.keyGet(this.refreshTimeKey, `${this.defaultRefreshTime}`);
this.refreshIntervalTime(Number(refreshTimeCache));
//=====================
// 设置预览参数
this.configSetting()
// 设置预览尺寸-中等
this.setPreViewSizeMode(1)
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/**
* 获取缓存key
* @param {*} cacheKey
* @returns
*/
getCacheKey = (cacheKey) => {
return `${this.scriptName}_${cacheKey}`;
}
/**
* 初始化缓存通用key
*/
initCommonCacheKey = () => {
// 颜色
this.colorCacheKey = this.getCacheKey('colorKey');
// 渐变角度
this.colorAngleCacheKey = this.getCacheKey('colorAngleKey');
// 颜色背景模式
this.colorBgModeKey = this.getCacheKey('colorBgModeKey');
// 组件刷新时间
this.refreshTimeKey = this.getCacheKey('refreshKey');
// 是否使用iCloud
this.useiCloudKey = this.getCacheKey('useiCloudKey');
}
/**
* 使用缓存
* @returns
*/
useCache = (cacheKey) => {
const iCloud = this.keyGet(this.useiCloudKey, 'false');
const fm = FileManager[iCloud == 'true' ? 'iCloud' : 'local']();
const cacheDirectory = fm.joinPath(fm.documentsDirectory(), `${this.scriptName}/cache`);
const cacheFile = fm.joinPath(cacheDirectory, this.getCacheKey(cacheKey));
if (!fm.fileExists(cacheDirectory)) {
fm.createDirectory(cacheDirectory, true);
}
const saveStringCache = (content) => {
console.log('cececec-?' + cacheFile);
fm.writeString(cacheFile, content);
};
const getStringCache = () => {
const fileExists = fm.fileExists(cacheFile)
let cacheString = ""
if (fileExists) {
cacheString = fm.readString(cacheFile)
}
return cacheString
}
return {
saveStringCache,
getStringCache,
}
};
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
initDefaultValue(widgetFamily = config.widgetFamily) {
//=====================
this.defaultRefreshTime = 30;
this.defaultBgAlpha = 0.5;
this.defaultBgShadowColor = '#000';
this.defaultGradientAngle = 0;
this.defaultWidgetBgColor = '#141E30,#243B55';
//=====================
// 组件大小:small,medium,large
this.widgetFamily = widgetFamily
// 本地存储管理
this.fmLocal = FileManager.local()
}
/**
* 预览模式
* @param {number} mode 预览尺寸,0:小型,1:中型,2:大型,负数:不进行预览
*/
setPreViewSizeMode(mode) {
this.previewSizeMode = mode
}
/**
* 设置组件刷新间隔
* @param {number}} interval 刷新间隔(单位:分钟)
*/
refreshIntervalTime(interval = 30) {
this.refreshInterval = interval
}
/**
* 是否是纯色背景模式
* @param {bool} mode 模式开关
* @param {Color} bgColor 背景颜色
*/
setColorBgMode(mode, bgColor = Color.black()) {
this.colorBgMode = mode
this.picBgMode = !mode
this.bgColor = bgColor
this.keySave(this.colorBgModeKey, '' + mode);
}
/**
* 是否是背景模式
* @param {bool} mode 模式开关
*/
setSelectPicBg(mode) {
this.setColorBgMode(!mode)
}
/**
* 小组件边距设置
* @param {obj} padding 小组件边距
*/
paddingSetting(padding = { top: 0, left: 0, bottom: 0, right: 0 }) {
this.padding = padding
}
/**
* 小组件参数设置
* @param {configArr} 小组件预览配置
*/
configSetting(configArr = []) {
this.configArr = configArr
}
/**
* 小组件全路径名
* @param {name} 名称
*/
setModuleName(name = '') {
this.moduleName = name
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
getColors = (color = '') => {
const colors = typeof color === 'string' ? color.split(',') : color
return colors
}
/**
* 渐变色
* @param {颜色} colors
* @returns
*/
getLinearGradientColor = (colors) => {
const colorAngleCache = this.keyGet(this.colorAngleCacheKey, this.defaultGradientAngle);
let angle = Number(colorAngleCache);
const locations = [];
const linearColor = new LinearGradient();
let x = 0, y = 0;
if (angle < 45) {
y = 0.5 - 0.5 / 45 * angle;
} else if (angle < 135) {
x = 1 / 90 * (angle - 45);
} else if (angle <= 180) {
x = 1;
y = 0.5 / 45 * (angle - 135);
}
linearColor.startPoint = new Point(x, y);
linearColor.endPoint = new Point(1 - x, 1 - y);
let avg = 1 / (colors.length - 1);
linearColor.colors = colors.map((item, index) => {
locations.push(index * avg);
return new Color(item);
});
linearColor.locations = locations;
return linearColor;
}
/**
* 字符串是否包含中文
* @param {string} str 文本
* @returns 是否包含中文
*/
strContainCn(str) {
return /.*[\u4e00-\u9fa5]+.*/.test(str)
}
/**
* 字符串是否全部是中文
* @param {string} str 文本
* @returns 是否全部是中文
*/
strAllCn(str) {
return /^[\u4e00-\u9fa5]+$/.test(str)
}
/**
* 画icon
* @param {*} icon
* @param {*} color
* @param {*} cornerWidth
* @returns
*/
drawTableIcon = async (
icon = 'square.grid.2x2',
color = '#e8e8e8',
cornerWidth = 42
) => {
let sf = SFSymbol.named(icon);
if (sf == null) {
sf = SFSymbol.named('scribble');
}
sf.applyFont(Font.mediumSystemFont(30));
const imgData = Data.fromPNG(sf.image).toBase64String();
const html = `
<img id="sourceImg" src="data:image/png;base64,${imgData}" />
<img id="silhouetteImg" src="" />
<canvas id="mainCanvas" />
`
const js = `
var canvas = document.createElement("canvas");
var sourceImg = document.getElementById("sourceImg");
var silhouetteImg = document.getElementById("silhouetteImg");
var ctx = canvas.getContext('2d');
var size = sourceImg.width > sourceImg.height ? sourceImg.width : sourceImg.height;
canvas.width = size;
canvas.height = size;
ctx.drawImage(sourceImg, (canvas.width - sourceImg.width) / 2, (canvas.height - sourceImg.height) / 2);
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var pix = imgData.data;
//convert the image into a silhouette
for (var i=0, n = pix.length; i < n; i+= 4){
//set red to 0
pix[i] = 255;
//set green to 0
pix[i+1] = 255;
//set blue to 0
pix[i+2] = 255;
//retain the alpha value
pix[i+3] = pix[i+3];
}
ctx.putImageData(imgData,0,0);
silhouetteImg.src = canvas.toDataURL();
output=canvas.toDataURL()
`
let wv = new WebView()
await wv.loadHTML(html)
const base64Image = await wv.evaluateJavaScript(js)
const iconImage = await new Request(base64Image).loadImage()
const size = new Size(160, 160)
const ctx = new DrawContext()
ctx.opaque = false
ctx.respectScreenScale = true
ctx.size = size
const path = new Path()
const rect = new Rect(0, 0, size.width, size.width)
path.addRoundedRect(rect, cornerWidth, cornerWidth)
path.closeSubpath()
ctx.setFillColor(new Color(color))
ctx.addPath(path)
ctx.fillPath()
const rate = 36
const iw = size.width - rate
const x = (size.width - iw) / 2
ctx.drawImageInRect(iconImage, new Rect(x, x, iw, iw))
return ctx.getImage()
}
/**
* 绘制自定义字体文本
* @param {string} fontUrl ttf字体url
* @param {string} text 文本
* @param {number} fontSize 文本字体大小
* @param {Color} textColor 文本颜色
* @param {string} align 文本对齐
* @param {number} lineLimit 行数
* @param {number} rowSpacing 行间距
* @returns 绘制的文字图片
*/
async drawTextWithCustomFont(fontUrl, text, fontSize, textColor, align = "center", lineLimit = 1, rowSpacing = 5) {
const font = new CustomFont(new WebView(), {
fontFamily: 'customFont', // 字体名称
fontUrl: fontUrl, // 字体地址
timeout: 60000, // 加载字体的超时时间
}) // 创建字体
await font.load() // 加载字体
const image = await font.drawText(text, {
fontSize: fontSize, // 字体大小
textWidth: 0, // 文本宽度
align: align, // left、right、center
lineLimit: lineLimit, // 文本行数限制
rowSpacing: rowSpacing, // 文本行间距
textColor: textColor, // 文本颜色
scale: 2, // 缩放因子
})
return image
}
/**
* base64 编码字符串
* @param {string} str 要编码的字符串
*/
base64Encode(str) {
const data = Data.fromString(str)
return data.toBase64String()
}
/**
* base64解码数据 返回字符串
* @param {string} b64 base64编码的数据
*/
base64Decode(b64) {
const data = Data.fromBase64String(b64)
return data.toRawString()
}
/**
* Http Get 请求接口
* @param {string} url 请求的url
* @param {bool} json 返回数据是否为json,默认true
* @param {Obj} headers 请求头
* @param {string} pointCacheKey 指定缓存key
* @param {bool} logable 是否打印数据,默认true
* @return {string | json | null}
*/
async httpGet(url, json = true, headers, pointCacheKey, logable = false) {
// 根据URL进行md5生成cacheKey
let cacheKey = pointCacheKey
if (cacheKey == undefined || cacheKey == null || cacheKey.length == 0) {
cacheKey = this.md5(url)
}
// 读取本地缓存
const localCache = this.loadStringCache(cacheKey)
// 判断是否需要刷新
const lastCacheTime = this.getCacheModificationDate(cacheKey)
const timeInterval = Math.floor((this.getCurrentTimeStamp() - lastCacheTime) / 60)
const canLoadCache = localCache != null && localCache.length > 0;
console.log(`⏰已缓存:${timeInterval}min, 缓存时间:${this.getDateStr(new Date(lastCacheTime * 1000), 'HH:mm')}, 刷新:${this.refreshInterval}min`);
// 过时且有本地缓存则直接返回本地缓存数据
if (timeInterval <= this.refreshInterval && canLoadCache) {
console.log(`🤖Get读取缓存:${url}`)
// 是否打印响应数据
if (logable) {
console.log(`🤖Get请求响应:${localCache}`)
}
console.log(`----------------------------------------`)
return json ? JSON.parse(localCache) : localCache
}
let data = null
try {
console.log(`🚀Get在线请求:${url}`)
let req = new Request(url)
req.method = 'GET'
if (headers != null && headers != undefined) {
req.headers = headers
}
data = await (json ? req.loadJSON() : req.loadString())
} catch (e) {
console.error(`🚫Get请求失败:${e}: ${url}`)
}
// 判断数据是否为空(加载失败)
if (!data && canLoadCache) {
console.log(`🤖Get读取缓存:${url}`)
console.log(`----------------------------------------`)
return json ? JSON.parse(localCache) : localCache
}
// 存储缓存
this.saveStringCache(cacheKey, json ? JSON.stringify(data) : data)
// 是否打印响应数据
if (logable) {
console.log(`🤖Get请求响应:${JSON.stringify(data)}`)
}
console.log(`----------------------------------------`)
return data
}
/**
* Http POST 请求接口
* @param {string} url 请求的url
* @param {Array} parameterKV 请求参数键值对数组
* @param {bool} json 返回数据是否为json,默认true
* @param {Obj} headers 请求头
* @param {string} pointCacheKey 指定缓存key
* @param {bool} logable 是否打印数据,默认false
* @return {string | json | null}
*/
async httpPost(url, parameterKV, json = true, headers, pointCacheKey, logable = true) {
// 根据URL进行md5生成cacheKey
let cacheKey = pointCacheKey
if (cacheKey == undefined || cacheKey == null || cacheKey.length == 0) {
cacheKey = this.md5(url)
}
// 读取本地缓存
const localCache = this.loadStringCache(cacheKey)
// 判断是否需要刷新
const lastCacheTime = this.getCacheModificationDate(cacheKey)
const timeInterval = Math.floor((this.getCurrentTimeStamp() - lastCacheTime) / 60)
const canLoadCache = localCache != null && localCache.length > 0;
console.log(`⏰已缓存:${timeInterval}min, 缓存时间:${this.getDateStr(new Date(lastCacheTime * 1000), 'HH:mm')}, 刷新:${this.refreshInterval}min`);
// 过时且有本地缓存则直接返回本地缓存数据
if (timeInterval <= this.refreshInterval && canLoadCache) {
console.log(`🤖Post读取缓存: ${url}`)
// 是否打印响应数据
if (logable) {
console.log(`🤖Post请求响应:${localCache}`)
}
console.log(`----------------------------------------`)
return json ? JSON.parse(localCache) : localCache
}
let data = null
try {
console.log(`🚀Post在线请求:${url}`)
let req = new Request(url)
req.method = 'POST'
if (headers != null && headers != undefined) {
req.headers = headers
}
for (const parameter of parameterKV) {
req.addParameterToMultipart(Object.keys(parameter)[0], Object.values(parameter)[0])
}
data = await (json ? req.loadJSON() : req.loadString())
} catch (e) {
console.error(`🚫Post请求失败:${e}: ${url}`)
}
// 判断数据是否为空(加载失败)
if (!data && canLoadCache) {
console.log(`🤖Post读取缓存: ${url}`)
console.log(`----------------------------------------`)
return json ? JSON.parse(localCache) : localCache
}
// 存储缓存
this.saveStringCache(cacheKey, json ? JSON.stringify(data) : data)
// 是否打印响应数据
if (logable) {
console.log(`🤖Post请求响应:${JSON.stringify(data)}`)
}
console.log(`----------------------------------------`)
return data
}
/**
* 获取手机定位信息
* @param {string} locale 地区
* @return 定位信息
*/
async getLocation(locale = "zh_cn") {
// 定位信息
let locationData = {
"latitude": undefined,
"longitude": undefined,
"locality": undefined,
"subLocality": undefined
}
// 缓存key
const cacheKey = "lsp-location-cache"
// 判断是否需要刷新
const lastCacheTime = this.getCacheModificationDate(cacheKey)
const timeInterval = Math.floor((this.getCurrentTimeStamp() - lastCacheTime) / 60)
// 缓存数据
const locationCache = this.loadStringCache(cacheKey)
if (timeInterval <= this.refreshInterval && locationCache != null && locationCache.length > 0) {
// 读取缓存数据
console.log(`🤖读取定位缓存数据:${locationCache}`)
locationData = JSON.parse(locationCache)
} else {
console.log(`📌开始定位`)
try {
const location = await Location.current()
const geocode = await Location.reverseGeocode(location.latitude, location.longitude, locale)
locationData.latitude = location.latitude
locationData.longitude = location.longitude
const geo = geocode[0]
// 市
if (locationData.locality == undefined) {
locationData.locality = geo.locality
}
// 区
if (locationData.subLocality == undefined) {
locationData.subLocality = geo.subLocality
}
// 街道
locationData.street = geo.thoroughfare
// 缓存数据
this.saveStringCache(cacheKey, JSON.stringify(locationData))
console.log(`🚀定位信息:latitude=${location.latitude},longitude=${location.longitude},locality=${locationData.locality},subLocality=${locationData.subLocality},street=${locationData.street}`)
} catch (e) {
console.error(`🚫定位出错了,${e.toString()}`)
// 读取缓存数据
const locationCache = this.loadStringCache(cacheKey)
console.log(`🤖读取定位缓存数据:${locationCache}`)
locationData = JSON.parse(locationCache)
}
}
console.log(`----------------------------------------`)
return locationData
}
/**
* 绘制图片阴影浮层
* @param {Image} img 图片
* @param {Color} shadowColor 阴影颜色
* @return {Image}
*/
async loadShadowColor2Image(img, shadowColor) {
let drawContext = new DrawContext()
drawContext.size = img.size
// 把图片画上去
drawContext.drawImageInRect(img, new Rect(0, 0, img.size['width'], img.size['height']))
// 填充蒙版颜色
drawContext.setFillColor(shadowColor)
// 填充
drawContext.fillRect(new Rect(0, 0, img.size['width'], img.size['height']))
return await drawContext.getImage()
}
/**
* 获取在线图片
* @param {string} url 图片链接
* @param {string} pointCacheKey 指定缓存key
* @param {bool} temporary 是否临时目录
* @param {bool} useCache 是否使用缓存
* @return {Image}
*/
async getImageByUrl(url, pointCacheKey = null, temporary = false, useCache = true) {
// 根据URL进行md5生成cacheKey
let cacheKey = pointCacheKey
let isPointCacheKey = true
if (cacheKey == undefined || cacheKey == null || cacheKey.length == 0) {
isPointCacheKey = false
cacheKey = this.md5(url)
}
// 缓存数据
if (useCache) {
const cacheImg = this.loadImgCache(cacheKey, temporary);
if (cacheImg != undefined && cacheImg != null) {
if (isPointCacheKey) {
// 判断是否需要刷新
const lastCacheTime = this.getCacheModificationDate(cacheKey, temporary);
const timeInterval = Math.floor((this.getCurrentTimeStamp() - lastCacheTime) / 60)
// 是否使用缓存
if (timeInterval <= this.refreshInterval) {
return cacheImg
}
} else {
return cacheImg
}
}
}
// 在线
try {
console.log(`🚀在线请求图片:${url}`)
const req = new Request(url)
const img = await req.loadImage()
// 存储到缓存
this.saveImgCache(cacheKey, img)
console.log(`----------------------------------------`)
return img
} catch (e) {
console.error(`图片加载失败:${e}`)
// 判断本地是否有缓存,有的话直接返回缓存
let cacheImg = this.loadImgCache(cacheKey)
if (cacheImg != undefined) {
console.error(`🚫图片加载失败,返回缓存图片`)
console.log(`----------------------------------------`)
return cacheImg
}
// 没有缓存+失败情况下,返回灰色背景
console.log(`📵返回默认图片,原链接:${url}`)
let ctx = new DrawContext()
ctx.size = new Size(80, 80)
ctx.setFillColor(Color.darkGray())
ctx.fillRect(new Rect(0, 0, 80, 80))
console.log(`----------------------------------------`)
return await ctx.getImage()
}
}
/**
* 获取缓存路径
* @param {是否是临时目录} temporary
*/
getCacheFilePath(cacheKey, temporary = false) {
let path = this.fmLocal.joinPath(temporary ? FileManager.local().temporaryDirectory() : FileManager.local().documentsDirectory(), cacheKey);
return path;
}
/**
* 保存字符串到本地
* @param {string} cacheKey 缓存key
* @param {string} content 缓存内容
*/
saveStringCache(cacheKey, content) {
const cacheFile = this.getCacheFilePath(cacheKey);
this.fmLocal.writeString(cacheFile, content)
}
/**
* 获取本地缓存字符串
* @param {string} cacheKey 缓存key
* @return {string} 本地字符串缓存
*/
loadStringCache(cacheKey) {
const cacheFile = this.getCacheFilePath(cacheKey);
const fileExists = this.fmLocal.fileExists(cacheFile)
let cacheString = ""
if (fileExists) {
cacheString = this.fmLocal.readString(cacheFile)
}
return cacheString
}
/**
* 保存图片到本地
* @param {string} cacheKey 缓存key
* @param {Image} img 缓存图片
* @param {boolean} temporary 是否是缓存目录
*/
saveImgCache(cacheKey, img, temporary = false) {
const cacheFile = this.getCacheFilePath(cacheKey, temporary);
this.fmLocal.writeImage(cacheFile, img)
}
/**
* 获取本地缓存图片
* @param {string} cacheKey 缓存key
* @return {Image} 本地图片缓存
* @param {boolean} temporary 是否是缓存目录
*/
loadImgCache(cacheKey, temporary) {
const cacheFile = this.getCacheFilePath(cacheKey, temporary);
const fileExists = this.fmLocal.fileExists(cacheFile);
let img = undefined;
if (fileExists) {
img = this.fmLocal.readImage(cacheFile);
}
return img
}
/**
* 获取缓存文件的上次修改时间
* @param {string} cacheKey 缓存key
* @param {boolean} temporary 是否是临时目录
* @return 返回上次缓存文件修改的时间戳(单位:秒)
*/
getCacheModificationDate(cacheKey, temporary = false) {
const cacheFile = this.getCacheFilePath(cacheKey, temporary);
const fileExists = this.fmLocal.fileExists(cacheFile)
if (fileExists) {
return Math.floor(this.fmLocal.modificationDate(cacheFile).getTime() / 1000)
} else {
return 0
}
}
/**
* 获取当前时间戳(单位:秒)
*/
getCurrentTimeStamp() {
return Math.floor(new Date().getTime() / 1000)
}
/**
* 删除本地缓存
*/
removeAllCache() {
const cacheFile = this.fmLocal.joinPath(FileManager.local().documentsDirectory(), '')
this.fmLocal.remove(cacheFile)
this.fmLocal.createDirectory(this.fmLocal.joinPath(FileManager.local().documentsDirectory(), '/'))
}
/**
* 删除本地缓存
* @param {string} cacheKey 缓存key
*/
removeCache(cacheKey) {
const cacheFile = this.getCacheFilePath(cacheKey);
if (this.fmLocal.fileExists(cacheFile)) {
this.fmLocal.remove(cacheFile)
}
}
/**
* 删除本地缓存集合
* @param {string} cacheKey 缓存key
*/
removeCaches(cacheKeyList) {
for (const cacheKey of cacheKeyList) {
removeCache(cacheKey)
}
}
/**
* 索引值轮播
* @param {string} cacheKey 缓存key
* @param {number} size 轮播大小
*/
carouselIndex(cacheKey, size) {
let index = -1
if (Keychain.contains(cacheKey)) {
let cacheString = Keychain.get(cacheKey)
index = parseInt(cacheString)
}
index = index + 1
index = index % size
Keychain.set(cacheKey, `${index}`)
return index
}
/**
* 保存key相关设置,缓存清除不会清理这个
* @param {string} cacheKey
* @param {string} cache
*/
keySave(cacheKey, cache) {
if (cache) {
Keychain.set(cacheKey, cache);
}
}
/**
* 获取key相关设置
* @param {string} cacheKey
*/
keyGet(cacheKey, defaultValue = '') {
if (Keychain.contains(cacheKey)) {
return Keychain.get(cacheKey);
} else {
return defaultValue;
}
}
/**
* 格式化时间
* @param {Date} date 日期
* @param {DateFormatter} formatter 格式化
* @param {string} locale 地区
*/
getDateStr(date, formatter = "yyyy年MM月d日 EEE", locale = "zh_cn") {
const df = new DateFormatter()
df.locale = locale
df.dateFormat = formatter
return df.string(date)
}
/**
* 获取组件尺寸宽度大小
* @param {string} size 组件尺寸【小号】、【中号】、【大号】
* @param {bool} isIphone12Mini 是否是12mini
*/
getWidgetWidthSize(size, isIphone12Mini) {
// 屏幕缩放比例
const screenScale = Device.screenScale()
// 组件宽度
let phoneWidgetSize = undefined
// 手机屏幕高度
const screenHeight = Device.screenSize().height * screenScale
if (screenHeight == 2436) {
// 2436尺寸的手机有【11 Pro, XS, X】 & 【12 mini】
if (isIphone12Mini) {
phoneWidgetSize = this.phoneSizes()[screenHeight].mini
} else {
phoneWidgetSize = this.phoneSizes()[screenHeight].x
}
} else {
phoneWidgetSize = this.phoneSizes()[screenHeight]
}
let width = phoneWidgetSize[size] / screenScale
if (size === '大号') {
width = phoneWidgetSize['中号'] / screenScale
}
return width
}
/**
* 获取组件尺寸高度大小
* @param {string} size 组件尺寸【小号】、【中号】、【大号】
* @param {bool} isIphone12Mini 是否是12mini
*/
getWidgetHeightSize(size, isIphone12Mini) {
// 屏幕缩放比例
const screenScale = Device.screenScale()
// 组件宽度
let phoneWidgetSize = undefined
// 手机屏幕高度
const screenHeight = Device.screenSize().height * screenScale
if (screenHeight == 2436) {
// 2436尺寸的手机有【11 Pro, XS, X】 & 【12 mini】
if (isIphone12Mini) {
phoneWidgetSize = this.phoneSizes()[screenHeight].mini
} else {
phoneWidgetSize = this.phoneSizes()[screenHeight].x
}
} else {
phoneWidgetSize = this.phoneSizes()[screenHeight]
}
let height = phoneWidgetSize['小号'] / screenScale
if (size === '大号') {
height = phoneWidgetSize['大号'] / screenScale
}
return height
}
/**
* 获取上次保存的背景图
* @return 背景图
*/
loadLastSavedBgImg() {
return this.loadImgCache(this.scriptName)
}
/**
* 画图
* @param {DrawContext} drawContext 画板
* @param {Image} image 图片
* @param {number} x 坐标x
* @param {number} y 坐标y
*/
drawImage(drawContext, image, x, y) {
drawContext.drawImageAtPoint(image, new Point(x, y))
}
/**
* 画文本
* @param {DrawContext} drawContext 画板
* @param {string} text 文本
* @param {Font} fontSize 字体
* @param {number} x 坐标x
* @param {number} y 坐标y
* @param {Color} color 颜色
*/
drawText(drawContext, text, fontSize, x, y, color = Color.white()) {
drawContext.setFont(Font.boldSystemFont(fontSize))
drawContext.setTextColor(color)
drawContext.drawText(new String(text).toString(), new Point(x, y))
}
/**
* 画线
* @param {DrawContext} drawContext 画板
* @param {number} x1 坐标
* @param {number} y1 坐标
* @param {number} x2 坐标
* @param {number} y2 坐标
* @param {*} width 线宽
* @param {*} color 颜色
*/
drawLine(drawContext, x1, y1, x2, y2, width = 2, color = Color.white()) {
const path = new Path()
path.move(new Point(x1, y1))
path.addLine(new Point(x2, y2))
drawContext.addPath(path)
drawContext.setStrokeColor(color)
drawContext.setLineWidth(width)
drawContext.strokePath()
}
/**
* 获取SFSymbol
* @param {string}} name 名
* @param {number} size 尺寸
*/
getSFSymbol(name, size) {
const sf = SFSymbol.named(name)
if (sf != null) {
if (size != undefined && size != null) {
sf.applyFont(Font.systemFont(size))
}
return sf.image
} else {
return undefined
}
}
/**
* 获取widget输入
* @param {string} defaultInput 默认输入
*/
getWidgetInput(defaultInput = "") {
// 获取外部输入的参数
let widgetInputRAW = args.widgetParameter
try {
widgetInputRAW.toString()
} catch (e) {
widgetInputRAW = defaultInput
}
return widgetInputRAW.toString()
}
/**
* 获取数组的随机索引
* @param {Array} arr 数组
*/
getRandowArrValue(arr) {
// 索引
const key = parseInt(Math.random() * arr.length)
let item = arr[key]
if (item == undefined) {
item = arr[0]
}
return item
}
/**
* md5 加密字符串
* @param {string} str 要加密成md5的数据
*/
md5(str) {
function d(n, t) {
var r = (65535 & n) + (65535 & t);
return (((n >> 16) + (t >> 16) + (r >> 16)) << 16) | (65535 & r);
}
function f(n, t, r, e, o, u) {
return d(((c = d(d(t, n), d(e, u))) << (f = o)) | (c >>> (32 - f)), r);
var c, f;
}
function l(n, t, r, e, o, u, c) {
return f((t & r) | (~t & e), n, t, o, u, c);
}
function v(n, t, r, e, o, u, c) {
return f((t & e) | (r & ~e), n, t, o, u, c);
}
function g(n, t, r, e, o, u, c) {
return f(t ^ r ^ e, n, t, o, u, c);
}
function m(n, t, r, e, o, u, c) {
return f(r ^ (t | ~e), n, t, o, u, c);
}
function i(n, t) {
var r, e, o, u;
(n[t >> 5] |= 128 << t % 32), (n[14 + (((t + 64) >>> 9) << 4)] = t);
for (
var c = 1732584193,
f = -271733879,
i = -1732584194,
a = 271733878,
h = 0;
h < n.length;
h += 16
)
(c = l((r = c), (e = f), (o = i), (u = a), n[h], 7, -680876936)),
(a = l(a, c, f, i, n[h + 1], 12, -389564586)),
(i = l(i, a, c, f, n[h + 2], 17, 606105819)),
(f = l(f, i, a, c, n[h + 3], 22, -1044525330)),
(c = l(c, f, i, a, n[h + 4], 7, -176418897)),
(a = l(a, c, f, i, n[h + 5], 12, 1200080426)),