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
| export default { async fetch(request, env, ctx) { const url = new URL(request.url); const path = url.pathname; if (!env.TIP_STORAGE) { return new Response(showErrorPage( "系统配置错误", "KV存储未配置,请在Worker设置中绑定KV命名空间到'TIP_STORAGE'变量" ), { status: 500, headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } try { switch (path) { case '/': const isAfterOperation = request.headers.get('Referer')?.includes('/add-tip') || request.headers.get('Referer')?.includes('/delete-tip'); return await handleHome(request, env, isAfterOperation); case '/login': return await handleLogin(request, env); case '/add-tip': return await handleAddTip(request, env); case '/delete-tip': return await handleDeleteTip(request, env); case '/all': return await handleAllTips(request, env); default: return new Response(showErrorPage("页面未找到", "请求的路径不存在"), { status: 404, headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } } catch (err) { return new Response(showErrorPage("操作失败", err.message), { status: 500, headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } } };
async function isAuthenticated(request) { const cookies = request.headers.get('Cookie') || ''; return cookies.includes('authenticated=true'); }
async function handleHome(request, env, forceRefresh = false) { const authenticated = await isAuthenticated(request); if (!authenticated) { return new Response(loginPageHtml(), { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } let tips; if (forceRefresh) { tips = await getLatestTips(env); } else { tips = await getTips(env); } return new Response(tipManagementPageHtml(tips), { headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' } }); }
async function handleLogin(request, env) { const url = new URL(request.url); if (url.searchParams.get('logout')) { return new Response('', { status: 302, headers: { 'Location': '/', 'Set-Cookie': 'authenticated=true; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=0', 'Content-Type': 'text/html; charset=utf-8' } }); } if (request.method !== 'POST') { return new Response(showErrorPage("方法不允许", "请使用POST方法登录"), { status: 405, headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } const formData = await request.formData(); const password = formData.get('password'); const correctPassword = env.TIP_PASSWORD || 'defaultpassword'; if (password === correctPassword) { return new Response('', { status: 302, headers: { 'Location': '/', 'Set-Cookie': 'authenticated=true; HttpOnly; Secure; SameSite=Strict; Path=/', 'Content-Type': 'text/html; charset=utf-8' } }); } else { return new Response(loginPageHtml('密码错误,请重试'), { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } }
async function handleAllTips(request, env) { const tips = await getLatestTips(env); const simplifiedTips = tips.map(tip => ({ person: tip.person, amount: tip.amount, time: tip.time, method: tip.method, color: tip.color })); return new Response(JSON.stringify(simplifiedTips, null, 2), { headers: { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' } }); }
function getCurrentShanghaiTime() { const now = new Date(); const shanghaiTime = new Date(now.toLocaleString("en-US", {timeZone: "Asia/Shanghai"})); const year = shanghaiTime.getFullYear(); const month = String(shanghaiTime.getMonth() + 1).padStart(2, '0'); const day = String(shanghaiTime.getDate()).padStart(2, '0'); const hours = String(shanghaiTime.getHours()).padStart(2, '0'); const minutes = String(shanghaiTime.getMinutes()).padStart(2, '0'); return `${year}-${month}-${day}T${hours}:${minutes}`; }
function formatTimeForDisplay(datetimeLocal) { if (!datetimeLocal) return ''; const [date, time] = datetimeLocal.split('T'); return `${date} ${time}:00`; }
function formatTimeForInput(displayTime) { if (!displayTime) return ''; return displayTime.replace(' ', 'T').replace(':00', ''); }
async function getTips(env) { const keys = await env.TIP_STORAGE.list({ limit: 1000, cacheTtl: 60 }); const tips = []; for (const key of keys.keys) { const tip = await env.TIP_STORAGE.get(key.name, { type: 'json', cacheTtl: 60 }); if (tip) { tips.push({ id: key.name, ...tip }); } } return tips.sort((a, b) => b.createdAt - a.createdAt); }
async function getLatestTips(env) { const keys = await env.TIP_STORAGE.list({ limit: 1000, cacheTtl: 60 }); await new Promise(resolve => setTimeout(resolve, 250)); const tips = []; for (const key of keys.keys) { let tip = null; for (let i = 0; i < 3; i++) { tip = await env.TIP_STORAGE.get(key.name, { type: 'json', cacheTtl: 60 }); if (tip) break; if (i < 2) await new Promise(resolve => setTimeout(resolve, 150 * (i + 1))); } if (tip) { tips.push({ id: key.name, ...tip }); } } return tips.sort((a, b) => b.createdAt - a.createdAt); }
async function handleAddTip(request, env) { const authenticated = await isAuthenticated(request); if (!authenticated) { return new Response(showErrorPage("未授权", "请先登录"), { status: 401, headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } if (request.method !== 'POST') { return new Response(showErrorPage("方法不允许", "请使用POST方法添加记录"), { status: 405, headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } const formData = await request.formData(); const id = crypto.randomUUID(); const tip = { amount: formData.get('amount'), person: formData.get('person'), method: formData.get('method'), color: formData.get('color'), time: formatTimeForDisplay(formData.get('time')) || '', createdAt: Date.now() }; await env.TIP_STORAGE.put(id, JSON.stringify(tip)); await new Promise(resolve => setTimeout(resolve, 400)); return new Response('', { status: 302, headers: { 'Location': '/', 'Cache-Control': 'no-store', 'Pragma': 'no-cache' } }); }
async function handleDeleteTip(request, env) { const authenticated = await isAuthenticated(request); if (!authenticated) { return new Response(showErrorPage("未授权", "请先登录"), { status: 401, headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } const url = new URL(request.url); const id = url.searchParams.get('id'); if (!id) { return new Response(showErrorPage("参数错误", "缺少记录ID"), { status: 400, headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } await env.TIP_STORAGE.delete(id); await new Promise(resolve => setTimeout(resolve, 400)); return new Response('', { status: 302, headers: { 'Location': '/', 'Cache-Control': 'no-store', 'Pragma': 'no-cache' } }); }
function showErrorPage(title, message) { return ` <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>${title}</title> <style> body { font-family: Arial, sans-serif; text-align: center; padding: 50px; } .error { color: #d32f2f; margin: 20px 0; } .back { margin-top: 20px; } a { color: #1976d2; text-decoration: none; } a:hover { text-decoration: underline; } </style> </head> <body> <h1>${title}</h1> <div class="error">${message}</div> <div class="back"><a href="/">返回首页</a></div> </body> </html> `; }
function loginPageHtml(errorMessage = '') { return ` <!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: Arial, sans-serif; background: #f5f5f5; margin: 0; padding: 20px; } .login-container { max-width: 400px; margin: 100px auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } h1 { text-align: center; color: #333; margin-bottom: 30px; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; color: #555; } input[type="password"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; } button { width: 100%; padding: 12px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; } button:hover { background: #1565c0; } .error { color: #d32f2f; margin-bottom: 20px; text-align: center; } </style> </head> <body> <div class="login-container"> <h1>打赏管理系统</h1> ${errorMessage ? `<div class="error">${errorMessage}</div>` : ''} <form method="POST" action="/login"> <div class="form-group"> <label for="password">密码:</label> <input type="password" id="password" name="password" required> </div> <button type="submit">登录</button> </form> </div> </body> </html> `; }
function tipManagementPageHtml(tips) { const currentTime = getCurrentShanghaiTime(); return ` <!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: Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; } .container { max-width: 1200px; margin: 0 auto; } .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; } h1 { color: #333; margin: 0; } .logout { color: #d32f2f; text-decoration: none; } .logout:hover { text-decoration: underline; } .form-section { background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; } .form-group { display: flex; flex-direction: column; } label { margin-bottom: 5px; color: #555; font-weight: bold; } input, select { padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; } button { padding: 12px 24px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; } button:hover { background: #1565c0; } .tips-section { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } .tips-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; } .api-link { color: #1976d2; text-decoration: none; } .api-link:hover { text-decoration: underline; } .tips-table { width: 100%; border-collapse: collapse; } .tips-table th, .tips-table td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; } .tips-table th { background: #f8f9fa; font-weight: bold; } .delete-btn { color: #d32f2f; text-decoration: none; } .delete-btn:hover { text-decoration: underline; } .amount { font-weight: bold; } .person { color: #1976d2; } .method { color: #388e3c; } .time { color: #666; font-size: 12px; } .empty { text-align: center; color: #666; padding: 40px; } </style> </head> <body> <div class="container"> <div class="header"> <h1>打赏管理系统</h1> <a href="/login?logout=true" class="logout">退出登录</a> </div> <div class="form-section"> <h2>添加打赏记录</h2> <form method="POST" action="/add-tip"> <div class="form-grid"> <div class="form-group"> <label for="amount">金额:</label> <input type="number" id="amount" name="amount" step="0.01" required> </div> <div class="form-group"> <label for="person">打赏人:</label> <input type="text" id="person" name="person" required> </div> <div class="form-group"> <label for="method">支付方式:</label> <select id="method" name="method" required> <option value="">请选择</option> <option value="微信">微信</option> <option value="支付宝">支付宝</option> </select> </div> <div class="form-group"> <label for="color">颜色:</label> <div style="display: flex; align-items: center; gap: 10px;"> <input type="color" id="color" name="color" value="#1677FF" style="width: 50px; height: 50px; padding: 0; border: none; border-radius: 4px; cursor: pointer;"> <input type="text" id="colorHex" placeholder="#1677FF" style="width: 80px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-family: monospace; font-size: 14px;"> </div> </div> <div class="form-group"> <label for="time">时间:</label> <input type="datetime-local" id="time" name="time" value="${currentTime}" required> </div> </div> <button type="submit" style="margin-top: 15px;">添加记录</button> </form> <script> // 颜色选择器和十六进制输入框双向同步 const colorPicker = document.getElementById('color'); const colorHex = document.getElementById('colorHex'); const methodSelect = document.getElementById('method'); // 支付方式改变时自动设置对应颜色 methodSelect.addEventListener('change', function(e) { if (e.target.value === '支付宝') { colorPicker.value = '#1677FF'; colorHex.value = '#1677FF'; } else if (e.target.value === '微信') { colorPicker.value = '#09bb07'; colorHex.value = '#09bb07'; } }); // 颜色选择器改变时更新十六进制输入框 colorPicker.addEventListener('input', function(e) { colorHex.value = e.target.value; }); // 十六进制输入框改变时更新颜色选择器 colorHex.addEventListener('input', function(e) { const value = e.target.value; if (/^#[0-9A-Fa-f]{6}$/.test(value)) { colorPicker.value = value; } }); // 十六进制输入框失去焦点时验证格式 colorHex.addEventListener('blur', function(e) { const value = e.target.value; if (!/^#[0-9A-Fa-f]{6}$/.test(value) && value !== '') { e.target.value = colorPicker.value; } }); // 初始化十六进制输入框的值 colorHex.value = colorPicker.value; </script> </div> <div class="tips-section"> <div class="tips-header"> <h2>打赏记录 (${tips.length})</h2> <a href="/all" class="api-link" target="_blank">查看 JSON 数据</a> </div> ${tips.length === 0 ? '<div class="empty">暂无打赏记录</div>' : `<table class="tips-table"> <thead> <tr> <th>金额</th> <th>打赏人</th> <th>支付方式</th> <th>时间</th> <th>操作</th> </tr> </thead> <tbody> ${tips.map(tip => ` <tr> <td class="amount" style="color: ${tip.color}">¥${tip.amount}</td> <td class="person">${tip.person}</td> <td class="method">${tip.method}</td> <td class="time">${tip.time || formatTimeForDisplay(getCurrentShanghaiTime())}</td> <td><a href="/delete-tip?id=${tip.id}" class="delete-btn" onclick="return confirm('确定要删除这条记录吗?')">删除</a></td> </tr> `).join('')} </tbody> </table>` } </div> </div> </body> </html> `; }
|