aboutsummaryrefslogtreecommitdiffstats
path: root/apps/admin_audit/lib/Listener/FileEventListener.php
blob: 46a4962123b5979d18f3cd41b500f6a527aea58d (plain)
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
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OCA\AdminAudit\Listener;

use OCA\AdminAudit\Actions\Action;
use OCA\Files_Versions\Events\VersionRestoredEvent;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Files\InvalidPathException;
use OCP\Files\NotFoundException;
use OCP\Preview\BeforePreviewFetchedEvent;
use OCP\Server;
use Psr\Log\LoggerInterface;

/**
 * @template-implements IEventListener<BeforePreviewFetchedEvent|VersionRestoredEvent>
 */
class FileEventListener extends Action implements IEventListener {
	public function handle(Event $event): void {
		if ($event instanceof BeforePreviewFetchedEvent) {
			$this->beforePreviewFetched($event);
		} elseif ($event instanceof VersionRestoredEvent) {
			$this->versionRestored($event);
		}
	}

	/**
	 * Logs preview access to a file
	 */
	private function beforePreviewFetched(BeforePreviewFetchedEvent $event): void {
		try {
			$file = $event->getNode();
			$params = [
				'id' => $file->getId(),
				'width' => $event->getWidth(),
				'height' => $event->getHeight(),
				'crop' => $event->isCrop(),
				'mode' => $event->getMode(),
				'path' => $file->getPath(),
			];
			$this->log(
				'Preview accessed: (id: "%s", width: "%s", height: "%s" crop: "%s", mode: "%s", path: "%s")',
				$params,
				array_keys($params)
			);
		} catch (InvalidPathException|NotFoundException $e) {
			Server::get(LoggerInterface::class)->error(
				'Exception thrown in file preview: ' . $e->getMessage(), ['app' => 'admin_audit', 'exception' => $e]
			);
			return;
		}
	}

	/**
	 * Logs when a version is restored
	 */
	private function versionRestored(VersionRestoredEvent $event): void {
		$version = $event->getVersion();
		$this->log('Version "%s" of "%s" was restored.',
			[
				'version' => $version->getRevisionId(),
				'path' => $version->getVersionPath()
			],
			['version', 'path']
		);
	}
}