This commit is contained in:
Hell13Cat
2026-06-06 12:05:30 +03:00
parent bd3036f058
commit 34f144d240
7 changed files with 296 additions and 39 deletions
+2 -2
View File
@@ -6,7 +6,7 @@
// @grant GM_registerMenuCommand // @grant GM_registerMenuCommand
// @grant GM_getValue // @grant GM_getValue
// @grant GM_setValue // @grant GM_setValue
// @version 1.0r // @version 1.1r
// @author https://t.me/Nyako_TW // @author https://t.me/Nyako_TW
// @downloadURL https://git.nekono.su/Nyako/Local-Booru/raw/branch/main/button_script.user.js // @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 // @updateURL https://git.nekono.su/Nyako/Local-Booru/raw/branch/main/button_script.user.js
@@ -107,7 +107,7 @@ if (originalImageLinkElement) {
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json"
}, },
data: JSON.stringify({ id: imageID }), data: JSON.stringify({ id: imageID , type: "download"}),
onload: function(response) { onload: function(response) {
console.log('Ответ от API:', response.responseText); console.log('Ответ от API:', response.responseText);
newDownloadButton.style.outline = "2px solid green"; // Успех newDownloadButton.style.outline = "2px solid green"; // Успех
+38 -31
View File
@@ -8,7 +8,7 @@ import requests
from flask import (Flask, jsonify, render_template, render_template_string, from flask import (Flask, jsonify, render_template, render_template_string,
request, send_from_directory, make_response) request, send_from_directory, make_response)
from system_module import db, gelbooru, image_processor, logger from system_module import db, gelbooru, image_processor, logger, tasks
if Path("config_gb.json").exists(): if Path("config_gb.json").exists():
CONFIG_FILE = "config_gb.json" CONFIG_FILE = "config_gb.json"
@@ -53,6 +53,10 @@ def index():
def analytics(): def analytics():
return render_template("analytics.html") return render_template("analytics.html")
@app.route("/task")
def task():
return render_template("task.html")
@app.route("/post/<path:post_id>") @app.route("/post/<path:post_id>")
def post(post_id): def post(post_id):
return render_template("post.html") return render_template("post.html")
@@ -69,9 +73,40 @@ def serve_image(filename):
def serve_thumb(filename): def serve_thumb(filename):
return send_from_directory(THUMB_FOLDER, filename) return send_from_directory(THUMB_FOLDER, filename)
@app.route("/dw_api", methods=['POST']) @app.route("/api", methods=["GET", "POST"])
def dw_api(): def api():
data = request.get_json() 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"] == "task":
if data["task"] == "analytic":
if tasks.calculate_analytic():
return "", 200
else:
return "", 500
elif data["type"] == "download":
if not data or 'id' not in data: if not data or 'id' not in data:
return jsonify({'status': 'error', 'message': 'URL not get'}), 400 return jsonify({'status': 'error', 'message': 'URL not get'}), 400
image_id = data["id"] image_id = data["id"]
@@ -104,34 +139,6 @@ def dw_api():
error_message = f"Unknown error: {e}" error_message = f"Unknown error: {e}"
log.send("error", "all", error_message) log.send("error", "all", error_message)
return jsonify({'status': 'error', 'message': error_message}), 500 return jsonify({'status': 'error', 'message': error_message}), 500
@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)
else: else:
pass pass
return "", 204 return "", 204
+2
View File
@@ -0,0 +1,2 @@
def calculate_analytic():
pass
+2
View File
@@ -18,6 +18,7 @@
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; } 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; } .logo { font-weight: bold; font-size: 18px; color: white; text-decoration: none; }
.analytics { color: #88bece; text-decoration: none; font-size: 12px; } .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 { 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 { width: 100%; background-color: var(--bg-input); border: 1px solid var(--border-color); color: white; padding: 6px 10px; border-radius: 3px; outline: none; }
@@ -66,6 +67,7 @@
<!-- <!--
<a class="analytics" href="/analytics">📊 Analytics</a> <a class="analytics" href="/analytics">📊 Analytics</a>
--> -->
<a class="tasks" href="/task">⚙️ Tasks</a>
<div class="search-wrapper"> <div class="search-wrapper">
<input type="text" id="searchInput" placeholder="Search tags..."> <input type="text" id="searchInput" placeholder="Search tags...">
<ul id="autocompleteList" class="autocomplete-list"></ul> <ul id="autocompleteList" class="autocomplete-list"></ul>
+182
View File
@@ -0,0 +1,182 @@
<!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; }
.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 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; }
.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; transition: background-color 0.2s; }
.task-card:hover { background-color: var(--bg-box); }
.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); }
@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>
<div class="search-wrapper">
<input type="text" id="searchInput" placeholder="Search tags...">
<ul id="autocompleteList" class="autocomplete-list"></ul>
</div>
</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>
<!-- ШАБЛОН ДЛЯ БУДУЩИХ ЗАДАЧ (просто скопируйте блок ниже и измените 'task_name') -->
<!--
<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('new_task_name', this)">Запустить</button>
</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 {
// Отправляем POST запрос на API
const response = await fetch('/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
type: "task",
task: taskName
})
});
// Обработка ответа (200 - успех, 500+ - ошибка)
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 = "Запустить";
}
}
// === ЛОГИКА ПОИСКА (оставлена из предыдущей версии) ===
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 };
const data = await mockAutocompleteAPI(req);
if (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();
});
});
}, 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=${searchInput.value.trim()}`; });
// Заглушка для поиска (оставьте или замените на ваш fetch)
function mockAutocompleteAPI(req) { return new Promise(res => { const db = [{tag: "long_hair", count: 8184}, {tag: "1girl", count: 11061}]; res(db.filter(t => t.tag.includes(req.q.toLowerCase()))); }); }
</script>
</body>
</html>
+5
View File
@@ -0,0 +1,5 @@
{
"host":"https://git.nekono.su",
"user":"Nyako",
"repo":"Local-Booru"
}
+59
View File
@@ -0,0 +1,59 @@
import os
import json
import shutil
import tempfile
import zipfile
import urllib.request
CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.json")
EXCLUDE_PATHS = {
"data",
"config.json",
"logs.log",
"updater"
}
def load_config():
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
return json.load(f)
def get_latest_release(cfg):
url = f"{cfg['host']}/api/v1/repos/{cfg['user']}/{cfg['repo']}/releases/latest"
with urllib.request.urlopen(url) as r:
return json.loads(r.read().decode("utf-8"))
def download(url, path):
urllib.request.urlretrieve(url, path)
def should_exclude(relative_path: str) -> bool:
parts = set(relative_path.split(os.sep))
return any(ex in parts for ex in EXCLUDE_PATHS)
def apply_update(src_root, target_root):
for root, dirs, files in os.walk(src_root):
rel_dir = os.path.relpath(root, src_root)
if rel_dir == ".":
rel_dir = ""
for file in files:
rel_path = os.path.normpath(os.path.join(rel_dir, file))
if should_exclude(rel_path):
continue
src_file = os.path.join(root, file)
dst_file = os.path.join(target_root, rel_path)
os.makedirs(os.path.dirname(dst_file), exist_ok=True)
shutil.copy2(src_file, dst_file)
cfg = load_config()
release = get_latest_release(cfg)
zip_url = release["zipball_url"]
tmp = tempfile.mkdtemp()
zip_path = os.path.join(tmp, "release.zip")
print("Downloading:", release["tag_name"])
download(zip_url, zip_path)
with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(tmp)
extracted_root = os.path.join(tmp, os.listdir(tmp)[0])
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
apply_update(extracted_root, project_root)
print("Update success!")