Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

18.7 KB
Raw Blame
# LumReels: bộ cài một chạm cho Windows 10/11.
#   Bấm đúp LumReels-Setup.cmd, hoặc trong PowerShell:
#     powershell -ExecutionPolicy Bypass -File install\windows\install.ps1 [-DryRun] [-NoLaunch]
#     powershell -ExecutionPolicy Bypass -c "irm https://raw.githubusercontent.com/lumtekvn/lumreels/main/install/windows/install.ps1 | iex"
# Làm gì: kiểm rồi cài thiếu (qua winget) Node 22+, ffmpeg, Google Chrome, Git → clone/cập nhật mã vào
#   %LOCALAPPDATA%\LumReels\app → npm install → shortcut "LumReels" ở Desktop + Start Menu → mở app.
# Chạy lại an toàn: thứ đã có thì bỏ qua, mã đã clone thì chỉ cập nhật.
# -Ref: tag/commit/nhánh cần cài. Mặc định: tag phát hành mới nhất (v*) trên GitHub; repo chưa có tag nào thì
#   dùng nhánh mặc định (main) và in cảnh báo. Ghim tag thì app không tự báo bản mới (cài lại để lên tag mới).
# -DryRun: chỉ kiểm và in việc sẽ làm, không cài, không tải, không tạo gì (trừ file log).
# Log: %LOCALAPPDATA%\LumReels\install.log
# File này phải lưu UTF-8 có BOM (Windows PowerShell 5.1 mới đọc đúng chữ có dấu).
param(
  [switch]$DryRun,
  [switch]$NoLaunch,
  [switch]$NoShortcut,
  [string]$InstallDir = (Join-Path $env:LOCALAPPDATA 'LumReels\app'),
  [string]$Repo = 'https://github.com/lumtekvn/lumreels.git',
  [string]$Ref = ''
)

# chạy qua `irm | iex` thì các biến này nằm trong phiên của người dùng: nhớ để trả lại ở cuối
$savedEAP = $ErrorActionPreference; $savedPP = $ProgressPreference; $savedOE = $OutputEncoding
$savedCOE = $null; try { $savedCOE = [Console]::OutputEncoding } catch { }
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
try {
  $utf8 = New-Object System.Text.UTF8Encoding $false
  [Console]::OutputEncoding = $utf8
  $OutputEncoding = $utf8
} catch { }

$BaseDir = Join-Path $env:LOCALAPPDATA 'LumReels'
$LogFile = Join-Path $BaseDir 'install.log'
$script:Failed = 0
$script:Warned = 0
$MIN_NODE = 22
$MIN_FREE_GB = 3

New-Item -ItemType Directory -Force -Path $BaseDir | Out-Null

function Write-Log([string]$line) {
  try { Add-Content -LiteralPath $LogFile -Value ("{0}  {1}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $line) -Encoding UTF8 } catch { }
}
function Say([string]$kind, [string]$msg, [string]$hint = '') {
  switch ($kind) {
    'ok'   { Write-Host ('  ✓ ' + $msg) -ForegroundColor Green }
    'fail' { Write-Host ('  ✗ ' + $msg) -ForegroundColor Red; $script:Failed++ }
    'warn' { Write-Host ('  ! ' + $msg) -ForegroundColor Yellow; $script:Warned++ }
    'plan' { Write-Host ('  → ' + $msg) -ForegroundColor Cyan }
    'head' { Write-Host ''; Write-Host $msg -ForegroundColor White }
    default { Write-Host ('    ' + $msg) }
  }
  if ($hint) { Write-Host ('      Cách sửa: ' + $hint) -ForegroundColor DarkGray }
  Write-Log ("[{0}] {1}{2}" -f $kind, $msg, $(if ($hint) { ' | Cách sửa: ' + $hint } else { '' }))
}

# Chạy lệnh ngoài (winget/git/npm). PowerShell 5.1 với ErrorActionPreference=Stop biến MỌI dòng stderr (vd "npm warn",
# "From https://github.com/…" của git) thành lỗi dừng khi có 2>&1 → đặt Continue cục bộ, chỉ tin exit code.
# Ghi từng dòng vào log với tiền tố $tag. Trả @{ code; out }.
function Invoke-Native([string]$tag, [string]$exe, [string[]]$argv) {
  $ErrorActionPreference = 'Continue'
  $lines = New-Object System.Collections.Generic.List[string]
  $code = $null
  try {
    & $exe @argv 2>&1 | ForEach-Object { $l = [string]$_; $lines.Add($l); Write-Log ("  ${tag}: " + $l) }
    $code = $LASTEXITCODE
  } catch {
    $lines.Add($_.Exception.Message); Write-Log ("  ${tag}: " + $_.Exception.Message); $code = 1
  }
  if ($null -eq $code) { $code = 0 }
  return @{ code = [int]$code; out = $lines }
}

# Tag phát hành mới nhất (v*) trên GitHub, hoặc '' nếu chưa có tag nào / không đọc được.
function Get-LatestTag {
  $r = Invoke-Native 'git' 'git' @('ls-remote', '--tags', '--refs', '--sort=-v:refname', $Repo, 'v*')
  if ($r.code -ne 0) { return '' }
  foreach ($l in $r.out) { if ($l -match 'refs/tags/(v\S+)$') { return $Matches[1] } }
  return ''
}

function Update-SessionPath {
  $machine = [Environment]::GetEnvironmentVariable('Path', 'Machine')
  $user = [Environment]::GetEnvironmentVariable('Path', 'User')
  $links = Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Links'
  $env:Path = (@($machine, $user, $links) | Where-Object { $_ }) -join ';'
}

function Find-Exe([string]$name) {
  $c = Get-Command $name -ErrorAction SilentlyContinue | Select-Object -First 1
  if ($c) { return $c.Source }
  return $null
}

function Get-NodeMajor {
  $exe = Find-Exe 'node'
  if (-not $exe) { return $null }
  try {
    $v = (& $exe --version 2>$null | Select-Object -First 1)
    if ($v -match '^v(\d+)\.') { return @{ major = [int]$Matches[1]; text = $v.Trim(); path = $exe } }
  } catch { }
  return $null
}

function Find-Chrome {
  $cands = @(
    $env:CHROME_PATH,
    (Join-Path $env:ProgramFiles 'Google\Chrome\Application\chrome.exe'),
    (Join-Path ${env:ProgramFiles(x86)} 'Google\Chrome\Application\chrome.exe'),
    (Join-Path $env:LOCALAPPDATA 'Google\Chrome\Application\chrome.exe')
  )
  foreach ($c in $cands) { if ($c -and (Test-Path -LiteralPath $c)) { return $c } }
  return $null
}

function Test-Winget { return [bool](Find-Exe 'winget') }

# Cài 1 gói qua winget: thử --scope user trước (không cần quyền admin), không được thì cài bình thường (có thể hiện hộp UAC).
function Install-WingetPackage([string]$id, [string]$label) {
  $common = @('install', '--id', $id, '-e', '--silent', '--accept-package-agreements', '--accept-source-agreements', '--disable-interactivity')
  Say 'info' ("Đang cài $label qua winget ($id)…")
  Write-Log ("winget " + ($common -join ' ') + ' --scope user')
  $code = (Invoke-Native 'winget' 'winget' ($common + @('--scope', 'user'))).code
  if ($code -ne 0) {
    Write-Log ("winget --scope user thoát mã $code, thử cài cho cả máy")
    Say 'info' ("Bản cho riêng người dùng không có, cài cho cả máy (Windows có thể hỏi quyền admin, bấm Yes)…")
    $code = (Invoke-Native 'winget' 'winget' $common).code
  }
  Update-SessionPath
  return $code
}

function Test-Online {
  try {
    $r = Invoke-WebRequest -Uri 'https://github.com' -Method Head -UseBasicParsing -TimeoutSec 8
    return ($r.StatusCode -ge 200 -and $r.StatusCode -lt 400)
  } catch { return $false }
}

function New-LumIcon([string]$file) {
  if (Test-Path -LiteralPath $file) { return $true }
  try {
    Add-Type -AssemblyName System.Drawing
    $bmp = New-Object System.Drawing.Bitmap 64, 64
    $g = [System.Drawing.Graphics]::FromImage($bmp)
    $g.SmoothingMode = 'AntiAlias'
    $g.Clear([System.Drawing.Color]::FromArgb(255, 17, 17, 16))
    $brush = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(255, 255, 107, 44))
    $g.FillRectangle($brush, 22, 10, 20, 44)
    $g.Dispose()
    $icon = [System.Drawing.Icon]::FromHandle($bmp.GetHicon())
    $fs = [System.IO.File]::Create($file)
    $icon.Save($fs)
    $fs.Close()
    return $true
  } catch { Write-Log ("tạo icon lỗi: " + $_.Exception.Message); return $false }
}

function New-Shortcut([string]$lnk, [string]$target, [string]$workDir, [string]$icon) {
  $sh = New-Object -ComObject WScript.Shell
  $s = $sh.CreateShortcut($lnk)
  $s.TargetPath = $target
  $s.WorkingDirectory = $workDir
  $s.WindowStyle = 7
  $s.Description = 'LumReels: dựng video dọc từ mẫu'
  if ($icon -and (Test-Path -LiteralPath $icon)) { $s.IconLocation = $icon }
  $s.Save()
}

function Invoke-Main {
  Write-Log '================================================================'
  Write-Log ("Bắt đầu cài LumReels{0}. InstallDir=$InstallDir" -f $(if ($DryRun) { ' (DryRun)' } else { '' }))
  Write-Host ''
  Write-Host 'LumReels: bộ cài cho Windows' -ForegroundColor White
  if ($DryRun) { Write-Host '(chạy thử -DryRun: chỉ kiểm, không cài gì)' -ForegroundColor Cyan }
  Write-Host ("Log: $LogFile") -ForegroundColor DarkGray

  # ---- 1. Máy ----
  Say 'head' '1. Kiểm máy'
  $os = [Environment]::OSVersion.Version
  if ($os.Major -ge 10) { Say 'ok' ("Windows $($os.Major).$($os.Minor) build $($os.Build)") }
  else { Say 'fail' "Windows quá cũ ($os)" 'Cần Windows 10 hoặc 11.' }
  Say 'ok' ("PowerShell $($PSVersionTable.PSVersion)")
  if (-not [Environment]::Is64BitOperatingSystem) { Say 'fail' 'Windows 32-bit' 'LumReels cần Windows 64-bit.' }

  $drive = (Split-Path -Qualifier ([System.IO.Path]::GetFullPath($InstallDir)))
  try {
    $disk = Get-CimInstance -ClassName Win32_LogicalDisk -Filter ("DeviceID='{0}'" -f $drive)
    $freeGB = [math]::Round($disk.FreeSpace / 1GB, 1)
    if ($freeGB -ge $MIN_FREE_GB) { Say 'ok' ("Ổ $drive còn trống $freeGB GB") }
    else { Say 'fail' ("Ổ $drive chỉ còn $freeGB GB (cần ít nhất $MIN_FREE_GB GB)") 'Dọn bớt file, hoặc cài vào ổ khác: install.ps1 -InstallDir D:\LumReels\app' }
  } catch { Say 'warn' 'Không đọc được dung lượng ổ đĩa' }

  $online = Test-Online
  if ($online) { Say 'ok' 'Có mạng, vào được GitHub' }
  else { Say 'fail' 'Không vào được github.com' 'Kiểm tra mạng / proxy / VPN rồi chạy lại bộ cài.' }

  $hasWinget = Test-Winget
  if ($hasWinget) { Say 'ok' 'Có winget (trình cài gói của Windows)' }
  else {
    Say 'warn' 'Máy chưa có winget' 'Mở Microsoft Store, tìm "App Installer" (Trình cài đặt ứng dụng), bấm Cập nhật/Cài, rồi chạy lại bộ cài. Hoặc tự cài tay: Node 22+ (nodejs.org), ffmpeg (gyan.dev/ffmpeg), Chrome, Git (git-scm.com).'
  }

  # ---- 2. Phần mềm cần có ----
  Say 'head' '2. Phần mềm cần có'
  Update-SessionPath
  $deps = @(
    @{ key = 'node'; label = 'Node.js 22+'; id = 'OpenJS.NodeJS.LTS'; manual = 'Tải bản LTS ở https://nodejs.org rồi cài.' },
    @{ key = 'ffmpeg'; label = 'ffmpeg'; id = 'Gyan.FFmpeg'; manual = 'Tải ở https://www.gyan.dev/ffmpeg/builds/ và thêm thư mục bin vào PATH.' },
    @{ key = 'chrome'; label = 'Google Chrome'; id = 'Google.Chrome'; manual = 'Tải ở https://www.google.com/chrome/' },
    @{ key = 'git'; label = 'Git'; id = 'Git.Git'; manual = 'Tải ở https://git-scm.com/download/win' }
  )
  foreach ($d in $deps) {
    $found = $null; $detail = ''
    switch ($d.key) {
      'node' { $n = Get-NodeMajor; if ($n -and $n.major -ge $MIN_NODE) { $found = $n.path; $detail = $n.text } elseif ($n) { $detail = "đang có $($n.text), cần v$MIN_NODE trở lên" } }
      'ffmpeg' { $found = Find-Exe 'ffmpeg' }
      'chrome' { $found = Find-Chrome }
      'git' { $found = Find-Exe 'git' }
    }
    if ($found) { Say 'ok' ("$($d.label): có ($(if ($detail) { $detail } else { $found }))"); continue }
    $why = $(if ($detail) { " ($detail)" } else { '' })
    if ($DryRun) {
      if ($hasWinget) { Say 'plan' ("$($d.label): thiếu$why → sẽ cài: winget install --id $($d.id) -e --scope user") }
      else { Say 'fail' ("$($d.label): thiếu$why") $d.manual }
      continue
    }
    if (-not $hasWinget) { Say 'fail' ("$($d.label): thiếu$why") $d.manual; continue }
    $code = Install-WingetPackage $d.id $d.label
    $ok = $false
    switch ($d.key) {
      'node' { $n = Get-NodeMajor; $ok = [bool]($n -and $n.major -ge $MIN_NODE) }
      'ffmpeg' { $ok = [bool](Find-Exe 'ffmpeg') }
      'chrome' { $ok = [bool](Find-Chrome) }
      'git' { $ok = [bool](Find-Exe 'git') }
    }
    if ($ok) { Say 'ok' ("$($d.label): đã cài") }
    else { Say 'fail' ("$($d.label): cài không xong (winget mã $code)") ("Đóng cửa sổ này, mở lại LumReels-Setup.cmd (PATH mới chỉ có ở cửa sổ mới). Vẫn lỗi thì cài tay: " + $d.manual) }
  }

  $n = Get-NodeMajor
  $needCore = (-not (Find-Exe 'git')) -or (-not $n) -or ($n.major -lt $MIN_NODE)
  if ($needCore -and -not $DryRun) {
    Say 'head' 'Dừng lại'
    Say 'fail' "Thiếu Git hoặc Node $MIN_NODE+ nên chưa lấy mã được" 'Sửa các mục ✗ ở trên rồi chạy lại bộ cài (chạy lại an toàn).'
    return 1
  }

  # ---- 3. Mã LumReels ----
  Say 'head' '3. Mã LumReels'
  $want = $Ref
  if (-not $want) {
    if (Find-Exe 'git') { $want = Get-LatestTag }
    if ($want) { Say 'ok' "Bản phát hành mới nhất: $want" }
    else { Say 'warn' 'Repo chưa có tag phát hành (v*): dùng nhánh main, là mã mới nhất chưa qua phát hành' 'Muốn ghim bản cố định: install.ps1 -Ref <tag hoặc commit>' }
  } else { Say 'info' "Cài theo -Ref $want" }
  $isGit = Test-Path -LiteralPath (Join-Path $InstallDir '.git')
  $isEmpty = -not (Test-Path -LiteralPath $InstallDir) -or -not (Get-ChildItem -LiteralPath $InstallDir -Force -ErrorAction SilentlyContinue | Select-Object -First 1)
  if ($isGit) {
    if ($DryRun) { Say 'plan' ("Đã có ở $InstallDir → sẽ cập nhật " + $(if ($want) { "về $want (git fetch + checkout)" } else { '(git pull --ff-only)' })) }
    else {
      if ($want) {
        $c = Invoke-Native 'git' 'git' @('-C', $InstallDir, 'fetch', '--quiet', '--tags', 'origin')
        if ($c.code -eq 0) { $c = Invoke-Native 'git' 'git' @('-C', $InstallDir, 'checkout', '--quiet', $want) }
        # -Ref là tên nhánh: checkout xong thì kéo bản mới của nhánh đó
        if ($c.code -eq 0 -and (Invoke-Native 'git' 'git' @('-C', $InstallDir, 'symbolic-ref', '-q', 'HEAD')).code -eq 0) { $c = Invoke-Native 'git' 'git' @('-C', $InstallDir, 'pull', '--ff-only', '--quiet') }
      } else { $c = Invoke-Native 'git' 'git' @('-C', $InstallDir, 'pull', '--ff-only') }
      if ($c.code -eq 0) { Say 'ok' ("Đã cập nhật mã ở $InstallDir" + $(if ($want) { " ($want)" } else { '' })) }
      else { Say 'warn' 'Không cập nhật được (máy có sửa tay hoặc mất mạng), dùng bản đang có' "Tự gộp: cd `"$InstallDir`"; git stash; git pull; git stash pop" }
    }
  } elseif ($isEmpty) {
    if ($DryRun) { Say 'plan' ("Sẽ tải mã: git clone $Repo `"$InstallDir`"" + $(if ($want) { " rồi checkout $want" } else { '' })) }
    else {
      New-Item -ItemType Directory -Force -Path (Split-Path -Parent $InstallDir) | Out-Null
      $r = Invoke-Native 'git' 'git' @('clone', '--quiet', $Repo, $InstallDir)
      if ($r.code -eq 0 -and $want) { $r = Invoke-Native 'git' 'git' @('-C', $InstallDir, 'checkout', '--quiet', $want) }
      if ($r.code -eq 0) { Say 'ok' ("Đã tải mã vào $InstallDir" + $(if ($want) { " ($want)" } else { '' })) }
      else { Say 'fail' 'Tải mã từ GitHub lỗi' 'Kiểm tra mạng (và -Ref có tồn tại không) rồi chạy lại. Xem chi tiết trong install.log.'; return 1 }
    }
  } else {
    Say 'fail' "Thư mục $InstallDir đã có file nhưng không phải bản clone git" 'Đổi tên/xoá thư mục đó, hoặc cài chỗ khác: install.ps1 -InstallDir <thư mục trống>'
    if (-not $DryRun) { return 1 }
  }

  # ---- 4. Thư viện ----
  Say 'head' '4. Thư viện (npm install)'
  if ($DryRun) {
    if (Test-Path -LiteralPath (Join-Path $InstallDir 'node_modules\hyperframes')) { Say 'plan' 'Đã có node_modules → sẽ chạy lại npm install (nhanh, chỉ bù phần thiếu)' }
    else { Say 'plan' 'Sẽ chạy: npm install (tải khoảng 300 MB, 2–5 phút)' }
  } else {
    Push-Location $InstallDir
    try {
      Say 'info' 'Đang chạy npm install (lần đầu mất 2–5 phút)…'
      $code = (Invoke-Native 'npm' 'npm.cmd' @('install', '--no-audit', '--no-fund')).code
      if ($code -eq 0) { Say 'ok' 'Đã cài thư viện + font tiếng Việt' }
      else { Say 'fail' "npm install lỗi (mã $code)" "Xem install.log. Thử lại: cd `"$InstallDir`"; npm install" ; return 1 }
    } finally { Pop-Location }
  }

  # ---- 5. Shortcut ----
  Say 'head' '5. Shortcut'
  $launcher = Join-Path $InstallDir 'install\windows\start.cmd'
  if (-not $DryRun -and -not (Test-Path -LiteralPath $launcher)) {
    # bản trên GitHub chưa có launcher (cũ hơn bộ cài này): chép launcher đi kèm bộ cài ra thư mục riêng
    $own = $(if ($PSScriptRoot) { Join-Path $PSScriptRoot 'start.cmd' } else { $null })
    if ($own -and (Test-Path -LiteralPath $own)) {
      $ldir = Join-Path $BaseDir 'launcher'
      New-Item -ItemType Directory -Force -Path $ldir | Out-Null
      Copy-Item -LiteralPath $own, (Join-Path $PSScriptRoot 'start.ps1') -Destination $ldir -Force
      $launcher = Join-Path $ldir 'start.cmd'
    }
  }
  $icon = Join-Path $BaseDir 'lumreels.ico'
  $desktop = [Environment]::GetFolderPath('Desktop')
  $startMenu = Join-Path ([Environment]::GetFolderPath('Programs')) 'LumReels.lnk'
  $desk = Join-Path $desktop 'LumReels.lnk'
  if ($NoShortcut) { Say 'info' 'Bỏ qua shortcut (-NoShortcut)' }
  elseif ($DryRun) {
    foreach ($l in @($desk, $startMenu)) {
      if (Test-Path -LiteralPath $l) { Say 'ok' "Đã có: $l (sẽ ghi lại cho đúng đích)" } else { Say 'plan' "Sẽ tạo: $l → $launcher" }
    }
  } elseif (-not (Test-Path -LiteralPath $launcher)) {
    Say 'fail' 'Không thấy launcher start.cmd' 'Chạy tay: cd vào thư mục app rồi gõ npm start'
  } else {
    New-LumIcon $icon | Out-Null
    try {
      New-Shortcut $desk $launcher $InstallDir $icon
      New-Shortcut $startMenu $launcher $InstallDir $icon
      Say 'ok' 'Đã tạo shortcut "LumReels" ở Desktop và Start Menu'
    } catch { Say 'warn' ('Tạo shortcut lỗi: ' + $_.Exception.Message) "Mở app bằng: `"$launcher`"" }
  }

  # ---- Tổng kết ----
  Say 'head' 'Kết quả'
  if ($DryRun) {
    if ($script:Failed) { Say 'fail' "Có $($script:Failed) mục cần sửa tay trước khi cài (xem ✗ ở trên)" }
    else { Say 'ok' 'Máy cài được. Chạy lại không có -DryRun để cài thật.' }
    return [int]($script:Failed -gt 0)
  }
  if ($script:Failed) {
    Say 'fail' "Cài xong nhưng còn $($script:Failed) mục lỗi (xem ✗ ở trên, chi tiết trong $LogFile)"
    return 1
  }
  Say 'ok' 'Cài xong. Mở LumReels bằng shortcut "LumReels" trên Desktop.'
  Write-Host '    Lần đầu mở, app hiện màn "Kiểm tra máy" để nhập khoá AI hoặc nối Claude Code.' -ForegroundColor DarkGray
  if (-not $NoLaunch -and (Test-Path -LiteralPath $launcher)) {
    Say 'info' 'Đang mở LumReels…'
    Start-Process -FilePath $launcher -WorkingDirectory $InstallDir -WindowStyle Minimized
  }
  return 0
}

$code = 1
try { $code = Invoke-Main }
catch {
  Say 'fail' ('Lỗi không lường trước: ' + $_.Exception.Message) "Gửi file $LogFile khi báo lỗi."
  Write-Log ($_ | Out-String)
}
Write-Log ("Kết thúc, mã $code")
# chạy qua `irm | iex` thì không exit (sẽ đóng luôn cửa sổ PowerShell của người dùng)
$ErrorActionPreference = $savedEAP; $ProgressPreference = $savedPP; $OutputEncoding = $savedOE
if ($savedCOE) { try { [Console]::OutputEncoding = $savedCOE } catch { } }
if ($PSCommandPath) { exit $code }