192 lines
6.6 KiB
JavaScript
192 lines
6.6 KiB
JavaScript
// Инициализация при загрузке страницы
|
|
document.addEventListener('DOMContentLoaded', function () {
|
|
updateStatusIndicators();
|
|
});
|
|
|
|
// Обновление индикаторов статуса
|
|
function updateStatusIndicators() {
|
|
const vkStatus = document.getElementById('vkStatus');
|
|
const saveButton = document.getElementById('saveButton');
|
|
|
|
if (pageData && pageData.vk_settings) {
|
|
vkStatus.innerHTML = '<span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Настроено</span>';
|
|
saveButton.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i>Обновить настройки';
|
|
saveButton.classList.remove('btn-primary');
|
|
saveButton.classList.add('btn-outline-primary');
|
|
} else {
|
|
vkStatus.innerHTML = '<span class="badge bg-warning"><i class="bi bi-exclamation-triangle me-1"></i>Не настроено</span>';
|
|
saveButton.innerHTML = '<i class="bi bi-save me-1"></i>Сохранить настройки';
|
|
saveButton.classList.remove('btn-outline-primary');
|
|
saveButton.classList.add('btn-primary');
|
|
}
|
|
}
|
|
|
|
// Переключение видимости пароля
|
|
function togglePassword(inputId) {
|
|
const input = document.getElementById(inputId);
|
|
const button = input.nextElementSibling.querySelector('i');
|
|
|
|
if (input.type === 'password') {
|
|
input.type = 'text';
|
|
button.classList.remove('bi-eye');
|
|
button.classList.add('bi-eye-slash');
|
|
} else {
|
|
input.type = 'password';
|
|
button.classList.remove('bi-eye-slash');
|
|
button.classList.add('bi-eye');
|
|
}
|
|
}
|
|
|
|
// Сброс формы
|
|
function resetForm() {
|
|
document.getElementById('vkForm').reset();
|
|
updateStatusIndicators();
|
|
}
|
|
|
|
// Сохранение настроек VK
|
|
async function saveVkSettings() {
|
|
const access_token = document.getElementById('access_token').value.trim();
|
|
const group_id = document.getElementById('group_id').value.trim();
|
|
const base_photo_url = document.getElementById('base_photo_url').value.trim();
|
|
|
|
// Проверка обязательных полей
|
|
if (!access_token || !group_id) {
|
|
showAlert('warning', 'Заполните обязательные поля: Access Token и ID сообщества');
|
|
return;
|
|
}
|
|
|
|
// Проверка формата group_id (должно быть число)
|
|
if (!/^\d+$/.test(group_id)) {
|
|
showAlert('warning', 'ID сообщества должен содержать только цифры');
|
|
return;
|
|
}
|
|
|
|
const settings = {
|
|
access_token,
|
|
group_id,
|
|
base_photo_url: base_photo_url || null
|
|
};
|
|
|
|
if (pageData && pageData.vk_settings) {
|
|
settings.id = pageData.vk_settings.id;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch('/api/vk', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify(settings)
|
|
});
|
|
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
showAlert('success', 'Настройки VK успешно сохранены!');
|
|
|
|
updateStatusIndicators();
|
|
|
|
// Перезагружаем страницу для отображения обновленных данных
|
|
setTimeout(() => {
|
|
window.location.reload();
|
|
}, 1500);
|
|
|
|
} else {
|
|
const error = await response.text();
|
|
showAlert('danger', 'Ошибка сохранения: ' + error);
|
|
}
|
|
} catch (error) {
|
|
console.error('Ошибка:', error);
|
|
showAlert('danger', 'Ошибка сохранения настроек!');
|
|
}
|
|
}
|
|
|
|
// Вспомогательные функции для уведомлений
|
|
function showAlert(type, message) {
|
|
const alertContainer = document.getElementById('alertContainer');
|
|
|
|
// Создаем алерт
|
|
const alert = document.createElement('div');
|
|
alert.className = `alert alert-${type} alert-dismissible fade show shadow`;
|
|
|
|
// Иконка для типа алерта
|
|
const icon = getAlertIcon(type);
|
|
|
|
alert.innerHTML = `
|
|
<div class="d-flex align-items-center">
|
|
<i class="bi ${icon} me-2 fs-5"></i>
|
|
<div class="flex-grow-1">${message}</div>
|
|
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
|
</div>
|
|
`;
|
|
|
|
alertContainer.appendChild(alert);
|
|
|
|
// Автоматическое удаление через 5 секунд
|
|
setTimeout(() => {
|
|
if (alert.parentNode) {
|
|
alert.classList.remove('show');
|
|
setTimeout(() => alert.remove(), 150);
|
|
}
|
|
}, 5000);
|
|
}
|
|
|
|
function getAlertIcon(type) {
|
|
const icons = {
|
|
'success': 'bi-check-circle-fill',
|
|
'warning': 'bi-exclamation-triangle-fill',
|
|
'danger': 'bi-x-circle-fill',
|
|
'info': 'bi-info-circle-fill'
|
|
};
|
|
return icons[type] || 'bi-info-circle-fill';
|
|
}
|
|
|
|
// Дополнительная проверка при вводе данных
|
|
document.getElementById('group_id').addEventListener('input', function (e) {
|
|
this.value = this.value.replace(/[^\d]/g, '');
|
|
});
|
|
|
|
// Подсказка для base_photo_url при фокусе
|
|
document.getElementById('base_photo_url').addEventListener('focus', function () {
|
|
if (!this.value) {
|
|
showAlert('info', 'Формат ID фото: photo_id (например: 7236456789)');
|
|
}
|
|
});
|
|
|
|
function handleLink() {
|
|
const link = prompt('Введите ссылку на фотографию:');
|
|
if (!link) return;
|
|
|
|
try {
|
|
const url = new URL(link);
|
|
const zParam = url.searchParams.get('z');
|
|
|
|
if (!zParam || !zParam.startsWith('photo')) {
|
|
alert('Некорректная ссылка на фото ВК');
|
|
return;
|
|
}
|
|
|
|
const decoded = decodeURIComponent(zParam);
|
|
const match = decoded.match(/photo(-?\d+)_(\d+)/);
|
|
|
|
if (!match) {
|
|
alert('Не удалось разобрать ссылку');
|
|
return;
|
|
}
|
|
|
|
const groupId = Math.abs(Number(match[1]));
|
|
const photoId = Number(match[2]);
|
|
|
|
const isConfirmed = window.confirm(
|
|
`Применить новые данные?\nГруппа: ${groupId}\nID фото: ${photoId}`
|
|
);
|
|
|
|
if (isConfirmed) {
|
|
document.getElementById('group_id').value = groupId;
|
|
document.getElementById('base_photo_url').value = photoId;
|
|
}
|
|
|
|
} catch (e) {
|
|
alert('Ошибка обработки ссылки');
|
|
}
|
|
} |