feat: mobile-like window size and always-visible stats

- Changed window size to mobile phone format (400x800)
- Removed width condition for ActiveProxyFooter - now always visible
- Added run-umbrix.sh launch script with icon copying
- Stats cards now display on all screen sizes
This commit is contained in:
Umbrix Developer
2026-01-17 13:09:20 +03:00
parent ec5ebbd54b
commit 76a374950f
245 changed files with 7931 additions and 1315 deletions

View File

@@ -0,0 +1,33 @@
# Umbrix Admin Panel - Защита доступа
# Базовая аутентификация
AuthType Basic
AuthName "Umbrix Update Manager"
# Путь к файлу паролей (создайте командой: htpasswd -c .htpasswd admin)
AuthUserFile /var/www/updates/admin/.htpasswd
Require valid-user
# Блокировка прямого доступа к PHP файлам из браузера (опционально)
# <FilesMatch "save\.php$">
# Order deny,allow
# Deny from all
# </FilesMatch>
# CORS для локальных запросов
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, X-Admin-Password"
</IfModule>
# Запрет доступа к бэкапам
<FilesMatch "\.backup.*$">
Order deny,allow
Deny from all
</FilesMatch>
# Запрет доступа к логам
<FilesMatch "\.log$">
Order deny,allow
Deny from all
</FilesMatch>

View File

@@ -0,0 +1,305 @@
# 🎨 Веб-панель управления обновлениями
## 📋 Что это?
Простой веб-интерфейс для управления обновлениями Umbrix без редактирования JSON вручную!
```
┌──────────────────────────────────────────────┐
│ 🚀 Umbrix Update Manager │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ │
│ 📦 Текущая версия: 2.5.7 │
│ │
│ Версия: [2.5.8____________] │
│ Build: [258______________] │
│ URL: [https://...] │
│ Описание: [Что нового...] │
│ │
│ [🔄 Загрузить] [💾 Сохранить обновление] │
└──────────────────────────────────────────────┘
```
---
## 🚀 Установка
### Шаг 1: Загрузите файлы
Загрузите на сервер папку `admin/`:
```
update-server/
├── admin/ ← загрузите эту папку
│ ├── index.html ← веб-интерфейс
│ ├── save.php ← скрипт сохранения
│ └── .htaccess ← защита (опционально)
├── api.php
└── latest.json
```
### Шаг 2: Настройте права доступа
```bash
# Права на папку admin
chmod 755 admin/
# Права на файлы
chmod 644 admin/index.html
chmod 644 admin/save.php
# latest.json должен быть доступен для записи
chmod 666 latest.json
```
### Шаг 3: Откройте в браузере
Перейдите по адресу:
```
https://api.umbrix.net/admin/
```
---
## 🎯 Как пользоваться?
### 1. Просмотр текущей версии
В верхней части автоматически отображается:
- ✅ Текущая версия
- ✅ Build number
- ✅ Статус (STABLE/BETA)
- ✅ Дата публикации
### 2. Создание нового обновления
1. Заполните форму:
- **Версия** (обязательно): `2.5.8`
- **Build Number** (обязательно): `258`
- **URL APK** (обязательно): `https://api.umbrix.net/downloads/umbrix-2.5.8.apk`
- **Описание**: Что нового в версии
- **Дата**: Автоматически или выберите
- **Мин. версия**: С какой версии можно обновляться
- **Бета**: Поставьте галочку для предварительных релизов
2. Нажмите **"💾 Сохранить обновление"**
3. Готово! Файл `latest.json` обновлен
### 3. Загрузка существующих данных
Нажмите **"🔄 Загрузить текущую"** чтобы заполнить форму данными из `latest.json`
---
## 🔒 Безопасность
### Вариант 1: Защита паролем через .htaccess
Создайте файл `admin/.htaccess`:
```apache
AuthType Basic
AuthName "Umbrix Admin Panel"
AuthUserFile /var/www/updates/admin/.htpasswd
Require valid-user
```
Создайте пароль:
```bash
cd /var/www/updates/admin
htpasswd -c .htpasswd admin
# Введите пароль
```
### Вариант 2: Защита через PHP
Раскомментируйте строки в `save.php`:
```php
// РАСКОММЕНТИРУЙТЕ ЭТИ СТРОКИ:
$provided_password = $_SERVER['HTTP_X_ADMIN_PASSWORD'] ?? '';
if ($provided_password !== $admin_password) {
http_response_code(403);
echo json_encode(['success' => false, 'message' => 'Неверный пароль']);
exit();
}
```
Затем в `index.html` добавьте в fetch:
```javascript
headers: {
'Content-Type': 'application/json',
'X-Admin-Password': 'umbrix2024' // ваш пароль
}
```
### Вариант 3: Скрыть папку admin
Переименуйте папку в что-то секретное:
```bash
mv admin secret-panel-f7a8e2b9
```
Адрес будет: `https://api.umbrix.net/secret-panel-f7a8e2b9/`
---
## 📱 Использование с телефона
Интерфейс адаптивный - можно управлять с телефона!
1. Откройте в браузере
2. Сохраните на главный экран
3. Готово - полноценное PWA приложение
---
## 🧪 Тестирование локально
```bash
# Запустите PHP сервер
cd update-server
php -S localhost:8000
# Откройте в браузере:
http://localhost:8000/admin/
```
---
## ✨ Возможности
**Красивый интерфейс** - современный дизайн
**Без кода** - просто заполните форму
**Валидация** - проверка всех полей
**Автобэкап** - старые версии сохраняются
**Логирование** - все действия записываются
**Мобильный** - работает на телефоне
**Безопасность** - защита паролем
---
## 📝 Пример использования
### Сценарий: Выкатка новой версии
1. **Соберите APK:**
```bash
flutter build apk --release
```
2. **Загрузите APK на сервер** в `downloads/umbrix-2.5.8.apk`
3. **Откройте админ-панель** в браузере
4. **Заполните форму:**
- Версия: `2.5.8`
- Build: `258`
- URL: `https://api.umbrix.net/downloads/umbrix-2.5.8.apk`
- Описание: `🎉 Исправлены ошибки, улучшена стабильность`
5. **Нажмите "Сохранить"**
6. **Готово!** Пользователи получат уведомление
---
## 🐛 Решение проблем
### Ошибка "Permission denied"
```bash
# Дайте права на запись
chmod 666 latest.json
chmod 777 logs/
```
### Ошибка "Method Not Allowed"
Проверьте, что файл `save.php` доступен:
```bash
curl -X POST https://api.umbrix.net/admin/save.php
```
### Не загружается current version
Проверьте путь к `latest.json` в `save.php`:
```php
$json_file = __DIR__ . '/../latest.json';
```
---
## 📊 Структура файлов
```
update-server/
├── admin/
│ ├── index.html ← Веб-интерфейс
│ ├── save.php ← Скрипт сохранения
│ ├── .htaccess ← Защита (опционально)
│ └── README.md ← Эта инструкция
├── api.php ← API для приложения
├── latest.json ← Текущая версия
├── latest.json.backup.* ← Автобэкапы
├── downloads/ ← APK файлы
│ └── umbrix-*.apk
└── logs/
├── access.log ← Логи API
└── admin.log ← Логи админки
```
---
## 🎓 Дополнительные возможности
### Добавить подтверждение
В `index.html` перед сохранением:
```javascript
if (!confirm('Точно сохранить обновление v' + formData.version + '?')) {
return;
}
```
### Показать историю версий
Добавьте в `save.php`:
```php
// Сохранение в историю
$history_file = __DIR__ . '/../history.json';
$history = file_exists($history_file)
? json_decode(file_get_contents($history_file), true)
: [];
$history[] = array_merge($update_data, ['saved_at' => date('c')]);
file_put_contents($history_file, json_encode($history, JSON_PRETTY_PRINT));
```
---
## ✅ Готово!
Теперь у вас есть удобная панель управления обновлениями!
**Не нужно:**
- ❌ Редактировать JSON вручную
- ❌ Подключаться через SSH
- ❌ Помнить формат файлов
**Просто:**
- ✅ Открыли браузер
- ✅ Заполнили форму
- ✅ Нажали "Сохранить"
---
**🎉 Приятного использования!**

View File

@@ -0,0 +1,67 @@
<?php
/**
* Umbrix Update Manager - Version History API
* Получение списка всех сохранённых версий (бэкапов)
*/
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=utf-8');
$backups_dir = __DIR__ . '/../';
$versions = [];
// Сканируем директорию на наличие бэкапов
$files = glob($backups_dir . 'latest.json.backup.*');
// Также добавляем текущую версию
if (file_exists($backups_dir . 'latest.json')) {
$current = json_decode(file_get_contents($backups_dir . 'latest.json'), true);
if ($current) {
$versions[] = [
'filename' => 'latest.json',
'version' => $current['version'] ?? 'unknown',
'build_number' => $current['build_number'] ?? 0,
'published_at' => $current['published_at'] ?? null,
'is_prerelease' => $current['is_prerelease'] ?? false,
'is_current' => true,
'timestamp' => file_exists($backups_dir . 'latest.json') ? filemtime($backups_dir . 'latest.json') : time(),
'size' => filesize($backups_dir . 'latest.json')
];
}
}
// Добавляем все бэкапы
foreach ($files as $file) {
$content = json_decode(file_get_contents($file), true);
if ($content) {
$filename = basename($file);
// Извлекаем дату из имени файла (формат: latest.json.backup.2026-01-17_08-30-45)
preg_match('/backup\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})/', $filename, $matches);
$backup_date = $matches[1] ?? null;
$versions[] = [
'filename' => $filename,
'version' => $content['version'] ?? 'unknown',
'build_number' => $content['build_number'] ?? 0,
'published_at' => $content['published_at'] ?? null,
'is_prerelease' => $content['is_prerelease'] ?? false,
'is_current' => false,
'timestamp' => filemtime($file),
'backup_date' => $backup_date,
'size' => filesize($file),
'release_notes' => $content['release_notes'] ?? ''
];
}
}
// Сортируем по времени (новые сверху)
usort($versions, function($a, $b) {
return $b['timestamp'] - $a['timestamp'];
});
echo json_encode([
'success' => true,
'count' => count($versions),
'versions' => $versions
]);

View File

@@ -0,0 +1,653 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🚀 Umbrix Update Manager</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: #1a1f2e;
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
}
.header {
text-align: center;
color: #ffffff;
margin-bottom: 30px;
}
.header h1 {
font-size: 2.5em;
margin-bottom: 10px;
}
.subtitle {
text-align: center;
color: #b4bcc9;
margin-bottom: 30px;
}
.panel {
background: #252d3d;
border-radius: 16px;
padding: 30px;
box-shadow: 0 10px 40px rgba(0,0,0,0.4);
border: 1px solid #2d3548;
}
.current-version {
background: #1e2533;
padding: 20px;
border-radius: 12px;
margin-bottom: 20px;
border-left: 4px solid #4ade80;
border: 1px solid #2d3548;
}
.current-version h3 {
margin-bottom: 12px;
color: #4ade80;
font-size: 1.1em;
}
.version-info {
display: grid;
grid-template-columns: 150px 1fr;
gap: 10px;
font-size: 0.9em;
}
.version-info strong {
color: #9ca3af;
}
.version-info span {
color: #ffffff;
}
.badge {
display: inline-block;
padding: 5px 12px;
border-radius: 8px;
font-size: 0.8em;
font-weight: 600;
}
.badge.beta {
background: rgba(239, 68, 68, 0.15);
color: #ef4444;
border: 1px solid rgba(239, 68, 68, 0.3);
}
.badge.stable {
background: rgba(74, 222, 128, 0.15);
color: #4ade80;
border: 1px solid rgba(74, 222, 128, 0.3);
}
.form-group {
margin-bottom: 20px;
}
.form-group h3 {
color: #ffffff;
margin-bottom: 15px;
font-size: 1.1em;
}
label {
display: block;
font-weight: 600;
margin-bottom: 8px;
color: #ffffff;
font-size: 0.95em;
}
.hint {
font-size: 0.85em;
color: #9ca3af;
margin-top: 4px;
}
input[type="text"],
input[type="url"],
input[type="datetime-local"],
textarea {
width: 100%;
padding: 12px;
border: 2px solid #2d3548;
border-radius: 12px;
font-size: 1em;
transition: all 0.3s;
background: #1e2533;
color: #ffffff;
}
input::placeholder,
textarea::placeholder {
color: #6b7280;
}
input:focus,
textarea:focus {
outline: none;
border-color: #4ade80;
background: #252d3d;
}
textarea {
min-height: 120px;
resize: vertical;
font-family: inherit;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 10px;
}
input[type="checkbox"] {
width: 20px;
height: 20px;
cursor: pointer;
accent-color: #4ade80;
}
.checkbox-group label {
color: #e5e7eb;
font-weight: 400;
margin-bottom: 0;
}
.button-group {
display: flex;
gap: 15px;
margin-top: 30px;
}
button {
flex: 1;
padding: 15px;
border: none;
border-radius: 12px;
font-size: 1em;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
}
.btn-primary {
background: #4ade80;
color: #1a1f2e;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(74, 222, 128, 0.3);
background: #5ef590;
}
.btn-secondary {
background: #2d3548;
color: #ffffff;
border: 1px solid #3d4658;
}
.btn-secondary:hover {
background: #363f54;
border-color: #4ade80;
}
.status {
margin-top: 20px;
padding: 15px;
border-radius: 12px;
display: none;
border: 1px solid;
}
.status.success {
background: rgba(74, 222, 128, 0.15);
color: #4ade80;
border-color: rgba(74, 222, 128, 0.3);
}
.status.error {
background: rgba(239, 68, 68, 0.15);
color: #ef4444;
border-color: rgba(239, 68, 68, 0.3);
}
.tabs {
display: flex;
gap: 10px;
margin-bottom: 20px;
border-bottom: 2px solid #2d3548;
}
.tab {
padding: 12px 24px;
background: transparent;
border: none;
color: #9ca3af;
cursor: pointer;
font-size: 1em;
font-weight: 600;
border-bottom: 3px solid transparent;
transition: all 0.3s;
}
.tab:hover {
color: #ffffff;
}
.tab.active {
color: #4ade80;
border-bottom-color: #4ade80;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.history-list {
margin-top: 20px;
}
.history-item {
background: #1e2533;
padding: 15px;
border-radius: 12px;
margin-bottom: 10px;
border: 1px solid #2d3548;
display: flex;
justify-content: space-between;
align-items: center;
}
.history-item.current {
border-left: 4px solid #4ade80;
}
.history-info {
flex: 1;
}
.history-version {
color: #ffffff;
font-weight: 600;
font-size: 1.1em;
margin-bottom: 5px;
}
.history-meta {
color: #9ca3af;
font-size: 0.85em;
}
.btn-restore {
background: #f59e0b;
color: #1a1f2e;
padding: 8px 16px;
border: none;
border-radius: 8px;
cursor: pointer;
font-weight: 600;
transition: all 0.3s;
}
.btn-restore:hover {
background: #fbbf24;
transform: translateY(-2px);
}
.btn-restore:disabled {
background: #374151;
color: #6b7280;
cursor: not-allowed;
transform: none;
}
@media (max-width: 768px) {
.button-group {
flex-direction: column-reverse;
}
.history-item {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🚀 Umbrix Update Manager</h1>
<p class="subtitle">Панель управления обновлениями приложения</p>
</div>
<div class="panel">
<div class="tabs">
<button class="tab active" onclick="switchTab('update')">📝 Обновление</button>
<button class="tab" onclick="switchTab('history')">🕐 История версий</button>
</div>
<div id="updateTab" class="tab-content active">
<div class="current-version">
<h3>📦 Текущая версия</h3>
<div class="version-info">
<strong>Версия:</strong>
<span id="currentVersion">Ошибка загрузки</span>
<strong>Build:</strong>
<span id="currentBuild">-</span>
<strong>Статус:</strong>
<span id="currentStatus">-</span>
<strong>Опубликовано:</strong>
<span id="currentPublished">-</span>
</div>
</div>
<form id="updateForm">
<div class="form-group">
<label for="version">Версия *</label>
<input
type="text"
id="version"
name="version"
placeholder="2.5.8"
required
>
<div class="hint">Формат: X.Y.Z (например: 2.5.8)</div>
</div>
<div class="form-group">
<label for="buildNumber">Build Number *</label>
<input
type="text"
id="buildNumber"
name="buildNumber"
placeholder="258"
required
>
<div class="hint">Число, соответствующее версии</div>
</div>
<div class="form-group">
<label for="downloadUrl">URL для скачивания APK *</label>
<input
type="url"
id="downloadUrl"
name="downloadUrl"
placeholder="https://api.umbrix.net/downloads/umbrix-2.5.8.apk"
required
>
<div class="hint">Полный URL к APK файлу на вашем сервере</div>
</div>
<div class="form-group">
<label for="releaseNotes">Описание обновления</label>
<textarea
id="releaseNotes"
name="releaseNotes"
placeholder="🎉 Что нового в этой версии:
✨ Новые функции:
- Улучшена стабильность
- Исправлены ошибки
Что нового в этой версии? (поддерживаются эмодзи)"
></textarea>
<div class="hint">Что нового в этой версии? (поддерживаются эмодзи)</div>
</div>
<div class="form-group">
<label for="publishedAt">Дата публикации</label>
<input
type="datetime-local"
id="publishedAt"
name="publishedAt"
>
<div class="hint">Оставьте пустым для текущей даты</div>
</div>
<div class="form-group">
<label for="minVersion">Минимальная требуемая версия</label>
<input
type="text"
id="minVersion"
name="minVersion"
placeholder="2.0.0"
>
<div class="hint">Версии ниже не смогут обновиться (опционально)</div>
</div>
<div class="checkbox-group">
<input
type="checkbox"
id="isPrerelease"
name="isPrerelease"
>
<label for="isPrerelease">Это бета-версия (предварительный релиз)</label>
</div>
<div class="button-group">
<button type="button" class="btn-secondary" onclick="loadCurrentVersion()">
📂 Загрузить текущую
</button>
<button type="submit" class="btn-primary">
💾 Сохранить обновление
</button>
</div>
<div class="status" id="status"></div>
</form>
</div>
<div id="historyTab" class="tab-content">
<div class="current-version">
<h3>📚 История всех версий</h3>
<p style="color: #9ca3af; margin-top: 10px;">Все сохранённые версии с возможностью отката</p>
</div>
<div class="history-list" id="historyList">
<p style="text-align: center; color: #9ca3af; padding: 20px;">Загрузка...</p>
</div>
</div>
</div>
</div>
<script>
// Load current version on page load
window.addEventListener('DOMContentLoaded', () => {
loadCurrentVersion();
loadHistory();
});
function switchTab(tab) {
// Update tab buttons
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
event.target.classList.add('active');
// Update tab content
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
document.getElementById(tab + 'Tab').classList.add('active');
if (tab === 'history') {
loadHistory();
}
}
async function loadHistory() {
const historyList = document.getElementById('historyList');
try {
const response = await fetch('history.php');
if (!response.ok) throw new Error('Не удалось загрузить историю');
const data = await response.json();
if (!data.success || data.versions.length === 0) {
historyList.innerHTML = '<p style="text-align: center; color: #9ca3af; padding: 20px;">История пуста</p>';
return;
}
historyList.innerHTML = data.versions.map(v => `
<div class="history-item ${v.is_current ? 'current' : ''}">
<div class="history-info">
<div class="history-version">
${v.is_current ? '🟢 ' : ''}v${v.version} (Build ${v.build_number})
${v.is_prerelease ? '<span class="badge beta">Бета</span>' : '<span class="badge stable">Стабильная</span>'}
</div>
<div class="history-meta">
📅 ${new Date(v.timestamp * 1000).toLocaleString('ru-RU')}
${v.backup_date ? ` • Бэкап: ${v.backup_date.replace('_', ' ').replace(/-/g, '.')}` : ''}
• 💾 ${(v.size / 1024).toFixed(1)} KB
</div>
${v.release_notes ? `<div style="color: #6b7280; font-size: 0.85em; margin-top: 8px; max-width: 500px; white-space: pre-wrap;">${v.release_notes.substring(0, 100)}${v.release_notes.length > 100 ? '...' : ''}</div>` : ''}
</div>
<button
class="btn-restore"
onclick="restoreVersion('${v.filename}')"
${v.is_current ? 'disabled' : ''}
>
${v.is_current ? '✓ Текущая' : '↩️ Откатить'}
</button>
</div>
`).join('');
} catch (error) {
console.error('Error loading history:', error);
historyList.innerHTML = '<p style="text-align: center; color: #ef4444; padding: 20px;">❌ Ошибка загрузки истории</p>';
}
}
async function restoreVersion(filename) {
if (!confirm(`Откатить на версию из ${filename}?\n\nТекущая версия будет сохранена в бэкап.`)) {
return;
}
try {
const response = await fetch('restore.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ filename })
});
const result = await response.json();
if (result.success) {
alert(`${result.message}\n\nВосстановлена версия: v${result.version} (Build ${result.build_number})`);
await loadCurrentVersion();
await loadHistory();
switchTab('update');
} else {
alert('❌ ' + result.message);
}
} catch (error) {
alert('❌ Ошибка отката: ' + error.message);
}
}
async function loadCurrentVersion() {
try {
const response = await fetch('../latest.json');
if (!response.ok) {
throw new Error('Не удалось загрузить текущую версию');
}
const data = await response.json();
// Update current version display
document.getElementById('currentVersion').textContent = data.version || '-';
document.getElementById('currentBuild').textContent = data.build_number || '-';
document.getElementById('currentStatus').innerHTML = data.is_prerelease
? '<span class="badge beta">Бета-версия</span>'
: '<span class="badge stable">Стабильная</span>';
document.getElementById('currentPublished').textContent = data.published_at
? new Date(data.published_at).toLocaleString('ru-RU')
: '-';
} catch (error) {
console.error('Error loading current version:', error);
document.getElementById('currentVersion').textContent = 'Ошибка загрузки';
}
}
document.getElementById('updateForm').addEventListener('submit', async function(e) {
e.preventDefault();
const statusDiv = document.getElementById('status');
statusDiv.style.display = 'none';
const formData = new FormData(e.target);
const data = {
version: formData.get('version'),
build_number: formData.get('buildNumber'),
download_url: formData.get('downloadUrl'),
release_notes: formData.get('releaseNotes'),
published_at: formData.get('publishedAt') || new Date().toISOString(),
min_required_version: formData.get('minVersion') || null,
is_prerelease: formData.get('isPrerelease') === 'on'
};
try {
const response = await fetch('save.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
if (result.success) {
showStatus('success', '✅ ' + result.message);
await loadCurrentVersion();
e.target.reset();
} else {
showStatus('error', '❌ ' + result.message);
}
} catch (error) {
showStatus('error', '❌ Ошибка сохранения: ' + error.message);
}
});
function showStatus(type, message) {
const statusDiv = document.getElementById('status');
statusDiv.className = 'status ' + type;
statusDiv.textContent = message;
statusDiv.style.display = 'block';
// Auto-hide after 5 seconds
setTimeout(() => {
statusDiv.style.display = 'none';
}, 5000);
}
</script>
</body>
</html>

View File

@@ -0,0 +1,85 @@
<?php
/**
* Umbrix Update Manager - Restore Version
* Откат на предыдущую версию из бэкапа
*/
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
exit();
}
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (!isset($data['filename'])) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Не указан файл для восстановления']);
exit();
}
$filename = basename($data['filename']); // Защита от path traversal
$backups_dir = __DIR__ . '/../';
$backup_file = $backups_dir . $filename;
$current_file = $backups_dir . 'latest.json';
// Проверяем существование файла бэкапа
if (!file_exists($backup_file)) {
http_response_code(404);
echo json_encode(['success' => false, 'message' => 'Файл бэкапа не найден']);
exit();
}
// Проверяем, что это действительно файл бэкапа
if (!preg_match('/^latest\.json\.backup\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$/', $filename)) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Неверный формат файла']);
exit();
}
// Создаём бэкап текущей версии перед откатом
if (file_exists($current_file)) {
$backup_name = 'latest.json.backup.' . date('Y-m-d_H-i-s');
copy($current_file, $backups_dir . $backup_name);
}
// Восстанавливаем версию из бэкапа
if (copy($backup_file, $current_file)) {
// Логируем откат
$log_dir = $backups_dir . 'logs';
if (!is_dir($log_dir)) {
mkdir($log_dir, 0755, true);
}
$log_entry = sprintf(
"[%s] RESTORE: %s -> latest.json (IP: %s)\n",
date('Y-m-d H:i:s'),
$filename,
$_SERVER['REMOTE_ADDR'] ?? 'unknown'
);
file_put_contents($log_dir . '/restore.log', $log_entry, FILE_APPEND);
// Получаем данные восстановленной версии
$restored_data = json_decode(file_get_contents($current_file), true);
echo json_encode([
'success' => true,
'message' => 'Версия успешно восстановлена',
'version' => $restored_data['version'] ?? 'unknown',
'build_number' => $restored_data['build_number'] ?? 0
]);
} else {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Ошибка при восстановлении файла']);
}

View File

@@ -0,0 +1,140 @@
<?php
/**
* Umbrix Update Manager - Save Script
* Сохранение данных обновления в latest.json
*/
// CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json; charset=utf-8');
// Обработка preflight запроса
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
// Только POST запросы
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
exit();
}
// === НАСТРОЙКИ ===
// Путь к файлу latest.json (на уровень выше)
$json_file = __DIR__ . '/../latest.json';
// Пароль для доступа (ИЗМЕНИТЕ ЭТО!)
$admin_password = 'umbrix2024';
// Проверка пароля (опционально, раскомментируйте если нужна защита)
// $provided_password = $_SERVER['HTTP_X_ADMIN_PASSWORD'] ?? '';
// if ($provided_password !== $admin_password) {
// http_response_code(403);
// echo json_encode(['success' => false, 'message' => 'Неверный пароль']);
// exit();
// }
// === КОНЕЦ НАСТРОЕК ===
// Получение данных
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (!$data) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Неверный формат данных']);
exit();
}
// Валидация обязательных полей
$required_fields = ['version', 'build_number', 'download_url', 'published_at'];
foreach ($required_fields as $field) {
if (!isset($data[$field]) || empty($data[$field])) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => "Отсутствует обязательное поле: $field"
]);
exit();
}
}
// Валидация версии (формат X.Y.Z)
if (!preg_match('/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/', $data['version'])) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => 'Неверный формат версии. Используйте X.Y.Z (например: 2.5.8)'
]);
exit();
}
// Валидация URL
if (!filter_var($data['download_url'], FILTER_VALIDATE_URL)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => 'Неверный формат URL'
]);
exit();
}
// Подготовка данных для сохранения
$update_data = [
'version' => $data['version'],
'build_number' => $data['build_number'],
'is_prerelease' => $data['is_prerelease'] ?? false,
'download_url' => $data['download_url'],
'release_notes' => $data['release_notes'] ?? '',
'published_at' => $data['published_at'],
'min_required_version' => $data['min_required_version'] ?? '2.0.0',
'file_size_bytes' => 0,
'file_checksum_sha256' => ''
];
// Попытка получить размер файла (если APK доступен)
$apk_path = __DIR__ . '/../downloads/' . basename(parse_url($data['download_url'], PHP_URL_PATH));
if (file_exists($apk_path)) {
$update_data['file_size_bytes'] = filesize($apk_path);
}
// Создание бэкапа старой версии
if (file_exists($json_file)) {
$backup_file = __DIR__ . '/../latest.json.backup.' . date('Y-m-d_H-i-s');
copy($json_file, $backup_file);
}
// Сохранение в JSON
$json_content = json_encode($update_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (file_put_contents($json_file, $json_content) === false) {
http_response_code(500);
echo json_encode([
'success' => false,
'message' => 'Не удалось сохранить файл. Проверьте права доступа.'
]);
exit();
}
// Логирование
$log_entry = sprintf(
"[%s] Обновление сохранено: v%s (build %s) | IP: %s\n",
date('Y-m-d H:i:s'),
$data['version'],
$data['build_number'],
$_SERVER['REMOTE_ADDR'] ?? 'unknown'
);
file_put_contents(__DIR__ . '/../logs/admin.log', $log_entry, FILE_APPEND);
// Успешный ответ
echo json_encode([
'success' => true,
'message' => 'Обновление успешно сохранено',
'data' => $update_data
]);
?>