.
This commit is contained in:
1 parent
db60190e19
commit
843e6435cc
9 files changed
+663
-7
No files matched your search
@@ -1,14 +1,24 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type {
|
||||
AutoReservationState,
|
||||
AutoSalvoState,
|
||||
CaptchaResult,
|
||||
ClockCalibrationSettings,
|
||||
ClockEstimate,
|
||||
ReservationRequest,
|
||||
ReservationResult,
|
||||
ReservationSelection,
|
||||
TimingTestResult,
|
||||
} from '../type/reservation'
|
||||
import { CLOCK_CALIBRATION_DEFAULTS } from '../type/reservation'
|
||||
|
||||
const MAX_SALVO_ATTEMPTS = 8
|
||||
|
||||
// n개의 토큰을 목표 시각 0을 중심으로 stepMs 간격으로 대칭 배치한 오프셋 목록을 만든다.
|
||||
function symmetricOffsets(count: number, stepMs: number) {
|
||||
return Array.from({ length: count }, (_, index) => Math.round((index - (count - 1) / 2) * stepMs))
|
||||
}
|
||||
|
||||
const KST_OFFSET_MS = 9 * 60 * 60 * 1_000
|
||||
const CLOCK_SETTINGS_STORAGE_KEY = 'escape-reserve.clock-calibration.v1'
|
||||
const LEGACY_CLOCK_SETTINGS_STORAGE_KEY = 'reserve-escape.clock-calibration.v1'
|
||||
@@ -25,6 +35,8 @@ function loadClockSettings(): ClockCalibrationSettings {
|
||||
|
||||
interface AutomationPanelProps {
|
||||
request: ReservationRequest | null
|
||||
salvoBaseRequest: Omit<ReservationRequest, 'captchaToken'> | null
|
||||
captchaSelection: ReservationSelection | null
|
||||
captchaToken: string
|
||||
captchaPastedAtMs: number | null
|
||||
onTokenConsumed: () => void
|
||||
@@ -105,6 +117,8 @@ function SampleGraph({ estimate }: { estimate: ClockEstimate }) {
|
||||
|
||||
export default function AutomationPanel({
|
||||
request,
|
||||
salvoBaseRequest,
|
||||
captchaSelection,
|
||||
captchaToken,
|
||||
captchaPastedAtMs,
|
||||
onTokenConsumed,
|
||||
@@ -120,8 +134,15 @@ export default function AutomationPanel({
|
||||
const [timingTest, setTimingTest] = useState<TimingTestResult | null>(null)
|
||||
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||
const [clockSettings, setClockSettings] = useState<ClockCalibrationSettings>(loadClockSettings)
|
||||
const [tokens, setTokens] = useState<CaptchaResult[]>([])
|
||||
const [salvoStepMs, setSalvoStepMs] = useState(300)
|
||||
const [stopOnSuccess, setStopOnSuccess] = useState(true)
|
||||
const [salvoState, setSalvoState] = useState<AutoSalvoState>({ status: 'idle', stopOnSuccess: true, attempts: [] })
|
||||
const [salvoBusy, setSalvoBusy] = useState<'token' | 'arm' | null>(null)
|
||||
const [salvoError, setSalvoError] = useState('')
|
||||
const previousFingerprint = useRef('')
|
||||
const previousAutoStatus = useRef(autoState.status)
|
||||
const previousSalvoStatus = useRef(salvoState.status)
|
||||
const previousCaptchaAt = useRef<number | null>(null)
|
||||
const targetServerTimeMs = parseKstInput(targetInput)
|
||||
const liveServerTimeMs = clock
|
||||
@@ -134,6 +155,17 @@ export default function AutomationPanel({
|
||||
: Number.POSITIVE_INFINITY
|
||||
const tokenReady = captchaToken.trim().length >= 30 && tokenAgeAtTargetMs >= 0 && tokenAgeAtTargetMs <= 90_000
|
||||
const armed = autoState.status === 'armed' || autoState.status === 'firing'
|
||||
const salvoArmed = salvoState.status === 'armed' || salvoState.status === 'firing'
|
||||
const attemptCount = Math.min(tokens.length, MAX_SALVO_ATTEMPTS)
|
||||
const salvoOffsets = useMemo(() => symmetricOffsets(attemptCount, salvoStepMs), [attemptCount, salvoStepMs])
|
||||
const salvoTokenState = tokens.slice(0, attemptCount).map((token, index) => {
|
||||
const effectiveTargetServerMs = targetServerTimeMs + userOffsetMs + salvoOffsets[index]
|
||||
const ageAtTargetMs = Number.isFinite(effectiveTargetServerMs)
|
||||
? effectiveTargetServerMs - (token.solvedAtMs + (clock?.offsetMs ?? 0))
|
||||
: Number.POSITIVE_INFINITY
|
||||
return { token, offsetMs: salvoOffsets[index], ageAtTargetMs, ready: ageAtTargetMs >= 0 && ageAtTargetMs <= 90_000 }
|
||||
})
|
||||
const salvoReady = attemptCount > 0 && salvoBaseRequest !== null && Number.isFinite(targetServerTimeMs) && salvoTokenState.every((item) => item.ready)
|
||||
|
||||
const requestFingerprint = useMemo(() => request ? JSON.stringify({
|
||||
...request,
|
||||
@@ -143,17 +175,20 @@ export default function AutomationPanel({
|
||||
useEffect(() => {
|
||||
const unsubscribeClock = window.reservationApi.subscribeClock(setClock)
|
||||
const unsubscribeAuto = window.reservationApi.subscribeAutoState(setAutoState)
|
||||
const unsubscribeSalvo = window.reservationApi.subscribeAutoSalvo(setSalvoState)
|
||||
void Promise.all([
|
||||
window.reservationApi.configureClock(clockSettings).then((estimate) => {
|
||||
setClock(estimate)
|
||||
setClockSettings(estimate.calibrationSettings)
|
||||
}),
|
||||
window.reservationApi.getAutoReservationState().then(setAutoState),
|
||||
window.reservationApi.getAutoSalvoState().then(setSalvoState),
|
||||
]).catch(() => undefined)
|
||||
const interval = window.setInterval(() => setNowMs(Date.now()), 50)
|
||||
return () => {
|
||||
unsubscribeClock()
|
||||
unsubscribeAuto()
|
||||
unsubscribeSalvo()
|
||||
window.clearInterval(interval)
|
||||
}
|
||||
}, [])
|
||||
@@ -184,6 +219,16 @@ export default function AutomationPanel({
|
||||
}
|
||||
}, [autoState, onResult, onTokenConsumed])
|
||||
|
||||
useEffect(() => {
|
||||
if (previousSalvoStatus.current !== salvoState.status) {
|
||||
if (salvoState.status === 'succeeded' && salvoState.result) {
|
||||
onResult(salvoState.result)
|
||||
setTokens([])
|
||||
}
|
||||
previousSalvoStatus.current = salvoState.status
|
||||
}
|
||||
}, [salvoState, onResult])
|
||||
|
||||
const toggleMonitor = async () => {
|
||||
setBusy('monitor')
|
||||
setError('')
|
||||
@@ -264,6 +309,60 @@ export default function AutomationPanel({
|
||||
}
|
||||
}
|
||||
|
||||
const addToken = async () => {
|
||||
setSalvoError('')
|
||||
if (!captchaSelection) return setSalvoError('먼저 지점·테마·시간을 선택해주세요.')
|
||||
if (tokens.length >= MAX_SALVO_ATTEMPTS) return setSalvoError(`토큰은 최대 ${MAX_SALVO_ATTEMPTS}개까지 준비할 수 있습니다.`)
|
||||
setSalvoBusy('token')
|
||||
try {
|
||||
const result = await window.reservationApi.openCaptcha(captchaSelection)
|
||||
setTokens((current) => [...current, result])
|
||||
} catch (reason) {
|
||||
setSalvoError(reason instanceof Error ? reason.message : '캡차 토큰을 생성하지 못했습니다.')
|
||||
} finally {
|
||||
setSalvoBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
const removeToken = (solvedAtMs: number) => setTokens((current) => current.filter((token) => token.solvedAtMs !== solvedAtMs))
|
||||
|
||||
const armSalvo = async () => {
|
||||
setSalvoError('')
|
||||
if (!salvoBaseRequest) return setSalvoError('예약 정보, 인원, 예약자 정보와 동의를 모두 완료해주세요.')
|
||||
if (attemptCount === 0) return setSalvoError('캡차 토큰을 먼저 하나 이상 생성해주세요.')
|
||||
if (!Number.isFinite(targetServerTimeMs)) return setSalvoError('실행 시각을 올바르게 입력해주세요.')
|
||||
if (!salvoReady) return setSalvoError('일부 토큰이 목표 시각에 90초를 초과합니다. 간격을 줄이거나 토큰을 다시 생성해주세요.')
|
||||
setSalvoBusy('arm')
|
||||
try {
|
||||
if (!clock?.monitoring) setClock(await window.reservationApi.startClockMonitor())
|
||||
const attempts = salvoTokenState.map((item) => ({
|
||||
offsetMs: item.offsetMs,
|
||||
captchaToken: item.token.token,
|
||||
captchaSolvedAtMs: item.token.solvedAtMs,
|
||||
}))
|
||||
setSalvoState(await window.reservationApi.armAutoSalvo({
|
||||
baseRequest: salvoBaseRequest,
|
||||
targetServerTimeMs,
|
||||
userOffsetMs,
|
||||
attempts,
|
||||
stopOnSuccess,
|
||||
}))
|
||||
} catch (reason) {
|
||||
setSalvoError(reason instanceof Error ? reason.message : '다중 시도를 시작하지 못했습니다.')
|
||||
} finally {
|
||||
setSalvoBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
const disarmSalvo = async () => {
|
||||
setSalvoError('')
|
||||
try {
|
||||
setSalvoState(await window.reservationApi.disarmAutoSalvo())
|
||||
} catch (reason) {
|
||||
setSalvoError(reason instanceof Error ? reason.message : '다중 시도를 해제하지 못했습니다.')
|
||||
}
|
||||
}
|
||||
|
||||
const qualityTone = clock?.quality === 'good' ? 'good' : clock?.quality === 'poor' || clock?.quality === 'unavailable' ? 'warn' : 'normal'
|
||||
|
||||
return (
|
||||
@@ -345,7 +444,67 @@ export default function AutomationPanel({
|
||||
{autoState.timeline?.actualSendAtMs && <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4"><Metric label="actual send" value={formatClock(autoState.timeline.actualSendAtMs).split(' ').at(-1) ?? '—'} /><Metric label="arrival error" value={autoState.timeline.arrivalErrorMs === undefined ? '—' : `${autoState.timeline.arrivalErrorMs >= 0 ? '+' : ''}${autoState.timeline.arrivalErrorMs.toFixed(1)}ms`} /><Metric label="response RTT" value={autoState.timeline.rttMs === undefined ? '—' : `${autoState.timeline.rttMs.toFixed(1)}ms`} /><Metric label="HTTP / connection" value={`${autoState.timeline.httpStatus ?? '—'} · ${autoState.timeline.protocol ?? '—'} ${autoState.timeline.connectionId ?? ''} · ${autoState.timeline.reusedSocket ? 'reused' : 'new'}`} /></div>}
|
||||
{(error || autoState.message) && <p role="alert" className={`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${error || autoState.status === 'failed' ? 'border-danger/25 bg-danger/8 text-danger' : 'border-success/25 bg-success/8 text-success'}`}>{error || autoState.message}</p>}
|
||||
{!armed && (!request || !tokenReady) && <p className="mt-3 text-[10px] leading-4 text-warning">{!request ? '예약자 정보·인원·동의와 CAPTCHA 인증을 완료해주세요.' : tokenAgeAtTargetMs < 0 ? '실행 시각이 이미 지났습니다. 미래 시각으로 변경해주세요.' : 'CAPTCHA 인증 후 90초 이내의 실행 시각을 입력해주세요.'}</p>}
|
||||
<div className="mt-4 grid grid-cols-2 gap-2">{armed ? <button onClick={disarm} disabled={autoState.status === 'firing'} className="col-span-2 rounded-xl border border-danger/30 py-3 text-xs font-semibold text-danger hover:bg-danger/8 disabled:opacity-40">자동 예약 해제</button> : <button onClick={arm} disabled={busy === 'arm'} className="col-span-2 rounded-xl bg-coral py-3 text-xs font-bold text-coral-ink hover:bg-coral-strong disabled:cursor-not-allowed disabled:bg-chrome disabled:text-ink-muted">{busy === 'arm' ? '시작 중…' : '자동 예약 시작'}</button>}</div>
|
||||
<div className="mt-4 grid grid-cols-2 gap-2">{armed ? <button onClick={disarm} disabled={autoState.status === 'firing'} className="col-span-2 rounded-xl border border-danger/30 py-3 text-xs font-semibold text-danger hover:bg-danger/8 disabled:opacity-40">자동 예약 해제</button> : <button onClick={arm} disabled={busy === 'arm' || salvoArmed} className="col-span-2 rounded-xl bg-coral py-3 text-xs font-bold text-coral-ink hover:bg-coral-strong disabled:cursor-not-allowed disabled:bg-chrome disabled:text-ink-muted">{busy === 'arm' ? '시작 중…' : '자동 예약 시작'}</button>}</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-line-soft p-5 sm:p-6">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-ink">다중 시도 · 토큰 여러 개</h3>
|
||||
<p className="mt-1 text-[10px] leading-4 text-ink-muted">캡차를 여러 번 풀어 토큰을 미리 모아두고, 목표 시각 ±오프셋에서 각각 다른 토큰으로 시도합니다.</p>
|
||||
</div>
|
||||
<span className={`rounded-full px-2.5 py-1 text-[9px] font-semibold uppercase tracking-wider ${salvoArmed ? 'bg-gold text-gold-ink' : salvoState.status === 'succeeded' ? 'bg-success/10 text-success' : salvoState.status === 'failed' ? 'bg-danger/10 text-danger' : 'bg-chrome text-ink-muted'}`}>{salvoState.status}</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 rounded-xl border border-line-soft bg-canvas p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<p className="text-[10px] font-semibold text-ink-muted">토큰 풀 <span className="text-ink">{tokens.length}</span> / {MAX_SALVO_ATTEMPTS}</p>
|
||||
<div className="flex gap-2">
|
||||
{tokens.length > 0 && !salvoArmed && <button onClick={() => setTokens([])} className="rounded-lg border border-line px-2.5 py-1.5 text-[10px] font-semibold text-ink-muted hover:text-ink">모두 비우기</button>}
|
||||
<button onClick={addToken} disabled={salvoBusy === 'token' || salvoArmed || !captchaSelection || tokens.length >= MAX_SALVO_ATTEMPTS} className="rounded-lg border border-accent/30 bg-accent/5 px-2.5 py-1.5 text-[10px] font-semibold text-accent hover:bg-accent/10 disabled:opacity-40">{salvoBusy === 'token' ? '인증 창 대기…' : '+ 토큰 생성'}</button>
|
||||
</div>
|
||||
</div>
|
||||
{tokens.length === 0 ? (
|
||||
<p className="mt-3 text-[10px] leading-4 text-ink-muted">토큰이 없습니다. ‘토큰 생성’을 눌러 인증 창에서 캡차를 풀면 토큰이 하나씩 쌓입니다.</p>
|
||||
) : (
|
||||
<ul className="mt-3 space-y-1.5">
|
||||
{salvoTokenState.map((item) => (
|
||||
<li key={item.token.solvedAtMs} className="flex items-center justify-between gap-3 rounded-lg border border-line-soft bg-surface px-3 py-2 text-[10px]">
|
||||
<span className="font-mono text-ink-muted">{item.token.token.slice(0, 6)}••••{item.token.token.slice(-4)}</span>
|
||||
<span className={`font-semibold tabular-nums ${item.ready ? 'text-success' : 'text-warning'}`}>{item.offsetMs >= 0 ? '+' : ''}{item.offsetMs}ms · 목표시 잔여 {Number.isFinite(item.ageAtTargetMs) ? formatDuration(90_000 - item.ageAtTargetMs) : '—'}</span>
|
||||
{!salvoArmed && <button onClick={() => removeToken(item.token.solvedAtMs)} className="text-ink-muted hover:text-danger" aria-label="토큰 삭제">✕</button>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-[1fr_auto]">
|
||||
<label className="space-y-2"><span className="text-[10px] font-semibold text-ink-muted">시도 간격 (ms, 목표 시각 중심 대칭)</span><input type="number" min="0" max="3000" step="10" value={salvoStepMs} onChange={(event) => setSalvoStepMs(Math.max(0, Math.min(3_000, Number(event.target.value))))} disabled={salvoArmed} className="w-full rounded-xl border border-line bg-surface px-3 py-3 font-mono text-xs text-ink outline-none focus:border-accent disabled:opacity-50" /></label>
|
||||
<label className="flex items-end gap-2 pb-3 text-[10px] font-semibold text-ink-muted"><input type="checkbox" checked={stopOnSuccess} onChange={(event) => setStopOnSuccess(event.target.checked)} disabled={salvoArmed} className="accent-coral" />첫 성공 시 이후 취소</label>
|
||||
</div>
|
||||
{attemptCount > 0 && <p className="mt-2 text-[10px] leading-4 text-ink-muted">시도 <span className="font-semibold text-ink">{attemptCount}</span>개 · 오프셋 <span className="font-mono text-ink">{salvoOffsets.map((offset) => `${offset >= 0 ? '+' : ''}${offset}`).join(' / ')}</span> ms</p>}
|
||||
|
||||
{salvoState.attempts.length > 0 && (
|
||||
<div className="mt-3 overflow-hidden rounded-xl border border-line-soft">
|
||||
{salvoState.attempts.map((attempt) => (
|
||||
<div key={attempt.index} className="flex items-center justify-between gap-3 border-b border-line-soft px-3 py-2 text-[10px] last:border-b-0">
|
||||
<span className="font-mono text-ink-muted">{attempt.offsetMs >= 0 ? '+' : ''}{attempt.offsetMs}ms{attempt.plannedSendAtMs ? ` · ${formatClock(attempt.plannedSendAtMs).split(' ').at(-1)}` : ''}</span>
|
||||
<span className="flex items-center gap-2">
|
||||
{attempt.arrivalErrorMs !== undefined && <span className="font-mono text-ink-muted">도착 {attempt.arrivalErrorMs >= 0 ? '+' : ''}{attempt.arrivalErrorMs.toFixed(0)}ms</span>}
|
||||
{attempt.httpStatus !== undefined && <span className="font-mono text-ink-muted">{attempt.httpStatus}</span>}
|
||||
<span className={`rounded-full px-2 py-0.5 font-semibold ${attempt.status === 'succeeded' ? 'bg-success/10 text-success' : attempt.status === 'failed' ? 'bg-danger/10 text-danger' : attempt.status === 'firing' ? 'bg-gold text-gold-ink' : attempt.status === 'skipped' ? 'bg-chrome text-ink-muted' : 'bg-accent/10 text-accent'}`}>{attempt.status}</span>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(salvoError || salvoState.message) && <p role="alert" className={`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${salvoError || salvoState.status === 'failed' ? 'border-danger/25 bg-danger/8 text-danger' : 'border-success/25 bg-success/8 text-success'}`}>{salvoError || salvoState.message}</p>}
|
||||
|
||||
<div className="mt-4">{salvoArmed
|
||||
? <button onClick={disarmSalvo} disabled={salvoState.status === 'firing'} className="w-full rounded-xl border border-danger/30 py-3 text-xs font-semibold text-danger hover:bg-danger/8 disabled:opacity-40">다중 시도 해제</button>
|
||||
: <button onClick={armSalvo} disabled={salvoBusy !== null || armed} className="w-full rounded-xl bg-coral py-3 text-xs font-bold text-coral-ink hover:bg-coral-strong disabled:cursor-not-allowed disabled:bg-chrome disabled:text-ink-muted">{salvoBusy === 'arm' ? '시작 중…' : `다중 시도 시작 (${attemptCount})`}</button>}</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user