Вложения к записям, профилировщик запросов, приём вебхуков по токену
This commit is contained in:
1 parent
a75f27f3ed
commit
e42404ebe0
33 files changed
+1494
-124
No files matched your search
@@ -21,11 +21,20 @@ use Rsgrinko\Proton\Support\ProtonException;
|
||||
*/
|
||||
final class BackupsController extends Controller
|
||||
{
|
||||
public function index(): Response
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
// Копий бывает много: ручные накапливаются рядом с суточными
|
||||
$files = Backup::files();
|
||||
$perPage = $this->perPage();
|
||||
$pages = max(1, (int) ceil(count($files) / $perPage));
|
||||
$page = min($this->page($request), $pages);
|
||||
|
||||
return $this->view('admin/backups', [
|
||||
'active' => 'backups',
|
||||
'files' => Backup::files(),
|
||||
'files' => array_slice($files, ($page - 1) * $perPage, $perPage),
|
||||
'total' => count($files),
|
||||
'page' => $page,
|
||||
'pages' => $pages,
|
||||
'keep' => (int) Config::get('backup.keep', 7),
|
||||
'schedule' => trim((string) Config::get('backup.schedule', '')),
|
||||
'dir' => Backup::directory(),
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace App\Controllers\Admin;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Logger;
|
||||
|
||||
/**
|
||||
@@ -28,12 +29,16 @@ final class LogsController extends Controller
|
||||
$current = $files[0]['name'] ?? '';
|
||||
}
|
||||
|
||||
$level = $request->text('level');
|
||||
$level = $request->text('level');
|
||||
$needle = $request->text('q');
|
||||
$lines = [];
|
||||
|
||||
// Хвост читаем глубже, а показываем страницами: под фильтр может подойти
|
||||
// и тысяча строк, вываливать их одним куском незачем
|
||||
$depth = max(500, (int) Config::get('log.tail_lines', 2000));
|
||||
|
||||
if ($current !== '') {
|
||||
foreach ($logger->tail($current, 500) as $line) {
|
||||
foreach ($logger->tail($current, $depth) as $line) {
|
||||
$parsed = Logger::parse($line);
|
||||
|
||||
if ($level !== '' && $parsed['level'] !== $level) {
|
||||
@@ -51,11 +56,19 @@ final class LogsController extends Controller
|
||||
$lines = array_reverse($lines);
|
||||
}
|
||||
|
||||
$perPage = $this->perPage();
|
||||
$pages = max(1, (int) ceil(count($lines) / $perPage));
|
||||
$page = min($this->page($request), $pages);
|
||||
|
||||
return $this->view('admin/logs', [
|
||||
'active' => 'logs',
|
||||
'files' => $files,
|
||||
'current' => $current,
|
||||
'lines' => $lines,
|
||||
'lines' => array_slice($lines, ($page - 1) * $perPage, $perPage),
|
||||
'total' => count($lines),
|
||||
'page' => $page,
|
||||
'pages' => $pages,
|
||||
'depth' => $depth,
|
||||
'filters' => ['level' => $level, 'q' => $needle],
|
||||
], 'Логи');
|
||||
}
|
||||
|
||||
@@ -19,11 +19,14 @@ use Rsgrinko\Proton\Support\Audit;
|
||||
*/
|
||||
final class RolesController extends Controller
|
||||
{
|
||||
public function index(): Response
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$page = Role::query()->orderBy('id')->paginate($this->page($request), $this->perPage());
|
||||
|
||||
return $this->view('admin/roles', [
|
||||
'active' => 'roles',
|
||||
'roles' => Role::query()->orderBy('id')->get(),
|
||||
'roles' => $page['items'],
|
||||
'page' => $page,
|
||||
], 'Роли');
|
||||
}
|
||||
|
||||
|
||||
@@ -39,11 +39,32 @@ final class WebhooksController extends Controller
|
||||
'stats' => WebhookDelivery::stats(),
|
||||
'filters' => $filters,
|
||||
// Входящие — обратная сторона: эти посылки присылают нам
|
||||
'incoming' => IncomingHook::query()->orderBy('id', 'desc')->limit(20)->get(),
|
||||
'incoming' => IncomingHook::query()->orderBy('id', 'desc')->limit(5)->get(),
|
||||
'sources' => Incoming::sources(),
|
||||
], 'Вебхуки');
|
||||
}
|
||||
|
||||
/**
|
||||
* Все входящие посылки: страницами и с отбором. В разделе вебхуков
|
||||
* показаны только последние — этого хватает, пока ничего не сломалось.
|
||||
*/
|
||||
public function incoming(Request $request): Response
|
||||
{
|
||||
$filters = $this->filters($request, [
|
||||
Filter::select('status', 'Состояние', IncomingHook::LABELS),
|
||||
Filter::text('source', 'Источник', 'source', 'billing'),
|
||||
Filter::search('q', 'Поиск', ['event', 'error', 'ip'], 'событие, ошибка или адрес'),
|
||||
Filter::dates('when', 'Когда', 'created_at'),
|
||||
])->sortable(['id', 'created_at'], 'id');
|
||||
|
||||
return $this->view('admin/incoming', [
|
||||
'active' => 'webhooks',
|
||||
'page' => $filters->apply(IncomingHook::query())->paginate($this->page($request), $this->perPage()),
|
||||
'filters' => $filters,
|
||||
'sources' => Incoming::sources(),
|
||||
], 'Входящие вебхуки');
|
||||
}
|
||||
|
||||
public function create(): Response
|
||||
{
|
||||
return $this->view('admin/webhook', [
|
||||
|
||||
@@ -10,10 +10,10 @@ use Rsgrinko\Proton\Models\IncomingHook;
|
||||
use Rsgrinko\Proton\Webhooks\Incoming;
|
||||
|
||||
/**
|
||||
* Приём чужих вебхуков: POST /api/v1/hooks/{источник}.
|
||||
* Приём чужих вебхуков: POST или GET /api/v1/hooks/{источник}.
|
||||
*
|
||||
* Ключ API здесь не нужен — чужая система его не знает; вместо него подпись,
|
||||
* которую проверяет `Incoming`. Отвечаем быстро и коротко: отправитель ждёт
|
||||
* Ключ API здесь не нужен — чужая система его не знает; вместо него токен,
|
||||
* который проверяет `Incoming`. Отвечаем быстро и коротко: отправитель ждёт
|
||||
* ответа и повторит посылку, если мы задумаемся.
|
||||
*/
|
||||
final class HooksController extends ApiController
|
||||
@@ -24,7 +24,7 @@ final class HooksController extends ApiController
|
||||
|
||||
return match ($status) {
|
||||
IncomingHook::DONE => $this->data(['status' => 'принято']),
|
||||
IncomingHook::REJECTED => Response::error('Подпись не сошлась', 401),
|
||||
IncomingHook::REJECTED => Response::error('Токен не подошёл', 401),
|
||||
IncomingHook::UNKNOWN => Response::error('Неизвестный источник', 404),
|
||||
// Обработчик упал — посылку мы приняли, повторять её не нужно
|
||||
default => $this->data(['status' => 'принято с ошибкой'], 202),
|
||||
|
||||
@@ -11,6 +11,7 @@ use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Database\Model\Query;
|
||||
use Rsgrinko\Proton\Database\Model\RecordNotFound;
|
||||
use Rsgrinko\Proton\Events\Events;
|
||||
use Rsgrinko\Proton\Files\Attachment;
|
||||
use Rsgrinko\Proton\Files\Storage;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
@@ -288,10 +289,11 @@ final class NotesController extends Controller
|
||||
|
||||
$note->setAttribute('user_id', $viewer->id());
|
||||
|
||||
$this->attachFile($request, $note);
|
||||
|
||||
$note->save();
|
||||
|
||||
// Вложения прикладываются после сохранения: до него у записи нет id
|
||||
$this->attachFile($request, $note);
|
||||
|
||||
Audit::created('note', $note->id(), 'заметка «' . (string) $note->title . '»');
|
||||
|
||||
// Событие уходит подписчикам вебхуков — список в config/webhooks.php
|
||||
@@ -307,9 +309,10 @@ final class NotesController extends Controller
|
||||
$note = $this->find($id, $scope);
|
||||
|
||||
return $this->view('notes/show', [
|
||||
'active' => 'notes',
|
||||
'note' => $note,
|
||||
'author' => $note->author,
|
||||
'active' => 'notes',
|
||||
'note' => $note,
|
||||
'author' => $note->author,
|
||||
'attachments' => Attachment::of('note', $note->id()),
|
||||
], (string) $note->title);
|
||||
}
|
||||
|
||||
@@ -370,7 +373,8 @@ final class NotesController extends Controller
|
||||
|
||||
$this->authorize('note.delete', $note);
|
||||
|
||||
// Мягкое удаление: запись остаётся в базе с отметкой времени
|
||||
// Мягкое удаление: запись остаётся в базе с отметкой времени, а файлы
|
||||
// вложений живут дальше — вернём заметку из корзины, вернутся и они
|
||||
$note->delete();
|
||||
|
||||
Audit::deleted('note', $note->id(), 'заметка «' . (string) $note->title . '»');
|
||||
@@ -443,26 +447,80 @@ final class NotesController extends Controller
|
||||
*/
|
||||
private function attachFile(Request $request, Note $note): void
|
||||
{
|
||||
$file = $request->file('attachment');
|
||||
$files = $request->files('attachment');
|
||||
|
||||
if ($file === null || !$file->uploaded()) {
|
||||
if ($files === [] || $note->id() === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$stored = Storage::put($file, 'notes');
|
||||
} catch (ProtonException $e) {
|
||||
$this->flash($e->getMessage(), 'error');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$previous = (string) $note->raw('file_path');
|
||||
|
||||
$note->forceFill(['file_path' => $stored['path'], 'file_name' => $stored['name']]);
|
||||
|
||||
if ($previous !== '' && $previous !== $stored['path']) {
|
||||
Storage::delete($previous);
|
||||
foreach ($files as $file) {
|
||||
try {
|
||||
Attachment::attach($file, 'note', $note->id(), (int) $note->raw('user_id'));
|
||||
} catch (ProtonException $e) {
|
||||
// Один негодный файл не должен отменять остальные и саму правку
|
||||
$this->flash($file->name() . ': ' . $e->getMessage(), 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Отдаёт вложение. Хранилище лежит вне public, поэтому файлы отдаёт код:
|
||||
* присланный «аватар.php» не должен стать скриптом на сайте.
|
||||
*/
|
||||
public function attachment(int $id, int $attachment, Scope $scope): Response
|
||||
{
|
||||
$note = $this->find($id, $scope);
|
||||
|
||||
/** @var Attachment|null $found */
|
||||
$found = Attachment::query()
|
||||
->where('entity', 'note')
|
||||
->where('entity_id', (string) $note->id())
|
||||
->where('id', $attachment)
|
||||
->first();
|
||||
|
||||
if ($found === null || !Storage::exists((string) $found->raw('path'))) {
|
||||
$this->flash('Файла нет', 'error');
|
||||
|
||||
return $this->redirect('notes.show', ['id' => $note->id()]);
|
||||
}
|
||||
|
||||
return Response::download(
|
||||
Storage::read((string) $found->raw('path')),
|
||||
(string) $found->raw('name'),
|
||||
(string) $found->raw('mime') ?: 'application/octet-stream'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Убрать вложение заметки.
|
||||
*/
|
||||
public function detach(Request $request, int $id, Scope $scope): Response
|
||||
{
|
||||
$note = $this->find($id, $scope);
|
||||
|
||||
$this->authorize('note.edit', $note);
|
||||
|
||||
/** @var Attachment|null $attachment */
|
||||
$attachment = Attachment::query()
|
||||
->where('entity', 'note')
|
||||
->where('entity_id', (string) $note->id())
|
||||
->where('id', (int) $request->input('attachment', 0))
|
||||
->first();
|
||||
|
||||
if ($attachment === null) {
|
||||
$this->flash('Вложения нет', 'error');
|
||||
|
||||
return $this->redirect('notes.show', ['id' => $note->id()]);
|
||||
}
|
||||
|
||||
$name = (string) $attachment->raw('name');
|
||||
|
||||
$attachment->remove();
|
||||
|
||||
Audit::action('note', $note->id(), 'убрано вложение «' . $name . '»');
|
||||
|
||||
$this->flash('Вложение убрано');
|
||||
|
||||
return $this->redirect('notes.show', ['id' => $note->id()]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user