From 86987d0632d38fef9061e283d03f05598b14ab04 Mon Sep 17 00:00:00 2001 From: Artur Neumann Date: Fri, 18 Mar 2022 16:55:19 +0545 Subject: [PATCH] get config in request function Signed-off-by: Artur Neumann --- lib/Controller/ConfigController.php | 26 +-- lib/Controller/OpenProjectAPIController.php | 18 +- lib/Search/OpenProjectSearchProvider.php | 5 +- lib/Service/OpenProjectAPIService.php | 101 +++------ tests/lib/Controller/ConfigControllerTest.php | 6 - .../OpenProjectAPIControllerTest.php | 5 - .../lib/Service/OpenProjectAPIServiceTest.php | 205 +++++++++--------- 7 files changed, 135 insertions(+), 231 deletions(-) diff --git a/lib/Controller/ConfigController.php b/lib/Controller/ConfigController.php index ed2e052fd..3ff9d4f88 100644 --- a/lib/Controller/ConfigController.php +++ b/lib/Controller/ConfigController.php @@ -85,7 +85,7 @@ public function setConfig(array $values): DataResponse { if (isset($values['token'])) { if ($values['token'] && $values['token'] !== '') { - $result = $this->storeUserInfo($values['token']); + $result = $this->storeUserInfo(); } else { $this->config->deleteUserValue($this->userId, Application::APP_ID, 'token'); $this->config->deleteUserValue($this->userId, Application::APP_ID, 'login'); @@ -168,7 +168,7 @@ public function oauthRedirect(string $code = '', string $state = ''): RedirectRe $this->config->setUserValue($this->userId, Application::APP_ID, 'refresh_token', $refreshToken); // get user info // ToDo check response for errors - $this->storeUserInfo($accessToken); + $this->storeUserInfo(); return new RedirectResponse( $this->urlGenerator->linkToRoute('settings.PersonalSettings.index', ['section' => 'connected-accounts']) . '?openprojectToken=success' @@ -200,20 +200,10 @@ public function oauthRedirect(string $code = '', string $state = ''): RedirectRe } /** - * @param string $accessToken - * @return array{error?: string, user_name?: string, errorMesssage?: string} + * @return array{error?: string, user_name?: string, statusCode?: int} */ - private function storeUserInfo(string $accessToken): array { - $refreshToken = $this->config->getUserValue($this->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::validateOpenProjectURL($openprojectUrl)) { - return ['error' => 'OpenProject URL is invalid']; - } - - $info = $this->openprojectAPIService->request($openprojectUrl, $accessToken, $refreshToken, $clientID, $clientSecret, $this->userId, 'users/me'); + private function storeUserInfo(): array { + $info = $this->openprojectAPIService->request($this->userId, 'users/me'); if (isset($info['lastName'], $info['firstName'], $info['id'])) { $fullName = $info['firstName'] . ' ' . $info['lastName']; $this->config->setUserValue($this->userId, Application::APP_ID, 'user_id', $info['id']); @@ -223,9 +213,11 @@ private function storeUserInfo(string $accessToken): array { $this->config->deleteUserValue($this->userId, Application::APP_ID, 'user_id'); $this->config->deleteUserValue($this->userId, Application::APP_ID, 'user_name'); if (isset($info['statusCode']) && $info['statusCode'] === 404) { - $info['errorMessage'] = 'Not found'; + $info['error'] = 'Not found'; } else { - $info['errorMessage'] = 'Invalid token'; + if (!isset($info['error'])) { + $info['error'] = 'Invalid token'; + } } return $info; } diff --git a/lib/Controller/OpenProjectAPIController.php b/lib/Controller/OpenProjectAPIController.php index b92d0a468..c88d542c0 100644 --- a/lib/Controller/OpenProjectAPIController.php +++ b/lib/Controller/OpenProjectAPIController.php @@ -125,9 +125,7 @@ public function getNotifications(?string $since = null): DataResponse { if ($this->accessToken === '' || !OpenProjectAPIService::validateOpenProjectURL($this->openprojectUrl)) { return new DataResponse('', Http::STATUS_BAD_REQUEST); } - $result = $this->openprojectAPIService->getNotifications( - $this->openprojectUrl, $this->accessToken, $this->refreshToken, $this->clientID, $this->clientSecret, $this->userId, $since, 7 - ); + $result = $this->openprojectAPIService->getNotifications($this->userId, $since, 7); if (!isset($result['error'])) { $response = new DataResponse($result); } else { @@ -153,11 +151,6 @@ public function getSearchedWorkPackages(?string $searchQuery = null, ?int $fileI ); } $result = $this->openprojectAPIService->searchWorkPackage( - $this->openprojectUrl, - $this->accessToken, - $this->refreshToken, - $this->clientID, - $this->clientSecret, $this->userId, $searchQuery, $fileId @@ -192,11 +185,6 @@ public function linkWorkPackageToFile(int $workpackageId, int $fileId, string $f try { $result = $this->openprojectAPIService->linkWorkPackageToFile( - $this->openprojectUrl, - $this->accessToken, - $this->refreshToken, - $this->clientID, - $this->clientSecret, $workpackageId, $fileId, $fileName, @@ -227,7 +215,7 @@ public function getOpenProjectWorkPackageStatus(string $id): DataResponse { return new DataResponse('', Http::STATUS_BAD_REQUEST); } $result = $this->openprojectAPIService->getOpenProjectWorkPackageStatus( - $this->openprojectUrl, $this->accessToken, $this->refreshToken, $this->clientID, $this->clientSecret, $this->userId, $id + $this->userId, $id ); if (!isset($result['error'])) { $response = new DataResponse($result); @@ -251,7 +239,7 @@ public function getOpenProjectWorkPackageType(string $id): DataResponse { return new DataResponse('', Http::STATUS_BAD_REQUEST); } $result = $this->openprojectAPIService->getOpenProjectWorkPackageType( - $this->openprojectUrl, $this->accessToken, $this->refreshToken, $this->clientID, $this->clientSecret, $this->userId, $id + $this->userId, $id ); if (!isset($result['error'])) { $response = new DataResponse($result); diff --git a/lib/Search/OpenProjectSearchProvider.php b/lib/Search/OpenProjectSearchProvider.php index f65cb6080..211cd9628 100644 --- a/lib/Search/OpenProjectSearchProvider.php +++ b/lib/Search/OpenProjectSearchProvider.php @@ -126,16 +126,13 @@ public function search(IUser $user, ISearchQuery $query): SearchResult { $openprojectUrl = $this->config->getAppValue(Application::APP_ID, 'oauth_instance_url'); $accessToken = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'token'); - $refreshToken = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'refresh_token'); - $clientID = $this->config->getAppValue(Application::APP_ID, 'client_id'); - $clientSecret = $this->config->getAppValue(Application::APP_ID, 'client_secret'); $searchEnabled = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'search_enabled', '0') === '1'; if ($accessToken === '' || !$searchEnabled) { return SearchResult::paginated($this->getName(), [], 0); } - $searchResults = $this->service->searchWorkPackage($openprojectUrl, $accessToken, $refreshToken, $clientID, $clientSecret, $user->getUID(), $term); + $searchResults = $this->service->searchWorkPackage($user->getUID(), $term); $searchResults = array_slice($searchResults, $offset, $limit); if (isset($searchResults['error'])) { diff --git a/lib/Service/OpenProjectAPIService.php b/lib/Service/OpenProjectAPIService.php index 19ded618c..544011de8 100644 --- a/lib/Service/OpenProjectAPIService.php +++ b/lib/Service/OpenProjectAPIService.php @@ -116,7 +116,6 @@ private function checkNotificationsForUser(string $userId): void { $accessToken = $this->config->getUserValue($userId, Application::APP_ID, 'token'); $notificationEnabled = ($this->config->getUserValue($userId, Application::APP_ID, 'notification_enabled', '0') === '1'); if ($accessToken && $notificationEnabled) { - $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'); @@ -127,9 +126,7 @@ private function checkNotificationsForUser(string $userId): void { $myOPUserId = $this->config->getUserValue($userId, Application::APP_ID, 'user_id'); if ($myOPUserId !== '') { $myOPUserId = (int) $myOPUserId; - $notifications = $this->getNotifications( - $openprojectUrl, $accessToken, $refreshToken, $clientID, $clientSecret, $userId, $lastNotificationCheck - ); + $notifications = $this->getNotifications($userId, $lastNotificationCheck); if (!isset($notifications['error']) && count($notifications) > 0) { $newLastNotificationCheck = $notifications[0]['updatedAt']; $this->config->setUserValue($userId, Application::APP_ID, 'last_notification_check', $newLastNotificationCheck); @@ -198,19 +195,14 @@ public function now(): string { } /** - * @param string $url - * @param string $accessToken - * @param string $refreshToken - * @param string $clientID - * @param string $clientSecret * @param string $userId * @param ?string $since * @param ?int $limit * @return array */ - public function getNotifications(string $url, string $accessToken, - string $refreshToken, string $clientID, string $clientSecret, string $userId, - ?string $since = null, ?int $limit = null): array { + public function getNotifications( + string $userId, ?string $since = null, ?int $limit = null + ): array { if ($since) { $filters = '[{"updatedAt":{"operator":"<>d","values":["' . $since . '","' . $this->now() . '"]}},{"status":{"operator":"!","values":["14"]}}]'; } else { @@ -226,9 +218,7 @@ public function getNotifications(string $url, string $accessToken, 'sortBy' => '[["updatedAt", "desc"]]', // 'limit' => $limit, ]; - $result = $this->request( - $url, $accessToken, $refreshToken, $clientID, $clientSecret, $userId, 'work_packages', $params - ); + $result = $this->request($userId, 'work_packages', $params); if (isset($result['error'])) { return $result; } elseif (!isset($result['_embedded']['elements'])) { @@ -243,11 +233,6 @@ public function getNotifications(string $url, string $accessToken, } /** - * @param string $url - * @param string $accessToken - * @param string $refreshToken - * @param string $clientID - * @param string $clientSecret * @param string $userId * @param string|null $query * @param int|null $fileId @@ -257,9 +242,9 @@ public function getNotifications(string $url, string $accessToken, * @throws \OCP\PreConditionNotMetException * @throws \Safe\Exceptions\JsonException */ - public function searchWorkPackage(string $url, string $accessToken, - string $refreshToken, string $clientID, string $clientSecret, string $userId, - string $query = null, int $fileId = null, int $offset = 0, int $limit = 5): array { + public function searchWorkPackage( + string $userId, string $query = null, int $fileId = null, int $offset = 0, int $limit = 5 + ): array { $resultsById = []; $filters = []; @@ -276,9 +261,7 @@ public function searchWorkPackage(string $url, string $accessToken, 'sortBy' => '[["updatedAt", "desc"]]', // 'limit' => $limit, ]; - $searchDescResult = $this->request( - $url, $accessToken, $refreshToken, $clientID, $clientSecret, $userId, 'work_packages', $params - ); + $searchDescResult = $this->request($userId, 'work_packages', $params); if (isset($searchDescResult['error'])) { return $searchDescResult; @@ -300,9 +283,7 @@ public function searchWorkPackage(string $url, string $accessToken, 'sortBy' => '[["updatedAt", "desc"]]', // 'limit' => $limit, ]; - $searchSubjectResult = $this->request( - $url, $accessToken, $refreshToken, $clientID, $clientSecret, $userId, 'work_packages', $params - ); + $searchSubjectResult = $this->request($userId, 'work_packages', $params); if (isset($searchSubjectResult['error'])) { return $searchSubjectResult; @@ -359,11 +340,6 @@ public function getOpenProjectAvatar(string $url, } /** - * @param string $openprojectUrl - * @param string $accessToken - * @param string $refreshToken - * @param string $clientID - * @param string $clientSecret * @param string $userId * @param string $endPoint * @param array $params @@ -371,9 +347,16 @@ public function getOpenProjectAvatar(string $url, * @return array * @throws \OCP\PreConditionNotMetException */ - public function request(string $openprojectUrl, string $accessToken, string $refreshToken, - string $clientID, string $clientSecret, string $userId, + 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::validateOpenProjectURL($openprojectUrl)) { + return ['error' => 'OpenProject URL is invalid', 'statusCode' => 500]; + } try { $url = $openprojectUrl . '/api/v3/' . $endPoint; $options = [ @@ -433,9 +416,7 @@ public function request(string $openprojectUrl, string $accessToken, string $ref $accessToken = $result['access_token']; $this->config->setUserValue($userId, Application::APP_ID, 'token', $accessToken); // retry the request with new access token - return $this->request( - $openprojectUrl, $accessToken, $refreshToken, $clientID, $clientSecret, $userId, $endPoint, $params, $method - ); + return $this->request($userId, $endPoint, $params, $method); } } // try to get the error in the response @@ -520,25 +501,12 @@ public static function validateOpenProjectURL(string $openprojectUrl): bool { /** * authenticated request to get status of a work package * - * @param string $url - * @param string $accessToken - * @param string $refreshToken - * @param string $clientID - * @param string $clientSecret * @param string $userId * @param string $statusId * @return string[] */ - public function getOpenProjectWorkPackageStatus( - string $url, - string $accessToken, - string $refreshToken, - string $clientID, - string $clientSecret, - string $userId, - string $statusId): array { - $result = $this->request( - $url, $accessToken, $refreshToken, $clientID, $clientSecret, $userId, 'statuses/' . $statusId); + public function getOpenProjectWorkPackageStatus(string $userId, string $statusId): array { + $result = $this->request($userId, 'statuses/' . $statusId); if (!isset($result['id'])) { return ['error' => 'Malformed response']; } @@ -548,26 +516,12 @@ public function getOpenProjectWorkPackageStatus( /** * authenticated request to get status of a work package * - * @param string $url - * @param string $accessToken - * @param string $refreshToken - * @param string $clientID - * @param string $clientSecret * @param string $userId * @param string $typeId * @return string[] */ - public function getOpenProjectWorkPackageType( - string $url, - string $accessToken, - string $refreshToken, - string $clientID, - string $clientSecret, - string $userId, - string $typeId - ): array { - $result = $this->request( - $url, $accessToken, $refreshToken, $clientID, $clientSecret, $userId, 'types/' . $typeId); + public function getOpenProjectWorkPackageType(string $userId, string $typeId): array { + $result = $this->request($userId, 'types/' . $typeId); if (!isset($result['id'])) { return ['error' => 'Malformed response']; } @@ -623,11 +577,6 @@ public function getNode($userId, $fileId) { * @return int */ public function linkWorkPackageToFile( - string $openprojectUrl, - string $accessToken, - string $refreshToken, - string $clientID, - string $clientSecret, int $workpackageId, int $fileId, string $fileName, @@ -665,7 +614,7 @@ public function linkWorkPackageToFile( $params['body'] = \Safe\json_encode($body); $result = $this->request( - $openprojectUrl, $accessToken, $refreshToken, $clientID, $clientSecret, $userId, 'work_packages/' . $workpackageId. '/file_links', $params, 'POST' + $userId, 'work_packages/' . $workpackageId. '/file_links', $params, 'POST' ); if (isset($result['error'])) { diff --git a/tests/lib/Controller/ConfigControllerTest.php b/tests/lib/Controller/ConfigControllerTest.php index 0bb2880c4..c72896358 100644 --- a/tests/lib/Controller/ConfigControllerTest.php +++ b/tests/lib/Controller/ConfigControllerTest.php @@ -67,12 +67,6 @@ public function setUpMocks(): void { $apiServiceMock ->method('request') ->with( - 'http://openproject.org', - 'oAuthAccessToken', - 'oauth', - 'oAuthRefreshToken', - 'clientID', - 'clientSecret', 'testUser', 'users/me' ) diff --git a/tests/lib/Controller/OpenProjectAPIControllerTest.php b/tests/lib/Controller/OpenProjectAPIControllerTest.php index 74da9692d..8a3783263 100644 --- a/tests/lib/Controller/OpenProjectAPIControllerTest.php +++ b/tests/lib/Controller/OpenProjectAPIControllerTest.php @@ -213,11 +213,6 @@ public function testGetSearchedWorkPackages($searchQuery, $fileId, array $expect $service->expects($this->once()) ->method('searchWorkPackage') ->with( - $this->anything(), - $this->anything(), - $this->anything(), - $this->anything(), - $this->anything(), $this->anything(), $searchQuery, $fileId diff --git a/tests/lib/Service/OpenProjectAPIServiceTest.php b/tests/lib/Service/OpenProjectAPIServiceTest.php index ed457d954..ddb56ab5d 100644 --- a/tests/lib/Service/OpenProjectAPIServiceTest.php +++ b/tests/lib/Service/OpenProjectAPIServiceTest.php @@ -142,17 +142,19 @@ private function getStorageMock($nodeClassName = null) { /** * @param IRootFolder|null $storageMock + * @param string $oAuthToken * @return OpenProjectAPIService */ - private function getOpenProjectAPIService($storageMock = null) { - $config = $this->createMock(IConfig::class); + private function getOpenProjectAPIService( + $storageMock = null, $oAuthToken = '1234567890' + ) { $certificateManager = $this->getMockBuilder('\OCP\ICertificateManager')->getMock(); $certificateManager->method('getAbsoluteBundlePath')->willReturn('/'); $logger = $this->createMock(ILogger::class); $client = new GuzzleClient(); $ocClient = new Client( - $config, + $this->createMock(IConfig::class), $logger, $certificateManager, $client, @@ -174,6 +176,45 @@ private function getOpenProjectAPIService($storageMock = null) { if ($storageMock === null) { $storageMock = $this->createMock(\OCP\Files\IRootFolder::class); } + $configMock = $this->getMockBuilder(IConfig::class)->getMock(); + + $configMock + ->method('getUserValue') + ->withConsecutive( + ['testUser', 'integration_openproject', 'token'], + ['testUser', 'integration_openproject', 'refresh_token'], + ['testUser', 'integration_openproject', 'token'], + ) + ->willReturnOnConsecutiveCalls( + $oAuthToken, + 'oAuthRefreshToken', + 'new-Token' + ); + + $pactMockServerConfig = new MockServerEnvConfig(); + + $configMock + ->method('getAppValue') + ->withConsecutive( + ['integration_openproject', 'client_id'], + ['integration_openproject', 'client_secret'], + ['integration_openproject', 'oauth_instance_url'], + + // for second request after invalid token reply + ['integration_openproject', 'client_id'], + ['integration_openproject', 'client_secret'], + ['integration_openproject', 'oauth_instance_url'], + ) + ->willReturnOnConsecutiveCalls( + $this->clientId, + $this->clientSecret, + $pactMockServerConfig->getBaseUri()->__toString(), + + // for second request after invalid token reply + $this->clientId, + $this->clientSecret, + $pactMockServerConfig->getBaseUri()->__toString() + ); return new OpenProjectAPIService( 'integration_openproject', @@ -181,7 +222,7 @@ private function getOpenProjectAPIService($storageMock = null) { $avatarManagerMock, $this->createMock(\Psr\Log\LoggerInterface::class), $this->createMock(\OCP\IL10N::class), - $this->createMock(\OCP\IConfig::class), + $configMock, $this->createMock(\OCP\Notification\IManager::class), $clientService, $storageMock @@ -276,14 +317,14 @@ public function testSearchWorkPackageOnlyQueryDescAndSubjectResponse( $service->method('request') ->withConsecutive( [ - 'url','token', 'refresh', 'id', 'secret', 'user', 'work_packages', + 'user', 'work_packages', [ 'filters' => '[{"description":{"operator":"~","values":["search query"]}},{"status":{"operator":"!","values":["14"]}}]', 'sortBy' => '[["updatedAt", "desc"]]', ] ], [ - 'url','token', 'refresh', 'id', 'secret', 'user', 'work_packages', + 'user', 'work_packages', [ 'filters' => '[{"subject":{"operator":"~","values":["search query"]}},{"status":{"operator":"!","values":["14"]}}]', 'sortBy' => '[["updatedAt", "desc"]]', @@ -294,9 +335,7 @@ public function testSearchWorkPackageOnlyQueryDescAndSubjectResponse( $descriptionResponse, $subjectResponse ); - $result = $service->searchWorkPackage( - 'url', 'token', 'refresh', 'id', 'secret', 'user', 'search query' - ); + $result = $service->searchWorkPackage('user', 'search query'); $this->assertSame($expectedResult, $result); } @@ -308,7 +347,7 @@ public function testSearchWorkPackageByFileIdOnlyFileId() { $service->method('request') ->withConsecutive( [ - 'url','token', 'refresh', 'id', 'secret', 'user', 'work_packages', + 'user', 'work_packages', [ 'filters' => '[{"file_link_origin_id":{"operator":"=","values":["123"]}}]', 'sortBy' => '[["updatedAt", "desc"]]', @@ -318,9 +357,7 @@ public function testSearchWorkPackageByFileIdOnlyFileId() { ->willReturnOnConsecutiveCalls( ["_embedded" => ["elements" => [['id' => 1], ['id' => 2], ['id' => 3]]]] ); - $result = $service->searchWorkPackage( - 'url', 'token', 'refresh', 'id', 'secret', 'user', null, 123 - ); + $result = $service->searchWorkPackage('user', null, 123); $this->assertSame([['id' => 1], ['id' => 2], ['id' => 3]], $result); } @@ -332,14 +369,14 @@ public function testSearchWorkPackageByFileIdQueryAndFileId() { $service->method('request') ->withConsecutive( [ - 'url','token', 'refresh', 'id', 'secret', 'user', 'work_packages', + 'user', 'work_packages', [ 'filters' => '[{"file_link_origin_id":{"operator":"=","values":["123"]}},{"description":{"operator":"~","values":["search query"]}},{"status":{"operator":"!","values":["14"]}}]', 'sortBy' => '[["updatedAt", "desc"]]', ] ], [ - 'url','token', 'refresh', 'id', 'secret', 'user', 'work_packages', + 'user', 'work_packages', [ 'filters' => '[{"subject":{"operator":"~","values":["search query"]}},{"status":{"operator":"!","values":["14"]}}]', 'sortBy' => '[["updatedAt", "desc"]]', @@ -350,9 +387,7 @@ public function testSearchWorkPackageByFileIdQueryAndFileId() { ["_embedded" => ["elements" => [['id' => 1], ['id' => 2], ['id' => 3]]]], ["_embedded" => ["elements" => [['id' => 4], ['id' => 5], ['id' => 6]]]] ); - $result = $service->searchWorkPackage( - 'url', 'token', 'refresh', 'id', 'secret', 'user', 'search query', 123 - ); + $result = $service->searchWorkPackage('user', 'search query', 123); $this->assertSame([['id' => 1], ['id' => 2], ['id' => 3], ['id' => 4], ['id' => 5], ['id' => 6]], $result); } @@ -363,9 +398,7 @@ public function testSearchWorkPackageRequestProblem() { $service = $this->getServiceMock(); $service->method('request') ->willReturn(['error' => 'some issue', 'statusCode' => 404 ]); - $result = $service->searchWorkPackage( - 'url', 'token', 'refresh', 'id', 'secret', 'user', 'search query', 123 - ); + $result = $service->searchWorkPackage('user', 'search query', 123); $this->assertSame(['error' => 'some issue', 'statusCode' => 404 ], $result); } @@ -380,9 +413,7 @@ public function testSearchWorkPackageSecondRequestProblem() { ["_embedded" => ["elements" => [['id' => 1], ['id' => 2], ['id' => 3]]]], ['error' => 'some issue', 'statusCode' => 404 ] ); - $result = $service->searchWorkPackage( - 'url', 'token', 'refresh', 'id', 'secret', 'user', 'search query', 123 - ); + $result = $service->searchWorkPackage('user', 'search query', 123); $this->assertSame(['error' => 'some issue', 'statusCode' => 404 ], $result); } @@ -410,12 +441,7 @@ public function testGetNotificationsRequest() { ->willRespondWith($providerResponse); $result = $this->service->getNotifications( - $this->mockServerBaseUri, - '1234567890', - '', - $this->clientId, - $this->clientSecret, - 'admin' + 'testUser' ); $this->assertSame([['some' => 'data']], $result); } @@ -439,7 +465,7 @@ public function testGetNotificationsMalformedResponse($response) { $service = $this->getServiceMock(); $service->method('request') ->willReturn($response); - $result = $service->getNotifications('', '', '', '', '', ''); + $result = $service->getNotifications('', ''); $this->assertSame(["error" => "Malformed response"], $result); } @@ -450,7 +476,7 @@ public function testGetNotificationsErrorResponse() { $service = $this->getServiceMock(); $service->method('request') ->willReturn(['error' => 'my error']); - $result = $service->getNotifications('', '', '', '', '', '', ''); + $result = $service->getNotifications('', ''); $this->assertSame(["error" => "my error"], $result); } @@ -464,13 +490,13 @@ public function testGetNotificationsFilters() { $service->expects($this->once()) ->method('request') ->with( - 'url', 'token', 'refresh', 'id', 'secret', 'user', 'work_packages', + 'user', 'work_packages', [ 'filters' => '[{"updatedAt":{"operator":"<>d","values":["2022-01-01T12:01:01Z","2022-01-27T08:15:48Z"]}},{"status":{"operator":"!","values":["14"]}}]', 'sortBy' => '[["updatedAt", "desc"]]' ]); - $service->getNotifications('url', 'token', 'refresh', 'id', 'secret', 'user', '2022-01-01T12:01:01Z'); + $service->getNotifications('user', '2022-01-01T12:01:01Z'); } /** @@ -480,7 +506,7 @@ public function testGetNotificationsLimit() { $service = $this->getServiceMock(); $service->method('request') ->willReturn(["_embedded" => ["elements" => [['id' => 1], ['id' => 2], ['id' => 3]]]]); - $result = $service->getNotifications('', '', '', '', '', '', '', 2); + $result = $service->getNotifications('', '', 2); $this->assertSame([['id' => 1], ['id' => 2]], $result); } @@ -506,12 +532,7 @@ public function testRequestUsingOAuthToken() { ->willRespondWith($providerResponse); $result = $this->service->request( - $this->mockServerBaseUri, - '1234567890', - '', - $this->clientId, - $this->clientSecret, - 'admin', + 'testUser', 'work_packages' ); $this->assertSame(["_embedded" => ["elements" => []]], $result); @@ -544,7 +565,7 @@ public function testRequestRefreshOAuthToken() { ->setBody( 'client_id=' . $this->clientId . '&client_secret=' . $this->clientSecret . - '&grant_type=refresh_token&refresh_token=myRefreshToken' + '&grant_type=refresh_token&refresh_token=oAuthRefreshToken' ); $refreshTokenResponse = new ProviderResponse(); @@ -573,13 +594,9 @@ public function testRequestRefreshOAuthToken() { ->with($consumerRequestNewOAuthToken) ->willRespondWith($providerResponseNewOAuthToken); - $result = $this->service->request( - $this->mockServerBaseUri, - 'invalid', - 'myRefreshToken', - $this->clientId, - $this->clientSecret, - 'admin', + $service = $this->getOpenProjectAPIService(null, 'invalid'); + $result = $service->request( + 'testUser', 'work_packages' ); $this->assertSame(["_embedded" => ["elements" => [['id' => 1], ['id' => 2]]]], $result); @@ -604,12 +621,7 @@ public function testRequestToNotExistingPath() { ->willRespondWith($providerResponse); $result = $this->service->request( - $this->mockServerBaseUri, - '1234567890', - '', - $this->clientId, - $this->clientSecret, - 'admin', + 'testUser', 'not_existing' ); $this->assertSame([ @@ -713,12 +725,7 @@ public function testGetOpenProjectWorkPackageStatusRequest(): void { ->willRespondWith($providerResponse); $result = $this->service->getOpenProjectWorkPackageStatus( - $this->mockServerBaseUri, - '1234567890', - '', - $this->clientId, - $this->clientSecret, - 'admin', + 'testUser', '7' ); $this->assertSame(["_type" => "Status", "id" => 7, "name" => "In progress", @@ -733,7 +740,7 @@ public function testGetOpenProjectWorkPackageStatusResponse(): void { $service->method('request') ->willReturn(["_type" => "Status", "id" => 7, "name" => "In progress", "isClosed" => false, "color" => "#CC5DE8", "isDefault" => false, "isReadonly" => false, "defaultDoneRatio" => null, "position" => 7]); - $result = $service->getOpenProjectWorkPackageStatus('url', 'token', 'refresh', 'id', 'secret', 'user', 'statusId'); + $result = $service->getOpenProjectWorkPackageStatus('user', 'statusId'); $this->assertSame(["_type" => "Status", "id" => 7, "name" => "In progress", "isClosed" => false, "color" => "#CC5DE8", "isDefault" => false, "isReadonly" => false, "defaultDoneRatio" => null, "position" => 7], $result); } @@ -745,7 +752,7 @@ public function testGetOpenProjectWorkPackageStatusMalFormedResponse(): void { $service = $this->getServiceMock(); $service->method('request') ->willReturn(['error' => 'Malformed response']); - $result = $service->getOpenProjectWorkPackageStatus('', '', '', '', '', '', ''); + $result = $service->getOpenProjectWorkPackageStatus('', ''); $this->assertSame(['error' => 'Malformed response'], $result); } @@ -771,12 +778,7 @@ public function testGetOpenProjectWorkPackageTypeRequest(): void { ->willRespondWith($providerResponse); $result = $this->service->getOpenProjectWorkPackageType( - $this->mockServerBaseUri, - '1234567890', - '', - $this->clientId, - $this->clientSecret, - 'admin', + 'testUser', '3' ); @@ -794,7 +796,7 @@ public function testGetOpenProjectWorkPackageTypeResponse(): void { "_type" => "Type", "id" => 3, "name" => "Phase", "color" => "#CC5DE8", "position" => 4, "isDefault" => true, "isMilestone" => false, "createdAt" => "2022-01-12T08:53:15Z", "updatedAt" => "2022-01-12T08:53:34Z" ]); - $result = $service->getOpenProjectWorkPackageType('url', 'token', 'refresh', 'id', 'secret', 'user', 'typeId'); + $result = $service->getOpenProjectWorkPackageType('user', 'typeId'); $this->assertSame([ "_type" => "Type", "id" => 3, "name" => "Phase", "color" => "#CC5DE8", "position" => 4, "isDefault" => true, "isMilestone" => false, "createdAt" => "2022-01-12T08:53:15Z", "updatedAt" => "2022-01-12T08:53:34Z" @@ -808,7 +810,7 @@ public function testGetOpenProjectWorkPackageTypeMalFormedResponse(): void { $service = $this->getServiceMock(); $service->method('request') ->willReturn(['error' => 'Malformed response']); - $result = $service->getOpenProjectWorkPackageType('', '', '', '', '', '', ''); + $result = $service->getOpenProjectWorkPackageType('', ''); $this->assertSame(['error' => 'Malformed response'], $result); } @@ -949,12 +951,11 @@ public function testLinkWorkPackageToFileRequest(): void { $service->expects($this->once()) ->method('request') ->with( - 'url', 'token', 'refresh', 'id', 'secret', 'user', 'work_packages/123/file_links', + 'user', 'work_packages/123/file_links', ['body' => \Safe\json_encode($this->validFileLinkRequestBody)] ); $result = $service->linkWorkPackageToFile( - 'url', 'token', 'refresh', 'id', 'secret', 123, 5503, 'logo.png', 'http://nextcloud.org', 'user' ); $this->assertSame(2456, $result); @@ -977,7 +978,6 @@ public function testLinkWorkPackageToFileFileNotReadable(): void { $this->expectException(NotPermittedException::class); $service->linkWorkPackageToFile( - 'url', 'token', 'refresh', 'id', 'secret', 123, 5503, 'logo.png', 'http://nextcloud.org', 'user' ); } @@ -1000,7 +1000,6 @@ public function testLinkWorkPackageToFileFileNotFound(): void { $this->expectException(NotFoundException::class); $result = $service->linkWorkPackageToFile( - 'url', 'token', 'refresh', 'id', 'secret', 123, 5503, 'logo.png', 'http://nextcloud.org', 'user' ); } @@ -1023,19 +1022,34 @@ public function testRequestException( $clientService = $this->getMockBuilder('\OCP\Http\Client\IClientService')->getMock(); $clientService->method('newClient')->willReturn($ocClient); + $configMock = $this->getMockBuilder(IConfig::class) + ->getMock(); + $configMock + ->method('getAppValue') + ->withConsecutive( + ['integration_openproject', 'client_id'], + ['integration_openproject', 'client_secret'], + ['integration_openproject', 'oauth_instance_url'], + ) + ->willReturnOnConsecutiveCalls( + $this->clientId, + $this->clientSecret, + 'http://openproject.org', + ); + $service = new OpenProjectAPIService( 'integration_openproject', $this->createMock(\OCP\IUserManager::class), $this->createMock(\OCP\IAvatarManager::class), $this->createMock(\Psr\Log\LoggerInterface::class), $this->createMock(\OCP\IL10N::class), - $this->createMock(\OCP\IConfig::class), + $configMock, $this->createMock(\OCP\Notification\IManager::class), $clientService, $this->createMock(\OCP\Files\IRootFolder::class), ); - $response = $service->request('', '', '', '', '', '', '', []); + $response = $service->request('', '', []); $this->assertSame($expectedError, $response['error']); $this->assertSame($expectedHttpStatusCode, $response['statusCode']); } @@ -1063,16 +1077,11 @@ public function testLinkWorkPackageToFilePact(): void { $service = $this->getOpenProjectAPIService($storageMock); $result = $service->linkWorkPackageToFile( - $this->mockServerBaseUri, - '1234567890', - '', - $this->clientId, - $this->clientSecret, 123, 5503, 'logo.png', 'http://nextcloud.org', - 'admin' + 'testUser' ); $this->assertSame(1337, $result); @@ -1122,16 +1131,11 @@ public function testLinkWorkPackageToFileEmptyStorageUrlPact(): void { $this->expectException(OpenprojectErrorException::class); $service->linkWorkPackageToFile( - $this->mockServerBaseUri, - '1234567890', - '', - $this->clientId, - $this->clientSecret, 123, 5503, 'logo.png', '', - 'admin' + 'testUser' ); } @@ -1179,16 +1183,11 @@ public function testLinkWorkPackageToFileNotAvailableStorageUrlPact(): void { $this->expectException(OpenprojectErrorException::class); $service->linkWorkPackageToFile( - $this->mockServerBaseUri, - '1234567890', - '', - $this->clientId, - $this->clientSecret, 123, 5503, 'logo.png', 'http://not-existing', - 'admin' + 'testUser' ); } @@ -1218,20 +1217,15 @@ public function testLinkWorkPackageToFileMissingPermissionPact(): void { ->willRespondWith($providerResponse); $storageMock = $this->getStorageMock(); - $service = $this->getOpenProjectAPIService($storageMock); + $service = $this->getOpenProjectAPIService($storageMock, 'MissingPermission'); $this->expectException(OpenprojectErrorException::class); $service->linkWorkPackageToFile( - $this->mockServerBaseUri, - 'MissingPermission', - '', - $this->clientId, - $this->clientSecret, 123, 5503, 'logo.png', 'http://nextcloud.org', - 'admin' + 'testUser' ); } @@ -1265,16 +1259,11 @@ public function testLinkWorkPackageToFileNotFoundPact(): void { $this->expectException(OpenprojectErrorException::class); $service->linkWorkPackageToFile( - $this->mockServerBaseUri, - '1234567890', - '', - $this->clientId, - $this->clientSecret, 999999, 5503, 'logo.png', 'http://nextcloud.org', - 'admin' + 'testUser' ); }