This commit is contained in:
Nyako
2026-06-06 15:30:28 +03:00
parent 21e37776f9
commit b2b2145c37
3 changed files with 123 additions and 26 deletions
+4
View File
@@ -56,6 +56,7 @@ def post(post_id):
@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:
@@ -100,6 +101,9 @@ def api():
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
+9
View File
@@ -41,6 +41,15 @@ def get_size_edge(type_searсh: bool, file_list: list[str]):
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"], [])
+110 -26
View File
@@ -17,20 +17,18 @@
/* 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; }
/* Добавил 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; }
@@ -44,6 +42,10 @@
.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; }
@@ -75,48 +77,46 @@
</div>
</div>
<!-- ШАБЛОН ДЛЯ БУДУЩИХ ЗАДАЧ (просто скопируйте блок ниже и измените 'task_name') -->
<!--
<!-- ЗАДАЧА 2: Поиск недоступных файлов -->
<div class="task-card">
<div class="task-info">
<h3>Новая задача</h3>
<p>Описание новой задачи.</p>
<h3>Поиск недоступных файлов</h3>
<p>Ищет посты, для которых отсутствуют физические файлы на диске. Выводит список ссылок на экран и предлагает скачать их в формате .txt.</p>
</div>
<div class="task-actions">
<span class="task-status"></span>
<button class="btn" onclick="executeTask('new_task_name', this)">Запустить</button>
<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"; // сброс классов успеха/ошибки
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
})
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: "task", task: taskName })
});
// Обработка ответа (200 - успех, 500+ - ошибка)
if (response.ok) {
statusSpan.innerText = "Успешно ✔";
statusSpan.classList.add('status-success');
@@ -125,16 +125,100 @@
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>