From 6bc6a8758dbf2f57c53a3d0a1f84da6c25a732a9 Mon Sep 17 00:00:00 2001 From: JianMiau Date: Mon, 13 Jul 2026 12:32:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20macOS=20=E7=89=88=20cronta?= =?UTF-8?q?b-ui?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 摘要: 網頁版排程與程序管理面板(macOS 原版),操作系統 crontab 並整合 PM2、Node.js 程序、Docker 與 log 檢視。 說明: - Crontab 頁籤直接讀寫系統 crontab,任務由系統 cron 執行 - 監聽 port 以 lsof 偵測、程序清單用 ps aux、結束程序用 kill - 附 README 說明安裝、PM2 常駐與運作方式 Co-Authored-By: Claude Fable 5 --- .gitignore | 4 + README.md | 60 +++ package-lock.json | 827 +++++++++++++++++++++++++++++++ package.json | 11 + public/index.html | 1201 +++++++++++++++++++++++++++++++++++++++++++++ server.js | 424 ++++++++++++++++ 6 files changed, 2527 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/index.html create mode 100644 server.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..88dbd1c --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +logs/ +.DS_Store +*.stackdump diff --git a/README.md b/README.md new file mode 100644 index 0000000..f778d16 --- /dev/null +++ b/README.md @@ -0,0 +1,60 @@ +# Crontab UI (macOS) + +網頁版的排程與程序管理面板,直接操作 macOS 的系統 `crontab`,並整合 PM2、Node.js 程序、Docker 與 log 檢視。 + +單一 Node.js 伺服器(Express)+ 單一 HTML 前端,無框架、無建置步驟。 + +> Windows 移植版請見 `master` 分支。 + +## 功能 + +| 頁籤 | 說明 | +|---|---| +| ⏰ Crontab | 讀寫**系統 crontab**(`crontab -l` / `crontab `),支援新增、編輯、啟用/停用、刪除、任務備註(label) | +| 🟢 PM2 | 列出 PM2 程序(狀態、PID、CPU、記憶體、重啟次數、監聽 port),可啟動/停止/重啟/刪除 | +| 🟡 Node.js | 列出系統上所有 node / bun 程序(`ps aux`),可結束程序(`kill -15` / `kill -9`) | +| 🐳 Docker | 列出容器並可啟動/停止/重啟(需安裝 Docker) | +| 📋 Log | 瀏覽 log 目錄下的 `.log` 檔案,支援 tail 與自動刷新 | + +## 安裝與執行 + +需求:Node.js 18+、macOS(或其他有 crontab 的 Unix 系統) + +```bash +npm install +node server.js +``` + +開啟 + +### 用 PM2 背景常駐(建議) + +```bash +npm install -g pm2 +pm2 start server.js --name crontab-ui +pm2 save +pm2 startup # 依照輸出的指令設定開機自動啟動(launchd) +``` + +## 環境變數 + +| 變數 | 預設值 | 說明 | +|---|---|---| +| `PORT` | `3789` | 網頁伺服器 port | +| `LOG_DIR` | `/Volumes/HDD/Claude/logs` | Log 頁籤讀取的目錄 | + +## 運作方式 + +- 排程任務由**系統 cron** 執行,本工具只負責讀寫 crontab 內容;伺服器停止不影響排程執行 +- 任務上方緊鄰的 `#` 註解行會被視為該任務的備註(label),在 UI 中一併顯示與編輯 +- 停用任務 = 在該行前面加 `#`,啟用 = 移除 +- 監聽 port 以 `lsof -iTCP -sTCP:LISTEN` 偵測後對應到 PM2 程序 + +## 專案結構 + +``` +crontab-ui/ +├── server.js # Express API(crontab / pm2 / ps / docker / logs) +└── public/ + └── index.html # 前端(單檔,無建置) +``` diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..ea02951 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,827 @@ +{ + "name": "crontab-ui", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "crontab-ui", + "version": "1.0.0", + "dependencies": { + "express": "^4.18.2" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", + "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.14.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.14.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", + "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..155f773 --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "name": "crontab-ui", + "version": "1.0.0", + "type": "commonjs", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "express": "^4.18.2" + } +} diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..8062586 --- /dev/null +++ b/public/index.html @@ -0,0 +1,1201 @@ + + + + + + 程序管理 + + + + + +
+

程序管理

+
+ + + +
+
+ +
+ + + + + +
+ + +
+
+
+
+
-
+
總任務數
+
+
+
-
+
啟用中
+
+
+
-
+
已停用
+
+
+ +
+
所有排程任務
+
+ +
+

載入中...

+
+ +

+
+
+ + +
+
+
+
PM2 進程列表
+
+
+ + + + + + + + + + + + + + + + + +
名稱狀態PortPIDCPU記憶體重啟運行時間操作
載入中...
+
+
+
+ + +
+
+
+
Node.js 進程列表
+
+
+ + + + + + + + + + + + + + +
PIDCPU記憶體啟動時間指令操作
載入中...
+
+
+
+ + +
+
+
+
Docker 容器列表
+
+
+ + + + + + + + + + + + + + + +
名稱狀態映像Port容器 ID建立 / 執行操作
載入中...
+
+
+
+ + +
+
+
+
Log 檔案
+
+ + +
+
+ +
選擇左上角的 Log 檔案查看內容
+
+
+ + + + + + + +
+ + + + diff --git a/server.js b/server.js new file mode 100644 index 0000000..c0b0e6d --- /dev/null +++ b/server.js @@ -0,0 +1,424 @@ +const express = require('express'); +const { exec } = require('child_process'); +const path = require('path'); +const fs = require('fs'); + +const app = express(); +const PORT = process.env.PORT || 3789; + +app.use(express.json()); +app.use(express.static(path.join(__dirname, 'public'))); + +// ── 判斷是否為 cron 格式 ────────────────────────────────── +function isCronFormat(content) { + if (!content) return false; + if (content.startsWith('@')) return /^@\w+\s+\S/.test(content); + return /^[\d\*\/\-,]+\s+[\d\*\/\-,]+\s+[\d\*\/\-,]+\s+[\d\*\/\-,]+\s+[\d\*\/\-,]+\s+\S/.test(content); +} + +// ── 解析 crontab 文字 ───────────────────────────────────── +function parseCrontab(raw) { + const lines = raw.split('\n'); + const labelLineSet = new Set(); // 屬於某個 cron 任務的 label 行 + + // 第一輪:標記所有緊接在 cron 行前面的連續 comment 行 + for (let i = 0; i < lines.length; i++) { + const trimmed = lines[i].trim(); + if (!trimmed) continue; + const disabled = trimmed.startsWith('#'); + const content = disabled ? trimmed.replace(/^#+\s*/, '').trim() : trimmed; + if (!isCronFormat(content)) continue; + + // 往前找所有連續的 comment 行(中間沒有空行) + let j = i - 1; + while (j >= 0) { + const t = lines[j].trim(); + if (!t) break; // 空行就停 + if (t.startsWith('#') && !isCronFormat(t.replace(/^#+\s*/, '').trim())) { + labelLineSet.add(j); + j--; + } else { + break; + } + } + } + + // 第二輪:建立 entries + const entries = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const trimmed = line.trim(); + if (!trimmed) continue; + if (labelLineSet.has(i)) continue; // label 行由 cron entry 帶走 + + const disabled = trimmed.startsWith('#'); + const content = disabled ? trimmed.replace(/^#+\s*/, '').trim() : trimmed; + + if (isCronFormat(content)) { + const entry = parseCronLine(i, line, content, disabled); + + // 收集緊接在上方的 label 行(由小到大排列) + const labelIndices = []; + let j = i - 1; + while (j >= 0 && labelLineSet.has(j)) { + labelIndices.unshift(j); + j--; + } + if (labelIndices.length > 0) { + entry.label = labelIndices + .map(idx => lines[idx].trim().replace(/^#+\s*/, '')) + .join('\n'); + entry.labelIndices = labelIndices; + } + + entries.push(entry); + } else { + entries.push({ index: i, type: 'comment', raw: line, text: trimmed }); + } + } + + return entries; +} + +function parseCronLine(index, raw, content, disabled) { + let schedule, command, scheduleDesc; + + if (content.startsWith('@')) { + const spaceIdx = content.indexOf(' '); + schedule = content.slice(0, spaceIdx); + command = content.slice(spaceIdx + 1).trim(); + const macros = { + '@reboot': '開機時執行', '@yearly': '每年', '@annually': '每年', + '@monthly': '每月1日', '@weekly': '每週日', '@daily': '每天', + '@midnight': '每天', '@hourly': '每小時', + }; + scheduleDesc = macros[schedule] || schedule; + } else { + const parts = content.split(/\s+/); + const [min, hour, day, month, weekday, ...rest] = parts; + schedule = `${min} ${hour} ${day} ${month} ${weekday}`; + command = rest.join(' '); + scheduleDesc = describeSchedule(min, hour, day, month, weekday); + } + + return { index, type: 'cron', raw, schedule, command, scheduleDesc, disabled, label: '', labelIndices: [] }; +} + +function describeSchedule(min, hour, day, month, weekday) { + const wd = ['日', '一', '二', '三', '四', '五', '六']; + const parts = []; + if (weekday !== '*') { + parts.push(`每週${weekday.split(',').map(n => wd[parseInt(n)] || n).join('、')}`); + } else if (day !== '*') { + parts.push(`每月 ${day} 日`); + } else { + parts.push('每天'); + } + if (hour !== '*' && min !== '*') parts.push(`${hour}:${String(min).padStart(2, '0')}`); + else if (hour !== '*') parts.push(`${hour} 時`); + else if (min !== '*') parts.push(`每小時第 ${min} 分`); + if (month !== '*') parts.unshift(`${month} 月`); + return parts.join(' '); +} + +// ── 工具 ───────────────────────────────────────────────── +function getCrontabLines(cb) { + exec('crontab -l 2>/dev/null || echo ""', (err, stdout) => { + cb((stdout || '').split('\n')); + }); +} + +function applyLines(lines, res) { + const content = lines.join('\n'); + console.log('[applyLines] writing crontab:'); + lines.forEach((l, i) => console.log(` [${i}] ${JSON.stringify(l)}`)); + + try { + const tmpFile = `/tmp/crontab_ui_${Date.now()}.txt`; + fs.writeFileSync(tmpFile, content); + const result = require('child_process').execSync(`crontab ${tmpFile} 2>&1`).toString(); + fs.unlinkSync(tmpFile); + res.json({ success: true }); + } catch (e) { + // 讀出檔案內容給 error message + const tmpFiles = require('child_process') + .execSync('ls /tmp/crontab_ui_*.txt 2>/dev/null || echo ""') + .toString().trim().split('\n').filter(Boolean); + let fileContent = ''; + try { + if (tmpFiles.length > 0) fileContent = fs.readFileSync(tmpFiles[tmpFiles.length - 1], 'utf-8'); + } catch {} + console.error('[applyLines] error:', e.message); + if (fileContent) console.error('[applyLines] file content:\n' + fileContent); + res.status(500).json({ error: e.message, fileContent }); + } +} + +// label 文字 → 陣列的 # 行 +function labelToLines(label) { + if (!label || !label.trim()) return []; + return label.split('\n').filter(l => l.trim()).map(l => `# ${l.trim()}`); +} + +// ── GET /api/crontab ────────────────────────────────────── +app.get('/api/crontab', (req, res) => { + exec('crontab -l 2>/dev/null || echo ""', (err, stdout) => { + const raw = stdout || ''; + res.json({ raw, entries: parseCrontab(raw) }); + }); +}); + +// ── POST /api/crontab/toggle ────────────────────────────── +app.post('/api/crontab/toggle', (req, res) => { + const { index } = req.body; + if (index === undefined) return res.status(400).json({ error: 'index required' }); + getCrontabLines((lines) => { + if (index < 0 || index >= lines.length) return res.status(404).json({ error: 'not found' }); + const t = lines[index].trim(); + lines[index] = t.startsWith('#') ? t.replace(/^#+\s*/, '') : '# ' + lines[index]; + applyLines(lines, res); + }); +}); + +// ── DELETE /api/crontab/:index ──────────────────────────── +// body: { labelIndices?: number[] } +app.delete('/api/crontab/:index', (req, res) => { + const cronIndex = parseInt(req.params.index); + const labelIndices = req.body?.labelIndices || []; + + getCrontabLines((lines) => { + if (isNaN(cronIndex) || cronIndex < 0 || cronIndex >= lines.length) + return res.status(404).json({ error: 'not found' }); + + const toDelete = [...labelIndices, cronIndex].sort((a, b) => b - a); + toDelete.forEach(idx => { if (idx >= 0 && idx < lines.length) lines.splice(idx, 1); }); + applyLines(lines, res); + }); +}); + +// ── PUT /api/crontab/:index ─────────────────────────────── +// body: { schedule, command, label, labelIndices?: number[] } +app.put('/api/crontab/:index', (req, res) => { + const cronIndex = parseInt(req.params.index); + const { schedule, command, label, labelIndices = [] } = req.body; + console.log('[PUT] index=%d schedule=%j command=%j label=%j labelIndices=%j', + cronIndex, schedule, command, label, labelIndices); + if (!schedule || !command) return res.status(400).json({ error: 'schedule and command required' }); + + getCrontabLines((lines) => { + if (isNaN(cronIndex) || cronIndex < 0 || cronIndex >= lines.length) + return res.status(404).json({ error: 'not found' }); + + const wasDisabled = lines[cronIndex].trim().startsWith('#'); + const newCronLine = wasDisabled ? `# ${schedule} ${command}` : `${schedule} ${command}`; + + // 所有要移除的行(倒序) + const allRemove = [...labelIndices, cronIndex].sort((a, b) => b - a); + const insertAt = Math.min(...allRemove); + allRemove.forEach(idx => lines.splice(idx, 1)); + + // 重建:新 label 行 + cron 行 + const newLines = [...labelToLines(label), newCronLine]; + lines.splice(insertAt, 0, ...newLines); + + applyLines(lines, res); + }); +}); + +// ── POST /api/crontab/add ───────────────────────────────── +// body: { schedule, command, label? } +app.post('/api/crontab/add', (req, res) => { + const { schedule, command, label } = req.body; + if (!schedule || !command) return res.status(400).json({ error: 'schedule and command required' }); + + getCrontabLines((lines) => { + while (lines.length && !lines[lines.length - 1].trim()) lines.pop(); + labelToLines(label).forEach(l => lines.push(l)); + lines.push(`${schedule} ${command}`); + lines.push(''); + applyLines(lines, res); + }); +}); + +// ── GET /api/pm2 ───────────────────────────────────────── +app.get('/api/pm2', (req, res) => { + exec('pm2 jlist 2>/dev/null', (err, stdout) => { + if (err) return res.json({ processes: [], error: err.message }); + try { + const list = JSON.parse(stdout || '[]'); + const processes = list.map(p => ({ + id: p.pm_id, + name: p.name, + status: p.pm2_env?.status || 'unknown', + pid: p.pid, + cpu: p.monit?.cpu ?? '-', + memory: p.monit?.memory ?? 0, + restarts: p.pm2_env?.restart_time ?? 0, + uptime: p.pm2_env?.pm_uptime ?? null, + mode: p.pm2_env?.exec_mode || 'fork', + script: p.pm2_env?.pm_exec_path || p.pm2_env?.script || '', + ports: [], + })); + + // 用 lsof 取得所有 LISTEN port,再依 PID 對應 + const pids = processes.filter(p => p.pid).map(p => p.pid).join(','); + if (!pids) return res.json({ processes }); + + exec(`lsof -iTCP -sTCP:LISTEN -nP -p ${pids} 2>/dev/null`, (e2, lsofOut) => { + // 解析 lsof 輸出:每行取 PID 和 NAME(*:PORT 或 addr:PORT) + const portMap = {}; // pid → [port, ...] + (lsofOut || '').split('\n').forEach(line => { + // 格式: COMMAND PID USER ... NAME (LISTEN) + // NAME 可能是 *:3000 或 localhost:3000,後面跟著 (LISTEN) + const m = line.match(/\s+(\d+)\s+\S+\s+.*?:(\d+)\s+\(LISTEN\)/); + if (!m) return; + const pid = parseInt(m[1]); + const port = m[2]; + if (pid && port) { + if (!portMap[pid]) portMap[pid] = []; + if (!portMap[pid].includes(port)) portMap[pid].push(port); + } + }); + + processes.forEach(p => { + if (portMap[p.pid]) p.ports = portMap[p.pid]; + }); + res.json({ processes }); + }); + } catch (e) { + res.json({ processes: [], error: e.message }); + } + }); +}); + +// ── POST /api/pm2/:action ───────────────────────────────── +// action: start | stop | restart | delete +app.post('/api/pm2/:action', (req, res) => { + const { action } = req.params; + const { name } = req.body; + if (!name) return res.status(400).json({ error: 'name required' }); + const allowed = ['start', 'stop', 'restart', 'delete']; + if (!allowed.includes(action)) return res.status(400).json({ error: 'invalid action' }); + + exec(`pm2 ${action} ${JSON.stringify(name)} 2>&1`, (err, stdout) => { + if (err) return res.status(500).json({ error: stdout || err.message }); + res.json({ success: true }); + }); +}); + +// ── GET /api/node ───────────────────────────────────────── +app.get('/api/node', (req, res) => { + exec("ps aux | grep -E '[n]ode|[b]un' | grep -v grep", (err, stdout) => { + const lines = (stdout || '').trim().split('\n').filter(Boolean); + const processes = lines.map(line => { + const cols = line.trim().split(/\s+/); + const pid = cols[1]; + const cpu = cols[2]; + const mem = cols[3]; + const started = cols[8]; + const time = cols[9]; + const cmd = cols.slice(10).join(' '); + return { pid, cpu, mem, started, time, cmd }; + }).filter(p => p.pid && p.pid !== String(process.pid)); // 排除自己 + res.json({ processes }); + }); +}); + +// ── POST /api/node/kill ─────────────────────────────────── +app.post('/api/node/kill', (req, res) => { + const { pid, force } = req.body; + if (!pid) return res.status(400).json({ error: 'pid required' }); + const sig = force ? '-9' : '-15'; + exec(`kill ${sig} ${parseInt(pid)} 2>&1`, (err, stdout) => { + if (err) return res.status(500).json({ error: stdout || err.message }); + res.json({ success: true }); + }); +}); + +// ── GET /api/docker ────────────────────────────────────── +app.get('/api/docker', (req, res) => { + const format = '{{json .}}'; + exec(`docker ps -a --format ${JSON.stringify(format)} 2>&1`, (err, stdout) => { + if (err) return res.json({ containers: [], error: stdout.trim() || err.message }); + + try { + const containers = (stdout || '') + .split('\n') + .filter(Boolean) + .map(line => JSON.parse(line)) + .map(container => ({ + id: container.ID, + name: container.Names, + image: container.Image, + status: container.Status, + state: (container.State || 'unknown').toLowerCase(), + ports: container.Ports || '', + command: container.Command || '', + createdAt: container.CreatedAt || '', + runningFor: container.RunningFor || '', + })); + + res.json({ containers }); + } catch (e) { + res.json({ containers: [], error: e.message }); + } + }); +}); + +// ── POST /api/docker/:action ───────────────────────────── +// action: start | stop | restart +app.post('/api/docker/:action', (req, res) => { + const { action } = req.params; + const { id } = req.body; + const allowed = ['start', 'stop', 'restart']; + if (!allowed.includes(action)) return res.status(400).json({ error: 'invalid action' }); + if (!id) return res.status(400).json({ error: 'id required' }); + + exec(`docker ${action} ${JSON.stringify(id)} 2>&1`, (err, stdout) => { + if (err) return res.status(500).json({ error: stdout.trim() || err.message }); + res.json({ success: true }); + }); +}); + +// ── Log API ─────────────────────────────────────────────── +const LOG_DIR = process.env.LOG_DIR || '/Volumes/HDD/Claude/logs'; + +app.get('/api/logs', (req, res) => { + try { + if (!fs.existsSync(LOG_DIR)) return res.json([]); + const files = fs.readdirSync(LOG_DIR) + .filter(f => f.endsWith('.log')) + .map(f => { + const stat = fs.statSync(path.join(LOG_DIR, f)); + return { name: f, size: stat.size, mtime: stat.mtimeMs }; + }) + .sort((a, b) => b.mtime - a.mtime); + res.json(files); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + +app.get('/api/logs/:filename', (req, res) => { + const filename = path.basename(req.params.filename); // 防止路徑穿越 + const filepath = path.join(LOG_DIR, filename); + if (!filepath.startsWith(LOG_DIR)) return res.status(403).json({ error: 'forbidden' }); + try { + if (!fs.existsSync(filepath)) return res.status(404).json({ error: '找不到檔案' }); + const lines = parseInt(req.query.lines) || 200; + const content = fs.readFileSync(filepath, 'utf-8'); + const allLines = content.split('\n'); + const tail = allLines.slice(-lines).join('\n'); + res.json({ filename, lines: allLines.length, content: tail }); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + +app.use('/api', (req, res) => { + res.status(404).json({ error: `API not found: ${req.method} ${req.originalUrl}` }); +}); + +app.listen(PORT, () => { + console.log(`✅ Crontab UI 已啟動:http://localhost:${PORT}`); +});