.
This commit is contained in:
1 parent
db60190e19
commit
843e6435cc
9 files changed
+663
-7
No files matched your search
@@ -0,0 +1,303 @@
|
|||||||
|
import { app, BrowserWindow, ipcMain } from 'electron'
|
||||||
|
import type {
|
||||||
|
AutoReservationSnapshot,
|
||||||
|
AutoSalvoAttempt,
|
||||||
|
AutoSalvoConfig,
|
||||||
|
AutoSalvoState,
|
||||||
|
ClockEstimate,
|
||||||
|
ReservationRequest,
|
||||||
|
} from '../../src/type/reservation'
|
||||||
|
import { executeReservation } from './reservation'
|
||||||
|
import { serverClock } from './server-clock'
|
||||||
|
import { computePlannedSendAtMs } from './server-clock-core'
|
||||||
|
|
||||||
|
const SALVO_EVENT = 'reservation:salvo-state'
|
||||||
|
const MAX_TOKEN_TARGET_AGE_MS = 90_000
|
||||||
|
const MAX_ATTEMPTS = 8
|
||||||
|
const MAX_OFFSET_MS = 10_000
|
||||||
|
const MAX_LATE_FIRE_MS = 1_500
|
||||||
|
|
||||||
|
function broadcast(value: AutoSalvoState) {
|
||||||
|
for (const window of BrowserWindow.getAllWindows()) {
|
||||||
|
if (!window.isDestroyed()) window.webContents.send(SALVO_EVENT, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function snapshot(base: Omit<ReservationRequest, 'captchaToken'>): AutoReservationSnapshot {
|
||||||
|
return {
|
||||||
|
branchNum: base.branchNum,
|
||||||
|
themeNum: base.themeNum,
|
||||||
|
themeInfoNum: base.themeInfoNum,
|
||||||
|
date: base.date,
|
||||||
|
timeNum: base.timeNum,
|
||||||
|
timeLabel: base.timeLabel,
|
||||||
|
themeName: base.themeName,
|
||||||
|
totalPrice: base.totalPrice,
|
||||||
|
person: base.person,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PlannedAttempt {
|
||||||
|
attempt: AutoSalvoAttempt
|
||||||
|
captchaToken: string
|
||||||
|
plannedSendAtMs: number
|
||||||
|
frozenOffsetMs: number
|
||||||
|
frozenOneWayMs: number
|
||||||
|
fired: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AutoSalvoService {
|
||||||
|
private base?: Omit<ReservationRequest, 'captchaToken'>
|
||||||
|
private planned: PlannedAttempt[] = []
|
||||||
|
private timer?: NodeJS.Timeout
|
||||||
|
private inFlight = 0
|
||||||
|
private stopOnSuccess = true
|
||||||
|
private state: AutoSalvoState = { status: 'idle', stopOnSuccess: true, attempts: [] }
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly clock: {
|
||||||
|
ensureSample(): Promise<ClockEstimate>
|
||||||
|
getEstimate(): ClockEstimate
|
||||||
|
setAutoTarget(targetServerTimeMs?: number): void
|
||||||
|
} = serverClock,
|
||||||
|
private readonly execute: (request: ReservationRequest) => Promise<Awaited<ReturnType<typeof executeReservation>>> = executeReservation,
|
||||||
|
private readonly emitState: (state: AutoSalvoState) => void = broadcast,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
getState() {
|
||||||
|
return this.state
|
||||||
|
}
|
||||||
|
|
||||||
|
async arm(input: AutoSalvoConfig) {
|
||||||
|
if (this.state.status === 'armed' || this.state.status === 'firing') {
|
||||||
|
throw new Error('이미 다중 시도가 진행 중입니다.')
|
||||||
|
}
|
||||||
|
if (!Number.isFinite(input.targetServerTimeMs)) throw new Error('실행 시각이 올바르지 않습니다.')
|
||||||
|
if (!Number.isFinite(input.userOffsetMs) || input.userOffsetMs < -5_000 || input.userOffsetMs > 5_000) {
|
||||||
|
throw new Error('사용자 오프셋은 -5000ms에서 +5000ms 사이여야 합니다.')
|
||||||
|
}
|
||||||
|
if (input.attempts.length === 0) throw new Error('시도가 하나도 없습니다. 토큰을 먼저 생성해주세요.')
|
||||||
|
if (input.attempts.length > MAX_ATTEMPTS) throw new Error(`시도는 최대 ${MAX_ATTEMPTS}개까지 가능합니다.`)
|
||||||
|
|
||||||
|
const seenTokens = new Set<string>()
|
||||||
|
for (const attempt of input.attempts) {
|
||||||
|
if (attempt.captchaToken.trim().length < 30) throw new Error('각 시도에는 유효한 캡차 토큰이 필요합니다.')
|
||||||
|
if (seenTokens.has(attempt.captchaToken)) throw new Error('같은 캡차 토큰을 두 번 사용할 수 없습니다.')
|
||||||
|
seenTokens.add(attempt.captchaToken)
|
||||||
|
if (!Number.isFinite(attempt.offsetMs) || Math.abs(attempt.offsetMs) > MAX_OFFSET_MS) {
|
||||||
|
throw new Error(`오프셋은 ±${MAX_OFFSET_MS}ms 이내여야 합니다.`)
|
||||||
|
}
|
||||||
|
if (!Number.isFinite(attempt.captchaSolvedAtMs) || attempt.captchaSolvedAtMs > Date.now()) {
|
||||||
|
throw new Error('캡차 토큰 생성 시각이 올바르지 않습니다.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const estimate = await this.clock.ensureSample()
|
||||||
|
if (estimate.acceptedSamples === 0) throw new Error('유효한 서버시간 표본이 없어 다중 시도를 시작할 수 없습니다.')
|
||||||
|
if (input.targetServerTimeMs <= estimate.estimatedServerTimeMs + 150) {
|
||||||
|
throw new Error('실행 시각은 현재 관측 서버시각보다 최소 0.15초 이후여야 합니다.')
|
||||||
|
}
|
||||||
|
|
||||||
|
const planned: PlannedAttempt[] = input.attempts.map((raw, index) => {
|
||||||
|
const combinedOffsetMs = input.userOffsetMs + raw.offsetMs
|
||||||
|
const effectiveTargetServerMs = input.targetServerTimeMs + combinedOffsetMs
|
||||||
|
const targetLocalTimeMs = effectiveTargetServerMs - estimate.offsetMs
|
||||||
|
const tokenAgeAtTargetMs = targetLocalTimeMs - raw.captchaSolvedAtMs
|
||||||
|
if (tokenAgeAtTargetMs < 0 || tokenAgeAtTargetMs > MAX_TOKEN_TARGET_AGE_MS) {
|
||||||
|
throw new Error(`${raw.offsetMs >= 0 ? '+' : ''}${raw.offsetMs}ms 시도의 토큰이 목표 시각에 90초를 초과합니다. 토큰을 다시 생성하거나 오프셋을 줄여주세요.`)
|
||||||
|
}
|
||||||
|
const plannedSendAtMs = computePlannedSendAtMs(input.targetServerTimeMs, combinedOffsetMs, estimate)
|
||||||
|
return {
|
||||||
|
attempt: {
|
||||||
|
index,
|
||||||
|
offsetMs: raw.offsetMs,
|
||||||
|
effectiveTargetServerMs,
|
||||||
|
plannedSendAtMs,
|
||||||
|
status: 'pending',
|
||||||
|
},
|
||||||
|
captchaToken: raw.captchaToken,
|
||||||
|
plannedSendAtMs,
|
||||||
|
frozenOffsetMs: estimate.offsetMs,
|
||||||
|
frozenOneWayMs: estimate.oneWayMs,
|
||||||
|
fired: false,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
planned.sort((a, b) => a.plannedSendAtMs - b.plannedSendAtMs)
|
||||||
|
|
||||||
|
this.base = input.baseRequest
|
||||||
|
this.planned = planned
|
||||||
|
this.stopOnSuccess = input.stopOnSuccess
|
||||||
|
this.inFlight = 0
|
||||||
|
this.state = {
|
||||||
|
status: 'armed',
|
||||||
|
targetServerTimeMs: input.targetServerTimeMs,
|
||||||
|
userOffsetMs: input.userOffsetMs,
|
||||||
|
armedAtMs: Date.now(),
|
||||||
|
stopOnSuccess: input.stopOnSuccess,
|
||||||
|
snapshot: snapshot(input.baseRequest),
|
||||||
|
attempts: planned.map((item) => item.attempt),
|
||||||
|
warning: estimate.quality === 'poor' || (estimate.calibrationSettings.enabled && !estimate.calibrationReady) ? estimate.warning : undefined,
|
||||||
|
}
|
||||||
|
this.clock.setAutoTarget(planned[0].attempt.effectiveTargetServerMs)
|
||||||
|
this.emit()
|
||||||
|
this.scheduleNext()
|
||||||
|
return this.state
|
||||||
|
}
|
||||||
|
|
||||||
|
disarm(message = '다중 시도가 해제되었습니다.') {
|
||||||
|
if (this.state.status === 'firing') return this.state
|
||||||
|
this.clearTimer()
|
||||||
|
this.planned = []
|
||||||
|
this.base = undefined
|
||||||
|
this.clock.setAutoTarget(undefined)
|
||||||
|
this.state = { status: 'cancelled', stopOnSuccess: this.stopOnSuccess, attempts: this.state.attempts, message }
|
||||||
|
this.emit()
|
||||||
|
return this.state
|
||||||
|
}
|
||||||
|
|
||||||
|
reset() {
|
||||||
|
this.clearTimer()
|
||||||
|
this.planned = []
|
||||||
|
this.base = undefined
|
||||||
|
this.inFlight = 0
|
||||||
|
this.clock.setAutoTarget(undefined)
|
||||||
|
this.state = { status: 'idle', stopOnSuccess: true, attempts: [] }
|
||||||
|
this.emit()
|
||||||
|
}
|
||||||
|
|
||||||
|
private clearTimer() {
|
||||||
|
if (this.timer) clearTimeout(this.timer)
|
||||||
|
this.timer = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
private nextPending() {
|
||||||
|
return this.planned.find((item) => !item.fired)
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleNext() {
|
||||||
|
this.clearTimer()
|
||||||
|
if (this.state.status !== 'armed' && this.state.status !== 'firing') return
|
||||||
|
const next = this.nextPending()
|
||||||
|
if (!next) return
|
||||||
|
const delayMs = Math.max(0, next.plannedSendAtMs - Date.now())
|
||||||
|
this.timer = setTimeout(() => this.fireDue(), Math.min(delayMs, 60_000))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fireDue() {
|
||||||
|
this.clearTimer()
|
||||||
|
const next = this.nextPending()
|
||||||
|
if (!next) return
|
||||||
|
// 아직 발사 시각이 남았으면(타이머 상한/절전 복귀) 다시 대기한다.
|
||||||
|
const remainingMs = next.plannedSendAtMs - Date.now()
|
||||||
|
if (remainingMs > 20) {
|
||||||
|
this.scheduleNext()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.fired = true
|
||||||
|
|
||||||
|
const estimate = this.clock.getEstimate()
|
||||||
|
if (estimate.acceptedSamples === 0) {
|
||||||
|
this.markAttempt(next, { status: 'skipped', message: '유효한 서버시간 표본이 없어 건너뜀' })
|
||||||
|
this.afterAttemptSettled()
|
||||||
|
this.scheduleNext()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (estimate.estimatedServerTimeMs > next.attempt.effectiveTargetServerMs + MAX_LATE_FIRE_MS) {
|
||||||
|
this.markAttempt(next, { status: 'skipped', message: '목표 시각이 지나 건너뜀' })
|
||||||
|
this.afterAttemptSettled()
|
||||||
|
this.scheduleNext()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.state.status === 'armed') {
|
||||||
|
this.state = { ...this.state, status: 'firing' }
|
||||||
|
}
|
||||||
|
this.markAttempt(next, { status: 'firing' })
|
||||||
|
this.inFlight += 1
|
||||||
|
void this.execute({ ...this.base!, captchaToken: next.captchaToken } as ReservationRequest)
|
||||||
|
.then((result) => {
|
||||||
|
const transport = result.transport
|
||||||
|
const estimatedArrivalServerMs = transport
|
||||||
|
? transport.sentAtMs + next.frozenOffsetMs + next.frozenOneWayMs
|
||||||
|
: undefined
|
||||||
|
this.markAttempt(next, {
|
||||||
|
status: result.success ? 'succeeded' : 'failed',
|
||||||
|
message: result.message,
|
||||||
|
reservationNum: result.reservationNum,
|
||||||
|
actualSendAtMs: transport?.sentAtMs,
|
||||||
|
arrivalErrorMs: estimatedArrivalServerMs === undefined ? undefined : estimatedArrivalServerMs - next.attempt.effectiveTargetServerMs,
|
||||||
|
rttMs: transport?.rttMs,
|
||||||
|
httpStatus: transport?.httpStatus,
|
||||||
|
})
|
||||||
|
if (result.success) {
|
||||||
|
this.state = { ...this.state, succeededIndex: next.attempt.index, result }
|
||||||
|
if (this.stopOnSuccess) this.cancelRemaining('먼저 성공한 시도가 있어 이후 시도를 취소했습니다.')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
this.markAttempt(next, { status: 'failed', message: error instanceof Error ? error.message : '요청 실패' })
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
this.inFlight -= 1
|
||||||
|
this.afterAttemptSettled()
|
||||||
|
})
|
||||||
|
|
||||||
|
this.scheduleNext()
|
||||||
|
}
|
||||||
|
|
||||||
|
private cancelRemaining(message: string) {
|
||||||
|
this.clearTimer()
|
||||||
|
for (const item of this.planned) {
|
||||||
|
if (!item.fired) {
|
||||||
|
item.fired = true
|
||||||
|
this.markAttempt(item, { status: 'skipped', message })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private afterAttemptSettled() {
|
||||||
|
if (this.nextPending() || this.inFlight > 0) return
|
||||||
|
const attempts = this.state.attempts
|
||||||
|
const succeeded = attempts.some((attempt) => attempt.status === 'succeeded')
|
||||||
|
const anyFired = attempts.some((attempt) => attempt.status === 'succeeded' || attempt.status === 'failed')
|
||||||
|
this.clock.setAutoTarget(undefined)
|
||||||
|
this.state = {
|
||||||
|
...this.state,
|
||||||
|
status: succeeded ? 'succeeded' : anyFired ? 'failed' : 'cancelled',
|
||||||
|
message: succeeded
|
||||||
|
? '한 시도가 성공하여 예약이 접수되었습니다.'
|
||||||
|
: anyFired ? '모든 시도가 실패했습니다.' : '실행된 시도가 없습니다.',
|
||||||
|
}
|
||||||
|
this.emit()
|
||||||
|
}
|
||||||
|
|
||||||
|
private markAttempt(planned: PlannedAttempt, patch: Partial<AutoSalvoAttempt>) {
|
||||||
|
planned.attempt = { ...planned.attempt, ...patch }
|
||||||
|
this.state = {
|
||||||
|
...this.state,
|
||||||
|
attempts: this.state.attempts.map((attempt) => attempt.index === planned.attempt.index ? planned.attempt : attempt),
|
||||||
|
}
|
||||||
|
this.emit()
|
||||||
|
}
|
||||||
|
|
||||||
|
private emit() {
|
||||||
|
this.emitState(this.state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const autoSalvo = new AutoSalvoService()
|
||||||
|
|
||||||
|
export function registerAutoSalvoHandlers() {
|
||||||
|
const safe = async <T>(task: () => T | Promise<T>) => {
|
||||||
|
try {
|
||||||
|
return { ok: true, data: await task() }
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false, error: error instanceof Error ? error.message : '다중 시도 오류가 발생했습니다.' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ipcMain.handle('reservation:salvo-arm', (_event, config: AutoSalvoConfig) => safe(() => autoSalvo.arm(config)))
|
||||||
|
ipcMain.handle('reservation:salvo-disarm', () => safe(() => autoSalvo.disarm()))
|
||||||
|
ipcMain.handle('reservation:salvo-get', () => safe(() => autoSalvo.getState()))
|
||||||
|
ipcMain.on('reservation:renderer-unload', () => autoSalvo.reset())
|
||||||
|
app.once('before-quit', () => autoSalvo.reset())
|
||||||
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
import { registerReservationHandlers } from './reservation'
|
import { registerReservationHandlers } from './reservation'
|
||||||
import { registerAutoReservationHandlers } from './auto-reservation'
|
import { registerAutoReservationHandlers } from './auto-reservation'
|
||||||
|
import { registerAutoSalvoHandlers } from './auto-salvo'
|
||||||
import { registerClockHandlers } from './server-clock'
|
import { registerClockHandlers } from './server-clock'
|
||||||
|
|
||||||
registerReservationHandlers()
|
registerReservationHandlers()
|
||||||
registerClockHandlers()
|
registerClockHandlers()
|
||||||
registerAutoReservationHandlers()
|
registerAutoReservationHandlers()
|
||||||
|
registerAutoSalvoHandlers()
|
||||||
@@ -35,6 +35,14 @@ const reservationApi: ReservationApi = {
|
|||||||
ipcRenderer.on('reservation:auto-state', wrapped)
|
ipcRenderer.on('reservation:auto-state', wrapped)
|
||||||
return () => ipcRenderer.off('reservation:auto-state', wrapped)
|
return () => ipcRenderer.off('reservation:auto-state', wrapped)
|
||||||
},
|
},
|
||||||
|
armAutoSalvo: (config) => invoke('reservation:salvo-arm', config),
|
||||||
|
disarmAutoSalvo: () => invoke('reservation:salvo-disarm'),
|
||||||
|
getAutoSalvoState: () => invoke('reservation:salvo-get'),
|
||||||
|
subscribeAutoSalvo: (listener) => {
|
||||||
|
const wrapped = (_event: Electron.IpcRendererEvent, state: Parameters<typeof listener>[0]) => listener(state)
|
||||||
|
ipcRenderer.on('reservation:salvo-state', wrapped)
|
||||||
|
return () => ipcRenderer.off('reservation:salvo-state', wrapped)
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('reservationApi', reservationApi)
|
contextBridge.exposeInMainWorld('reservationApi', reservationApi)
|
||||||
|
|||||||
+12
-1
@@ -133,6 +133,17 @@ function ReservationApp() {
|
|||||||
}
|
}
|
||||||
}, [agreed, captchaToken, name, person, phone, selectedPrice, selection])
|
}, [agreed, captchaToken, name, person, phone, selectedPrice, selection])
|
||||||
|
|
||||||
|
const salvoBaseRequest = useMemo<Omit<ReservationRequest, 'captchaToken'> | null>(() => {
|
||||||
|
if (!selection || !selectedPrice || !name.trim() || !/^01\d-?\d{3,4}-?\d{4}$/.test(phone) || !agreed) return null
|
||||||
|
return {
|
||||||
|
...selection,
|
||||||
|
totalPrice: selectedPrice.totalPrice,
|
||||||
|
person,
|
||||||
|
name: name.trim(),
|
||||||
|
phone,
|
||||||
|
}
|
||||||
|
}, [agreed, name, person, phone, selectedPrice, selection])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const unsubscribe = window.reservationApi.subscribeAutoState((state) => setAutoStatus(state.status))
|
const unsubscribe = window.reservationApi.subscribeAutoState((state) => setAutoStatus(state.status))
|
||||||
window.reservationApi.getAutoReservationState().then((state) => setAutoStatus(state.status)).catch(() => undefined)
|
window.reservationApi.getAutoReservationState().then((state) => setAutoStatus(state.status)).catch(() => undefined)
|
||||||
@@ -446,7 +457,7 @@ function ReservationApp() {
|
|||||||
<div className="p-5 sm:p-6"><textarea aria-label="캡차 토큰" value={captchaToken} onChange={(event) => { const value = event.target.value; setCaptchaToken(value); setCaptchaPastedAtMs(value.trim() ? Date.now() : null) }} disabled={!scheduleDone || loading === 'captcha'} rows={3} placeholder="앱에서 인증하면 토큰이 자동으로 입력됩니다. 필요한 경우 직접 붙여넣을 수도 있습니다." spellCheck={false} className={`${inputClass} resize-none font-mono text-xs leading-5`} /><div className="mt-2 flex items-start justify-between gap-3 text-[10px] leading-4 text-ink-muted"><p>인증 창에서는 실제 예약 제출이 차단됩니다. 인증이 끝나면 창이 자동으로 닫히며 토큰은 메모리에만 보관됩니다.</p>{captchaToken && <span className="shrink-0 rounded-full bg-success/10 px-2 py-1 font-semibold text-success">인증 완료</span>}</div></div>
|
<div className="p-5 sm:p-6"><textarea aria-label="캡차 토큰" value={captchaToken} onChange={(event) => { const value = event.target.value; setCaptchaToken(value); setCaptchaPastedAtMs(value.trim() ? Date.now() : null) }} disabled={!scheduleDone || loading === 'captcha'} rows={3} placeholder="앱에서 인증하면 토큰이 자동으로 입력됩니다. 필요한 경우 직접 붙여넣을 수도 있습니다." spellCheck={false} className={`${inputClass} resize-none font-mono text-xs leading-5`} /><div className="mt-2 flex items-start justify-between gap-3 text-[10px] leading-4 text-ink-muted"><p>인증 창에서는 실제 예약 제출이 차단됩니다. 인증이 끝나면 창이 자동으로 닫히며 토큰은 메모리에만 보관됩니다.</p>{captchaToken && <span className="shrink-0 rounded-full bg-success/10 px-2 py-1 font-semibold text-success">인증 완료</span>}</div></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{autoMode && <AutomationPanel request={autoRequest} captchaToken={captchaToken} captchaPastedAtMs={captchaPastedAtMs} onTokenConsumed={() => { setCaptchaToken(''); setCaptchaPastedAtMs(null) }} onResult={setResult} />}
|
{autoMode && <AutomationPanel request={autoRequest} salvoBaseRequest={salvoBaseRequest} captchaSelection={selection} captchaToken={captchaToken} captchaPastedAtMs={captchaPastedAtMs} onTokenConsumed={() => { setCaptchaToken(''); setCaptchaPastedAtMs(null) }} onResult={setResult} />}
|
||||||
|
|
||||||
<section className="rounded-2xl border border-coral-soft bg-surface p-5 sm:p-6">
|
<section className="rounded-2xl border border-coral-soft bg-surface p-5 sm:p-6">
|
||||||
<div className="flex items-start justify-between gap-5"><div><p className="text-[10px] font-semibold uppercase tracking-[0.26em] text-violet">Final check</p><h2 className="mt-2 text-xl font-bold text-ink">예약 요약</h2></div><p className="text-xl font-bold tabular-nums text-ink">{formatPrice(selectedPrice?.totalPrice)}</p></div>
|
<div className="flex items-start justify-between gap-5"><div><p className="text-[10px] font-semibold uppercase tracking-[0.26em] text-violet">Final check</p><h2 className="mt-2 text-xl font-bold text-ink">예약 요약</h2></div><p className="text-xl font-bold tabular-nums text-ink">{formatPrice(selectedPrice?.totalPrice)}</p></div>
|
||||||
|
|||||||
@@ -1,14 +1,24 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import type {
|
import type {
|
||||||
AutoReservationState,
|
AutoReservationState,
|
||||||
|
AutoSalvoState,
|
||||||
|
CaptchaResult,
|
||||||
ClockCalibrationSettings,
|
ClockCalibrationSettings,
|
||||||
ClockEstimate,
|
ClockEstimate,
|
||||||
ReservationRequest,
|
ReservationRequest,
|
||||||
ReservationResult,
|
ReservationResult,
|
||||||
|
ReservationSelection,
|
||||||
TimingTestResult,
|
TimingTestResult,
|
||||||
} from '../type/reservation'
|
} from '../type/reservation'
|
||||||
import { CLOCK_CALIBRATION_DEFAULTS } 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 KST_OFFSET_MS = 9 * 60 * 60 * 1_000
|
||||||
const CLOCK_SETTINGS_STORAGE_KEY = 'escape-reserve.clock-calibration.v1'
|
const CLOCK_SETTINGS_STORAGE_KEY = 'escape-reserve.clock-calibration.v1'
|
||||||
const LEGACY_CLOCK_SETTINGS_STORAGE_KEY = 'reserve-escape.clock-calibration.v1'
|
const LEGACY_CLOCK_SETTINGS_STORAGE_KEY = 'reserve-escape.clock-calibration.v1'
|
||||||
@@ -25,6 +35,8 @@ function loadClockSettings(): ClockCalibrationSettings {
|
|||||||
|
|
||||||
interface AutomationPanelProps {
|
interface AutomationPanelProps {
|
||||||
request: ReservationRequest | null
|
request: ReservationRequest | null
|
||||||
|
salvoBaseRequest: Omit<ReservationRequest, 'captchaToken'> | null
|
||||||
|
captchaSelection: ReservationSelection | null
|
||||||
captchaToken: string
|
captchaToken: string
|
||||||
captchaPastedAtMs: number | null
|
captchaPastedAtMs: number | null
|
||||||
onTokenConsumed: () => void
|
onTokenConsumed: () => void
|
||||||
@@ -105,6 +117,8 @@ function SampleGraph({ estimate }: { estimate: ClockEstimate }) {
|
|||||||
|
|
||||||
export default function AutomationPanel({
|
export default function AutomationPanel({
|
||||||
request,
|
request,
|
||||||
|
salvoBaseRequest,
|
||||||
|
captchaSelection,
|
||||||
captchaToken,
|
captchaToken,
|
||||||
captchaPastedAtMs,
|
captchaPastedAtMs,
|
||||||
onTokenConsumed,
|
onTokenConsumed,
|
||||||
@@ -120,8 +134,15 @@ export default function AutomationPanel({
|
|||||||
const [timingTest, setTimingTest] = useState<TimingTestResult | null>(null)
|
const [timingTest, setTimingTest] = useState<TimingTestResult | null>(null)
|
||||||
const [settingsOpen, setSettingsOpen] = useState(false)
|
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||||
const [clockSettings, setClockSettings] = useState<ClockCalibrationSettings>(loadClockSettings)
|
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 previousFingerprint = useRef('')
|
||||||
const previousAutoStatus = useRef(autoState.status)
|
const previousAutoStatus = useRef(autoState.status)
|
||||||
|
const previousSalvoStatus = useRef(salvoState.status)
|
||||||
const previousCaptchaAt = useRef<number | null>(null)
|
const previousCaptchaAt = useRef<number | null>(null)
|
||||||
const targetServerTimeMs = parseKstInput(targetInput)
|
const targetServerTimeMs = parseKstInput(targetInput)
|
||||||
const liveServerTimeMs = clock
|
const liveServerTimeMs = clock
|
||||||
@@ -134,6 +155,17 @@ export default function AutomationPanel({
|
|||||||
: Number.POSITIVE_INFINITY
|
: Number.POSITIVE_INFINITY
|
||||||
const tokenReady = captchaToken.trim().length >= 30 && tokenAgeAtTargetMs >= 0 && tokenAgeAtTargetMs <= 90_000
|
const tokenReady = captchaToken.trim().length >= 30 && tokenAgeAtTargetMs >= 0 && tokenAgeAtTargetMs <= 90_000
|
||||||
const armed = autoState.status === 'armed' || autoState.status === 'firing'
|
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({
|
const requestFingerprint = useMemo(() => request ? JSON.stringify({
|
||||||
...request,
|
...request,
|
||||||
@@ -143,17 +175,20 @@ export default function AutomationPanel({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const unsubscribeClock = window.reservationApi.subscribeClock(setClock)
|
const unsubscribeClock = window.reservationApi.subscribeClock(setClock)
|
||||||
const unsubscribeAuto = window.reservationApi.subscribeAutoState(setAutoState)
|
const unsubscribeAuto = window.reservationApi.subscribeAutoState(setAutoState)
|
||||||
|
const unsubscribeSalvo = window.reservationApi.subscribeAutoSalvo(setSalvoState)
|
||||||
void Promise.all([
|
void Promise.all([
|
||||||
window.reservationApi.configureClock(clockSettings).then((estimate) => {
|
window.reservationApi.configureClock(clockSettings).then((estimate) => {
|
||||||
setClock(estimate)
|
setClock(estimate)
|
||||||
setClockSettings(estimate.calibrationSettings)
|
setClockSettings(estimate.calibrationSettings)
|
||||||
}),
|
}),
|
||||||
window.reservationApi.getAutoReservationState().then(setAutoState),
|
window.reservationApi.getAutoReservationState().then(setAutoState),
|
||||||
|
window.reservationApi.getAutoSalvoState().then(setSalvoState),
|
||||||
]).catch(() => undefined)
|
]).catch(() => undefined)
|
||||||
const interval = window.setInterval(() => setNowMs(Date.now()), 50)
|
const interval = window.setInterval(() => setNowMs(Date.now()), 50)
|
||||||
return () => {
|
return () => {
|
||||||
unsubscribeClock()
|
unsubscribeClock()
|
||||||
unsubscribeAuto()
|
unsubscribeAuto()
|
||||||
|
unsubscribeSalvo()
|
||||||
window.clearInterval(interval)
|
window.clearInterval(interval)
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
@@ -184,6 +219,16 @@ export default function AutomationPanel({
|
|||||||
}
|
}
|
||||||
}, [autoState, onResult, onTokenConsumed])
|
}, [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 () => {
|
const toggleMonitor = async () => {
|
||||||
setBusy('monitor')
|
setBusy('monitor')
|
||||||
setError('')
|
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'
|
const qualityTone = clock?.quality === 'good' ? 'good' : clock?.quality === 'poor' || clock?.quality === 'unavailable' ? 'warn' : 'normal'
|
||||||
|
|
||||||
return (
|
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>}
|
{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>}
|
{(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>}
|
{!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>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -222,6 +222,48 @@ export interface AutoReservationState {
|
|||||||
timeline?: AutoReservationTimeline
|
timeline?: AutoReservationTimeline
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SalvoAttemptInput {
|
||||||
|
offsetMs: number
|
||||||
|
captchaToken: string
|
||||||
|
captchaSolvedAtMs: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AutoSalvoConfig {
|
||||||
|
baseRequest: Omit<ReservationRequest, 'captchaToken'>
|
||||||
|
targetServerTimeMs: number
|
||||||
|
userOffsetMs: number
|
||||||
|
attempts: SalvoAttemptInput[]
|
||||||
|
stopOnSuccess: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AutoSalvoAttempt {
|
||||||
|
index: number
|
||||||
|
offsetMs: number
|
||||||
|
effectiveTargetServerMs: number
|
||||||
|
plannedSendAtMs?: number
|
||||||
|
actualSendAtMs?: number
|
||||||
|
arrivalErrorMs?: number
|
||||||
|
rttMs?: number
|
||||||
|
httpStatus?: number
|
||||||
|
status: 'pending' | 'firing' | 'succeeded' | 'failed' | 'skipped'
|
||||||
|
message?: string
|
||||||
|
reservationNum?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AutoSalvoState {
|
||||||
|
status: 'idle' | 'armed' | 'firing' | 'succeeded' | 'failed' | 'cancelled'
|
||||||
|
targetServerTimeMs?: number
|
||||||
|
userOffsetMs?: number
|
||||||
|
armedAtMs?: number
|
||||||
|
stopOnSuccess: boolean
|
||||||
|
snapshot?: AutoReservationSnapshot
|
||||||
|
attempts: AutoSalvoAttempt[]
|
||||||
|
succeededIndex?: number
|
||||||
|
warning?: string
|
||||||
|
message?: string
|
||||||
|
result?: ReservationResult
|
||||||
|
}
|
||||||
|
|
||||||
export interface ReservationApi {
|
export interface ReservationApi {
|
||||||
getBranches(): Promise<Branch[]>
|
getBranches(): Promise<Branch[]>
|
||||||
getThemes(branchNum: number): Promise<Theme[]>
|
getThemes(branchNum: number): Promise<Theme[]>
|
||||||
@@ -240,4 +282,8 @@ export interface ReservationApi {
|
|||||||
disarmAutoReservation(): Promise<AutoReservationState>
|
disarmAutoReservation(): Promise<AutoReservationState>
|
||||||
getAutoReservationState(): Promise<AutoReservationState>
|
getAutoReservationState(): Promise<AutoReservationState>
|
||||||
subscribeAutoState(listener: (state: AutoReservationState) => void): () => void
|
subscribeAutoState(listener: (state: AutoReservationState) => void): () => void
|
||||||
|
armAutoSalvo(config: AutoSalvoConfig): Promise<AutoSalvoState>
|
||||||
|
disarmAutoSalvo(): Promise<AutoSalvoState>
|
||||||
|
getAutoSalvoState(): Promise<AutoSalvoState>
|
||||||
|
subscribeAutoSalvo(listener: (state: AutoSalvoState) => void): () => void
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { AutoSalvoService } from '../electron/main/auto-salvo'
|
||||||
|
import { CLOCK_CALIBRATION_DEFAULTS, type AutoSalvoConfig, type ClockEstimate, type ReservationResult } from '../src/type/reservation'
|
||||||
|
|
||||||
|
function estimate(): ClockEstimate {
|
||||||
|
const now = Date.now()
|
||||||
|
return {
|
||||||
|
monitoring: true,
|
||||||
|
observedAtMs: now,
|
||||||
|
estimatedServerTimeMs: now,
|
||||||
|
offsetMs: 0,
|
||||||
|
driftPpm: 0,
|
||||||
|
minRttMs: 60,
|
||||||
|
p50RttMs: 62,
|
||||||
|
p95RttMs: 70,
|
||||||
|
oneWayMs: 0,
|
||||||
|
uncertaintyMs: 400,
|
||||||
|
sampleAgeMs: 0,
|
||||||
|
acceptedSamples: 8,
|
||||||
|
rawOffsetMs: 0,
|
||||||
|
boundaryCount: 5,
|
||||||
|
boundaryOffsetMs: 0,
|
||||||
|
boundaryUncertaintyMs: 40,
|
||||||
|
boundarySpreadMs: 15,
|
||||||
|
recommendedCorrectionMs: 0,
|
||||||
|
calibrationReady: true,
|
||||||
|
calibrationApplied: true,
|
||||||
|
calibrationSettings: CLOCK_CALIBRATION_DEFAULTS,
|
||||||
|
remoteIp: '13.125.18.86',
|
||||||
|
quality: 'fair',
|
||||||
|
samples: [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function config(targetServerTimeMs: number, tokenCount: number, stepMs: number, stopOnSuccess = false): AutoSalvoConfig {
|
||||||
|
const solvedAtMs = Date.now()
|
||||||
|
const attempts = Array.from({ length: tokenCount }, (_, index) => ({
|
||||||
|
offsetMs: Math.round((index - (tokenCount - 1) / 2) * stepMs),
|
||||||
|
captchaToken: `token-${index}-${'x'.repeat(40)}`,
|
||||||
|
captchaSolvedAtMs: solvedAtMs,
|
||||||
|
}))
|
||||||
|
return {
|
||||||
|
targetServerTimeMs,
|
||||||
|
userOffsetMs: 0,
|
||||||
|
stopOnSuccess,
|
||||||
|
attempts,
|
||||||
|
baseRequest: {
|
||||||
|
branchNum: 22, themeNum: 66, themeInfoNum: 44,
|
||||||
|
date: '2026-08-18', timeNum: 2309, timeLabel: '14:25', themeName: '내 방',
|
||||||
|
totalPrice: 60_000, person: 2, name: '테스트', phone: '010-1234-5678',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function result(reservationNum: string, success = true): ReservationResult {
|
||||||
|
return {
|
||||||
|
success, message: success ? '완료' : '실패', reservationNum: success ? reservationNum : undefined,
|
||||||
|
transport: {
|
||||||
|
sentAtMs: Date.now(), receivedAtMs: Date.now() + 60, rttMs: 60,
|
||||||
|
httpStatus: success ? 200 : 409, remoteIp: '13.125.18.86', reusedSocket: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('multi-attempt (salvo) auto reservation scheduler', () => {
|
||||||
|
afterEach(() => vi.useRealTimers())
|
||||||
|
|
||||||
|
it('fires one attempt per token at each ± offset', async () => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z'))
|
||||||
|
const execute = vi.fn<() => Promise<ReservationResult>>().mockImplementation(async () => result('R', false))
|
||||||
|
const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() }
|
||||||
|
const service = new AutoSalvoService(clock, execute, vi.fn())
|
||||||
|
|
||||||
|
await service.arm(config(Date.now() + 2_000, 3, 300))
|
||||||
|
await vi.advanceTimersByTimeAsync(3_000)
|
||||||
|
|
||||||
|
expect(execute).toHaveBeenCalledTimes(3)
|
||||||
|
const tokensUsed = execute.mock.calls.map((call) => (call[0] as { captchaToken: string }).captchaToken)
|
||||||
|
expect(new Set(tokensUsed).size).toBe(3)
|
||||||
|
expect(service.getState().status).toBe('failed')
|
||||||
|
expect(service.getState().attempts.map((attempt) => attempt.status)).toEqual(['failed', 'failed', 'failed'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cancels remaining attempts after the first success when stopOnSuccess is set', async () => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z'))
|
||||||
|
const execute = vi.fn<() => Promise<ReservationResult>>().mockResolvedValue(result('R-1'))
|
||||||
|
const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() }
|
||||||
|
const service = new AutoSalvoService(clock, execute, vi.fn())
|
||||||
|
|
||||||
|
await service.arm(config(Date.now() + 2_000, 4, 300, true))
|
||||||
|
await vi.advanceTimersByTimeAsync(4_000)
|
||||||
|
|
||||||
|
expect(execute).toHaveBeenCalledTimes(1)
|
||||||
|
const state = service.getState()
|
||||||
|
expect(state.status).toBe('succeeded')
|
||||||
|
expect(state.succeededIndex).toBe(0)
|
||||||
|
expect(state.attempts.filter((attempt) => attempt.status === 'skipped')).toHaveLength(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects a token that would be older than 90s at its target', async () => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z'))
|
||||||
|
const execute = vi.fn<() => Promise<ReservationResult>>()
|
||||||
|
const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() }
|
||||||
|
const service = new AutoSalvoService(clock, execute, vi.fn())
|
||||||
|
|
||||||
|
await expect(service.arm(config(Date.now() + 120_000, 2, 300))).rejects.toThrow(/90초/)
|
||||||
|
expect(execute).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('disarming clears the schedule and prevents submission', async () => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z'))
|
||||||
|
const execute = vi.fn<() => Promise<ReservationResult>>()
|
||||||
|
const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() }
|
||||||
|
const service = new AutoSalvoService(clock, execute, vi.fn())
|
||||||
|
|
||||||
|
await service.arm(config(Date.now() + 2_000, 3, 300))
|
||||||
|
service.disarm()
|
||||||
|
await vi.advanceTimersByTimeAsync(3_000)
|
||||||
|
|
||||||
|
expect(execute).not.toHaveBeenCalled()
|
||||||
|
expect(service.getState().status).toBe('cancelled')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -81,10 +81,10 @@ test.describe('[escape-reserve] e2e tests', () => {
|
|||||||
test('exposes the reservation bridge', async () => {
|
test('exposes the reservation bridge', async () => {
|
||||||
const methods = await page.evaluate(() => Object.keys(window.reservationApi).sort())
|
const methods = await page.evaluate(() => Object.keys(window.reservationApi).sort())
|
||||||
expect(methods).toEqual([
|
expect(methods).toEqual([
|
||||||
'armAutoReservation', 'configureClock', 'disarmAutoReservation', 'getAutoReservationState',
|
'armAutoReservation', 'armAutoSalvo', 'configureClock', 'disarmAutoReservation', 'disarmAutoSalvo',
|
||||||
'getBranches', 'getClockState', 'getThemeDetail', 'getThemes', 'getTimes',
|
'getAutoReservationState', 'getAutoSalvoState', 'getBranches', 'getClockState', 'getThemeDetail',
|
||||||
'openCaptcha', 'prepare', 'runTimingTest', 'startClockMonitor',
|
'getThemes', 'getTimes', 'openCaptcha', 'prepare', 'runTimingTest', 'startClockMonitor',
|
||||||
'stopClockMonitor', 'submit', 'subscribeAutoState', 'subscribeClock',
|
'stopClockMonitor', 'submit', 'subscribeAutoSalvo', 'subscribeAutoState', 'subscribeClock',
|
||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -129,7 +129,7 @@ test.describe('[escape-reserve] e2e tests', () => {
|
|||||||
await page.getByPlaceholder('홍길동').fill('테스트')
|
await page.getByPlaceholder('홍길동').fill('테스트')
|
||||||
await page.getByPlaceholder('010-0000-0000').fill('010-1234-5678')
|
await page.getByPlaceholder('010-0000-0000').fill('010-1234-5678')
|
||||||
await page.getByLabel('캡차 토큰').fill('x'.repeat(100))
|
await page.getByLabel('캡차 토큰').fill('x'.repeat(100))
|
||||||
await page.getByRole('checkbox').check()
|
await page.getByRole('checkbox', { name: '개인정보 수집' }).check()
|
||||||
|
|
||||||
const target = await page.evaluate(() => {
|
const target = await page.evaluate(() => {
|
||||||
const value = new Date(Date.now() + 30_000 + 9 * 60 * 60 * 1_000)
|
const value = new Date(Date.now() + 30_000 + 9 * 60 * 60 * 1_000)
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 117 KiB After Width: | Height: | Size: 90 KiB |
Reference in new issue
Block a user