diff --git a/install/autorun.ps1 b/install/autorun.ps1 index 07d2c2f7..f7479a40 100644 --- a/install/autorun.ps1 +++ b/install/autorun.ps1 @@ -5,9 +5,11 @@ param( ) $ErrorActionPreference = "Stop" -# 自动提权 & 切回脚本目录 +# ------------------------------------------------- +# 1. 自动提权 & 回到脚本目录 +# ------------------------------------------------- if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { - Write-Host "当前非管理员权限,正在尝试以管理员身份重新启动..." -ForegroundColor Yellow + Write-Host "当前非管理员权限,正在尝试以管理员身份重新启动,如果闪退请走代理..." -ForegroundColor Yellow $arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$($MyInvocation.MyCommand.Path)`"" if ($UseProxy) { $arguments += " -UseProxy -ProxyHost `"$ProxyHost`"" } if ($SkipConfirm) { $arguments += " -SkipConfirm" } @@ -16,7 +18,9 @@ if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdenti } Set-Location -LiteralPath $PSScriptRoot -# ---------- 代理 ---------- +# ------------------------------------------------- +# 2. 通用函数 +# ------------------------------------------------- function Use-ProxyIfNeeded { param([scriptblock]$Script) if ($UseProxy) { @@ -36,111 +40,168 @@ function Invoke-WebRequestWithProxy([string]$Url, [string]$OutFile) { else { Invoke-WebRequest $Url -OutFile $OutFile } } -# ---------- 用户确认 ---------- +# ------------------------------------------------- +# 3. 按需安装 winget +# ------------------------------------------------- +function Install-Winget { + if (Test-Cmd winget) { return } + Write-Host "未检测到 winget,正在安装 App Installer..." -ForegroundColor Yellow + $url = "https://aka.ms/getwinget" + $out = "$env:TEMP\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" + Invoke-WebRequestWithProxy $url $out + Add-AppxPackage -Path $out -ErrorAction SilentlyContinue + Remove-Item $out + # 刷新 PATH + $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") +} + +# ------------------------------------------------- +# 4. 用户确认 +# ------------------------------------------------- if (-not $SkipConfirm) { Write-Host "警告:此脚本仅适用于 Windows 10/11 64 位" -ForegroundColor Green Write-Host "建议使用 Windows Terminal 终端管理员方式运行" -ForegroundColor Green Write-Host "如果 nvm、git、python 安装失败,建议手动安装" -ForegroundColor Green - Write-Host "下载失败可指定旁路由代理:.\drpys-final.ps1 -UseProxy -ProxyHost `"192.168.1.21:7890`"" -ForegroundColor Green + Write-Host "下载失败可指定旁路由代理:.\drpys-auto.ps1 -UseProxy -ProxyHost `"192.168.1.21:7890`"" -ForegroundColor Green Write-Host "如果旁路由也下载失败那就换成道长那个白嫖地址" -ForegroundColor Green $confirm = Read-Host "您是否理解并同意继续?(y/n) 默认(y)" if ($confirm -eq "n") { exit 1 } } -# ---------- 安装 Node / nvm / git / python ---------- -Use-ProxyIfNeeded -Script { - $needNode = $false - if (Test-Cmd "node") { - # 取出三段版本号 - $nodeVer = (node -v) -replace '^v','' -split '\.' | ForEach-Object { [int]$_ } - # 构造一个可比较的整数:主*10000 + 次*100 + 修订 - $current = $nodeVer[0]*10000 + $nodeVer[1]*100 + $nodeVer[2] - $require = 20*10000 + 18*100 + 3 # 20.18.3 - if ($current -ge $require) { - Write-Host "已检测到 Node v$($nodeVer -join '.') ≥20.18.3,跳过安装" -ForegroundColor Green - } else { - Write-Host "Node 版本低于 20.18.3,将使用 nvm 安装/切换到 20.18.3" -ForegroundColor Yellow - $needNode = $true - } +# ------------------------------------------------- +# 5. 安装 nvm(不变) +# ------------------------------------------------- +if (-not (Test-Cmd "nvm")) { + Write-Host "正在安装 nvm-windows..." -ForegroundColor Green + $nvmSetup = "$env:TEMP\nvm-setup.exe" + Invoke-WebRequestWithProxy "https://github.com/coreybutler/nvm-windows/releases/latest/download/nvm-setup.exe" $nvmSetup + Start-Process -Wait -FilePath $nvmSetup -ArgumentList "/silent" + Remove-Item $nvmSetup + Write-Host "" + Write-Host "--------------------------------------------------" -ForegroundColor Yellow + Write-Host "nvm 已安装完毕,但当前 PowerShell 会话尚未识别到它。" -ForegroundColor Yellow + Write-Host "请执行以下任意一步后再继续:" -ForegroundColor Cyan + Write-Host " 1) 关闭本窗口,重新打开一个『管理员』PowerShell后,再次执行脚本;" -ForegroundColor Cyan + Write-Host " 2) 或者再次右键选PS运行本脚本。" -ForegroundColor Cyan + Write-Host "--------------------------------------------------" -ForegroundColor Yellow + Read-Host "按 Enter 键退出本窗口" + exit +} else { + Write-Host "已检测到 nvm,跳过安装" -ForegroundColor Green +} + +# ------------------------------------------------- +# 6. 安装/切换 Node +# ------------------------------------------------- +$needNode = $false +if (Test-Cmd "node") { + $nodeVer = (node -v) -replace '^v','' -split '\.' | ForEach-Object { [int]$_ } + $current = $nodeVer[0]*10000 + $nodeVer[1]*100 + $nodeVer[2] + $require = 20*10000 + 18*100 + 3 # 20.18.3 + if ($current -ge $require) { + Write-Host "已检测到 Node v$($nodeVer -join '.') ≥20.18.3,跳过安装" -ForegroundColor Green } else { - Write-Host "未检测到 Node,准备安装" -ForegroundColor Yellow + Write-Host "Node 版本低于 20.18.3,将使用 nvm 安装/切换到 20.18.3" -ForegroundColor Yellow $needNode = $true } +} else { + Write-Host "未检测到 Node,准备安装" -ForegroundColor Yellow + $needNode = $true +} +if ($needNode) { + nvm install 20.18.3 + nvm use 20.18.3 +} - if (-not (Test-Cmd "nvm")) { - Write-Host "正在安装 nvm-windows..." -ForegroundColor Green - $nvmSetup = "$env:TEMP\nvm-setup.exe" - Invoke-WebRequestWithProxy "https://github.com/coreybutler/nvm-windows/releases/latest/download/nvm-setup.exe" $nvmSetup - Start-Process -Wait -FilePath $nvmSetup -ArgumentList "/silent" - Remove-Item $nvmSetup - $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") +# ------------------------------------------------- +# 7. 安装 Python 3.11(优先 winget) +# ------------------------------------------------- +$pyNeed = $false +try { + $ver = (python -V 2>$null) -replace 'Python ','' + if ($ver -match '^3\.11') { + Write-Host "已检测到 Python 3.11 ($ver),跳过安装" -ForegroundColor Green } else { - Write-Host "已检测到 nvm,跳过安装" -ForegroundColor Green - } - - if ($needNode) { - nvm install 20.18.3 - nvm use 20.18.3 + Write-Host "检测到非 3.11 版本,准备覆盖安装 3.11" -ForegroundColor Yellow + $pyNeed = $true } +} catch { + Write-Host "未检测到 Python,准备安装 3.11" -ForegroundColor Yellow + $pyNeed = $true +} +if ($pyNeed) { + Install-Winget + Write-Host "正在通过 winget 安装 Python 3.11..." -ForegroundColor Green + winget install --id Python.Python.3.11 -e --accept-source-agreements --accept-package-agreements + $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") +} - # ---------- 安装 Python 3.11 ---------- - $pyExe = "python-3.11.9-amd64.exe" - $pyUrl = "https://www.python.org/ftp/python/3.11.9/$pyExe" - $pyDir = "C:\Python311" - $needPy = $false - - if (Test-Cmd "python") { - $ver = (& python -V 2>&1) -replace 'Python ','' - if ($ver -match '^3\.11') { - Write-Host "已检测到 Python 3.11 ($ver),跳过安装" -ForegroundColor Green - } else { - Write-Host "检测到非 3.11 版本,准备覆盖安装 3.11" -ForegroundColor Yellow - $needPy = $true +# ------------------------------------------------- +# 安装 Git:winget 优先,失败自动离线 +# ------------------------------------------------- +if (-not (Test-Cmd "git")) { + # 1) winget 交互式安装 + Install-Winget + if (Test-Cmd winget) { + Write-Host "正在通过 winget 安装 Git(交互模式)..." -ForegroundColor Green + try { + winget install --id Git.Git -e --source winget + if (Test-Cmd git) { + Write-Host "Git 安装成功(winget)" -ForegroundColor Green + $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") + continue + } + } catch { + Write-Host "winget 安装失败,将使用离线包..." -ForegroundColor Yellow } - } else { - Write-Host "未检测到 Python,准备安装 3.11" -ForegroundColor Yellow - $needPy = $true } - if ($needPy) { - Write-Host "正在下载并安装 Python 3.11..." -ForegroundColor Green - $exePath = "$env:TEMP\$pyExe" - Invoke-WebRequestWithProxy $pyUrl $exePath - $proc = Start-Process -FilePath $exePath -ArgumentList ` - "/quiet InstallAllUsers=1 TargetDir=$pyDir PrependPath=1" -PassThru - $proc.WaitForExit() - Remove-Item $exePath - $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") - if (-not (Test-Cmd "python")) { - Write-Error "Python 3.11 安装失败,脚本终止" - exit 1 - } + # 2) winget 失败 → 离线安装 + Write-Host "正在解析 Git 最新版本..." -ForegroundColor Green + try { + $latestUri = (Invoke-WebRequest -Uri "https://github.com/git-for-windows/git/releases/latest" -MaximumRedirection 0 -ErrorAction SilentlyContinue).Headers.Location + $ver = if ($latestUri) { $latestUri -replace '.*/tag/v([0-9.]+).*$','$1' } else { "2.51.0" } + } catch { + $ver = "2.51.0" } - $tools = @{ - yarn = { npm install -g yarn } - pm2 = { npm install -g pm2 } - git = { winget install --id Git.Git -e --source winget } - } - foreach ($kv in $tools.GetEnumerator()) { - $cmd = $kv.Key - if (-not (Test-Cmd $cmd)) { - Write-Host "正在安装 $cmd ..." -ForegroundColor Yellow - & $kv.Value - } else { - Write-Host "已检测到 $cmd,跳过安装" -ForegroundColor Green - } - } + Write-Host "正在下载 Git $ver ..." -ForegroundColor Green + $gitSetup = "$env:TEMP\Git-$ver-64-bit.exe" + $gitUrl = "https://github.com/git-for-windows/git/releases/download/v$ver.windows.1/Git-$ver-64-bit.exe" + Invoke-WebRequestWithProxy $gitUrl $gitSetup + Start-Process -Wait -FilePath $gitSetup -ArgumentList ` + "/VERYSILENT /NORESTART /NOCANCEL /SP- /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS" + Remove-Item $gitSetup -Force $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") +} else { + Write-Host "已检测到 Git,跳过安装" -ForegroundColor Green } -# ---------- 工作目录 ---------- +# ------------------------------------------------- +# 9. 安装全局 npm 工具 +# ------------------------------------------------- +$tools = @{ + yarn = { npm install -g yarn } + pm2 = { npm install -g pm2 } +} +foreach ($kv in $tools.GetEnumerator()) { + if (-not (Test-Cmd $kv.Key)) { + Write-Host "正在安装 $($kv.Key) ..." -ForegroundColor Yellow + & $kv.Value + } else { + Write-Host "已检测到 $($kv.Key),跳过安装" -ForegroundColor Green + } +} +$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") + +# ------------------------------------------------- +# 10. 克隆仓库 / 配置 / 依赖 / PM2(保持不变) +# ------------------------------------------------- $repoDir = Read-Host "请输入项目存放目录(留空则使用当前目录)" if ([string]::IsNullOrWhiteSpace($repoDir)) { $repoDir = (Get-Location).Path } $projectPath = Join-Path $repoDir "drpy-node" $remoteRepo = "https://github.com/hjdhnx/drpy-node.git" -# ---------- 首次克隆 / 配置 ---------- Use-ProxyIfNeeded -Script { if (-not (Test-Path $projectPath)) { Write-Host "正在克隆仓库..." -ForegroundColor Yellow @@ -152,12 +213,10 @@ Use-ProxyIfNeeded -Script { } Set-Location $projectPath - # ---------- 生成 env.json(目录不存在则创建,UTF-8 无 BOM) ---------- + # 生成 env.json $configDir = Join-Path $projectPath "config" $configJson = Join-Path $configDir "env.json" - if (-not (Test-Path $configDir)) { - New-Item -ItemType Directory -Path $configDir -Force | Out-Null - } + if (-not (Test-Path $configDir)) { New-Item -ItemType Directory -Path $configDir -Force | Out-Null } if (-not (Test-Path $configJson)) { $utf8NoBom = [System.Text.UTF8Encoding]::new($false) $jsonText = @{ @@ -168,18 +227,15 @@ Use-ProxyIfNeeded -Script { [System.IO.File]::WriteAllLines($configJson, $jsonText, $utf8NoBom) } - # ---------- 生成 .env(复制后重写为 UTF-8 无 BOM) ---------- + # 生成 .env $envFile = Join-Path $projectPath ".env" if (-not (Test-Path $envFile)) { $template = Join-Path $projectPath ".env.development" Copy-Item $template $envFile - - # 强制无 BOM 重写 $utf8NoBom = [System.Text.UTF8Encoding]::new($false) $content = [System.IO.File]::ReadAllText($envFile) [System.IO.File]::WriteAllText($envFile, $content, $utf8NoBom) - # 交互式替换 $cookieAuth = Read-Host "网盘入库密码(默认 drpys)" $apiUser = Read-Host "登录用户名(默认 admin)" $apiPass = Read-Host "登录密码(默认 drpys)" @@ -197,7 +253,7 @@ Use-ProxyIfNeeded -Script { if (-not (Test-Path "node_modules")) { Write-Host "首次安装 Node 依赖..." -ForegroundColor Yellow yarn config set registry https://registry.npmmirror.com/ - yarn install + yarn } elseif ((git diff HEAD^ HEAD --name-only 2>$null) -match [regex]::Escape("yarn.lock")) { Write-Host "检测到 yarn.lock 变动,更新 Node 依赖..." -ForegroundColor Yellow yarn install --registry https://registry.npmmirror.com/ @@ -208,8 +264,7 @@ Use-ProxyIfNeeded -Script { Write-Host "首次创建 Python 虚拟环境..." -ForegroundColor Yellow python -m venv .venv & .\.venv\Scripts\Activate.ps1 - Write-Host "首次安装 Python 依赖..." -ForegroundColor Yellow - python.exe -m pip install --upgrade pip + python -m pip install --upgrade pip pip install -r spider\py\base\requirements.txt -i https://mirrors.cloud.tencent.com/pypi/simple } else { & .\.venv\Scripts\Activate.ps1 @@ -219,6 +274,7 @@ Use-ProxyIfNeeded -Script { } } + # PM2 if (-not (pm2 list | Select-String "drpyS.*online")) { Write-Host "首次启动 PM2 进程..." -ForegroundColor Yellow pm2 start index.js --name drpyS --update-env @@ -228,20 +284,19 @@ Use-ProxyIfNeeded -Script { } } -# ---------- 任务计划 ---------- +# ------------------------------------------------- +# 11. 计划任务(开机自启 + 6 小时更新) +# ------------------------------------------------- $taskStartup = "drpyS_PM2_Startup" $taskUpdate = "drpyS_Update" - $pm2 = (Get-Command pm2.cmd -ErrorAction SilentlyContinue).Source $nodeExe = (Get-Command node.exe -ErrorAction SilentlyContinue).Source - if ($pm2 -and $nodeExe) { $taskStartup,$taskUpdate | ForEach-Object { if (Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue) { Unregister-ScheduledTask -TaskName $_ -Confirm:$false } } - $commonSettings = New-ScheduledTaskSettingsSet ` -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable @@ -257,16 +312,17 @@ if ($pm2 -and $nodeExe) { # 每 6 小时更新 $action = New-ScheduledTaskAction ` -Execute "powershell.exe" ` - -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command `"& { `$env:PM2_HOME='C:\$env:USERNAME\.pm2'; Set-Location '$projectPath'; git fetch origin; if (git status -uno | Select-String 'Your branch is behind') { git reset --hard origin/main; yarn install --registry https://registry.npmmirror.com/; pip install -r spider\py\base\requirements.txt -i https://mirrors.cloud.tencent.com/pypi/simple; & '$pm2' restart drpyS } }`"" ` + -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command `"& { `$env:PM2_HOME='C:\$env:USERNAME\.pm2'; Set-Location '$projectPath'; git fetch origin; if (git status -uno | Select-String 'Your branch is behind') { git reset --hard origin/main; yarn install --registry https://registry.npmmirror.com/ ; pip install -r spider\py\base\requirements.txt -i https://mirrors.cloud.tencent.com/pypi/simple ; & '$pm2' restart drpyS } }`"" ` -WorkingDirectory $projectPath $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 6) Register-ScheduledTask -TaskName $taskUpdate -Action $action -Trigger $trigger -Settings $commonSettings -User "SYSTEM" -RunLevel Highest -Force | Out-Null Write-Host "已创建/更新每 6 小时更新任务:$taskUpdate" -ForegroundColor Green } -# ------ 退出虚拟环境 ------ +# ------------------------------------------------- +# 12. 结束提示 +# ------------------------------------------------- deactivate -# ---------- 完成 ---------- $ip = (ipconfig | Select-String "IPv4 地址" | Select-Object -First 1).ToString().Split(":")[-1].Trim() $public = (Invoke-RestMethod "https://ipinfo.io/ip") Write-Host "内网地址:http://${ip}:5757" -ForegroundColor Green