commit 41ab88abbb98c0e6e9d8fbd871681ed96a45bfa0 Author: JianMiau Date: Mon Jul 13 12:30:30 2026 +0800 新增 Windows 版 crontab-ui 摘要: 從 macOS 版移植的網頁排程與程序管理面板,可在 Windows 原生執行。 說明: - Windows 無系統 cron,改為本地檔案 crontab.txt 儲存 + 伺服器內建排程器執行(支援五欄位語法與 @ 巨集,@reboot 於伺服器啟動時執行) - lsof → netstat -ano、ps aux → PowerShell Get-CimInstance、kill → taskkill - PM2 / Docker 指令跨平台,維持不變 - 前端:PM2 頁籤設為首頁;script 路徑僅顯示檔名,滑鼠停留顯示完整路徑;port 連結改用目前主機名 Co-Authored-By: Claude Fable 5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1dcec24 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +logs/ +crontab.txt +*.stackdump diff --git a/README.md b/README.md new file mode 100644 index 0000000..b882d03 --- /dev/null +++ b/README.md @@ -0,0 +1,80 @@ +# Crontab UI (Windows) + +網頁版的排程與程序管理面板,移植自 macOS 版 crontab-ui,改為在 Windows 上原生執行。 + +單一 Node.js 伺服器(Express)+ 單一 HTML 前端,無框架、無建置步驟。 + +## 功能 + +| 頁籤 | 說明 | +|---|---| +| 🟢 PM2(首頁) | 列出 PM2 程序(狀態、PID、CPU、記憶體、重啟次數、監聽 port),可啟動/停止/重啟/刪除 | +| ⏰ Crontab | 以 cron 語法管理排程任務,支援新增、編輯、啟用/停用、刪除、任務備註(label) | +| 🟡 Node.js | 列出系統上所有 node / bun 程序,可結束程序(taskkill) | +| 🐳 Docker | 列出容器並可啟動/停止/重啟(需安裝 Docker) | +| 📋 Log | 瀏覽 log 目錄下的 `.log` 檔案,支援 tail 與自動刷新 | + +## 安裝與執行 + +需求:Node.js 18+、Windows + +```bash +npm install +node server.js +``` + +開啟 + +### 用 PM2 背景常駐(建議) + +```bash +npm install -g pm2 pm2-windows-startup +pm2 start server.js --name crontab-ui +pm2 save +pm2-startup install # 登入 Windows 後自動啟動 +``` + +## 環境變數 + +| 變數 | 預設值 | 說明 | +|---|---|---| +| `PORT` | `3789` | 網頁伺服器 port | +| `CRONTAB_FILE` | `<專案目錄>\crontab.txt` | 排程任務儲存檔 | +| `LOG_DIR` | `<專案目錄>\logs` | Log 頁籤讀取的目錄,排程執行紀錄 `cron.log` 也寫在這裡 | + +## 排程機制(與 macOS 版的差異) + +Windows 沒有系統 cron,本版本改為: + +- 任務儲存在本地檔案 `crontab.txt`(格式與 crontab 完全相同,含 `#` 停用與備註行) +- 伺服器**內建排程器**,每分鐘比對一次並以 `cmd.exe` 執行到期的指令 +- 執行結果(stdout / stderr / 錯誤)寫入 `logs\cron.log`,可直接在 UI 的 Log 頁籤查看 + +支援的 cron 語法: + +- 五欄位:`分 時 日 月 週`,可用 `*`、清單 `1,15`、範圍 `9-17`、步進 `*/5`、組合 `1-5/2` +- 巨集:`@hourly`、`@daily`/`@midnight`、`@weekly`、`@monthly`、`@yearly`/`@annually` +- `@reboot`:改為「伺服器啟動時」執行一次 +- 日與週同時指定時,符合其一即執行(標準 cron 行為) + +> ⚠️ 排程器跟著伺服器運行:伺服器停止期間的任務不會補跑。請搭配 PM2 常駐。 + +其他系統層替換: + +| 功能 | macOS 版 | Windows 版 | +|---|---|---| +| 排程儲存/執行 | 系統 `crontab` + cron | 本地檔案 + 內建排程器 | +| 監聽 port 偵測 | `lsof` | `netstat -ano` | +| 程序清單 | `ps aux` | PowerShell `Get-CimInstance Win32_Process` | +| 結束程序 | `kill -15` / `-9` | `taskkill` / `taskkill /F /T` | + +## 專案結構 + +``` +crontab-ui/ +├── server.js # Express API + 內建 cron 排程器 +├── public/ +│ └── index.html # 前端(單檔,無建置) +├── crontab.txt # 排程任務(執行時自動建立,不進版控) +└── logs/ # log 目錄(不進版控) +``` diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..2bc93fc --- /dev/null +++ b/package-lock.json @@ -0,0 +1,828 @@ +{ + "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.6", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.6.tgz", + "integrity": "sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g==", + "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.15.1", + "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.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "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.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz", + "integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.5", + "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.15.1", + "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.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "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.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "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.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "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..63a22d3 --- /dev/null +++ b/public/index.html @@ -0,0 +1,1202 @@ + + + + + + 程序管理 + + + + + +
+

程序管理

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

載入中...

+
+ +

+
+
+ + +
+
+
+
PM2 進程列表
+
+
+ + + + + + + + + + + + + + + + + +
名稱狀態PortPIDCPU記憶體重啟運行時間操作
載入中...
+
+
+
+ + +
+
+
+
Node.js 進程列表
+
+
+ + + + + + + + + + + + + + +
PIDCPU記憶體啟動時間指令操作
載入中...
+
+
+
+ + +
+
+
+
Docker 容器列表
+
+
+ + + + + + + + + + + + + + + +
名稱狀態映像Port容器 ID建立 / 執行操作
載入中...
+
+
+
+ + +
+
+
+
Log 檔案
+
+ + +
+
+ +
選擇左上角的 Log 檔案查看內容
+
+
+ + + + + + + +
+ + + + diff --git a/server.js b/server.js new file mode 100644 index 0000000..836fcf0 --- /dev/null +++ b/server.js @@ -0,0 +1,535 @@ +const express = require('express'); +const { exec, execFile } = require('child_process'); +const path = require('path'); +const fs = require('fs'); + +const app = express(); +const PORT = process.env.PORT || 3789; + +// Windows 版:crontab 內容存在本地檔案,由內建排程器執行 +const CRONTAB_FILE = process.env.CRONTAB_FILE || path.join(__dirname, 'crontab.txt'); +const LOG_DIR = process.env.LOG_DIR || path.join(__dirname, 'logs'); + +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(' '); +} + +// ── 內建排程器 ──────────────────────────────────────────── +// macro → 5 欄位(@reboot 於伺服器啟動時執行) +const MACRO_MAP = { + '@yearly': '0 0 1 1 *', '@annually': '0 0 1 1 *', + '@monthly': '0 0 1 * *', '@weekly': '0 0 * * 0', + '@daily': '0 0 * * *', '@midnight': '0 0 * * *', + '@hourly': '0 * * * *', +}; + +// 解析單一 cron 欄位(*、*/n、a-b、a-b/n、a,b,c),回傳允許值 Set;null 表示格式錯誤 +function parseField(field, min, max) { + const values = new Set(); + for (const part of field.split(',')) { + const m = part.match(/^(\*|\d+(?:-\d+)?)(?:\/(\d+))?$/); + if (!m) return null; + const step = m[2] ? parseInt(m[2]) : 1; + if (step < 1) return null; + let lo, hi; + if (m[1] === '*') { lo = min; hi = max; } + else if (m[1].includes('-')) { [lo, hi] = m[1].split('-').map(Number); } + else { lo = hi = parseInt(m[1]); if (m[2]) hi = max; } // "a/n" 視為 a-max/n + if (lo < min || hi > max || lo > hi) return null; + for (let v = lo; v <= hi; v += step) values.add(v); + } + return values; +} + +function cronMatches(schedule, date) { + const fields = schedule.trim().split(/\s+/); + if (fields.length !== 5) return false; + const [min, hour, day, month, weekday] = fields; + const fMin = parseField(min, 0, 59); + const fHour = parseField(hour, 0, 23); + const fDay = parseField(day, 1, 31); + const fMonth = parseField(month, 1, 12); + const fWd = parseField(weekday, 0, 7); + if (!fMin || !fHour || !fDay || !fMonth || !fWd) return false; + if (fWd.has(7)) fWd.add(0); // 7 也代表週日 + + if (!fMin.has(date.getMinutes())) return false; + if (!fHour.has(date.getHours())) return false; + if (!fMonth.has(date.getMonth() + 1)) return false; + + // 標準 cron 規則:day 與 weekday 都有限制時,符合其一即可 + const dayRestricted = day !== '*'; + const wdRestricted = weekday !== '*'; + const dayOk = fDay.has(date.getDate()); + const wdOk = fWd.has(date.getDay()); + if (dayRestricted && wdRestricted) return dayOk || wdOk; + if (dayRestricted) return dayOk; + if (wdRestricted) return wdOk; + return true; +} + +function cronLog(message) { + const line = `[${new Date().toLocaleString('sv-SE')}] ${message}\n`; + try { + if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true }); + fs.appendFileSync(path.join(LOG_DIR, 'cron.log'), line); + } catch {} + console.log(line.trim()); +} + +function runJob(schedule, command) { + cronLog(`▶ 執行 [${schedule}] ${command}`); + exec(command, { windowsHide: true, maxBuffer: 10 * 1024 * 1024 }, (err, stdout, stderr) => { + const out = [stdout, stderr].filter(s => s && s.trim()).join('\n').trim(); + if (err) cronLog(`✖ 失敗 [${command}]:${err.message}${out ? '\n' + out : ''}`); + else cronLog(`✔ 完成 [${command}]${out ? '\n' + out : ''}`); + }); +} + +// 取得目前啟用中的 cron 任務 +function activeJobs() { + return parseCrontab(readCrontabRaw()) + .filter(e => e.type === 'cron' && !e.disabled) + .map(e => ({ + schedule: MACRO_MAP[e.schedule] || e.schedule, + isReboot: e.schedule === '@reboot', + command: e.command, + })); +} + +let lastMinuteKey = ''; +function schedulerTick() { + const now = new Date(); + const key = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}`; + if (key === lastMinuteKey) return; // 同一分鐘不重複執行 + lastMinuteKey = key; + + for (const job of activeJobs()) { + if (job.isReboot) continue; + if (cronMatches(job.schedule, now)) runJob(job.schedule, job.command); + } +} + +function startScheduler() { + // @reboot:伺服器啟動時執行一次 + for (const job of activeJobs()) { + if (job.isReboot) runJob('@reboot', job.command); + } + lastMinuteKey = ''; // 啟動當下這一分鐘也要檢查 + setInterval(schedulerTick, 5000); + schedulerTick(); +} + +// ── 工具 ───────────────────────────────────────────────── +function readCrontabRaw() { + try { + return fs.readFileSync(CRONTAB_FILE, 'utf-8'); + } catch { + return ''; + } +} + +function getCrontabLines(cb) { + cb(readCrontabRaw().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 { + fs.writeFileSync(CRONTAB_FILE, content); + res.json({ success: true }); + } catch (e) { + console.error('[applyLines] error:', e.message); + res.status(500).json({ error: e.message }); + } +} + +// 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) => { + const raw = readCrontabRaw(); + 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', { windowsHide: true }, (err, stdout) => { + if (err) return res.json({ processes: [], error: err.message }); + try { + // pm2 jlist 前面可能夾雜非 JSON 訊息,從第一個 [ 開始取 + const jsonStart = stdout.indexOf('['); + const list = JSON.parse(jsonStart >= 0 ? stdout.slice(jsonStart) : '[]'); + 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: [], + })); + + const pids = new Set(processes.filter(p => p.pid).map(p => String(p.pid))); + if (pids.size === 0) return res.json({ processes }); + + // 用 netstat 取得所有 LISTENING port,再依 PID 對應 + exec('netstat -ano', { windowsHide: true, maxBuffer: 10 * 1024 * 1024 }, (e2, netOut) => { + const portMap = {}; // pid → [port, ...] + (netOut || '').split('\n').forEach(line => { + // 格式: TCP 0.0.0.0:3789 0.0.0.0:0 LISTENING 12345 + const m = line.trim().match(/^TCP\s+\S+:(\d+)\s+\S+\s+LISTENING\s+(\d+)/); + if (!m) return; + const port = m[1]; + const pid = m[2]; + if (pids.has(pid)) { + if (!portMap[pid]) portMap[pid] = []; + if (!portMap[pid].includes(port)) portMap[pid].push(port); + } + }); + + processes.forEach(p => { + if (portMap[String(p.pid)]) p.ports = portMap[String(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)}`, { windowsHide: true }, (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) => { + const script = `Get-CimInstance Win32_Process | Where-Object { $_.Name -match '^(node|bun)' } | ` + + `Select-Object ProcessId, CommandLine, ` + + `@{n='MemMB';e={[math]::Round($_.WorkingSetSize/1MB,1)}}, ` + + `@{n='Started';e={if ($_.CreationDate) {$_.CreationDate.ToString('MM/dd HH:mm')} else {'-'}}} | ` + + `ConvertTo-Json -Compress`; + execFile('powershell.exe', ['-NoProfile', '-Command', script], { windowsHide: true, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => { + if (err) return res.json({ processes: [], error: err.message }); + let list = []; + try { + const parsed = JSON.parse(stdout.trim() || '[]'); + list = Array.isArray(parsed) ? parsed : [parsed]; + } catch {} + const processes = list.map(p => ({ + pid: String(p.ProcessId), + cpu: '-', + mem: `${p.MemMB}MB`, + started: p.Started || '-', + time: '-', + cmd: p.CommandLine || '', + })).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 args = force ? `/F /T /PID ${parseInt(pid)}` : `/PID ${parseInt(pid)}`; + exec(`taskkill ${args}`, { windowsHide: true }, (err, stdout, stderr) => { + if (err) return res.status(500).json({ error: (stderr || stdout || err.message).trim() }); + res.json({ success: true }); + }); +}); + +// ── GET /api/docker ────────────────────────────────────── +app.get('/api/docker', (req, res) => { + const format = '{{json .}}'; + exec(`docker ps -a --format ${JSON.stringify(format)}`, { windowsHide: true }, (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)}`, { windowsHide: true }, (err, stdout) => { + if (err) return res.status(500).json({ error: (stdout || '').trim() || err.message }); + res.json({ success: true }); + }); +}); + +// ── Log API ─────────────────────────────────────────────── +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 (Windows) 已啟動:http://localhost:${PORT}`); + console.log(` 排程檔:${CRONTAB_FILE}`); + console.log(` Log 目錄:${LOG_DIR}`); + startScheduler(); +});