Added lite versions

This commit is contained in:
nyan404 committed 2025-11-06 14:04:02 +03:00
1 parent 4a18a18aae
commit fff03bf0d4
3 files changed
+567

No files matched your search

+357
View File
@@ -0,0 +1,357 @@
// ==UserScript==
// @name CW: Shed Lite
// @version 0.3
// @description Облегчённая версия CW:Shed — базовые уведомления без тяжёлых наблюдателей
// @author Tis & Lite maintainers
// @license MIT; https://opensource.org/licenses/MIT
// @match *://catwar.net/*
// @match *://catwar.su/*
// ==/UserScript==
(function (window, document) {
'use strict';
/**
* Настройки можно менять из консоли:
* window.CWShedLite.set('smellTimer', false)
* window.CWShedLite.set('actionAlertThreshold', 2)
*/
const STORAGE_KEY = 'cwshed-lite';
const SMELL_STORAGE_KEY = 'cwshed-lite-smell-end';
const defaults = {
smellTimer: true,
smellTimerSound: 'https://cat.nyan404.ru/data/action_end.mp3',
smellTimerVolume: 0.25,
actionAlert: true,
actionAlertTitle: true,
actionAlertThreshold: 1,
actionAlertSound: 'https://cat.nyan404.ru/data/action_end.mp3',
actionAlertVolume: 0.2,
showDmId: true
};
const smellDurations = {
'0': 3600,
'1': 3600,
'2': 3600,
'3': 3600,
'4': 1800,
'5': 1200,
'6': 900,
'7': 720,
'8': 600,
'9': 0
};
const settings = Object.assign({}, defaults, loadSettings());
let smellTimerHandle = null;
let smellClickHandler = null;
let actionIntervalHandle = null;
let storedTitle = document.title;
let lastActionAlert = 0;
let actionListenersAttached = false;
document.addEventListener('DOMContentLoaded', init, { once: true });
window.CWShedLite = {
get(key) {
return settings[key];
},
set(key, value) {
settings[key] = value;
saveSettings(settings);
if (key.startsWith('smellTimer')) restartSmellTimer();
if (key.startsWith('actionAlert')) restartActionWatcher();
if (key === 'showDmId') injectDmId(true);
return settings[key];
},
reset() {
Object.keys(defaults).forEach(function (key) {
settings[key] = defaults[key];
});
saveSettings(settings);
restartSmellTimer();
restartActionWatcher();
injectDmId(true);
}
};
function init() {
if (isGamePage()) {
if (settings.smellTimer) setupSmellTimer();
if (settings.actionAlert || settings.actionAlertTitle) setupActionWatcher();
}
if (isDmPage() && settings.showDmId) {
injectDmId();
}
}
function isGamePage() {
return /^\/cw3(\/(kns|jagd))?/.test(window.location.pathname);
}
function isDmPage() {
return /^\/ls/.test(window.location.pathname);
}
/**
* ---------------------
* Вспомогательные утилиты
* ---------------------
*/
function loadSettings() {
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return {};
const data = JSON.parse(raw);
return (data && typeof data === 'object') ? data : {};
} catch (err) {
console.warn('[CWShedLite] Настройки не загружены', err);
return {};
}
}
function saveSettings(value) {
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value));
} catch (err) {
console.warn('[CWShedLite] Настройки не сохранены', err);
}
}
function createAudio(src, volume) {
const audio = new Audio();
audio.preload = 'none';
audio.src = src;
audio.volume = volume;
return audio;
}
function parseSeconds(text) {
if (!text) return NaN;
const clean = text.replace(/\u00A0/g, ' ');
const hourMatch = clean.match(/(\d+)\s*ч/);
const minMatch = clean.match(/(\d+)\s*мин/);
const secMatch = clean.match(/(\d+)\s*с/);
let total = 0;
if (hourMatch) total += parseInt(hourMatch[1], 10) * 3600;
if (minMatch) total += parseInt(minMatch[1], 10) * 60;
if (secMatch) total += parseInt(secMatch[1], 10);
return total || NaN;
}
/**
* ---------------------
* Смелл-таймер
* ---------------------
*/
function setupSmellTimer() {
const menu = document.querySelector('#app > span.small, .small');
if (!menu || menu.querySelector('#cwshed-lite-smell')) return;
const label = document.createElement('span');
label.id = 'cwshed-lite-smell';
label.style.marginLeft = '8px';
label.textContent = 'Нюх: —';
menu.appendChild(document.createTextNode(' | '));
menu.appendChild(label);
if (smellClickHandler) {
document.removeEventListener('click', smellClickHandler, true);
}
smellClickHandler = function (event) {
const actionLink = event.target.closest('#dein a[data-id="14"], #actions a[data-id="14"]');
if (!actionLink) return;
const levelNode = document.querySelector('#smell b');
const level = levelNode ? levelNode.textContent.trim() : '';
const seconds = smellDurations[level] || smellDurations['0'];
if (!seconds) {
clearSmellTimer();
return;
}
startSmellTimer(seconds);
};
document.addEventListener('click', smellClickHandler, true);
const savedEnd = Number(window.localStorage.getItem(SMELL_STORAGE_KEY) || 0);
if (savedEnd > Date.now()) {
startSmellTimer(Math.floor((savedEnd - Date.now()) / 1000));
} else {
window.localStorage.removeItem(SMELL_STORAGE_KEY);
}
}
function startSmellTimer(seconds) {
const label = document.getElementById('cwshed-lite-smell');
if (!label) return;
const endTime = Date.now() + seconds * 1000;
window.localStorage.setItem(SMELL_STORAGE_KEY, String(endTime));
if (smellTimerHandle) window.clearInterval(smellTimerHandle);
const audio = settings.smellTimerSound ? createAudio(settings.smellTimerSound, settings.smellTimerVolume) : null;
const tick = function () {
const remaining = Math.max(0, Math.floor((endTime - Date.now()) / 1000));
if (remaining <= 0) {
label.textContent = 'Нюх: готово';
window.localStorage.removeItem(SMELL_STORAGE_KEY);
window.clearInterval(smellTimerHandle);
smellTimerHandle = null;
if (audio) {
audio.currentTime = 0;
void audio.play();
}
return;
}
label.textContent = 'Нюх: ' + formatTime(remaining);
};
tick();
smellTimerHandle = window.setInterval(tick, 1000);
}
function clearSmellTimer() {
if (smellTimerHandle) {
window.clearInterval(smellTimerHandle);
smellTimerHandle = null;
}
if (smellClickHandler) {
document.removeEventListener('click', smellClickHandler, true);
smellClickHandler = null;
}
window.localStorage.removeItem(SMELL_STORAGE_KEY);
const label = document.getElementById('cwshed-lite-smell');
if (label) label.textContent = 'Нюх: —';
}
function restartSmellTimer() {
clearSmellTimer();
if (settings.smellTimer && isGamePage()) {
setupSmellTimer();
}
}
function formatTime(totalSeconds) {
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const segments = [];
if (hours) segments.push(hours + ' ч');
if (minutes) segments.push(minutes + ' мин');
segments.push(seconds + ' с');
return segments.join(' ');
}
/**
* ---------------------
* Уведомление о конце действия
* ---------------------
*/
function setupActionWatcher() {
if (actionIntervalHandle) window.clearInterval(actionIntervalHandle);
const audio = (settings.actionAlert && settings.actionAlertSound)
? createAudio(settings.actionAlertSound, settings.actionAlertVolume)
: null;
if (!actionListenersAttached) {
window.addEventListener('focus', restoreTitle);
window.addEventListener('blur', function () {
storedTitle = storedTitle || document.title;
});
actionListenersAttached = true;
}
actionIntervalHandle = window.setInterval(function () {
const timerNode = document.querySelector('#sek');
if (!timerNode) {
restoreTitle();
lastActionAlert = 0;
return;
}
const secondsLeft = parseSeconds(timerNode.textContent);
if (Number.isNaN(secondsLeft)) return;
if (settings.actionAlertTitle) {
if (secondsLeft > 0) {
document.title = '(' + secondsLeft + ' с) CatWar';
} else {
restoreTitle();
}
}
if (settings.actionAlert && secondsLeft <= settings.actionAlertThreshold && secondsLeft >= 0) {
const now = Date.now();
if (now - lastActionAlert > 1500) {
lastActionAlert = now;
if (audio) {
audio.currentTime = 0;
void audio.play();
}
}
}
}, 1000);
}
function restoreTitle() {
if (storedTitle) {
document.title = storedTitle;
}
}
function restartActionWatcher() {
if (!isGamePage()) return;
if (actionIntervalHandle) {
window.clearInterval(actionIntervalHandle);
actionIntervalHandle = null;
}
if (settings.actionAlert || settings.actionAlertTitle) {
setupActionWatcher();
} else {
restoreTitle();
}
}
/**
* ---------------------
* ID собеседника в ЛС
* ---------------------
*/
function injectDmId(force) {
const container = document.getElementById('main');
if (!container) return;
const applyId = function () {
if (!settings.showDmId && !force) return;
const login = document.getElementById('msg_login');
if (!login) return;
const href = login.getAttribute('href') || '';
const match = href.match(/(\d+)/);
if (!match) return;
let badge = document.getElementById('cwshed-lite-dm-id');
if (!settings.showDmId) {
if (badge && badge.parentNode) badge.parentNode.removeChild(badge);
return;
}
if (!badge) {
badge = document.createElement('span');
badge.id = 'cwshed-lite-dm-id';
badge.style.marginLeft = '6px';
badge.style.fontSize = '12px';
badge.style.color = '#555';
login.insertAdjacentElement('afterend', badge);
}
badge.textContent = '[' + match[1] + ']';
};
applyId();
const observer = new MutationObserver(function () {
applyId();
});
observer.observe(container, { childList: true, subtree: true });
}
})(window, document);