n/chit-chatu/mc838 · 10개월 전
회원가입 로그인
n/chit-chat · 10개월 전 · 편집됨 · 조회 1186회
u/mc838다이아몬드

GitHub 暂停 Actions 的规则

GitHub 暂停 Actions 的规则

条件 说明
60 天无活动 仓库没有"有意义的活动"
判断标准 push、issue、PR、release 等人为操作

我想到了一个方法:通过外部 Webhook 调用 GitHub API 触发 workflow_dispatch 被视为外部事件

佬们有更好的方法吗?

这个工具可以自动保持你的 GitHub 仓库活跃,防止仓库因为长期不活动被 GitHub 标记为"不活跃"或归档。

它会每月自动更新你指定的仓库,让 GitHub 认为这些仓库还在使用中。

需要配置的变量

一共需要配置 3 个东西:

变量名 类型 说明
KV KV 命名空间 绑定创建的KV空间 存储执行记录
PASSWORD Secret 登录密码
CONFIG Secret 仓库配置

CONFIG(仓库配置)

格式说明

[
  {
    "owner": "GitHub用户名",
    "token": "GitHub Token",
    "repos": ["仓库1", "仓库2", "仓库3"]
  }
]

单账号示例

假设:

  • 用户名:zhangsan
  • Token:ghp_abc123456789
  • 仓库:my-blog 和 my-project
[{"owner":"zhangsan","token":"ghp_abc123456789","repos":["my-blog","my-project"]}]

多账号示例

[{"owner":"zhangsan","token":"ghp_abc123","repos":["blog","project"]},{"owner":"lisi","token":"ghp_xyz789","repos":["app","tool","demo"]}]

Worker代码

export default {
  async scheduled(event, env, ctx) {
    const results = await keepAliveAll(env);
    await saveLog(env, results);
  },

  async fetch(request, env, ctx) {
    const url = new URL(request.url);

    // 主页面
    if (url.pathname === '/') {
      return new Response(getHTML(), {
        headers: { 'Content-Type': 'text/html; charset=utf-8' }
      });
    }

    // 登录接口
    if (url.pathname === '/api/login' && request.method === 'POST') {
      try {
        const { password } = await request.json();
        if (password === env.PASSWORD) {
          const token = crypto.randomUUID();
          await env.KV.put(`session:${token}`, '1', { expirationTtl: 86400 });
          return Response.json({ success: true, token });
        }
        return Response.json({ error: '密码错误' }, { status: 401 });
      } catch (e) {
        return Response.json({ error: '请求格式错误' }, { status: 400 });
      }
    }

    // 验证 Token
    const authHeader = request.headers.get('Authorization') || '';
    const token = authHeader.replace('Bearer ', '');
    
    if (!token) {
      return Response.json({ error: '未提供Token' }, { status: 401 });
    }
    
    const session = await env.KV.get(`session:${token}`);
    if (!session) {
      return Response.json({ error: '未登录或会话已过期' }, { status: 401 });
    }

    // 执行 Keep Alive
    if (url.pathname === '/api/run') {
      try {
        const results = await keepAliveAll(env);
        await saveLog(env, results);
        return Response.json(results);
      } catch (e) {
        return Response.json({ error: e.message }, { status: 500 });
      }
    }

    // 获取仓库状态
    if (url.pathname === '/api/status') {
      try {
        const status = await getReposStatus(env);
        return Response.json(status);
      } catch (e) {
        return Response.json({ error: e.message }, { status: 500 });
      }
    }

    // 获取执行记录
    if (url.pathname === '/api/logs') {
      try {
        const logs = await getLogs(env);
        return Response.json(logs);
      } catch (e) {
        return Response.json({ error: e.message }, { status: 500 });
      }
    }

    // 清空记录
    if (url.pathname === '/api/logs/clear' && request.method === 'POST') {
      try {
        await clearLogs(env);
        return Response.json({ success: true });
      } catch (e) {
        return Response.json({ error: e.message }, { status: 500 });
      }
    }

    // 登出
    if (url.pathname === '/api/logout' && request.method === 'POST') {
      await env.KV.delete(`session:${token}`);
      return Response.json({ success: true });
    }

    return Response.json({ error: 'Not Found' }, { status: 404 });
  }
};

// ============ Keep Alive 核心逻辑 ============

async function keepAliveAll(env) {
  const accounts = JSON.parse(env.CONFIG);
  const results = [];

  for (const { owner, token, repos } of accounts) {
    for (const repo of repos) {
      const start = Date.now();
      try {
        await keepAlive(token, owner, repo);
        results.push({
          repo: `${owner}/${repo}`,
          status: 'success',
          time: Date.now() - start
        });
      } catch (e) {
        results.push({
          repo: `${owner}/${repo}`,
          status: 'error',
          error: e.message,
          time: Date.now() - start
        });
      }
      await sleep(1000);
    }
  }

  return {
    total: results.length,
    success: results.filter(r => r.status === 'success').length,
    failed: results.filter(r => r.status === 'error').length,
    timestamp: new Date().toISOString(),
    results
  };
}

async function keepAlive(token, owner, repo) {
  const apiUrl = `https://api.github.com/repos/${owner}/${repo}/contents/.keep-alive`;
  const headers = {
    'Authorization': `token ${token}`,
    'Content-Type': 'application/json',
    'User-Agent': 'CF-Worker'
  };

  const uuid = crypto.randomUUID();
  const content = btoa(`${uuid}\n${new Date().toISOString()}`);

  let sha = null;
  const getRes = await fetch(apiUrl, { headers });
  if (getRes.ok) {
    sha = (await getRes.json()).sha;
  }

  const putRes = await fetch(apiUrl, {
    method: 'PUT',
    headers,
    body: JSON.stringify({
      message: `keep alive: ${uuid.slice(0, 8)}`,
      content,
      sha
    })
  });

  if (!putRes.ok) {
    const errText = await putRes.text();
    throw new Error(errText.slice(0, 100));
  }
}

// ============ 仓库状态查询 ============

async function getReposStatus(env) {
  const accounts = JSON.parse(env.CONFIG);
  const results = [];

  for (const { owner, token, repos } of accounts) {
    for (const repo of repos) {
      try {
        const status = await getRepoStatus(token, owner, repo);
        results.push(status);
      } catch (e) {
        results.push({
          repo: `${owner}/${repo}`,
          error: e.message
        });
      }
      await sleep(300);
    }
  }

  return {
    timestamp: new Date().toISOString(),
    repos: results
  };
}

async function getRepoStatus(token, owner, repo) {
  const headers = {
    'Authorization': `token ${token}`,
    'User-Agent': 'CF-Worker'
  };

  const repoRes = await fetch(`https://api.github.com/repos/${owner}/${repo}`, { headers });
  if (!repoRes.ok) throw new Error('仓库不存在或无权限');
  const repoData = await repoRes.json();

  const commitsRes = await fetch(
    `https://api.github.com/repos/${owner}/${repo}/commits?per_page=1`,
    { headers }
  );
  
  let lastCommit = null;
  if (commitsRes.ok) {
    const commits = await commitsRes.json();
    if (commits.length > 0) {
      lastCommit = {
        sha: commits[0].sha.slice(0, 7),
        message: commits[0].commit.message.slice(0, 50),
        date: commits[0].commit.committer.date
      };
    }
  }

  const lastActivity = new Date(repoData.pushed_at);
  const daysSinceActivity = Math.floor((Date.now() - lastActivity) / (1000 * 60 * 60 * 24));

  return {
    repo: `${owner}/${repo}`,
    private: repoData.private,
    archived: repoData.archived,
    disabled: repoData.disabled,
    lastPush: repoData.pushed_at,
    daysSinceActivity,
    status: daysSinceActivity > 50 ? 'warning' : daysSinceActivity > 30 ? 'notice' : 'active',
    lastCommit
  };
}

// ============ KV 日志存储 ============

async function saveLog(env, result) {
  const key = `log:${Date.now()}`;
  await env.KV.put(key, JSON.stringify(result), { expirationTtl: 15552000 });
}

async function getLogs(env) {
  const list = await env.KV.list({ prefix: 'log:' });
  const logs = [];
  const keys = list.keys.sort((a, b) => b.name.localeCompare(a.name)).slice(0, 50);

  for (const key of keys) {
    const value = await env.KV.get(key.name);
    if (value) logs.push(JSON.parse(value));
  }

  return { total: list.keys.length, showing: logs.length, logs };
}

async function clearLogs(env) {
  const list = await env.KV.list({ prefix: 'log:' });
  for (const key of list.keys) {
    await env.KV.delete(key.name);
  }
}

function sleep(ms) {
  return new Promise(r => setTimeout(r, ms));
}

// ============ 完整 HTML 页面 ============

function getHTML() {
  return `<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GitHub Keep Alive</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
      min-height: 100vh;
      padding: 20px;
    }

    /* 登录页样式 */
    .login-page {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: calc(100vh - 40px);
    }

    .login-container {
      width: 100%;
      max-width: 400px;
    }

    .login-card {
      background: rgba(255, 255, 255, 0.05);
      border-radius: 20px;
      padding: 40px;
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.1);
      text-align: center;
    }

    .logo { font-size: 4em; margin-bottom: 20px; }

    .login-card h1 {
      color: #fff;
      font-size: 1.8em;
      margin-bottom: 8px;
    }

    .login-card > p {
      color: #8892b0;
      margin-bottom: 30px;
    }

    .input-wrapper {
      position: relative;
      margin-bottom: 20px;
    }

    .input-wrapper input {
      width: 100%;
      padding: 16px 20px 16px 50px;
      border: 2px solid rgba(255, 255, 255, 0.1);
      border-radius: 12px;
      background: rgba(0, 0, 0, 0.3);
      color: #fff;
      font-size: 16px;
      transition: all 0.3s;
    }

    .input-wrapper input:focus {
      outline: none;
      border-color: #64ffda;
    }

    .input-wrapper .icon {
      position: absolute;
      left: 18px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 1.2em;
    }

    .btn-login {
      width: 100%;
      padding: 16px;
      border: none;
      border-radius: 12px;
      background: linear-gradient(135deg, #64ffda 0%, #48c9b0 100%);
      color: #1a1a2e;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s;
    }

    .btn-login:hover {
      transform: translateY(-2px);
      box-shadow: 0 10px 30px rgba(100, 255, 218, 0.3);
    }

    .btn-login:disabled {
      opacity: 0.6;
      cursor: not-allowed;
      transform: none;
    }

    .error-msg {
      background: rgba(255, 107, 107, 0.1);
      border: 1px solid rgba(255, 107, 107, 0.3);
      color: #ff6b6b;
      padding: 12px;
      border-radius: 10px;
      margin-bottom: 20px;
      display: none;
      font-size: 14px;
    }

    .error-msg.show { display: block; }

    /* 主面板样式 */
    .dashboard-page { display: none; }

    .container { max-width: 900px; margin: 0 auto; }

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 25px 0;
    }

    .header-left h1 {
      color: #fff;
      font-size: 1.8em;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .header-left p {
      color: #8892b0;
      font-size: 0.9em;
      margin-top: 5px;
    }

    .btn-logout {
      padding: 10px 20px;
      border: 1px solid rgba(255, 107, 107, 0.5);
      border-radius: 8px;
      background: transparent;
      color: #ff6b6b;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.3s;
    }

    .btn-logout:hover {
      background: rgba(255, 107, 107, 0.1);
    }

    .card {
      background: rgba(255, 255, 255, 0.05);
      border-radius: 16px;
      padding: 25px;
      margin-bottom: 20px;
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.1);
    }

    .btn-group {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }

    .btn {
      padding: 14px 28px;
      border: none;
      border-radius: 10px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .btn-primary {
      background: linear-gradient(135deg, #64ffda 0%, #48c9b0 100%);
      color: #1a1a2e;
    }

    .btn-secondary {
      background: rgba(255, 255, 255, 0.1);
      color: #fff;
    }

    .btn-danger {
      background: rgba(255, 107, 107, 0.15);
      color: #ff6b6b;
    }

    .btn:hover { transform: translateY(-2px); }
    .btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }

    .tabs {
      display: flex;
      gap: 5px;
      margin-bottom: 20px;
      background: rgba(0, 0, 0, 0.2);
      padding: 5px;
      border-radius: 10px;
    }

    .tab {
      flex: 1;
      padding: 12px;
      border: none;
      background: transparent;
      color: #8892b0;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      border-radius: 8px;
      transition: all 0.3s;
    }

    .tab.active {
      background: rgba(100, 255, 218, 0.2);
      color: #64ffda;
    }

    .tab-content { display: none; }
    .tab-content.active { display: block; }

    .stats {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;
      margin-bottom: 20px;
    }

    .stat-item {
      background: rgba(0, 0, 0, 0.2);
      padding: 20px;
      border-radius: 12px;
      text-align: center;
    }

    .stat-item .number {
      font-size: 2em;
      font-weight: 700;
    }

    .stat-item .label {
      color: #8892b0;
      font-size: 0.85em;
      margin-top: 5px;
    }

    .stat-item.success .number { color: #64ffda; }
    .stat-item.failed .number { color: #ff6b6b; }
    .stat-item.total .number { color: #ffd93d; }

    .list {
      max-height: 450px;
      overflow-y: auto;
    }

    .list-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 14px 16px;
      background: rgba(0, 0, 0, 0.2);
      border-radius: 10px;
      margin-bottom: 8px;
      transition: all 0.3s;
    }

    .list-item:hover { background: rgba(0, 0, 0, 0.3); }

    .repo-info {
      display: flex;
      flex-direction: column;
      gap: 4px;
    }

    .repo-name {
      color: #fff;
      font-weight: 500;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .repo-name a {
      color: #64ffda;
      text-decoration: none;
    }

    .repo-name a:hover { text-decoration: underline; }

    .repo-meta {
      font-size: 0.8em;
      color: #5a6a8a;
    }

    .badge {
      padding: 5px 12px;
      border-radius: 20px;
      font-size: 0.8em;
      font-weight: 600;
    }

    .badge.success { background: rgba(100, 255, 218, 0.2); color: #64ffda; }
    .badge.error { background: rgba(255, 107, 107, 0.2); color: #ff6b6b; }
    .badge.warning { background: rgba(255, 193, 7, 0.2); color: #ffc107; }
    .badge.notice { background: rgba(255, 152, 0, 0.2); color: #ff9800; }
    .badge.active { background: rgba(100, 255, 218, 0.2); color: #64ffda; }
    .badge.private { background: rgba(156, 39, 176, 0.2); color: #ce93d8; font-size: 0.7em; }

    .loading-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.7);
      display: none;
      align-items: center;
      justify-content: center;
      z-index: 1000;
    }

    .loading-overlay.show { display: flex; }

    .loading-box {
      background: rgba(255, 255, 255, 0.1);
      padding: 40px;
      border-radius: 16px;
      text-align: center;
    }

    .spinner {
      width: 50px;
      height: 50px;
      border: 3px solid rgba(100, 255, 218, 0.2);
      border-top-color: #64ffda;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin: 0 auto 15px;
    }

    @keyframes spin { to { transform: rotate(360deg); } }

    .loading-box p { color: #8892b0; }

    .empty {
      text-align: center;
      padding: 50px;
      color: #5a6a8a;
    }

    .empty-icon {
      font-size: 3em;
      margin-bottom: 15px;
    }

    .timestamp {
      text-align: center;
      color: #5a6a8a;
      font-size: 0.85em;
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px solid rgba(255, 255, 255, 0.05);
    }

    .log-item {
      background: rgba(0, 0, 0, 0.2);
      border-radius: 10px;
      margin-bottom: 10px;
      overflow: hidden;
    }

    .log-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 14px 16px;
      cursor: pointer;
      transition: background 0.3s;
    }

    .log-header:hover { background: rgba(0, 0, 0, 0.2); }

    .log-time { color: #fff; font-size: 0.95em; }

    .log-summary {
      display: flex;
      gap: 15px;
      font-size: 0.85em;
    }

    .log-summary span { color: #5a6a8a; }
    .log-summary .s-success { color: #64ffda; }
    .log-summary .s-failed { color: #ff6b6b; }

    .log-details {
      display: none;
      padding: 0 16px 16px;
      border-top: 1px solid rgba(255, 255, 255, 0.05);
    }

    .log-details.show { display: block; }
    .log-details .list-item { margin-top: 8px; }

    .logs-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      padding-bottom: 15px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    }

    .logs-header span { color: #8892b0; font-size: 0.9em; }

    .status-badges {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    ::-webkit-scrollbar { width: 6px; }
    ::-webkit-scrollbar-track { background: rgba(0, 0, 0, 0.2); border-radius: 3px; }
    ::-webkit-scrollbar-thumb { background: rgba(100, 255, 218, 0.3); border-radius: 3px; }

    @media (max-width: 600px) {
      .header { flex-direction: column; gap: 15px; text-align: center; }
      .header-left h1 { font-size: 1.5em; justify-content: center; }
      .btn-group { flex-direction: column; }
      .btn { justify-content: center; }
      .stats { grid-template-columns: 1fr; }
      .list-item { flex-direction: column; align-items: flex-start; gap: 10px; }
      .log-header { flex-direction: column; align-items: flex-start; gap: 8px; }
      .status-badges { margin-top: 8px; }
    }
  </style>
</head>
<body>
  <!-- 登录页 -->
  <div class="login-page" id="loginPage">
    <div class="login-container">
      <div class="login-card">
        <div class="logo">🚀</div>
        <h1>GitHub Keep Alive</h1>
        <p>请输入密码登录管理面板</p>
        
        <div class="error-msg" id="loginError"></div>
        
        <form id="loginForm">
          <div class="input-wrapper">
            <span class="icon">🔑</span>
            <input type="password" id="passwordInput" placeholder="请输入访问密码" autofocus>
          </div>
          <button type="submit" class="btn-login" id="loginBtn">登 录</button>
        </form>
      </div>
    </div>
  </div>

  <!-- 主面板 -->
  <div class="dashboard-page" id="dashboardPage">
    <div class="container">
      <div class="header">
        <div class="header-left">
          <h1>🚀 GitHub Keep Alive</h1>
          <p>自动保持仓库活跃,防止被 GitHub 归档</p>
        </div>
        <button class="btn-logout" id="logoutBtn">退出登录</button>
      </div>

      <div class="card">
        <div class="btn-group">
          <button class="btn btn-primary" id="runBtn">
            <span>▶</span> 执行 Keep Alive
          </button>
          <button class="btn btn-secondary" id="statusBtn">
            <span>📊</span> 仓库状态
          </button>
          <button class="btn btn-secondary" id="logsBtn">
            <span>📋</span> 执行记录
          </button>
        </div>
      </div>

      <div class="card">
        <div class="tabs">
          <button class="tab active" data-tab="result">执行结果</button>
          <button class="tab" data-tab="status">仓库状态</button>
          <button class="tab" data-tab="logs">历史记录</button>
        </div>

        <div class="tab-content active" id="tab-result">
          <div class="empty" id="resultEmpty">
            <div class="empty-icon">📦</div>
            <p>点击「执行 Keep Alive」开始</p>
          </div>
          <div id="resultContent"></div>
        </div>

        <div class="tab-content" id="tab-status">
          <div class="empty" id="statusEmpty">
            <div class="empty-icon">📊</div>
            <p>点击「仓库状态」查看各仓库详情</p>
          </div>
          <div id="statusContent"></div>
        </div>

        <div class="tab-content" id="tab-logs">
          <div class="empty" id="logsEmpty">
            <div class="empty-icon">📋</div>
            <p>点击「执行记录」查看历史</p>
          </div>
          <div id="logsContent"></div>
        </div>
      </div>
    </div>
  </div>

  <!-- 加载遮罩 -->
  <div class="loading-overlay" id="loadingOverlay">
    <div class="loading-box">
      <div class="spinner"></div>
      <p id="loadingText">加载中...</p>
    </div>
  </div>

  <script>
    // ============ 全局变量 ============
    let authToken = localStorage.getItem('authToken');

    // ============ 初始化 ============
    document.addEventListener('DOMContentLoaded', function() {
      if (authToken) {
        showDashboard();
      } else {
        showLogin();
      }
      bindEvents();
    });

    // ============ 绑定事件 ============
    function bindEvents() {
      // 登录表单
      document.getElementById('loginForm').addEventListener('submit', handleLogin);
      
      // 登出按钮
      document.getElementById('logoutBtn').addEventListener('click', handleLogout);
      
      // 功能按钮
      document.getElementById('runBtn').addEventListener('click', handleRun);
      document.getElementById('statusBtn').addEventListener('click', handleStatus);
      document.getElementById('logsBtn').addEventListener('click', handleLogs);
      
      // Tab 切换
      document.querySelectorAll('.tab').forEach(tab => {
        tab.addEventListener('click', function() {
          switchTab(this.dataset.tab);
        });
      });
    }

    // ============ 页面切换 ============
    function showLogin() {
      document.getElementById('loginPage').style.display = 'flex';
      document.getElementById('dashboardPage').style.display = 'none';
    }

    function showDashboard() {
      document.getElementById('loginPage').style.display = 'none';
      document.getElementById('dashboardPage').style.display = 'block';
    }

    // ============ 登录处理 ============
    async function handleLogin(e) {
      e.preventDefault();
      
      const password = document.getElementById('passwordInput').value;
      const loginBtn = document.getElementById('loginBtn');
      const errorEl = document.getElementById('loginError');
      
      if (!password) {
        showLoginError('请输入密码');
        return;
      }
      
      loginBtn.disabled = true;
      loginBtn.textContent = '登录中...';
      errorEl.classList.remove('show');
      
      try {
        const res = await fetch('/api/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ password })
        });
        
        const data = await res.json();
        
        if (!res.ok) {
          throw new Error(data.error || '登录失败');
        }
        
        authToken = data.token;
        localStorage.setItem('authToken', authToken);
        showDashboard();
        
      } catch (err) {
        showLoginError(err.message);
      } finally {
        loginBtn.disabled = false;
        loginBtn.textContent = '登 录';
      }
    }

    function showLoginError(msg) {
      const el = document.getElementById('loginError');
      el.textContent = msg;
      el.classList.add('show');
    }

    // ============ 登出处理 ============
    async function handleLogout() {
      showLoading('正在登出...');
      
      try {
        await fetch('/api/logout', {
          method: 'POST',
          headers: { 'Authorization': 'Bearer ' + authToken }
        });
      } catch (e) {
        // 忽略错误
      }
      
      authToken = null;
      localStorage.removeItem('authToken');
      hideLoading();
      showLogin();
      
      // 清空输入框
      document.getElementById('passwordInput').value = '';
    }

    // ============ API 请求 ============
    async function apiRequest(url, loadingText) {
      showLoading(loadingText);
      
      try {
        const res = await fetch(url, {
          headers: { 'Authorization': 'Bearer ' + authToken }
        });
        
        const data = await res.json();
        
        if (!res.ok) {
          if (res.status === 401) {
            // Token 过期,重新登录
            authToken = null;
            localStorage.removeItem('authToken');
            showLogin();
            throw new Error('会话已过期,请重新登录');
          }
          throw new Error(data.error || '请求失败');
        }
        
        return data;
        
      } catch (err) {
        alert('错误: ' + err.message);
        return null;
      } finally {
        hideLoading();
      }
    }

    async function apiPost(url, loadingText) {
      showLoading(loadingText);
      
      try {
        const res = await fetch(url, {
          method: 'POST',
          headers: { 'Authorization': 'Bearer ' + authToken }
        });
        
        const data = await res.json();
        
        if (!res.ok) {
          if (res.status === 401) {
            authToken = null;
            localStorage.removeItem('authToken');
            showLogin();
            throw new Error('会话已过期,请重新登录');
          }
          throw new Error(data.error || '请求失败');
        }
        
        return data;
        
      } catch (err) {
        alert('错误: ' + err.message);
        return null;
      } finally {
        hideLoading();
      }
    }

    // ============ 执行 Keep Alive ============
    async function handleRun() {
      const data = await apiRequest('/api/run', '正在执行 Keep Alive...');
      if (!data) return;
      
      switchTab('result');
      document.getElementById('resultEmpty').style.display = 'none';
      document.getElementById('resultContent').innerHTML = renderResult(data);
    }

    function renderResult(data) {
      return \`
        <div class="stats">
          <div class="stat-item total">
            <div class="number">\${data.total}</div>
            <div class="label">总计</div>
          </div>
          <div class="stat-item success">
            <div class="number">\${data.success}</div>
            <div class="label">成功</div>
          </div>
          <div class="stat-item failed">
            <div class="number">\${data.failed}</div>
            <div class="label">失败</div>
          </div>
        </div>
        <div class="list">
          \${data.results.map(item => \`
            <div class="list-item">
              <div class="repo-info">
                <span class="repo-name">
                  <a href="https://github.com/\${item.repo}" target="_blank">\${item.repo}</a>
                </span>
                <span class="repo-meta">\${item.time}ms\${item.error ? ' · ' + item.error.substring(0, 50) : ''}</span>
              </div>
              <span class="badge \${item.status}">\${item.status === 'success' ? '✓ 成功' : '✗ 失败'}</span>
            </div>
          \`).join('')}
        </div>
        <div class="timestamp">执行时间: \${new Date(data.timestamp).toLocaleString()}</div>
      \`;
    }

    // ============ 仓库状态 ============
    async function handleStatus() {
      const data = await apiRequest('/api/status', '正在获取仓库状态...');
      if (!data) return;
      
      switchTab('status');
      document.getElementById('statusEmpty').style.display = 'none';
      document.getElementById('statusContent').innerHTML = renderStatus(data);
    }

    function renderStatus(data) {
      const statusMap = { active: '活跃', notice: '注意', warning: '警告' };
      
      return \`
        <div class="list">
          \${data.repos.map(repo => {
            if (repo.error) {
              return \`
                <div class="list-item">
                  <span class="repo-name">\${repo.repo}</span>
                  <span class="badge error">错误: \${repo.error}</span>
                </div>
              \`;
            }
            return \`
              <div class="list-item">
                <div class="repo-info">
                  <span class="repo-name">
                    <a href="https://github.com/\${repo.repo}" target="_blank">\${repo.repo}</a>
                    \${repo.private ? '<span class="badge private">私有</span>' : ''}
                  </span>
                  <span class="repo-meta">
                    最后活动: \${new Date(repo.lastPush).toLocaleDateString()}
                    \${repo.lastCommit ? ' · ' + repo.lastCommit.message : ''}
                  </span>
                </div>
                <div class="status-badges">
                  <span class="badge \${repo.status}">\${repo.daysSinceActivity} 天前</span>
                  <span class="badge \${repo.status}">\${statusMap[repo.status]}</span>
                </div>
              </div>
            \`;
          }).join('')}
        </div>
        <div class="timestamp">更新时间: \${new Date(data.timestamp).toLocaleString()}</div>
      \`;
    }

    // ============ 执行记录 ============
    async function handleLogs() {
      const data = await apiRequest('/api/logs', '正在加载执行记录...');
      if (!data) return;
      
      switchTab('logs');
      document.getElementById('logsEmpty').style.display = 'none';
      document.getElementById('logsContent').innerHTML = renderLogs(data);
    }

    function renderLogs(data) {
      if (data.logs.length === 0) {
        return '<div class="empty"><div class="empty-icon">📭</div><p>暂无执行记录</p></div>';
      }
      
      return \`
        <div class="logs-header">
          <span>共 \${data.total} 条记录,显示最近 \${data.showing} 条</span>
          <button class="btn btn-danger" onclick="handleClearLogs()">🗑 清空记录</button>
        </div>
        <div class="list">
          \${data.logs.map((log, index) => \`
            <div class="log-item">
              <div class="log-header" onclick="toggleLogDetail(\${index})">
                <span class="log-time">\${new Date(log.timestamp).toLocaleString()}</span>
                <div class="log-summary">
                  <span>总计: \${log.total}</span>
                  <span class="s-success">成功: \${log.success}</span>
                  <span class="s-failed">失败: \${log.failed}</span>
                </div>
              </div>
              <div class="log-details" id="log-detail-\${index}">
                \${log.results.map(r => \`
                  <div class="list-item">
                    <span class="repo-name">\${r.repo}</span>
                    <span class="badge \${r.status}">\${r.status === 'success' ? '✓' : '✗'} \${r.time}ms</span>
                  </div>
                \`).join('')}
              </div>
            </div>
          \`).join('')}
        </div>
      \`;
    }

    function toggleLogDetail(index) {
      const el = document.getElementById('log-detail-' + index);
      el.classList.toggle('show');
    }

    async function handleClearLogs() {
      if (!confirm('确定要清空所有执行记录吗?此操作不可恢复。')) {
        return;
      }
      
      const data = await apiPost('/api/logs/clear', '正在清空记录...');
      if (!data) return;
      
      document.getElementById('logsContent').innerHTML = 
        '<div class="empty"><div class="empty-icon">📭</div><p>记录已清空</p></div>';
    }

    // ============ Tab 切换 ============
    function switchTab(tabName) {
      // 更新 tab 按钮状态
      document.querySelectorAll('.tab').forEach(tab => {
        tab.classList.toggle('active', tab.dataset.tab === tabName);
      });
      
      // 更新内容显示
      document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.toggle('active', content.id === 'tab-' + tabName);
      });
    }

    // ============ 加载状态 ============
    function showLoading(text) {
      document.getElementById('loadingText').textContent = text || '加载中...';
      document.getElementById('loadingOverlay').classList.add('show');
    }

    function hideLoading() {
      document.getElementById('loadingOverlay').classList.remove('show');
    }
  </script>
</body>
</html>`;
}

在设置里找到 Cron 设置定时执行时间

  • 每月 1 号和 15 号的 0 点
0 0 1,15 * *

手动测试

不想等定时执行?可以手动测试:

  1. 访问你的 Worker 地址
  2. 登录后点击「执行 Keep Alive」
  3. 查看是否正常执行

还有一个更简单的

on:
  schedule:
    - cron: '0 1 */5 * *'
  workflow_dispatch:

permissions:
  contents: write

        
      - name: 私有仓库 Actions 保活
        run: |
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git pull --rebase || true
          git commit --allow-empty -m "Chore: 仓库 Actions 保活 [skip ci]"
          git push
12
65
로그인하고 토론에 참여하세요.

답글 65개

정렬
  1. yexu 실버 10개월 전

    感谢分享!1

    3
  2. yellowbins 골드 3 YEARS 10개월 전

    看看

    3
  3. xkm 브론즈 10개월 전

    自动更新仓库push

    2
  4. cadecstren 실버 9개월 전

    看看

    0
  5. azhaoyihao 글로리 水王 10개월 전

    感谢大佬分享方法!

    2
  6. kof97zip 다이아몬드 10개월 전

    看大佬方法

    2
  7. NooMI 골드 10개월 전

    看一下

    2
  8. user68 💬 플래티넘 3 YEARS 9개월 전

    感谢大佬分享方法!

    2
  9. yonggaoya 다이아몬드 3 YEARS 9개월 전

    看看

    2
  10. edison 골드 10개월 전

    直接手动运行一遍

    1
  11. kissbye 다이아몬드 10개월 전

    要更代码或者手动运行

    1
  12. Hao_Xiao 실버 10개월 전

    怎么解决?

    1
  13. mir_xiong 골드 3 YEARS 10개월 전

    看看

    1
  14. 51518 실버 10개월 전

    用的好好的,谁出的幺蛾子

    1
  15. lioil 골드 10개월 전

    看看什么方法

    1
  16. zlh 실버 9개월 전

    谢谢分享

    1
  17. dudu666 실버 9개월 전

    谢谢分享,看看是啥方法

    1
  18. mc838 다이아몬드 글쓴이 9개월 전

    写了个Worker 定时更新仓库txt内容

    0
  19. nikanchik 골드 9개월 전

    k k

    1
  20. nekozilla 골드 9개월 전

    看看

    1
  21. axuitomo 실버 9개월 전

    手动运行?还有什么方法?

    1
  22. denkun 실버 9개월 전

    爱了爱了!!!

    1
  23. freelost 골드 9개월 전

    定时更新readme

    1
  24. xiaomiAsscan 실버 9개월 전

    我来看看

    1
  25. linxone2895 골드 9개월 전

    直接手动运行一遍!

    1
  26. sixsix 골드 9개월 전

    看一下

    1
  27. dreamer 골드 3 YEARS 9개월 전

    来参观一下

    1
  28. gmlxh 브론즈 2 YEARS 9개월 전

    来看看,话说actions是什么

    1
  29. lyrhub 다이아몬드 3 YEARS 9개월 전

    来学习下下

    1
  30. bobli 💬 골드 9개월 전

    我一般都是去改改readme

    1
  31. Wade 골드 3 YEARS 9개월 전

    看看,怎么个事

    1
  32. sirnice 골드 9개월 전

    又整死出了,谢谢

    1