Completed
Pull Request — master (#362)
by Maxence
01:52
created

GSUpstreamService::newEvent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php declare(strict_types=1);
2
3
4
/**
5
 * Circles - Bring cloud-users closer together.
6
 *
7
 * This file is licensed under the Affero General Public License version 3 or
8
 * later. See the COPYING file.
9
 *
10
 * @author Maxence Lange <[email protected]>
11
 * @copyright 2017
12
 * @license GNU AGPL version 3 or any later version
13
 *
14
 * This program is free software: you can redistribute it and/or modify
15
 * it under the terms of the GNU Affero General Public License as
16
 * published by the Free Software Foundation, either version 3 of the
17
 * License, or (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU Affero General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU Affero General Public License
25
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26
 *
27
 */
28
29
30
namespace OCA\Circles\Service;
31
32
33
use daita\MySmallPhpTools\Exceptions\RequestContentException;
34
use daita\MySmallPhpTools\Exceptions\RequestNetworkException;
35
use daita\MySmallPhpTools\Exceptions\RequestResultSizeException;
36
use daita\MySmallPhpTools\Exceptions\RequestServerException;
37
use daita\MySmallPhpTools\Model\Request;
38
use daita\MySmallPhpTools\Traits\TRequest;
39
use OCA\Circles\Db\CirclesRequest;
40
use OCA\Circles\Db\GSEventsRequest;
41
use OCA\Circles\Exceptions\CircleDoesNotExistException;
42
use OCA\Circles\Exceptions\ConfigNoCircleAvailableException;
43
use OCA\Circles\Exceptions\GSKeyException;
44
use OCA\Circles\Exceptions\JsonException;
45
use OCA\Circles\Exceptions\ModelException;
46
use OCA\Circles\Exceptions\TokenDoesNotExistException;
47
use OCA\Circles\Model\GlobalScale\GSEvent;
48
use OCA\Circles\Model\GlobalScale\GSWrapper;
49
use OCP\IURLGenerator;
50
51
52
/**
53
 * Class GSUpstreamService
54
 *
55
 * @package OCA\Circles\Service
56
 */
57
class GSUpstreamService {
58
59
60
	use TRequest;
61
62
63
	/** @var string */
64
	private $userId = '';
65
66
	/** @var IURLGenerator */
67
	private $urlGenerator;
68
69
	/** @var GSEventsRequest */
70
	private $gsEventsRequest;
71
72
	/** @var CirclesRequest */
73
	private $circlesRequest;
74
75
	/** @var ConfigService */
76
	private $configService;
77
78
	/** @var MiscService */
79
	private $miscService;
80
81
82
	/**
83
	 * GSUpstreamService constructor.
84
	 *
85
	 * @param $userId
86
	 * @param IURLGenerator $urlGenerator
87
	 * @param GSEventsRequest $gsEventsRequest
88
	 * @param CirclesRequest $circlesRequest
89
	 * @param ConfigService $configService
90
	 * @param MiscService $miscService
91
	 */
92
	public function __construct(
93
		$userId,
94
		IURLGenerator $urlGenerator,
95
		GSEventsRequest $gsEventsRequest,
96
		CirclesRequest $circlesRequest,
97
		ConfigService $configService,
98
		MiscService $miscService
99
	) {
100
		$this->userId = $userId;
101
		$this->urlGenerator = $urlGenerator;
102
		$this->gsEventsRequest = $gsEventsRequest;
103
		$this->circlesRequest = $circlesRequest;
104
		$this->configService = $configService;
105
		$this->miscService = $miscService;
106
	}
107
108
109
	/**
110
	 * @param GSEvent $event
111
	 *
112
	 * @throws CircleDoesNotExistException
113
	 * @throws ConfigNoCircleAvailableException
114
	 */
115
	public function newEvent(GSEvent $event) {
116
		$this->fillEvent($event);
117
		if ($this->isLocalEvent($event)) {
118
			// TODO: manage the event locally - needed ?
119
			// TODO: confirm that action is ok for the front-end
120
			$this->asyncBroadcast($event);
121
		} else {
122
			$this->confirmEvent($event);
123
			// TODO: send the event to the right instance. based on the result, do something on the front-end
124
//			$path = $this->urlGenerator->linkToRouteAbsolute('circles.GlobalScale.event');
125
//			$request = new Request($path, Request::TYPE_POST);
126
		}
127
128
	}
129
130
131
	/**
132
	 * @param GSEvent $event
133
	 */
134
	public function asyncBroadcast(GSEvent $event): void {
135
		$wrapper = $this->gsEventsRequest->create($event, $this->getInstances());
136
		$path = $this->urlGenerator->linkToRoute(
137
			'circles.GlobalScale.asyncBroadcast', ['token' => $wrapper->getToken()]
138
		);
139
140
		$request = new Request($path, Request::TYPE_PUT);
141
		$request->setAddressFromUrl($this->urlGenerator->getBaseUrl());
142
		$request->setDataSerialize($event);
143
144
		try {
145
			$this->doRequest($request);
146
		} catch (RequestContentException | RequestNetworkException | RequestResultSizeException | RequestServerException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
147
		}
148
	}
149
150
151
	/**
152
	 * @param GSEvent $event
153
	 */
154
	public function broadcastEvent(GSEvent $event): void {
155
		$this->signEvent($event);
156
157
		$path = $this->urlGenerator->linkToRoute('circles.GlobalScale.broadcast');
158
		$request = new Request($path, Request::TYPE_POST);
159
		$request->setDataSerialize($event);
160
161
		foreach ($this->getInstances() as $instance) {
162
			$request->setAddressFromUrl($instance);
163
164
			try {
165
				$this->doRequest($request);
166
			} catch (RequestContentException | RequestNetworkException | RequestResultSizeException | RequestServerException $e) {
167
				// TODO: queue request
168
			}
169
		}
170
171
	}
172
173
174
	/**
175
	 * @param GSEvent $event
176
	 *
177
	 * @throws RequestContentException
178
	 * @throws RequestNetworkException
179
	 * @throws RequestResultSizeException
180
	 * @throws RequestServerException
181
	 */
182
	public function confirmEvent(GSEvent $event): void {
183
		$this->miscService->log('____ ' . json_encode($event));
184
185
		$circle = $event->getCircle();
186
		$owner = $circle->getOwner();
187
		$owner->getInstance();
0 ignored issues
show
Unused Code introduced by
The call to the method OCA\Circles\Model\Member::getInstance() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
188
189
		$this->miscService->log('NOW REQUEST ' . $owner->getInstance());
190
191
//		$wrapper = $this->gsEventsRequest->create($event, $this->getInstances());
192
		$path = $this->urlGenerator->linkToRoute('circles.GlobalScale.event');
193
194
		$request = new Request($path, Request::TYPE_POST);
195
		$request->setAddressFromUrl($owner->getInstance());
196
		$request->setDataSerialize($event);
197
198
		$this->doRequest($request);
199
	}
200
201
202
	/**
203
	 * @param GSEvent $event
204
	 *
205
	 * @throws CircleDoesNotExistException
206
	 * @throws ConfigNoCircleAvailableException
207
	 */
208
	private function fillEvent(GSEvent $event): void {
209
		$event->setSource('http://nc18.local');
210
//		if (!$event->hasCircle()) {
211
//			$event->setCircle($this->circlesRequest->getCircle($event->getCircleId(), $this->userId, true));
212
//		}
213
	}
214
215
216
	/**
217
	 * @param bool $all
218
	 *
219
	 * @return array
220
	 */
221
	public function getInstances(bool $all = false): array {
222
		$instances = [
223
//			'test.artificial-owl.com',
224
//			'nc18.artificial-owl.com'
225
'http://nc18.local',
226
'http://nc18-001.local',
227
'http://nc18-002.local',
228
'http://nc18-003.local'
229
		];
230
231
		if ($all) {
232
			return $instances;
233
		}
234
235
//		$local = $this->configService->getAvailableHosts();
236
//		$local = ['test.artificial-owl.com'];
237
		$local = ['http://nc18.local'];
238
239
		return array_diff($instances, $local);
240
	}
241
242
243
	/**
244
	 * @return string
245
	 */
246
	public function getKey(): string {
247
		return 'abcd';
248
	}
249
250
251
	/**
252
	 * @param string $key
253
	 *
254
	 * @throws GSKeyException
255
	 */
256
	public function checkKey(string $key) {
257
		if ($key !== $this->getKey()) {
258
			throw new GSKeyException('invalid key');
259
		}
260
	}
261
262
263
	/**
264
	 * @param GSEvent $event
265
	 */
266
	private function signEvent(GSevent $event) {
267
		$event->setKey($this->getKey());
268
	}
269
270
271
	/**
272
	 * @param GSEvent $event
273
	 *
274
	 * @return bool
275
	 */
276
	private function isLocalEvent(GSEvent $event): bool {
277
		if ($event->isLocal()) {
278
			return true;
279
		}
280
281
		$circle = $event->getCircle();
282
		$owner = $circle->getOwner();
283
		$this->miscService->log('### ' . json_encode($owner));
284
		if ($owner->getInstance() !== '') {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !($owner->getInstance() !== '');.
Loading history...
285
			return false;
286
		}
287
288
		return true;
289
	}
290
291
292
	/**
293
	 * @param string $token
294
	 *
295
	 * @return GSWrapper
296
	 * @throws JsonException
297
	 * @throws ModelException
298
	 * @throws TokenDoesNotExistException
299
	 */
300
	public function getEventByToken(string $token): GSWrapper {
301
		return $this->gsEventsRequest->getByToken($token);
302
	}
303
304
}
305
306