keep-alive-24h / index.js
isididiidid's picture
Update index.js
51746f2 verified
const axios = require('axios');
const moment = require('moment-timezone');
const http = require('http');
const cron = require('node-cron');
const port = process.env.PORT || 7860;
// 保活网址列表(24小时访问周期)
const webpages = [
'https://huggingface.co/spaces/isididiidid/Cursor-To-OpenAI', // Cursor-To-OpenAI
'https://huggingface.co/spaces/isididiidid/cursor-ai-proxy', // cursor-ai-proxy
'https://huggingface.co/spaces/isididiidid/keep-alive-24h', // 保活服务
'https://isididiidid-getni.hf.space', // Gemini Balance
'https://isididiidid-gemini-balancre.hf.space', // Gemini Balance (短网址)
'https://isididiidid-hajimi.hf.space' // Hajimi
];
// 访问日志,用于显示详细信息
const accessLogs = {};
// 创建HTTP服务器
const createServer = () => {
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(generateStatusPage());
});
server.listen(port, () => {
console.log(`服务器启动,端口: ${port}`);
});
};
// 计算下次执行时间
function getNextExecutionTime() {
const now = moment().tz('Asia/Hong_Kong');
// 计算下一个24小时时间点
const nextExecution = moment().tz('Asia/Hong_Kong').add(24, 'hours').startOf('hour');
return nextExecution.format('YYYY-MM-DD HH:mm:ss');
}
// 获取服务器运行时间
let startTime = new Date();
function getUptime() {
const now = new Date();
const uptimeMs = now - startTime;
const days = Math.floor(uptimeMs / (24 * 60 * 60 * 1000));
const hours = Math.floor((uptimeMs % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
const minutes = Math.floor((uptimeMs % (60 * 60 * 1000)) / (60 * 1000));
const seconds = Math.floor((uptimeMs % (60 * 1000)) / 1000);
return `${days}${hours}小时 ${minutes}${seconds}秒`;
}
// 生成HTML状态页面
function generateStatusPage() {
const currentTime = moment().tz('Asia/Hong_Kong').format('YYYY-MM-DD HH:mm:ss');
let lastCheckTime = "从未检查";
if (Object.keys(accessLogs).length > 0) {
lastCheckTime = Object.values(accessLogs).sort((a, b) => b.timestamp - a.timestamp)[0].time;
}
// 生成访问记录卡片
let webpageCards = '';
for (const url of webpages) {
const log = accessLogs[url];
const status = log ? (log.status === 200 ? '成功' : '失败') : '等待检查';
const statusClass = log ? (log.status === 200 ? 'success' : 'error') : 'waiting';
const time = log ? log.time : '尚未检查';
// 从URL中提取空间名称
let spaceName;
if (url.includes('huggingface.co/spaces/')) {
const shortUrl = url.replace(/https?:\/\/(www\.)?huggingface\.co\/spaces\//, '');
spaceName = shortUrl.split('/').pop();
} else {
spaceName = url.split('/').pop().split('.')[0];
}
webpageCards += `
<div class="card ${statusClass}">
<div class="card-icon">
${log && log.status === 200 ?
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>' :
(log ? '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>' :
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>')
}
</div>
<div class="card-content">
<h3>${spaceName}</h3>
<p class="url"><a href="${url}" target="_blank">${url}</a></p>
<div class="status-indicator">
<span class="status-dot ${statusClass}"></span>
<span class="status-text">${status}</span>
</div>
<p class="time">上次访问: ${time}</p>
</div>
</div>
`;
}
return `
<!DOCTYPE html>
<html lang="zh" data-theme="light">
<head>
<title>HuggingFace 空间保活服务</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary-color: #5546ff;
--success-color: #10b981;
--error-color: #ef4444;
--waiting-color: #f59e0b;
--text-color: #1f2937;
--text-secondary: #6b7280;
--bg-color: #f9fafb;
--card-bg: #ffffff;
--border-color: #e5e7eb;
--hover-color: #f3f4f6;
--shadow-color: rgba(0, 0, 0, 0.1);
}
[data-theme="dark"] {
--primary-color: #818cf8;
--success-color: #34d399;
--error-color: #f87171;
--waiting-color: #fbbf24;
--text-color: #f9fafb;
--text-secondary: #d1d5db;
--bg-color: #111827;
--card-bg: #1f2937;
--border-color: #374151;
--hover-color: #374151;
--shadow-color: rgba(0, 0, 0, 0.3);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
line-height: 1.5;
}
.container {
max-width: 1000px;
margin: 0 auto;
padding: 2rem 1rem;
}
.header {
text-align: center;
margin-bottom: 2.5rem;
position: relative;
}
.header h1 {
font-size: 2.2rem;
font-weight: 700;
margin-bottom: 0.5rem;
background: linear-gradient(90deg, var(--primary-color), #8b5cf6);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
.header p {
color: var(--text-secondary);
font-size: 1.1rem;
}
.status-badge {
display: inline-flex;
align-items: center;
padding: 0.5rem 1rem;
background-color: var(--success-color);
color: white;
border-radius: 9999px;
font-weight: 600;
margin: 1rem 0;
box-shadow: 0 2px 5px rgba(16, 185, 129, 0.2);
}
.status-badge svg {
margin-right: 0.5rem;
}
.info-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1rem;
margin-bottom: 2rem;
}
.info-card {
background-color: var(--card-bg);
border-radius: 0.75rem;
padding: 1.25rem;
box-shadow: 0 1px 3px var(--shadow-color);
border: 1px solid var(--border-color);
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.info-card h3 {
color: var(--text-secondary);
font-size: 0.875rem;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.info-card p {
font-size: 1.25rem;
font-weight: 600;
}
.cards-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1.5rem;
margin-top: 2rem;
}
.card {
background-color: var(--card-bg);
border-radius: 0.75rem;
padding: 1.5rem;
box-shadow: 0 1px 3px var(--shadow-color);
border: 1px solid var(--border-color);
display: flex;
gap: 1rem;
transition: transform 0.2s ease, box-shadow 0.2s ease, background-color 0.3s ease;
}
.card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 6px var(--shadow-color);
}
.card.success {
border-left: 4px solid var(--success-color);
}
.card.error {
border-left: 4px solid var(--error-color);
}
.card.waiting {
border-left: 4px solid var(--waiting-color);
}
.card-icon {
color: var(--text-secondary);
}
.card.success .card-icon {
color: var(--success-color);
}
.card.error .card-icon {
color: var(--error-color);
}
.card.waiting .card-icon {
color: var(--waiting-color);
}
.card-content {
flex: 1;
}
.card h3 {
font-size: 1.25rem;
font-weight: 600;
margin-bottom: 0.25rem;
}
.url {
color: var(--text-secondary);
font-size: 0.875rem;
margin-bottom: 1rem;
word-break: break-all;
}
.url a {
color: var(--primary-color);
text-decoration: none;
}
.url a:hover {
text-decoration: underline;
}
.status-indicator {
display: flex;
align-items: center;
margin-bottom: 0.5rem;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 0.5rem;
}
.status-dot.success {
background-color: var(--success-color);
}
.status-dot.error {
background-color: var(--error-color);
}
.status-dot.waiting {
background-color: var(--waiting-color);
}
.status-text {
font-weight: 500;
}
.time {
color: var(--text-secondary);
font-size: 0.875rem;
}
.section-title {
font-size: 1.5rem;
font-weight: 600;
margin-bottom: 1rem;
margin-top: 2.5rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.footer {
margin-top: 3rem;
text-align: center;
padding: 1.5rem 0;
color: var(--text-secondary);
font-size: 0.875rem;
border-top: 1px solid var(--border-color);
}
.footer p {
margin: 0.25rem 0;
}
.controls {
position: absolute;
top: 0;
right: 0;
display: flex;
gap: 0.5rem;
}
.theme-switch {
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: 0.5rem;
padding: 0.5rem;
display: flex;
gap: 0.5rem;
}
.control-btn {
background: none;
border: none;
cursor: pointer;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-weight: 500;
color: var(--text-secondary);
display: flex;
align-items: center;
gap: 0.25rem;
}
.control-btn.active {
background-color: var(--primary-color);
color: white;
}
.control-btn svg {
width: 16px;
height: 16px;
}
@media (max-width: 640px) {
.header h1 {
font-size: 1.8rem;
}
.info-grid {
grid-template-columns: 1fr;
}
.controls {
position: relative;
flex-direction: column;
align-items: center;
margin-top: 1rem;
width: 100%;
}
.theme-switch {
width: 100%;
justify-content: center;
}
}
</style>
</head>
<body>
<div class="container">
<header class="header">
<div class="controls">
<div class="theme-switch">
<button class="control-btn active" id="light-mode" onclick="setTheme('light')">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="5"></circle>
<line x1="12" y1="1" x2="12" y2="3"></line>
<line x1="12" y1="21" x2="12" y2="23"></line>
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
<line x1="1" y1="12" x2="3" y2="12"></line>
<line x1="21" y1="12" x2="23" y2="12"></line>
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
</svg>
</button>
<button class="control-btn" id="dark-mode" onclick="setTheme('dark')">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
</svg>
</button>
</div>
</div>
<h1>HuggingFace 空间保活服务</h1>
<p>保持你的 HuggingFace Spaces 应用 24 小时在线</p>
<div class="status-badge">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
<polyline points="22 4 12 14.01 9 11.01"></polyline>
</svg>
<span>服务运行中</span>
</div>
</header>
<div class="info-grid">
<div class="info-card">
<h3>当前时间</h3>
<p id="current-time">${currentTime}</p>
</div>
<div class="info-card">
<h3>上次检查</h3>
<p>${lastCheckTime}</p>
</div>
<div class="info-card">
<h3>下次检查</h3>
<p>${getNextExecutionTime()}</p>
</div>
<div class="info-card">
<h3>运行时间</h3>
<p id="uptime">${getUptime()}</p>
</div>
</div>
<h2 class="section-title">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
</svg>
<span>监控状态</span>
</h2>
<div class="cards-grid">
${webpageCards}
</div>
</div>
<footer class="footer">
<p>HuggingFace 空间保活服务 · 由 isididiidid 提供</p>
<p>© ${new Date().getFullYear()} · 基于 Hugging Face Spaces</p>
</footer>
<script>
// 设置主题
function setTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
// 更新主题按钮
document.querySelectorAll('.theme-switch .control-btn').forEach(btn => {
btn.classList.remove('active');
});
if (theme === 'light') {
document.getElementById('light-mode').classList.add('active');
} else {
document.getElementById('dark-mode').classList.add('active');
}
// 存储偏好设置
localStorage.setItem('preferred-theme', theme);
}
// 动态时间更新
function updateTime() {
const now = new Date();
// 转换为香港时间
const options = {
timeZone: 'Asia/Hong_Kong',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
};
const formatter = new Intl.DateTimeFormat('zh-CN', options);
let timeString = formatter.format(now);
// 格式化为 YYYY-MM-DD HH:mm:ss
timeString = timeString.replace(/(\d{4})\/(\d{2})\/(\d{2})/, '$1-$2-$3');
document.getElementById('current-time').textContent = timeString;
// 更新运行时间
const uptimeMs = now - ${startTime.getTime()};
const days = Math.floor(uptimeMs / (24 * 60 * 60 * 1000));
const hours = Math.floor((uptimeMs % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
const minutes = Math.floor((uptimeMs % (60 * 60 * 1000)) / (60 * 1000));
const seconds = Math.floor((uptimeMs % (60 * 1000)) / 1000);
document.getElementById('uptime').textContent = days + '天 ' + hours + '小时 ' + minutes + '分 ' + seconds + '秒';
}
// 加载保存的偏好设置或使用默认值
function loadPreferences() {
// 加载主题偏好设置
const savedTheme = localStorage.getItem('preferred-theme') || 'light';
setTheme(savedTheme);
// 检查系统是否偏好深色模式
if (!localStorage.getItem('preferred-theme') &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches) {
setTheme('dark');
}
// 监听系统主题变化
if (window.matchMedia) {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
if (!localStorage.getItem('preferred-theme')) {
setTheme(e.matches ? 'dark' : 'light');
}
});
}
}
// 每秒更新时间
setInterval(updateTime, 1000);
// 初始化
loadPreferences();
updateTime(); // 立即运行
</script>
</body>
</html>
`;
}
// 访问函数
async function access(url) {
try {
const response = await axios.get(url);
const currentTime = moment().tz('Asia/Hong_Kong').format('YYYY-MM-DD HH:mm:ss');
accessLogs[url] = { status: response.status, time: currentTime, timestamp: Date.now() };
console.log(`${currentTime} 成功访问: ${url} - 状态: ${response.status}`);
} catch (error) {
const currentTime = moment().tz('Asia/Hong_Kong').format('YYYY-MM-DD HH:mm:ss');
accessLogs[url] = { status: error.response ? error.response.status : 0, time: currentTime, timestamp: Date.now() };
console.error(`${currentTime} 访问失败 ${url}, 错误: ${error.message}`);
}
}
// 批量访问所有网址
async function batchVisit() {
console.log(`${moment().tz('Asia/Hong_Kong').format('YYYY-MM-DD HH:mm:ss')} 开始24小时访问周期...`);
for (let url of webpages) {
await access(url);
}
}
// 重启函数
const restart = () => {
console.log(`${moment().tz('Asia/Hong_Kong').format('YYYY-MM-DD HH:mm:ss')} 服务器重启中...`);
process.exit(1); // 退出进程,Docker会自动重启
};
// 启动服务器
createServer();
// 定时任务:每24小时执行一次
cron.schedule('0 0 */24 * * *', async () => {
await batchVisit(); // 先访问所有网址
restart(); // 然后重启服务
});
// 启动时立即运行一次
batchVisit().catch(console.error);