Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Operation.php « Flow « lib - github.com/nextcloud/spreed.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: dd152218adf8d870f3c531fa59be8122b0e01517 (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
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
<?php

declare(strict_types=1);
/**
 * @copyright Copyright (c) 2019 Arthur Schiwon <blizzz@arthur-schiwon.de>
 *
 * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
 *
 * @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\Talk\Flow;

use OCA\Talk\Chat\ChatManager;
use OCA\Talk\Exceptions\ParticipantNotFoundException;
use OCA\Talk\Exceptions\RoomNotFoundException;
use OCA\Talk\Manager as TalkManager;
use OCA\Talk\Participant;
use OCA\Talk\Room;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserSession;
use OCP\Util;
use OCP\WorkflowEngine\EntityContext\IDisplayText;
use OCP\WorkflowEngine\EntityContext\IUrl;
use OCP\WorkflowEngine\IEntity;
use OCP\WorkflowEngine\IManager as FlowManager;
use OCP\WorkflowEngine\IOperation;
use OCP\WorkflowEngine\IRuleMatcher;
use Symfony\Component\EventDispatcher\GenericEvent;
use UnexpectedValueException;

class Operation implements IOperation {

	/** @var int[] */
	public const MESSAGE_MODES = [
		'NO_MENTION' => 1,
		'SELF_MENTION' => 2,
		'ROOM_MENTION' => 3,
	];

	/** @var IL10N */
	private $l;
	/** @var IURLGenerator */
	private $urlGenerator;
	/** @var TalkManager */
	private $talkManager;
	/** @var IUserSession */
	private $session;
	/** @var ChatManager */
	private $chatManager;

	public function __construct(
		IL10N $l,
		IURLGenerator $urlGenerator,
		TalkManager $talkManager,
		IUserSession $session,
		ChatManager $chatManager
	) {
		$this->l = $l;
		$this->urlGenerator = $urlGenerator;
		$this->talkManager = $talkManager;
		$this->session = $session;
		$this->chatManager = $chatManager;
	}

	public static function register(IEventDispatcher $dispatcher): void {
		$dispatcher->addListener(FlowManager::EVENT_NAME_REG_OPERATION, function (GenericEvent $event) {
			$operation = \OC::$server->query(Operation::class);
			$event->getSubject()->registerOperation($operation);
			Util::addScript('spreed', 'flow');
		});
	}

	public function getDisplayName(): string {
		return $this->l->t('Write to conversation');
	}

	public function getDescription(): string {
		return $this->l->t('Writes event information into a conversation of your choice');
	}

	public function getIcon(): string {
		return $this->urlGenerator->imagePath('spreed', 'app.svg');
	}

	public function isAvailableForScope(int $scope): bool {
		return $scope === FlowManager::SCOPE_USER;
	}

	/**
	 * Validates whether a configured workflow rule is valid. If it is not,
	 * an `\UnexpectedValueException` is supposed to be thrown.
	 *
	 * @throws UnexpectedValueException
	 * @since 9.1
	 */
	public function validateOperation(string $name, array $checks, string $operation): void {
		list($mode, $token) = $this->parseOperationConfig($operation);
		$this->validateOperationConfig($mode, $token, $this->getUser()->getUID());
	}

	public function onEvent(string $eventName, Event $event, IRuleMatcher $ruleMatcher): void {
		$flows = $ruleMatcher->getFlows(false);
		foreach ($flows as $flow) {
			try {
				list($mode, $token) = $this->parseOperationConfig($flow['operation']);
				$uid = $flow['scope_actor_id'];
				$this->validateOperationConfig($mode, $token, $uid);

				$entity = $ruleMatcher->getEntity();

				$message = $this->prepareText($entity, $eventName);
				if ($message === '') {
					continue;
				}

				$room = $this->getRoom($token, $uid);
				$participant = $this->getParticipant($uid, $room);
				$this->chatManager->sendMessage(
					$room,
					$participant,
					'bots',
					$participant->getUser(),
					$this->prepareMention($mode, $participant) . $message,
					new \DateTime(),
					null,
					''
				);
			} catch (UnexpectedValueException $e) {
				continue;
			} catch (ParticipantNotFoundException $e) {
				continue;
			} catch (RoomNotFoundException $e) {
				continue;
			}
		}
	}

	protected function prepareText(IEntity $entity, string $eventName) {
		$message = $eventName;
		if ($entity instanceof IDisplayText) {
			$message = trim($entity->getDisplayText(3));
		}
		if ($entity instanceof IUrl && $message !== '') {
			$message .= ' ' . $entity->getUrl();
		}
		return $message;
	}

	/**
	 * returns a mention including a trailing whitespace, or an empty string
	 */
	protected function prepareMention(int $mode, Participant $participant): string {
		switch ($mode) {
			case self::MESSAGE_MODES['ROOM_MENTION']:
				return '@all ';
			case self::MESSAGE_MODES['SELF_MENTION']:
				$hasWhitespace = strpos($participant->getUser(), ' ') !== false;
				$enclosure = $hasWhitespace ? '"' : '';
				return '@' . $enclosure . $participant->getUser() . $enclosure . ' ';
			case self::MESSAGE_MODES['NO_MENTION']:
			default:
				return '';
		}
	}

	protected function parseOperationConfig(string $raw): array {
		/**
		 * We expect $operation be a json string, containing
		 * 	't' => string, the room token
		 *  'm' => int > 0, see self::MESSAGE_MODES
		 *
		 * setting up room mentions are only permitted to moderators
		 */

		$opConfig = \json_decode($raw, true);
		if (!is_array($opConfig) || empty($opConfig)) {
			throw new UnexpectedValueException('Cannot decode operation details');
		}

		$mode = (int)($opConfig['m'] ?? 0);
		$token = trim((string)($opConfig['t'] ?? ''));

		return [$mode, $token];
	}

	protected function validateOperationConfig(int $mode, string $token, string $uid): void {
		if (!in_array($mode, self::MESSAGE_MODES)) {
			throw new UnexpectedValueException('Invalid mode');
		}

		if (empty($token)) {
			throw new UnexpectedValueException('Invalid token');
		}

		try {
			$room = $this->getRoom($token, $uid);
		} catch (RoomNotFoundException $e) {
			throw new UnexpectedValueException('Room not found', $e->getCode(), $e);
		}

		if ($mode === self::MESSAGE_MODES['ROOM_MENTION']) {
			try {
				$participant = $this->getParticipant($uid, $room);
				if (!$participant->hasModeratorPermissions(false)) {
					throw new UnexpectedValueException('Not allowed to mention room');
				}
			} catch (ParticipantNotFoundException $e) {
				throw new UnexpectedValueException('Participant not found', $e->getCode(), $e);
			}
		}
	}

	/**
	 * @throws UnexpectedValueException
	 */
	protected function getUser(): IUser {
		$user = $this->session->getUser();
		if ($user === null) {
			throw new UnexpectedValueException('User not logged in');
		}
		return $user;
	}

	/**
	 * @throws RoomNotFoundException
	 */
	protected function getRoom(string $token, string $uid): Room {
		return $this->talkManager->getRoomForParticipantByToken($token, $uid);
	}

	/**
	 * @throws ParticipantNotFoundException
	 */
	protected function getParticipant(string $uid, Room $room): Participant {
		return $room->getParticipant($uid);
	}
}