Compare commits
29 Commits
1977fed437
..
0.2.0b
| Author | SHA1 | Date | |
|---|---|---|---|
| 7831149465 | |||
| b2b2145c37 | |||
| 21e37776f9 | |||
| 2c2aa65947 | |||
| 36a044c8da | |||
| d1bc3fe836 | |||
| 34f144d240 | |||
| bd3036f058 | |||
| 7fe9b73d49 | |||
| 18a3e3d3f2 | |||
| 228555e8f7 | |||
| 831c2a0b85 | |||
| 76397a4fc0 | |||
| 7b86090b75 | |||
| 800c9cb651 | |||
| 4cddd19c76 | |||
| 4a88e4c491 | |||
| 627b374b7f | |||
| 2a103d246b | |||
| ed7bc4fba5 | |||
| 30e0d58a7c | |||
| 612332e4ee | |||
| 270be38d1e | |||
| 6cdf1cc5eb | |||
| 535ab65fa4 | |||
| bdb9d599bd | |||
| 843a3d4bc5 | |||
| bf53a2b208 | |||
| f5de7bb62d |
+10
@@ -1,4 +1,14 @@
|
|||||||
# ---> Python
|
# ---> Python
|
||||||
|
# Secure data
|
||||||
|
.vscode
|
||||||
|
old/
|
||||||
|
data_test/
|
||||||
|
tmp/
|
||||||
|
config_gb.json
|
||||||
|
migration.py
|
||||||
|
change_log.txt
|
||||||
|
up/
|
||||||
|
|
||||||
# Byte-compiled / optimized / DLL files
|
# Byte-compiled / optimized / DLL files
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
|
|||||||
@@ -1,11 +1,5 @@
|
|||||||
# Local-Booru
|
# Local-Booru
|
||||||
|
|
||||||
Version Naming Rules:
|
## [ENGLISH README](doc/readme_en.md) | [РУССКИЙ README](doc/readme_ru.md)
|
||||||
|
|
||||||
[Version Code][Version Type]
|
## [INSTALL INSRUCTION](doc/install_en.md) | [ИНСТРУКЦИЯ ПО УСТАНОВКЕ](doc/install_ru.md)
|
||||||
|
|
||||||
All technical versions are designated as snapshots (s)
|
|
||||||
|
|
||||||
All test versions are designated as alpha and beta (a, b)
|
|
||||||
|
|
||||||
All pre-release and release versions are designated as release candidate and release (rc, r)
|
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
// ==UserScript==
|
||||||
|
// @name gelbooru.com Button DW ADD
|
||||||
|
// @namespace nyakonya_gelbooruocdw_dev
|
||||||
|
// @match https://gelbooru.com/index.php*
|
||||||
|
// @grant GM_xmlhttpRequest
|
||||||
|
// @grant GM_registerMenuCommand
|
||||||
|
// @grant GM_getValue
|
||||||
|
// @grant GM_setValue
|
||||||
|
// @version 1.1r
|
||||||
|
// @author https://t.me/Nyako_TW
|
||||||
|
// @downloadURL https://git.nekono.su/Nyako/Local-Booru/raw/branch/main/button_script.user.js
|
||||||
|
// @updateURL https://git.nekono.su/Nyako/Local-Booru/raw/branch/main/button_script.user.js
|
||||||
|
// @description Adds a one-click button to download the original image on Gelbooru post pages.
|
||||||
|
// ==/UserScript==
|
||||||
|
|
||||||
|
'use strict'; // Рекомендуется оставить для более строгого и безопасного выполнения кода.
|
||||||
|
|
||||||
|
// Функция безопасного запуска функций
|
||||||
|
function safeRun(fn, name) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`Ошибка в ${name}:`, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Функция генерации текстовой конфигурации
|
||||||
|
function registerTextInput(key, defaultValue, title, promptMessage) {
|
||||||
|
const currentValue = GM_getValue(key, defaultValue);
|
||||||
|
const menuText = `⚙️ ${title}: ${currentValue}`;
|
||||||
|
|
||||||
|
GM_registerMenuCommand(menuText, () => {
|
||||||
|
const newValue = prompt(promptMessage, currentValue);
|
||||||
|
if (newValue !== null) {
|
||||||
|
GM_setValue(key, newValue.trim());
|
||||||
|
alert(
|
||||||
|
`Настройка изменена!\n${title}: ${newValue.trim()}\nОбновите страницу для применения настроек.`
|
||||||
|
);
|
||||||
|
location.reload();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Генерация конфигураций
|
||||||
|
function config_runner() {
|
||||||
|
registerTextInput(
|
||||||
|
'nyakonya_gb_api_root',
|
||||||
|
'http://127.0.2.1',
|
||||||
|
'Адрес API',
|
||||||
|
'Введите базовый URL локального API (например, http://127.0.2.1 или https://booru.loc):'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Запуск конфигуратора
|
||||||
|
safeRun(config_runner, "config_runner");
|
||||||
|
|
||||||
|
// 1. Находим ссылку на оригинальное изображение по тексту
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
const imageID = params.get("id");
|
||||||
|
const xpathResult = document.evaluate(
|
||||||
|
'//a[text()="Original image"]',
|
||||||
|
document,
|
||||||
|
null,
|
||||||
|
XPathResult.FIRST_ORDERED_NODE_TYPE,
|
||||||
|
null
|
||||||
|
);
|
||||||
|
const originalImageLinkElement = xpathResult.singleNodeValue;
|
||||||
|
|
||||||
|
if (originalImageLinkElement) {
|
||||||
|
const imageUrl = originalImageLinkElement.href;
|
||||||
|
const existingAnchor = document.querySelector('a[onclick*="saveTagSearch"]');
|
||||||
|
|
||||||
|
if (existingAnchor) {
|
||||||
|
const downloadSvgIcon = `
|
||||||
|
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="2em" height="2em" viewBox="0 0 122.433 122.88" enable-background="new 0 0 122.433 122.88" xml:space="preserve"><g><polygon fill-rule="evenodd" clip-rule="evenodd" points="61.216,122.88 0,59.207 39.403,59.207 39.403,0 83.033,0 83.033,59.207 122.433,59.207 61.216,122.88"/></g></svg>
|
||||||
|
`;
|
||||||
|
|
||||||
|
const newDownloadButton = document.createElement('a');
|
||||||
|
newDownloadButton.id = "nyakonya-gelbooruocdw-geter";
|
||||||
|
newDownloadButton.title = "Download original image";
|
||||||
|
newDownloadButton.innerHTML = downloadSvgIcon;
|
||||||
|
newDownloadButton.className = existingAnchor.className;
|
||||||
|
newDownloadButton.style.cssText = existingAnchor.style.cssText;
|
||||||
|
existingAnchor.parentNode.insertBefore(newDownloadButton, existingAnchor.nextSibling);
|
||||||
|
|
||||||
|
const searchBox = document.getElementById("tags-search");
|
||||||
|
if (searchBox) {
|
||||||
|
searchBox.style.width = "calc(100% - 380px)";
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Кнопка для скачивания добавлена:', newDownloadButton);
|
||||||
|
newDownloadButton.addEventListener('click', (event) => {
|
||||||
|
event.preventDefault(); // Отменяем стандартное действие ссылки
|
||||||
|
|
||||||
|
// Получаем настроенный пользователем корневой путь
|
||||||
|
const apiRoot = GM_getValue('nyakonya_gb_api_root', 'http://127.0.2.1');
|
||||||
|
// Формируем корректный URL для запроса к dw_api
|
||||||
|
const apiUrl = apiRoot.endsWith('/') ? `${apiRoot}dw_api` : `${apiRoot}/api`;
|
||||||
|
|
||||||
|
console.log(`Отправка URL на локальный API: ${imageUrl} (Endpoint: ${apiUrl})`);
|
||||||
|
const originalOutline = newDownloadButton.style.outline;
|
||||||
|
newDownloadButton.style.outline = "2px solid yellow"; // Статус "в процессе"
|
||||||
|
|
||||||
|
GM_xmlhttpRequest({
|
||||||
|
method: "POST",
|
||||||
|
url: apiUrl,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
data: JSON.stringify({ id: imageID , type: "download"}),
|
||||||
|
onload: function(response) {
|
||||||
|
console.log('Ответ от API:', response.responseText);
|
||||||
|
newDownloadButton.style.outline = "2px solid green"; // Успех
|
||||||
|
setTimeout(() => { newDownloadButton.style.outline = originalOutline; }, 2000);
|
||||||
|
},
|
||||||
|
onerror: function(response) {
|
||||||
|
console.error('Ошибка при отправке на API:', response);
|
||||||
|
newDownloadButton.style.outline = "2px solid red"; // Ошибка
|
||||||
|
alert('Не удалось отправить на локальный загрузчик. Убедитесь, что Python-скрипт запущен и вы приняли самоподписанный сертификат в браузере. Подробности в консоли (F12).');
|
||||||
|
setTimeout(() => { newDownloadButton.style.outline = originalOutline; }, 5000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
} else {
|
||||||
|
console.warn('Исходный элемент для вставки кнопки (saveTagSearch) не найден.');
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"server":{
|
||||||
|
"host":"127.0.2.1",
|
||||||
|
"port":80,
|
||||||
|
"count_page":25,
|
||||||
|
"thumb_size":250
|
||||||
|
},
|
||||||
|
"gb":{
|
||||||
|
"id":"",
|
||||||
|
"hash":"",
|
||||||
|
"headers":{
|
||||||
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||||
|
"Referer": "https://gelbooru.com/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"file":{
|
||||||
|
"repos":["data/files"],
|
||||||
|
"dw":"data/files",
|
||||||
|
"thumb":"data/thumb",
|
||||||
|
"data":"data"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
### 0.2.0b
|
||||||
|
|
||||||
|
> **Fixes**
|
||||||
|
|
||||||
|
1. Added 404 error handling when the source file is not found.
|
||||||
|
|
||||||
|
> **Changes**
|
||||||
|
|
||||||
|
1. Merged `/dw_api` and `/api` into a single `/api` endpoint.
|
||||||
|
|
||||||
|
> **New**
|
||||||
|
|
||||||
|
1. Added a system module for background tasks.
|
||||||
|
2. Added an analytics page.
|
||||||
|
|
||||||
|
> **Code**
|
||||||
|
|
||||||
|
1. Deleted the legacy `db_old.py` file.
|
||||||
|
2. Sorted and refactored imports.
|
||||||
|
3. Added type hinting for input data in `system_module` functions.
|
||||||
|
4. Removed `data/analytic.json`.
|
||||||
|
5. Updated the logic for retrieving popular tags to support analytics.
|
||||||
|
- 5.1. Renamed `get_autocomplete` function to `get_top_tags`.
|
||||||
|
- 5.2. Added an optional `limit` argument to the `get_top_tags` function.
|
||||||
|
6. Removed the `get_binary_file()` function from the `gelbooru` module as it was unused.
|
||||||
|
7. Refactored the logging module.
|
||||||
|
8. Added comprehensive error logging.
|
||||||
|
9. Added the `/task` endpoint.
|
||||||
|
10. Implemented new logic for passing the database path via the configuration file.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
### 0.2.0b
|
||||||
|
|
||||||
|
> **Иправления**
|
||||||
|
|
||||||
|
1. Добавлен вывод 404 если исходный файл не найден
|
||||||
|
|
||||||
|
> **Изменения**
|
||||||
|
|
||||||
|
1. /dw_api и /api объединены в /api
|
||||||
|
|
||||||
|
> **Новое**
|
||||||
|
|
||||||
|
1. Системный модуль с задачами
|
||||||
|
2. Страница с аналитикой
|
||||||
|
|
||||||
|
> **Код**
|
||||||
|
|
||||||
|
1. Удалён старый файл db_old.py
|
||||||
|
2. Отсортированы и изменены импорты
|
||||||
|
3. Добавлена типизация входных данных в функции расположенные в system_module
|
||||||
|
4. Удалён data/analytic.json
|
||||||
|
5. Изменена логика получения списка популярных тегов для адаптации к аналитике
|
||||||
|
- 5.1. Функция get_autocomplete переименована в get_top_tag
|
||||||
|
- 5.1. Для функции get_top_tag добален необязательный аргумент для лимита выдачи
|
||||||
|
6. Функция get_binary_file() из модуля gelbooru удалена из-за отсусвия факта использования
|
||||||
|
7. Переписан модуль логов
|
||||||
|
8. Добавлено полное логирование ошибок
|
||||||
|
9. Добавлен эндпойнт /task
|
||||||
|
10. Новая логика передачи пути к базе данных через конфиг
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
@@ -0,0 +1,67 @@
|
|||||||
|
# Installation Guide
|
||||||
|
|
||||||
|
## System Requirements
|
||||||
|
|
||||||
|
- **OS:** Windows 10+, macOS 10.13+, Linux kernel 3.x+
|
||||||
|
- **RAM:** 512 MB or higher
|
||||||
|
- **Disk Space:** 512 MB minimum + additional space for data
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Python 3.13.13 or higher
|
||||||
|
- ffmpeg 2026-01-29 (required if you intend to store video files)
|
||||||
|
- git (optional)
|
||||||
|
|
||||||
|
## Instructions
|
||||||
|
|
||||||
|
Once you have installed the required software, you need to configure the booru.
|
||||||
|
|
||||||
|
### Downloading the package
|
||||||
|
|
||||||
|
You have two options depending on whether you have git installed:
|
||||||
|
|
||||||
|
#### Using CLI (recommended)
|
||||||
|
Run the following command in the folder where the site will be located:
|
||||||
|
`git clone https://git.nekono.su/Nyako/Local-Booru.git .`
|
||||||
|
|
||||||
|
#### Using the website
|
||||||
|
1. Download the archive by clicking the buttons shown below:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
2. Extract the archive into the folder where the site will be hosted.
|
||||||
|
|
||||||
|
### Installing dependencies
|
||||||
|
|
||||||
|
In the terminal, navigate to the folder where the site is located and run:
|
||||||
|
`pip install -r requirements.txt`
|
||||||
|
|
||||||
|
### Configuring `config.json`
|
||||||
|
|
||||||
|
Config explanation:
|
||||||
|
|
||||||
|
| Key | Default | Description |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `server`-`host` | `"127.0.2.1"` | Server host address |
|
||||||
|
| `server`-`port` | `80` | Server port |
|
||||||
|
| `server`-`count_page` | `25` | Number of items per page |
|
||||||
|
| `server`-`thumb_size` | `250` | Thumbnail size (pixels, long side) |
|
||||||
|
| `gb`-`id` | `""` | Gelbooru User ID |
|
||||||
|
| `gb`-`hash` | `""` | Gelbooru User Hash |
|
||||||
|
| `file`-`repos` | `["data/files"]` | List of directories where source files are stored |
|
||||||
|
| `file`-`dw` | `"data/files"` | Directory for new downloads |
|
||||||
|
| `file`-`thumb` | `"data/thumb"` | Directory for thumbnails |
|
||||||
|
| `file`-`data` | `"data"` | Directory for database |
|
||||||
|
|
||||||
|
1. You must obtain your Gelbooru User ID and Hash and add them to the config file for the system to function correctly.
|
||||||
|
2. Install the script in [VioletMonkey](https://git.nekono.su/Nyako/Local-Booru/raw/branch/main/button_script.user.js).
|
||||||
|
|
||||||
|
#### If you changed the Host or Port:
|
||||||
|
- Open any post.
|
||||||
|
- Update the base URL in the script configuration to match your custom settings.
|
||||||
|
|
||||||
|
### Launch
|
||||||
|
|
||||||
|
Simply run: `python run.py`
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# Инструкция по установке
|
||||||
|
|
||||||
|
## Системные требования
|
||||||
|
|
||||||
|
- **OC:** Windows 10+, macOS 10.13+, Linux kernel 3.x+
|
||||||
|
- **ОЗУ:** 512 МБ и выше
|
||||||
|
- **Диск:** 512 МБ минимум + место под данные
|
||||||
|
|
||||||
|
## Требуеться заранее установить
|
||||||
|
|
||||||
|
- Python 3.13.13 и выше
|
||||||
|
- ffmpeg 2026-01-29 (Если вы будете хранить видео)
|
||||||
|
- git (по желанию)
|
||||||
|
|
||||||
|
## Инструкиция
|
||||||
|
|
||||||
|
Приготовив все программы вам надо настроить booru
|
||||||
|
|
||||||
|
### Скачиваем пакет
|
||||||
|
|
||||||
|
У вас есть два варианта в зависимости от установленного git
|
||||||
|
|
||||||
|
#### Используя CLI сделать в папке где будет размещен сайт
|
||||||
|
|
||||||
|
`git clone https://git.nekono.su/Nyako/Local-Booru.git .`
|
||||||
|
|
||||||
|
#### Используя веб-сайт
|
||||||
|
|
||||||
|
1. Скачиваем архив по кнопке:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
2. Делаем распаковку в папку где будет сайт
|
||||||
|
|
||||||
|
### Производим установку зависимостей
|
||||||
|
|
||||||
|
Используя CLI сделать в папке где будет размещен сайт:
|
||||||
|
`pip install -r requirements.txt`
|
||||||
|
|
||||||
|
### Делаем конфигурацию файла config.json
|
||||||
|
|
||||||
|
Объяснение конфига:
|
||||||
|
|
||||||
|
| Ключ | По умолчанию | Пояснение |
|
||||||
|
|----------|----------|----------|
|
||||||
|
| `server`-`host` | `"127.0.2.1"` | Хост запуска сервера |
|
||||||
|
| `server`-`port` | `80` | Порт запуска сервера |
|
||||||
|
| `server`-`count_page` | `25` | Количество элементов на странице |
|
||||||
|
| `server`-`thumb_size` | `250` | Размер превью в пикселях по широкой стороне |
|
||||||
|
| `gb`-`id` | `""` | ID пользователя Gelbooru |
|
||||||
|
| `gb`-`hash` | `""` | Hash пользователя Gelbooru |
|
||||||
|
| `file`-`repos` | `["data/files"]` | Список каталогов где храняться полные файлы |
|
||||||
|
| `file`-`dw` | `"data/files"` | Каталог хранения загрузок |
|
||||||
|
| `file`-`thumb` | `"data/thumb"` | Каталог обложек |
|
||||||
|
| `file`-`data` | `"data"` | Каталог базы данных |
|
||||||
|
|
||||||
|
1. Обязательно надо получить ID и Hash пользователя и внести в конфиг для работы!
|
||||||
|
|
||||||
|
2. Установить скрипт в [VioletMonkey](https://git.nekono.su/Nyako/Local-Booru/raw/branch/main/button_script.user.js)
|
||||||
|
|
||||||
|
#### Если вы меняли Host или Port
|
||||||
|
- Открыть любой пост
|
||||||
|
- Ввести корневой путь в конфигурации скрипта на тот что у вас
|
||||||
|
|
||||||
|
### Запуск
|
||||||
|
|
||||||
|
Просто выполните `python run.py`
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
## Remarque
|
||||||
|
|
||||||
|
Version Naming Rules:
|
||||||
|
|
||||||
|
[Version Code][Version Type]
|
||||||
|
|
||||||
|
All technical versions are designated as snapshots (s)
|
||||||
|
|
||||||
|
All test versions are designated as beta (b)
|
||||||
|
|
||||||
|
All pre-release and release versions are designated as release candidate and release (rc, r)
|
||||||
|
|
||||||
|
## AI Usage Disclaimer
|
||||||
|
|
||||||
|
Files in the "template" folder may be entirely or partially generated by AI.
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# Local-Booru
|
## Ремарка
|
||||||
|
|
||||||
Правила найменования версий:
|
Правила найменования версий:
|
||||||
|
|
||||||
@@ -6,6 +6,10 @@
|
|||||||
|
|
||||||
Все технические версии обозначаються как снапшоты (s)
|
Все технические версии обозначаються как снапшоты (s)
|
||||||
|
|
||||||
Все тестовые версии обозначаються как альфа и бета (a, b)
|
Все тестовые версии обозначаються как бета (b)
|
||||||
|
|
||||||
Все предрелизны и релизные версии обозначаються как кандидат в релиз и релиз (rc, r)
|
Все предрелизны и релизные версии обозначаються как кандидат в релиз и релиз (rc, r)
|
||||||
|
|
||||||
|
## Уведомление о использовании ИИ
|
||||||
|
|
||||||
|
Файлы в папке "template" могут быть целиком либо частично сгенерированы ИИ
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
blinker==1.9.0
|
||||||
|
certifi==2026.5.20
|
||||||
|
charset-normalizer==3.4.7
|
||||||
|
click==8.4.1
|
||||||
|
colorama==0.4.6
|
||||||
|
Flask==3.1.3
|
||||||
|
idna==3.17
|
||||||
|
itsdangerous==2.2.0
|
||||||
|
Jinja2==3.1.6
|
||||||
|
MarkupSafe==3.0.3
|
||||||
|
pillow==12.2.0
|
||||||
|
requests==2.34.2
|
||||||
|
urllib3==2.7.0
|
||||||
|
Werkzeug==3.1.8
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import traceback
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import requests
|
||||||
|
from flask import (Flask, jsonify, render_template, render_template_string,
|
||||||
|
request, send_from_directory, make_response, send_file)
|
||||||
|
|
||||||
|
from system_module import db, gelbooru, image_processor, logger, tasks
|
||||||
|
|
||||||
|
if Path("config_gb.json").exists():
|
||||||
|
CONFIG_FILE = "config_gb.json"
|
||||||
|
else:
|
||||||
|
CONFIG_FILE = "config.json"
|
||||||
|
|
||||||
|
CONFIG_ROOT = json.load(open(CONFIG_FILE, "r", encoding="utf-8"))
|
||||||
|
CONFIG_HOST = CONFIG_ROOT["server"]["host"]
|
||||||
|
CONFIG_PORT = CONFIG_ROOT["server"]["port"]
|
||||||
|
PAGINATION_COUNT = CONFIG_ROOT["server"]["count_page"]
|
||||||
|
TARGET_MIN_SIZE = CONFIG_ROOT["server"]["thumb_size"]
|
||||||
|
GB_ID = CONFIG_ROOT["gb"]["id"]
|
||||||
|
GB_HASH = CONFIG_ROOT["gb"]["hash"]
|
||||||
|
GB_HEADERS = CONFIG_ROOT["gb"]["headers"]
|
||||||
|
FILE_FOLDERS = CONFIG_ROOT["file"]["repos"]
|
||||||
|
FILE_DW_FOLDERS = CONFIG_ROOT["file"]["dw"]
|
||||||
|
THUMB_FOLDER = CONFIG_ROOT["file"]["thumb"]
|
||||||
|
DATA_FOLDER = CONFIG_ROOT["file"]["data"]
|
||||||
|
|
||||||
|
|
||||||
|
gb = gelbooru.GB(GB_ID, GB_HASH, GB_HEADERS, FILE_DW_FOLDERS)
|
||||||
|
log = logger.Logger()
|
||||||
|
log.init_global_exception_hook()
|
||||||
|
database = db.DB(DATA_FOLDER)
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
if not image_processor.check_ffmpeg(): print("WARNING!\n\nУ вас не установлен ffmpeg. Генерация превью для видео не доступна!")
|
||||||
|
|
||||||
|
@app.route("/")
|
||||||
|
def index():
|
||||||
|
return render_template("index.html")
|
||||||
|
|
||||||
|
@app.route("/analytics")
|
||||||
|
def analytics():
|
||||||
|
return render_template("analytics.html")
|
||||||
|
|
||||||
|
@app.route("/task")
|
||||||
|
def task():
|
||||||
|
return render_template("task.html")
|
||||||
|
|
||||||
|
@app.route("/post/<path:post_id>")
|
||||||
|
def post(post_id):
|
||||||
|
return render_template("post.html")
|
||||||
|
|
||||||
|
@app.route('/file/<path:filename>')
|
||||||
|
def serve_image(filename):
|
||||||
|
folder_path = tasks.find_file(filename, FILE_FOLDERS)
|
||||||
|
print(filename, FILE_FOLDERS)
|
||||||
|
if folder_path == None:
|
||||||
|
return make_response("Not found", 404)
|
||||||
|
else:
|
||||||
|
return send_from_directory(folder_path, filename)
|
||||||
|
|
||||||
|
@app.route('/thumb/<path:filename>')
|
||||||
|
def serve_thumb(filename):
|
||||||
|
return send_from_directory(THUMB_FOLDER, filename)
|
||||||
|
|
||||||
|
@app.route("/api", methods=["GET", "POST"])
|
||||||
|
def api():
|
||||||
|
data = request.get_json()
|
||||||
|
if data["type"] == "search":
|
||||||
|
search_query = data["query"]
|
||||||
|
search_rating = data["rating"]
|
||||||
|
if search_query == "" and search_rating == "e+q+s+g":
|
||||||
|
results = database.get_all()
|
||||||
|
else:
|
||||||
|
search_query = search_query.split(" ")
|
||||||
|
search_rating = search_rating.split("+")
|
||||||
|
results = database.get_search(search_rating, search_query)
|
||||||
|
if len(results) <= PAGINATION_COUNT:
|
||||||
|
results_send = {"results_info":{"total":len(results), "page":int(data["page"]), "count_page":PAGINATION_COUNT}, "results":results}
|
||||||
|
return jsonify(results_send)
|
||||||
|
else:
|
||||||
|
results_slile = results[int(data["page"])*PAGINATION_COUNT:(int(data["page"])+1)*PAGINATION_COUNT]
|
||||||
|
results_send = {"results_info":{"total":len(results), "page":int(data["page"]), "count_page":PAGINATION_COUNT}, "results":results_slile}
|
||||||
|
return jsonify(results_send)
|
||||||
|
elif data["type"] == "autocomplete":
|
||||||
|
tag_slise = data["q"]
|
||||||
|
result_autocomplete = database.get_top_tag(tag_slise, count_tag_get=10)
|
||||||
|
return jsonify(result_autocomplete)
|
||||||
|
elif data["type"] == "post":
|
||||||
|
post_id = data["post_id"]
|
||||||
|
result_post = database.get_from_id(post_id)
|
||||||
|
return jsonify(result_post)
|
||||||
|
elif data["type"] == "analytic":
|
||||||
|
return send_file(os.path.join(DATA_FOLDER, "analytic.json"), mimetype="application/json")
|
||||||
|
elif data["type"] == "task":
|
||||||
|
if data["task"] == "analytic":
|
||||||
|
if tasks.calculate_analytic(database, CONFIG_ROOT):
|
||||||
|
return "", 200
|
||||||
|
else:
|
||||||
|
return "", 500
|
||||||
|
if data["task"] == "not_found_file":
|
||||||
|
list_md5_not_found = tasks.get_files_not_found(database, CONFIG_ROOT)
|
||||||
|
return jsonify({'list': list_md5_not_found}), 200
|
||||||
|
elif data["type"] == "download":
|
||||||
|
if not data or 'id' not in data:
|
||||||
|
return jsonify({'status': 'error', 'message': 'URL not get'}), 400
|
||||||
|
image_id = data["id"]
|
||||||
|
try:
|
||||||
|
data_get, url_file, file_name = gb.get_from_id(image_id)
|
||||||
|
if database.check_uni(data_get["md5"]):
|
||||||
|
message = f"File '{file_name}' already exists. Skipping."
|
||||||
|
log.send("warning", "all", message)
|
||||||
|
return jsonify({'status': 'skipped', 'message': message})
|
||||||
|
with requests.get(url_file, stream=True, headers=GB_HEADERS, timeout=30) as r:
|
||||||
|
r.raise_for_status()
|
||||||
|
content_type = r.headers.get('Content-Type', '')
|
||||||
|
if 'text/html' in content_type:
|
||||||
|
log.send("error", "all", "The server returned HTML instead of an image. Bot protection.")
|
||||||
|
return False
|
||||||
|
with open(FILE_DW_FOLDERS+"/"+file_name, 'wb') as f:
|
||||||
|
for chunk in r.iter_content(chunk_size=8192):
|
||||||
|
f.write(chunk)
|
||||||
|
database.add_raw(data_get)
|
||||||
|
res_data = image_processor.generate_thumb(FILE_DW_FOLDERS+"/"+file_name, THUMB_FOLDER, TARGET_MIN_SIZE)
|
||||||
|
if not res_data["status"]:
|
||||||
|
print(res_data["message"])
|
||||||
|
return jsonify({'status': 'success'})
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
error_message = f"Network error {image_id}: {e}"
|
||||||
|
log.send("error", "all", error_message)
|
||||||
|
return jsonify({'status': 'error', 'message': error_message}), 500
|
||||||
|
except Exception as e:
|
||||||
|
traceback.print_exc()
|
||||||
|
error_message = f"Unknown error: {e}"
|
||||||
|
log.send("error", "all", error_message)
|
||||||
|
return jsonify({'status': 'error', 'message': error_message}), 500
|
||||||
|
else:
|
||||||
|
pass
|
||||||
|
return "", 204
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app.run(host=CONFIG_HOST, port=CONFIG_PORT)
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from system_module.gelbooru import gelbooru_date_parse
|
||||||
|
|
||||||
|
|
||||||
|
class DB:
|
||||||
|
def __init__(self, db_path: str):
|
||||||
|
|
||||||
|
if not os.path.exists(db_path):
|
||||||
|
os.makedirs(db_path)
|
||||||
|
|
||||||
|
self.conn = sqlite3.connect(os.path.join(db_path, "db.sqlite"), check_same_thread=False)
|
||||||
|
self.conn.row_factory = sqlite3.Row
|
||||||
|
self._create_table()
|
||||||
|
|
||||||
|
def _create_table(self):
|
||||||
|
with self.conn:
|
||||||
|
self.conn.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS files (
|
||||||
|
md5 TEXT PRIMARY KEY,
|
||||||
|
local_filename TEXT,
|
||||||
|
is_video INTEGER,
|
||||||
|
is_gif INTEGER,
|
||||||
|
tags TEXT,
|
||||||
|
rating TEXT,
|
||||||
|
score INTEGER,
|
||||||
|
timestamp TEXT,
|
||||||
|
parsed_time INTEGER,
|
||||||
|
display_date TEXT,
|
||||||
|
source TEXT,
|
||||||
|
width INTEGER,
|
||||||
|
height INTEGER
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
def _row_to_dict(self, row: sqlite3.Row) -> dict:
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
d = dict(row)
|
||||||
|
d["is_video"] = bool(d["is_video"])
|
||||||
|
d["is_gif"] = bool(d["is_gif"])
|
||||||
|
|
||||||
|
# Парсинг тегов из JSON-строки обратно в массив
|
||||||
|
d["tags"] = json.loads(d["tags"]) if d["tags"] else []
|
||||||
|
|
||||||
|
# Восстанавливаем другие поля (например, display_date и source),
|
||||||
|
# если в них были переданы кортежи или списки
|
||||||
|
for field in ["display_date", "source"]:
|
||||||
|
val = d.get(field)
|
||||||
|
if isinstance(val, str) and (val.startswith('[') or val.startswith('{')):
|
||||||
|
try:
|
||||||
|
d[field] = json.loads(val)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return d
|
||||||
|
|
||||||
|
def add(self, data_add: dict):
|
||||||
|
parsed_time = 0
|
||||||
|
if "timestamp" in data_add:
|
||||||
|
try:
|
||||||
|
parsed_time = int(datetime.strptime(data_add["timestamp"], "%a %b %d %H:%M:%S %z %Y").timestamp())
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
row_data = {
|
||||||
|
"md5": data_add.get("md5"),
|
||||||
|
"local_filename": data_add.get("local_filename", data_add.get("image")),
|
||||||
|
"is_video": int(data_add.get("is_video", False)),
|
||||||
|
"is_gif": int(data_add.get("is_gif", False)),
|
||||||
|
"tags": data_add.get("tags", []),
|
||||||
|
"rating": data_add.get("rating"),
|
||||||
|
"score": data_add.get("score"),
|
||||||
|
"timestamp": data_add.get("timestamp", data_add.get("created_at")),
|
||||||
|
"parsed_time": parsed_time,
|
||||||
|
"display_date": data_add.get("display_date"),
|
||||||
|
"source": data_add.get("source"),
|
||||||
|
"width": data_add.get("width"),
|
||||||
|
"height": data_add.get("height")
|
||||||
|
}
|
||||||
|
|
||||||
|
# БЕЗОПАСНАЯ СЕРИАЛИЗАЦИЯ ДЛЯ SQLITE:
|
||||||
|
# SQLite принимает только числа, строки и байты.
|
||||||
|
# Любые списки (tags) или кортежи (display_date) мы перегоняем в JSON.
|
||||||
|
for key, value in row_data.items():
|
||||||
|
if isinstance(value, (list, tuple, dict)):
|
||||||
|
row_data[key] = json.dumps(value)
|
||||||
|
|
||||||
|
columns = ", ".join(row_data.keys())
|
||||||
|
placeholders = ", ".join(["?"] * len(row_data))
|
||||||
|
|
||||||
|
with self.conn:
|
||||||
|
self.conn.execute(
|
||||||
|
f"INSERT OR REPLACE INTO files ({columns}) VALUES ({placeholders})",
|
||||||
|
tuple(row_data.values())
|
||||||
|
)
|
||||||
|
|
||||||
|
def add_raw(self, data_add: dict):
|
||||||
|
is_video = data_add["image"].split(".")[-1] in ["webm", "mp4", "avi"]
|
||||||
|
is_gif = data_add["image"].split(".")[-1] == "gif"
|
||||||
|
|
||||||
|
dt_obj = datetime.strptime(data_add["created_at"], "%a %b %d %H:%M:%S %z %Y")
|
||||||
|
parsed_time = int(dt_obj.timestamp())
|
||||||
|
|
||||||
|
add_data = {
|
||||||
|
"md5": data_add["md5"],
|
||||||
|
"local_filename": data_add["image"],
|
||||||
|
"is_video": is_video,
|
||||||
|
"is_gif": is_gif,
|
||||||
|
"tags": data_add["tags"].split(" "),
|
||||||
|
"rating": data_add["rating"],
|
||||||
|
"score": data_add["score"],
|
||||||
|
"timestamp": data_add["created_at"],
|
||||||
|
"parsed_time": parsed_time,
|
||||||
|
"display_date": gelbooru_date_parse(data_add["created_at"]),
|
||||||
|
"source": data_add["source"],
|
||||||
|
"width": data_add["width"],
|
||||||
|
"height": data_add["height"]
|
||||||
|
}
|
||||||
|
self.add(add_data)
|
||||||
|
|
||||||
|
def get_all(self):
|
||||||
|
cursor = self.conn.execute("SELECT * FROM files ORDER BY parsed_time DESC")
|
||||||
|
return [self._row_to_dict(row) for row in cursor.fetchall()]
|
||||||
|
|
||||||
|
def get_search(self, rating_tmp: list[str], tags: list[str]):
|
||||||
|
mapping_rating = {
|
||||||
|
"e": "explicit",
|
||||||
|
"g": "general",
|
||||||
|
"s": "sensitive",
|
||||||
|
"q": "questionable"
|
||||||
|
}
|
||||||
|
|
||||||
|
query = "SELECT * FROM files WHERE 1=1"
|
||||||
|
params = []
|
||||||
|
|
||||||
|
ratings = [mapping_rating.get(x, x) for x in rating_tmp if x]
|
||||||
|
if ratings:
|
||||||
|
placeholders = ",".join("?" * len(ratings))
|
||||||
|
query += f" AND rating IN ({placeholders})"
|
||||||
|
params.extend(ratings)
|
||||||
|
|
||||||
|
tags = [t for t in tags if t]
|
||||||
|
if tags:
|
||||||
|
for tag in tags:
|
||||||
|
query += " AND EXISTS (SELECT 1 FROM json_each(files.tags) WHERE value = ?)"
|
||||||
|
params.append(tag)
|
||||||
|
|
||||||
|
query += " ORDER BY parsed_time DESC"
|
||||||
|
|
||||||
|
cursor = self.conn.execute(query, tuple(params))
|
||||||
|
return [self._row_to_dict(row) for row in cursor.fetchall()]
|
||||||
|
|
||||||
|
def get_unknow(self):
|
||||||
|
cursor = self.conn.execute("SELECT * FROM files WHERE tags = '[]' OR tags IS NULL")
|
||||||
|
return [self._row_to_dict(row) for row in cursor.fetchall()]
|
||||||
|
|
||||||
|
def check_uni(self, md5: str):
|
||||||
|
query = "SELECT 1 FROM files WHERE md5 = ? LIMIT 1"
|
||||||
|
cursor = self.conn.execute(query, (md5,))
|
||||||
|
return cursor.fetchone() is not None
|
||||||
|
|
||||||
|
def get_top_tag(self, tag_slise: str, count_tag_get: int = 9999999):
|
||||||
|
query = """
|
||||||
|
SELECT value AS tag, COUNT(*) AS count
|
||||||
|
FROM files, json_each(files.tags)
|
||||||
|
WHERE value LIKE ?
|
||||||
|
GROUP BY value
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT {count_tag_get}
|
||||||
|
""".format(count_tag_get=count_tag_get)
|
||||||
|
cursor = self.conn.execute(query, (f"{tag_slise.lower()}%",))
|
||||||
|
return [{"tag": row["tag"], "count": row["count"]} for row in cursor.fetchall()]
|
||||||
|
|
||||||
|
def edit_data(self, id_file: str, edit_data: dict):
|
||||||
|
if not edit_data:
|
||||||
|
return
|
||||||
|
|
||||||
|
set_clauses = []
|
||||||
|
params = []
|
||||||
|
|
||||||
|
for key, value in edit_data.items():
|
||||||
|
# Если передаем списки/кортежи, пакуем в JSON
|
||||||
|
if isinstance(value, (list, tuple, dict)):
|
||||||
|
value = json.dumps(value)
|
||||||
|
|
||||||
|
set_clauses.append(f"{key} = ?")
|
||||||
|
|
||||||
|
if key == "timestamp":
|
||||||
|
params.append(value)
|
||||||
|
try:
|
||||||
|
set_clauses.append("parsed_time = ?")
|
||||||
|
params.append(int(datetime.strptime(value, "%a %b %d %H:%M:%S %z %Y").timestamp()))
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
params.append(value)
|
||||||
|
|
||||||
|
params.append(id_file)
|
||||||
|
|
||||||
|
query = f"UPDATE files SET {', '.join(set_clauses)} WHERE md5 = ?"
|
||||||
|
with self.conn:
|
||||||
|
self.conn.execute(query, tuple(params))
|
||||||
|
|
||||||
|
def get_from_id(self, id_file: str):
|
||||||
|
cursor = self.conn.execute("SELECT * FROM files WHERE md5 = ?", (id_file,))
|
||||||
|
return self._row_to_dict(cursor.fetchone())
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.conn.close()
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import os
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
|
||||||
|
def gelbooru_date_parse(date_str: str):
|
||||||
|
if not date_str:
|
||||||
|
return 0, "Unknown"
|
||||||
|
try:
|
||||||
|
dt = datetime.strptime(date_str, "%a %b %d %H:%M:%S %z %Y")
|
||||||
|
return dt.timestamp(), dt.strftime("%Y-%m-%d")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка парсинга даты '{date_str}': {e}")
|
||||||
|
return 0, "Unknown"
|
||||||
|
|
||||||
|
class GB:
|
||||||
|
def __init__(self, api_id: str, api_hash: str, headers: dict[str, str], dw_folder: str):
|
||||||
|
self.api_id = api_id
|
||||||
|
self.api_hash = api_hash
|
||||||
|
self.dw_folder = dw_folder
|
||||||
|
self.root_url = "https://gelbooru.com/index.php"
|
||||||
|
self.HEADERS = headers
|
||||||
|
|
||||||
|
def get_from_id(self, id_post: int):
|
||||||
|
params = {"page": "dapi", "s": "post", "q": "index", "json": 1, "id": id_post, "api_key":self.api_hash, "user_id":self.api_id}
|
||||||
|
response = requests.get(self.root_url, params=params, headers=self.HEADERS, timeout=15)
|
||||||
|
print(response.url)
|
||||||
|
url_file = response.json()["post"][0]["file_url"]
|
||||||
|
file_name = response.json()["post"][0]["image"]
|
||||||
|
return response.json()["post"][0], url_file, file_name
|
||||||
|
|
||||||
|
def get_from_md5(self, md5: str):
|
||||||
|
params = {"page": "dapi", "s": "post", "q": "index", "json": 1, "tags":"md5:"+md5, "api_key":self.api_hash, "user_id":self.api_id}
|
||||||
|
response = requests.get(self.root_url, params=params, headers=self.HEADERS, timeout=15)
|
||||||
|
print(response.url)
|
||||||
|
url_file = response.json()["post"][0]["file_url"]
|
||||||
|
file_name = response.json()["post"][0]["image"]
|
||||||
|
return response.json()["post"][0], url_file, file_name
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
EXTENSIONS_IMG = ('jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp')
|
||||||
|
EXTENSIONS_VID = ('mp4', 'webm')
|
||||||
|
VALID_EXTENSIONS = EXTENSIONS_IMG + EXTENSIONS_VID
|
||||||
|
|
||||||
|
def check_ffmpeg():
|
||||||
|
try:
|
||||||
|
if os.name == 'nt': creationflags = subprocess.CREATE_NO_WINDOW
|
||||||
|
else: creationflags = 0
|
||||||
|
subprocess.run(["ffmpeg", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, creationflags=creationflags)
|
||||||
|
return True
|
||||||
|
except (FileNotFoundError, subprocess.CalledProcessError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def video_gen(input_path_file: str, output_path_file: str, TARGET_MIN_SIZE: int):
|
||||||
|
vf_scale = f"scale='if(gt(iw,ih),-1,{TARGET_MIN_SIZE})':'if(gt(iw,ih),{TARGET_MIN_SIZE},-1)'"
|
||||||
|
cmd = ["ffmpeg", "-y", "-i", input_path_file, "-ss", "00:00:00", "-vframes", "1", "-vf", vf_scale, "-q:v", "2", output_path_file]
|
||||||
|
if os.name == 'nt': creationflags = subprocess.CREATE_NO_WINDOW
|
||||||
|
else: creationflags = 0
|
||||||
|
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags)
|
||||||
|
if result.returncode != 0:
|
||||||
|
raise Exception(f"FFmpeg error: {result.stderr.decode('utf-8', errors='ignore')}")
|
||||||
|
|
||||||
|
def image_and_gif_gen(input_path_file: str, output_path_file: str, TARGET_MIN_SIZE: int):
|
||||||
|
with Image.open(input_path_file) as img:
|
||||||
|
img_rgba = img.convert("RGBA")
|
||||||
|
background = Image.new("RGB", img_rgba.size, (255, 255, 255))
|
||||||
|
background.paste(img_rgba, mask=img_rgba)
|
||||||
|
final_img = background
|
||||||
|
width, height = final_img.size
|
||||||
|
if width <= TARGET_MIN_SIZE and height <= TARGET_MIN_SIZE:
|
||||||
|
final_img.save(output_path_file, "JPEG", quality=90)
|
||||||
|
else:
|
||||||
|
if width < height:
|
||||||
|
new_width = TARGET_MIN_SIZE
|
||||||
|
new_height = int(TARGET_MIN_SIZE * (height / width))
|
||||||
|
else:
|
||||||
|
new_height = TARGET_MIN_SIZE
|
||||||
|
new_width = int(TARGET_MIN_SIZE * (width / height))
|
||||||
|
resized_img = final_img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
||||||
|
resized_img.save(output_path_file, "JPEG", quality=85)
|
||||||
|
|
||||||
|
def generate_thumb(input_path_file: str, THUMB_FOLDER: str, TARGET_MIN_SIZE: int):
|
||||||
|
ext_file = input_path_file.split(".")[-1]
|
||||||
|
if ext_file not in VALID_EXTENSIONS:
|
||||||
|
return {"status":False, "message":"Расширение не поддерживаеться!"}
|
||||||
|
thumb_filename = f"{os.path.basename(input_path_file).split(".")[-2]}.jpg"
|
||||||
|
output_path_file = os.path.join(THUMB_FOLDER, thumb_filename)
|
||||||
|
if ext_file in EXTENSIONS_IMG:
|
||||||
|
image_and_gif_gen(input_path_file, output_path_file, TARGET_MIN_SIZE)
|
||||||
|
return {"status":True}
|
||||||
|
else:
|
||||||
|
if not check_ffmpeg(): return {"status":False, "message":"ffmpeg не установлен!"}
|
||||||
|
video_gen(input_path_file, output_path_file, TARGET_MIN_SIZE)
|
||||||
|
return {"status":True}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import sys
|
||||||
|
import logging
|
||||||
|
|
||||||
|
class Logger:
|
||||||
|
def __init__(self):
|
||||||
|
self.logger = logging.getLogger(__name__)
|
||||||
|
self.logger.setLevel(logging.DEBUG)
|
||||||
|
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
|
||||||
|
|
||||||
|
file_handler = logging.FileHandler("logs.log", encoding="utf-8")
|
||||||
|
file_handler.setLevel(logging.DEBUG)
|
||||||
|
file_handler.setFormatter(formatter)
|
||||||
|
|
||||||
|
console_handler = logging.StreamHandler()
|
||||||
|
console_handler.setLevel(logging.DEBUG)
|
||||||
|
console_handler.setFormatter(formatter)
|
||||||
|
|
||||||
|
self.logger.addHandler(file_handler)
|
||||||
|
self.logger.addHandler(console_handler)
|
||||||
|
|
||||||
|
def init_global_exception_hook(self):
|
||||||
|
def handle_exception(exc_type, exc_value, exc_traceback):
|
||||||
|
if issubclass(exc_type, KeyboardInterrupt):
|
||||||
|
sys.__excepthook__(
|
||||||
|
exc_type,
|
||||||
|
exc_value,
|
||||||
|
exc_traceback
|
||||||
|
)
|
||||||
|
return
|
||||||
|
self.logger.critical("ERROR:", exc_info=(exc_type, exc_value, exc_traceback))
|
||||||
|
sys.excepthook = handle_exception
|
||||||
|
|
||||||
|
def send(self, level_log: str, message: str):
|
||||||
|
getattr(self.logger, level_log)(message)
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
import os
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
def find_file(filename: str, file_folders: list[str], is_folder: bool = True):
|
||||||
|
for folder in file_folders:
|
||||||
|
folder_path = Path(folder)
|
||||||
|
if not folder_path.exists():
|
||||||
|
continue
|
||||||
|
for file_path in folder_path.rglob(filename):
|
||||||
|
return str(folder_path) if is_folder else str(file_path)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_size_format(b: int, factor=1024, suffix="B"):
|
||||||
|
for unit in ["", "K", "M", "G", "T"]:
|
||||||
|
if b < factor:
|
||||||
|
return f"{b:.2f} {unit}{suffix}"
|
||||||
|
b /= factor
|
||||||
|
return f"{b:.2f} P{suffix}"
|
||||||
|
|
||||||
|
def get_dir_size(path: str):
|
||||||
|
total = 0
|
||||||
|
if os.path.exists(path):
|
||||||
|
for f in os.listdir(path):
|
||||||
|
fp = os.path.join(path, f)
|
||||||
|
if os.path.isfile(fp):
|
||||||
|
total += os.path.getsize(fp)
|
||||||
|
return total
|
||||||
|
|
||||||
|
def get_file_list_size(file_list: list[str]):
|
||||||
|
total = 0
|
||||||
|
for fp in file_list:
|
||||||
|
if os.path.isfile(fp):
|
||||||
|
total += os.path.getsize(fp)
|
||||||
|
return total
|
||||||
|
|
||||||
|
def get_size_edge(type_searсh: bool, file_list: list[str]):
|
||||||
|
if type_searсh:
|
||||||
|
result = min(file_list, key=lambda f: Path(f).stat().st_size)
|
||||||
|
else:
|
||||||
|
result = max(file_list, key=lambda f: Path(f).stat().st_size)
|
||||||
|
return str(result)
|
||||||
|
|
||||||
|
def get_files_not_found(database, config):
|
||||||
|
all_db = database.get_all()
|
||||||
|
list_md5 = []
|
||||||
|
for one_post in all_db:
|
||||||
|
file_path = find_file(one_post["local_filename"], config["file"]["repos"], is_folder=False)
|
||||||
|
if file_path == None:
|
||||||
|
list_md5.append(one_post["md5"])
|
||||||
|
return list_md5
|
||||||
|
|
||||||
|
def calculate_analytic(database, config):
|
||||||
|
all_db = database.get_all()
|
||||||
|
explicit_db = database.get_search(["e"], [])
|
||||||
|
sensitive_db = database.get_search(["s"], [])
|
||||||
|
questionable_db = database.get_search(["q"], [])
|
||||||
|
general_db = database.get_search(["g"], [])
|
||||||
|
rating_list_file_path = {"explicit":[], "sensitive":[], "questionable":[], "general":[]}
|
||||||
|
type_list_file_path = {"images":[], "videos":[], "gifs":[]}
|
||||||
|
files_not_found = 0
|
||||||
|
for one_post in all_db:
|
||||||
|
file_path = find_file(one_post["local_filename"], config["file"]["repos"], is_folder=False)
|
||||||
|
if file_path != None:
|
||||||
|
file_path = str(file_path)
|
||||||
|
rating_list_file_path[one_post["rating"]].append(file_path)
|
||||||
|
if one_post["is_gif"] == 1:
|
||||||
|
type_list_file_path["gifs"].append(file_path)
|
||||||
|
elif one_post["is_video"] == 1:
|
||||||
|
type_list_file_path["videos"].append(file_path)
|
||||||
|
else:
|
||||||
|
type_list_file_path["images"].append(file_path)
|
||||||
|
else:
|
||||||
|
files_not_found += 1
|
||||||
|
file_size_dict = {"explicit":get_file_list_size(rating_list_file_path["explicit"]),
|
||||||
|
"sensitive":get_file_list_size(rating_list_file_path["sensitive"]),
|
||||||
|
"questionable":get_file_list_size(rating_list_file_path["questionable"]),
|
||||||
|
"general":get_file_list_size(rating_list_file_path["general"])
|
||||||
|
}
|
||||||
|
type_size_dict = {"images":get_file_list_size(type_list_file_path["images"]),
|
||||||
|
"videos":get_file_list_size(type_list_file_path["videos"]),
|
||||||
|
"gifs":get_file_list_size(type_list_file_path["gifs"])}
|
||||||
|
ratings_stats = {
|
||||||
|
"explicit": {
|
||||||
|
"count": len(explicit_db),
|
||||||
|
"size_formatted": get_size_format(file_size_dict["explicit"])
|
||||||
|
},
|
||||||
|
"sensitive": {
|
||||||
|
"count": len(sensitive_db),
|
||||||
|
"size_formatted": get_size_format(file_size_dict["sensitive"])
|
||||||
|
},
|
||||||
|
"questionable": {
|
||||||
|
"count": len(questionable_db),
|
||||||
|
"size_formatted": get_size_format(file_size_dict["questionable"])
|
||||||
|
},
|
||||||
|
"general": {
|
||||||
|
"count": len(general_db),
|
||||||
|
"size_formatted": get_size_format(file_size_dict["general"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
total_file_data_size = file_size_dict["general"]+file_size_dict["questionable"]+file_size_dict["sensitive"]+file_size_dict["explicit"]
|
||||||
|
total_thumb_size = get_dir_size(config["file"]["thumb"])
|
||||||
|
total_log_size = get_file_list_size(["logs.log"])
|
||||||
|
total_db_size = get_file_list_size([os.path.join(config["file"]["data"], "db.sqlite")])
|
||||||
|
weight_stats_smallest_file = get_size_edge(True, type_list_file_path["gifs"]+type_list_file_path["images"]+type_list_file_path["videos"])
|
||||||
|
weight_stats_largest_file = get_size_edge(False, type_list_file_path["gifs"]+type_list_file_path["images"]+type_list_file_path["videos"])
|
||||||
|
weight_stats_data = {
|
||||||
|
"smallest":{
|
||||||
|
"file":"",
|
||||||
|
"md5":"",
|
||||||
|
"size":0
|
||||||
|
},
|
||||||
|
"largest":{
|
||||||
|
"file":"",
|
||||||
|
"md5":"",
|
||||||
|
"size":0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resolution_stats_data = {
|
||||||
|
"smallest":{
|
||||||
|
"file":"",
|
||||||
|
"md5":"",
|
||||||
|
"res":{
|
||||||
|
"width":0,
|
||||||
|
"height":0,
|
||||||
|
"total":99999999999999999999999999
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"largest":{
|
||||||
|
"file":"",
|
||||||
|
"md5":"",
|
||||||
|
"res":{
|
||||||
|
"width":0,
|
||||||
|
"height":0,
|
||||||
|
"total":0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for one_post_scan in all_db:
|
||||||
|
if one_post_scan["local_filename"] == os.path.basename(weight_stats_smallest_file):
|
||||||
|
weight_stats_data["smallest"] = {
|
||||||
|
"file":os.path.basename(weight_stats_smallest_file),
|
||||||
|
"md5":one_post_scan["md5"],
|
||||||
|
"size":get_file_list_size([weight_stats_smallest_file])
|
||||||
|
}
|
||||||
|
if one_post_scan["local_filename"] == os.path.basename(weight_stats_largest_file):
|
||||||
|
weight_stats_data["largest"] = {
|
||||||
|
"file":os.path.basename(weight_stats_largest_file),
|
||||||
|
"md5":one_post_scan["md5"],
|
||||||
|
"size":get_file_list_size([weight_stats_largest_file])
|
||||||
|
}
|
||||||
|
print(get_file_list_size([os.path.basename(weight_stats_largest_file)]))
|
||||||
|
one_post_res_total = one_post_scan["width"]*one_post_scan["height"]
|
||||||
|
if resolution_stats_data["largest"]["res"]["total"] < one_post_res_total:
|
||||||
|
resolution_stats_data["largest"] = {
|
||||||
|
"file":one_post_scan["local_filename"],
|
||||||
|
"md5":one_post_scan["md5"],
|
||||||
|
"res":{
|
||||||
|
"width":one_post_scan["width"],
|
||||||
|
"height":one_post_scan["height"],
|
||||||
|
"total":one_post_res_total
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if resolution_stats_data["smallest"]["res"]["total"] > one_post_res_total:
|
||||||
|
resolution_stats_data["smallest"] = {
|
||||||
|
"file":one_post_scan["local_filename"],
|
||||||
|
"md5":one_post_scan["md5"],
|
||||||
|
"res":{
|
||||||
|
"width":one_post_scan["width"],
|
||||||
|
"height":one_post_scan["height"],
|
||||||
|
"total":one_post_res_total
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result = {
|
||||||
|
"total_images_analyzed": len(all_db),
|
||||||
|
"files_not_found":files_not_found,
|
||||||
|
"average_weight": {
|
||||||
|
"bytes": round(total_file_data_size/(len(rating_list_file_path["explicit"])+len(rating_list_file_path["sensitive"])+len(rating_list_file_path["questionable"])+len(rating_list_file_path["general"])), 2),
|
||||||
|
"formatted": get_size_format(round(total_file_data_size/(len(rating_list_file_path["explicit"])+len(rating_list_file_path["sensitive"])+len(rating_list_file_path["questionable"])+len(rating_list_file_path["general"])), 2))
|
||||||
|
},
|
||||||
|
"storage_stats": {
|
||||||
|
"folders": {
|
||||||
|
"data": get_size_format(total_file_data_size),
|
||||||
|
"db": get_size_format(total_db_size),
|
||||||
|
"thumb": get_size_format(total_thumb_size),
|
||||||
|
"logs": get_size_format(total_log_size)
|
||||||
|
},
|
||||||
|
"types": {
|
||||||
|
"images": get_size_format(type_size_dict["images"]),
|
||||||
|
"videos": get_size_format(type_size_dict["videos"]),
|
||||||
|
"gifs": get_size_format(type_size_dict["gifs"])
|
||||||
|
},
|
||||||
|
"grand_total": get_size_format(total_file_data_size+total_thumb_size+total_log_size+total_db_size)
|
||||||
|
},
|
||||||
|
"ratings_stats": ratings_stats,
|
||||||
|
"resolution_stats": {
|
||||||
|
"largest": {
|
||||||
|
"filename": resolution_stats_data["largest"]["file"],
|
||||||
|
"md5": resolution_stats_data["largest"]["md5"],
|
||||||
|
"resolution": str(resolution_stats_data["largest"]["res"]["width"]) + " x " + str(resolution_stats_data["largest"]["res"]["height"])
|
||||||
|
},
|
||||||
|
"smallest": {
|
||||||
|
"filename": resolution_stats_data["smallest"]["file"],
|
||||||
|
"md5": resolution_stats_data["smallest"]["md5"],
|
||||||
|
"resolution": str(resolution_stats_data["smallest"]["res"]["width"]) + " x " + str(resolution_stats_data["smallest"]["res"]["height"])
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"weight_stats": {
|
||||||
|
"largest": {
|
||||||
|
"filename": os.path.basename(weight_stats_data["largest"]["file"]),
|
||||||
|
"md5": weight_stats_data["largest"]["md5"],
|
||||||
|
"size_formatted": get_size_format(weight_stats_data["largest"]["size"])
|
||||||
|
},
|
||||||
|
"smallest": {
|
||||||
|
"filename": os.path.basename(weight_stats_data["smallest"]["file"]),
|
||||||
|
"md5": weight_stats_data["smallest"]["md5"],
|
||||||
|
"size_formatted": get_size_format(weight_stats_data["smallest"]["size"])
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"top_tag":database.get_top_tag("")
|
||||||
|
}
|
||||||
|
with open(os.path.join(config["file"]["data"], "analytic.json"), 'w', encoding='utf-8') as out_f:
|
||||||
|
json.dump(result, out_f, indent=4, ensure_ascii=False)
|
||||||
|
return True
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Analytics - LocalBooru</title>
|
||||||
|
<style>
|
||||||
|
:root { --bg-main: #1e1e1e; --bg-header: #252525; --bg-panel: #222; --bg-box: #2a2a2a; --bg-input: #333; --text-main: #eee; --text-muted: #aaa; --border-color: #444; --link-color: #4da8da; --color-g: #4caf50; --color-s: #ff9800; --color-q: #ffeb3b; --color-e: #f44336; }
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
body { background-color: var(--bg-main); color: var(--text-main); font-family: sans-serif; font-size: 13px; }
|
||||||
|
|
||||||
|
header { display: flex; align-items: center; background-color: var(--bg-header); padding: 10px 20px; border-bottom: 1px solid var(--border-color); gap: 15px; flex-wrap: wrap; }
|
||||||
|
.logo { font-weight: bold; font-size: 18px; color: white; text-decoration: none; }
|
||||||
|
.analytics-link { color: var(--link-color); text-decoration: none; font-size: 12px; font-weight: bold;}
|
||||||
|
|
||||||
|
.search-wrapper { flex-grow: 1; max-width: 400px; position: relative; }
|
||||||
|
.search-wrapper input { width: 100%; background-color: var(--bg-input); border: 1px solid var(--border-color); color: white; padding: 6px 10px; border-radius: 3px; outline: none; }
|
||||||
|
.autocomplete-list { position: absolute; top: 100%; left: 0; right: 0; background-color: var(--bg-box); border: 1px solid var(--border-color); border-radius: 3px; margin-top: 4px; list-style: none; z-index: 1000; max-height: 250px; overflow-y: auto; box-shadow: 0 4px 10px rgba(0,0,0,0.5); display: none; }
|
||||||
|
.autocomplete-item { padding: 8px 10px; cursor: pointer; display: flex; justify-content: space-between; border-bottom: 1px solid #333; }
|
||||||
|
.autocomplete-item:hover { background-color: var(--bg-input); }
|
||||||
|
.autocomplete-count { color: var(--text-muted); font-size: 12px; }
|
||||||
|
|
||||||
|
main { padding: 20px; max-width: 1400px; margin: 0 auto; }
|
||||||
|
h1 { font-size: 20px; margin-bottom: 20px; color: white; }
|
||||||
|
.dashboard-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; align-items: start; }
|
||||||
|
.panel { background-color: var(--bg-panel); border: 1px solid var(--border-color); border-radius: 4px; padding: 15px; display: flex; flex-direction: column; gap: 15px; }
|
||||||
|
.panel-header { font-size: 16px; font-weight: bold; color: var(--link-color); border-bottom: 1px solid var(--border-color); padding-bottom: 10px; }
|
||||||
|
.left-col { display: flex; flex-direction: column; gap: 20px; }
|
||||||
|
.rating-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||||
|
.rating-box { background-color: var(--bg-box); border: 1px solid var(--border-color); border-radius: 4px; padding: 15px; text-align: center; }
|
||||||
|
.data-list { list-style: none; display: flex; flex-direction: column; gap: 8px;}
|
||||||
|
.data-row { display: flex; justify-content: space-between; border-bottom: 1px solid #333; padding-bottom: 4px; }
|
||||||
|
.table-header { display: flex; justify-content: space-between; font-weight: bold; margin-bottom: 10px; color: white;}
|
||||||
|
.tag-row { display: flex; justify-content: space-between; margin-bottom: 8px; }
|
||||||
|
.tag-row a { color: var(--link-color); text-decoration: none; }
|
||||||
|
.tag-row a:hover { text-decoration: underline; }
|
||||||
|
.pagination { display: flex; justify-content: center; gap: 5px; margin-top: 15px; align-items: center; }
|
||||||
|
.page-btn { background: transparent; border: 1px solid var(--border-color); color: white; padding: 4px 10px; border-radius: 3px; cursor: pointer; }
|
||||||
|
|
||||||
|
.ext-block { margin-bottom: 10px; }
|
||||||
|
.ext-block a { color: var(--link-color); text-decoration: none; word-break: break-all; }
|
||||||
|
.ext-block a:hover { text-decoration: underline; }
|
||||||
|
|
||||||
|
.loader { color: var(--text-muted); font-size: 16px; }
|
||||||
|
|
||||||
|
@media (max-width: 1000px) { .dashboard-grid { grid-template-columns: 1fr 1fr; } .left-col { grid-column: 1/-1; display: grid; grid-template-columns: 1fr 1fr; } }
|
||||||
|
@media (max-width: 700px) { .dashboard-grid, .left-col { grid-template-columns: 1fr; } header { flex-wrap: wrap; } .search-wrapper { order: 3; min-width: 100%; margin-top: 10px;} }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<a href="/" class="logo">LocalBooru</a>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<h1>Database Analytics</h1>
|
||||||
|
<div id="loadingIndicator" class="loader">Fetching data from API...</div>
|
||||||
|
|
||||||
|
<div class="dashboard-grid" id="analyticsGrid" style="display: none;">
|
||||||
|
<div class="left-col">
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-header">⭐ Rating Breakdown</div>
|
||||||
|
<div class="rating-grid" id="ratingContainer"></div>
|
||||||
|
</div>
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-header">📁 Storage Breakdown</div>
|
||||||
|
<div class="data-list" id="storageContainer"></div>
|
||||||
|
</div>
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-header">🎨 Media Types</div>
|
||||||
|
<div class="data-list" id="mediaContainer"></div>
|
||||||
|
</div>
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-header">📏 Extremes (Click to view)</div>
|
||||||
|
<div id="extremesContainer"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-header">🏷️ Top Tags List</div>
|
||||||
|
<div class="table-header"><span>Tag</span><span>Count</span></div>
|
||||||
|
<div class="data-list" id="tagsListContainer"></div>
|
||||||
|
<div class="pagination">
|
||||||
|
<button class="page-btn" onclick="prevTagPage()">‹</button>
|
||||||
|
<span id="tagPageInfo" style="font-weight:bold; padding:0 10px;"></span>
|
||||||
|
<button class="page-btn" onclick="nextTagPage()">›</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Заменено, так как в новом JSON нет top_pairs -->
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-header">ℹ️ System Overview</div>
|
||||||
|
<div class="data-list" id="overviewContainer"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
let debounceTimer;
|
||||||
|
let allTags = [], currentTagPage = 1, tagsPerPage = 22;
|
||||||
|
|
||||||
|
// Укорачиваем длинные имена файлов (хэши) для красивого отображения
|
||||||
|
const shortenName = (name) => name.length > 20 ? name.substring(0, 10) + '...' + name.substring(name.length - 6) : name;
|
||||||
|
|
||||||
|
async function fetchAnalytics() {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ type: "analytic" })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) throw new Error("Network response was not ok");
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
// Скрываем лоадер, показываем сетку
|
||||||
|
document.getElementById('loadingIndicator').style.display = 'none';
|
||||||
|
document.getElementById('analyticsGrid').style.display = 'grid';
|
||||||
|
|
||||||
|
// 1. Рейтинги
|
||||||
|
const rStats = data.ratings_stats;
|
||||||
|
document.getElementById('ratingContainer').innerHTML = Object.keys(rStats).map(k => `
|
||||||
|
<div class="rating-box" style="border-top: 2px solid var(--color-${k[0]})">
|
||||||
|
<div style="font-weight:bold; color:var(--color-${k[0]}); margin-bottom:5px;">${k.charAt(0).toUpperCase() + k.slice(1)}</div>
|
||||||
|
<div style="color:var(--text-muted); margin-bottom:3px;">${rStats[k].count} items</div>
|
||||||
|
<div style="font-weight:bold;">${rStats[k].size_formatted}</div>
|
||||||
|
</div>
|
||||||
|
`).join('');
|
||||||
|
|
||||||
|
// 2. Хранилище (Storage)
|
||||||
|
const s = data.storage_stats.folders;
|
||||||
|
document.getElementById('storageContainer').innerHTML = `
|
||||||
|
<div class="data-row"><span>Logs:</span><span class="val">${s.logs}</span></div>
|
||||||
|
<div class="data-row"><span>DB:</span><span class="val">${s.db}</span></div>
|
||||||
|
<div class="data-row"><span>Thumb:</span><span class="val">${s.thumb}</span></div>
|
||||||
|
<div class="data-row"><span>Data (Img):</span><span class="val">${s.data}</span></div>
|
||||||
|
<div class="data-row" style="color:var(--color-g); font-weight:bold; border-top:1px solid #444; border-bottom:none; padding-top:8px;"><span>GRAND TOTAL:</span><span>${data.storage_stats.grand_total}</span></div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// 3. Медиа типы
|
||||||
|
const m = data.storage_stats.types;
|
||||||
|
document.getElementById('mediaContainer').innerHTML = `
|
||||||
|
<div class="data-row"><span>IMG:</span><span class="val">${m.images}</span></div>
|
||||||
|
<div class="data-row"><span>VID:</span><span class="val">${m.videos}</span></div>
|
||||||
|
<div class="data-row"><span>GIF:</span><span class="val">${m.gifs}</span></div>
|
||||||
|
<div style="font-size:11px; color:var(--text-muted); margin-top:5px;">Total: <b>${data.total_images_analyzed}</b> | Avg: <b>${data.average_weight.formatted}</b></div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// 4. Рекорды (Extremes)
|
||||||
|
const res = data.resolution_stats;
|
||||||
|
const weight = data.weight_stats;
|
||||||
|
document.getElementById('extremesContainer').innerHTML = `
|
||||||
|
<div class="ext-block"><b>Largest Res:</b> ${res.largest.resolution}<br>(<a href="post/${res.largest.md5}">${shortenName(res.largest.filename)}</a>)</div>
|
||||||
|
<div class="ext-block"><b>Smallest Res:</b> ${res.smallest.resolution}<br>(<a href="post/${res.smallest.md5}">${shortenName(res.smallest.filename)}</a>)</div>
|
||||||
|
<div class="ext-block"><b>Heaviest:</b> ${weight.largest.size_formatted}<br>(<a href="post/${weight.largest.md5}">${shortenName(weight.largest.filename)}</a>)</div>
|
||||||
|
<div class="ext-block"><b>Lightest:</b> ${weight.smallest.size_formatted}<br>(<a href="post/${weight.smallest.md5}">${shortenName(weight.smallest.filename)}</a>)</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// 5. System Overview (вместо Top Pairs)
|
||||||
|
document.getElementById('overviewContainer').innerHTML = `
|
||||||
|
<div class="data-row"><span>Images Analyzed:</span><span class="val" style="font-weight:bold;">${data.total_images_analyzed}</span></div>
|
||||||
|
<div class="data-row"><span>Files Not Found:</span><span class="val" style="font-weight:bold; color: ${data.files_not_found > 0 ? 'var(--color-e)' : 'inherit'};">${data.files_not_found}</span></div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// 6. Теги
|
||||||
|
allTags = data.top_tag;
|
||||||
|
renderTagsPage();
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching analytics:', error);
|
||||||
|
document.getElementById('loadingIndicator').innerHTML = `<span style="color: var(--color-e)">Failed to load data. See console for details.</span>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Пагинация тегов
|
||||||
|
function renderTagsPage() {
|
||||||
|
if (!allTags || allTags.length === 0) return;
|
||||||
|
|
||||||
|
const totalPages = Math.ceil(allTags.length / tagsPerPage) || 1;
|
||||||
|
document.getElementById('tagPageInfo').innerText = `${currentTagPage} / ${totalPages}`;
|
||||||
|
|
||||||
|
const start = (currentTagPage - 1) * tagsPerPage;
|
||||||
|
document.getElementById('tagsListContainer').innerHTML = allTags.slice(start, start + tagsPerPage).map(t =>
|
||||||
|
`<div class="tag-row"><a href="index.html?query=${encodeURIComponent(t.tag)}">${t.tag}</a> <span>${t.count}</span></div>`
|
||||||
|
).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
window.prevTagPage = () => { if(currentTagPage > 1) { currentTagPage--; renderTagsPage(); }};
|
||||||
|
window.nextTagPage = () => { if(currentTagPage < Math.ceil(allTags.length/tagsPerPage)) { currentTagPage++; renderTagsPage(); }};
|
||||||
|
|
||||||
|
// Запуск
|
||||||
|
fetchAnalytics();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>LocalBooru</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg-main: #1e1e1e; --bg-header: #252525; --bg-card: #2a2a2a;
|
||||||
|
--bg-panel: #222; --bg-input: #333; --text-main: #eee;
|
||||||
|
--text-muted: #aaa; --border-color: #444;
|
||||||
|
--color-g: #4caf50; --color-s: #ff9800; --color-q: #ffeb3b; --color-e: #f44336;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
body { background-color: var(--bg-main); color: var(--text-main); font-family: sans-serif; font-size: 14px; }
|
||||||
|
|
||||||
|
header { display: flex; align-items: center; background-color: var(--bg-header); padding: 10px 20px; border-bottom: 1px solid var(--border-color); gap: 15px; flex-wrap: wrap; }
|
||||||
|
.logo { font-weight: bold; font-size: 18px; color: white; text-decoration: none; }
|
||||||
|
.analytics { color: #88bece; text-decoration: none; font-size: 12px; }
|
||||||
|
.tasks { color: #88bece; text-decoration: none; font-size: 12px; }
|
||||||
|
|
||||||
|
.search-wrapper { flex-grow: 1; max-width: 400px; position: relative; }
|
||||||
|
.search-wrapper input { width: 100%; background-color: var(--bg-input); border: 1px solid var(--border-color); color: white; padding: 6px 10px; border-radius: 3px; outline: none; }
|
||||||
|
.search-wrapper input:focus { border-color: var(--text-muted); }
|
||||||
|
|
||||||
|
.autocomplete-list { position: absolute; top: 100%; left: 0; right: 0; background-color: var(--bg-card); border: 1px solid var(--border-color); border-radius: 3px; margin-top: 4px; list-style: none; z-index: 1000; max-height: 250px; overflow-y: auto; box-shadow: 0 4px 10px rgba(0,0,0,0.5); display: none; }
|
||||||
|
.autocomplete-item { padding: 8px 10px; cursor: pointer; display: flex; justify-content: space-between; border-bottom: 1px solid #333; }
|
||||||
|
.autocomplete-item:last-child { border-bottom: none; }
|
||||||
|
.autocomplete-item:hover { background-color: var(--bg-input); }
|
||||||
|
.autocomplete-count { color: var(--text-muted); font-size: 12px; }
|
||||||
|
|
||||||
|
.rating-filters { display: flex; gap: 5px; }
|
||||||
|
.rating-btn { background: transparent; color: white; border: 1px solid; width: 24px; height: 24px; border-radius: 3px; cursor: pointer; font-size: 12px; font-weight: bold; }
|
||||||
|
.rating-btn.active { opacity: 1; }
|
||||||
|
.rating-btn:not(.active) { opacity: 0.3; }
|
||||||
|
#btn-e { border-color: var(--color-e); color: var(--color-e); }
|
||||||
|
#btn-q { border-color: var(--color-q); color: var(--color-q); }
|
||||||
|
#btn-s { border-color: var(--color-s); color: var(--color-s); }
|
||||||
|
#btn-g { border-color: var(--color-g); color: var(--color-g); }
|
||||||
|
|
||||||
|
main { padding: 20px; max-width: 1600px; margin: 0 auto; }
|
||||||
|
.results-header { font-size: 18px; font-weight: bold; margin-bottom: 20px; }
|
||||||
|
|
||||||
|
/* Pagination */
|
||||||
|
.pagination-container { display: flex; justify-content: center; align-items: center; gap: 10px; margin: 20px 0; }
|
||||||
|
.pagination-btn { background-color: var(--bg-header); border: 1px solid var(--border-color); color: var(--text-muted); padding: 5px 12px; cursor: pointer; border-radius: 3px; }
|
||||||
|
.pagination-btn:hover:not(:disabled) { background-color: var(--bg-input); color: white; }
|
||||||
|
.pagination-btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||||
|
|
||||||
|
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 10px; }
|
||||||
|
.card { background-color: var(--bg-card); display: flex; flex-direction: column; border-radius: 3px; overflow: hidden; text-decoration: none; color: inherit; transition: transform 0.1s;}
|
||||||
|
.card:hover { transform: translateY(-2px); }
|
||||||
|
.card-image-container { width: 100%; aspect-ratio: 1/1; background-color: #333; position: relative; }
|
||||||
|
.card-image-container img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||||
|
.card-meta { padding: 6px; text-align: center; font-size: 10px; color: var(--text-muted); }
|
||||||
|
|
||||||
|
.loader { text-align: center; padding: 50px; color: var(--text-muted); grid-column: 1/-1; }
|
||||||
|
|
||||||
|
@media (max-width: 600px) { .search-wrapper { order: 3; max-width: 100%; width: 100%; margin-top: 10px; } }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<header>
|
||||||
|
<a href="/" class="logo">LocalBooru</a>
|
||||||
|
<a class="analytics" href="/analytics">📊 Analytics</a>
|
||||||
|
<a class="tasks" href="/task">⚙️ Tasks</a>
|
||||||
|
<div class="search-wrapper">
|
||||||
|
<input type="text" id="searchInput" placeholder="Search tags...">
|
||||||
|
<ul id="autocompleteList" class="autocomplete-list"></ul>
|
||||||
|
</div>
|
||||||
|
<div class="rating-filters">
|
||||||
|
<button id="btn-e" class="rating-btn active" data-rating="e">E</button>
|
||||||
|
<button id="btn-q" class="rating-btn active" data-rating="q">Q</button>
|
||||||
|
<button id="btn-s" class="rating-btn active" data-rating="s">S</button>
|
||||||
|
<button id="btn-g" class="rating-btn active" data-rating="g">G</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<div class="results-header" id="resultsCount">Results (0)</div>
|
||||||
|
<div class="pagination-container" id="paginationTop"></div>
|
||||||
|
<div class="grid" id="imageGrid"></div>
|
||||||
|
<div class="pagination-container" id="paginationBottom"></div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const state = {
|
||||||
|
page: 0,
|
||||||
|
query: "",
|
||||||
|
ratings: { e: true, q: true, s: true, g: true },
|
||||||
|
totalPages: 1,
|
||||||
|
totalResults: 0
|
||||||
|
};
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
setupAutocomplete('searchInput', 'autocompleteList');
|
||||||
|
|
||||||
|
const searchInput = document.getElementById('searchInput');
|
||||||
|
|
||||||
|
searchInput.addEventListener('keypress', (e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
document.getElementById('autocompleteList').style.display = 'none';
|
||||||
|
state.query = searchInput.value;
|
||||||
|
state.page = 0;
|
||||||
|
fetchData();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll('.rating-btn').forEach(btn => {
|
||||||
|
btn.addEventListener('click', (e) => {
|
||||||
|
const r = e.target.getAttribute('data-rating');
|
||||||
|
state.ratings[r] = !state.ratings[r];
|
||||||
|
e.target.classList.toggle('active', state.ratings[r]);
|
||||||
|
state.page = 0;
|
||||||
|
fetchData();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const urlQuery = new URLSearchParams(window.location.search).get('query');
|
||||||
|
if (urlQuery) {
|
||||||
|
state.query = urlQuery;
|
||||||
|
searchInput.value = urlQuery;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchData();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- АВТОДОПОЛНЕНИЕ ---
|
||||||
|
function setupAutocomplete(inputId, listId) {
|
||||||
|
const input = document.getElementById(inputId);
|
||||||
|
const list = document.getElementById(listId);
|
||||||
|
let debounceTimer;
|
||||||
|
|
||||||
|
input.addEventListener('input', () => {
|
||||||
|
clearTimeout(debounceTimer);
|
||||||
|
const words = input.value.split(' ');
|
||||||
|
const currentWord = words[words.length - 1];
|
||||||
|
|
||||||
|
if (currentWord.length < 2) {
|
||||||
|
list.style.display = 'none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
debounceTimer = setTimeout(async () => {
|
||||||
|
const req = { type: "autocomplete", q: currentWord };
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(req)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) throw new Error('Ошибка API');
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!data || data.length === 0) {
|
||||||
|
list.style.display = 'none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
list.innerHTML = data.map(item => `
|
||||||
|
<li class="autocomplete-item" data-tag="${item.tag}">
|
||||||
|
<span>${item.tag}</span><span class="autocomplete-count">${item.count}</span>
|
||||||
|
</li>
|
||||||
|
`).join('');
|
||||||
|
list.style.display = 'block';
|
||||||
|
|
||||||
|
list.querySelectorAll('.autocomplete-item').forEach(li => {
|
||||||
|
li.addEventListener('click', () => {
|
||||||
|
words[words.length - 1] = li.getAttribute('data-tag');
|
||||||
|
input.value = words.join(' ') + ' ';
|
||||||
|
list.style.display = 'none';
|
||||||
|
input.focus();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
}, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
if (e.target !== input && e.target !== list) list.style.display = 'none';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- ПОИСК И ВЫВОД РЕЗУЛЬТАТОВ ---
|
||||||
|
async function fetchData() {
|
||||||
|
const grid = document.getElementById('imageGrid');
|
||||||
|
grid.innerHTML = `<div class="loader">Загрузка...</div>`;
|
||||||
|
|
||||||
|
const activeRatings = Object.keys(state.ratings).filter(k => state.ratings[k]).join('+');
|
||||||
|
const req = {
|
||||||
|
type: "search",
|
||||||
|
page: state.page,
|
||||||
|
query: state.query.trim(),
|
||||||
|
rating: activeRatings
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(req)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) throw new Error('Ошибка сервера');
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
// Синхронизация состояния: вычисляем количество страниц (Math.ceil(всего / элементов_на_странице))
|
||||||
|
state.totalResults = data.results_info.total;
|
||||||
|
state.page = data.results_info.page;
|
||||||
|
|
||||||
|
const itemsPerPage = data.results_info.count_page || 1; // защита от деления на 0
|
||||||
|
state.totalPages = Math.ceil(state.totalResults / itemsPerPage);
|
||||||
|
|
||||||
|
document.getElementById('resultsCount').textContent = `Results (${state.totalResults})`;
|
||||||
|
|
||||||
|
if (data.results.length === 0) {
|
||||||
|
grid.innerHTML = `<div class="loader">Ничего не найдено</div>`;
|
||||||
|
} else {
|
||||||
|
grid.innerHTML = data.results.map(i => `
|
||||||
|
<a href="/post/${i.md5}" class="card">
|
||||||
|
<div class="card-image-container">
|
||||||
|
<img src="/thumb/${i.md5}.jpg" alt="thumbnail" loading="lazy">
|
||||||
|
</div>
|
||||||
|
<div class="card-meta">
|
||||||
|
Date: ${i.display_date[1]}<br>
|
||||||
|
Score: ${i.score} | Rating: <span style="color:var(--color-${i.rating[0].toLowerCase()})">${i.rating}</span>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
`).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
renderPagination();
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
grid.innerHTML = `<div class="loader">Ошибка связи с API</div>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- ПАГИНАЦИЯ ---
|
||||||
|
function renderPagination() {
|
||||||
|
const totalPages = Math.max(0, state.totalPages);
|
||||||
|
const currentPage = state.page;
|
||||||
|
|
||||||
|
const hasPrev = currentPage > 0;
|
||||||
|
const hasNext = currentPage < totalPages - 1;
|
||||||
|
|
||||||
|
const displayPage = totalPages === 0 ? 1 : currentPage + 1;
|
||||||
|
const displayTotal = totalPages === 0 ? 1 : totalPages;
|
||||||
|
|
||||||
|
const html = `
|
||||||
|
<button class="pagination-btn" onclick="changePage(0)" ${!hasPrev ? 'disabled' : ''}>« First</button>
|
||||||
|
<button class="pagination-btn" onclick="changePage(${currentPage - 1})" ${!hasPrev ? 'disabled' : ''}>‹ Prev</button>
|
||||||
|
<span style="font-size:12px; font-weight:bold;">Page ${displayPage} of ${displayTotal}</span>
|
||||||
|
<button class="pagination-btn" onclick="changePage(${currentPage + 1})" ${!hasNext ? 'disabled' : ''}>Next ›</button>
|
||||||
|
<button class="pagination-btn" onclick="changePage(${totalPages - 1})" ${!hasNext ? 'disabled' : ''}>Last »</button>
|
||||||
|
`;
|
||||||
|
|
||||||
|
document.getElementById('paginationTop').innerHTML = html;
|
||||||
|
document.getElementById('paginationBottom').innerHTML = html;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Смена страницы
|
||||||
|
window.changePage = (newPage) => {
|
||||||
|
if (newPage < 0 || (state.totalPages > 0 && newPage >= state.totalPages)) return;
|
||||||
|
|
||||||
|
state.page = newPage;
|
||||||
|
fetchData();
|
||||||
|
window.scrollTo(0, 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
init();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Post - LocalBooru</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg-main: #1e1e1e; --bg-header: #252525; --bg-panel: #2a2a2a; --bg-input: #333;
|
||||||
|
--text-main: #eee; --text-muted: #aaa; --border-color: #444; --link-color: #4da8da;
|
||||||
|
--color-g: #4caf50; --color-s: #ff9800; --color-q: #ffeb3b; --color-e: #f44336;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
body { background-color: var(--bg-main); color: var(--text-main); font-family: sans-serif; font-size: 14px; }
|
||||||
|
|
||||||
|
header { display: flex; align-items: center; background-color: var(--bg-header); padding: 10px 20px; border-bottom: 1px solid var(--border-color); gap: 15px; }
|
||||||
|
.logo { font-weight: bold; font-size: 18px; color: white; text-decoration: none; }
|
||||||
|
|
||||||
|
.search-wrapper { flex-grow: 1; max-width: 400px; position: relative; }
|
||||||
|
.search-wrapper input { width: 100%; background-color: var(--bg-input); border: 1px solid var(--border-color); color: white; padding: 6px 10px; border-radius: 3px; outline: none; }
|
||||||
|
.autocomplete-list { position: absolute; top: 100%; left: 0; right: 0; background-color: var(--bg-panel); border: 1px solid var(--border-color); border-radius: 3px; margin-top: 4px; list-style: none; z-index: 1000; max-height: 250px; overflow-y: auto; box-shadow: 0 4px 10px rgba(0,0,0,0.5); display: none; }
|
||||||
|
.autocomplete-item { padding: 8px 10px; cursor: pointer; display: flex; justify-content: space-between; border-bottom: 1px solid #333; }
|
||||||
|
.autocomplete-item:last-child { border-bottom: none; }
|
||||||
|
.autocomplete-item:hover { background-color: var(--bg-input); }
|
||||||
|
.autocomplete-count { color: var(--text-muted); font-size: 12px; }
|
||||||
|
|
||||||
|
main { padding: 20px; max-width: 1600px; margin: 0 auto; display: grid; grid-template-columns: 300px 1fr; gap: 20px; align-items: start; }
|
||||||
|
.sidebar { background-color: var(--bg-panel); border: 1px solid var(--border-color); border-radius: 4px; padding: 15px; display: flex; flex-direction: column; gap: 20px; }
|
||||||
|
.section-title { font-size: 16px; font-weight: bold; border-bottom: 1px solid var(--border-color); padding-bottom: 8px; margin-bottom: 10px; }
|
||||||
|
.stat-row { margin-bottom: 6px; word-break: break-all; line-height: 1.4;}
|
||||||
|
.stat-label { font-weight: bold; }
|
||||||
|
.tags-list { display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.tags-list a { color: var(--link-color); text-decoration: none; }
|
||||||
|
.tags-list a:hover { text-decoration: underline; }
|
||||||
|
.media-container { background-color: var(--bg-panel); border: 1px solid var(--border-color); border-radius: 4px; padding: 20px; display: flex; justify-content: center; align-items: center; min-height: 400px; }
|
||||||
|
.media-container img, .media-container video { max-width: 100%; max-height: 85vh; object-fit: contain; border-radius: 2px; }
|
||||||
|
.loader { grid-column: 1/-1; text-align: center; padding: 50px; color: var(--text-muted); }
|
||||||
|
|
||||||
|
@media (max-width: 900px) { main { grid-template-columns: 1fr; } .media-container { order: -1; } header { flex-wrap: wrap; } .search-wrapper { min-width: 100%; order: 3; margin-top: 10px; } }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<a href="/" class="logo">LocalBooru</a>
|
||||||
|
<div class="search-wrapper">
|
||||||
|
<input type="text" id="searchInput" placeholder="Search tags...">
|
||||||
|
<ul id="autocompleteList" class="autocomplete-list"></ul>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main id="mainContent">
|
||||||
|
<div class="loader">Загрузка поста...</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// Инициализация автодополнения
|
||||||
|
const searchInput = document.getElementById('searchInput');
|
||||||
|
const list = document.getElementById('autocompleteList');
|
||||||
|
let debounceTimer;
|
||||||
|
|
||||||
|
searchInput.addEventListener('input', () => {
|
||||||
|
clearTimeout(debounceTimer);
|
||||||
|
const words = searchInput.value.split(' ');
|
||||||
|
const currentWord = words[words.length - 1];
|
||||||
|
|
||||||
|
if (currentWord.length < 2) {
|
||||||
|
list.style.display = 'none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
debounceTimer = setTimeout(async () => {
|
||||||
|
const req = { type: "autocomplete", q: currentWord };
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(req)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) throw new Error('Ошибка API автодополнения');
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!data || data.length === 0) {
|
||||||
|
list.style.display = 'none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
list.innerHTML = data.map(item => `
|
||||||
|
<li class="autocomplete-item" data-tag="${item.tag}">
|
||||||
|
<span>${item.tag}</span><span class="autocomplete-count">${item.count}</span>
|
||||||
|
</li>
|
||||||
|
`).join('');
|
||||||
|
list.style.display = 'block';
|
||||||
|
|
||||||
|
list.querySelectorAll('.autocomplete-item').forEach(li => {
|
||||||
|
li.addEventListener('click', () => {
|
||||||
|
words[words.length - 1] = li.getAttribute('data-tag');
|
||||||
|
searchInput.value = words.join(' ') + ' ';
|
||||||
|
list.style.display = 'none';
|
||||||
|
searchInput.focus();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Автодополнение недоступно:", error);
|
||||||
|
}
|
||||||
|
}, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Скрытие списка автодополнения при клике вне него
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
if (e.target !== searchInput && e.target !== list) {
|
||||||
|
list.style.display = 'none';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Переход на главную при поиске
|
||||||
|
searchInput.addEventListener('keypress', (e) => {
|
||||||
|
if(e.key === 'Enter') {
|
||||||
|
window.location.href = `index.html?query=${encodeURIComponent(searchInput.value.trim())}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Загрузка данных поста
|
||||||
|
async function fetchPost() {
|
||||||
|
// Получаем ID из параметра ?id=... или из конца URL пути
|
||||||
|
let postId = new URLSearchParams(window.location.search).get('id') || window.location.pathname.split('/').pop();
|
||||||
|
|
||||||
|
if (!postId || postId.includes('.html')) {
|
||||||
|
document.getElementById('mainContent').innerHTML = `<div class="loader">ID поста не указан</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = { type: "post", post_id: postId };
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(req)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) throw new Error('Ошибка загрузки данных с сервера');
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
// Рендер медиа (предполагается, что оригиналы лежат в /img/)
|
||||||
|
let mediaHtml = '';
|
||||||
|
const mediaUrl = `/file/${data.local_filename}`;
|
||||||
|
|
||||||
|
if (data.is_video) {
|
||||||
|
mediaHtml = `<video controls autoplay loop src="${mediaUrl}"></video>`;
|
||||||
|
} else {
|
||||||
|
// И для изображений, и для GIF подойдет тег <img>
|
||||||
|
mediaHtml = `<img src="${mediaUrl}" alt="Post Media">`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Рендер тегов
|
||||||
|
const tagsHtml = data.tags.map(t => `<a href="/?query=${encodeURIComponent(t)}">${t}</a>`).join('');
|
||||||
|
|
||||||
|
// Рендер всей страницы
|
||||||
|
document.getElementById('mainContent').innerHTML = `
|
||||||
|
<aside class="sidebar">
|
||||||
|
<div class="statistics">
|
||||||
|
<div class="section-title">Statistics</div>
|
||||||
|
<div class="stat-row"><span class="stat-label">File:</span> ${data.local_filename}</div>
|
||||||
|
<div class="stat-row"><span class="stat-label">Date:</span> ${data.display_date[1]}</div>
|
||||||
|
<div class="stat-row"><span class="stat-label">Rating:</span> <span style="color:var(--color-${data.rating[0].toLowerCase()})">${data.rating}</span></div>
|
||||||
|
<div class="stat-row"><span class="stat-label">Score:</span> ${data.score}</div>
|
||||||
|
<div class="stat-row"><span class="stat-label">Resolution:</span> ${data.width}x${data.height}</div>
|
||||||
|
<div class="stat-row"><span class="stat-label">Source:</span> <a href="${data.source}" target="_blank" rel="noopener noreferrer" style="color: var(--link-color); text-decoration: none;">Link</a></div>
|
||||||
|
</div>
|
||||||
|
<div class="tags">
|
||||||
|
<div class="section-title">Tags</div>
|
||||||
|
<div class="tags-list">${tagsHtml}</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
<div class="media-container">
|
||||||
|
${mediaHtml}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
document.getElementById('mainContent').innerHTML = `<div class="loader">Ошибка загрузки поста. Проверьте соединение с сервером.</div>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Вызов функции при старте
|
||||||
|
fetchPost();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Tasks - LocalBooru</title>
|
||||||
|
<style>
|
||||||
|
:root { --bg-main: #1e1e1e; --bg-header: #252525; --bg-panel: #222; --bg-box: #2a2a2a; --bg-input: #333; --text-main: #eee; --text-muted: #aaa; --border-color: #444; --link-color: #4da8da; --color-g: #4caf50; --color-s: #ff9800; --color-q: #ffeb3b; --color-e: #f44336; }
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
body { background-color: var(--bg-main); color: var(--text-main); font-family: sans-serif; font-size: 13px; }
|
||||||
|
|
||||||
|
/* Header Styles */
|
||||||
|
header { display: flex; align-items: center; background-color: var(--bg-header); padding: 10px 20px; border-bottom: 1px solid var(--border-color); gap: 15px; flex-wrap: wrap; }
|
||||||
|
.logo { font-weight: bold; font-size: 18px; color: white; text-decoration: none; }
|
||||||
|
.nav-link { color: var(--link-color); text-decoration: none; font-size: 12px; font-weight: bold;}
|
||||||
|
|
||||||
|
/* Search Autocomplete Styles */
|
||||||
|
.search-wrapper { flex-grow: 1; max-width: 400px; position: relative; }
|
||||||
|
.search-wrapper input { width: 100%; background-color: var(--bg-input); border: 1px solid var(--border-color); color: white; padding: 6px 10px; border-radius: 3px; outline: none; }
|
||||||
|
|
||||||
|
/* Main Content & Tasks Styles */
|
||||||
|
main { padding: 20px; max-width: 1000px; margin: 0 auto; }
|
||||||
|
h1 { font-size: 20px; margin-bottom: 20px; color: white; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; }
|
||||||
|
|
||||||
|
.task-list { display: flex; flex-direction: column; gap: 15px; }
|
||||||
|
|
||||||
|
/* Добавил flex-wrap: wrap чтобы результаты могли падать на новую строку */
|
||||||
|
.task-card { background-color: var(--bg-panel); border: 1px solid var(--border-color); border-radius: 4px; padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; gap: 20px; flex-wrap: wrap; transition: background-color 0.2s; }
|
||||||
|
.task-card:hover { background-color: var(--bg-box); }
|
||||||
|
|
||||||
|
.task-info { flex: 1; min-width: 250px; }
|
||||||
|
.task-info h3 { font-size: 16px; color: var(--link-color); margin-bottom: 5px; }
|
||||||
|
.task-info p { color: var(--text-muted); font-size: 13px; line-height: 1.4; }
|
||||||
|
|
||||||
|
.task-actions { display: flex; align-items: center; gap: 15px; min-width: 200px; justify-content: flex-end; }
|
||||||
|
|
||||||
|
.btn { background-color: var(--bg-input); border: 1px solid var(--border-color); color: white; padding: 8px 16px; border-radius: 3px; cursor: pointer; font-weight: bold; transition: all 0.2s; }
|
||||||
|
.btn:hover:not(:disabled) { background-color: #444; border-color: #555; }
|
||||||
|
.btn:active:not(:disabled) { background-color: #222; }
|
||||||
|
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||||
|
|
||||||
|
.task-status { font-weight: bold; font-size: 13px; min-width: 90px; text-align: right; }
|
||||||
|
.status-success { color: var(--color-g); }
|
||||||
|
.status-error { color: var(--color-e); }
|
||||||
|
|
||||||
|
/* Стили для вывода результатов */
|
||||||
|
.task-result-box { width: 100%; margin-top: 10px; border-top: 1px solid var(--border-color); padding-top: 15px; display: none; }
|
||||||
|
.task-result-box textarea { width: 100%; height: 150px; background-color: var(--bg-input); color: var(--text-main); border: 1px solid var(--border-color); border-radius: 3px; padding: 10px; margin-top: 10px; resize: vertical; outline: none; font-family: monospace; }
|
||||||
|
|
||||||
|
@media (max-width: 700px) {
|
||||||
|
header { flex-wrap: wrap; }
|
||||||
|
.search-wrapper { order: 3; min-width: 100%; margin-top: 10px;}
|
||||||
|
.task-card { flex-direction: column; align-items: flex-start; }
|
||||||
|
.task-actions { justify-content: flex-start; width: 100%; margin-top: 10px; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<a href="/" class="logo">LocalBooru</a>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<h1>System Tasks</h1>
|
||||||
|
|
||||||
|
<div class="task-list">
|
||||||
|
|
||||||
|
<!-- ЗАДАЧА 1: Пересчёт аналитики -->
|
||||||
|
<div class="task-card">
|
||||||
|
<div class="task-info">
|
||||||
|
<h3>Пересчёт аналитики</h3>
|
||||||
|
<p>Обновляет статистику (количество файлов, занимаемое место). Рекомендуется запускать после массового добавления или удаления постов.</p>
|
||||||
|
</div>
|
||||||
|
<div class="task-actions">
|
||||||
|
<span class="task-status"></span>
|
||||||
|
<button class="btn" onclick="executeTask('analytic', this)">Запустить</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ЗАДАЧА 2: Поиск недоступных файлов -->
|
||||||
|
<div class="task-card">
|
||||||
|
<div class="task-info">
|
||||||
|
<h3>Поиск недоступных файлов</h3>
|
||||||
|
<p>Ищет посты, для которых отсутствуют физические файлы на диске. Выводит список ссылок на экран и предлагает скачать их в формате .txt.</p>
|
||||||
|
</div>
|
||||||
|
<div class="task-actions">
|
||||||
|
<span class="task-status"></span>
|
||||||
|
<button class="btn" onclick="executeNotFoundFilesTask(this)">Запустить</button>
|
||||||
|
</div>
|
||||||
|
<!-- Блок вывода результатов (изначально скрыт) -->
|
||||||
|
<div class="task-result-box" id="result-box-not-found">
|
||||||
|
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||||
|
<span>Найдено битых ссылок: <b id="not-found-count" style="color: var(--color-e);">0</b></span>
|
||||||
|
<button class="btn" id="btn-download-txt" style="display: none;">Скачать .txt</button>
|
||||||
|
</div>
|
||||||
|
<textarea id="not-found-textarea" readonly></textarea>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// === БАЗОВАЯ ЛОГИКА ЗАДАЧ (БЕЗ ВОЗВРАТА ДАННЫХ) ===
|
||||||
|
async function executeTask(taskName, btn) {
|
||||||
|
const statusSpan = btn.previousElementSibling;
|
||||||
|
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.innerText = "Выполнение...";
|
||||||
|
statusSpan.innerText = "В процессе ⏳";
|
||||||
|
statusSpan.className = "task-status";
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ type: "task", task: taskName })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
statusSpan.innerText = "Успешно ✔";
|
||||||
|
statusSpan.classList.add('status-success');
|
||||||
|
} else {
|
||||||
|
statusSpan.innerText = `Ошибка (${response.status}) ✖`;
|
||||||
|
statusSpan.classList.add('status-error');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
statusSpan.innerText = "Сбой сети ✖";
|
||||||
|
statusSpan.classList.add('status-error');
|
||||||
|
console.error("Task execution error:", error);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.innerText = "Запустить";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// === ЛОГИКА ЗАДАЧИ: Поиск недоступных файлов ===
|
||||||
|
async function executeNotFoundFilesTask(btn) {
|
||||||
|
const statusSpan = btn.previousElementSibling;
|
||||||
|
|
||||||
|
// Элементы интерфейса для вывода
|
||||||
|
const resultBox = document.getElementById('result-box-not-found');
|
||||||
|
const textarea = document.getElementById('not-found-textarea');
|
||||||
|
const countSpan = document.getElementById('not-found-count');
|
||||||
|
const downloadBtn = document.getElementById('btn-download-txt');
|
||||||
|
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.innerText = "Выполнение...";
|
||||||
|
statusSpan.innerText = "В процессе ⏳";
|
||||||
|
statusSpan.className = "task-status";
|
||||||
|
|
||||||
|
// Скрываем прошлый результат перед новым запуском
|
||||||
|
resultBox.style.display = 'none';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ type: "task", task: "not_found_file" })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
const md5List = data.list || [];
|
||||||
|
|
||||||
|
statusSpan.innerText = "Успешно ✔";
|
||||||
|
statusSpan.classList.add('status-success');
|
||||||
|
|
||||||
|
if (md5List.length > 0) {
|
||||||
|
// Формируем ссылки
|
||||||
|
const linksArray = md5List.map(md5 => `/post/${md5}`);
|
||||||
|
const linksText = linksArray.join('\n');
|
||||||
|
|
||||||
|
// Выводим на экран
|
||||||
|
countSpan.innerText = md5List.length;
|
||||||
|
textarea.value = linksText;
|
||||||
|
resultBox.style.display = 'block';
|
||||||
|
|
||||||
|
// Настраиваем скачивание
|
||||||
|
downloadBtn.style.display = 'block';
|
||||||
|
downloadBtn.onclick = () => downloadFileAsTxt(linksText, 'not_found_files.txt');
|
||||||
|
|
||||||
|
// Сразу инициируем скачивание
|
||||||
|
downloadFileAsTxt(linksText, 'not_found_files.txt');
|
||||||
|
} else {
|
||||||
|
// Если битых файлов нет
|
||||||
|
countSpan.innerText = '0';
|
||||||
|
textarea.value = "Недоступных файлов не обнаружено.";
|
||||||
|
downloadBtn.style.display = 'none';
|
||||||
|
resultBox.style.display = 'block';
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
statusSpan.innerText = `Ошибка (${response.status}) ✖`;
|
||||||
|
statusSpan.classList.add('status-error');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
statusSpan.innerText = "Сбой сети ✖";
|
||||||
|
statusSpan.classList.add('status-error');
|
||||||
|
console.error("Task execution error:", error);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.innerText = "Запустить";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// === ВСПОМОГАТЕЛЬНАЯ ФУНКЦИЯ ДЛЯ СКАЧИВАНИЯ TXT ===
|
||||||
|
function downloadFileAsTxt(content, filename) {
|
||||||
|
const blob = new Blob([content], { type: 'text/plain' });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = filename;
|
||||||
|
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user