-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
FileEventsListener.php
371 lines (333 loc) · 11.4 KB
/
FileEventsListener.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
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
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bart Visscher <bartv@thisnet.nl>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Robin McCorkell <robin@mccorkell.me.uk>
* @author Sam Tuke <mail@samtuke.com>
* @author Louis Chmn <louis@chmn.me>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Versions\Listener;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use OC\DB\Exceptions\DbalException;
use OC\Files\Filesystem;
use OC\Files\Mount\MoveableMount;
use OC\Files\Node\NonExistingFile;
use OC\Files\View;
use OCA\Files_Versions\Storage;
use OCA\Files_Versions\Versions\INeedSyncVersionBackend;
use OCA\Files_Versions\Versions\IVersionManager;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\DB\Exception;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Files\Events\Node\BeforeNodeCopiedEvent;
use OCP\Files\Events\Node\BeforeNodeDeletedEvent;
use OCP\Files\Events\Node\BeforeNodeRenamedEvent;
use OCP\Files\Events\Node\BeforeNodeTouchedEvent;
use OCP\Files\Events\Node\BeforeNodeWrittenEvent;
use OCP\Files\Events\Node\NodeCopiedEvent;
use OCP\Files\Events\Node\NodeCreatedEvent;
use OCP\Files\Events\Node\NodeDeletedEvent;
use OCP\Files\Events\Node\NodeRenamedEvent;
use OCP\Files\Events\Node\NodeTouchedEvent;
use OCP\Files\Events\Node\NodeWrittenEvent;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\IMimeTypeLoader;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use Psr\Log\LoggerInterface;
class FileEventsListener implements IEventListener {
private IRootFolder $rootFolder;
private IVersionManager $versionManager;
/**
* @var array<int, array>
*/
private array $writeHookInfo = [];
/**
* @var array<int, Node>
*/
private array $nodesTouched = [];
/**
* @var array<string, Node>
*/
private array $versionsDeleted = [];
private IMimeTypeLoader $mimeTypeLoader;
private LoggerInterface $logger;
public function __construct(
IRootFolder $rootFolder,
IVersionManager $versionManager,
IMimeTypeLoader $mimeTypeLoader,
LoggerInterface $logger,
) {
$this->rootFolder = $rootFolder;
$this->versionManager = $versionManager;
$this->mimeTypeLoader = $mimeTypeLoader;
$this->logger = $logger;
}
public function handle(Event $event): void {
if ($event instanceof NodeCreatedEvent) {
$this->created($event->getNode());
}
if ($event instanceof BeforeNodeTouchedEvent) {
$this->pre_touch_hook($event->getNode());
}
if ($event instanceof NodeTouchedEvent) {
$this->touch_hook($event->getNode());
}
if ($event instanceof BeforeNodeWrittenEvent) {
$this->write_hook($event->getNode());
}
if ($event instanceof NodeWrittenEvent) {
$this->post_write_hook($event->getNode());
}
if ($event instanceof BeforeNodeDeletedEvent) {
$this->pre_remove_hook($event->getNode());
}
if ($event instanceof NodeDeletedEvent) {
$this->remove_hook($event->getNode());
}
if ($event instanceof NodeRenamedEvent) {
$this->rename_hook($event->getSource(), $event->getTarget());
}
if ($event instanceof NodeCopiedEvent) {
$this->copy_hook($event->getSource(), $event->getTarget());
}
if ($event instanceof BeforeNodeRenamedEvent) {
$this->pre_renameOrCopy_hook($event->getSource(), $event->getTarget());
}
if ($event instanceof BeforeNodeCopiedEvent) {
$this->pre_renameOrCopy_hook($event->getSource(), $event->getTarget());
}
}
public function pre_touch_hook(Node $node): void {
// Do not handle folders.
if ($node instanceof Folder) {
return;
}
// $node is a non-existing on file creation.
if ($node instanceof NonExistingFile) {
return;
}
$this->nodesTouched[$node->getId()] = $node;
}
public function touch_hook(Node $node): void {
$previousNode = $this->nodesTouched[$node->getId()] ?? null;
if ($previousNode === null) {
return;
}
unset($this->nodesTouched[$node->getId()]);
try {
if ($node instanceof File && $this->versionManager instanceof INeedSyncVersionBackend) {
// We update the timestamp of the version entity associated with the previousNode.
$this->versionManager->updateVersionEntity($node, $previousNode->getMTime(), ['timestamp' => $node->getMTime()]);
}
} catch (DbalException $ex) {
// Ignore UniqueConstraintViolationException, as we are probably in the middle of a rollback
// Where the previous node would temporary have the mtime of the old version, so the rollback touches it to fix it.
if (!($ex->getPrevious() instanceof UniqueConstraintViolationException)) {
throw $ex;
}
} catch (DoesNotExistException $ex) {
// Ignore DoesNotExistException, as we are probably in the middle of a rollback
// Where the previous node would temporary have a wrong mtime, so the rollback touches it to fix it.
}
}
public function created(Node $node): void {
// Do not handle folders.
if ($node instanceof File && $this->versionManager instanceof INeedSyncVersionBackend) {
$this->versionManager->createVersionEntity($node);
}
}
/**
* listen to write event.
*/
public function write_hook(Node $node): void {
// Do not handle folders.
if ($node instanceof Folder) {
return;
}
// $node is a non-existing on file creation.
if ($node instanceof NonExistingFile) {
return;
}
$path = $this->getPathForNode($node);
$result = Storage::store($path);
// Store the result of the version creation so it can be used in post_write_hook.
$this->writeHookInfo[$node->getId()] = [
'previousNode' => $node,
'versionCreated' => $result !== false
];
}
/**
* listen to post_write event.
*/
public function post_write_hook(Node $node): void {
// Do not handle folders.
if ($node instanceof Folder) {
return;
}
$writeHookInfo = $this->writeHookInfo[$node->getId()] ?? null;
if ($writeHookInfo === null) {
return;
}
if (
($writeHookInfo['versionCreated'] || $writeHookInfo['previousNode']->getSize() === 0) &&
$node->getMTime() !== $writeHookInfo['previousNode']->getMTime()
) {
// If a new version was created, insert a version in the DB for the current content.
// Unless both versions have the same mtime.
$this->created($node);
} else {
try {
// If no new version was stored in the FS, no new version should be added in the DB.
// So we simply update the associated version.
if ($node instanceof File && $this->versionManager instanceof INeedSyncVersionBackend) {
$this->versionManager->updateVersionEntity(
$node,
$writeHookInfo['previousNode']->getMtime(),
[
'timestamp' => $node->getMTime(),
'size' => $node->getSize(),
'mimetype' => $this->mimeTypeLoader->getId($node->getMimetype()),
],
);
}
} catch (Exception $e) {
$this->logger->error('Failed to update existing version for ' . $node->getPath(), [
'exception' => $e,
'versionCreated' => $writeHookInfo['versionCreated'],
'previousNode' => [
'size' => $writeHookInfo['previousNode']->getSize(),
'mtime' => $writeHookInfo['previousNode']->getMTime(),
],
'node' => [
'size' => $node->getSize(),
'mtime' => $node->getMTime(),
]
]);
throw $e;
}
}
unset($this->writeHookInfo[$node->getId()]);
}
/**
* Erase versions of deleted file
*
* This function is connected to the delete signal of OC_Filesystem
* cleanup the versions directory if the actual file gets deleted
*/
public function remove_hook(Node $node): void {
// Need to normalize the path as there is an issue with path concatenation in View.php::getAbsolutePath.
$path = Filesystem::normalizePath($node->getPath());
if (!array_key_exists($path, $this->versionsDeleted)) {
return;
}
$node = $this->versionsDeleted[$path];
$relativePath = $this->getPathForNode($node);
unset($this->versionsDeleted[$path]);
Storage::delete($relativePath);
// If no new version was stored in the FS, no new version should be added in the DB.
// So we simply update the associated version.
if ($node instanceof File && $this->versionManager instanceof INeedSyncVersionBackend) {
$this->versionManager->deleteVersionsEntity($node);
}
}
/**
* mark file as "deleted" so that we can clean up the versions if the file is gone
*/
public function pre_remove_hook(Node $node): void {
$path = $this->getPathForNode($node);
Storage::markDeletedFile($path);
$this->versionsDeleted[$node->getPath()] = $node;
}
/**
* rename/move versions of renamed/moved files
*
* This function is connected to the rename signal of OC_Filesystem and adjust the name and location
* of the stored versions along the actual file
*/
public function rename_hook(Node $source, Node $target): void {
$oldPath = $this->getPathForNode($source);
$newPath = $this->getPathForNode($target);
Storage::renameOrCopy($oldPath, $newPath, 'rename');
}
/**
* copy versions of copied files
*
* This function is connected to the copy signal of OC_Filesystem and copies the
* the stored versions to the new location
*/
public function copy_hook(Node $source, Node $target): void {
$oldPath = $this->getPathForNode($source);
$newPath = $this->getPathForNode($target);
Storage::renameOrCopy($oldPath, $newPath, 'copy');
}
/**
* Remember owner and the owner path of the source file.
* If the file already exists, then it was a upload of a existing file
* over the web interface and we call Storage::store() directly
*
*
*/
public function pre_renameOrCopy_hook(Node $source, Node $target): void {
// if we rename a movable mount point, then the versions don't have
// to be renamed
$oldPath = $this->getPathForNode($source);
$newPath = $this->getPathForNode($target);
$absOldPath = Filesystem::normalizePath('/' . \OC_User::getUser() . '/files' . $oldPath);
$manager = Filesystem::getMountManager();
$mount = $manager->find($absOldPath);
$internalPath = $mount->getInternalPath($absOldPath);
if ($internalPath === '' and $mount instanceof MoveableMount) {
return;
}
$view = new View(\OC_User::getUser() . '/files');
if ($view->file_exists($newPath)) {
Storage::store($newPath);
} else {
Storage::setSourcePathAndUser($oldPath);
}
}
/**
* Retrieve the path relative to the current user root folder.
* If no user is connected, try to use the node's owner.
*/
private function getPathForNode(Node $node): ?string {
try {
return $this->rootFolder
->getUserFolder(\OC_User::getUser())
->getRelativePath($node->getPath());
} catch (\Throwable $ex) {
$owner = $node->getOwner();
if ($owner === null) {
return null;
}
return $this->rootFolder
->getUserFolder($owner->getUid())
->getRelativePath($node->getPath());
}
}
}