-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsite.js
More file actions
131 lines (118 loc) · 4.48 KB
/
Copy pathsite.js
File metadata and controls
131 lines (118 loc) · 4.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
(function () {
'use strict';
const CACHE_KEY = 'dailyWallpaperCache.v1';
const FALLBACK_COLOR = '#1a1a1e';
const API_ORIGIN = 'https://bing.biturl.top/';
function localDateKey() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function wallpaperResolution() {
return window.matchMedia('(max-width: 768px)').matches ? 1366 : 1920;
}
function validateWallpaperUrl(value) {
try {
const url = new URL(String(value || ''));
const trustedHost = url.hostname === 'bing.com' || url.hostname.endsWith('.bing.com');
return url.protocol === 'https:' && trustedHost ? url.href : '';
} catch (error) {
return '';
}
}
function readCache() {
try {
const cached = JSON.parse(localStorage.getItem(CACHE_KEY) || 'null');
if (!cached || typeof cached !== 'object') return null;
const url = validateWallpaperUrl(cached.url);
if (!url) return null;
return {
date: String(cached.date || ''),
resolution: Number(cached.resolution),
url,
};
} catch (error) {
return null;
}
}
function writeCache(value) {
try {
localStorage.setItem(CACHE_KEY, JSON.stringify(value));
} catch (error) {
// Private browsing or storage policy may disable localStorage.
}
}
function clearCache() {
try {
localStorage.removeItem(CACHE_KEY);
} catch (error) {
// Storage access can be disabled without affecting the fallback.
}
}
async function resolveWallpaperUrl() {
const connection = navigator.connection;
if (connection && (connection.saveData || ['slow-2g', '2g'].includes(connection.effectiveType))) {
throw new Error('Wallpaper disabled on a constrained connection');
}
const resolution = wallpaperResolution();
const date = localDateKey();
const cached = readCache();
if (cached && cached.date === date && cached.resolution === resolution) {
return cached.url;
}
const apiUrl = new URL(API_ORIGIN);
apiUrl.searchParams.set('resolution', String(resolution));
apiUrl.searchParams.set('format', 'json');
apiUrl.searchParams.set('index', '0');
apiUrl.searchParams.set('mkt', 'zh-CN');
const controller = new AbortController();
const timeout = window.setTimeout(() => controller.abort(), 6000);
try {
const response = await fetch(apiUrl, {
cache: 'no-store',
credentials: 'omit',
referrerPolicy: 'no-referrer',
signal: controller.signal,
});
if (!response.ok) throw new Error(`Wallpaper API returned ${response.status}`);
const payload = await response.json();
const url = validateWallpaperUrl(payload && payload.url);
if (!url) throw new Error('Wallpaper API returned an untrusted URL');
writeCache({ date, resolution, url });
return url;
} catch (error) {
if (cached) return cached.url;
throw error;
} finally {
window.clearTimeout(timeout);
}
}
function applyWallpaper(url, allowRetry = true) {
const image = new Image();
image.decoding = 'async';
image.fetchPriority = 'low';
image.referrerPolicy = 'no-referrer';
image.onload = function () {
document.body.style.backgroundImage = `url("${url}")`;
document.documentElement.dataset.wallpaper = 'ready';
};
image.onerror = function () {
if (allowRetry) {
clearCache();
resolveWallpaperUrl().then(function (replacementUrl) {
applyWallpaper(replacementUrl, false);
}).catch(showFallback);
return;
}
showFallback();
};
image.src = url;
}
function showFallback() {
document.body.style.background = FALLBACK_COLOR;
document.documentElement.dataset.wallpaper = 'fallback';
}
resolveWallpaperUrl().then(applyWallpaper).catch(showFallback);
}());