-
Notifications
You must be signed in to change notification settings - Fork 19
/
OpenProjectAPIService.php
882 lines (826 loc) · 26.4 KB
/
OpenProjectAPIService.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
<?php
/**
* Nextcloud - openproject
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Julien Veyssier
* @copyright Julien Veyssier 2020
*/
namespace OCA\OpenProject\Service;
use DateTime;
use DateTimeZone;
use Exception;
use OCA\Notifications\Handler;
use OCP\Files\Node;
use OCA\OpenProject\Exception\OpenprojectErrorException;
use OCA\OpenProject\Exception\OpenprojectResponseException;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Http\Client\IResponse;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\PreConditionNotMetException;
use Psr\Log\LoggerInterface;
use OCP\IConfig;
use OCP\IUserManager;
use OCP\IUser;
use OCP\IAvatarManager;
use OCP\Http\Client\IClientService;
use OCP\Notification\IManager as INotificationManager;
use OCP\Files\NotPermittedException;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\ConnectException;
use OCP\AppFramework\Http;
use OCA\OpenProject\AppInfo\Application;
use Safe\Exceptions\JsonException;
define('CACHE_TTL', 3600);
class OpenProjectAPIService {
/**
* @var string
*/
private $appName;
/**
* @var IUserManager
*/
private $userManager;
/**
* @var IAvatarManager
*/
private $avatarManager;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var IL10N
*/
private $l10n;
/**
* @var IConfig
*/
private $config;
/**
* @var INotificationManager
*/
private $notificationManager;
/**
* @var \OCP\Http\Client\IClient
*/
private $client;
/** @var IRootFolder */
private $storage;
/**
* @var IURLGenerator
*/
private $urlGenerator;
/**
* @var ICache
*/
private $cache = null;
/**
* @var Handler
*/
private $handler;
/**
* Service to make requests to OpenProject v3 (JSON) API
*/
public function __construct(
string $appName,
IUserManager $userManager,
IAvatarManager $avatarManager,
LoggerInterface $logger,
IL10N $l10n,
IConfig $config,
INotificationManager $notificationManager,
IClientService $clientService,
IRootFolder $storage,
IURLGenerator $urlGenerator,
ICacheFactory $cacheFactory,
Handler $handler = null) {
$this->appName = $appName;
$this->userManager = $userManager;
$this->avatarManager = $avatarManager;
$this->logger = $logger;
$this->l10n = $l10n;
$this->config = $config;
$this->notificationManager = $notificationManager;
$this->client = $clientService->newClient();
$this->storage = $storage;
$this->urlGenerator = $urlGenerator;
$this->handler = $handler;
$this->cache = $cacheFactory->createDistributed();
}
/**
* triggered by a cron job
* notifies user of their number of new tickets
*
* @return void
*/
public function checkNotifications(): void {
$this->userManager->callForAllUsers(function (IUser $user) {
$this->checkNotificationsForUser($user->getUID());
});
}
/**
* @param string $userId
* @return void
*/
private function checkNotificationsForUser(string $userId): void {
if ($this->handler === null) {
// notifications app seems not to exist
return;
}
$accessToken = $this->config->getUserValue($userId, Application::APP_ID, 'token');
$notificationEnabled = ($this->config->getUserValue(
$userId,
Application::APP_ID,
'notification_enabled',
$this->config->getAppValue(Application::APP_ID, 'default_enable_notifications', '0')) === '1');
if ($accessToken && $notificationEnabled) {
$notifications = $this->getNotifications($userId);
$aggregatedNotifications = [];
if (!isset($notifications['error'])) {
foreach ($notifications as $n) {
$wpId = preg_replace('/.*\//', '', $n['_links']['resource']['href']);
if (!array_key_exists($wpId, $aggregatedNotifications)) {
$aggregatedNotifications[$wpId] = [
'wpId' => $wpId,
'resourceTitle' => $n['_links']['resource']['title'],
'projectTitle' => $n['_links']['project']['title'],
'count' => 1,
'updatedAt' => $n['updatedAt']
];
} else {
$storedUpdatedAt = \Safe\strtotime($aggregatedNotifications[$wpId]['updatedAt']);
if (\Safe\strtotime($n['updatedAt']) > $storedUpdatedAt) {
// currently the code never comes here because the notifications are ordered
// by 'updatedAt' but as backup I would keep it
$aggregatedNotifications[$wpId]['updatedAt'] = $n['updatedAt'];
}
$aggregatedNotifications[$wpId]['count']++;
}
$aggregatedNotifications[$wpId]['reasons'][] = $n['reason'];
$aggregatedNotifications[$wpId]['actors'][] = $n['_links']['actor']['title'];
}
$manager = $this->notificationManager;
$notificationsFilter = $manager->createNotification();
$notificationsFilter->setApp(Application::APP_ID)
->setUser($userId);
$this->config->setUserValue(
$userId,
Application::APP_ID,
'refresh-notifications-in-progress',
'true'
);
$currentNotifications = $this->handler->get($notificationsFilter);
foreach ($currentNotifications as $notificationId => $currentNotification) {
$parametersCurrentNotifications = $currentNotification->getSubjectParameters();
$wpId = $parametersCurrentNotifications['wpId'];
if (isset($aggregatedNotifications[$wpId])) {
$currentNotificationUpdateTime = \Safe\strtotime($parametersCurrentNotifications['updatedAt']);
$newNotificationUpdateTime = \Safe\strtotime($aggregatedNotifications[$wpId]['updatedAt']);
if ($newNotificationUpdateTime <= $currentNotificationUpdateTime) {
// nothing changed with any notification associated with that WP
// so get rid of it
unset($aggregatedNotifications[$wpId]);
} else {
$manager->markProcessed($currentNotification);
}
} else { // there are no notifications in OP associated with that WP
$manager->markProcessed($currentNotification);
}
}
foreach ($aggregatedNotifications as $n) {
$n['reasons'] = array_unique($n['reasons']);
$n['actors'] = array_unique($n['actors']);
// TODO can we use https://github.com/nextcloud/notifications/blob/master/docs/notification-workflow.md#defer-and-flush ?
$this->sendNCNotification($userId, 'op_notification', $n);
}
$this->config->setUserValue(
$userId,
Application::APP_ID,
'refresh-notifications-in-progress',
'false'
);
}
}
}
/**
* @param array<mixed> $workPackage
* @return int|null
*/
private function getWPAssigneeOrAuthorId(array $workPackage): ?int {
return isset($workPackage['_links'], $workPackage['_links']['assignee'], $workPackage['_links']['assignee']['href'])
? (int) preg_replace('/.*\//', '', $workPackage['_links']['assignee']['href'])
: (isset($workPackage['_links'], $workPackage['_links']['author'], $workPackage['_links']['author']['href'])
? (int) preg_replace('/.*\//', '', $workPackage['_links']['author']['href'])
: null);
}
/**
* @param string $userId
* @param string $subject
* @param array<mixed> $params
* @return void
*/
private function sendNCNotification(string $userId, string $subject, array $params): void {
$manager = $this->notificationManager;
$notification = $manager->createNotification();
$notification->setApp(Application::APP_ID)
->setUser($userId)
->setDateTime(new DateTime())
->setObject('dum', 'dum');
$notification->setSubject($subject, $params);
$manager->notify($notification);
}
/**
* returns the current date and time with the correct format for OpenProject API
*
* @return string
*/
public function now(): string {
date_default_timezone_set('UTC');
$utcTimezone = new DateTimeZone('-0000');
$nowDt = new Datetime();
$nowDt->setTimezone($utcTimezone);
return $nowDt->format('Y-m-d\TH:i:s\Z');
}
/**
* @param string $userId
* @return array<mixed>
*/
public function getNotifications(string $userId): array {
$filters[] = [
'readIAN' =>
['operator' => '=', 'values' => ['f']]
];
$params = [
'filters' => \Safe\json_encode($filters),
];
$result = $this->request($userId, 'notifications', $params);
if (isset($result['error'])) {
return $result;
} elseif (
!isset($result['_embedded']['elements']) ||
( // if there is an element, it also has to contain '_links'
isset($result['_embedded']['elements'][0]) &&
!isset($result['_embedded']['elements'][0]['_links'])
)
) {
return ['error' => 'Malformed response'];
}
$result = $result['_embedded']['elements'];
return array_values($result);
}
/**
* wrapper around IURLGenerator::getBaseUrl() to make it easier to mock in tests
*/
public function getBaseUrl(): string {
return $this->urlGenerator->getBaseUrl();
}
/**
* @param string $userId
* @param string|null $query
* @param int|null $fileId
* @param int $offset
* @param int $limit
* @return array<mixed>
* @throws \OCP\PreConditionNotMetException
* @throws \Safe\Exceptions\JsonException
*/
public function searchWorkPackage(
string $userId,
string $query = null,
int $fileId = null,
int $offset = 0,
int $limit = 5
): array {
$resultsById = [];
$filters = [];
// search by description
if ($fileId !== null) {
$filters[] = ['file_link_origin_id' => ['operator' => '=', 'values' => [(string)$fileId]]];
}
if ($query !== null) {
$filters[] = ['typeahead' => ['operator' => '**', 'values' => [$query]]];
}
$resultsById = $this->searchRequest($userId, $filters);
if (isset($resultsById['error'])) {
return $resultsById;
}
return array_values($resultsById);
}
/**
* @param string $userId
* @param array<mixed> $filters
* @return array<mixed>
* @throws \OCP\PreConditionNotMetException
* @throws \Safe\Exceptions\JsonException
*/
private function searchRequest(string $userId, array $filters): array {
$resultsById = [];
$sortBy = [['updatedAt', 'desc']];
$filters[] = [
'linkable_to_storage_url' =>
['operator' => '=', 'values' => [urlencode($this->getBaseUrl())]]
];
$params = [
'filters' => \Safe\json_encode($filters),
'sortBy' => \Safe\json_encode($sortBy),
// 'limit' => $limit,
];
$searchResult = $this->request($userId, 'work_packages', $params);
if (isset($searchResult['error'])) {
return $searchResult;
}
if (isset($searchResult['_embedded'], $searchResult['_embedded']['elements'])) {
foreach ($searchResult['_embedded']['elements'] as $wp) {
$resultsById[$wp['id']] = $wp;
}
}
return $resultsById;
}
/**
* authenticated request to get an image from openproject
*
* @param string $userId
* @param string $userName
* @return array{avatar: string, type?: string}
* @throws \OCP\Files\NotFoundException
* @throws \OCP\Files\NotPermittedException
* @throws \OCP\Lock\LockedException
*/
public function getOpenProjectAvatar(string $userId, string $userName): array {
$accessToken = $this->config->getUserValue($userId, Application::APP_ID, 'token');
$this->config->getAppValue(Application::APP_ID, 'client_id');
$this->config->getAppValue(Application::APP_ID, 'client_secret');
$openprojectUrl = $this->config->getAppValue(Application::APP_ID, 'oauth_instance_url');
try {
$response = $this->rawRequest($accessToken, $openprojectUrl, 'users/'.$userId.'/avatar');
$headers = $response->getHeaders();
return [
'avatar' => $response->getBody(),
'type' => implode(',', $headers['Content-Type']),
];
} catch (ServerException | ClientException | ConnectException | Exception $e) {
$this->logger->debug('Error while getting OpenProject avatar for user ' . $userId . ': ' . $e->getMessage(), ['app' => $this->appName]);
$avatar = $this->avatarManager->getGuestAvatar($userName);
$avatarContent = $avatar->getFile(64)->getContent();
return ['avatar' => $avatarContent];
}
}
/**
* @param string $accessToken
* @param string $openprojectUrl
* @param string $endPoint
* @param array<mixed> $params
* @param string $method
* @param array<mixed> $options further options to be given to Guzzle see https://docs.guzzlephp.org/en/stable/request-options.html
* @return array{error: string} | IResponse
*/
public function rawRequest(string $accessToken, string $openprojectUrl,
string $endPoint, array $params = [],
string $method = 'GET',
array $options = []
) {
$url = $openprojectUrl . '/api/v3/' . $endPoint;
if (!isset($options['headers']['Authorization'])) {
$options['headers']['Authorization'] = 'Bearer ' . $accessToken;
}
if (!isset($options['headers']['User-Agent'])) {
$options['headers']['User-Agent'] = 'Nextcloud OpenProject integration';
}
if (count($params) > 0) {
if ($method === 'GET') {
// manage array parameters
$paramsContent = '';
foreach ($params as $key => $value) {
if (is_array($value)) {
foreach ($value as $oneArrayValue) {
$paramsContent .= $key . '[]=' . urlencode($oneArrayValue) . '&';
}
unset($params[$key]);
}
}
$paramsContent .= http_build_query($params);
$url .= '?' . $paramsContent;
} else {
if (isset($params['body'])) {
$options['body'] = $params['body'];
}
if (!isset($options['headers']['Content-Type'])) {
$options['headers']['Content-Type'] = 'application/json';
}
}
} elseif ($method === 'DELETE') {
if (!isset($options['headers']['Content-Type'])) {
$options['headers']['Content-Type'] = 'application/json';
}
}
if ($method === 'GET') {
$response = $this->client->get($url, $options);
} elseif ($method === 'POST') {
$response = $this->client->post($url, $options);
} elseif ($method === 'PUT') {
$response = $this->client->put($url, $options);
} elseif ($method === 'DELETE') {
$response = $this->client->delete($url, $options);
} else {
return ['error' => $this->l10n->t('Bad HTTP method')];
}
return $response;
}
/**
* @param string $userId
* @param string $endPoint
* @param array<mixed> $params
* @param string $method
* @return array<mixed>
* @throws \OCP\PreConditionNotMetException
*/
public function request(string $userId,
string $endPoint, array $params = [], string $method = 'GET'): array {
$accessToken = $this->config->getUserValue($userId, Application::APP_ID, 'token');
$refreshToken = $this->config->getUserValue($userId, Application::APP_ID, 'refresh_token');
$clientID = $this->config->getAppValue(Application::APP_ID, 'client_id');
$clientSecret = $this->config->getAppValue(Application::APP_ID, 'client_secret');
$openprojectUrl = $this->config->getAppValue(Application::APP_ID, 'oauth_instance_url');
if (!$openprojectUrl || !OpenProjectAPIService::validateURL($openprojectUrl)) {
return ['error' => 'OpenProject URL is invalid', 'statusCode' => 500];
}
try {
$response = $this->rawRequest($accessToken, $openprojectUrl, $endPoint, $params, $method);
if (($method === 'DELETE' || $method === 'POST') &&
$response->getStatusCode() === Http::STATUS_NO_CONTENT
) {
return ['success' => true];
}
return json_decode($response->getBody(), true);
} catch (ServerException | ClientException $e) {
$response = $e->getResponse();
$body = (string) $response->getBody();
// refresh token if it's invalid and we are using oauth
// response can be : 'OAuth2 token is expired!', 'Invalid token!' or 'Not authorized'
if ($response->getStatusCode() === 401) {
$this->logger->info('Trying to REFRESH the access token', ['app' => $this->appName]);
// try to refresh the token
$result = $this->requestOAuthAccessToken($openprojectUrl, [
'client_id' => $clientID,
'client_secret' => $clientSecret,
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
], 'POST');
if (isset($result['refresh_token'])) {
$refreshToken = $result['refresh_token'];
$this->config->setUserValue(
$userId, Application::APP_ID, 'refresh_token', $refreshToken
);
}
if (isset($result['access_token'])) {
$accessToken = $result['access_token'];
$this->config->setUserValue($userId, Application::APP_ID, 'token', $accessToken);
// retry the request with new access token
return $this->request($userId, $endPoint, $params, $method);
}
}
// try to get the error in the response
$this->logger->warning('OpenProject API error : '.$e->getMessage(), ['app' => $this->appName]);
$decodedBody = json_decode($body, true);
if ($decodedBody && isset($decodedBody['message'])) {
if (gettype($decodedBody['message']) === 'array') {
// the OpenProject API sometimes responds with an array as message
// e.g. when sending a not-existing workpackage as resourceId filter
// to /api/v3/notifications/read_ian
// see POST /api/v3/notifications/read_ian in https://community.openproject.org/api/docs
$message = implode(' ', $decodedBody['message']);
} else {
$message = $decodedBody['message'];
}
$this->logger->warning('OpenProject API error : '. $message, ['app' => $this->appName]);
}
return [
'error' => $e->getMessage(),
'statusCode' => $response->getStatusCode(),
];
} catch (ConnectException $e) {
$this->logger->warning('OpenProject connection error : '.$e->getMessage(), ['app' => $this->appName]);
return [
'error' => $e->getMessage(),
'statusCode' => 404,
];
} catch (Exception $e) {
$this->logger->critical('OpenProject error : '.$e->getMessage(), ['app' => $this->appName]);
return [
'error' => $e->getMessage(),
'statusCode' => 500,
];
}
}
/**
* @param string $url
* @param array<mixed> $params passed to `http_build_query` for GET requests, else send as body
* @param string $method
* @return array<mixed>
*/
public function requestOAuthAccessToken(string $url, array $params = [], string $method = 'GET'): array {
try {
$url = $url . '/oauth/token';
$options = [
'headers' => [
'User-Agent' => 'Nextcloud OpenProject integration',
]
];
if (count($params) > 0) {
if ($method === 'GET') {
$paramsContent = http_build_query($params);
$url .= '?' . $paramsContent;
} else {
$options['body'] = $params;
}
}
if ($method === 'GET') {
$response = $this->client->get($url, $options);
} elseif ($method === 'POST') {
$response = $this->client->post($url, $options);
} elseif ($method === 'PUT') {
$response = $this->client->put($url, $options);
} elseif ($method === 'DELETE') {
$response = $this->client->delete($url, $options);
} else {
return ['error' => $this->l10n->t('Bad HTTP method')];
}
$body = $response->getBody();
$respCode = $response->getStatusCode();
if ($respCode >= 400) {
return ['error' => $this->l10n->t('OAuth access token refused')];
} else {
return json_decode($body, true);
}
} catch (Exception $e) {
$this->logger->warning('OpenProject OAuth error : '.$e->getMessage(), ['app' => $this->appName]);
return ['error' => $e->getMessage()];
}
}
public static function validateURL(string $url): bool {
return filter_var($url, FILTER_VALIDATE_URL) &&
preg_match('/^https?/', $url);
}
/**
* authenticated request to get status of a work package
*
* @param string $userId
* @param string $statusId
* @return string[]
*/
public function getOpenProjectWorkPackageStatus(string $userId, string $statusId): array {
$result = $this->cache->get(Application::APP_ID . '/statuses/' . $statusId);
if ($result !== null) {
return $result;
}
$result = $this->request($userId, 'statuses/' . $statusId);
if (!isset($result['id'])) {
return ['error' => 'Malformed response'];
}
$this->cache->set(
Application::APP_ID . '/statuses/' . $statusId,
$result,
CACHE_TTL
);
return $result;
}
/**
* authenticated request to get status of a work package
*
* @param string $userId
* @param string $typeId
* @return string[]
*/
public function getOpenProjectWorkPackageType(string $userId, string $typeId): array {
$result = $this->cache->get(Application::APP_ID . '/types/' . $typeId);
if ($result !== null) {
return $result;
}
$result = $this->request($userId, 'types/' . $typeId);
if (!isset($result['id'])) {
return ['error' => 'Malformed response'];
}
$this->cache->set(
Application::APP_ID . '/types/' . $typeId,
$result,
CACHE_TTL
);
return $result;
}
/**
* @param IConfig $config
* @param IURLGenerator $urlGenerator
* @return string
* generates an oauth url to OpenProject containing client_id & redirect_uri as parameter
* please note that the state parameter is still missing, that needs to be generated dynamically
* and saved to the DB before calling the OAuth URI
* @throws Exception
*/
public static function getOpenProjectOauthURL(IConfig $config, IURLGenerator $urlGenerator): string {
if (!self::isAdminConfigOk($config)) {
throw new \Exception('OpenProject admin config is not valid!');
}
$clientID = $config->getAppValue(Application::APP_ID, 'client_id');
$oauthUrl = $config->getAppValue(Application::APP_ID, 'oauth_instance_url');
// remove trailing slash from the oauthUrl if present
if (substr($oauthUrl, -1) === '/') {
$oauthUrl = substr($oauthUrl, 0, -1);
}
return $oauthUrl .
'/oauth/authorize' .
'?client_id=' . $clientID .
'&redirect_uri=' . urlencode(self::getOauthRedirectUrl($urlGenerator)) .
'&response_type=code';
}
public static function getOauthRedirectUrl(IURLGenerator $urlGenerator): string {
return $urlGenerator->getAbsoluteURL(
'/index.php/apps/' . Application::APP_ID . '/oauth-redirect'
);
}
/**
* @param string $userId
* @param int $fileId
* @return \OCP\Files\Node
* @throws NotPermittedException
* @throws \OC\User\NoUserException
* @throws NotFoundException
*/
public function getNode($userId, $fileId) {
$userFolder = $this->storage->getUserFolder($userId);
$file = $userFolder->getById($fileId);
if (isset($file[0]) && $file[0] instanceof Node) {
return $file[0];
}
throw new NotFoundException();
}
/**
* @throws \OCP\Files\InvalidPathException
* @throws NotFoundException
* @throws \OCP\PreConditionNotMetException
* @throws NotPermittedException
* @throws OpenprojectErrorException
* @throws \OC\User\NoUserException
* @throws OpenprojectResponseException
* @return int
*/
public function linkWorkPackageToFile(
int $workpackageId,
int $fileId,
string $fileName,
string $userId
): int {
$file = $this->getNode($userId, $fileId);
if (!$file->isReadable()) {
throw new NotPermittedException();
}
$body = [
'_type' => 'Collection',
'_embedded' => [
'elements' => [
[
'originData' => [
'id' => $fileId,
'name' => $fileName,
'mimeType' => $file->getMimeType(),
'createdAt' => gmdate('Y-m-d\TH:i:s.000\Z', $file->getCreationTime()),
'lastModifiedAt' => gmdate('Y-m-d\TH:i:s.000\Z', $file->getMTime()),
'createdByName' => '',
'lastModifiedByName' => ''
],
'_links' => [
'storageUrl' => [
'href' => $this->getBaseUrl()
]
]
]
]
]
];
$params['body'] = \Safe\json_encode($body);
$result = $this->request(
$userId, 'work_packages/' . $workpackageId. '/file_links', $params, 'POST'
);
if (isset($result['error'])) {
throw new OpenprojectErrorException($result['error']);
}
if (
!isset($result['_type']) ||
$result['_type'] !== 'Collection' ||
!isset($result['_embedded']) ||
!isset($result['_embedded']['elements']) ||
!isset($result['_embedded']['elements'][0]) ||
!isset($result['_embedded']['elements'][0]['id'])
) {
throw new OpenprojectResponseException('Malformed response');
}
return $result['_embedded']['elements'][0]['id'];
}
/**
* @throws OpenprojectErrorException
* @throws PreConditionNotMetException
* @throws JsonException
* @throws Exception
* @return array<mixed>
*/
public function markAllNotificationsOfWorkPackageAsRead(
int $workpackageId, string $userId
) {
$filters[] = [
'resourceId' =>
['operator' => '=', 'values' => [(string)$workpackageId]]
];
$params['body'] = '';
$fullUrl = 'notifications/read_ian?filters=' . urlencode(\Safe\json_encode($filters));
$result = $this->request(
$userId, $fullUrl, $params, 'POST'
);
if (isset($result['error'])) {
throw new OpenprojectErrorException($result['error']);
}
return $result;
}
/**
* @param int $workpackageId
* @param string $userId
* @return array<mixed>
* @throws NotFoundException
* @throws OpenprojectErrorException
* @throws OpenprojectResponseException
*/
public function getWorkPackageFileLinks(int $workpackageId, string $userId): array {
$result = $this->request(
$userId, 'work_packages/' . $workpackageId. '/file_links'
);
if (isset($result['error'])) {
throw new OpenprojectErrorException($result['error']);
}
if (
!isset($result['_type']) ||
$result['_type'] !== 'Collection' ||
!isset($result['_embedded']) ||
!isset($result['_embedded']['elements'])
) {
throw new OpenprojectResponseException('Malformed response');
}
return $result['_embedded']['elements'];
}
/**
* @param int $fileLinkId
* @param string $userId
* @return array<mixed>
* @throws NotFoundException
* @throws OpenprojectErrorException|OpenprojectResponseException
*/
public function deleteFileLink(int $fileLinkId, string $userId): array {
$result = $this->request(
$userId, 'file_links/' . $fileLinkId, [""], 'DELETE'
);
if (isset($result['error'])) {
throw new OpenprojectErrorException($result['error']);
}
if (!isset($result['success'])) {
throw new OpenprojectResponseException('Malformed response');
}
return $result;
}
/**
* checks if every admin config variables are set
* checks if the oauth instance url is valid
*
* @param IConfig $config
* @return bool
*/
public static function isAdminConfigOk(IConfig $config):bool {
$clientId = $config->getAppValue(Application::APP_ID, 'client_id');
$clientSecret = $config->getAppValue(Application::APP_ID, 'client_secret');
$oauthInstanceUrl = $config->getAppValue(Application::APP_ID, 'oauth_instance_url');
$checkIfConfigIsSet = !!($clientId) && !!($clientSecret) && !!($oauthInstanceUrl);
if (!$checkIfConfigIsSet) {
return false;
} else {
return self::validateURL($oauthInstanceUrl);
}
}
/**
* makes sure the URL has no extra slashes
*/
public static function sanitizeUrl(
string $url, bool $trailingSlash = false
): string {
if ($trailingSlash === true) {
$url = $url . "/";
} else {
$url = \rtrim($url, "/");
}
$url = \preg_replace("/([^:]\/)\/+/", '$1', $url);
return $url;
}
}