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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
| package main
import (
_ "embed"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"syscall"
"text/template"
"time"
"unsafe"
"github.com/getlantern/systray"
"golang.org/x/sys/windows/registry"
)
//go:embed assets/icon.ico
var icon []byte
const (
appName = "BingWallpaperStoryV2"
wallpaperDir = "wallpapers"
configFile = "config.json"
storyFile = "stories.json"
logFile = "app.log"
)
type Config struct {
Market string `json:"market"`
AutoStart bool `json:"auto_start"`
LastDate string `json:"last_date"`
}
type Story struct {
Date string `json:"date"`
Title string `json:"title"`
Copyright string `json:"copyright"`
File string `json:"file"`
}
type BingResp struct {
Images []struct {
URLBase string `json:"urlbase"`
Title string `json:"title"`
Copyright string `json:"copyright"`
} `json:"images"`
}
var httpClient = &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
},
}
var (
config Config
stories []Story
serverRunning bool // 服务器是否已启动
mu sync.Mutex // 保护 stories 和 serverRunning
user32 = syscall.NewLazyDLL("user32.dll")
setWallpaper = user32.NewProc("SystemParametersInfoW")
)
func main() {
fmt.Println("icon size:", len(icon))
setupLogging()
loadConfig()
loadStories()
if config.AutoStart {
setAutoStart()
}
systray.Run(onReady, onExit)
}
func onReady() {
systray.SetIcon(icon) // ⭐关键
systray.SetTitle("Bing Story V2")
systray.SetTooltip("Wallpaper Tool")
mUpdate := systray.AddMenuItem("立即更新", "")
mToday := systray.AddMenuItem("查看今日故事", "")
mCenter := systray.AddMenuItem("📚 故事中心", "")
mOpenDir := systray.AddMenuItem("打开壁纸目录", "")
systray.AddSeparator()
mExit := systray.AddMenuItem("退出", "")
go func() {
autoRun()
for {
select {
case <-mUpdate.ClickedCh:
updateWallpaper()
case <-mToday.ClickedCh:
showToday()
case <-mCenter.ClickedCh:
showStoryCenter()
case <-mOpenDir.ClickedCh:
openPath(getWallpaperPath())
case <-mExit.ClickedCh:
systray.Quit()
return
}
}
}()
}
func onExit() {}
// =========================
// Core
// =========================
func autoRun() {
today := time.Now().Format("2006-01-02")
if config.LastDate == today {
return
}
updateWallpaper()
config.LastDate = today
saveConfig()
}
func updateWallpaper() {
url, story, file, err := fetchBing()
if err != nil {
log.Println(err)
return
}
if err := download(file, url); err != nil {
log.Println(err)
return
}
if err := setWall(file); err != nil {
log.Println(err)
return
}
saveStory(Story{
Date: time.Now().Format("2006-01-02"),
Title: story.Title,
Copyright: story.Copyright,
File: file,
})
}
// =========================
// Bing
// =========================
type StoryMeta struct {
Title string
Copyright string
}
func fetchBing() (string, StoryMeta, string, error) {
api := "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=" + getMarket()
resp, err := httpClient.Get(api)
if err != nil {
return "", StoryMeta{}, "", err
}
defer resp.Body.Close()
var data BingResp
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return "", StoryMeta{}, "", fmt.Errorf("failed to decode response: %v", err)
}
if len(data.Images) == 0 {
return "", StoryMeta{}, "", fmt.Errorf("no images returned from API")
}
img := data.Images[0]
url := "https://www.bing.com" + img.URLBase + "_UHD.jpg"
return url, StoryMeta{
Title: img.Title,
Copyright: img.Copyright,
}, time.Now().Format("20060102") + ".jpg", nil
}
// =========================
// Download
// =========================
func download(file, url string) error {
os.MkdirAll(getWallpaperPath(), 0755)
path := filepath.Join(getWallpaperPath(), file)
resp, err := httpClient.Get(url)
if err != nil {
return fmt.Errorf("failed to download image: %v", err)
}
defer resp.Body.Close()
out, err := os.Create(path)
if err != nil {
return fmt.Errorf("failed to create file: %v", err)
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return fmt.Errorf("failed to save image: %v", err)
}
return nil
}
// =========================
// Wallpaper
// =========================
func setWall(file string) error {
path := filepath.Join(getWallpaperPath(), file)
abs, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("failed to get absolute path: %v", err)
}
ptr, err := syscall.UTF16PtrFromString(abs)
if err != nil {
return fmt.Errorf("failed to convert path: %v", err)
}
ret, _, _ := setWallpaper.Call(20, 0, uintptr(unsafe.Pointer(ptr)), 3)
if ret == 0 {
return fmt.Errorf("failed to set wallpaper")
}
return nil
}
// =========================
// Story Center
// =========================
const (
pageSize = 10
)
var storyHTMLTemplate = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bing 壁纸故事中心</title>
<style>
:root {
--primary-color: #6366f1;
--primary-dark: #4f46e5;
--accent-color: #8b5cf6;
--bg-gradient-start: #0f172a;
--bg-gradient-end: #1e1b4b;
--card-bg: rgba(255, 255, 255, 0.08);
--card-bg-hover: rgba(255, 255, 255, 0.12);
--text-primary: #f1f5f9;
--text-secondary: #94a3b8;
--border-color: rgba(255, 255, 255, 0.1);
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3);
--shadow-md: 0 4px 6px rgba(0, 0, 0, 0.4);
--shadow-lg: 0 10px 25px rgba(0, 0, 0, 0.5);
--radius-sm: 8px;
--radius-md: 12px;
--radius-lg: 16px;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', -apple-system, sans-serif;
background: linear-gradient(145deg, var(--bg-gradient-start) 0%, var(--bg-gradient-end) 100%);
min-height: 100vh;
padding: 24px 16px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.container {
max-width: 800px;
margin: 0 auto;
}
.header {
text-align: center;
margin-bottom: 32px;
padding: 24px 0;
}
.header h1 {
font-size: 2rem;
font-weight: 600;
color: var(--text-primary);
letter-spacing: 0.5px;
margin-bottom: 8px;
background: linear-gradient(135deg, #a5b4fc 0%, #c4b5fd 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.header p {
font-size: 0.95rem;
color: var(--text-secondary);
font-weight: 400;
}
.stats-bar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
padding: 16px 20px;
background: var(--card-bg);
border-radius: var(--radius-md);
border: 1px solid var(--border-color);
}
.stats-info {
font-size: 0.9rem;
color: var(--text-secondary);
}
.stats-info strong {
color: var(--text-primary);
font-weight: 500;
}
.sync-btn {
padding: 8px 20px;
background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
color: white;
border: none;
border-radius: var(--radius-sm);
font-size: 0.85rem;
font-weight: 500;
cursor: pointer;
transition: all 0.25s ease;
box-shadow: var(--shadow-sm);
}
.sync-btn:hover {
transform: translateY(-1px);
box-shadow: var(--shadow-md);
opacity: 0.95;
}
.sync-btn:active {
transform: translateY(0);
}
.sync-hint {
font-size: 0.75rem;
color: var(--text-secondary);
opacity: 0.7;
margin-top: 8px;
text-align: center;
display: block;
}
.card {
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
overflow: hidden;
margin-bottom: 16px;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
backdrop-filter: blur(10px);
}
.card:hover {
background: var(--card-bg-hover);
border-color: rgba(255, 255, 255, 0.2);
transform: translateY(-2px);
box-shadow: var(--shadow-lg);
}
.card-inner {
display: flex;
align-items: stretch;
}
.card-image-wrapper {
position: relative;
width: 200px;
flex-shrink: 0;
min-height: 140px;
}
.card-image {
width: 100%;
height: 100%;
min-height: 140px;
object-fit: cover;
cursor: pointer;
transition: opacity 0.2s ease;
}
.card-image:hover {
opacity: 0.85;
}
.card-image-overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(to top, rgba(0,0,0,0.6), transparent);
padding: 8px 12px;
opacity: 0;
transition: opacity 0.2s ease;
}
.card-image-wrapper:hover .card-image-overlay {
opacity: 1;
}
.card-image-overlay span {
font-size: 0.75rem;
color: white;
font-weight: 400;
}
.card-content {
flex: 1;
padding: 16px 20px;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.card-header {
margin-bottom: 12px;
}
.card-date {
display: inline-block;
font-size: 0.75rem;
color: var(--text-secondary);
background: rgba(99, 102, 241, 0.15);
padding: 4px 10px;
border-radius: 12px;
margin-bottom: 8px;
border: 1px solid rgba(99, 102, 241, 0.2);
}
.card-title {
font-size: 1.1rem;
font-weight: 600;
color: var(--text-primary);
margin-bottom: 6px;
letter-spacing: 0.3px;
}
.card-desc {
font-size: 0.85rem;
color: var(--text-secondary);
line-height: 1.5;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.card-actions {
display: flex;
justify-content: flex-end;
}
.btn-set-wallpaper {
padding: 7px 18px;
background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
color: white;
border: none;
border-radius: var(--radius-sm);
font-size: 0.85rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
}
.btn-set-wallpaper:hover {
transform: scale(1.02);
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4);
}
.btn-set-wallpaper:active {
transform: scale(0.98);
}
.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 8px;
margin-top: 32px;
padding: 20px;
}
.page-btn {
width: 36px;
height: 36px;
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
color: var(--text-secondary);
font-size: 0.9rem;
cursor: pointer;
transition: all 0.2s ease;
}
.page-btn:hover:not(.active) {
background: var(--card-bg-hover);
color: var(--text-primary);
}
.page-btn.active {
background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
border-color: transparent;
color: white;
}
.empty-state {
text-align: center;
padding: 60px 20px;
color: var(--text-secondary);
}
.empty-state h2 {
font-size: 1.25rem;
font-weight: 500;
margin-bottom: 8px;
color: var(--text-primary);
}
.empty-state p {
font-size: 0.9rem;
}
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.9);
backdrop-filter: blur(8px);
justify-content: center;
align-items: center;
padding: 20px;
}
.modal.show {
display: flex;
animation: fadeIn 0.2s ease;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.modal-content {
position: relative;
max-width: 90vw;
max-height: 90vh;
animation: zoomIn 0.25s ease;
}
@keyframes zoomIn {
from { transform: scale(0.95); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
.modal img {
max-width: 100%;
max-height: 85vh;
border-radius: var(--radius-md);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6);
}
.modal-close {
position: absolute;
top: -40px;
right: 0;
color: white;
font-size: 28px;
font-weight: 300;
cursor: pointer;
opacity: 0.7;
transition: opacity 0.2s;
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
}
.modal-close:hover {
opacity: 1;
}
.toast {
position: fixed;
bottom: 30px;
left: 50%;
transform: translateX(-50%);
background: rgba(15, 23, 42, 0.95);
color: white;
padding: 14px 24px;
border-radius: var(--radius-md);
font-size: 0.9rem;
opacity: 0;
transition: opacity 0.3s;
z-index: 1001;
border: 1px solid var(--border-color);
box-shadow: var(--shadow-lg);
}
.toast.show {
opacity: 1;
}
@media (max-width: 600px) {
.card-inner {
flex-direction: column;
}
.card-image-wrapper {
width: 100%;
height: 180px;
}
.card-content {
padding: 16px;
}
.stats-bar {
flex-direction: column;
gap: 12px;
text-align: center;
}
.header h1 {
font-size: 1.6rem;
}
}
</style>
</head>
<body>
<!-- 图片预览模态框 -->
<div id="imageModal" class="modal">
<div class="modal-content">
<span class="modal-close" onclick="closeModal()">×</span>
<img id="modalImage" src="" alt="预览">
</div>
</div>
<div class="container">
<div class="header">
<h1>🖼️ 壁纸故事中心</h1>
<p>探索每一天的精彩瞬间</p>
</div>
<div class="stats-bar">
<span class="stats-info">共 <strong>{{.Total}}</strong> 条记录 · 第 <strong>{{.CurrentPage}}/{{.TotalPages}}</strong> 页</span>
<button class="sync-btn" onclick="syncStories()" title="同步壁纸文件与故事记录">🔄 同步</button>
</div>
<span class="sync-hint">近7天官方API · 更早日期尝试存档</span>
{{if .Stories}}
{{range .Stories}}
<div class="card">
<div class="card-inner">
<div class="card-image-wrapper">
<img class="card-image" src="/wallpaper/{{.File}}" alt="{{.Title}}"
onclick="previewImage('/wallpaper/{{.File}}')">
<div class="card-image-overlay"><span>点击预览大图</span></div>
</div>
<div class="card-content">
<div class="card-header">
<span class="card-date">{{.Date}}</span>
<div class="card-title">{{.Title}}</div>
<div class="card-desc">{{.Copyright}}</div>
</div>
<div class="card-actions">
<button class="btn-set-wallpaper" onclick="setWallpaper('{{.File}}', '{{.Date}}')">设为壁纸</button>
</div>
</div>
</div>
</div>
{{end}}
<div class="pagination">
{{if .HasPrev}}<button class="page-btn" onclick="navigatePage({{.CurrentPage}}-1)">‹</button>{{end}}
{{range .PageNumbers}}
<button class="page-btn {{if eq . $.CurrentPage}}active{{end}}" onclick="navigatePage({{.}})">{{.}}</button>
{{end}}
{{if .HasNext}}<button class="page-btn" onclick="navigatePage({{.CurrentPage}}+1)">›</button>{{end}}
</div>
{{else}}
<div class="empty-state">
<h2>暂无历史记录</h2>
<p>点击「立即更新」获取今日壁纸故事</p>
</div>
{{end}}
</div>
<div id="toast" class="toast"></div>
<script>
function syncStories() {
fetch('/sync')
.then(function(r) {
if (r.ok) {
showToast('同步成功,刷新页面查看更新');
} else {
showToast('同步失败');
}
})
.catch(function() {
showToast('同步失败');
});
}
function navigatePage(page) { window.location.href = '/story?page=' + page; }
function showToast(msg) {
var t = document.getElementById('toast');
t.textContent = msg;
t.classList.add('show');
setTimeout(function() { t.classList.remove('show'); }, 3000);
}
function setWallpaper(file, date) {
fetch('/setwallpaper?file=' + encodeURIComponent(file))
.then(function(r) { showToast(r.ok ? '已设置壁纸: ' + date : '设置失败'); })
.catch(function() { showToast('设置失败,请检查图片是否存在'); });
}
function previewImage(src) {
var modal = document.getElementById('imageModal');
var modalImg = document.getElementById('modalImage');
modalImg.src = src;
modal.classList.add('show');
}
function closeModal() {
document.getElementById('imageModal').classList.remove('show');
}
document.addEventListener('click', function(e) {
var modal = document.getElementById('imageModal');
if (e.target === modal) { closeModal(); }
});
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') { closeModal(); }
});
</script>
</body>
</html>`
// 故事中心 - 使用现代Web界面
func showStoryCenter() {
// 启动服务器(只启动一次)
if !serverRunning {
go startStoryServer()
serverRunning = true
time.Sleep(500 * time.Millisecond) // 等待服务器启动
}
// 打开浏览器
exec.Command("cmd", "/c", "start", "http://localhost:8765/story").Run()
}
// 启动本地HTTP服务器提供故事中心界面
func startStoryServer() {
http.HandleFunc("/story", storyHandler)
http.HandleFunc("/today", todayHandler)
http.HandleFunc("/setwallpaper", setWallpaperHandler)
http.HandleFunc("/wallpaper/", serveWallpaper)
http.HandleFunc("/sync", syncHandler)
log.Println("Story server started on :8765")
if err := http.ListenAndServe(":8765", nil); err != nil {
log.Println("Server error:", err)
}
}
// 手动同步处理
func syncHandler(w http.ResponseWriter, r *http.Request) {
syncStoriesWithWallpapers()
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"success": true}`))
}
// 提供壁纸图片访问
func serveWallpaper(w http.ResponseWriter, r *http.Request) {
file := strings.TrimPrefix(r.URL.Path, "/wallpaper/")
file = strings.TrimPrefix(file, "/")
file = filepath.Join(getWallpaperPath(), file)
if _, err := os.Stat(file); os.IsNotExist(err) {
http.NotFound(w, r)
return
}
http.ServeFile(w, r, file)
}
// 今日故事页面
func todayHandler(w http.ResponseWriter, r *http.Request) {
loadStoriesFromFile()
mu.Lock()
if len(stories) == 0 {
mu.Unlock()
w.Write([]byte(`
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>今日故事</title>
<style>
body {
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
background: linear-gradient(145deg, #0f172a 0%, #1e1b4b 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.container {
text-align: center;
color: #94a3b8;
}
.container h2 {
font-size: 1.5rem;
margin-bottom: 10px;
color: #f1f5f9;
}
</style>
</head>
<body>
<div class="container">
<h2>暂无数据</h2>
<p>点击「立即更新」获取今日壁纸故事</p>
</div>
</body>
</html>`))
return
}
s := stories[0]
mu.Unlock()
todayHTML := `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>` + s.Title + ` - 今日故事</title>
<style>
:root {
--primary-color: #6366f1;
--bg-dark: #0f172a;
--bg-card: rgba(255,255,255,0.08);
--text-primary: #f1f5f9;
--text-secondary: #94a3b8;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'PingFang SC', 'Microsoft YaHei', -apple-system, sans-serif;
background: linear-gradient(145deg, var(--bg-dark) 0%, #1e1b4b 100%);
min-height: 100vh;
padding: 24px;
-webkit-font-smoothing: antialiased;
}
.container {
max-width: 700px;
margin: 0 auto;
}
.header {
text-align: center;
margin-bottom: 32px;
}
.header h1 {
font-size: 1.1rem;
font-weight: 500;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 4px;
margin-bottom: 16px;
}
.card {
background: var(--bg-card);
border-radius: 20px;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.1);
backdrop-filter: blur(10px);
}
.image-wrapper {
position: relative;
height: 350px;
}
.image-wrapper img {
width: 100%;
height: 100%;
object-fit: cover;
}
.image-overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
padding: 40px 30px 20px;
}
.date-badge {
display: inline-block;
font-size: 0.85rem;
color: var(--text-secondary);
background: rgba(99, 102, 241, 0.2);
padding: 6px 14px;
border-radius: 20px;
margin-bottom: 12px;
border: 1px solid rgba(99, 102, 241, 0.3);
}
.title {
font-size: 2rem;
font-weight: 700;
color: var(--text-primary);
margin-bottom: 8px;
letter-spacing: 0.5px;
line-height: 1.2;
}
.content {
padding: 30px;
}
.desc {
font-size: 1.15rem;
color: var(--text-secondary);
line-height: 1.8;
font-weight: 400;
}
.actions {
display: flex;
gap: 12px;
margin-top: 24px;
justify-content: center;
}
.btn {
padding: 12px 32px;
border-radius: 30px;
font-size: 0.95rem;
font-weight: 500;
cursor: pointer;
transition: all 0.25s;
border: none;
}
.btn-primary {
background: linear-gradient(135deg, var(--primary-color) 0%, #8b5cf6 100%);
color: white;
box-shadow: 0 4px 15px rgba(99, 102, 241, 0.4);
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(99, 102, 241, 0.5);
}
.btn-secondary {
background: rgba(255,255,255,0.1);
color: var(--text-primary);
border: 1px solid rgba(255,255,255,0.2);
}
.btn-secondary:hover {
background: rgba(255,255,255,0.15);
}
.toast {
position: fixed;
bottom: 30px;
left: 50%;
transform: translateX(-50%);
background: rgba(15, 23, 42, 0.95);
color: white;
padding: 14px 24px;
border-radius: 12px;
font-size: 0.95rem;
opacity: 0;
transition: opacity 0.3s;
z-index: 1000;
border: 1px solid rgba(255,255,255,0.1);
}
.toast.show { opacity: 1; }
@media (max-width: 600px) {
.image-wrapper { height: 250px; }
.title { font-size: 1.5rem; }
.desc { font-size: 1rem; }
.content { padding: 20px; }
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Today's Story</h1>
</div>
<div class="card">
<div class="image-wrapper">
<img src="/wallpaper/` + s.File + `" alt="` + s.Title + `">
<div class="image-overlay">
<span class="date-badge">` + s.Date + `</span>
<div class="title">` + s.Title + `</div>
</div>
</div>
<div class="content">
<p class="desc">` + s.Copyright + `</p>
<div class="actions">
<button class="btn btn-primary" onclick="setWallpaper('` + s.File + `', '` + s.Date + `')">设为壁纸</button>
<button class="btn btn-secondary" onclick="window.location.href='/story'">查看历史</button>
</div>
</div>
</div>
</div>
<div id="toast" class="toast"></div>
<script>
function setWallpaper(file, date) {
fetch('/setwallpaper?file=' + encodeURIComponent(file))
.then(function(r) {
showToast(r.ok ? '壁纸已设置: ' + date : '设置失败');
})
.catch(function() {
showToast('设置失败');
});
}
function showToast(msg) {
var t = document.getElementById('toast');
t.textContent = msg;
t.classList.add('show');
setTimeout(function() { t.classList.remove('show'); }, 3000);
}
</script>
</body>
</html>`
w.Write([]byte(todayHTML))
}
func storyHandler(w http.ResponseWriter, r *http.Request) {
// 每次请求都重新加载数据,确保显示最新内容
loadStoriesFromFile()
page := 1
if p := r.URL.Query().Get("page"); p != "" {
fmt.Sscanf(p, "%d", &page)
}
mu.Lock()
totalPages := 1
if len(stories) > 0 {
totalPages = (len(stories) + pageSize - 1) / pageSize
}
if page < 1 {
page = 1
}
if page > totalPages {
page = totalPages
}
start := (page - 1) * pageSize
end := start + pageSize
if end > len(stories) {
end = len(stories)
}
if start > len(stories) {
start = len(stories)
}
mu.Unlock()
pageNumbers := []int{}
for i := 1; i <= totalPages; i++ {
pageNumbers = append(pageNumbers, i)
}
mu.Lock()
data := map[string]interface{}{
"Stories": stories[start:end],
"Total": len(stories),
"CurrentPage": page,
"TotalPages": totalPages,
"HasPrev": page > 1,
"HasNext": page < totalPages,
"PageNumbers": pageNumbers,
}
mu.Unlock()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl, err := template.New("story").Parse(storyHTMLTemplate)
if err != nil {
log.Println("Template error:", err)
http.Error(w, "Template error", 500)
return
}
tmpl.Execute(w, data)
}
func setWallpaperHandler(w http.ResponseWriter, r *http.Request) {
file := r.URL.Query().Get("file")
if file == "" {
http.Error(w, "missing file parameter", 400)
return
}
file, _ = url.QueryUnescape(file)
// 直接调用 setWall,传递文件名(setWall 内部会拼接完整路径)
if err := setWall(file); err != nil {
log.Println("Failed to set wallpaper:", err)
http.Error(w, err.Error(), 500)
return
}
log.Println("Wallpaper set successfully:", file)
w.WriteHeader(200)
}
func saveStory(s Story) {
mu.Lock()
// 去重:如果当天已有记录,更新而非追加
for i, st := range stories {
if st.Date == s.Date {
stories[i] = s
mu.Unlock()
saveStoriesToFile()
return
}
}
stories = append(stories, s)
// 排序
sort.Slice(stories, func(i, j int) bool {
return stories[i].Date > stories[j].Date
})
mu.Unlock()
saveStoriesToFile()
}
func saveStoriesToFile() {
mu.Lock()
data, _ := json.MarshalIndent(stories, "", " ")
mu.Unlock()
os.WriteFile(filepath.Join(getBase(), storyFile), data, 0644)
}
func loadStories() {
f, err := os.ReadFile(filepath.Join(getBase(), storyFile))
if err == nil {
mu.Lock()
json.Unmarshal(f, &stories)
sort.Slice(stories, func(i, j int) bool {
return stories[i].Date > stories[j].Date
})
mu.Unlock()
}
}
// 从文件加载故事数据(不执行同步)
func loadStoriesFromFile() {
f, err := os.ReadFile(filepath.Join(getBase(), storyFile))
if err != nil {
return
}
var newStories []Story
if err := json.Unmarshal(f, &newStories); err == nil {
mu.Lock()
stories = newStories
sort.Slice(stories, func(i, j int) bool {
return stories[i].Date > stories[j].Date
})
mu.Unlock()
}
}
// 同步 stories.json 与 wallpapers 文件夹
func syncStoriesWithWallpapers() {
wallpaperPath := getWallpaperPath()
// 扫描 wallpapers 文件夹获取所有图片文件
files, err := filepath.Glob(filepath.Join(wallpaperPath, "*.jpg"))
if err != nil {
return
}
// 建立文件名到文件的映射
fileMap := make(map[string]bool)
for _, f := range files {
fileMap[filepath.Base(f)] = true
}
mu.Lock()
// 清理 stories.json 中不存在对应文件的记录,同时尝试更新已有记录的元数据
validStories := []Story{}
for _, s := range stories {
if fileMap[s.File] {
// 尝试更新已有记录的元数据(如果是"未知标题"或日期在7天内)
if s.Title == "未知标题" || s.Copyright == "从壁纸文件导入" {
meta, err := fetchHistoricalBing(s.Date)
if err == nil && meta.Title != "" {
s.Title = meta.Title
s.Copyright = meta.Copyright
log.Println("Updated metadata for:", s.Date)
}
}
validStories = append(validStories, s)
} else {
log.Println("Removed orphaned story:", s.Date, s.File)
}
}
// 检查 wallpapers 中是否有 stories.json 中没有的文件
for _, f := range files {
baseName := filepath.Base(f)
found := false
for _, s := range stories {
if s.File == baseName {
found = true
break
}
}
if !found {
// 尝试从文件名推断日期
date := extractDateFromFilename(baseName)
if date != "" {
// 尝试从 Bing API 获取详细信息
meta, err := fetchHistoricalBing(date)
title := "未知标题"
copyright := "从壁纸文件导入"
if err == nil && meta.Title != "" {
title = meta.Title
copyright = meta.Copyright
log.Println("Fetched metadata for:", date)
} else {
log.Println("Using default metadata for:", date)
}
newStory := Story{
Date: date,
Title: title,
Copyright: copyright,
File: baseName,
}
validStories = append(validStories, newStory)
log.Println("Added missing story:", date, baseName)
}
}
}
// 重新排序并保存
sort.Slice(validStories, func(i, j int) bool {
return validStories[i].Date > validStories[j].Date
})
stories = validStories
mu.Unlock()
saveStoriesToFile()
}
// 从文件名提取日期(格式:20260609.jpg)
func extractDateFromFilename(filename string) string {
if len(filename) >= 12 && filename[8] == '.' && filename[9:] == "jpg" {
dateStr := filename[:8]
if _, err := time.Parse("20060102", dateStr); err == nil {
return fmt.Sprintf("%s-%s-%s", dateStr[:4], dateStr[4:6], dateStr[6:8])
}
}
return ""
}
// 获取历史壁纸信息(最多支持7天前)
func fetchHistoricalBing(date string) (StoryMeta, error) {
targetDate, err := time.Parse("2006-01-02", date)
if err != nil {
log.Println("fetchHistoricalBing: invalid date format:", date)
return StoryMeta{}, err
}
today := time.Now().Truncate(24 * time.Hour)
daysDiff := int(today.Sub(targetDate).Hours() / 24)
log.Printf("fetchHistoricalBing: date=%s, today=%s, daysDiff=%d\n", date, today.Format("2006-01-02"), daysDiff)
if daysDiff < 0 || daysDiff > 7 {
log.Printf("fetchHistoricalBing: date too old for Bing API, trying archive...\n")
// 超过7天,尝试从存档服务获取
return fetchFromArchive(date)
}
api := fmt.Sprintf("https://www.bing.com/HPImageArchive.aspx?format=js&idx=%d&n=1&mkt=%s", daysDiff, getMarket())
log.Printf("fetchHistoricalBing: calling API: %s\n", api)
resp, err := httpClient.Get(api)
if err != nil {
log.Println("fetchHistoricalBing: HTTP request failed:", err)
return StoryMeta{}, err
}
defer resp.Body.Close()
log.Printf("fetchHistoricalBing: HTTP status code: %d\n", resp.StatusCode)
var data BingResp
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
log.Println("fetchHistoricalBing: JSON decode failed:", err)
return StoryMeta{}, err
}
if len(data.Images) == 0 {
log.Println("fetchHistoricalBing: no images returned, trying archive...")
return fetchFromArchive(date)
}
img := data.Images[0]
log.Printf("fetchHistoricalBing: success - Title=%s\n", img.Title)
return StoryMeta{
Title: img.Title,
Copyright: img.Copyright,
}, nil
}
// 从存档服务获取历史壁纸信息(支持更早日期)
func fetchFromArchive(date string) (StoryMeta, error) {
// 尝试多个存档源
archives := []string{
fmt.Sprintf("https://bing.biturl.top/?d=%s", date),
fmt.Sprintf("https://bing-wallpaper-archive.herokuapp.com/api/%s", date),
}
for _, url := range archives {
log.Printf("fetchFromArchive: trying %s\n", url)
resp, err := httpClient.Get(url)
if err != nil {
log.Println("fetchFromArchive: HTTP request failed:", err)
continue
}
if resp.StatusCode != 200 {
resp.Body.Close()
continue
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
resp.Body.Close()
continue
}
title, titleOK := result["title"].(string)
copyright, copyrightOK := result["copyright"].(string)
if titleOK && copyrightOK && title != "" {
resp.Body.Close()
log.Printf("fetchFromArchive: success - Title=%s\n", title)
return StoryMeta{Title: title, Copyright: copyright}, nil
}
resp.Body.Close()
}
log.Println("fetchFromArchive: all archives failed")
return StoryMeta{}, fmt.Errorf("no archive data available")
}
func showToday() {
if len(stories) == 0 {
msg("暂无数据\n\n点击「立即更新」获取今日壁纸故事")
return
}
// 使用Web界面展示今日故事
if !serverRunning {
go startStoryServer()
serverRunning = true
time.Sleep(500 * time.Millisecond)
}
exec.Command("cmd", "/c", "start", "http://localhost:8765/today").Run()
}
// =========================
// UI
// =========================
func msg(text string) {
title, _ := syscall.UTF16PtrFromString("Bing Story V2")
msg, _ := syscall.UTF16PtrFromString(text)
user32.NewProc("MessageBoxW").Call(
0,
uintptr(unsafe.Pointer(msg)),
uintptr(unsafe.Pointer(title)),
0,
)
}
// =========================
// Utils
// =========================
func openPath(p string) {
exec.Command("explorer", p).Start()
}
func getMarket() string {
return "zh-CN"
}
func getBase() string {
exe, _ := os.Executable()
return filepath.Dir(exe)
}
func getWallpaperPath() string {
return filepath.Join(getBase(), wallpaperDir)
}
// =========================
// Config
// =========================
func loadConfig() {
config = Config{
Market: "zh-CN",
AutoStart: true,
}
f, err := os.ReadFile(filepath.Join(getBase(), configFile))
if err == nil {
json.Unmarshal(f, &config)
}
}
func saveConfig() {
data, _ := json.MarshalIndent(config, "", " ")
os.WriteFile(filepath.Join(getBase(), configFile), data, 0644)
}
// =========================
// Auto Start
// =========================
func setAutoStart() {
exe, _ := os.Executable()
key, _, _ := registry.CreateKey(
registry.CURRENT_USER,
`Software\Microsoft\Windows\CurrentVersion\Run`,
registry.SET_VALUE,
)
defer key.Close()
key.SetStringValue(appName, exe)
}
// =========================
// Logging
// =========================
func setupLogging() {
f, _ := os.OpenFile(filepath.Join(getBase(), logFile), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
log.SetOutput(f)
}
|