-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathHelper.php
169 lines (147 loc) · 5.64 KB
/
Helper.php
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
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Notes\Controller;
use OCA\Notes\AppInfo\Application;
use OCA\Notes\Db\Meta;
use OCA\Notes\Service\MetaNote;
use OCA\Notes\Service\MetaService;
use OCA\Notes\Service\Note;
use OCA\Notes\Service\NotesService;
use OCA\Notes\Service\Util;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IRequest;
use OCP\IUserSession;
use Psr\Log\LoggerInterface;
class Helper {
private NotesService $notesService;
private MetaService $metaService;
public LoggerInterface $logger;
private IUserSession $userSession;
public function __construct(
NotesService $notesService,
MetaService $metaService,
IUserSession $userSession,
LoggerInterface $logger,
) {
$this->notesService = $notesService;
$this->metaService = $metaService;
$this->userSession = $userSession;
$this->logger = $logger;
}
public function getUID() : string {
return $this->userSession->getUser()->getUID();
}
public function getNoteWithETagCheck(int $id, IRequest $request) : Note {
$userId = $this->getUID();
$note = $this->notesService->get($userId, $id);
$ifMatch = $request->getHeader('If-Match');
if ($ifMatch) {
$matchEtags = preg_split('/,\s*/', $ifMatch);
$meta = $this->metaService->update($userId, $note);
if (!in_array('"' . $meta->getEtag() . '"', $matchEtags)) {
throw new ETagDoesNotMatchException($note);
}
}
return $note;
}
public function getNoteData(Note $note, array $exclude = [], ?Meta $meta = null) : array {
if ($meta === null) {
$meta = $this->metaService->update($this->getUID(), $note);
}
$data = $note->getData($exclude);
$data['etag'] = $meta->getEtag();
return $data;
}
public function getNotesAndCategories(
int $pruneBefore,
array $exclude,
?string $category = null,
int $chunkSize = 0,
?string $chunkCursorStr = null,
) : array {
$userId = $this->getUID();
$chunkCursor = $chunkCursorStr ? ChunkCursor::fromString($chunkCursorStr) : null;
$lastUpdate = $chunkCursor->timeStart ?? new \DateTime();
$data = $this->notesService->getAll($userId, true); // auto-create notes folder if not exists
$metaNotes = $this->metaService->getAll($userId, $data['notes']);
// if a category is requested, then ignore all other notes
if ($category !== null) {
$metaNotes = array_filter($metaNotes, function (MetaNote $m) use ($category) {
return $m->note->getCategory() === $category;
});
}
// list of notes that should be sent to the client
$fullNotes = array_filter($metaNotes, function (MetaNote $m) use ($pruneBefore, $chunkCursor) {
$isPruned = $pruneBefore && $m->meta->getLastUpdate() < $pruneBefore;
$noteLastUpdate = (int)$m->meta->getLastUpdate();
$isBeforeCursor = $chunkCursor && (
$noteLastUpdate < $chunkCursor->noteLastUpdate
|| ($noteLastUpdate === $chunkCursor->noteLastUpdate
&& $m->note->getId() <= $chunkCursor->noteId)
);
return !$isPruned && !$isBeforeCursor;
});
// sort the list for slicing the next chunk
uasort($fullNotes, function (MetaNote $a, MetaNote $b) {
return $a->meta->getLastUpdate() <=> $b->meta->getLastUpdate()
?: $a->note->getId() <=> $b->note->getId();
});
// slice the next chunk
$chunkedNotes = $chunkSize ? array_slice($fullNotes, 0, $chunkSize, true) : $fullNotes;
$numPendingNotes = count($fullNotes) - count($chunkedNotes);
// if the chunk does not contain all remaining notes, then generate new chunk cursor
$newChunkCursor = $numPendingNotes ? ChunkCursor::fromNote($lastUpdate, end($chunkedNotes)) : null;
// load data for the current chunk
$notesData = array_map(function (MetaNote $m) use ($exclude) {
return $this->getNoteData($m->note, $exclude, $m->meta);
}, $chunkedNotes);
return [
'categories' => $data['categories'],
'notesAll' => $metaNotes,
'notesData' => $notesData,
'lastUpdate' => $lastUpdate,
'chunkCursor' => $newChunkCursor,
'numPendingNotes' => $numPendingNotes,
];
}
public function logException(\Throwable $e) : void {
$this->logger->error('Controller failed with ' . get_class($e), [ 'exception' => $e ]);
}
/** @param 200|201|400|403|404|423|500|507 $statusCode */
public function createErrorResponse(\Throwable $e, int $statusCode) : JSONResponse {
$response = [
'errorType' => get_class($e)
];
return new JSONResponse($response, $statusCode);
}
public function handleErrorResponse(callable $respond) : JSONResponse {
try {
$data = Util::retryIfLocked($respond);
$response = $data instanceof JSONResponse ? $data : new JSONResponse($data);
} catch (\OCA\Notes\Controller\ETagDoesNotMatchException $e) {
$response = new JSONResponse($this->getNoteData($e->note), Http::STATUS_PRECONDITION_FAILED);
} catch (\OCA\Notes\Service\NoteDoesNotExistException $e) {
$this->logException($e);
$response = $this->createErrorResponse($e, Http::STATUS_NOT_FOUND);
} catch (\OCA\Notes\Service\InsufficientStorageException $e) {
$this->logException($e);
$response = $this->createErrorResponse($e, Http::STATUS_INSUFFICIENT_STORAGE);
} catch (\OCA\Notes\Service\NoteNotWritableException $e) {
$this->logException($e);
$response = $this->createErrorResponse($e, Http::STATUS_FORBIDDEN);
} catch (\OCP\Lock\LockedException $e) {
$this->logException($e);
$response = $this->createErrorResponse($e, Http::STATUS_LOCKED);
} catch (\Throwable $e) {
$this->logException($e);
$response = $this->createErrorResponse($e, Http::STATUS_INTERNAL_SERVER_ERROR);
}
$response->addHeader('X-Notes-API-Versions', implode(', ', Application::$API_VERSIONS));
return $response;
}
}