275 lines
10 KiB
TypeScript
275 lines
10 KiB
TypeScript
import { app, BrowserWindow, ipcMain } from 'electron'
|
|
import type {
|
|
AutoReservationConfig,
|
|
AutoReservationSnapshot,
|
|
AutoReservationState,
|
|
ReservationRequest,
|
|
} from '../../src/type/reservation'
|
|
import { executeReservation } from './reservation'
|
|
import { serverClock } from './server-clock'
|
|
import { computePlannedSendAtMs } from './server-clock-core'
|
|
import type { ClockEstimate } from '../../src/type/reservation'
|
|
|
|
const AUTO_EVENT = 'reservation:auto-state'
|
|
const MAX_TOKEN_TARGET_AGE_MS = 90_000
|
|
const MAX_LATE_FIRE_MS = 1_000
|
|
|
|
function broadcast(value: AutoReservationState) {
|
|
for (const window of BrowserWindow.getAllWindows()) {
|
|
if (!window.isDestroyed()) window.webContents.send(AUTO_EVENT, value)
|
|
}
|
|
}
|
|
|
|
function snapshot(request: ReservationRequest): AutoReservationSnapshot {
|
|
return {
|
|
branchNum: request.branchNum,
|
|
themeNum: request.themeNum,
|
|
themeInfoNum: request.themeInfoNum,
|
|
date: request.date,
|
|
timeNum: request.timeNum,
|
|
timeLabel: request.timeLabel,
|
|
themeName: request.themeName,
|
|
totalPrice: request.totalPrice,
|
|
person: request.person,
|
|
}
|
|
}
|
|
|
|
function cloneRequest(request: ReservationRequest): ReservationRequest {
|
|
return {
|
|
branchNum: request.branchNum,
|
|
themeNum: request.themeNum,
|
|
themeInfoNum: request.themeInfoNum,
|
|
date: request.date,
|
|
timeNum: request.timeNum,
|
|
timeLabel: request.timeLabel,
|
|
themeName: request.themeName,
|
|
totalPrice: request.totalPrice,
|
|
person: request.person,
|
|
name: request.name,
|
|
phone: request.phone,
|
|
captchaToken: request.captchaToken,
|
|
}
|
|
}
|
|
|
|
export class AutoReservationService {
|
|
private config?: AutoReservationConfig
|
|
private timer?: NodeJS.Timeout
|
|
private expectedTickAtMs = 0
|
|
private frozenTiming?: { plannedSendAtMs: number; offsetMs: number; oneWayMs: number }
|
|
private state: AutoReservationState = { status: 'idle', tokenStatus: 'empty' }
|
|
|
|
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: AutoReservationState) => void = broadcast,
|
|
) {}
|
|
|
|
getState() {
|
|
return this.state
|
|
}
|
|
|
|
async arm(input: AutoReservationConfig) {
|
|
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 (!Number.isFinite(input.captchaPastedAtMs) || input.captchaPastedAtMs > Date.now()) {
|
|
throw new Error('캡차 토큰 입력 시각이 올바르지 않습니다.')
|
|
}
|
|
if (input.request.captchaToken.trim().length < 30) 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 targetLocalTimeMs = input.targetServerTimeMs - estimate.offsetMs
|
|
const tokenAgeAtTargetMs = targetLocalTimeMs - input.captchaPastedAtMs
|
|
if (tokenAgeAtTargetMs < 0 || tokenAgeAtTargetMs > MAX_TOKEN_TARGET_AGE_MS) {
|
|
throw new Error('캡차 토큰 입력 후 90초 이내의 실행 시각만 무장할 수 있습니다.')
|
|
}
|
|
|
|
this.config = {
|
|
request: cloneRequest(input.request),
|
|
targetServerTimeMs: input.targetServerTimeMs,
|
|
userOffsetMs: input.userOffsetMs,
|
|
captchaPastedAtMs: input.captchaPastedAtMs,
|
|
}
|
|
this.frozenTiming = undefined
|
|
this.state = {
|
|
status: 'armed',
|
|
targetServerTimeMs: input.targetServerTimeMs,
|
|
userOffsetMs: input.userOffsetMs,
|
|
armedAtMs: Date.now(),
|
|
captchaPastedAtMs: input.captchaPastedAtMs,
|
|
tokenStatus: 'ready',
|
|
snapshot: snapshot(input.request),
|
|
warning: estimate.quality === 'poor' || (estimate.calibrationSettings.enabled && !estimate.calibrationReady) ? estimate.warning : undefined,
|
|
}
|
|
this.clock.setAutoTarget(input.targetServerTimeMs)
|
|
this.emit()
|
|
this.scheduleTick(0)
|
|
return this.state
|
|
}
|
|
|
|
disarm(message = '자동 예약이 해제되었습니다.') {
|
|
if (this.state.status === 'firing') return this.state
|
|
if (this.timer) clearTimeout(this.timer)
|
|
this.timer = undefined
|
|
this.frozenTiming = undefined
|
|
this.config = undefined
|
|
this.clock.setAutoTarget(undefined)
|
|
this.state = { status: 'cancelled', tokenStatus: 'empty', message }
|
|
this.emit()
|
|
return this.state
|
|
}
|
|
|
|
reset() {
|
|
if (this.timer) clearTimeout(this.timer)
|
|
this.timer = undefined
|
|
this.frozenTiming = undefined
|
|
this.config = undefined
|
|
this.clock.setAutoTarget(undefined)
|
|
this.state = { status: 'idle', tokenStatus: 'empty' }
|
|
this.emit()
|
|
}
|
|
|
|
private scheduleTick(delayMs: number) {
|
|
if (this.timer) clearTimeout(this.timer)
|
|
const normalizedDelay = Math.max(0, delayMs)
|
|
this.expectedTickAtMs = Date.now() + normalizedDelay
|
|
this.timer = setTimeout(() => void this.tick(), normalizedDelay)
|
|
}
|
|
|
|
private tick() {
|
|
if (this.state.status !== 'armed' || !this.config) return
|
|
const tickLateMs = Math.max(0, Date.now() - this.expectedTickAtMs)
|
|
const estimate = this.clock.getEstimate()
|
|
if (estimate.acceptedSamples === 0) {
|
|
this.failBeforeSend('유효한 서버시간 표본이 없어 제출하지 않았습니다.', 'empty')
|
|
return
|
|
}
|
|
|
|
const plannedSendAtMs = this.frozenTiming?.plannedSendAtMs ?? computePlannedSendAtMs(
|
|
this.config.targetServerTimeMs, this.config.userOffsetMs, estimate,
|
|
)
|
|
const remainingMs = plannedSendAtMs - Date.now()
|
|
const effectiveTarget = this.config.targetServerTimeMs + this.config.userOffsetMs
|
|
if (estimate.estimatedServerTimeMs > effectiveTarget + MAX_LATE_FIRE_MS) {
|
|
this.failBeforeSend('절전 또는 지연으로 목표 시각이 지나 제출하지 않았습니다.', 'ready')
|
|
return
|
|
}
|
|
if (remainingMs < 0 && tickLateMs > 250) {
|
|
this.failBeforeSend('절전 또는 스케줄러 정지 후 목표 시각이 지나 제출하지 않았습니다.', 'ready')
|
|
return
|
|
}
|
|
|
|
this.state = {
|
|
...this.state,
|
|
warning: estimate.quality === 'poor' || (estimate.calibrationSettings.enabled && !estimate.calibrationReady) ? estimate.warning : undefined,
|
|
timeline: { ...this.state.timeline, plannedSendAtMs },
|
|
}
|
|
this.emit()
|
|
|
|
if (remainingMs > 100) {
|
|
this.scheduleTick(Math.min(1_000, Math.max(10, remainingMs - 100)))
|
|
return
|
|
}
|
|
if (!this.frozenTiming) {
|
|
this.frozenTiming = { plannedSendAtMs, offsetMs: estimate.offsetMs, oneWayMs: estimate.oneWayMs }
|
|
this.clock.setAutoTarget(undefined)
|
|
}
|
|
if (remainingMs > 0) {
|
|
this.scheduleTick(remainingMs)
|
|
return
|
|
}
|
|
if (remainingMs >= -MAX_LATE_FIRE_MS) void this.fire(this.frozenTiming.offsetMs, this.frozenTiming.oneWayMs)
|
|
else this.failBeforeSend('스케줄러 지연으로 목표 시각을 놓쳐 제출하지 않았습니다.', 'ready')
|
|
}
|
|
|
|
private async fire(offsetMs: number, oneWayMs: number) {
|
|
if (this.state.status !== 'armed' || !this.config) return
|
|
const config = this.config
|
|
this.config = undefined
|
|
if (this.timer) clearTimeout(this.timer)
|
|
this.timer = undefined
|
|
this.frozenTiming = undefined
|
|
this.state = { ...this.state, status: 'firing', tokenStatus: 'consumed' }
|
|
this.emit()
|
|
|
|
try {
|
|
const result = await this.execute(config.request)
|
|
const transport = result.transport
|
|
const estimatedArrivalServerMs = transport
|
|
? transport.sentAtMs + offsetMs + oneWayMs
|
|
: undefined
|
|
const effectiveTarget = config.targetServerTimeMs + config.userOffsetMs
|
|
this.state = {
|
|
...this.state,
|
|
status: result.success ? 'succeeded' : 'failed',
|
|
message: result.message,
|
|
result,
|
|
timeline: {
|
|
...this.state.timeline,
|
|
actualSendAtMs: transport?.sentAtMs,
|
|
estimatedArrivalServerMs,
|
|
arrivalErrorMs: estimatedArrivalServerMs === undefined ? undefined : estimatedArrivalServerMs - effectiveTarget,
|
|
rttMs: transport?.rttMs,
|
|
httpStatus: transport?.httpStatus,
|
|
remoteIp: transport?.remoteIp,
|
|
reusedSocket: transport?.reusedSocket,
|
|
},
|
|
}
|
|
} catch (error) {
|
|
this.state = {
|
|
...this.state,
|
|
status: 'failed',
|
|
message: error instanceof Error ? error.message : '자동 예약 요청에 실패했습니다.',
|
|
}
|
|
} finally {
|
|
this.clock.setAutoTarget(undefined)
|
|
this.emit()
|
|
}
|
|
}
|
|
|
|
private failBeforeSend(message: string, tokenStatus: AutoReservationState['tokenStatus']) {
|
|
if (this.timer) clearTimeout(this.timer)
|
|
this.timer = undefined
|
|
this.frozenTiming = undefined
|
|
this.config = undefined
|
|
this.clock.setAutoTarget(undefined)
|
|
this.state = { ...this.state, status: 'failed', tokenStatus, message }
|
|
this.emit()
|
|
}
|
|
|
|
private emit() {
|
|
this.emitState(this.state)
|
|
}
|
|
}
|
|
|
|
export const autoReservation = new AutoReservationService()
|
|
|
|
export function registerAutoReservationHandlers() {
|
|
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:auto-arm', (_event, config: AutoReservationConfig) => safe(() => autoReservation.arm(config)))
|
|
ipcMain.handle('reservation:auto-disarm', () => safe(() => autoReservation.disarm()))
|
|
ipcMain.handle('reservation:auto-get', () => safe(() => autoReservation.getState()))
|
|
ipcMain.on('reservation:renderer-unload', () => autoReservation.reset())
|
|
app.once('before-quit', () => {
|
|
autoReservation.reset()
|
|
serverClock.dispose()
|
|
})
|
|
}
|