<# 증바GG 내전 기록기 (PowerShell판). 윈도우에 기본으로 있는 Windows PowerShell 5.1에서 돈다. Node나 다른 설치가 필요 없다. 설치: PowerShell에 `irm https://jeungba.gg/rec | iex` (이 파일을 %LOCALAPPDATA%\JeungbaRecorder에 받고 -Install로 실행) 삭제: `irm https://jeungba.gg/rec-remove | iex` - 롤 클라이언트를 읽기만 한다. 게임이나 클라이언트에 아무것도 보내지 않는다. - 사설 방 게임이 시작되면 방 이름, 판 번호, 팀 명단을 적어 두고, 끝나면 그 판의 전적 상세를 records/에 저장한다. 끝난 판 전적에는 방 이름이 없어서(2026-11-13 확인) 게임 중에 받아 둔다. 사설 방 판은 그 판에 들어간 계정의 전적에만 보여서 방마다 그 방에 들어간 사람 한 명의 PC에서 돌아야 한다. - 사이트 연결: 처음 켜면 연결 코드를 받아 브라우저를 연다. 사이트에서 '이 기록기 연결'을 누르면 열쇠를 받아 state/token.json에 둔다. 방 이름에 내전 코드(JB4821, 예전 JB-XXXX)가 있는 판만 사이트로 올린다. 열쇠는 판 올리기와 연결 확인만 할 수 있다. - Node판(tools/naejeon-recorder/recorder.mjs)과 같은 동작이다. 사이트 API와 응답 처리는 그 README의 표와 같다. 스위치: -Install, -Uninstall, -Unlink, -NoTray(창에 기록을 찍음, 시험용), -RunSeconds N(N초 뒤 끝남, 시험용) #> [CmdletBinding()] param( [switch]$Install, [switch]$Uninstall, [switch]$Unlink, [switch]$NoTray, [int]$RunSeconds = 0 ) $Version = '0.4.0' $ErrorActionPreference = 'Continue' $ProgressPreference = 'SilentlyContinue' $Here = Split-Path -Parent $MyInvocation.MyCommand.Path $Self = $MyInvocation.MyCommand.Path $InstallDir = Join-Path $env:LOCALAPPDATA 'JeungbaRecorder' $AppName = '증바 내전 기록기' $Utf8 = New-Object System.Text.UTF8Encoding($false) $PowerShellExe = Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe' $UA = "JeungbaRecorder/$Version-ps (+https://jeungba.gg)" if ($NoTray) { try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch { } } # ---- 파일 ---------------------------------------------------------------------------------- function Write-Text([string]$Path, [string]$Text) { [System.IO.File]::WriteAllText($Path, $Text, $Utf8) } function Read-Text([string]$Path) { [System.IO.File]::ReadAllText($Path, [System.Text.Encoding]::UTF8) } function To-Json($Obj) { ConvertTo-Json -InputObject $Obj -Depth 20 -Compress } function Save-Json([string]$Path, $Obj) { $tmp = "$Path.tmp" Write-Text $tmp (To-Json $Obj) Move-Item -LiteralPath $tmp -Destination $Path -Force } function Read-Json([string]$Path) { if (-not (Test-Path -LiteralPath $Path)) { return $null } try { return (ConvertFrom-Json (Read-Text $Path)) } catch { return $null } } # ConvertFrom-Json은 배열을 통째로 한 덩어리로 내보내서, 원소를 하나씩 담은 목록으로 바꾼다. function To-List($Value) { $list = New-Object System.Collections.ArrayList if ($null -ne $Value) { foreach ($x in $Value) { [void]$list.Add($x) } } return , $list } function To-Hashtable($Obj) { $h = @{} if ($null -ne $Obj) { foreach ($p in $Obj.PSObject.Properties) { $h[$p.Name] = $p.Value } } return $h } function Now-Ms { [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() } # ---- 설치·삭제 ------------------------------------------------------------------------------- function Get-ShortcutPaths { $programs = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs' @((Join-Path $programs "$AppName.lnk"), (Join-Path (Join-Path $programs 'Startup') "$AppName.lnk")) } # 돌고 있는 기록기에 끝내라고 알리고(state/stop.flag) 끝날 때까지 기다린다. function Stop-Running([string]$Dir, [string]$MutexName) { $stateDir = Join-Path $Dir 'state' if (-not (Test-Path -LiteralPath $stateDir)) { return } $m = $null try { $m = [System.Threading.Mutex]::OpenExisting($MutexName) } catch { return } $m.Dispose() Write-Text (Join-Path $stateDir 'stop.flag') 'stop' for ($i = 0; $i -lt 40; $i++) { Start-Sleep -Milliseconds 250 try { $m = [System.Threading.Mutex]::OpenExisting($MutexName); $m.Dispose() } catch { return } } # 10초 안에 안 끝나면 이 스크립트를 돌리는 PowerShell만 골라 끈다. $target = Join-Path $Dir 'recorder.ps1' Get-CimInstance Win32_Process -Filter "name='powershell.exe'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($target) -and $_.ProcessId -ne $PID } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } } function New-TrayIcon { Add-Type -AssemblyName System.Drawing $bmp = New-IconBitmap [System.Drawing.Icon]::FromHandle($bmp.GetHicon()) } # 바로가기 아이콘 파일(PNG를 담은 .ico, 윈도우 비스타 이후 지원) function Save-IconFile([string]$Path) { Add-Type -AssemblyName System.Drawing $ms = New-Object System.IO.MemoryStream (New-IconBitmap).Save($ms, [System.Drawing.Imaging.ImageFormat]::Png) $png = $ms.ToArray() $fs = [System.IO.File]::Create($Path) $w = New-Object System.IO.BinaryWriter ($fs) $w.Write([uint16]0); $w.Write([uint16]1); $w.Write([uint16]1) $w.Write([byte]32); $w.Write([byte]32); $w.Write([byte]0); $w.Write([byte]0) $w.Write([uint16]1); $w.Write([uint16]32); $w.Write([uint32]$png.Length); $w.Write([uint32]22) $w.Write($png) $w.Close() } function New-IconBitmap { Add-Type -AssemblyName System.Drawing $bmp = New-Object System.Drawing.Bitmap 32, 32 $g = [System.Drawing.Graphics]::FromImage($bmp) $g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias $g.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit $g.Clear([System.Drawing.Color]::Transparent) $brush = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(255, 0x2B, 0x6E, 0xF2)) $g.FillEllipse($brush, 1, 1, 30, 30) $font = New-Object System.Drawing.Font ('Malgun Gothic', 15, [System.Drawing.FontStyle]::Bold, [System.Drawing.GraphicsUnit]::Pixel) $sf = New-Object System.Drawing.StringFormat $sf.Alignment = [System.Drawing.StringAlignment]::Center $sf.LineAlignment = [System.Drawing.StringAlignment]::Center $g.DrawString('내', $font, [System.Drawing.Brushes]::White, (New-Object System.Drawing.RectangleF (0, 1, 32, 32)), $sf) $g.Dispose() return $bmp } if ($Install) { $target = Join-Path $InstallDir 'recorder.ps1' New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null if ([System.IO.Path]::GetFullPath($Self) -ne [System.IO.Path]::GetFullPath($target)) { Copy-Item -LiteralPath $Self -Destination $target -Force } Write-Host "$AppName $Version 설치 중..." Stop-Running $InstallDir 'Local\JeungbaNaejeonRecorder' # 바로가기 아이콘 $ico = Join-Path $InstallDir 'icon.ico' try { Save-IconFile $ico } catch { $ico = $PowerShellExe } $shell = New-Object -ComObject WScript.Shell foreach ($lnkPath in (Get-ShortcutPaths)) { New-Item -ItemType Directory -Force -Path (Split-Path -Parent $lnkPath) | Out-Null $lnk = $shell.CreateShortcut($lnkPath) $lnk.TargetPath = $PowerShellExe $lnk.Arguments = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$target`"" $lnk.WorkingDirectory = $InstallDir $lnk.IconLocation = "$ico,0" $lnk.Description = $AppName $lnk.Save() } Write-Host '시작 메뉴와 시작 프로그램에 바로가기를 만들었어요. 윈도우를 켜면 같이 켜져요.' Start-Process -FilePath $PowerShellExe -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden', '-File', "`"$target`"") -WindowStyle Hidden Write-Host '기록기를 켰어요. 화면 오른쪽 아래 알림 영역에 파란 동그라미로 있어요.' if (-not (Test-Path -LiteralPath (Join-Path $InstallDir 'state\token.json'))) { Write-Host "곧 브라우저가 열려요. 브라우저에서 '이 기록기 연결'만 누르면 끝이에요." } else { Write-Host '이미 사이트에 연결돼 있어요. 이제 이 창은 닫아도 돼요.' } exit 0 } if ($Uninstall) { Set-Location -LiteralPath $env:TEMP Write-Host "$AppName 지우는 중..." Stop-Running $InstallDir 'Local\JeungbaNaejeonRecorder' foreach ($lnkPath in (Get-ShortcutPaths)) { Remove-Item -LiteralPath $lnkPath -Force -ErrorAction SilentlyContinue } if (Test-Path -LiteralPath $InstallDir) { Remove-Item -LiteralPath $InstallDir -Recurse -Force -ErrorAction SilentlyContinue } if (Test-Path -LiteralPath $InstallDir) { Write-Host "일부 파일을 지우지 못했어요. 이 폴더를 직접 지워 주세요: $InstallDir" } else { Write-Host '다 지웠어요. 사이트 연결은 jeungba.gg 내 기록방의 "연결된 내전 기록기"에서 끊을 수 있어요.' } exit 0 } # ---- 설정 ------------------------------------------------------------------------------------ $Records = Join-Path $Here 'records' $State = Join-Path $Here 'state' New-Item -ItemType Directory -Force -Path $Records | Out-Null New-Item -ItemType Directory -Force -Path $State | Out-Null $cfg = @{ lockfile = '' # 방 이름에서 찾을 내전 코드. 새 코드 JB4821(뒤에 '2경기'), 예전 코드 JB-TAMN(뒤에 '-2'). 뒤에 글자·숫자가 더 붙은 코드는 버린다. codePattern = 'JB-?[A-Z0-9]{4}(?:(?:-|\s+)[0-9]{1,2}(?:경기)?)?(?![A-Z0-9])' onlyCustom = $true pollSeconds = 3 retrySeconds = 20 giveUpMinutes = 30 siteUrl = 'https://jeungba.gg' openBrowser = $true uploadRetrySeconds = 300 augmentsUrl = 'https://jeungba.gg/recorder/augments.json' mutexName = 'Local\JeungbaNaejeonRecorder' } $userCfg = Read-Json (Join-Path $Here 'config.json') if ((Test-Path -LiteralPath (Join-Path $Here 'config.json')) -and -not $userCfg) { Write-Host 'config.json을 읽지 못해 기본 설정으로 켜요.' } if ($userCfg) { foreach ($p in $userCfg.PSObject.Properties) { $cfg[$p.Name] = $p.Value } } $Code = New-Object System.Text.RegularExpressions.Regex ($cfg.codePattern, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) $SiteBase = ([string]$cfg.siteUrl).TrimEnd('/') $SiteOn = [bool]$SiteBase $StopFlag = Join-Path $State 'stop.flag' $LogFile = Join-Path $State 'recorder.log' if ($Unlink) { Remove-Item -LiteralPath (Join-Path $State 'token.json') -Force -ErrorAction SilentlyContinue Write-Host '사이트 연결을 지웠어요. 다음에 켜면 새 연결 코드를 받아요.' exit 0 } # 사이트는 TLS 1.2 이상으로만 받는다. try { [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12 } catch { } [System.Net.ServicePointManager]::Expect100Continue = $false # ---- 기록과 알림 ----------------------------------------------------------------------------- $script:tray = $null $script:status = '시작하는 중' function Write-Log([string]$Msg) { $line = "$((Get-Date).ToString('HH:mm:ss')) $Msg" if ($NoTray) { Write-Host $line } try { if ((Test-Path -LiteralPath $LogFile) -and ((Get-Item -LiteralPath $LogFile).Length -gt 1MB)) { Move-Item -LiteralPath $LogFile -Destination "$LogFile.1" -Force } [System.IO.File]::AppendAllText($LogFile, "$((Get-Date).ToString('yyyy-MM-dd')) $line`r`n", $Utf8) } catch { } } function Set-Status([string]$Text) { $script:status = $Text if ($script:tray) { $t = "$AppName · $Text" if ($t.Length -gt 63) { $t = $t.Substring(0, 63) } $script:tray.Text = $t } } function Show-Note([string]$Title, [string]$Text) { if ($script:tray) { try { $script:tray.ShowBalloonTip(6000, $Title, $Text, [System.Windows.Forms.ToolTipIcon]::Info) } catch { } } } # ---- HTTP ------------------------------------------------------------------------------------ # 응답: @{ status; text; json }. 닿지 않으면 status 0. 4xx·5xx도 본문을 읽는다. # -Lcu면 그 요청 하나에만 롤 클라이언트의 자체 서명 인증서를 허용한다(사이트 요청은 정상 검사). function Invoke-Http { param([string]$Method, [string]$Url, [hashtable]$Headers, [string]$Body, [switch]$Lcu, [int]$TimeoutSec = 20, [switch]$Bytes) $r = @{ status = 0; text = ''; json = $null; bytes = $null } try { $req = [System.Net.HttpWebRequest]::Create($Url) $req.Method = $Method $req.Timeout = $TimeoutSec * 1000 $req.ReadWriteTimeout = $TimeoutSec * 1000 $req.UserAgent = $UA $req.Accept = 'application/json' $req.AllowAutoRedirect = $false if ($Lcu) { $req.ServerCertificateValidationCallback = { $true } $req.Proxy = $null } if ($Headers) { foreach ($k in $Headers.Keys) { $req.Headers[$k] = $Headers[$k] } } if ($PSBoundParameters.ContainsKey('Body') -and $null -ne $Body) { $data = [System.Text.Encoding]::UTF8.GetBytes($Body) $req.ContentType = 'application/json; charset=utf-8' $req.ContentLength = $data.Length $s = $req.GetRequestStream() $s.Write($data, 0, $data.Length) $s.Close() } elseif ($Method -eq 'POST') { $req.ContentLength = 0 } $res = $null try { $res = $req.GetResponse() } catch { $e = $_.Exception while ($e -and -not ($e -is [System.Net.WebException])) { $e = $e.InnerException } if ($e -and $e.Response) { $res = $e.Response } else { return $r } } $r.status = [int]$res.StatusCode $stream = $res.GetResponseStream() $ms = New-Object System.IO.MemoryStream $stream.CopyTo($ms) $res.Close() $raw = $ms.ToArray() if ($Bytes) { $r.bytes = $raw } $r.text = [System.Text.Encoding]::UTF8.GetString($raw) if ($r.text) { try { $r.json = ConvertFrom-Json $r.text } catch { } } } catch { } return $r } # ---- 롤 클라이언트(LCU) ---------------------------------------------------------------------- function Read-LockfileAt([string]$Path) { try { if (-not (Test-Path -LiteralPath $Path)) { return $null } $fs = New-Object System.IO.FileStream ($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, ([System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)) $sr = New-Object System.IO.StreamReader ($fs, [System.Text.Encoding]::UTF8) $text = $sr.ReadToEnd() $sr.Close() $parts = $text.Split(':') if ($parts.Count -ge 4 -and [int]$parts[2] -gt 0 -and $parts[3]) { return @{ port = [int]$parts[2]; password = $parts[3] } } } catch { } return $null } function Find-Lcu { # 설정에 lockfile을 적었으면 그것만 본다(시험할 때 진짜 클라이언트에 붙지 않게). if ($cfg.lockfile) { return (Read-LockfileAt $cfg.lockfile) } foreach ($p in @('C:/Riot Games/League of Legends/lockfile', 'D:/Riot Games/League of Legends/lockfile')) { $found = Read-LockfileAt $p if ($found) { return $found } } # 설치 경로가 다르면 실행 중인 클라이언트의 실행 인자에서 찾는다. try { $cl = (Get-CimInstance Win32_Process -Filter "name='LeagueClientUx.exe'" -ErrorAction Stop | Select-Object -First 1).CommandLine if ($cl) { $port = [regex]::Match($cl, '--app-port=(\d+)').Groups[1].Value $pw = [regex]::Match($cl, '--remoting-auth-token=([\w-]+)').Groups[1].Value if ($port -and $pw) { return @{ port = [int]$port; password = $pw } } } } catch { } return $null } function Get-Lcu([hashtable]$L, [string]$Path) { $auth = 'Basic ' + [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("riot:$($L.password)")) Invoke-Http -Method GET -Url "https://127.0.0.1:$($L.port)$Path" -Headers @{ Authorization = $auth } -Lcu -TimeoutSec 15 } # ---- 기록 중인 판 ----------------------------------------------------------------------------- $PendingFile = Join-Path $State 'pending.json' $script:pending = To-List (Read-Json $PendingFile) function Save-Pending { Save-Json $PendingFile ([object[]]$script:pending.ToArray()) } $script:saved = New-Object 'System.Collections.Generic.HashSet[string]' foreach ($f in (Get-ChildItem -LiteralPath $Records -Filter '*.json' -ErrorAction SilentlyContinue)) { [void]$script:saved.Add($f.BaseName.Split('_')[-1]) } $InGame = @('GameStart', 'InProgress', 'Reconnect') function Pick-Player($p) { $name = $p.gameName if (-not $name) { $name = $p.summonerName } [ordered]@{ puuid = [string]$p.puuid; name = [string]$name; tagLine = [string]$p.tagLine; championId = $(if ($p.championId) { $p.championId } else { 0 }) } } function New-Capture($Session, $LastLobby) { $gd = $Session.gameData $lobbyName = [string]$gd.gameName if (-not $lobbyName -and $LastLobby) { $lobbyName = $LastLobby.name } $m = $Code.Match($lobbyName) $code = '' if ($m.Success) { $code = $m.Value.ToUpper() } $queueId = 0; $gameMode = ''; $mapId = 0 if ($gd.queue) { $queueId = $gd.queue.id; $gameMode = $gd.queue.gameMode; $mapId = $gd.queue.mapId } if (-not $gameMode -and $Session.map) { $gameMode = $Session.map.gameMode } if (-not $mapId -and $Session.map) { $mapId = $Session.map.id } $one = @(); foreach ($p in $gd.teamOne) { $one += , (Pick-Player $p) } $two = @(); foreach ($p in $gd.teamTwo) { $two += , (Pick-Player $p) } $seen = '' if ($LastLobby) { $seen = $LastLobby.name } [pscustomobject][ordered]@{ gameId = $gd.gameId lobbyName = $lobbyName lobbyNameSeenInLobby = $seen code = $code isCustomGame = [bool]$gd.isCustomGame queueId = $queueId gameMode = [string]$gameMode mapId = $mapId teamOne = $one teamTwo = $two startedAt = (Now-Ms) endedAt = 0 lastTry = 0 eog = $null } } function Find-Pending($GameId) { foreach ($p in $script:pending) { if ("$($p.gameId)" -eq "$GameId") { return $p } } return $null } # ---- 이름(챔피언·아이템·주문·증강)과 HTML ---------------------------------------------------- $script:names = $null function Get-Names { if ($script:names) { return $script:names } $cache = Join-Path $State 'names.json' $old = Read-Json $cache $n = $null try { $vr = Invoke-Http -Method GET -Url 'https://ddragon.leagueoflegends.com/api/versions.json' -TimeoutSec 10 $v = @($vr.json)[0] if (-not $v) { throw 'no version' } if ($old -and $old.version -eq $v -and $old.augs -and @($old.augs.PSObject.Properties).Count -gt 0) { $n = $old } else { $dd = { param($f) (Invoke-Http -Method GET -Url "https://ddragon.leagueoflegends.com/cdn/$v/data/ko_KR/$f.json" -TimeoutSec 20).json.data } $champs = @{}; foreach ($c in (& $dd 'champion').PSObject.Properties) { $champs[[string]$c.Value.key] = $c.Value.name } $items = @{}; foreach ($c in (& $dd 'item').PSObject.Properties) { $items[[string]$c.Name] = $c.Value.name } $spells = @{}; foreach ($c in (& $dd 'summoner').PSObject.Properties) { $spells[[string]$c.Value.key] = $c.Value.name } $augs = @{} $ar = Invoke-Http -Method GET -Url $cfg.augmentsUrl -TimeoutSec 15 if ($ar.status -eq 200 -and $ar.json) { foreach ($c in $ar.json.PSObject.Properties) { $augs[[string]$c.Name] = @($c.Value) } } if ($champs.Count -eq 0) { throw 'no champions' } $n = [pscustomobject]@{ version = $v; champs = $champs; items = $items; spells = $spells; augs = $augs } Save-Json $cache $n $n = Read-Json $cache } } catch { $n = $old } if (-not $n) { $n = [pscustomobject]@{ champs = @{}; items = @{}; spells = @{}; augs = @{} } } $script:names = [pscustomobject]@{ champs = (To-Hashtable $n.champs); items = (To-Hashtable $n.items); spells = (To-Hashtable $n.spells); augs = (To-Hashtable $n.augs) } return $script:names } function Enc($s) { [System.Net.WebUtility]::HtmlEncode([string]$s) } $Ko = [System.Globalization.CultureInfo]::GetCultureInfo('ko-KR') function N0($v) { if ($null -eq $v) { $v = 0 }; ([double]$v).ToString('N0', $Ko) } function Local-Time([long]$Ms) { [DateTimeOffset]::FromUnixTimeMilliseconds($Ms).LocalDateTime } $Style = @' :root{--bg:#f6f6f4;--card:#fff;--ink:#1b1b1b;--sub:#6b6b6b;--line:#e3e3df;--blue:#2b6ef2;--red:#c2453d} @media (prefers-color-scheme:dark){:root{--bg:#141414;--card:#1e1e1e;--ink:#eee;--sub:#9a9a9a;--line:#333}} body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 "Pretendard","Malgun Gothic",system-ui,sans-serif} main{max-width:1240px;margin:0 auto;padding:28px 16px 60px}h1{font-size:24px;margin:0 0 6px}.lead{color:var(--sub);margin:0 0 20px} a{color:var(--blue)}.meta{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin-bottom:24px} .meta div{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px 12px}.meta b{display:block;font-size:16px}.meta span{color:var(--sub);font-size:13px} h2{font-size:17px;margin:24px 0 10px;padding-left:10px;border-left:4px solid}h2.t100{border-color:var(--blue)}h2.t200{border-color:var(--red)} .scroll{overflow-x:auto;background:var(--card);border:1px solid var(--line);border-radius:10px} table{border-collapse:collapse;width:100%;min-width:1100px}th,td{padding:9px 10px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top} th{font-size:12px;color:var(--sub);font-weight:600;white-space:nowrap}tr:last-child td{border-bottom:0} td.n,td.kda{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums}td.kda{font-weight:600} .who b{display:block;white-space:nowrap}.who span,.sub{display:block;color:var(--sub);font-size:12px}td.ch{white-space:nowrap} .tags i{display:inline-block;font-style:normal;font-size:12px;border:1px solid var(--line);border-radius:6px;padding:1px 6px;margin:0 4px 4px 0;white-space:nowrap} .tags i.r-prism{border-color:#b77ce8}.tags i.r-gold{border-color:#d9a93a}.tags i.r-silver{border-color:#9aa3ad}.sp{font-size:13px;white-space:nowrap} .ok{color:var(--blue);font-weight:600}.no{color:var(--sub)} '@ function Head([string]$Title) { "$(Enc $Title)
" } function Render-Game($Rec) { $c = $Rec.capture $g = $Rec.match if (-not $g) { $t1 = ($c.teamOne | ForEach-Object { Enc "$($_.name)#$($_.tagLine)" }) -join ', ' $t2 = ($c.teamTwo | ForEach-Object { Enc "$($_.name)#$($_.tagLine)" }) -join ', ' $name = $c.lobbyName; if (-not $name) { $name = '사설 방' } return (Head "내전 기록 $($c.gameId)") + "

$(Enc $name)

전적 상세를 받지 못해 게임 시작 때 받은 명단만 남았어요.

$(Enc (Local-Time $c.startedAt).ToString('g', $Ko)) · 판 번호 $($c.gameId)

팀 1: $t1
팀 2: $t2

" } $nm = Get-Names $ids = @{} foreach ($pi in $g.participantIdentities) { $ids["$($pi.participantId)"] = $pi.player } $sb = New-Object System.Text.StringBuilder $name = $c.lobbyName; if (-not $name) { $name = '사설 방' } [void]$sb.Append((Head "내전 기록 $($g.gameId)")) [void]$sb.Append('

← 기록 목록

') [void]$sb.Append("

$(Enc $name)

") if ($c.code) { [void]$sb.Append("

내전 코드 $(Enc $c.code)

") } else { [void]$sb.Append('

방 이름에 내전 코드가 없어요

') } $created = Local-Time $g.gameCreation $mode = $g.gameMode; if ($g.queueId -eq 3270) { $mode = '사설 증바람' } $size100 = @($g.participants | Where-Object { $_.teamId -eq 100 }).Count $size200 = @($g.participants | Where-Object { $_.teamId -eq 200 }).Count $patch = (([string]$g.gameVersion).Split('.') | Select-Object -First 2) -join '.' [void]$sb.Append('
') [void]$sb.Append("
$($created.ToString('d', $Ko))$($created.ToString('HH:mm')) 시작
") [void]$sb.Append("
$([math]::Floor($g.gameDuration / 60))분 $($g.gameDuration % 60)초게임 시간
") [void]$sb.Append("
$(Enc $mode)큐 $($g.queueId) · $(Enc $g.gameMode)
") [void]$sb.Append("
$size100 대 $size200인원
") [void]$sb.Append("
$(Enc $patch)패치
") [void]$sb.Append("
$($g.gameId)판 번호
") foreach ($teamId in 100, 200) { $ps = @($g.participants | Where-Object { $_.teamId -eq $teamId }) if (-not $ps.Count) { continue } $won = [bool]$ps[0].stats.win $kills = 0; foreach ($p in $ps) { $kills += [int]$p.stats.kills } $side = '레드'; if ($teamId -eq 100) { $side = '블루' } $result = '패배'; if ($won) { $result = '승리' } [void]$sb.Append("

$side 팀 · $result · $($ps.Count)명 · 킬 $kills

") [void]$sb.Append('
') foreach ($p in $ps) { $s = $p.stats $who = $ids["$($p.participantId)"] $wn = $who.gameName; if (-not $wn) { $wn = $who.summonerName } $champ = $nm.champs["$($p.championId)"]; if (-not $champ) { $champ = $p.championId } $augHtml = '' foreach ($i in 1..6) { $a = $s."playerAugment$i" if ($a) { $info = $nm.augs["$a"] $an = "$a"; $ar = 'x' if ($info) { $an = $info[0]; $ar = $info[1] } $augHtml += "$(Enc $an)" } } $itemHtml = '' foreach ($i in 0..5) { $it = $s."item$i" if ($it) { $iname = $nm.items["$it"]; if (-not $iname) { $iname = $it }; $itemHtml += "$(Enc $iname)" } } $sp1 = $nm.spells["$($p.spell1Id)"]; if (-not $sp1) { $sp1 = $p.spell1Id } $sp2 = $nm.spells["$($p.spell2Id)"]; if (-not $sp2) { $sp2 = $p.spell2Id } $cs = [int]$s.totalMinionsKilled + [int]$s.neutralMinionsKilled [void]$sb.Append("") } [void]$sb.Append('
플레이어챔피언K / D / A챔피언 피해받은 피해회복골드CS증강아이템주문
$(Enc $wn)#$(Enc $who.tagLine)$(Enc $champ)레벨 $($s.champLevel)$([int]$s.kills) / $([int]$s.deaths) / $([int]$s.assists)$(N0 $s.totalDamageDealtToChampions)$(N0 $s.totalDamageTaken)$(N0 $s.totalHeal)$(N0 $s.goldEarned)$cs$augHtml$itemHtml$(Enc $sp1)
$(Enc $sp2)
') } [void]$sb.Append('') return $sb.ToString() } # 목록은 판마다 한 줄 요약(state/records-index.json)으로 만든다(판 JSON을 매번 다 읽지 않게). $IndexFile = Join-Path $State 'records-index.json' $script:index = To-List (Read-Json $IndexFile) function Summary-Of([string]$File, $Rec) { $c = $Rec.capture $g = $Rec.match $winner = '결과 없음' $people = @($c.teamOne).Count + @($c.teamTwo).Count $queue = $c.queueId $when = $c.startedAt if ($g) { $w = @($g.participants | Where-Object { $_.stats.win } | Select-Object -First 1) if ($w.Count) { if ($w[0].teamId -eq 100) { $winner = '블루 승' } else { $winner = '레드 승' } } $people = @($g.participants).Count $queue = $g.queueId if ($g.gameCreation) { $when = $g.gameCreation } } [pscustomobject]@{ file = $File; gameId = "$($c.gameId)"; when = $when; lobbyName = [string]$c.lobbyName; code = [string]$c.code; queueId = $queue; people = $people; winner = $winner } } if ($script:index.Count -eq 0) { foreach ($f in (Get-ChildItem -LiteralPath $Records -Filter '*.json' -ErrorAction SilentlyContinue)) { $rec = Read-Json $f.FullName if ($rec) { [void]$script:index.Add((Summary-Of $f.Name $rec)) } } } $StatusFile = Join-Path $State 'upload-status.json' $script:uploadStatus = To-Hashtable (Read-Json $StatusFile) function Save-Status { Save-Json $StatusFile $script:uploadStatus } function Rebuild-Index { $rows = New-Object System.Text.StringBuilder foreach ($r in ($script:index | Sort-Object -Property @{ Expression = { [long]$_.when } } -Descending)) { $name = $r.lobbyName; if (-not $name) { $name = '사설 방' } $codeHtml = '없음'; if ($r.code) { $codeHtml = "$(Enc $r.code)" } $st = $script:uploadStatus[$r.gameId] if (-not $st) { if ($r.code) { $st = '' } else { $st = '코드 없음' } } [void]$rows.Append("$(Enc (Local-Time $r.when).ToString('g', $Ko))$(Enc $name)$codeHtml$($r.queueId)$($r.people)명$(Enc $r.winner)$(Enc $st)") } $body = $rows.ToString() if (-not $body) { $body = '아직 기록이 없어요. 사설 방 게임을 하면 여기에 쌓여요.' } Write-Text (Join-Path $Records 'index.html') ((Head '내전 기록') + "

내전 기록

이 PC의 내전 기록기가 저장한 사설 방 판이에요(최신 순).

$body
시작방 이름내전 코드큐인원결과사이트
") } # ---- 사이트 연동 ----------------------------------------------------------------------------- $TokenFile = Join-Path $State 'token.json' $UploadsFile = Join-Path $State 'uploads.json' $tok = Read-Json $TokenFile $script:site = @{ token = ''; nickname = ''; checked = $false linking = $false; linkTried = $false; quietUntil = [long]0 deviceCode = ''; linkDeadline = [long]0; nextPoll = [long]0; interval = 5 } if ($tok -and $tok.token) { $script:site.token = [string]$tok.token; $script:site.nickname = [string]$tok.nickname } $script:myPuuid = '' $script:uploads = To-List (Read-Json $UploadsFile) function Save-Uploads { Save-Json $UploadsFile ([object[]]$script:uploads.ToArray()) } function Site-Request([string]$Method, [string]$Path, $Body, [string]$Token) { $headers = @{} if ($Token) { $headers['Authorization'] = "Bearer $Token" } if ($null -ne $Body) { return (Invoke-Http -Method $Method -Url "$SiteBase$Path" -Headers $headers -Body (To-Json $Body) -TimeoutSec 20) } Invoke-Http -Method $Method -Url "$SiteBase$Path" -Headers $headers -TimeoutSec 20 } function Save-Token([string]$Token, [string]$Nickname) { $script:site.token = $Token $script:site.nickname = [string]$Nickname Save-Json $TokenFile ([ordered]@{ token = $Token; nickname = $script:site.nickname; linkedAt = (Now-Ms) }) } function Open-Url([string]$Url) { if (-not $cfg.openBrowser) { return } try { Start-Process $Url } catch { } } # 사이트에 기능이 없거나(4xx) 닿지 않으면(0) 30분 동안 조용히 이 PC에만 저장한다. function Site-Unavailable([int]$Status) { if ($Status -ge 200 -and $Status -lt 300) { return $false } if ((Now-Ms) -ge $script:site.quietUntil) { if ($Status -ge 400 -and $Status -lt 500) { Write-Log '사이트 연동이 아직 준비되지 않았어요. 기록은 이 PC에 저장하고, 내전 코드가 있는 판은 나중에 올릴게요.' } else { Write-Log '사이트에 닿지 않아요. 기록은 이 PC에 저장하고 나중에 다시 올릴게요.' } } $script:site.quietUntil = (Now-Ms) + 30 * 60000 return $true } function Start-Link { $script:site.linkTried = $true $start = Site-Request POST '/api/recorder/link/start' @{} if ($start.status -ne 201 -and $start.status -ne 200) { [void](Site-Unavailable $start.status); return } $j = $start.json $interval = 5; if ($j.interval) { $interval = [int]$j.interval } $expires = 600; if ($j.expiresIn) { $expires = [int]$j.expiresIn } $url = [string]$j.verifyUrl if (-not $url) { $url = "$SiteBase/recorder/link/?code=$([uri]::EscapeDataString([string]$j.userCode))" } $script:site.linking = $true $script:site.deviceCode = [string]$j.deviceCode $script:site.interval = [math]::Max(3, $interval) $script:site.linkDeadline = (Now-Ms) + $expires * 1000 $script:site.nextPoll = (Now-Ms) + $script:site.interval * 1000 Write-Log "사이트 연결 코드: $($j.userCode)" Write-Log "브라우저에서 로그인하고 같은 코드가 보이면 '이 기록기 연결'을 눌러 주세요: $url" Set-Status "연결 코드 $($j.userCode)" Show-Note '사이트에 연결해 주세요' "브라우저에서 코드 $($j.userCode)가 보이면 '이 기록기 연결'을 눌러 주세요." Open-Url $url } function Poll-Link { $now = Now-Ms if ($now -lt $script:site.nextPoll) { return } if ($now -ge $script:site.linkDeadline) { Stop-Link; return } $script:site.nextPoll = $now + $script:site.interval * 1000 $r = Site-Request POST '/api/recorder/link/poll' @{ deviceCode = $script:site.deviceCode } if ($r.status -eq 200 -and $r.json.status -eq 'approved' -and $r.json.token) { Save-Token ([string]$r.json.token) ([string]$r.json.nickname) $script:site.checked = $true $script:site.linking = $false $who = ''; if ($script:site.nickname) { $who = "($($script:site.nickname))" } Write-Log "사이트에 연결했어요$who. 내전 코드가 있는 판은 이제 사이트로 올라가요." Set-Status '사이트 연결됨' Show-Note '사이트에 연결했어요' '이제 켜 두기만 하면 돼요. 내전 판이 끝나면 자동으로 올라가요.' return } if ($r.status -eq 410 -or $r.json.status -eq 'expired') { Stop-Link } } function Stop-Link { $script:site.linking = $false Write-Log '연결 코드가 만료됐어요. 다음에 기록기를 켜면 새 코드를 받아요.' Set-Status '사이트 연결 안 됨' $script:site.quietUntil = (Now-Ms) + 30 * 60000 } function Check-Token { $script:site.checked = $true $r = Site-Request GET '/api/recorder/me' $null $script:site.token if ($r.status -eq 401) { Remove-Item -LiteralPath $TokenFile -Force -ErrorAction SilentlyContinue $script:site.token = '' Write-Log '사이트 연결이 해제돼 있어요. 다시 연결할게요.' } elseif ($r.status -eq 200) { if ($r.json.nickname) { $script:site.nickname = [string]$r.json.nickname } $who = ''; if ($script:site.nickname) { $who = "($($script:site.nickname))" } Write-Log "사이트에 연결돼 있어요$who." } else { [void](Site-Unavailable $r.status) } } # 전적 상세에서 사이트에 보낼 것만 고른다(원본 전체를 보내지 않는다). function Compact-Match($M) { $ids = @{} foreach ($pi in $M.participantIdentities) { $ids["$($pi.participantId)"] = $pi.player } $players = @() foreach ($p in $M.participants) { $s = $p.stats $who = $ids["$($p.participantId)"] $gn = $who.gameName; if (-not $gn) { $gn = $who.summonerName } $augs = @(); foreach ($i in 1..6) { $a = $s."playerAugment$i"; if ($a) { $augs += $a } } $items = @(); foreach ($i in 0..6) { $it = $s."item$i"; if ($null -eq $it) { $it = 0 }; $items += $it } $players += , ([ordered]@{ puuid = [string]$who.puuid gameName = [string]$gn tagLine = [string]$who.tagLine team = $p.teamId win = [bool]$s.win championId = $p.championId champLevel = [int]$s.champLevel kills = [int]$s.kills deaths = [int]$s.deaths assists = [int]$s.assists damageToChampions = [long]$s.totalDamageDealtToChampions damageTaken = [long]$s.totalDamageTaken heal = [long]$s.totalHeal gold = [long]$s.goldEarned cs = [int]$s.totalMinionsKilled + [int]$s.neutralMinionsKilled augments = $augs items = $items spells = @($p.spell1Id, $p.spell2Id) }) } [ordered]@{ gameId = $M.gameId queueId = $M.queueId gameMode = $M.gameMode mapId = $M.mapId gameVersion = $M.gameVersion gameCreation = $M.gameCreation gameDuration = $M.gameDuration players = $players } } function Queue-Upload($Capture, $Match) { if (-not $SiteOn -or -not $Capture.code -or -not $Match) { return } foreach ($u in $script:uploads) { if ("$($u.gameId)" -eq "$($Capture.gameId)") { return } } $payload = [ordered]@{ version = 1; code = $Capture.code; lobbyName = $Capture.lobbyName; uploader = [ordered]@{ puuid = $script:myPuuid }; match = (Compact-Match $Match) } # 저장했다가 다시 읽은 것과 같은 모양(pscustomobject)으로 둔다. $item = ConvertFrom-Json (To-Json ([ordered]@{ gameId = $Capture.gameId; tries = 0; nextAt = 0; payload = $payload })) [void]$script:uploads.Add($item) Save-Uploads $script:uploadStatus["$($Capture.gameId)"] = '올릴 차례' Save-Status } function Finish-Upload($U, [string]$Status, [string]$Text) { $script:uploads.Remove($U) $script:uploadStatus["$($U.gameId)"] = $Status Save-Uploads Save-Status Write-Log $Text Rebuild-Index } function Retry-Upload($U) { $U.tries = [int]$U.tries + 1 $U.nextAt = (Now-Ms) + [int]$cfg.uploadRetrySeconds * 1000 Save-Uploads } function Flush-Uploads { if (-not $script:site.token -or (Now-Ms) -lt $script:site.quietUntil) { return } foreach ($u in @($script:uploads.ToArray())) { if ((Now-Ms) -lt [long]$u.nextAt) { continue } # 기록기 계정을 늦게 알았으면(클라이언트가 나중에 켜짐) 채운다. if (-not $u.payload.uploader.puuid -and $script:myPuuid) { $u.payload.uploader.puuid = $script:myPuuid } $r = Site-Request POST '/api/naejeon/games' $u.payload $script:site.token $code = $u.payload.code if ($r.status -eq 201 -and $r.json.pending) { $who = (@($r.json.unknown) | ForEach-Object { if ($_.name) { $_.name } else { '이름 모름' } }) -join ', ' $extra = ''; if ($who) { $extra = "($who)" } Finish-Upload $u '올림(확인 필요)' "사이트에 올렸어요: 판 $($u.gameId)($code). 내전방 멤버와 이어지지 않은 계정이 있어 '확인 필요'로 들어갔어요$extra. 내전방 화면에서 한 번 이어 주면 반영돼요." Show-Note '사이트에 올렸어요(확인 필요)' '내전방 화면에서 이어지지 않은 계정을 한 번 골라 주세요.' } elseif ($r.status -eq 201) { $extra = '' if ($r.json.seriesId) { $extra = ', 내전방 대진에 붙었어요'; if ($r.json.closed) { $extra += '(시리즈 끝)' } } Finish-Upload $u '올림' "사이트에 올렸어요: 판 $($u.gameId)($code)$extra." Show-Note '사이트에 올렸어요' "판 $($u.gameId)($code)가 내전방에 들어갔어요." } elseif ($r.status -eq 200 -and $r.json.duplicate) { Finish-Upload $u '올림(다른 기록기가 먼저)' "판 $($u.gameId)는 같은 방의 다른 기록기가 이미 올렸어요." } elseif ($r.status -eq 401) { Remove-Item -LiteralPath $TokenFile -Force -ErrorAction SilentlyContinue $script:site.token = '' Write-Log '사이트 연결이 해제됐어요. 다시 연결한 뒤 남은 판을 올릴게요.' break } elseif ($r.status -eq 403 -and $null -eq $r.json) { # 사이트 앞단(Cloudflare 보안 설정)이 막은 것이다. 판 문제가 아니라서 버리지 않고 나중에 다시 보낸다. Retry-Upload $u if ($u.tries -eq 1) { Write-Log "사이트 보안 설정에 막혀 판 $($u.gameId)를 올리지 못했어요. 나중에 다시 보낼게요." } break } elseif ($r.status -eq 403 -and $r.json.error -eq 'not a member of this room') { Finish-Upload $u '안 올림(내전방 멤버 아님)' "판 $($u.gameId): 이 기록기를 연결한 계정이 $code 내전방 멤버가 아니라 올리지 않았어요. 내전방에 들어간 뒤에는 새 판부터 올라가요." Show-Note '올리지 않았어요' "연결한 계정이 $code 내전방 멤버가 아니에요." } elseif ($r.status -eq 404 -and $r.json.error) { Finish-Upload $u "안 올림($($r.json.error))" "판 $($u.gameId): 사이트에 없는 내전 코드($code)라 올리지 않았어요." } elseif ($r.status -ge 400 -and $r.status -lt 500 -and $r.status -ne 404 -and $r.status -ne 429) { $extra = ''; if ($r.json.error) { $extra = ", $($r.json.error)" } Finish-Upload $u "안 올림(HTTP $($r.status))" "판 $($u.gameId)를 사이트가 받지 않았어요(HTTP $($r.status)$extra)." } else { # 닿지 않음, 사이트 기능 없음(404 본문 없음), 429, 5xx: 나중에 다시 보낸다. Retry-Upload $u if ($u.tries -eq 1) { $why = '연결 안 됨'; if ($r.status) { $why = "HTTP $($r.status)" } $mins = [math]::Max(1, [math]::Round([int]$cfg.uploadRetrySeconds / 60)) Write-Log "판 $($u.gameId)를 사이트에 올리지 못했어요($why). ${mins}분마다 다시 보낼게요." } break } } } function Site-Tick { if (-not $SiteOn -or (Now-Ms) -lt $script:site.quietUntil) { return } if ($script:site.token -and -not $script:site.checked) { Check-Token; Flush-Uploads; return } if (-not $script:site.token) { if ($script:site.linking) { Poll-Link; return } if (-not $script:site.linkTried -or $script:uploads.Count) { Start-Link; return } return } if ($script:uploads.Count) { Flush-Uploads } } # ---- 판 저장 --------------------------------------------------------------------------------- function Save-Record($Capture, $Match) { $day = [DateTimeOffset]::FromUnixTimeMilliseconds([long]$Capture.startedAt).UtcDateTime.ToString('yyyy-MM-dd') $file = "${day}_$($Capture.gameId).json" $base = Join-Path $Records "${day}_$($Capture.gameId)" $cap = $Capture | Select-Object -Property * -ExcludeProperty lastTry $rec = [ordered]@{ capture = $cap; match = $Match; savedAt = (Now-Ms) } Save-Json "$base.json" $rec $recObj = Read-Json "$base.json" Write-Text "$base.html" (Render-Game $recObj) [void]$script:saved.Add("$($Capture.gameId)") for ($i = $script:index.Count - 1; $i -ge 0; $i--) { if ($script:index[$i].gameId -eq "$($Capture.gameId)") { $script:index.RemoveAt($i) } } [void]$script:index.Add((Summary-Of $file $recObj)) Save-Json $IndexFile ([object[]]$script:index.ToArray()) Queue-Upload $Capture $Match Rebuild-Index } # ---- 자동 업데이트 --------------------------------------------------------------------------- $script:nextUpdateCheck = [long]0 function Check-Update { if ($SiteBase -ne 'https://jeungba.gg' -or $RunSeconds -gt 0) { return $false } $script:nextUpdateCheck = (Now-Ms) + 6 * 3600 * 1000 $r = Invoke-Http -Method GET -Url 'https://jeungba.gg/recorder/version.txt' -TimeoutSec 15 $v = ([string]$r.text).Trim() if ($r.status -ne 200 -or $v -notmatch '^\d+\.\d+\.\d+$' -or $v -eq $Version) { return $false } $d = Invoke-Http -Method GET -Url 'https://jeungba.gg/recorder/recorder.ps1' -TimeoutSec 30 -Bytes $b = $d.bytes if ($d.status -ne 200 -or -not $b -or $b.Length -lt 1000 -or $b[0] -ne 0xEF -or $b[1] -ne 0xBB -or $b[2] -ne 0xBF) { return $false } if (-not ([System.Text.Encoding]::UTF8.GetString($b)).Contains("`$Version = '$v'")) { return $false } $tmp = Join-Path $State 'recorder.new.ps1' [System.IO.File]::WriteAllBytes($tmp, $b) Copy-Item -LiteralPath $tmp -Destination $Self -Force Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue Write-Log "새 버전 ${v}로 바꿨어요. 다시 켤게요." return $true } # ---- 실행 ------------------------------------------------------------------------------------ $createdNew = $false $script:mutex = [System.Threading.Mutex]::new($true, [string]$cfg.mutexName, [ref]$createdNew) if (-not $createdNew) { if ($NoTray) { Write-Host '기록기가 이미 켜져 있어요.' } exit 0 } Remove-Item -LiteralPath $StopFlag -Force -ErrorAction SilentlyContinue $script:quit = $false $script:restart = $false if (-not $NoTray) { Add-Type -AssemblyName System.Windows.Forms $script:tray = New-Object System.Windows.Forms.NotifyIcon $script:tray.Icon = New-TrayIcon $script:tray.Text = $AppName $menu = New-Object System.Windows.Forms.ContextMenuStrip [void]$menu.Items.Add('기록 보기', $null, { Start-Process (Join-Path $Records 'index.html') }) [void]$menu.Items.Add('로그 보기', $null, { Start-Process 'notepad.exe' -ArgumentList "`"$LogFile`"" }) [void]$menu.Items.Add('jeungba.gg 열기', $null, { Start-Process 'https://jeungba.gg/naejeon/' }) [void]$menu.Items.Add((New-Object System.Windows.Forms.ToolStripSeparator)) [void]$menu.Items.Add('끄기', $null, { $script:quit = $true }) $script:tray.ContextMenuStrip = $menu $script:tray.add_DoubleClick({ Start-Process (Join-Path $Records 'index.html') }) $script:tray.Visible = $true } Write-Log "내전 기록기 ${Version}을 켰어요. 기록은 $Records 에 쌓여요." Rebuild-Index if ($script:pending.Count) { Write-Log "지난번에 결과를 못 받은 판 $($script:pending.Count)개를 이어서 받아요." } Set-Status '롤 클라이언트 기다리는 중' if (Check-Update) { $script:restart = $true; $script:quit = $true } $script:lcu = $null $script:lastLobby = $null $script:waitingNotice = [long]0 $script:nextAttach = [long]0 $script:nextLcuTick = [long]0 $script:nextSiteTick = [long]0 function Lcu-Tick { $now = Now-Ms if (-not $script:lcu) { if ($now -lt $script:nextAttach) { return } $script:nextAttach = $now + 10000 $l = Find-Lcu if (-not $l) { if ($now - $script:waitingNotice -gt 10 * 60000) { $script:waitingNotice = $now Write-Log '롤 클라이언트를 기다리고 있어요. 롤을 켜면 바로 붙어요.' } Set-Status '롤 클라이언트 기다리는 중' return } $me = Get-Lcu $l '/lol-summoner/v1/current-summoner' if ($me.status -ne 200) { return } $script:lcu = $l $script:myPuuid = [string]$me.json.puuid Write-Log '롤 클라이언트에 붙었어요.' Set-Status '롤 클라이언트에 붙었어요' } $lcu = $script:lcu $s = Get-Lcu $lcu '/lol-gameflow/v1/session' if ($s.status -eq 0) { Write-Log '롤 클라이언트가 꺼졌어요. 다시 켜지면 이어서 할게요.' Set-Status '롤 클라이언트 기다리는 중' $script:lcu = $null return } $phase = 'None' if ($s.status -eq 200 -and $s.json.phase) { $phase = [string]$s.json.phase } # 사설 방에 들어가 있는 동안 방 이름을 기억해 둔다(게임 시작 정보에 이름이 비어 있을 때를 대비). if ($phase -eq 'Lobby' -or $phase -eq 'ChampSelect') { $lobby = Get-Lcu $lcu '/lol-lobby/v2/lobby' $gc = $lobby.json.gameConfig if ($lobby.status -eq 200 -and $gc.isCustom -and $gc.customLobbyName -and (-not $script:lastLobby -or $gc.customLobbyName -ne $script:lastLobby.name)) { $script:lastLobby = @{ name = [string]$gc.customLobbyName; at = (Now-Ms) } $note = ''; if ($Code.IsMatch([string]$gc.customLobbyName)) { $note = ' (내전 코드 있음)' } Write-Log "사설 방에 들어왔어요: `"$($gc.customLobbyName)`"$note" } } # 게임이 시작되면 적어 둔다. $gd = $null if ($s.status -eq 200) { $gd = $s.json.gameData } if (($InGame -contains $phase) -and $gd -and [long]$gd.gameId -gt 0 -and -not (Find-Pending $gd.gameId) -and -not $script:saved.Contains("$($gd.gameId)")) { if ($gd.isCustomGame -or -not $cfg.onlyCustom) { $c = New-Capture $s.json $script:lastLobby [void]$script:pending.Add($c) Save-Pending $nm = $c.lobbyName; if (-not $nm) { $nm = '(방 이름 없음)' } $cd = ', 내전 코드 없음'; if ($c.code) { $cd = ", 내전 코드 $($c.code)" } Write-Log "게임 시작: `"$nm`" 판 $($c.gameId), 큐 $($c.queueId), $(@($c.teamOne).Count)대$(@($c.teamTwo).Count)$cd" Set-Status '게임 기록 중' } } # 게임이 끝나면 끝난 시각을 적고, 끝난 판 화면의 통계를 받아 둔다(전적 상세가 늦게 뜰 때를 대비한 예비). $now = Now-Ms foreach ($p in @($script:pending.ToArray())) { if (-not $p.endedAt -and -not (($InGame -contains $phase) -and $gd -and "$($gd.gameId)" -eq "$($p.gameId)")) { $p.endedAt = $now Save-Pending Write-Log "게임 끝: 판 $($p.gameId). 결과를 받아 볼게요." Set-Status '결과 받는 중' } if ($p.endedAt -and -not $p.eog -and $phase -eq 'EndOfGame') { $eog = Get-Lcu $lcu '/lol-end-of-game/v1/eog-stats-block' if ($eog.status -eq 200 -and "$($eog.json.gameId)" -eq "$($p.gameId)") { $p.eog = $eog.json Save-Pending } } } # 끝난 판의 전적 상세를 받는다. 바로 안 뜨면 retrySeconds마다 다시 묻는다. foreach ($p in @($script:pending.ToArray())) { if (-not $p.endedAt -or ($now - [long]$p.lastTry) -lt [int]$cfg.retrySeconds * 1000) { continue } $p.lastTry = $now $r = Get-Lcu $lcu "/lol-match-history/v1/games/$($p.gameId)" if ($r.status -eq 200 -and @($r.json.participants).Count) { Save-Record $p $r.json $script:pending.Remove($p) Save-Pending $w = @($r.json.participants | Where-Object { $_.stats.win } | Select-Object -First 1) $win = '레드'; if ($w.Count -and $w[0].teamId -eq 100) { $win = '블루' } Write-Log "기록했어요: 판 $($p.gameId), $(@($r.json.participants).Count)명, $win 승리." Set-Status '기록했어요' Show-Note '내전 판을 기록했어요' "$win 승리 · $(@($r.json.participants).Count)명" } elseif ($now - [long]$p.endedAt -gt [int]$cfg.giveUpMinutes * 60000) { Save-Record $p $null $script:pending.Remove($p) Save-Pending Write-Log "판 $($p.gameId)의 전적 상세가 $($cfg.giveUpMinutes)분 동안 뜨지 않아, 시작 때 받은 명단만 남겼어요." } else { Save-Pending } } } $deadline = [long]::MaxValue if ($RunSeconds -gt 0) { $deadline = (Now-Ms) + $RunSeconds * 1000 } while (-not $script:quit) { if ($script:tray) { [System.Windows.Forms.Application]::DoEvents() } $now = Now-Ms if ($now -ge $deadline) { break } if (Test-Path -LiteralPath $StopFlag) { Remove-Item -LiteralPath $StopFlag -Force -ErrorAction SilentlyContinue Write-Log '끝내라는 신호를 받아 기록기를 멈춰요.' break } if ($now -ge $script:nextSiteTick) { $script:nextSiteTick = $now + 1000 try { Site-Tick } catch { Write-Log "사이트 처리 중 오류: $($_.Exception.Message)" } } if ($now -ge $script:nextLcuTick) { $script:nextLcuTick = $now + [int]$cfg.pollSeconds * 1000 try { Lcu-Tick } catch { Write-Log "기록 중 오류: $($_.Exception.Message)" } } if ($now -ge $script:nextUpdateCheck -and $script:nextUpdateCheck -gt 0) { try { if (Check-Update) { $script:restart = $true; break } } catch { } } Start-Sleep -Milliseconds 200 } try { Save-Pending } catch { } if ($script:tray) { $script:tray.Visible = $false; $script:tray.Dispose() } Write-Log '기록기를 멈췄어요. 다시 켜면 이어서 해요.' try { $script:mutex.ReleaseMutex(); $script:mutex.Dispose() } catch { } if ($script:restart) { Start-Process -FilePath $PowerShellExe -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden', '-File', "`"$Self`"") -WindowStyle Hidden } exit 0