-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathNotesService.php
More file actions
360 lines (320 loc) · 10.8 KB
/
NotesService.php
File metadata and controls
360 lines (320 loc) · 10.8 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
360
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2013 Bernhard Posselt <nukeawhale@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Notes\Service;
use OCP\Files\File;
use OCP\Files\FileInfo;
use OCP\Files\Folder;
use OCP\Files\NotPermittedException;
class NotesService {
private MetaService $metaService;
private SettingsService $settings;
private NoteUtil $noteUtil;
public function __construct(
MetaService $metaService,
SettingsService $settings,
NoteUtil $noteUtil,
) {
$this->metaService = $metaService;
$this->settings = $settings;
$this->noteUtil = $noteUtil;
}
public function getAll(string $userId, bool $autoCreateNotesFolder = false) : array {
$customExtension = $this->getCustomExtension($userId);
try {
$notesFolder = $this->getNotesFolder($userId, $autoCreateNotesFolder);
$data = self::gatherNoteFiles($customExtension, $notesFolder);
$fileIds = array_keys($data['files']);
// pre-load tags for all notes (performance improvement)
$this->noteUtil->getTagService()->loadTags($fileIds);
$notes = array_map(function (File $file) use ($notesFolder) : Note {
return new Note($file, $notesFolder, $this->noteUtil);
}, $data['files']);
} catch (NotesFolderException $e) {
$notes = [];
$data = [ 'categories' => [] ];
}
return [ 'notes' => $notes, 'categories' => $data['categories'] ];
}
public function getTopNotes(string $userId) : array {
$notes = $this->getAll($userId)['notes'];
usort($notes, function (Note $a, Note $b) {
$favA = $a->getFavorite();
$favB = $b->getFavorite();
if ($favA === $favB) {
return $b->getModified() - $a->getModified();
} else {
return $favA > $favB ? -1 : 1;
}
});
return $notes;
}
public function countNotes(string $userId) : int {
$customExtension = $this->getCustomExtension($userId);
try {
$notesFolder = $this->getNotesFolder($userId, false);
$data = self::gatherNoteFiles($customExtension, $notesFolder);
return count($data['files']);
} catch (NotesFolderException $e) {
return 0;
}
}
/**
* @throws NoteDoesNotExistException
*/
public function get(string $userId, int $id) : Note {
$customExtension = $this->getCustomExtension($userId);
$notesFolder = $this->getNotesFolder($userId);
$note = new Note(self::getFileById($customExtension, $notesFolder, $id), $notesFolder, $this->noteUtil);
$this->metaService->update($userId, $note);
return $note;
}
public function search(string $userId, string $search) : array {
$terms = preg_split('/\s+/', $search);
$notes = $this->getAll($userId)['notes'];
return array_values(array_filter(
$notes,
function (Note $note) use ($terms) : bool {
return $this->searchTermsInNote($note, $terms);
}
));
}
private function searchTermsInNote(Note $note, array $terms) : bool {
try {
$d = $note->getData();
$strings = [ $d['title'], $d['category'], $d['content'] ];
foreach ($terms as $term) {
if (!$this->searchTermInData($strings, $term)) {
return false;
}
}
return true;
} catch (\Throwable $e) {
return false;
}
}
private function searchTermInData(array $strings, string $term) : bool {
foreach ($strings as $str) {
if (stripos($str, $term) !== false) {
return true;
}
}
return false;
}
/**
* @throws \OCP\Files\NotPermittedException
*/
public function create(string $userId, string $title, string $category) : Note {
// get folder based on category
$notesFolder = $this->getNotesFolder($userId);
$folder = $this->noteUtil->getCategoryFolder($notesFolder, $category);
$this->noteUtil->ensureSufficientStorage($folder, 1);
// get file name
$fileSuffix = $this->settings->get($userId, 'fileSuffix');
if ($fileSuffix === 'custom') {
$fileSuffix = $this->settings->get($userId, 'customSuffix');
}
$filename = $this->noteUtil->generateFileName($folder, $title, $fileSuffix, -1);
// create file
$file = $folder->newFile($filename);
return new Note($file, $notesFolder, $this->noteUtil);
}
/**
* @throws NoteDoesNotExistException if note does not exist
*/
public function delete(string $userId, int $id) {
$customExtension = $this->getCustomExtension($userId);
$notesFolder = $this->getNotesFolder($userId);
$file = self::getFileById($customExtension, $notesFolder, $id);
$this->noteUtil->ensureNoteIsWritable($file);
$parent = $file->getParent();
$file->delete();
$this->noteUtil->deleteEmptyFolder($parent, $notesFolder);
}
/**
* @throws NoteDoesNotExistException
*/
public function renameCategory(string $userId, string $oldCategory, string $newCategory) : array {
$oldCategory = $this->noteUtil->normalizeCategoryPath($oldCategory);
$newCategory = $this->noteUtil->normalizeCategoryPath($newCategory);
if ($oldCategory === '' || $newCategory === '') {
throw new \InvalidArgumentException('Category must not be empty');
}
if ($oldCategory === $newCategory) {
return [
'oldCategory' => $oldCategory,
'newCategory' => $newCategory,
];
}
if (str_starts_with($newCategory, $oldCategory . '/')) {
throw new \InvalidArgumentException('Target category must not be a descendant of source category');
}
$notesFolder = $this->getNotesFolder($userId);
try {
$oldFolder = $this->noteUtil->getCategoryFolder($notesFolder, $oldCategory, false);
} catch (NotesFolderException $e) {
throw new NoteDoesNotExistException();
}
if ($notesFolder->nodeExists($newCategory)) {
throw new \InvalidArgumentException('Target category already exists');
}
$targetParentCategory = dirname($newCategory);
if ($targetParentCategory === '.') {
$targetParentCategory = '';
}
$targetParent = $this->noteUtil->getCategoryFolder($notesFolder, $targetParentCategory, true);
$oldParent = $oldFolder->getParent();
$targetPath = $targetParent->getPath() . '/' . basename($newCategory);
$oldFolder->move($targetPath);
if ($oldParent instanceof Folder) {
$this->noteUtil->deleteEmptyFolder($oldParent, $notesFolder);
}
return [
'oldCategory' => $oldCategory,
'newCategory' => $newCategory,
];
}
/**
* @throws NoteDoesNotExistException
*/
public function deleteCategory(string $userId, string $category) : array {
$category = $this->noteUtil->normalizeCategoryPath($category);
if ($category === '') {
throw new \InvalidArgumentException('Category must not be empty');
}
$notesFolder = $this->getNotesFolder($userId);
try {
$folder = $this->noteUtil->getCategoryFolder($notesFolder, $category, false);
} catch (NotesFolderException $e) {
// If category folder was already removed (e.g. last note moved away),
// treat delete as idempotent success.
return [
'category' => $category,
];
}
$parent = $folder->getParent();
$folder->delete();
if ($parent instanceof Folder) {
$this->noteUtil->deleteEmptyFolder($parent, $notesFolder);
}
return [
'category' => $category,
];
}
public function getTitleFromContent(string $content) : string {
$content = $this->noteUtil->stripMarkdown($content);
return $this->noteUtil->getSafeTitle($content);
}
private function getNotesFolder(string $userId, bool $create = true) : Folder {
return $this->noteUtil->getOrCreateNotesFolder($userId, $create);
}
/**
* gather note files in given directory and all subdirectories
*/
private static function gatherNoteFiles(
string $customExtension,
Folder $folder,
string $categoryPrefix = '',
) : array {
$data = [
'files' => [],
'categories' => [],
];
$nodes = $folder->getDirectoryListing();
foreach ($nodes as $node) {
if ($node->getType() === FileInfo::TYPE_FOLDER && $node instanceof Folder) {
$subCategory = $categoryPrefix . $node->getName();
$data['categories'][] = $subCategory;
$data_sub = self::gatherNoteFiles($customExtension, $node, $subCategory . '/');
$data['files'] = $data['files'] + $data_sub['files'];
$data['categories'] = $data['categories'] + $data_sub['categories'];
} elseif (self::isNote($node, $customExtension)) {
$data['files'][$node->getId()] = $node;
}
}
return $data;
}
/**
* test if file is a note
*/
private static function isNote(FileInfo $file, string $customExtension) : bool {
static $allowedExtensions = ['txt', 'org', 'markdown', 'md', 'note'];
$ext = strtolower(pathinfo($file->getName(), PATHINFO_EXTENSION));
return $file->getType() === 'file' && (in_array($ext, $allowedExtensions) || $ext === $customExtension);
}
/**
* Retrieve the value of user defined files extension
*/
private function getCustomExtension(string $userId) {
$suffix = $this->settings->get($userId, 'customSuffix');
return ltrim($suffix, '.');
}
/**
* @throws NoteDoesNotExistException
*/
private static function getFileById(string $customExtension, Folder $folder, int $id) : File {
$file = $folder->getById($id);
if (!array_key_exists(0, $file) || !($file[0] instanceof File) || !self::isNote($file[0], $customExtension)) {
throw new NoteDoesNotExistException();
}
return $file[0];
}
/**
* @NoAdminRequired
* @NoCSRFRequired
* @return \OCP\Files\File
*/
public function getAttachment(string $userId, int $noteid, string $path) : File {
$note = $this->get($userId, $noteid);
$notesFolder = $this->getNotesFolder($userId);
$path = str_replace('\\', '/', $path); // change windows style path
$p = explode('/', $note->getCategory());
// process relative target path
foreach (explode('/', $path) as $f) {
if ($f == '..') {
array_pop($p);
} elseif ($f !== '') {
array_push($p, $f);
}
}
$targetNode = $notesFolder->get(implode('/', $p));
assert($targetNode instanceof \OCP\Files\File);
return $targetNode;
}
/**
* @param $userId
* @param $noteid
* @param $fileDataArray
* @throws NotPermittedException
* @throws ImageNotWritableException
* https://github.com/nextcloud/deck/blob/master/lib/Service/AttachmentService.php
*/
public function createImage(string $userId, int $noteid, $fileDataArray) {
$note = $this->get($userId, $noteid);
$notesFolder = $this->getNotesFolder($userId);
$parent = $this->noteUtil->getCategoryFolder($notesFolder, $note->getCategory());
// try to generate long id, if not available on system fall back to a shorter one
try {
$filename = bin2hex(random_bytes(16));
} catch (\Exception $e) {
$filename = uniqid();
}
$parts = explode('.', $fileDataArray['name']);
$filename .= '.' . end($parts);
if ($fileDataArray['tmp_name'] === '') {
throw new ImageNotWritableException();
}
// read uploaded file from disk
$fp = fopen($fileDataArray['tmp_name'], 'r');
$content = fread($fp, $fileDataArray['size']);
fclose($fp);
$result = [];
$result['filename'] = $filename;
$this->noteUtil->getRoot()->newFile($parent->getPath() . '/' . $filename, $content);
return $result;
}
}