You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Ticket/TicketReadModel.php

246 lines
9.5 KiB
PHP

<?php
namespace App\Services\Ticket;
use App\Models\CloudInstance;
use App\Models\Ticket;
use App\Models\TicketAttachment;
use App\Models\User;
use App\Services\AdminDataMasker;
use App\Services\Cloud\CloudInstanceMetadata;
/**
* Builds ticket queues and threads in a fixed number of queries.
*
* Controllers pass the viewer once. Ownership, privacy, authors and private
* attachment visibility stay behind this interface instead of being rebuilt
* by each HTTP adapter and template.
*/
final class TicketReadModel
{
/**
* @return array{tickets: mixed, open_count: int, closed_count: int}
*/
public function queue(TicketQueueQuery $query, TicketViewer $viewer): array
{
$roots = Ticket::where('ticket.rootid', 0);
if (!$viewer->isAdmin) {
$roots->where('ticket.userid', $viewer->actorId);
}
$counts = (clone $roots)
->selectRaw('SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS open_count')
->selectRaw('SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS closed_count')
->first();
$tickets = $roots
->leftJoin('ticket_read_states AS ticket_reader', function ($join) use ($viewer): void {
$join->on('ticket_reader.ticket_id', '=', 'ticket.id')
->where('ticket_reader.reader_id', '=', $viewer->actorId);
})
->select('ticket.*')
->selectRaw('CASE WHEN COALESCE(ticket_reader.last_read_message_id, 0) '
. '< ticket.last_message_id THEN 1 ELSE 0 END AS is_unread')
->selectRaw("CASE WHEN ticket.status = 0 THEN 'closed' "
. "WHEN ticket.last_actor_is_admin = 1 THEN 'user' ELSE 'admin' END AS waiting_for")
->orderByDesc('ticket.last_activity_at')->orderByDesc('ticket.id')
->paginate($query->perPage, ['*'], 'page', $query->page);
return [
'tickets' => $tickets,
'open_count' => (int) ($counts->open_count ?? 0),
'closed_count' => (int) ($counts->closed_count ?? 0),
];
}
/**
* @return array{root: Ticket, title: string, messages: mixed, instance: ?object}|null
*/
public function thread(TicketThreadQuery $query, TicketViewer $viewer): ?array
{
$rootQuery = Ticket::where('id', $query->ticketId)->where('rootid', 0);
if (!$viewer->isAdmin) {
$rootQuery->where('userid', $viewer->actorId);
}
$root = $rootQuery->first();
if ($root === null) {
return null;
}
$messages = Ticket::where(static function ($builder) use ($query): void {
$builder->where('id', $query->ticketId)
->orWhere('rootid', $query->ticketId);
})->orderByDesc('datetime')->orderByDesc('id')
->paginate($query->perPage, ['*'], 'page', $query->page);
$models = $messages->getCollection();
$authorIds = $models->pluck('userid')->map(static fn ($id): int => (int) $id)
->unique()->values()->all();
$authors = $authorIds === []
? collect()
: User::whereIn('id', $authorIds)->get(['id', 'user_name', 'is_admin'])->keyBy('id');
$attachmentsByMessage = collect();
if (!$viewer->isAdmin || $viewer->isSuperAdmin) {
$messageIds = $models->pluck('id')->map(static fn ($id): int => (int) $id)->all();
if ($messageIds !== []) {
$attachmentsByMessage = TicketAttachment::where('ticket_id', (int) $root->id)
->whereIn('message_id', $messageIds)->orderBy('id')->get()
->groupBy('message_id');
}
}
$projected = $models->map(function (Ticket $message) use (
$authors,
$attachmentsByMessage,
$viewer
): object {
$author = $authors->get((int) $message->userid);
$authorIsAdmin = $author !== null && (int) $author->is_admin === 1;
$content = (string) $message->content;
if ($viewer->isAdmin && !$viewer->isSuperAdmin) {
$content = AdminDataMasker::sensitiveText($content);
}
$attachments = ($attachmentsByMessage->get((int) $message->id) ?? collect())
->map(static function (TicketAttachment $attachment): object {
return (object) [
'id' => (int) $attachment->id,
'name' => (string) $attachment->original_name,
'mime' => (string) $attachment->mime_type,
'bytes' => (int) $attachment->bytes,
'bytes_display' => self::bytes((int) $attachment->bytes),
];
})->values()->all();
return (object) [
'id' => (int) $message->id,
'content' => $content,
'datetime' => date('Y-m-d H:i:s', (int) $message->datetime),
'datetime_epoch' => max(0, (int) $message->datetime),
'datetime_iso' => gmdate(DATE_ATOM, (int) $message->datetime),
'author_id' => (int) $message->userid,
'author_is_admin' => $authorIsAdmin,
'viewer_is_author' => (int) $message->userid === $viewer->actorId,
'author_kind' => $this->authorKind($author, $authorIsAdmin, $viewer),
'author_name' => $this->authorName($author, $authorIsAdmin, $viewer),
'attachments' => $attachments,
'has_attachments' => $attachments !== [],
];
});
$messages->setCollection($projected);
$title = (string) $root->title;
if ($viewer->isAdmin && !$viewer->isSuperAdmin) {
$title = AdminDataMasker::sensitiveText($title);
}
return [
'root' => $root,
'title' => $title,
'messages' => $messages,
'instance' => $this->instance($root, $viewer),
];
}
public function markRead(TicketReadCommand $command, TicketViewer $viewer): bool
{
$query = Ticket::where('id', $command->ticketId)->where('rootid', 0);
if (!$viewer->isAdmin) {
$query->where('userid', $viewer->actorId);
}
$root = $query->first();
if ($root === null) {
return false;
}
$lastMessageId = max((int) $root->id, (int) $root->last_message_id);
(new Ticket())->getConnection()->table('ticket_read_states')->updateOrInsert(
['ticket_id' => (int) $root->id, 'reader_id' => $viewer->actorId],
['last_read_message_id' => $lastMessageId, 'read_at' => time()]
);
return true;
}
private function authorName($author, bool $authorIsAdmin, TicketViewer $viewer): string
{
if ($author === null) {
return '用户已删除';
}
if ((int) $author->id === $viewer->actorId) {
return '我';
}
if ($authorIsAdmin) {
return '管理员';
}
$name = (string) $author->user_name;
return $viewer->isAdmin ? AdminDataMasker::account($name) : $name;
}
private function authorKind($author, bool $authorIsAdmin, TicketViewer $viewer): string
{
if ($author === null) {
return 'deleted';
}
if ((int) $author->id === $viewer->actorId) {
return 'self';
}
if ($authorIsAdmin) {
return 'admin';
}
return 'account';
}
private function instance(Ticket $root, TicketViewer $viewer): ?object
{
$instanceId = (int) ($root->instance_id ?? 0);
if ($instanceId < 1) {
return null;
}
// The ticket owner remains the authority for this relationship. A
// stale or manually altered instance_id must never disclose another
// user's instance metadata to either HTTP adapter.
$instance = CloudInstance::where('id', $instanceId)
->where('user_id', (int) $root->userid)
->where('status', '<>', 'deleted')
->first(['id', 'name', 'spec_json']);
if ($instance === null) {
return null;
}
$decoded = json_decode((string) $instance->spec_json, true);
$network = CloudInstanceMetadata::publicSpec(
is_array($decoded) && !array_is_list($decoded) ? $decoded : []
);
$publicIpv4 = ($network['public_network_valid'] ?? false) === true
? (string) ($network['public_ipv4'] ?? '') : '';
$publicIpv6 = ($network['public_network_valid'] ?? false) === true
? (string) ($network['public_ipv6'] ?? '') : '';
if ($viewer->isAdmin && !$viewer->isSuperAdmin) {
$publicIpv4 = $publicIpv4 === '' ? ''
: AdminDataMasker::ip($publicIpv4);
$publicIpv6 = $publicIpv6 === '' ? ''
: AdminDataMasker::ip($publicIpv6);
}
return (object) [
'id' => (int) $instance->id,
'name' => (string) $instance->name,
'public_ipv4' => $publicIpv4,
'public_ipv6' => $publicIpv6,
'detail_url' => $viewer->isAdmin
? '/admin/cloud/instances?q=' . (int) $instance->id
: '/user/cloud/instances/' . (int) $instance->id,
];
}
private static function bytes(int $bytes): string
{
if ($bytes < 1024) {
return $bytes . ' B';
}
if ($bytes < 1024 * 1024) {
return number_format($bytes / 1024, 1) . ' KiB';
}
return number_format($bytes / (1024 * 1024), 1) . ' MiB';
}
}