Skip to content

Commit

Permalink
cleaner request configuration
Browse files Browse the repository at this point in the history
Signed-off-by: Maxence Lange <maxence@artificial-owl.com>
  • Loading branch information
ArtificialOwl committed Nov 16, 2020
1 parent 87a00d1 commit 80388d2
Show file tree
Hide file tree
Showing 10 changed files with 94 additions and 60 deletions.
8 changes: 4 additions & 4 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

43 changes: 24 additions & 19 deletions lib/Command/CirclesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,7 @@

namespace OCA\Circles\Command;

use daita\MySmallPhpTools\Exceptions\RequestContentException;
use daita\MySmallPhpTools\Exceptions\RequestNetworkException;
use daita\MySmallPhpTools\Exceptions\RequestResultSizeException;
use daita\MySmallPhpTools\Exceptions\RequestServerException;
use daita\MySmallPhpTools\Model\Nextcloud\NC19Request;
use daita\MySmallPhpTools\Model\Request;
use daita\MySmallPhpTools\Traits\Nextcloud\TNC19Request;
Expand Down Expand Up @@ -110,7 +107,7 @@ protected function configure() {
$this->setName('circles:test')
->setDescription('testing some features')
->addOption('delay', 'd', InputOption::VALUE_REQUIRED, 'delay before checking result')
->addOption('url', '', InputOption::VALUE_REQUIRED, 'specify a source url');
->addOption('url', '', InputOption::VALUE_REQUIRED, 'specify a source url', '');
}


Expand All @@ -126,12 +123,19 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$this->delay = (int)$input->getOption('delay');
}

// $url = $input->getOption('url');
if (!$this->testLocalAddress($output)) {
$this->configService->setAppValue(ConfigService::TEST_NC_BASE, '');
$this->configService->setAppValue(ConfigService::TEST_NC_BASE, $input->getOption('url'));

if (!$this->testRequest($output, 'GET', 'core.CSRFToken.index')) {
return 0;
}

$instances = array_merge($this->globalScaleService->getInstances(true));
if (!$this->testRequest(
$output, 'POST', 'circles.GlobalScale.asyncBroadcast',
['token' => 'test-dummy-token']
)) {
return 0;
}

$test = new GSEvent(GSEvent::TEST, true, true);
$test->setAsync(true);
Expand All @@ -144,6 +148,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$wrappers = $this->gsUpstreamService->getEventsByToken($token);

$result = [];
$instances = array_merge($this->globalScaleService->getInstances(true));
foreach ($wrappers as $wrapper) {
$result[$wrapper->getInstance()] = $wrapper->getEvent();
}
Expand All @@ -159,33 +164,33 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
}

$this->configService->setAppValue(ConfigService::TEST_NC_BASE, '');

return 0;
}


/**
* @param OutputInterface $output
* @param OutputInterface $o
* @param string $type
* @param string $route
* @param array $args
*
* @return bool
* @throws RequestContentException
* @throws RequestNetworkException
* @throws RequestResultSizeException
* @throws RequestServerException
*/
private function testLocalAddress(OutputInterface $output): bool {
$absolute = $this->urlGenerator->linkToRouteAbsolute('core.CSRFToken.index');
$output->write('- Simple request on ' . $absolute . ': ');

$request = new NC19Request('', Request::TYPE_GET);
$this->configService->configureRequest($request);
$request->setAddressFromUrl($absolute);
private function testRequest(OutputInterface $o, string $type, string $route, array $args = []): bool {
$request = new NC19Request('', Request::type($type));
$this->configService->configureRequest($request, $route, $args);

$o->write('- ' . $type . ' request on ' . $request->getCompleteUrl() . ': ');
$this->doRequest($request);

$color = 'error';
if ($request->getResultCode() === 200) {
$color = 'info';
}
$output->writeln('<' . $color . '>' . $request->getResultCode() . '</' . $color . '>');
$o->writeln('<' . $color . '>' . $request->getResultCode() . '</' . $color . '>');

if ($request->getResultCode() === 200) {
return true;
Expand Down
7 changes: 3 additions & 4 deletions lib/Command/MembersCreate.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
use daita\MySmallPhpTools\Model\Nextcloud\NC19Request;
use daita\MySmallPhpTools\Model\Request;
use daita\MySmallPhpTools\Traits\Nextcloud\TNC19Request;
use daita\MySmallPhpTools\Traits\TRequest;
use Exception;
use OC\Core\Command\Base;
use OC\User\NoUserException;
Expand Down Expand Up @@ -176,11 +175,11 @@ private function findUserFromLookup(string $search, string &$instance = ''): str
return '';
}

$request = new NC19Request('/users', Request::TYPE_GET);
$request = new NC19Request(ConfigService::GS_LOOKUP_USERS, Request::TYPE_GET);
$this->configService->configureRequest($request);
$request->setProtocols(['https', 'http']);
$request->addData('search', $search);
$request->setAddressFromUrl($lookup);
$request->basedOnUrl($lookup);
$request->addParam('search', $search);

try {
$users = $this->retrieveJson($request);
Expand Down
10 changes: 5 additions & 5 deletions lib/Cron/Maintenance.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,8 @@

use OC\BackgroundJob\TimedJob;
use OCA\Circles\AppInfo\Application;
use OCA\Circles\Exceptions\GSStatusException;
use OCA\Circles\Service\CirclesService;
use OCA\Circles\Service\CleanService;
use OCA\Circles\Service\GSUpstreamService;
use OCA\Circles\Service\MembersService;
use OCA\Circles\Service\ConfigService;
use OCP\AppFramework\QueryException;


Expand Down Expand Up @@ -66,8 +63,11 @@ protected function run($argument) {
$c = $app->getContainer();

/** @var CleanService $cleanService */
$cleanService = \OC::$server->query(CleanService::class);
$cleanService = $c->query(CleanService::class);
$cleanService->clean();

$configService = $c->query(ConfigService::class);
$configService->setAppValue(ConfigService::TEST_NC_BASE, '');
}

}
Expand Down
6 changes: 3 additions & 3 deletions lib/Search/GlobalScaleUsers.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,11 @@ public function search($search) {
return [];
}

$request = new NC19Request('/users', Request::TYPE_GET);
$request = new NC19Request(ConfigService::GS_LOOKUP_USERS, Request::TYPE_GET);
$this->configService->configureRequest($request);
$request->setProtocols(['https', 'http']);
$request->addData('search', $search);
$request->setAddressFromUrl($lookup);
$request->basedOnUrl($lookup);
$request->addParam('search', $search);

try {
$users = $this->retrieveJson($request);
Expand Down
43 changes: 41 additions & 2 deletions lib/Service/ConfigService.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
use OCA\Circles\Model\Circle;
use OCP\IConfig;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\PreConditionNotMetException;
use OCP\Util;

Expand All @@ -57,13 +58,16 @@ class ConfigService {
const CIRCLES_TEST_ASYNC_INIT = 'test_async_init';
const CIRCLES_TEST_ASYNC_HAND = 'test_async_hand';
const CIRCLES_TEST_ASYNC_COUNT = 'test_async_count';
const FORCE_NC_BASE = 'force_nc_base';
const TEST_NC_BASE = 'test_nc_base';

const GS_ENABLED = 'enabled';
const GS_MODE = 'mode';
const GS_KEY = 'key';
const GS_LOOKUP = 'lookup';

const GS_LOOKUP_INSTANCES = '/instances';
const GS_LOOKUP_USERS = '/users';


private $defaults = [
Expand All @@ -82,6 +86,7 @@ class ConfigService {
self::CIRCLES_NON_SSL_LOCAL => '0',
self::CIRCLES_SELF_SIGNED => '0',
self::LOCAL_CLOUD_ID => '',
self::FORCE_NC_BASE => '',
self::CIRCLES_ACTIVITY_ON_CREATION => '1',
self::CIRCLES_SKIP_INVITATION_STEP => '0',
self::CIRCLES_SEARCH_FROM_COLLABORATOR => '0'
Expand All @@ -99,6 +104,9 @@ class ConfigService {
/** @var IRequest */
private $request;

/** @var IURLGenerator */
private $urlGenerator;

/** @var MiscService */
private $miscService;

Expand All @@ -124,15 +132,18 @@ class ConfigService {
* @param IConfig $config
* @param IRequest $request
* @param string $userId
* @param IURLGenerator $urlGenerator
* @param MiscService $miscService
*/
public function __construct(
$appName, IConfig $config, IRequest $request, $userId, MiscService $miscService
$appName, IConfig $config, IRequest $request, $userId, IURLGenerator $urlGenerator,
MiscService $miscService
) {
$this->appName = $appName;
$this->config = $config;
$this->request = $request;
$this->userId = $userId;
$this->urlGenerator = $urlGenerator;
$this->miscService = $miscService;
}

Expand Down Expand Up @@ -551,14 +562,42 @@ public function getInstanceId() {

/**
* @param NC19Request $request
* @param string $routeName
* @param array $args
*/
public function configureRequest(NC19Request $request) {
public function configureRequest(NC19Request $request, string $routeName = '', array $args = []) {
$this->configureRequestAddress($request, $routeName, $args);

if ($this->getAppValue(ConfigService::CIRCLES_SELF_SIGNED) === '1') {
$request->setVerifyPeer(false);
}

$request->setLocalAddressAllowed(true);
}

/**
* @param NC19Request $request
* @param string $routeName
* @param array $args
*
* @return string
*/
private function configureRequestAddress(NC19Request $request, string $routeName, array $args = []) {
if ($routeName === '') {
return;
}

$ncBase = ($this->getAppValue(self::TEST_NC_BASE)) ?
$this->getAppValue(self::TEST_NC_BASE) : $this->getAppValue(self::FORCE_NC_BASE);

if ($ncBase !== '') {
$absolute = rtrim($ncBase, '/') . $this->urlGenerator->linkToRoute($routeName, $args);
} else {
$absolute = $this->urlGenerator->linkToRouteAbsolute($routeName, $args);
}

$request->basedOnUrl($absolute);
}

}

7 changes: 3 additions & 4 deletions lib/Service/GSUpstreamService.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,10 @@ public function broadcastEvent(GSEvent $event, string $instance, string $protoco
$protocols = [$protocol];
}

$request->setHost($instance);
$request->setProtocols($protocols);
$request->setDataSerialize($event);

$request->setAddress($instance);

$data = $this->retrieveJson($request);
$event->setResult(new SimpleDataStore($this->getArray('result', $data, [])));
}
Expand All @@ -232,14 +231,14 @@ public function confirmEvent(GSEvent &$event): void {
$path = $this->urlGenerator->linkToRoute('circles.GlobalScale.event');

$request = new NC19Request($path, Request::TYPE_POST);
$request->basedOnUrl($owner->getInstance());
$this->configService->configureRequest($request);

if ($this->get('REQUEST_SCHEME', $_SERVER) !== '') {
$request->setProtocols([$_SERVER['REQUEST_SCHEME']]);
} else {
$request->setProtocols(['https', 'http']);
}
$request->setAddressFromUrl($owner->getInstance());
$request->setDataSerialize($event);

$result = $this->retrieveJson($request);
Expand Down Expand Up @@ -427,7 +426,7 @@ public function confirmCircleStatus(Circle $circle): bool {
$notFound = false;
$foundWithNoOwner = false;
foreach ($this->globalScaleService->getInstances() as $instance) {
$request->setAddress($instance);
$request->setHost($instance);

try {
$result = $this->retrieveJson($request);
Expand Down
18 changes: 6 additions & 12 deletions lib/Service/GlobalScaleService.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,13 +137,10 @@ public function asyncBroadcast(GSEvent $event): string {
$wrapper = $this->gsEventsRequest->create($wrapper);
}

$absolute = $this->urlGenerator->linkToRouteAbsolute(
'circles.GlobalScale.asyncBroadcast', ['token' => $wrapper->getToken()]
);

$request = new NC19Request('', Request::TYPE_POST);
$this->configService->configureRequest($request);
$request->setAddressFromUrl($absolute);
$this->configService->configureRequest(
$request, 'circles.GlobalScale.asyncBroadcast', ['token' => $wrapper->getToken()]
);

try {
$this->doRequest($request);
Expand Down Expand Up @@ -225,13 +222,10 @@ public function getInstances(bool $all = false): array {
try {
$lookup = $this->configService->getGSStatus(ConfigService::GS_LOOKUP);
$request = new NC19Request(ConfigService::GS_LOOKUP_INSTANCES, Request::TYPE_POST);
$request->setProtocols(['https', 'http']);
$request->basedOnUrl($lookup);
$this->configService->configureRequest($request);

// $user = $this->getRandomUser();
// $data = $this->signer->sign('lookupserver', ['federationId' => $user->getCloudId()], $user);
$data = ['authKey' => $this->configService->getGSStatus(ConfigService::GS_KEY)];
$request->setData($data);
$request->setAddressFromUrl($lookup);
$request->addData('authKey', $this->configService->getGSStatus(ConfigService::GS_KEY));

try {
$instances = $this->retrieveJson($request);
Expand Down
8 changes: 4 additions & 4 deletions lib/Service/MembersService.php
Original file line number Diff line number Diff line change
Expand Up @@ -735,12 +735,12 @@ public function getUserDisplayName(string $ident, bool $fresh = false): string {
private function getGlobalScaleUserDisplayName(string $ident): string {
$lookup = $this->configService->getGSStatus(ConfigService::GS_LOOKUP);

$request = new NC19Request('/users', Request::TYPE_GET);
$request = new NC19Request(ConfigService::GS_LOOKUP_USERS, Request::TYPE_GET);
$this->configService->configureRequest($request);
$request->setProtocols(['https', 'http']);
$request->addData('search', $ident);
$request->addData('exact', '1');
$request->setAddressFromUrl($lookup);
$request->basedOnUrl($lookup);
$request->addParam('search', $ident);
$request->addParam('exact', '1');

try {
$users = $this->retrieveJson($request);
Expand Down
4 changes: 1 addition & 3 deletions lib/Service/SharingFrameService.php
Original file line number Diff line number Diff line change
Expand Up @@ -304,13 +304,11 @@ public function receiveFrame($token, $uniqueId, SharingFrame $frame) {
* @throws Exception
*/
public function initiateShare(string $circleUniqueId, string $frameUniqueId) {
$route = $this->urlGenerator->linkToRouteAbsolute('circles.Shares.initShareDelivery');
$request = new NC19Request('', Request::TYPE_POST);
$this->configService->configureRequest($request);
$request->setProtocols(['https', 'http']);
$this->configService->configureRequest($request, 'circles.Shares.initShareDelivery');
$request->addParam('circleId', $circleUniqueId);
$request->addParam('frameId', $frameUniqueId);
$request->setAddressFromUrl($route);

try {
$this->doRequest($request);
Expand Down

0 comments on commit 80388d2

Please sign in to comment.