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
361
362
363
364
365
366
367
368
369
370
371
|
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Text\Service;
use \InvalidArgumentException;
use function json_encode;
use OC\Files\Node\File;
use OCA\Text\Db\Document;
use OCA\Text\Db\DocumentMapper;
use OCA\Text\Db\Step;
use OCA\Text\Db\StepMapper;
use OCA\Text\DocumentSaveConflictException;
use OCA\Text\VersionMismatchException;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\Entity;
use OCP\Constants;
use OCP\Files\Folder;
use OCP\Files\GenericFileException;
use OCP\Files\IAppData;
use OCP\Files\InvalidPathException;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\Files\SimpleFS\ISimpleFile;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\ILogger;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager as ShareManager;
class DocumentService {
/**
* Delay to wait for between autosave versions
*/
public const AUTOSAVE_MINIMUM_DELAY = 60;
/**
* @var string|null
*/
private $userId;
/**
* @var DocumentMapper
*/
private $documentMapper;
/**
* @var ILogger
*/
private $logger;
/**
* @var ShareManager
*/
private $shareManager;
/**
* @var StepMapper
*/
private $stepMapper;
/**
* @var IRootFolder
*/
private $rootFolder;
/**
* @var ICache
*/
private $cache;
/**
* @var IAppData
*/
private $appData;
public function __construct(DocumentMapper $documentMapper, StepMapper $stepMapper, IAppData $appData, $userId, IRootFolder $rootFolder, ICacheFactory $cacheFactory, ILogger $logger, ShareManager $shareManager) {
$this->documentMapper = $documentMapper;
$this->stepMapper = $stepMapper;
$this->userId = $userId;
$this->appData = $appData;
$this->rootFolder = $rootFolder;
$this->cache = $cacheFactory->createDistributed('text');
$this->logger = $logger;
$this->shareManager = $shareManager;
try {
$this->appData->getFolder('documents');
} catch (NotFoundException $e) {
$this->appData->newFolder('documents');
}
}
/**
* @param $path
* @return array
* @throws NotFoundException
* @throws InvalidPathException
* @throws NotPermittedException
*/
public function createDocumentByPath($path) {
/** @var File $file */
$file = $this->rootFolder->getUserFolder($this->userId)->get($path);
return [$this->createDocument($file), $file];
}
/**
* @param $fileId
* @return array
* @throws NotFoundException
* @throws InvalidPathException
* @throws NotPermittedException
*/
public function createDocumentByFileId($fileId) {
$file = $this->getFileById($fileId);
return [$this->createDocument($file), $file];
}
/**
* @param $shareToken
* @param null $filePath
* @return array
* @throws InvalidPathException
* @throws NotFoundException
* @throws NotPermittedException
*/
public function createDocumentByShareToken($shareToken, $filePath = null) {
$file = $this->getFileByShareToken($shareToken, $filePath);
return [$this->createDocument($file), $file];
}
/**
* @param File $file
* @return Entity
* @throws NotFoundException
* @throws InvalidPathException
* @throws NotPermittedException
*/
protected function createDocument(File $file): Document {
try {
$document = $this->documentMapper->find($file->getFileInfo()->getId());
// Do not hard reset if changed from outside since this will throw away possible steps
// This way the user can still resolve conflicts in the editor view
if ($document->getLastSavedVersion() !== $document->getCurrentVersion()) {
$this->logger->debug('Unsaved steps but collission with file, continue collaborative editing');
return $document;
}
// TODO: Only do this when no sessions active, otherise we need to resolve the conflict differently
// TODO: Add parameter so that we can force this, else just opening the document will cause a rebuild
$lastMTime = $document->getLastSavedVersionTime();
if ($file->getMTime() > $lastMTime && $lastMTime > 0) {
$this->resetDocument($document->getId());
throw new NotFoundException();
}
return $document;
} catch (DoesNotExistException $e) {
} catch (InvalidPathException $e) {
} catch (NotFoundException $e) {
}
try {
$documentBaseFile = $this->appData->getFolder('documents')->getFile($file->getFileInfo()->getId());
} catch (NotFoundException $e) {
$documentBaseFile = $this->appData->getFolder('documents')->newFile($file->getFileInfo()->getId());
}
$documentBaseFile->putContent($file->fopen('r'));
$document = new Document();
$document->setId($file->getFileInfo()->getId());
$document->setCurrentVersion(0);
$document->setLastSavedVersion(0);
$document->setLastSavedVersionTime($file->getFileInfo()->getMtime());
$document->setLastSavedVersionEtag($file->getEtag());
$document->setBaseVersionEtag($file->getEtag());
$document = $this->documentMapper->insert($document);
$this->cache->set('document-version-'.$document->getId(), 0);
return $document;
}
/**
* @param $document
* @return ISimpleFile
* @throws NotFoundException
*/
public function getBaseFile($document): ISimpleFile {
return $this->appData->getFolder('documents')->getFile($document);
}
/**
* @param $documentId
* @param $sessionId
* @param $steps
* @param $version
* @return array
* @throws DoesNotExistException
* @throws VersionMismatchException
*/
public function addStep($documentId, $sessionId, $steps, $version): array {
// TODO check cache
$document = $this->documentMapper->find($documentId);
if ($version !== $document->getCurrentVersion()) {
throw new VersionMismatchException('Version does not match');
}
$stepsJson = json_encode($steps);
if (!is_array($steps) || $stepsJson === null) {
throw new InvalidArgumentException('Failed to encode steps');
}
$validStepTypes = ['addMark', 'removeMark', 'replace', 'replaceAround'];
foreach ($steps as $step) {
if (array_key_exists('stepType', $step) && !in_array($step['stepType'], $validStepTypes, true)) {
throw new InvalidArgumentException('Invalid step data');
}
}
$newVersion = $document->getCurrentVersion() + count($steps);
$document->setCurrentVersion($newVersion);
$this->documentMapper->update($document);
$step = new Step();
$step->setData($stepsJson);
$step->setSessionId($sessionId);
$step->setDocumentId($documentId);
$step->setVersion($version+1);
$this->stepMapper->insert($step);
$this->cache->set('document-version-'.$document->getId(), $newVersion);
// TODO restore old version for document if adding steps has failed
// TODO write steps to cache for quicker reading
return $steps;
}
public function getSteps($documentId, $lastVersion) {
return $this->stepMapper->find($documentId, $lastVersion);
}
/**
* @param $documentId
* @param $version
* @param $autoaveDocument
* @param bool $force
* @param bool $manualSave
* @param null $token
* @return Document
* @throws DocumentSaveConflictException
* @throws DoesNotExistException
* @throws GenericFileException
* @throws InvalidPathException
* @throws NotFoundException
* @throws NotPermittedException
* @throws ShareNotFound
*/
public function autosave($documentId, $version, $autoaveDocument, $force = false, $manualSave = false, $token = null): Document {
/** @var Document $document */
$document = $this->documentMapper->find($documentId);
/** @var File $file */
if (!$token) {
$file = $this->rootFolder->getUserFolder($this->userId)->getById($documentId)[0];
} else {
$share = $this->shareManager->getShareByToken($token);
$file = $share->getNode();
}
$lastMTime = $document->getLastSavedVersionTime();
if ($autoaveDocument === null) {
return $document;
}
// Do not save if version already saved
if (!$force && $version <= (string)$document->getLastSavedVersion()) {
return $document;
}
// Only save once every AUTOSAVE_MINIMUM_DELAY seconds
if ($file->getMTime() === $lastMTime && $lastMTime > time() - self::AUTOSAVE_MINIMUM_DELAY && $manualSave === false) {
return $document;
}
if ($lastMTime > 0 && $file->getEtag() !== $document->getLastSavedVersionEtag() && $force === false) {
throw new DocumentSaveConflictException('File changed in the meantime from outside');
}
$file->putContent($autoaveDocument);
$document->setLastSavedVersion($version);
$document->setLastSavedVersionTime(time());
$document->setLastSavedVersionEtag($file->getEtag());
$this->documentMapper->update($document);
return $document;
}
public function resetDocument($documentId): void {
$this->stepMapper->deleteAll($documentId);
try {
$document = $this->documentMapper->find($documentId);
$this->documentMapper->delete($document);
} catch (DoesNotExistException $e) {
}
try {
$this->appData->getFolder('documents')->getFile($documentId)->delete();
} catch (NotFoundException $e) {
} catch (NotPermittedException $e) {
}
}
public function getFileById($fileId): Node {
return $this->rootFolder->getUserFolder($this->userId)->getById($fileId)[0];
}
/**
* @param $shareToken
* @param null|string $path
* @return \OCP\Files\File|Folder|Node
* @throws NotFoundException
*/
public function getFileByShareToken($shareToken, $path = null) {
try {
$share = $this->shareManager->getShareByToken($shareToken);
} catch (ShareNotFound $e) {
throw new NotFoundException();
}
$node = $share->getNode();
if ($node instanceof \OCP\Files\File) {
return $node;
}
if ($node instanceof Folder) {
return $node->get($path);
}
throw new \InvalidArgumentException('No proper share data');
}
/**
* @param $shareToken
* @return void
* @throws NotFoundException
*/
public function checkSharePermissions($shareToken, $permission = Constants::PERMISSION_READ): void {
try {
$share = $this->shareManager->getShareByToken($shareToken);
} catch (ShareNotFound $e) {
throw new NotFoundException();
}
if (($share->getPermissions() & $permission) === 0) {
throw new NotFoundException();
}
}
public function hasUnsavedChanges(Document $document) {
return $document->getCurrentVersion() !== $document->getLastSavedVersion();
}
}
|