forked from dingdangnao/Scriptable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLockscreenWidget.js
1769 lines (1623 loc) · 62.9 KB
/
LockscreenWidget.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: stream;
// Author: 叮噹鬧 github.com/dingdangnao //
// 天气部份 mod from https://github.com/Enjoyee/Scriptable
// calendar.js from https://github.com/jjonline/calendar.js
// const { calendar } = importModule('calendar.js');
const calendar = calendarFunc();
const fmLocal = FileManager.local();
const _config = {
apiKey: "", // 彩云天气 key https://caiyunapp.com/api/weather#api
emojiUrl:"https://raw.githubusercontent.com/dingdangnao/Scriptable/main/AMEmoji/", //年份emoji的链接地址,要以 / 结尾
refreshInterval: 10, // 刷新时间--估算(单位:分钟)
imgRefreshInterval: 120, // 刷新时间--估算(单位:分钟)
// 位置,可以不进行定位,或者定位为出错的时候使用
location: {
latitude: undefined,
longitude: undefined,
locality: undefined,
subLocality: undefined,
},
locale: "zh-cn", // 地区
weatherDesc: {
CLEAR_DAY: "晴",
CLEAR_NIGHT: "晴",
PARTLY_CLOUDY_DAY: "多云",
PARTLY_CLOUDY_NIGHT: "多云",
CLOUDY: "阴",
CLOUDY_NIGHT: "阴",
LIGHT_HAZE: "轻度雾霾",
LIGHT_HAZE_NIGHT: "轻度雾霾",
MODERATE_HAZE: "中度雾霾",
MODERATE_HAZE_NIGHT: "中度雾霾",
HEAVY_HAZE: "重度雾霾",
HEAVY_HAZE_NIGHT: "重度雾霾",
LIGHT_RAIN: "小雨",
MODERATE_RAIN: "中雨",
HEAVY_RAIN: "大雨",
STORM_RAIN: "暴雨",
FOG: "雾",
LIGHT_SNOW: "小雪",
MODERATE_SNOW: "中雪",
HEAVY_SNOW: "大雪",
STORM_SNOW: "暴雪",
DUST: "浮尘",
SAND: "沙尘",
WIND: "大风",
},
weatherSFIcos: {
CLEAR_DAY: "sun.max.fill", // 晴(白天) CLEAR_DAY
CLEAR_NIGHT: "moon.stars.fill", // 晴(夜间) CLEAR_NIGHT
PARTLY_CLOUDY_DAY: "cloud.sun.fill", // 多云(白天) PARTLY_CLOUDY_DAY
PARTLY_CLOUDY_NIGHT: "cloud.moon.fill", // 多云(夜间) PARTLY_CLOUDY_NIGHT
CLOUDY: "cloud.fill", // 阴(白天) CLOUDY
CLOUDY_NIGHT: "cloud.fill", // 阴(夜间) CLOUDY
LIGHT_HAZE: "sun.haze.fill", // 轻度雾霾 LIGHT_HAZE
LIGHT_HAZE_NIGHT: "sun.haze.fill", // 轻度雾霾 LIGHT_HAZE
MODERATE_HAZE: "sun.haze.fill", // 中度雾霾 MODERATE_HAZE
MODERATE_HAZE_NIGHT: "sun.haze.fill", // 中度雾霾 MODERATE_HAZE
HEAVY_HAZE: "sun.haze.fill", // 重度雾霾 HEAVY_HAZE
HEAVY_HAZE_NIGHT: "sun.haze.fill", // 重度雾霾 HEAVY_HAZE
LIGHT_RAIN: "cloud.drizzle.fill", // 小雨 LIGHT_RAIN
MODERATE_RAIN: "cloud.drizzle.fill", // 中雨 MODERATE_RAIN
HEAVY_RAIN: "cloud.rain.fill", // 大雨 HEAVY_RAIN
STORM_RAIN: "cloud.heavyrain.fill", // 暴雨 STORM_RAIN
FOG: "cloud.fog.fill", // 雾 FOG
LIGHT_SNOW: "cloud.snow.fill", // 小雪 LIGHT_SNOW
MODERATE_SNOW: "cloud.snow.fill", // 中雪 MODERATE_SNOW
HEAVY_SNOW: "cloud.snow.fill", // 大雪 HEAVY_SNOW
STORM_SNOW: "cloud.snow.fill", // 暴雪 STORM_SNOW
DUST: "sun.dust.fill", // 浮尘 DUST
SAND: "smoke.fill", // 沙尘 SAND
WIND: "wind", // 大风 WIND
},
};
let widget = await renderLockscreenWidget()
Script.setWidget(widget);
Script.complete();
async function renderLockscreenWidget() {
let widget = new ListWidget();
widget.refreshAfterDate = new Date(Date.now() + 60 * 5 * 1000); // 设置刷新时间为30秒后
widget.useDefaultPadding();
let weatherInfo = await getWeather();
console.log('weatherInfo', weatherInfo)
if (!weatherInfo || !weatherInfo.temperature) {
for (let retries = 0; retries < 5; retries++) {
weatherInfo = await getWeather(true);
if (weatherInfo && weatherInfo.temperature) {
break; // 如果成功获取到数据,立即跳出循环
} else {
console.log(weatherInfo)
}
}
}
const dateInfo = calendar.solar2lunar();
//////////////////////////
// 农历
const lunarCalendarStack = widget.addStack();
lunarCalendarStack.centerAlignContent();
let lunarInfoData = `${dateInfo.gzYear}年 ${dateInfo.IMonthCn}${dateInfo.IDayCn}`;
if (dateInfo.lunarFestival && !dateInfo.festival) {
lunarInfoData = `${dateInfo.gzYear}年 ${dateInfo.IMonthCn}${dateInfo.IDayCn} • ${dateInfo.lunarFestival}`;
if (dateInfo.lunarFestival.length > 3) {
lunarInfoData = `${dateInfo.IMonthCn}${dateInfo.IDayCn} • ${dateInfo.lunarFestival}`;
}
}
if (dateInfo.festival && !dateInfo.lunarFestival) {
lunarInfoData = `${dateInfo.gzYear}年 ${dateInfo.IMonthCn}${dateInfo.IDayCn} • ${dateInfo.festival}`;
if (dateInfo.festival.length > 3) {
lunarInfoData = `${dateInfo.IMonthCn}${dateInfo.IDayCn} • ${dateInfo.festival}`;
}
}
if (dateInfo.festival && dateInfo.lunarFestival) {
lunarInfoData = `${dateInfo.IMonthCn}${dateInfo.IDayCn} • ${dateInfo.lunarFestival} • ${dateInfo.festival}`;
}
if (!dateInfo.festival && !dateInfo.lunarFestival) {
let yearAnimalImageContent = await getImageByUrl(
animalEmoji(dateInfo.Animal)
);
yearAnimalImage = lunarCalendarStack.addImage(yearAnimalImageContent);
yearAnimalImage.imageSize = new Size(17, 17);
yearAnimalImage.centerAlignImage();
lunarCalendarStack.addSpacer(6)
// let yearAnimalText = lunarCalendarStack.addText(` ${dateInfo.Animal} ⫶ `);
// let yearAnimalText = lunarCalendarStack.addText(` `);
// yearAnimalText.font = Font.boldSystemFont(12);
}
let lunarInfoTextWidget = lunarCalendarStack.addText(lunarInfoData);
lunarInfoTextWidget.font = Font.boldSystemFont(12);
if (lunarInfoData.length >= 10) {
lunarInfoTextWidget.font = Font.boldSystemFont(11);
}
lunarInfoTextWidget.lineLimit = 1;
lunarCalendarStack.addSpacer();
// 农历 END
//////////////////////////
widget.addSpacer(7);
//////////////////////////
// 天气
if (weatherInfo && weatherInfo.temperature) {
const weatherStack = widget.addStack();
// weatherStack.layoutHorizontally()
weatherStack.centerAlignContent();
// weatherStack.addSpacer()
// 天气图标
const weatherIcon = getSFSymbol(
_config.weatherSFIcos[weatherInfo.weatherIco]
);
let weatherIconWidget = weatherStack.addImage(weatherIcon);
weatherIconWidget.imageSize = new Size(18, 18);
weatherIconWidget.centerAlignImage();
// 天气描述
weatherStack.addSpacer(6);
let weatherDescValue = _config.weatherDesc[weatherInfo.weatherIco];
let weatherDescWidget = weatherStack.addText(`${weatherDescValue}`);
weatherDescWidget.font = Font.blackSystemFont(12);
// 天气温度
weatherStack.addSpacer(6);
let weatherTemperatureValue = weatherInfo.temperature;
weatherTemperatureValue = `${weatherTemperatureValue}℃`;
let weatherTemperatureWidget = weatherStack.addText(
`${weatherTemperatureValue}`
);
weatherTemperatureWidget.font = Font.boldRoundedSystemFont(12);
// 温度范围
if (weatherDescValue.length < 3) {
weatherStack.addSpacer(6);
let thermometerIcon = "thermometer.medium";
if (weatherInfo.maxTemperature > 30) {
thermometerIcon = "thermometer.high";
} else if (weatherInfo.maxTemperature > 15) {
thermometerIcon = "thermometer.medium";
} else {
thermometerIcon = "thermometer.low";
}
const tRangeIcon = getSFSymbol(thermometerIcon);
let tRangeIconWidget = weatherStack.addImage(tRangeIcon);
tRangeIconWidget.imageSize = new Size(11, 11);
tRangeIconWidget.tintColor = new Color("ffffff", 0.8);
weatherStack.addSpacer(2);
let aqiTextWidget = weatherStack.addText(
`${weatherInfo.minTemperature}~${weatherInfo.maxTemperature}`
);
aqiTextWidget.font = Font.semiboldRoundedSystemFont(10);
aqiTextWidget.textColor = new Color("ffffff", 0.8);
}
// 天气 END
//////////////////////////
weatherStack.addSpacer();
widget.addSpacer(8);
//////////////////////////
// AQI 日出 日落
const otherWeatherStack = widget.addStack();
otherWeatherStack.centerAlignContent();
// AQI
let aqiIcon = "aqi.medium";
if (weatherInfo.aqiValue <= 150) {
aqiIcon = "aqi.low";
} else if (weatherInfo.aqiValue < 200) {
aqiIcon = "aqi.medium";
} else {
aqiIcon = "aqi.high";
}
aqiImg = SFSymbol.named(aqiIcon).image;
const aqiImageElement = otherWeatherStack.addImage(aqiImg);
aqiImageElement.imageSize = new Size(12, 12);
let aqiTintColor = new Color("ffffff", 0.9);
aqiImageElement.tintColor = aqiTintColor;
//
otherWeatherStack.addSpacer(4);
const aqiTextElement = otherWeatherStack.addText(`${weatherInfo.aqiValue}`);
aqiTextElement.lineLimit = 1;
aqiTextElement.font = Font.boldRoundedSystemFont(10);
aqiTextElement.textColor = new Color("ffffff", 0.8);
// 日出ico
otherWeatherStack.addSpacer(8);
sunriseImg = SFSymbol.named("sunrise.fill").image;
const sunriseImageElement = otherWeatherStack.addImage(sunriseImg)
sunriseImageElement.imageSize = new Size(14, 14);
let sunriseTintColor = new Color("ffffff", 0.8);
sunriseImageElement.tintColor = sunriseTintColor;
//
otherWeatherStack.addSpacer(4);
const sunriseTextElement = otherWeatherStack.addText(`${weatherInfo.sunrise}`);
sunriseTextElement.lineLimit = 1;
sunriseTextElement.font = Font.boldRoundedSystemFont(10);
sunriseTextElement.textColor = new Color("ffffff", 0.8);
// 日落ico
otherWeatherStack.addSpacer(6);
sunsetImg = SFSymbol.named("sunset.fill").image;
const sunsetImageElement = otherWeatherStack.addImage(sunsetImg)
sunsetImageElement.imageSize = new Size(14, 14);
let sunsetTintColor = new Color("ffffff", 0.8);
sunsetImageElement.tintColor = sunsetTintColor;
//
otherWeatherStack.addSpacer(4);
const sunsetTextElement = otherWeatherStack.addText(`${weatherInfo.sunset}`);
sunsetTextElement.lineLimit = 1;
sunsetTextElement.font = Font.boldRoundedSystemFont(10);
sunsetTextElement.textColor = new Color("ffffff", 0.8);
otherWeatherStack.addSpacer();
} else {
const errStack = widget.addStack()
errStack.layoutVertically()
let errline1 = errStack.addText("🤔 获取天气信息失败")
errline1.font = Font.systemFont(12);
errStack.addSpacer(6)
let errline2 = errStack.addText("叮噹鬧")
errline2.font = Font.blackSystemFont(12);
}
widget.url = "weather://";
return widget;
}
/***************************************************************************
***************************************************************************
***************************************************************************
***************************************************************************
***************************************************************************
******* ___ _____ __________ ___ _ ________ _____ ____ ********
******* / _ \/ _/ |/ / ___/ _ \/ _ | / |/ / ___/ |/ / _ |/ __ \ ********
******* / // // // / (_ / // / __ |/ / (_ / / __ / /_/ / ********
******* /____/___/_/|_/\___/____/_/ |_/_/|_/\___/_/|_/_/ |_\____/ ********
***************************************************************************
***************************************************************************
***************************************************************************
***************************************************************************
**************************************************************************/
/**
* 获取彩云天气信息
*/
async function getWeather(forceRefresh = false) {
// 获取位置
let location = _config.location;
location = await getLocation(_config.locale);
// 小时
const hour = new Date().getHours();
// 彩云天气域名
const url = `https://api.caiyunapp.com/v2.6/${_config.apiKey}/${location.longitude},${location.latitude}/weather?alert=true`;
const weatherJsonData = await httpGet(url, true, null, "caiyunData", false, forceRefresh);
// console.log(weatherJsonData);
// 天气数据
let weatherInfo = {};
if (weatherJsonData.status == "ok") {
// log("天气数据请求成功");
// 天气突发预警
let alertWeather = weatherJsonData.result.alert.content;
if (alertWeather.length > 0) {
const alertWeatherTitle = alertWeather[0].title;
// log(`突发的天气预警==>${alertWeatherTitle}`);
weatherInfo.alertWeatherTitle = alertWeatherTitle;
}
if (weatherJsonData.status != 'ok') {
console.log(weatherJsonData);
}
// 温度范围
const temperatureData = weatherJsonData.result.daily.temperature[0];
// 最低温度
const minTemperature = temperatureData.min;
// 最高温度
const maxTemperature = temperatureData.max;
weatherInfo.minTemperature =
Math.round(minTemperature);
weatherInfo.maxTemperature = Math.round(maxTemperature);
// 体感温度
const bodyFeelingTemperature =
weatherJsonData.result.realtime.apparent_temperature;
weatherInfo.bodyFeelingTemperature = Math.floor(bodyFeelingTemperature);
// 显示温度
const temperature = weatherJsonData.result.realtime.temperature;
weatherInfo.temperature = Math.floor(temperature);
// 天气状况 weatherIcos[weatherIco]
let weather = weatherJsonData.result.realtime.skycon;
let night = hour - 12 >= 7;
let nightCloudy = night && weather == "CLOUDY";
let nightLightHaze = night && weather == "LIGHT_HAZE";
let nightModerateHaze = night && weather == "MODERATE_HAZE";
let nightHeavyHaze = night && weather == "HEAVY_HAZE";
if (nightCloudy) {
weather = "CLOUDY_NIGHT";
}
if (nightLightHaze) {
weather = "LIGHT_HAZE_NIGHT";
}
if (nightModerateHaze) {
weather = "MODERATE_HAZE_NIGHT";
}
if (nightHeavyHaze) {
weather = "HEAVY_HAZE_NIGHT";
}
weatherInfo.weatherIco = weather;
// log(`天气:${weather}`);
// 天气描述
const weatherDesc = weatherJsonData.result.forecast_keypoint;
weatherInfo.weatherDesc = weatherDesc.replace("。还在加班么?", ",");
// log("天气预告==>" + weatherDesc)
// 相对湿度
const humidity =
Math.floor(weatherJsonData.result.realtime.humidity * 100) + "%";
weatherInfo.humidity = humidity;
// 舒适指数
const comfort = weatherJsonData.result.realtime.life_index.comfort.desc;
weatherInfo.comfort = comfort;
// log(`舒适指数:${comfort}`)
// 紫外线指数
const ultraviolet =
weatherJsonData.result.realtime.life_index.ultraviolet.desc;
weatherInfo.ultraviolet = ultraviolet;
// 空气质量
const aqi = weatherJsonData.result.realtime.air_quality.aqi.chn;
const aqiInfo = airQuality(aqi);
weatherInfo.aqiInfo = aqiInfo;
weatherInfo.aqiValue = aqi;
// 日出日落
const astro = weatherJsonData.result.daily.astro[0];
// 日出
const sunrise = astro.sunrise.time;
// 日落
const sunset = astro.sunset.time;
weatherInfo.sunrise = sunrise.toString();
weatherInfo.sunset = sunset.toString();
// 小时预告
let hourlyArr = [];
const hourlyData = weatherJsonData.result.hourly;
const temperatureArr = hourlyData.temperature;
const temperatureSkyconArr = hourlyData.skycon;
for (var i = 0; i < temperatureArr.length; i++) {
let hourlyObj = {};
hourlyObj.datetime = temperatureArr[i].datetime;
hourlyObj.temperature = Math.round(temperatureArr[i].value);
let weather = temperatureSkyconArr[i].value;
if (nightCloudy) {
weather = "CLOUDY_NIGHT";
}
hourlyObj.skycon = `${weather}`;
hourlyArr.push(hourlyObj);
}
// weatherInfo.hourly = hourlyArr
console.log("=== weatherInfo ===");
console.log(weatherInfo);
} else {
log(`请求彩云天气出错:${weatherJsonData}`);
console.log(weatherJsonData)
// getWeather()
}
return weatherInfo;
}
/**
* 获取手机定位信息
* @param {string} locale 地区
* @return 定位信息
*/
async function getLocation(locale = "zh_cn") {
console.log("");
console.log(`----------------------------------------`);
console.log(`开始定位`);
// 定位信息
let locationData = {
latitude: undefined,
longitude: undefined,
locality: undefined,
subLocality: undefined,
};
// 缓存key
const cacheKey = "lsp-location-cache";
// 判断是否需要刷新
const lastCacheTime = getCacheModificationDate(cacheKey);
const timeInterval = Math.floor((getCurrentTimeStamp() - lastCacheTime) / 60);
// 缓存数据
const locationCache = loadStringCache(cacheKey);
console.log(
`定位缓存判断,上次缓存时间=${timeInterval}分钟前,缓存过期时间=${_config.refreshInterval}分钟,cache=${locationCache.length}`
);
if (
timeInterval <= _config.refreshInterval &&
locationCache != null &&
locationCache.length > 0
) {
// 读取缓存数据
console.log(`读取定位缓存数据:${locationCache}`);
locationData = JSON.parse(locationCache);
} else {
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;
// 缓存数据
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.log(`定位出错了,${e.toString()}`);
// 读取缓存数据
const locationCache = loadStringCache(cacheKey);
console.log(`读取定位缓存数据:${locationCache}`);
locationData = JSON.parse(locationCache);
}
}
console.log(`----------------------------------------`);
return locationData;
}
/**
* 保存图片到本地
* @param {string} cacheKey 缓存key
* @param {Image} img 缓存图片
*/
function saveImgCache(cacheKey, img) {
const cacheFile = fmLocal.joinPath(
FileManager.local().documentsDirectory(),
cacheKey
);
fmLocal.writeImage(cacheFile, img);
}
/**
* 获取本地缓存图片
* @param {string} cacheKey 缓存key
* @return {Image} 本地图片缓存
*/
function loadImgCache(cacheKey) {
const cacheFile = fmLocal.joinPath(
FileManager.local().documentsDirectory(),
cacheKey
);
const fileExists = fmLocal.fileExists(cacheFile);
let img = undefined;
if (fileExists) {
img = fmLocal.readImage(cacheFile);
}
return img;
}
/**
* 保存字符串到本地
* @param {string} cacheKey 缓存key
* @param {string} content 缓存内容
*/
function saveStringCache(cacheKey, content) {
const cacheFile = fmLocal.joinPath(
FileManager.local().documentsDirectory(),
cacheKey
);
fmLocal.writeString(cacheFile, content);
}
/**
* 获取本地缓存字符串
* @param {string} cacheKey 缓存key
* @return {string} 本地字符串缓存
*/
function loadStringCache(cacheKey) {
const cacheFile = fmLocal.joinPath(
FileManager.local().documentsDirectory(),
cacheKey
);
const fileExists = fmLocal.fileExists(cacheFile);
let cacheString = "";
if (fileExists) {
cacheString = fmLocal.readString(cacheFile);
}
return cacheString;
}
/**
* 获取缓存文件的上次修改时间
* @param {string} cacheKey 缓存key
* @return 返回上次缓存文件修改的时间戳(单位:秒)
*/
function getCacheModificationDate(cacheKey) {
const cacheFile = fmLocal.joinPath(
FileManager.local().documentsDirectory(),
cacheKey
);
const fileExists = fmLocal.fileExists(cacheFile);
if (fileExists) {
return fmLocal.modificationDate(cacheFile).getTime() / 1000;
} else {
return 0;
}
}
/**
* 获取当前时间戳(单位:秒)
*/
function getCurrentTimeStamp() {
return new Date().getTime() / 1000;
}
/**
* Http Get 请求接口
* @param {string} url 请求的url
* @param {bool} json 返回数据是否为json,默认true
* @param {Obj} headers 请求头
* @param {string} pointCacheKey 指定缓存key
* @param {bool} logable 是否打印数据,默认false
* @return {string | json | null}
*/
async function httpGet(
url,
json = true,
headers,
pointCacheKey,
logable = false,
forceRefresh = false
) {
console.log("");
console.log(`----------------------------------------`);
// 根据URL进行md5生成cacheKey
let cacheKey = pointCacheKey;
if (cacheKey == undefined || cacheKey == null || cacheKey.length == 0) {
cacheKey = md5(url);
}
// 读取本地缓存
const localCache = loadStringCache(cacheKey);
// 判断是否需要刷新
const lastCacheTime = getCacheModificationDate(cacheKey);
const timeInterval = Math.floor((getCurrentTimeStamp() - lastCacheTime) / 60);
// 过时且有本地缓存则直接返回本地缓存数据
console.log(
`httpGet缓存判断,上次缓存时间=${timeInterval}分钟前,缓存过期时间=${_config.refreshInterval}分钟,cache=${localCache.length}`
);
if (
timeInterval <= _config.refreshInterval &&
localCache != null &&
localCache.length > 0
&& !forceRefresh
) {
console.log(`httpGet读取缓存数据:==> ${url}`);
// 是否打印响应数据
if (logable) {
console.log(``);
console.log(`httpGet请求响应数据:${localCache}`);
console.log(``);
}
console.log(`----------------------------------------`);
return json ? JSON.parse(localCache) : localCache;
}
let data = null;
try {
console.log(`httpGet在线请求数据:==> ${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(`httpGet请求失败:${e}:==> ${url}`);
}
// 判断数据是否为空(加载失败)
if (!data && localCache != null && localCache.length > 0) {
console.log(`空数据`);
console.log(`httpGet读取缓存数据:==> ${url}`);
console.log(``);
console.log(`----------------------------------------`);
return json ? JSON.parse(localCache) : localCache;
}
// 存储缓存
saveStringCache(cacheKey, json ? JSON.stringify(data) : data);
// 是否打印响应数据
if (logable) {
console.log(``);
console.log(`httpGet请求响应数据:${JSON.stringify(data)}`);
console.log(``);
}
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 function httpPost(url, parameterKV, json = true, headers, pointCacheKey, logable = true) {
// 根据URL进行md5生成cacheKey
let cacheKey = pointCacheKey
if (cacheKey == undefined || cacheKey == null || cacheKey.length == 0) {
cacheKey = md5(url)
}
// 读取本地缓存
const localCache = loadStringCache(cacheKey)
// 判断是否需要刷新
const lastCacheTime = getCacheModificationDate(cacheKey)
const timeInterval = Math.floor((getCurrentTimeStamp() - lastCacheTime) / 60)
const canLoadCache = localCache != null && localCache.length > 0;
// console.log(`⏰已缓存:${timeInterval}min, 缓存时间:${getDateStr(new Date(lastCacheTime * 1000), 'HH:mm')}, 刷新:${refreshInterval}min`);
// 过时且有本地缓存则直接返回本地缓存数据
if (timeInterval <= _config.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
}
// 存储缓存
saveStringCache(cacheKey, json ? JSON.stringify(data) : data)
// 是否打印响应数据
if (logable) {
console.log(`🤖Post请求响应:${JSON.stringify(data)}`)
}
console.log(`----------------------------------------`)
return data
}
async function getImageByUrl(url, pointCacheKey = md5(url), useCache = true) {
console.log("");
console.log(`----------------------------------------`);
// 根据URL进行md5生成cacheKey
let cacheKey = pointCacheKey;
let isPointCacheKey = true;
if (cacheKey == undefined || cacheKey == null || cacheKey.length == 0) {
isPointCacheKey = false;
cacheKey = md5(url);
}
// 缓存数据
if (useCache) {
const cacheImg = loadImgCache(cacheKey);
if (cacheImg != undefined && cacheImg != null) {
console.log(`图片是否指定了缓存key:${isPointCacheKey}`);
if (isPointCacheKey) {
// 判断是否需要刷新
const lastCacheTime = getCacheModificationDate(cacheKey);
const timeInterval = Math.floor(
(getCurrentTimeStamp() - lastCacheTime) / 60
);
console.log(
`图片缓存判断,上次缓存时间=${timeInterval}分钟前,缓存过期时间=${_config.imgRefreshInterval}分钟`
);
// 是否使用缓存
if (timeInterval <= _config.imgRefreshInterval) {
console.log(`使用缓存图片:${url}`);
console.log(`----------------------------------------`);
return cacheImg;
}
} else {
console.log(`使用缓存图片:${url}`);
console.log(`----------------------------------------`);
return cacheImg;
}
}
}
// 在线
try {
console.log(`在线请求图片:${url}`);
console.log(`----------------------------------------`);
const req = new Request(url);
const img = await req.loadImage();
// 存储到缓存
saveImgCache(cacheKey, img);
return img;
} catch (e) {
console.error(`图片加载失败:${e}`);
// 判断本地是否有缓存,有的话直接返回缓存
let cacheImg = loadImgCache(cacheKey);
if (cacheImg != undefined) {
console.log(`使用缓存图片:${url}`);
console.log(`----------------------------------------`);
return cacheImg;
}
// 没有缓存+失败情况下,返回灰色背景
console.log(`返回默认图片:${url}`);
console.log(`----------------------------------------`);
let ctx = new DrawContext();
ctx.size = new Size(80, 80);
ctx.setFillColor(Color.darkGray());
ctx.fillRect(new Rect(0, 0, 80, 80));
return await ctx.getImage();
}
}
function airQuality(levelNum) {
// 0-50 优,51-100 良,101-150 轻度污染,151-200 中度污染
// 201-300 重度污染,>300 严重污染
if (levelNum >= 0 && levelNum <= 50) {
return "优秀";
} else if (levelNum >= 51 && levelNum <= 100) {
return "良好";
} else if (levelNum >= 101 && levelNum <= 150) {
return "轻度";
} else if (levelNum >= 151 && levelNum <= 200) {
return "中度";
} else if (levelNum >= 201 && levelNum <= 300) {
return "重度";
} else {
return "严重";
}
}
function 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)),
(i = l(i, a, c, f, n[h + 6], 17, -1473231341)),
(f = l(f, i, a, c, n[h + 7], 22, -45705983)),
(c = l(c, f, i, a, n[h + 8], 7, 1770035416)),
(a = l(a, c, f, i, n[h + 9], 12, -1958414417)),
(i = l(i, a, c, f, n[h + 10], 17, -42063)),
(f = l(f, i, a, c, n[h + 11], 22, -1990404162)),
(c = l(c, f, i, a, n[h + 12], 7, 1804603682)),
(a = l(a, c, f, i, n[h + 13], 12, -40341101)),
(i = l(i, a, c, f, n[h + 14], 17, -1502002290)),
(c = v(
c,
(f = l(f, i, a, c, n[h + 15], 22, 1236535329)),
i,
a,
n[h + 1],
5,
-165796510
)),
(a = v(a, c, f, i, n[h + 6], 9, -1069501632)),
(i = v(i, a, c, f, n[h + 11], 14, 643717713)),
(f = v(f, i, a, c, n[h], 20, -373897302)),
(c = v(c, f, i, a, n[h + 5], 5, -701558691)),
(a = v(a, c, f, i, n[h + 10], 9, 38016083)),
(i = v(i, a, c, f, n[h + 15], 14, -660478335)),
(f = v(f, i, a, c, n[h + 4], 20, -405537848)),
(c = v(c, f, i, a, n[h + 9], 5, 568446438)),
(a = v(a, c, f, i, n[h + 14], 9, -1019803690)),
(i = v(i, a, c, f, n[h + 3], 14, -187363961)),
(f = v(f, i, a, c, n[h + 8], 20, 1163531501)),
(c = v(c, f, i, a, n[h + 13], 5, -1444681467)),
(a = v(a, c, f, i, n[h + 2], 9, -51403784)),
(i = v(i, a, c, f, n[h + 7], 14, 1735328473)),
(c = g(
c,
(f = v(f, i, a, c, n[h + 12], 20, -1926607734)),
i,
a,
n[h + 5],
4,
-378558
)),
(a = g(a, c, f, i, n[h + 8], 11, -2022574463)),
(i = g(i, a, c, f, n[h + 11], 16, 1839030562)),
(f = g(f, i, a, c, n[h + 14], 23, -35309556)),
(c = g(c, f, i, a, n[h + 1], 4, -1530992060)),
(a = g(a, c, f, i, n[h + 4], 11, 1272893353)),
(i = g(i, a, c, f, n[h + 7], 16, -155497632)),
(f = g(f, i, a, c, n[h + 10], 23, -1094730640)),
(c = g(c, f, i, a, n[h + 13], 4, 681279174)),
(a = g(a, c, f, i, n[h], 11, -358537222)),
(i = g(i, a, c, f, n[h + 3], 16, -722521979)),
(f = g(f, i, a, c, n[h + 6], 23, 76029189)),
(c = g(c, f, i, a, n[h + 9], 4, -640364487)),
(a = g(a, c, f, i, n[h + 12], 11, -421815835)),
(i = g(i, a, c, f, n[h + 15], 16, 530742520)),
(c = m(
c,
(f = g(f, i, a, c, n[h + 2], 23, -995338651)),
i,
a,
n[h],
6,
-198630844
)),
(a = m(a, c, f, i, n[h + 7], 10, 1126891415)),
(i = m(i, a, c, f, n[h + 14], 15, -1416354905)),
(f = m(f, i, a, c, n[h + 5], 21, -57434055)),
(c = m(c, f, i, a, n[h + 12], 6, 1700485571)),
(a = m(a, c, f, i, n[h + 3], 10, -1894986606)),
(i = m(i, a, c, f, n[h + 10], 15, -1051523)),
(f = m(f, i, a, c, n[h + 1], 21, -2054922799)),
(c = m(c, f, i, a, n[h + 8], 6, 1873313359)),
(a = m(a, c, f, i, n[h + 15], 10, -30611744)),
(i = m(i, a, c, f, n[h + 6], 15, -1560198380)),
(f = m(f, i, a, c, n[h + 13], 21, 1309151649)),
(c = m(c, f, i, a, n[h + 4], 6, -145523070)),
(a = m(a, c, f, i, n[h + 11], 10, -1120210379)),
(i = m(i, a, c, f, n[h + 2], 15, 718787259)),
(f = m(f, i, a, c, n[h + 9], 21, -343485551)),
(c = d(c, r)),
(f = d(f, e)),
(i = d(i, o)),
(a = d(a, u));
return [c, f, i, a];
}
function a(n) {
for (var t = "", r = 32 * n.length, e = 0; e < r; e += 8)
t += String.fromCharCode((n[e >> 5] >>> e % 32) & 255);
return t;
}
function h(n) {
var t = [];
for (t[(n.length >> 2) - 1] = void 0, e = 0; e < t.length; e += 1) t[e] = 0;
for (var r = 8 * n.length, e = 0; e < r; e += 8)
t[e >> 5] |= (255 & n.charCodeAt(e / 8)) << e % 32;
return t;
}
function e(n) {
for (var t, r = "0123456789abcdef", e = "", o = 0; o < n.length; o += 1)
(t = n.charCodeAt(o)), (e += r.charAt((t >>> 4) & 15) + r.charAt(15 & t));
return e;
}
function r(n) {
return unescape(encodeURIComponent(n));
}
function o(n) {
return a(i(h((t = r(n))), 8 * t.length));
var t;
}