-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathContextController.php
More file actions
359 lines (338 loc) · 12.4 KB
/
ContextController.php
File metadata and controls
359 lines (338 loc) · 12.4 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Tables\Controller;
use InvalidArgumentException;
use OCA\Tables\AppInfo\Application;
use OCA\Tables\Db\Context;
use OCA\Tables\Errors\BadRequestError;
use OCA\Tables\Errors\InternalError;
use OCA\Tables\Errors\NotFoundError;
use OCA\Tables\Errors\PermissionError;
use OCA\Tables\Middleware\Attribute\RequirePermission;
use OCA\Tables\ResponseDefinitions;
use OCA\Tables\Service\ContextService;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\UserRateLimit;
use OCP\AppFramework\Http\DataResponse;
use OCP\DB\Exception;
use OCP\IL10N;
use OCP\IRequest;
use Psr\Log\LoggerInterface;
/**
* @psalm-import-type TablesContext from ResponseDefinitions
*/
class ContextController extends AOCSController {
private ContextService $contextService;
public function __construct(
IRequest $request,
LoggerInterface $logger,
IL10N $n,
string $userId,
ContextService $contextService,
) {
parent::__construct($request, $logger, $n, $userId);
$this->contextService = $contextService;
$this->userId = $userId;
}
/**
* [api v2] Get all contexts available to the requesting person
*
* Return an empty array if no contexts were found
*
* @return DataResponse<Http::STATUS_OK, list<TablesContext>, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
*
* 200: reporting in available contexts
*/
#[NoAdminRequired]
public function index(): DataResponse {
try {
$contexts = $this->contextService->findAll($this->userId);
return new DataResponse($this->contextsToArray($contexts));
} catch (InternalError|Exception $e) {
return $this->handleError($e);
}
}
/**
* [api v2] Get information about the requests context
*
* @param int $contextId ID of the context
* @return DataResponse<Http::STATUS_OK, TablesContext, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
*
* 200: returning the full context information
* 404: context not found or not available anymore
*
*/
#[NoAdminRequired]
public function show(int $contextId): DataResponse {
try {
$context = $this->contextService->findById($contextId, $this->userId);
return new DataResponse($context->jsonSerialize());
} catch (NotFoundError $e) {
return $this->handleNotFoundError($e);
} catch (InternalError|Exception $e) {
return $this->handleError($e);
}
}
/**
* [api v2] Create a new context and return it
*
* @param string $name Name of the context
* @param string $iconName Material design icon name of the context
* @param string $description Descriptive text of the context
* @psalm-param list<array{id: int, type: int, permissions?: int}> $nodes optional nodes to be connected to this context
*
* @return DataResponse<Http::STATUS_OK, TablesContext, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_BAD_REQUEST|Http::STATUS_FORBIDDEN, array{message: string}, array{}>
*
* 200: returning the full context information
* 400: invalid parameters were supplied
* 403: lacking permissions on a resource
*/
#[NoAdminRequired]
public function create(string $name, string $iconName, string $description = '', array $nodes = []): DataResponse {
try {
if (!$this->isValidIcon($iconName)) {
return new DataResponse(['message' => 'Invalid icon name'], Http::STATUS_BAD_REQUEST);
}
return new DataResponse($this->contextService->create(
$name,
$iconName,
$description,
$this->sanitizeInputNodes($nodes),
$this->userId,
0,
)->jsonSerialize());
} catch (Exception $e) {
return $this->handleError($e);
} catch (PermissionError $e) {
return $this->handlePermissionError($e);
} catch (InvalidArgumentException $e) {
return $this->handleError(new InternalError($e->getMessage(), $e->getCode(), $e));
}
}
/**
* [api v2] Update an existing context and return it
*
* @param int $contextId ID of the context
* @param ?string $name provide this parameter to set a new name
* @param ?string $iconName provide this parameter to set a new icon
* @param ?string $description provide this parameter to set a new description
* @param ?array{id: int, type: int, permissions: int, order: int} $nodes provide this parameter to set a new list of nodes.
*
* @return DataResponse<Http::STATUS_OK, TablesContext, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND|Http::STATUS_FORBIDDEN|Http::STATUS_BAD_REQUEST, array{message: string}, array{}>
*
* 200: returning the full context information
* 400: bad request
* 403: No permissions
* 404: Not found
*
* @CanManageContext
*/
#[NoAdminRequired]
public function update(int $contextId, ?string $name, ?string $iconName, ?string $description, ?array $nodes): DataResponse {
try {
if ($iconName !== null && !$this->isValidIcon($iconName)) {
return new DataResponse(['message' => 'Invalid icon name'], Http::STATUS_BAD_REQUEST);
}
$nodes = $nodes !== null ? $this->sanitizeInputNodes($nodes) : null;
return new DataResponse($this->contextService->update(
$contextId,
$this->userId,
$name,
$iconName,
$description,
$nodes,
)->jsonSerialize());
} catch (Exception|MultipleObjectsReturnedException $e) {
return $this->handleError($e);
} catch (PermissionError $e) {
return $this->handlePermissionError($e);
} catch (DoesNotExistException $e) {
return $this->handleNotFoundError(new NotFoundError($e->getMessage(), $e->getCode(), $e));
}
}
/**
* @psalm-param list<array{id: mixed, type: mixed, permissions?: mixed, order?: mixed}> $nodes
* @psalm-return list<array{id: int, type: int, permissions?: int, order?: int}>
*/
protected function sanitizeInputNodes(array $nodes): array {
foreach ($nodes as &$node) {
if (!is_numeric($node['type'])) {
throw new InvalidArgumentException('Unexpected node type');
}
$node['type'] = (int)$node['type'];
if (!is_numeric($node['id'])) {
throw new InvalidArgumentException('Unexpected node id');
}
$node['id'] = (int)$node['id'];
if (isset($node['permissions'])) {
$node['permissions'] = (int)$node['permissions'];
}
if (isset($node['order'])) {
$node['order'] = (int)$node['order'];
}
}
return $nodes;
}
/**
* [api v2] Delete an existing context and return it
*
* @param int $contextId ID of the context
* @return DataResponse<Http::STATUS_OK, TablesContext, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND|Http::STATUS_FORBIDDEN, array{message: string}, array{}>
*
* 200: returning the full context information
* 403: No permissions
* 404: Not found
*
* @CanManageContext
*/
#[NoAdminRequired]
public function destroy(int $contextId): DataResponse {
try {
return new DataResponse($this->contextService->delete($contextId, $this->userId)->jsonSerialize());
} catch (Exception $e) {
return $this->handleError($e);
} catch (NotFoundError $e) {
return $this->handleNotFoundError($e);
}
}
/**
* [api v2] Transfer the ownership of a context and return it
*
* @param int $contextId ID of the context
* @param string $newOwnerId ID of the new owner
* @param int $newOwnerType any Application::OWNER_TYPE_* constant
*
* @return DataResponse<Http::STATUS_OK, TablesContext, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_FORBIDDEN|Http::STATUS_NOT_FOUND|Http::STATUS_BAD_REQUEST, array{message: string}, array{}>
*
* 200: Ownership transferred
* 400: Invalid request
* 403: No permissions
* 404: Not found
*
* @CanManageContext
*
* @psalm-param int<0, max> $contextId
* @psalm-param int<0, 0> $newOwnerType
*/
#[NoAdminRequired]
public function transfer(int $contextId, string $newOwnerId, int $newOwnerType = 0): DataResponse {
try {
return new DataResponse($this->contextService->transfer($contextId, $newOwnerId, $newOwnerType)->jsonSerialize());
} catch (Exception|MultipleObjectsReturnedException $e) {
return $this->handleError($e);
} catch (DoesNotExistException $e) {
return $this->handleNotFoundError(new NotFoundError($e->getMessage(), $e->getCode(), $e));
} catch (BadRequestError $e) {
return $this->handleBadRequestError($e);
}
}
/**
* [api v2] Archive a context for the requesting user
*
* Owners archive the context for all users (clears per-user overrides).
* Non-owners archive only for themselves.
*
* @param int $contextId ID of the context
* @return DataResponse<Http::STATUS_OK, TablesContext, array{}>|DataResponse<Http::STATUS_FORBIDDEN|Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
*
* 200: Context returned with updated archived state
* 403: No permissions
* 404: Context not found or not available
*/
#[NoAdminRequired]
#[UserRateLimit(limit: 20, period: 60)]
#[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_CONTEXT, idParam: 'contextId')]
public function archiveContext(int $contextId): DataResponse {
try {
return new DataResponse($this->contextService->archiveContext($contextId, $this->userId)->jsonSerialize());
} catch (PermissionError $e) {
return $this->handlePermissionError($e);
} catch (NotFoundError $e) {
return $this->handleNotFoundError($e);
} catch (InternalError|Exception $e) {
return $this->handleError($e);
}
}
/**
* [api v2] Unarchive a context for the requesting user
*
* Owners unarchive the context for all users (clears per-user overrides).
* Non-owners remove only their personal archive override.
*
* @param int $contextId ID of the context
* @return DataResponse<Http::STATUS_OK, TablesContext, array{}>|DataResponse<Http::STATUS_FORBIDDEN|Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
*
* 200: Context returned with updated archived state
* 403: No permissions
* 404: Context not found or not available
*/
#[NoAdminRequired]
#[UserRateLimit(limit: 20, period: 60)]
#[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_CONTEXT, idParam: 'contextId')]
public function unarchiveContext(int $contextId): DataResponse {
try {
return new DataResponse($this->contextService->unarchiveContext($contextId, $this->userId)->jsonSerialize());
} catch (PermissionError $e) {
return $this->handlePermissionError($e);
} catch (NotFoundError $e) {
return $this->handleNotFoundError($e);
} catch (InternalError|Exception $e) {
return $this->handleError($e);
}
}
/**
* [api v2] Update the order on a page of a context
*
* @param int $contextId ID of the context
* @param int $pageId ID of the page
* @param array{id: int, order: int} $content content items with it and order values
*
* @return DataResponse<Http::STATUS_OK, TablesContext, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND|Http::STATUS_FORBIDDEN|Http::STATUS_BAD_REQUEST, array{message: string}, array{}>
*
* @CanManageContext
*
* 200: content updated successfully
* 400: Invalid request
* 403: No permissions
* 404: Not found
*/
#[NoAdminRequired]
public function updateContentOrder(int $contextId, int $pageId, array $content): DataResponse {
try {
$context = $this->contextService->findById($contextId, $this->userId);
} catch (Exception|InternalError $e) {
return $this->handleError($e);
} catch (NotFoundError $e) {
return $this->handleNotFoundError($e);
}
if (!isset($context->getPages()[$pageId])) {
return $this->handleBadRequestError(new BadRequestError('Page not found in given Context'));
}
return new DataResponse($this->contextService->updateContentOrder($pageId, $content));
}
protected function isValidIcon(string $iconName): bool {
if ($iconName === '' || !preg_match('/^[a-zA-Z0-9-]+$/', $iconName)) {
return false;
}
$iconPath = dirname(__DIR__, 2) . '/img/material/' . $iconName . '.svg';
return file_exists($iconPath);
}
/**
* @param Context[] $contexts
* @return array
*/
protected function contextsToArray(array $contexts): array {
$result = [];
foreach ($contexts as $context) {
$result[] = $context->jsonSerialize();
}
return $result;
}
}