-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathSearchRetrieveApi.php
More file actions
222 lines (203 loc) · 9.02 KB
/
SearchRetrieveApi.php
File metadata and controls
222 lines (203 loc) · 9.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<?php
declare(strict_types=1);
namespace App\Controller\Api\Search;
use App\ActivityPub\ActorHandle;
use App\Controller\Api\BaseApi;
use App\Controller\Traits\PrivateContentTrait;
use App\DTO\SearchResponseDto;
use App\Entity\Entry;
use App\Entity\EntryComment;
use App\Entity\Magazine;
use App\Entity\Post;
use App\Entity\PostComment;
use App\Entity\User;
use App\Repository\SearchRepository;
use App\Schema\PaginationSchema;
use App\Service\SearchManager;
use Nelmio\ApiDocBundle\Attribute\Model;
use OpenApi\Attributes as OA;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\RateLimiter\RateLimiterFactoryInterface;
class SearchRetrieveApi extends BaseApi
{
use PrivateContentTrait;
#[OA\Response(
response: 200,
description: 'Returns a paginated list of content, along with any ActivityPub actors that matched the query by username, or ActivityPub objects that matched the query by URL. AP-Objects are not paginated.',
content: new OA\JsonContent(
type: 'object',
properties: [
new OA\Property(
property: 'items',
type: 'array',
items: new OA\Items(ref: new Model(type: SearchResponseDto::class))
),
new OA\Property(
property: 'pagination',
ref: new Model(type: PaginationSchema::class)
),
new OA\Property(
property: 'apResults',
type: 'array',
items: new OA\Items(ref: new Model(type: SearchResponseDto::class))
),
]
),
headers: [
new OA\Header(header: 'X-RateLimit-Remaining', schema: new OA\Schema(type: 'integer'), description: 'Number of requests left until you will be rate limited'),
new OA\Header(header: 'X-RateLimit-Retry-After', schema: new OA\Schema(type: 'integer'), description: 'Unix timestamp to retry the request after'),
new OA\Header(header: 'X-RateLimit-Limit', schema: new OA\Schema(type: 'integer'), description: 'Number of requests available'),
]
)]
#[OA\Response(
response: 400,
description: 'The search query parameter `q` is required!',
content: new OA\JsonContent(ref: new Model(type: \App\Schema\Errors\BadRequestErrorSchema::class))
)]
#[OA\Response(
response: 401,
description: 'Permission denied due to missing or expired token',
content: new OA\JsonContent(ref: new Model(type: \App\Schema\Errors\UnauthorizedErrorSchema::class))
)]
#[OA\Response(
response: 429,
description: 'You are being rate limited',
content: new OA\JsonContent(ref: new Model(type: \App\Schema\Errors\TooManyRequestsErrorSchema::class)),
headers: [
new OA\Header(header: 'X-RateLimit-Remaining', schema: new OA\Schema(type: 'integer'), description: 'Number of requests left until you will be rate limited'),
new OA\Header(header: 'X-RateLimit-Retry-After', schema: new OA\Schema(type: 'integer'), description: 'Unix timestamp to retry the request after'),
new OA\Header(header: 'X-RateLimit-Limit', schema: new OA\Schema(type: 'integer'), description: 'Number of requests available'),
]
)]
#[OA\Parameter(
name: 'p',
description: 'Page of items to retrieve',
in: 'query',
schema: new OA\Schema(type: 'integer', default: 1, minimum: 1)
)]
#[OA\Parameter(
name: 'perPage',
description: 'Number of items per page',
in: 'query',
schema: new OA\Schema(type: 'integer', default: SearchRepository::PER_PAGE, minimum: self::MIN_PER_PAGE, maximum: self::MAX_PER_PAGE)
)]
#[OA\Parameter(
name: 'q',
description: 'Search term',
in: 'query',
required: true,
schema: new OA\Schema(type: 'string')
)]
#[OA\Parameter(
name: 'authorId',
description: 'User id of the author',
in: 'query',
required: false,
schema: new OA\Schema(type: 'integer')
)]
#[OA\Parameter(
name: 'magazineId',
description: 'Id of the magazine',
in: 'query',
required: false,
schema: new OA\Schema(type: 'integer')
)]
#[OA\Parameter(
name: 'type',
description: 'The type of content',
in: 'query',
required: false,
schema: new OA\Schema(type: 'string', enum: ['', 'entry', 'post'])
)]
#[OA\Tag(name: 'search')]
public function __invoke(
SearchManager $manager,
RateLimiterFactoryInterface $apiReadLimiter,
RateLimiterFactoryInterface $anonymousApiReadLimiter,
): JsonResponse {
$headers = $this->rateLimit($apiReadLimiter, $anonymousApiReadLimiter);
$request = $this->request->getCurrentRequest();
/** @var string $q */
$q = $request->get('q');
if (null === $q) {
throw new BadRequestHttpException();
}
$page = $this->getPageNb($request);
$perPage = self::constrainPerPage($request->get('perPage', SearchRepository::PER_PAGE));
$authorIdRaw = $request->get('authorId');
$authorId = null === $authorIdRaw ? null : \intval($authorIdRaw);
$magazineIdRaw = $request->get('magazineId');
$magazineId = null === $magazineIdRaw ? null : \intval($magazineIdRaw);
$type = $request->get('type');
if ('entry' !== $type && 'post' !== $type && null !== $type) {
throw new BadRequestHttpException();
}
/** @var ?SearchResponseDto $searchResults */
$searchResults = [];
$items = $manager->findPaginated($this->getUser(), $q, $page, $perPage, authorId: $authorId, magazineId: $magazineId, specificType: $type);
foreach ($items->getCurrentPageResults() as $item) {
$searchResults[] = $this->serializeItem($item);
}
/** @var ?SearchResponseDto $apResults */
$apResults = [];
if ($this->federatedSearchAllowed()) {
if ($handle = ActorHandle::parse($q)) {
$actors = $manager->findActivityPubActorsByUsername($handle);
foreach ($actors as $actor) {
$apResults[] = $this->serializeItem($actor['object']);
}
} else {
$objects = $manager->findActivityPubObjectsByURL($q);
foreach ($objects['errors'] as $error) {
/** @var \Exception $error */
$this->logger->warning(
'Exception while resolving URL {url}: {type}: {msg}',
[
'url' => $q,
'type' => \get_class($error),
'msg' => $error->getMessage(),
]
);
}
foreach ($objects['results'] as $object) {
$apResults[] = $this->serializeItem($object['object']);
}
}
}
$response = $this->serializePaginated($searchResults, $items);
$response['apResults'] = $apResults;
return new JsonResponse(
$response,
headers: $headers
);
}
private function federatedSearchAllowed(): bool
{
return !$this->settingsManager->get('KBIN_FEDERATED_SEARCH_ONLY_LOGGEDIN')
|| $this->getUser();
}
private function serializeItem(object $item): ?SearchResponseDto
{
if ($item instanceof Entry) {
$this->handlePrivateContent($item);
return new SearchResponseDto(entry: $this->serializeEntry($this->entryFactory->createDto($item), $this->tagLinkRepository->getTagsOfContent($item)));
} elseif ($item instanceof Post) {
$this->handlePrivateContent($item);
return new SearchResponseDto(post: $this->serializePost($this->postFactory->createDto($item), $this->tagLinkRepository->getTagsOfContent($item)));
} elseif ($item instanceof EntryComment) {
$this->handlePrivateContent($item);
return new SearchResponseDto(entryComment: $this->serializeEntryComment($this->entryCommentFactory->createDto($item), $this->tagLinkRepository->getTagsOfContent($item)));
} elseif ($item instanceof PostComment) {
$this->handlePrivateContent($item);
return new SearchResponseDto(postComment: $this->serializePostComment($this->postCommentFactory->createDto($item), $this->tagLinkRepository->getTagsOfContent($item)));
} elseif ($item instanceof Magazine) {
return new SearchResponseDto(magazine: $this->serializeMagazine($this->magazineFactory->createDto($item)));
} elseif ($item instanceof User) {
return new SearchResponseDto(user: $this->serializeUser($this->userFactory->createDto($item)));
} else {
$this->logger->error('Unexpected result type: '.\get_class($item));
return null;
}
}
}