/* In-page controls only. Authentication, authority and all sends belong to the * supplied engine. This panel never starts from stored settings. */ (function (global) { 'use strict'; const ID = /^[a-z0-9_]{2,32}$/; const STORAGE_PREFIX = 'soop-auto-manager:rules:v1:'; const MAX_RULES = 100; let mounted = null; const REASONS = { user_stop: '사용자가 중지했습니다.', panel_closed: '관리 패널을 닫아 중지했습니다.', manual_moderation: '직접 제재한 내역을 보호하기 위해 자동 관리를 중지했습니다.', roster_refresh: '명단을 다시 받아 중지했습니다. 확인 후 다시 시작해 주세요.', permission_unverified: '현재 방송의 로그인·매니저 권한을 확인할 수 없습니다.', context_changed: '계정·방송·권한 또는 연결이 변경되어 중지했습니다.', permission_or_connection_changed: '권한 또는 채팅 연결이 변경되어 중지했습니다.', connection_or_broadcast_changed: '채팅 연결 또는 방송이 변경되어 중지했습니다.', unverified_server_response: '서버 응답을 확인할 수 없어 중지했습니다.', disabled: '대상을 설정하고 직접 시작해 주세요.', not_connected: '방송 채팅에 연결한 뒤 다시 확인해 주세요.', disconnected: '채팅 연결이 종료되어 중지되었습니다.', connection_closed: '채팅 연결이 종료되어 중지되었습니다.', insufficient_role: '이 방송의 BJ 또는 매니저 권한이 필요합니다.', authority_unverified: '현재 로그인 계정의 방송 권한을 확인하는 중입니다.', permission_denied: '이 방송의 BJ 또는 매니저 권한이 필요합니다.', role_lost: '방송 권한이 변경되어 중지되었습니다.', account_changed: '로그인 계정이 변경되어 중지되었습니다.', broadcast_changed: '방송이 변경되어 중지되었습니다.', scope_changed: '계정 또는 방송이 변경되어 중지되었습니다.', invalid_rules: '대상 아이디와 실행 설정을 확인해 주세요.', already_running: '이미 실행 중입니다.', cooldown: '연속 실행 제한으로 건너뛰었습니다.', kick_requested: '강퇴 요청', mute_requested: '채팅금지 요청', cancel_requested: '강퇴 취소 요청', kick_confirmed: '강퇴 확인', cancel_confirmed: '강퇴 취소 확인', confirmed: '확인 완료', cancel_packet_confirmed: '취소 응답 확인', requested: '요청 처리 중', rejected: '요청 거절', unknown: '결과 확인 불가', reserved: '실행 예약', aborted: '중지', skipped: '건너뜀', blocked: '실행 차단', error: '처리 오류', own_kick_packet_confirmed: '0076 강퇴 성공 응답 확인', kick_result_unverified: '강퇴 결과 미확인', send_result_unverified: '전송 결과 미확인', operation_unverified: '실행 조건 미확인', mute_packet_confirmed: '채금 응답 확인', mute_result_unverified: '채금 결과 미확인', mute_blind_confirmed: '블라인드 응답 확인', mute_series_stopped: '남은 채금 중지', target_departed: '대상이 퇴장하여 반복 중지', duration_unverified: '서버 지속시간 미확인', target_disabled: '이 유저의 자동 관리 OFF', repeat_conditions_changed: '실행 조건 변경으로 반복 중지', blind_kick_confirmed: '블라인드 강퇴 확인', mute_no_pending_request: '대기 중인 채금 요청 없음', mute_duplicate_response: '중복 응답', mute_scope_changed: '요청 중지 또는 연결·권한 변경', mute_target_mismatch: '대상 접속 ID 불일치', mute_actor_mismatch: '제재자 계정 불일치', mute_count_mismatch: '채금 누적 횟수 불일치', mute_response_shape: '채금 응답 필드 미확인', mute_server_rejected: '서버 요청 거절', mute_response_unmatched: '채금 요청과 응답 미일치', send_guard_changed: '계정·방송·권한 변경으로 중지', intervening_kick: '다른 강퇴 기록이 있어 자동 취소 중지', cancel_result_unverified: '취소 결과 미확인', cancel_guard_changed: '취소 조건이 달라져 중지', }; const CSS = ` :host{all:initial;position:fixed;right:16px;bottom:16px;width:min(410px,calc(100vw - 24px));z-index:2147483647;color-scheme:dark;font:12px/1.5 Arial,"Malgun Gothic",sans-serif;color:#e8eef4} *{box-sizing:border-box}button,input,select,textarea{font:inherit}button{cursor:pointer}button:disabled{opacity:.4;cursor:default} button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid #8cebbd;outline-offset:2px} .panel{background:#101b23;border:1px solid #385363;border-radius:14px;box-shadow:0 14px 55px #0008;max-height:min(760px,calc(100dvh - 32px));overflow:auto} header{display:flex;justify-content:space-between;align-items:center;padding:15px 16px;background:#1b2b35;position:sticky;top:0;z-index:1;border-bottom:1px solid #314754;cursor:grab;touch-action:none;user-select:none}header[data-dragging=true]{cursor:grabbing} h1,h2,p{margin:0}h1{font-size:16px;line-height:1.4}header p{font-size:10px;color:#9bb1bf;margin-top:2px}h2{font-size:12px} .close{border:0;border-radius:7px;background:#2b414d;color:#d6e5ed;width:28px;height:28px;font-size:20px;line-height:1} .target-toggle{display:flex;align-items:center;gap:4px;color:#9ccdb6;font-size:10px;white-space:nowrap;cursor:pointer}.target-toggle[data-active=false]{color:#8ba0ad} .body{padding:14px 16px}.scope{background:#1a2a34;border:1px solid #2c444f;border-radius:9px;padding:11px 12px} .scope-head,.section-head,.row,.controls,.draft-bottom{display:flex;align-items:center;justify-content:space-between;gap:8px}.scope-head{margin-bottom:8px} .room{font-size:15px;font-weight:700;overflow-wrap:anywhere}.phase{font-size:10px;white-space:nowrap;padding:3px 7px;border:1px solid #48616e;border-radius:20px;color:#b4c9d5} .phase[data-active=true]{background:#153e2e;border-color:#427e60;color:#a0efbd}.account,.role{font-size:11px;color:#aec3cf;overflow-wrap:anywhere}.hint{font-size:10px;color:#91a9b9;line-height:1.6} .scope-note{margin-top:8px;padding-top:8px;border-top:1px solid #304651}.section-head{margin:17px 0 8px}.count{color:#8da8b8;font-size:10px} .rules{display:grid;gap:8px;max-height:230px;overflow:auto;padding:2px}.rule{padding:9px;background:#182933;border:1px solid #304956;border-radius:8px}.rule .row+ .row{margin-top:7px} input,select,textarea{background:#10202a;color:#e0ecf2;border:1px solid #405b6a;border-radius:5px;padding:6px 7px;min-width:0}.target{flex:1;width:120px;font-family:Consolas,monospace;font-size:12px} .target-identity{flex:1;min-width:0}.target-identity .target{width:100%}.target-nick{display:block;color:#e0ecf2;font-weight:700;margin-bottom:3px;white-space:pre-wrap;overflow-wrap:anywhere} select{width:82px;font-size:11px}.remove{border:0;background:transparent;color:#acc1ce;padding:3px 5px;font-size:17px}.cancel-label{font-size:10px;color:#b3c8d4;display:flex;gap:5px;align-items:center;flex-wrap:wrap} input[type=checkbox]{width:14px;height:14px;margin:0;accent-color:#80e3ad}.delay{width:54px;padding:4px 5px;font-size:11px}.row[hidden]{display:none}.empty{font-size:11px;color:#819cab;padding:10px 0} .draft{margin-top:9px;padding:10px;background:#14252f;border:1px dashed #3b5564;border-radius:8px}.draft label{font-size:10px;color:#9eb6c4}.draft textarea{display:block;width:100%;resize:vertical;min-height:52px;max-height:120px;margin-top:5px;font-size:11px;line-height:1.5}.draft-bottom{margin-top:7px} .secondary{border:1px solid #46616e;border-radius:6px;background:#223c49;color:#dceaf1;padding:6px 10px;font-size:11px;white-space:nowrap}.secondary:hover:enabled{background:#2d4a58} .settings-note{margin-top:8px}.notice{padding:9px 10px;border-radius:7px;background:#1a3c2d;color:#b6efcf;margin-top:12px;font-size:11px;overflow-wrap:anywhere}.notice[data-error=true]{background:#452b31;color:#f0bcc2} .controls{margin-top:12px}.start,.stop{padding:10px 12px;border-radius:7px;font-size:12px;font-weight:700}.start{flex:1;border:0;background:#86e6b2;color:#103326}.stop{min-width:74px;border:1px solid #7a535e;background:#422d36;color:#f2ccd3} .session-note{margin-top:9px}.activity{border-top:1px solid #2b414e;margin-top:14px;padding-top:12px}.activity .section-head{margin:0 0 7px}.logs{list-style:none;padding:0;margin:0;max-height:130px;overflow:auto}.logs li{padding:6px 0;border-top:1px solid #223c48;font-size:10px;display:grid;grid-template-columns:1fr auto;gap:2px 7px}.logs li:first-child{border:0}.log-target{overflow-wrap:anywhere;white-space:pre-wrap;color:#c9dee9}.log-time{color:#7f9baa}.log-state{grid-column:1/-1;color:#9bb6c6}.logs .empty{display:block} :host([hidden]),[hidden]{display:none!important}@media(max-width:450px){:host{right:8px;bottom:8px;width:calc(100vw - 16px)}.panel{max-height:calc(100dvh - 16px)}} `; function node(tag, className = '', text = '') { const element = document.createElement(tag); if (className) element.className = className; if (text) element.textContent = text; return element; } function text(element, value) { const next = String(value == null ? '' : value); if (element.textContent !== next) element.textContent = next; } function button(label, className, handler) { const element = node('button', className, label); element.type = 'button'; element.addEventListener('click', handler); return element; } function option(value, label) { const element = node('option', '', label); element.value = value; return element; } function normalizeRules(rules) { if (!Array.isArray(rules) || rules.length > MAX_RULES) throw new Error('대상은 최대 100명까지 설정할 수 있습니다.'); const seen = new Set(); return rules.map(rule => { const targetId = String(rule.targetId || '').trim(); if (!ID.test(targetId)) throw new Error('아이디는 영문 소문자·숫자·밑줄 2~32자로 입력해 주세요. 접속 번호 (2) 등은 제외합니다.'); if (seen.has(targetId)) throw new Error('같은 아이디는 한 번만 등록해 주세요.'); seen.add(targetId); if (!['mute', 'kick'].includes(rule.action)) throw new Error('채팅금지 또는 강퇴를 선택해 주세요.'); const autoCancel = rule.action === 'kick' && rule.autoCancel === true; const seconds = Number(rule.cancelDelaySeconds); const muteCount = Number(rule.muteCount ?? 1); if (!Number.isSafeInteger(muteCount) || muteCount < 1) throw new Error('채금 횟수는 1 이상의 정수로 입력해 주세요.'); if (autoCancel && (!Number.isInteger(seconds) || seconds < 0 || seconds > 300)) { throw new Error('강퇴 취소 대기 시간은 0~300초의 정수로 입력해 주세요.'); } const autoCancelBlindKick = rule.autoCancelBlindKick === true; const repeatMute = rule.action === 'mute' && rule.repeatMute === true; const blindSeconds = Number(rule.blindCancelDelaySeconds ?? 1); if (autoCancelBlindKick && (!Number.isInteger(blindSeconds) || blindSeconds < 0 || blindSeconds > 300)) throw new Error('블라인드 강퇴 취소 대기 시간은 0~300초의 정수로 입력해 주세요.'); return {targetId, action:rule.action, enabled:rule.enabled !== false, autoCancel, muteCount, repeatMute, autoCancelBlindKick, blindCancelDelaySeconds:Number.isInteger(blindSeconds) && blindSeconds >= 0 && blindSeconds <= 300 ? blindSeconds : 1, cancelDelaySeconds:Number.isInteger(seconds) && seconds >= 0 && seconds <= 300 ? seconds : 10}; }); } function actionSummary(action, forFile = false) { let result = REASONS[action.state] || REASONS[action.type] || '상태 확인 중'; if (REASONS[action.reason] && REASONS[action.reason] !== result) result += ` · ${REASONS[action.reason]}`; if (action.action === 'mute' && Number.isInteger(action.muteRequested)) { result += ` · ${action.muteConfirmed || 0}/${action.muteRequested}회 확인`; if (Number.isInteger(action.muteServerCount)) result += ' · ' + (action.muteServerCount >= 3 ? '블라인드 응답' : `서버 누적 ${action.muteServerCount}회`); } if (action.repeatState) { const label = action.repeatState === 'waiting_timer' ? (forFile ? '다음 채금 대기' : `다음 채금까지 ${Math.max(0,Math.ceil((action.repeatAt-Date.now())/1000))}초`) : {waiting_blind:'블라인드 해제 신호 대기',queued:'다음 채금 대기',sent:'다음 채금 실행',stopped:'자동 반복 중지'}[action.repeatState]; if (label) result += ` · ${label}`; if (action.repeatState === 'stopped' && REASONS[action.repeatReason]) result += ` · ${REASONS[action.repeatReason]}`; } if (action.cancelState) { result += ' · ' + ({scheduled:'강퇴 취소 대기',requested:'강퇴 취소 요청',confirmed:'강퇴 취소 확인',unknown:'취소 결과 미확인',aborted:'자동 취소 중지'}[action.cancelState] || '취소 상태 확인 중'); if (REASONS[action.cancelReason] && !['cancel_requested','cancel_confirmed'].includes(action.cancelReason)) result += ` · ${REASONS[action.cancelReason]}`; } return result; } function logTime(value) { const date = new Date(value); return Number.isFinite(date.getTime()) ? new Intl.DateTimeFormat('sv-SE', {timeZone:'Asia/Seoul', year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit',hourCycle:'h23'}).format(date) + '.' + String(date.getMilliseconds()).padStart(3,'0') : '시각 미확인'; } const logText = value => String(value ?? '').replace(/[\u0000-\u001f\u007f]/g,' '); function formatLogRecord(row) { const id = logText(row.targetId || row.target_id || '아이디 미확인'); const nick = logText(row.nick); const action = {mute:'채팅금지',kick:'강퇴',blind_kick:'블라인드 강퇴'}[row.action] || '처리'; return `[${logTime(row.updatedAt ?? row.at)} KST] ${nick ? `${nick} (${id})` : id} · ${action}\r\n` + `방송: ${logText(row.bjId)}${row.bno ? ` / ${logText(row.bno)}` : ''} · 실행 계정: ${logText(row.accountId)} · 시작: ${logTime(row.at)}\r\n` + `결과: ${actionSummary(row,true)}\r\n\r\n`; } function formatLogFile(records, version) { return '\ufeffSOOP 자동 관리 실행 로그\r\n' + `저장: ${logTime(Date.now())} KST\r\n` + `버전: ${logText(version)} · ${records.length}건\r\n\r\n` + records.map(formatLogRecord).join(''); } function mountPanel({engine, getStatus, getTargetNames, getSavedLogs, chooseLogDirectory, onClose, initialRules = []} = {}) { if (!engine || typeof engine.start !== 'function' || typeof engine.stop !== 'function' || typeof getStatus !== 'function') { throw new Error('자동 관리 실행기와 상태 조회 함수가 필요합니다.'); } if (mounted) { mounted.focus(); return mounted; } const host = node('div'); host.id = 'soop-auto-manager-panel'; const shadow = host.attachShadow({mode:'open'}); const style = node('style'); style.textContent = CSS; const panel = node('section', 'panel'); panel.setAttribute('aria-label', 'SOOP 자동 관리'); const header = node('header'); header.title = '헤더를 드래그하여 패널 이동'; const heading = node('div'); const versionText = node('p', '', '현재 로그인 계정 · 현재 방송'); heading.append(node('h1', '', 'SOOP 자동 관리'), versionText); const closeButton = button('×', 'close', () => hide()); closeButton.setAttribute('aria-label', '패널 숨기기'); closeButton.title = '패널 숨기기 · 자동 관리는 계속 실행'; header.append(heading, closeButton); const body = node('div', 'body'); const scopeCard = node('section', 'scope'); const scopeHead = node('div', 'scope-head'); const roomText = node('div', 'room', '방송 확인 중'); const phaseText = node('span', 'phase', '중지 상태'); scopeHead.append(roomText, phaseText); const accountText = node('p', 'account', '로그인 계정 확인 중'); const roleText = node('p', 'role', '방송 권한 미확인'); const scopeNote = node('p', 'hint scope-note', '현재 방송의 BJ 또는 매니저 권한을 확인합니다.'); scopeCard.append(scopeHead, accountText, roleText, scopeNote); const rulesHeading = node('div', 'section-head'); const countText = node('span', 'count', '0명'); const rulesTitle = node('h2', '', 'BJ별 등록 목록'); rulesHeading.append(rulesTitle, countText); const rulesContainer = node('div', 'rules'); const draft = node('div', 'draft'); const draftLabel = node('label', '', '대상 추가 · 한 줄에 아이디 하나씩'); const draftInput = node('textarea'); draftInput.rows = 2; draftInput.maxLength = 3400; draftInput.placeholder = '기본 아이디를 입력해 주세요'; draftInput.spellcheck = false; draftLabel.append(draftInput); const draftBottom = node('div', 'draft-bottom'); const draftAction = node('select'); draftAction.setAttribute('aria-label', '추가할 대상의 실행 종류'); draftAction.append(option('kick', '강퇴'), option('mute', '채팅금지')); const addButton = button('대상 추가', 'secondary', addTargets); draftBottom.append(draftAction, addButton); draft.append(draftLabel, draftBottom); const saveRow = node('div', 'section-head'); const settingsNote = node('span', 'hint', '목록과 설정만 이 브라우저에 저장'); const saveButton = button('설정 저장', 'secondary', save); saveRow.append(settingsNote, saveButton); const noticeText = node('p', 'notice'); noticeText.hidden = true; noticeText.setAttribute('role', 'status'); noticeText.setAttribute('aria-live', 'polite'); const controls = node('div', 'controls'); const startButton = button('이 방송에서 시작', 'start', start); const stopButton = button('중지', 'stop', stop); controls.append(startButton, stopButton); const sessionNote = node('p', 'hint session-note', '설정을 불러와도 자동으로 시작하지 않습니다. 계정·방송·권한이 바뀌면 중지됩니다.'); const activity = node('section', 'activity'); const activityHead = node('div', 'section-head'); const pendingText = node('span', 'count'); const logDownload = button('로그 내려받기', 'secondary', downloadLogs); const logFolder = button('자동 저장 폴더', 'secondary', selectLogDirectory); logFolder.title = '폴더를 선택하면 로그 파일을 자동으로 저장합니다.'; const logControls = node('div','controls'); logControls.style.marginTop = '7px'; logControls.append(logDownload,logFolder); const logSaveStatus = node('p','hint'); logSaveStatus.style.marginTop = '7px'; activityHead.append(node('h2', '', '최근 실행'), pendingText); const logs = node('ul', 'logs'); activity.append(activityHead, logs, logControls, logSaveStatus); body.append(scopeCard, rulesHeading, rulesContainer, draft, saveRow, noticeText, controls, sessionNote, activity); panel.append(header, body); shadow.append(style, panel); (document.body || document.documentElement).append(host); let status = null; let ownerKey = ''; let initialOwner = ''; let rows = []; let dirty = false; let busy = false; let refreshing = false; let closed = false; let hidden = false; let timer = null; let position = null; let drag = null; let logSignature = ''; let downloading = false, choosingDirectory = false; function notify(message = '', error = false) { text(noticeText, message); noticeText.hidden = !message; noticeText.dataset.error = String(error); } function owner(value) { return value && value.settingsScopeVerified !== false && ID.test(value.accountId || '') && ID.test(value.bjId || '') ? `${value.accountId}:${value.bjId}` : ''; } function scope(value) { return value ? [value.accountId, value.bjId, value.bno].join(':') : ''; } function authorized(value) { return Boolean(owner(value) && value.connected === true && ['bj','manager'].includes(value.role) && /^[1-9][0-9]{0,19}$/.test(String(value.bno || ''))); } function running() { return Boolean(status && (status.enabled === true || status.running === true)); } function readRules() { return normalizeRules(rows.map(row => ({targetId:row.target.value, action:row.action.value, enabled:row.enabled.checked, autoCancel:row.cancel.checked, cancelDelaySeconds:row.delay.value, muteCount:row.muteCount.value, repeatMute:row.repeatMute.checked, autoCancelBlindKick:row.blindCancel.checked, blindCancelDelaySeconds:row.blindDelay.value}))); } function updateButtons() { const active = running(); const locked = busy || active || !owner(status); let valid = true; try { readRules(); } catch (_) { valid = false; } startButton.disabled = busy || active || !authorized(status) || !valid || !rows.length; stopButton.disabled = busy || (!active && status !== null); saveButton.disabled = locked || !owner(status) || !valid || !dirty; addButton.disabled = locked || rows.length >= MAX_RULES || !draftInput.value.trim(); draftInput.disabled = locked; draftAction.disabled = locked; for (const row of rows) { row.enabled.disabled = busy || !owner(status) || (active && !authorized(status)); row.enabled.setAttribute('aria-label', `${row.target.value} 자동 관리 ON/OFF`); text(row.enabledText,row.enabled.checked ? 'ON' : 'OFF'); row.enabledLabel.dataset.active = String(row.enabled.checked); row.target.disabled = locked; row.action.disabled = locked; row.cancel.disabled = locked || row.action.value !== 'kick'; row.delay.disabled = locked; row.remove.disabled = locked; row.cancelRow.hidden = row.action.value !== 'kick'; row.muteCount.disabled = locked; row.muteRow.hidden = row.action.value !== 'mute'; row.repeatMute.disabled = locked || row.action.value !== 'mute'; row.repeatRow.hidden = row.action.value !== 'mute'; row.blindCancel.disabled = locked; row.blindDelay.disabled = locked; } text(countText, owner(status) ? `${rows.length}명 · ON ${rows.filter(row=>row.enabled.checked).length}명` : '방송 확인 중'); text(settingsNote, !owner(status) ? '로그인 계정과 BJ를 확인한 뒤 목록을 표시합니다.' : active ? '수정하려면 먼저 중지해 주세요.' : dirty ? '저장하지 않은 변경 사항이 있습니다.' : '이 계정·BJ의 목록과 설정만 이 브라우저에 저장'); logDownload.disabled = downloading || !(Number(status?.logStore?.count) > 0 || status?.actions?.length); logFolder.disabled = choosingDirectory || typeof chooseLogDirectory !== 'function' || status?.fileLog?.supported === false; } function renderTargetNames() { let names = null; try { if (typeof getTargetNames === 'function') names = getTargetNames(rows.map(row => row.target.value.trim())); } catch (_) {} for (const row of rows) { const id = row.target.value.trim(); const name = names && Object.prototype.hasOwnProperty.call(names,id) ? names[id] : null; const nickname = name && typeof name.nickname === 'string' && name.nickname.length <= 512 ? name.nickname : ''; const pending = !nickname && name?.state === 'loading'; const failed = !nickname && name?.state === 'error'; text(row.nickname,nickname || (pending ? '닉네임 확인 중…' : failed ? '닉네임 확인 실패' : '')); row.nickname.hidden = !nickname && !pending && !failed; row.nickname.title = nickname ? (name.source === 'station' ? '원닉 · 방송국 조회' : name.present ? '이 방송 닉네임' : '마지막으로 확인한 방송 닉네임') : ''; } } function changed() { dirty = true; notify(); updateButtons(); renderTargetNames(); } function renderRows(rules) { rulesContainer.replaceChildren(); rows = []; if (!rules.length) rulesContainer.append(node('p', 'empty', '아래에 관리할 대상 아이디를 추가해 주세요.')); for (const rule of rules) { const element = node('div', 'rule'); const first = node('div', 'row'); const enabledLabel = node('label','target-toggle'); const enabled = node('input','target-enabled'); enabled.type='checkbox'; enabled.checked = rule.enabled !== false; const enabledText = node('span','',enabled.checked ? 'ON' : 'OFF'); enabledLabel.title = 'ON: 해당 유저 적용\nOFF: 해당 유저만 중지'; enabledLabel.append(enabled,enabledText); const target = node('input', 'target'); target.type = 'text'; target.maxLength = 32; target.value = rule.targetId; target.spellcheck = false; target.setAttribute('aria-label', '대상 기본 아이디'); const identity = node('div','target-identity'); const nickname = node('span','target-nick'); nickname.hidden = true; identity.append(nickname,target); const action = node('select'); action.setAttribute('aria-label', '실행 종류'); action.append(option('kick', '강퇴'), option('mute', '채팅금지')); action.value = rule.action; const remove = button('×', 'remove', () => { const index = rows.indexOf(row); rows.splice(index, 1); element.remove(); if (!rows.length) rulesContainer.append(node('p', 'empty', '아래에 관리할 대상 아이디를 추가해 주세요.')); changed(); }); remove.setAttribute('aria-label', '이 대상 삭제'); first.append(enabledLabel, identity, action, remove); const cancelRow = node('div', 'row'); const cancelLabel = node('label', 'cancel-label'); const cancel = node('input'); cancel.type = 'checkbox'; cancel.checked = rule.autoCancel; const delay = node('input', 'delay'); delay.type = 'number'; delay.min = '0'; delay.max = '300'; delay.step = '1'; delay.value = String(rule.cancelDelaySeconds); delay.setAttribute('aria-label', '강퇴 취소까지 대기 시간, 초'); cancelLabel.append(cancel, node('span', '', '강퇴 확인 후'), delay, node('span', '', '초 뒤 강퇴 취소 · 0초는 즉시')); cancelRow.append(cancelLabel); const muteRow = node('div', 'row mute-row'); const muteLabel = node('label', 'cancel-label'); const muteCount = node('input', 'delay mute-count'); muteCount.type = 'number'; muteCount.min = '1'; muteCount.step = '1'; muteCount.value = String(rule.muteCount ?? 1); muteCount.setAttribute('aria-label', '이번 입장에 적용할 채금 횟수'); muteLabel.append(node('span', '', '채금 횟수'), muteCount, node('span', '', '회')); muteRow.append(muteLabel); const repeatRow = node('div', 'row repeat-row'); const repeatLabel = node('label', 'cancel-label'); const repeatMute = node('input'); repeatMute.type = 'checkbox'; repeatMute.checked = rule.repeatMute === true; repeatMute.setAttribute('aria-label', '자동 연속 채금'); const repeatDescription = '채금 시간이 끝나면 자동으로 반복합니다.\n블라인드도 해제되면 다시 적용합니다.'; repeatLabel.title = repeatDescription; repeatMute.title = repeatDescription; const repeatInfo = node('span', 'hint repeat-info', 'ⓘ'); repeatInfo.title = repeatDescription; repeatInfo.style.cursor = 'help'; repeatLabel.append(repeatMute, node('span', '', '자동 연속 채금'), repeatInfo); repeatRow.append(repeatLabel); repeatRow.style.flexWrap = 'wrap'; const blindRow = node('div', 'row'); const blindLabel = node('label', 'cancel-label'); const blindCancel = node('input'); blindCancel.type = 'checkbox'; blindCancel.checked = rule.autoCancelBlindKick === true; blindCancel.setAttribute('aria-label', '블라인드 강퇴 자동 취소'); const blindDescription = '블라인드 상태에서 퇴장해 발생한 강퇴를 취소합니다. 블라인드 자체를 해제하는 옵션은 아닙니다.'; blindLabel.title = blindDescription; blindCancel.title = blindDescription; const blindDelay = node('input', 'delay'); blindDelay.type = 'number'; blindDelay.min = '0'; blindDelay.max = '300'; blindDelay.step = '1'; blindDelay.value = String(rule.blindCancelDelaySeconds ?? 1); blindDelay.setAttribute('aria-label', '블라인드 강퇴 취소까지 대기 시간, 초'); blindLabel.append(blindCancel, node('span', '', '블라인드로 인한 강퇴 시'), blindDelay, node('span', '', '초 뒤 강퇴 자동 취소 · 0초는 즉시')); blindRow.append(blindLabel); element.append(first, cancelRow, muteRow, repeatRow, blindRow); rulesContainer.append(element); const row = {element,target,nickname,enabled,enabledLabel,enabledText,action,remove,cancelRow,cancel,delay,muteRow,muteCount,repeatRow,repeatMute,blindCancel,blindDelay}; rows.push(row); enabled.addEventListener('change', () => toggleTarget(row)); target.addEventListener('input', changed); delay.addEventListener('input', changed); muteCount.addEventListener('input', changed); repeatMute.addEventListener('change', changed); blindCancel.addEventListener('change', changed); blindDelay.addEventListener('input', changed); cancel.addEventListener('change', changed); action.addEventListener('change', () => { if (action.value !== 'kick') cancel.checked = false; if (action.value !== 'mute') repeatMute.checked = false; changed(); }); } updateButtons(); renderTargetNames(); } async function toggleTarget(row) { const next = row.enabled.checked, previous = !next, previousScope = scope(status), previousOwner = ownerKey; if (closed || busy) { row.enabled.checked=previous; return; } let rollbackRules = null, saved = false; busy=true;updateButtons(); try { const fresh=await getStatus(); if (closed) return; if (ownerKey!==previousOwner || scope(status)!==previousScope || !owner(status) || !rows.includes(row)) throw new Error('현재 로그인 계정과 방송을 확인해 주세요.'); if (!owner(fresh) || scope(fresh)!==previousScope) { adopt(fresh); throw new Error('현재 로그인 계정과 방송을 확인해 주세요.'); } const active = fresh.enabled === true || fresh.running === true; // Editing a saved rule sends no moderation command. Only changes to // an active engine need the current room's moderation authority. if (active && !authorized(fresh)) throw new Error('현재 방송의 로그인·관리 권한을 확인해 주세요.'); const rules=readRules(); rollbackRules=rules.map(rule=>rule.targetId===row.target.value ? {...rule,enabled:previous} : rule); persist(rules,previousOwner);saved=true; if (active) { if (typeof engine.setTargetEnabled!=='function') throw new Error('유저별 ON/OFF를 지원하는 최신 버전을 실행해 주세요.'); const result=await engine.setTargetEnabled(row.target.value,next); if (!result || result.ok!==true) throw new Error(REASONS[result?.reason] || '해당 유저의 설정을 적용하지 못했습니다.'); } if (closed || ownerKey!==previousOwner || !rows.includes(row)) return; dirty=false;notify(`${row.target.value} 자동 관리 ${next ? 'ON' : 'OFF'}`); try { adopt(await getStatus()); } catch (_) { /* Applied state remains authoritative if display refresh fails. */ } } catch(error) { row.enabled.checked=previous; if(saved && rollbackRules) try {writeSettings(previousOwner,rollbackRules);} catch(_) {} notify(error.message || '유저별 설정을 변경하지 못했습니다.',true); } finally {busy=false;updateButtons();} } function addTargets() { if (busy || running() || !owner(status)) return; try { const targets = draftInput.value.trim().split(/[\s,]+/).filter(Boolean); if (!targets.length) return; const rules = normalizeRules([...readRules(), ...targets.map(targetId => ({targetId, action:draftAction.value, autoCancel:false, cancelDelaySeconds:10}))]); renderRows(rules); draftInput.value = ''; changed(); } catch (error) { notify(error.message, true); } } function loadSettings(nextOwner) { if (!initialOwner) initialOwner = nextOwner; let rules = []; try { const raw = global.localStorage.getItem(STORAGE_PREFIX + nextOwner); if (raw !== null) { const stored = JSON.parse(raw); if (!stored || stored.version !== 1) throw new Error('invalid_storage'); rules = normalizeRules(stored.rules); } else if (nextOwner === initialOwner) { rules = normalizeRules(typeof initialRules === 'function' ? initialRules(status) : initialRules); } } catch (_) { notify('저장된 설정을 불러오지 못했습니다. 대상을 다시 확인해 주세요.', true); } ownerKey = nextOwner; dirty = false; draftInput.value = ''; renderRows(rules); } function writeSettings(key, rules) { global.localStorage.setItem(STORAGE_PREFIX + key, JSON.stringify({version:1,rules,updatedAt:Date.now()})); } function persist(rules, expectedOwner = ownerKey) { const key = owner(status); if (!key || key !== ownerKey || key !== expectedOwner) throw new Error('현재 로그인 계정과 방송을 확인해 주세요.'); writeSettings(key, rules); dirty = false; } async function save() { if (closed || busy || running()) return; const previousScope = scope(status), previousOwner = ownerKey; busy = true; updateButtons(); try { const rules = readRules(), fresh = await getStatus(); if (closed) return; if (ownerKey !== previousOwner || scope(status) !== previousScope || !owner(status)) throw new Error('현재 로그인 계정과 방송을 확인해 주세요.'); if (!owner(fresh) || scope(fresh) !== previousScope) { adopt(fresh); throw new Error('현재 로그인 계정과 방송을 확인해 주세요.'); } adopt(fresh); persist(rules, previousOwner); notify('이 계정·BJ의 설정을 저장했습니다. 실행은 직접 시작해 주세요.'); } catch (error) { notify(error.message === '현재 로그인 계정과 방송을 확인해 주세요.' ? error.message : '설정 저장에 실패했습니다. 입력값과 브라우저 저장 권한을 확인해 주세요.', true); } finally { busy = false; if (!closed) updateButtons(); } } function renderLog() { const actions = Array.isArray(status && status.actions) ? status.actions.slice(-8) : []; const pending = status && status.pending; const count = Array.isArray(pending) ? pending.length : Number.isInteger(pending) ? pending : 0; text(pendingText, count > 0 ? `취소 대기 ${count}건` : '현재 페이지'); const countdown = actions.map(action => action.repeatState === 'waiting_timer' && Number.isFinite(action.repeatAt) ? Math.max(0, Math.ceil((action.repeatAt-Date.now())/1000)) : null); const signature = JSON.stringify([actions,countdown]); if (signature === logSignature) return; logSignature = signature; logs.replaceChildren(); if (!actions.length) logs.append(node('li', 'empty', '아직 실행 기록이 없습니다.')); for (const action of actions.slice().reverse()) { if (!action || typeof action !== 'object') continue; const item = node('li'); const targetId = String(action.targetId || action.target_id || '대상 확인 중'); const nickname = typeof action.nick === 'string' && action.nick.trim() ? action.nick : ''; const target = node('span', 'log-target', nickname ? `${nickname} (${targetId})` : targetId); const rawAt = action.at; const date = new Date(typeof rawAt === 'number' && rawAt < 1e12 ? rawAt*1000 : rawAt); const time = node('span', 'log-time', Number.isFinite(date.getTime()) ? date.toLocaleTimeString('ko-KR', {hour12:false}) : ''); const state = node('span', 'log-state', actionSummary(action)); item.append(target, time, state); logs.append(item); } } function adopt(next) { status = next && typeof next === 'object' ? next : null; text(versionText, `현재 로그인 계정 · 현재 방송${status && /^\d+\.\d+\.\d+$/.test(status.version || '') ? ` · v${status.version}` : ''}`); const nextOwner = owner(status); if (nextOwner && nextOwner !== ownerKey) loadSettings(nextOwner); rulesContainer.hidden = !nextOwner; draft.hidden = !nextOwner; text(rulesTitle, nextOwner ? `${status.bjId} · 등록 목록` : 'BJ별 등록 목록'); text(roomText, nextOwner ? status.bjId : '방송 확인 필요'); text(accountText, `로그인 계정 · ${status && status.accountId ? status.accountId : '미확인'}`); const knownRole = status && {bj:'BJ 권한', manager:'매니저 권한'}[status.role]; const roleLabel = knownRole ? `${knownRole}${authorized(status) ? ' 확인' : ' · 연결 재확인 필요'}` : status && status.role === 'none' ? '일반 시청자 · 관리 권한 없음' : '연결·로그인 확인 필요'; text(roleText, roleLabel); text(phaseText, running() ? '실행 중' : authorized(status) ? '중지 상태' : knownRole ? '연결 확인 필요' : '권한 확인 필요'); phaseText.dataset.active = String(running()); text(scopeNote, running() ? '이미 있는 등록 대상과 새로 입장하는 대상에게 설정한 동작을 실행합니다.' : REASONS[status && status.reason] || (authorized(status) ? '설정한 내용을 확인한 뒤 직접 시작해 주세요.' : knownRole ? '관리 권한은 확인했으며 현재 방송 연결을 다시 확인해야 합니다.' : '현재 방송의 BJ 또는 매니저 권한을 확인합니다.')); const saved = status?.logStore; const browserSave = saved?.state === 'error' || saved?.state === 'unavailable' ? '브라우저 로그 저장 실패' : saved?.state === 'saving' ? '브라우저에 로그 저장 중' : saved ? `브라우저 자동 저장 · ${saved.count || 0}건` : ''; const fileSave = status?.fileLog?.message || ''; text(logSaveStatus,[browserSave,fileSave].filter(Boolean).join(' · ')); renderTargetNames(); renderLog(); updateButtons(); } async function downloadLogs() { if (downloading || closed) return; downloading = true; updateButtons(); let link, objectUrl; try { const result = typeof getSavedLogs === 'function' ? await getSavedLogs() : status?.actions || []; const records = Array.isArray(result) ? result : result?.records; if (!Array.isArray(records) || !records.length) throw new Error('empty'); const blob = new global.Blob([formatLogFile(records,status?.version)],{type:'text/plain;charset=utf-8'}); objectUrl = global.URL.createObjectURL(blob); link = node('a'); link.href = objectUrl; link.download = `SOOP-자동관리-${logTime(Date.now()).replace(/[^0-9]/g,'').slice(0,14)}.txt`; link.hidden = true; (document.body || document.documentElement).append(link); link.click(); notify(result?.warning || '로그 파일 다운로드를 시작했습니다.'); } catch (error) { notify(error.message === 'empty' ? '저장할 실행 로그가 없습니다.' : '로그를 내려받지 못했습니다. 다시 시도해 주세요.',true); } finally { link?.remove(); if (objectUrl) global.setTimeout(()=>global.URL.revokeObjectURL(objectUrl),1000); downloading = false; if (!closed) updateButtons(); } } async function selectLogDirectory() { if (choosingDirectory || closed || typeof chooseLogDirectory !== 'function') return; choosingDirectory = true; updateButtons(); try { await chooseLogDirectory(); await refresh(); } catch (_) { notify('자동 저장 폴더를 선택하지 못했습니다.',true); } finally { choosingDirectory = false; if (!closed) updateButtons(); } } async function refresh() { if (closed || hidden || refreshing || busy) return; refreshing = true; try { const next = await getStatus(); if (!closed && !hidden) adopt(next); } catch (_) { if (!closed && !hidden) adopt(null); } finally { refreshing = false; } } async function start() { if (closed || busy || running()) return; const previousScope = scope(status), previousOwner = ownerKey; busy = true; updateButtons(); try { const rules = readRules(); if (!rules.length) throw new Error('대상 아이디를 추가해 주세요.'); const fresh = await getStatus(); if (closed) return; if (ownerKey !== previousOwner || scope(status) !== previousScope || !owner(status)) throw new Error('계정·방송·권한이 변경되었습니다. 현재 상태를 확인한 뒤 다시 시작해 주세요.'); if (!authorized(fresh) || scope(fresh) !== previousScope) { adopt(fresh); throw new Error('계정·방송·권한이 변경되었습니다. 현재 상태를 확인한 뒤 다시 시작해 주세요.'); } if (rules.some(rule => rule.targetId === fresh.accountId || rule.targetId === fresh.bjId)) { throw new Error('로그인 계정과 BJ는 자동 관리 대상으로 지정할 수 없습니다.'); } adopt(fresh); persist(rules, previousOwner); const result = await engine.start(rules); if (closed) { await engine.stop('panel_closed'); return; } if (!result || result.ok !== true) throw new Error(REASONS[result && result.reason] || '시작하지 못했습니다. 현재 방송의 로그인과 권한을 확인해 주세요.'); adopt(await getStatus()); notify('이 계정의 현재 방송에서 자동 관리를 시작했습니다.'); } catch (error) { if (!closed) notify(error.message || '자동 관리를 시작하지 못했습니다.', true); } finally { busy = false; if (!closed) updateButtons(); } } async function stop() { if (closed || busy) return; busy = true; updateButtons(); try { await engine.stop('user_stop'); adopt(await getStatus()); notify('자동 관리를 중지했습니다.'); } catch (_) { notify('중지 상태를 확인하지 못했습니다. 방송 페이지에서 상태를 확인해 주세요.', true); } finally { busy = false; if (!closed) updateButtons(); } } function stopPolling() { if (timer !== null) { global.clearInterval(timer); timer = null; } } function startPolling() { if (!closed && !hidden && timer === null) timer = global.setInterval(refresh, 1000); } function applyPosition(left, top) { const rect = host.getBoundingClientRect(); const width = global.innerWidth || document.documentElement.clientWidth; const height = global.innerHeight || document.documentElement.clientHeight; const margin = 8; position = {left:Math.min(Math.max(margin, left), Math.max(margin, width - rect.width - margin)), top:Math.min(Math.max(margin, top), Math.max(margin, height - rect.height - margin))}; host.style.left = `${position.left}px`; host.style.top = `${position.top}px`; host.style.right = 'auto'; host.style.bottom = 'auto'; } function clampPosition() { if (!closed && !hidden && position) applyPosition(position.left, position.top); } function endDrag(event) { if (!drag || (event && event.pointerId !== drag.pointerId)) return; const pointerId = drag.pointerId; drag = null; header.dataset.dragging = 'false'; try { if (header.hasPointerCapture(pointerId)) header.releasePointerCapture(pointerId); } catch (_) {} } header.addEventListener('pointerdown', event => { if (closed || hidden || drag || event.isPrimary === false || event.button !== 0 || event.target.closest?.('button,input,select,textarea,a,[role="button"]') || !Number.isFinite(event.clientX) || !Number.isFinite(event.clientY)) return; const rect = host.getBoundingClientRect(); drag = {pointerId:event.pointerId, x:event.clientX, y:event.clientY, left:rect.left, top:rect.top}; header.dataset.dragging = 'true'; try { header.setPointerCapture(event.pointerId); } catch (_) {} event.preventDefault(); }); header.addEventListener('pointermove', event => { if (!drag || event.pointerId !== drag.pointerId) return; applyPosition(drag.left + event.clientX - drag.x, drag.top + event.clientY - drag.y); event.preventDefault(); }); for (const eventName of ['pointerup', 'pointercancel', 'lostpointercapture']) { header.addEventListener(eventName, endDrag); } global.addEventListener('resize', clampPosition); function hideOnOutsidePointer(event) { if (closed || hidden || drag || event.isPrimary === false || event.button !== 0) return; const path = typeof event.composedPath === 'function' ? event.composedPath() : []; if (path.includes(host) || event.target === host || host.contains?.(event.target)) return; hide(); } global.addEventListener('pointerdown', hideOnOutsidePointer, true); // Outside this shadow root, shortcut handlers see the DIV host rather than // the focused input. Window capture precedes SOOPKIT's document capture. // Keep browser editing, clipboard, IME and focus defaults intact. // Custom key handlers added inside the panel must be routed here as well. function isolatePanelKeyboard(event) { if (closed || hidden) return; const path = typeof event.composedPath === 'function' ? event.composedPath() : []; if (path.includes(host) || event.target === host || host.contains?.(event.target)) { event.stopImmediatePropagation(); } } const keyboardEvents = ['keydown', 'keypress', 'keyup']; for (const name of keyboardEvents) global.addEventListener(name, isolatePanelKeyboard, true); function hide() { if (closed || hidden) return; hidden = true; endDrag(); stopPolling(); host.hidden = true; } function show() { if (closed) return; hidden = false; host.hidden = false; clampPosition(); startPolling(); return refresh(); } function close() { if (closed) return; closed = true; endDrag(); stopPolling(); global.removeEventListener('resize', clampPosition); global.removeEventListener('pointerdown', hideOnOutsidePointer, true); for (const name of keyboardEvents) global.removeEventListener(name, isolatePanelKeyboard, true); try { engine.stop('panel_closed'); } finally { host.remove(); mounted = null; if (typeof onClose === 'function') onClose(); } } draftInput.addEventListener('input', updateButtons); mounted = {close, hide, show, refresh, acceptStatus(next) { if (!closed) adopt(next); }, focus() { show(); closeButton.focus(); }, element:host}; renderRows([]); startPolling(); refresh(); return mounted; } global.SoopAutoManagerPanel = Object.freeze({mountPanel,formatLogRecord,formatLogFile}); })(globalThis);