diff options
author | sualko <klaus@jsxc.org> | 2022-01-04 15:24:54 +0300 |
---|---|---|
committer | sualko <klaus@jsxc.org> | 2022-01-04 15:35:37 +0300 |
commit | d6afb7e494e12c7779b7765c9514797ba0bec6c8 (patch) | |
tree | c7168a9a403c1a7ec5bbeaff03fbf316599229b0 | |
parent | 0a6e5710fd222ed3fc1f39e285e0c68c8f45832d (diff) |
feat: remove internal backend
we do not have the time anymore to maintaine it and fix
severe bugs
BREAKING CHANGE: the internal server is no longer available
Signed-off-by: sualko <klaus@jsxc.org>
69 files changed, 23 insertions, 6793 deletions
diff --git a/appinfo/app.php b/appinfo/app.php index e371aae..b97b168 100755 --- a/appinfo/app.php +++ b/appinfo/app.php @@ -95,12 +95,4 @@ if(!$apiSecret) { $config->setAppValue('ojsxc', Config::API_SECRET, $apiSecret); } -if (Application::getServerType() === Application::INTERNAL) { - Hooks::register(); -} - -if (!class_exists("\\Sabre\\Xml\\Version")) { - require_once __DIR__ . "/../vendor/autoload.php"; -} - ?> diff --git a/appinfo/info.xml b/appinfo/info.xml index 9306c7e..d30eef4 100755 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -53,9 +53,6 @@ <post-migration> <step>OCA\OJSXC\Migration\MigrateConfig</step> </post-migration> - <install> - <step>OCA\OJSXC\Migration\RefreshRoster</step> - </install> </repair-steps> <settings> diff --git a/appinfo/register_command.php b/appinfo/register_command.php deleted file mode 100644 index b376f7d..0000000 --- a/appinfo/register_command.php +++ /dev/null @@ -1,11 +0,0 @@ -<?php - -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\Command\RefreshRoster; -use OCA\OJSXC\Command\ServerSharing; - -$app = new Application(); - -/** @var Symfony\Component\Console\Application $application */ -$application->add($app->getContainer()->query(RefreshRoster::class)); -$application->add($app->getContainer()->query(ServerSharing::class)); diff --git a/appinfo/routes.php b/appinfo/routes.php index d276547..308fadd 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -8,8 +8,6 @@ $this->create('ojsxc_ajax_registerManagedServer', 'ajax/registerManagedServer.ph $application = new Application(); $application->registerRoutes($this, array( 'routes' => array( - array('name' => 'http_bind#index', 'url' => '/http-bind', 'verb' => 'POST'), - array('name' => 'settings#index', 'url' => '/settings', 'verb' => 'POST'), array('name' => 'settings#setAdmin', 'url' => '/settings/admin', 'verb' => 'POST'), array('name' => 'settings#setUser', 'url' => '/settings/user', 'verb' => 'POST'), diff --git a/composer.json b/composer.json index 543e412..331bfbd 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,5 @@ { "require": { - "sabre/xml": "^1.2", - "sabre/uri": "~1.0" }, "require-dev": { "phpunit/phpunit": "^8.5 || ^9.3", diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index 40e6e12..92d890b 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -3,42 +3,15 @@ namespace OCA\OJSXC\AppInfo; use OCA\OJSXC\Controller\ManagedServerController; -use OCA\OJSXC\Controller\SettingsController; -use OCA\OJSXC\Controller\ExternalApiController; -use OCA\OJSXC\Controller\JavascriptController; use OCA\OJSXC\Middleware\ExternalApiMiddleware; -use OCA\OJSXC\Command\RefreshRoster; -use OCA\OJSXC\Command\ServerSharing; -use OCA\OJSXC\Controller\HttpBindController; -use OCA\OJSXC\Db\IQRosterPushMapper; -use OCA\OJSXC\Db\MessageMapper; -use OCA\OJSXC\Db\PresenceMapper; -use OCA\OJSXC\Db\StanzaMapper; -use OCA\OJSXC\Migration\RefreshRoster as RefreshRosterMigration; -use OCA\OJSXC\NewContentContainer; -use OCA\OJSXC\RosterPush; -use OCA\OJSXC\StanzaHandlers\IQ; -use OCA\OJSXC\StanzaHandlers\Message; -use OCA\OJSXC\StanzaHandlers\Presence; -use OCA\OJSXC\StanzaLogger; -use OCA\OJSXC\RawRequest; -use OCA\OJSXC\DataRetriever; -use OCA\OJSXC\ILock; -use OCA\OJSXC\DbLock; -use OCA\OJSXC\MemLock; -use OCA\OJSXC\Hooks; -use OCA\OJSXC\UserManagerUserProvider; -use OCA\OJSXC\ContactsStoreUserProvider; use OCA\OJSXC\Config; -use OCA\OJSXC\IUserProvider; use OCP\IContainer; use OCP\IRequest; -use OCP\IUserBackend; -use OCA\OJSXC\Migration\MigrateConfig; use OCP\AppFramework\App; class Application extends App { + const NOT_CONFIGURED = 'not-configured'; const INTERNAL = 'internal'; const EXTERNAL = 'external'; const MANAGED = 'managed'; @@ -53,40 +26,6 @@ class Application extends App /** @var $config \OCP\IConfig */ $configManager = $container->query(\OCP\IConfig::class); - self::$config['polling'] = $configManager->getSystemValue( - 'ojsxc.polling', - ['sleep_time' => 1, 'max_cycles' => 10] - ); - - self::$config['polling']['timeout'] = self::$config['polling']['sleep_time'] * self::$config['polling']['max_cycles'] + 5; - - self::$config['use_memcache'] = $configManager->getSystemValue( - 'ojsxc.use_memcache', - ['locking' => false] - ); - - - /** - * Controllers - */ - $container->registerService('HttpBindController', function (IContainer $c) { - return new HttpBindController( - $c->query('AppName'), - $c->query('Request'), - $c->query('UserId'), - $c->query(StanzaMapper::class), - $c->query(IQ::class), - $c->query(Message::class), - $this->getLock(), - $c->query(Presence::class), - $c->query(PresenceMapper::class), - file_get_contents("php://input"), - self::$config['polling']['sleep_time'], - self::$config['polling']['max_cycles'], - $c->query(NewContentContainer::class), - $c->query(StanzaLogger::class) - ); - }); $container->registerService('ManagedServerController', function (IContainer $c) { return new ManagedServerController( @@ -106,7 +45,6 @@ class Application extends App /** * Middleware */ - $container->registerService('ExternalApiMiddleware', function (IContainer $c) { return new ExternalApiMiddleware( $c->query('Request'), @@ -115,182 +53,10 @@ class Application extends App ); }); $container->registerMiddleware('ExternalApiMiddleware'); - - /** - * Database Layer - */ - $container->registerService(MessageMapper::class, function (IContainer $c) use ($container) { - return new MessageMapper( - $container->getServer()->getDatabaseConnection(), - $c->query('Host'), - $c->query(StanzaLogger::class) - ); - }); - - $container->registerService(IQRosterPushMapper::class, function (IContainer $c) use ($container) { - return new IQRosterPushMapper( - $container->getServer()->getDatabaseConnection(), - $c->query('Host'), - $c->query(StanzaLogger::class) - ); - }); - - $container->registerService(StanzaMapper::class, function (IContainer $c) use ($container) { - return new StanzaMapper( - $container->getServer()->getDatabaseConnection(), - $c->query('Host'), - $c->query(StanzaLogger::class) - ); - }); - - $container->registerService(PresenceMapper::class, function (IContainer $c) use ($container) { - return new PresenceMapper( - $container->getServer()->getDatabaseConnection(), - $c->query('Host'), - $c->query('UserId'), - $c->query(MessageMapper::class), - $c->query(NewContentContainer::class), - self::$config['polling']['timeout'], - $c->query(IUserProvider::class) - ); - }); - - - /** - * XMPP Stanza Handlers - */ - $container->registerService(IQ::class, function (IContainer $c) { - return new IQ( - $c->query('UserId'), - $c->query('Host'), - $c->query(\OCP\IUserManager::class), - $c->query(\OCP\IConfig::class), - $c->query(IUserProvider::class) - ); - }); - - /** - * Config values - */ - $container->registerService('Host', function (IContainer $c) { - /** @var IRequest $request */ - $request = $c->query('Request'); - return preg_replace('/:\d+$/', '', $request->getServerHost()); - }); - - /** - * Helpers - */ - - $container->registerService(IUserProvider::class, function (IContainer $c) { - if (self::contactsStoreApiSupported()) { - return new ContactsStoreUserProvider( - $c->query(\OCP\Contacts\ContactsMenu\IContactsStore::class), - $c->query('ServerContainer')->getUserSession(), - $c->query('ServerContainer')->getUserManager(), - $c->query(\OCP\IGroupManager::class), - $c->query(\OCP\IConfig::class) - ); - } else { - return new UserManagerUserProvider( - $c->query('ServerContainer')->getUserManager() - ); - } - }); - } - - /** - * @return ILock - */ - private function getLock() - { - $c = $this->getContainer(); - if (self::$config['use_memcache']['locking'] === true) { - $cache = $c->getServer()->getMemCacheFactory(); - $version = \OC::$server->getSession()->get('OC_Version'); - if ($version[0] === 8 && $version[1] === 0) { - $c->getServer()->getLogger()->warning('OJSXC is configured to use memcache as backend for locking, but ownCloud version 8 doesn\'t suppor this.'); - } elseif ($cache->isAvailable()) { - $memcache = $cache->create('ojsxc'); - return new MemLock( - $c->query('UserId'), - $memcache - ); - } else { - $c->getServer()->getLogger()->warning('OJSXC is configured to use memcache as backend for locking, but no memcache is available.'); - } - } - - // default - return new DbLock( - $c->query('UserId'), - $c->query(\OCP\IConfig::class), - $c->getServer()->getDatabaseConnection() - ); - } - - - public static function sanitizeUserId($providedUid) - { - return str_replace( - [" ", "'", "@"], - ["_ojsxc_esc_space_", "_ojsxc_squote_space_", "_ojsxc_esc_at_"], - $providedUid - ); - } - - public static function deSanitize($providedUid) - { - return str_replace( - ["_ojsxc_esc_space_", "_ojsxc_squote_space_", "_ojsxc_esc_at_"], - [" ", "'", "@"], - $providedUid - ); - } - - - public static function convertToRealUID($providedUid) - { - $user = \OC::$server->getUserManager()->get($providedUid); - if (is_null($user)) { - return $providedUid; - } - - $backends = \OC::$server->getUserManager()->getBackends(); - foreach ($backends as $backend) { - if ($backend instanceof IUserBackend) { - $backendName = $backend->getBackendName(); - } else { - $backendName = get_class($backend); - } - if ($backendName === $user->getBackendClassName()) { - if (method_exists($backend, 'loginName2UserName')) { - $uid = $backend->loginName2UserName($providedUid); - if ($uid !== false) { - return $uid; - } - } - } - } - - return $providedUid; - } - - /** - * @return bool whether the ContactsStore API is enabled - */ - public static function contactsStoreApiSupported() - { - $version = \OCP\Util::getVersion(); - if ($version[0] >= 13 && \OC::$server->getConfig()->getAppValue('ojsxc', 'use_server_sharing_settings', 'no') === 'yes') { - // ContactsStore API is supported and feature is enabled - return true; - } - return false; } public static function getServerType() { - return \OC::$server->getConfig()->getAppValue('ojsxc', Config::XMPP_SERVER_TYPE, self::INTERNAL); + return \OC::$server->getConfig()->getAppValue('ojsxc', Config::XMPP_SERVER_TYPE, self::NOT_CONFIGURED); } } diff --git a/lib/Command/RefreshRoster.php b/lib/Command/RefreshRoster.php deleted file mode 100644 index b7eb769..0000000 --- a/lib/Command/RefreshRoster.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php - -namespace OCA\OJSXC\Command; - -use OCA\OJSXC\Db\PresenceMapper; -use OCA\OJSXC\RosterPush; -use OCP\IUserManager; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; - -class RefreshRoster extends Command -{ - - /** - * @var IUserManager - */ - private $userManager; - - /** - * @var RosterPush - */ - private $rosterPush; - - /** - * @var PresenceMapper - */ - private $presenceMapper; - - public function __construct( - IUserManager $userManager, - RosterPush $rosterPush, - PresenceMapper $presenceMapper - ) { - parent::__construct(); - $this->userManager = $userManager; - $this->rosterPush = $rosterPush; - $this->presenceMapper = $presenceMapper; - } - - protected function configure() - { - $this->setName('ojsxc:refresh-roster'); - $this->setDescription('Refresh the roster of all users'); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - $stats = $this->rosterPush->refreshRoster(); - $output->writeln("Updated " . $stats["updated"] . " roster items"); - $output->writeln("Removed " . $stats["removed"] . " roster items"); - - return 0; - } -} diff --git a/lib/Command/ServerSharing.php b/lib/Command/ServerSharing.php deleted file mode 100644 index c290581..0000000 --- a/lib/Command/ServerSharing.php +++ /dev/null @@ -1,73 +0,0 @@ -<?php - -namespace OCA\OJSXC\Command; - -use OCA\OJSXC\AppInfo\Application; -use OCP\IConfig; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; - -class ServerSharing extends Command -{ - - /** - * @var IConfig - */ - private $config; - - public function __construct( - IConfig $config - ) { - parent::__construct(); - $this->config = $config; - } - - protected function configure() - { - $this->setName('ojsxc:server_sharing'); - $this->setDescription('Use the Server Sharing settings https://github.com/jsxc/jsxc/wiki/Restrict-chatting-(Nextcloud-internal)'); - $this->addOption('enable'); - $this->addOption('disable'); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - if (Application::getServerType() !== 'internal') { - $output->write('This feature is only supported using the internal backend.', true); - return 0; - } - - $enable = $input->getOption('enable'); - $disable = $input->getOption('disable'); - - if (!$enable && !$disable) { - if ($this->config->getAppValue('ojsxc', 'use_server_sharing_settings', 'no') === 'yes') { - $state = 'enabled'; - } else { - $state = 'disabled'; - } - $output->write('This feature is currently ' . $state, true); - return 0; - } - - if ($enable === $disable) { - // if both enable and disable passed or none option - $output->write('Please provide only --enable or --disable', true); - return 1; - } - - - if ($enable) { - $this->config->setAppValue('ojsxc', 'use_server_sharing_settings', 'yes'); - $output->write('Successfully enabled.', true); - } - - if ($disable) { - $this->config->setAppValue('ojsxc', 'use_server_sharing_settings', 'no'); - $output->write('Successfully disabled.', true); - } - - return 0; - } -} diff --git a/lib/ContactsMenu/Providers/ChatProvider.php b/lib/ContactsMenu/Providers/ChatProvider.php index 4d7d130..ca835cb 100644 --- a/lib/ContactsMenu/Providers/ChatProvider.php +++ b/lib/ContactsMenu/Providers/ChatProvider.php @@ -55,11 +55,7 @@ class ChatProvider implements IProvider $xmppPreferMail = $xmppPreferMail === true || $xmppPreferMail === 'true'; $serverType = Application::getServerType(); - if ($serverType === Application::INTERNAL) { - $domain = \OC::$server->getRequest()->getServerHost(); - } else { - $domain = trim($config->getAppValue('ojsxc', 'xmppDomain')); - } + $domain = trim($config->getAppValue('ojsxc', 'xmppDomain')); $localIm = null; diff --git a/lib/ContactsStoreUserProvider.php b/lib/ContactsStoreUserProvider.php deleted file mode 100644 index 0da3de8..0000000 --- a/lib/ContactsStoreUserProvider.php +++ /dev/null @@ -1,127 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -use OCP\IConfig; -use OCP\IGroup; -use OCP\IGroupManager; -use OCP\IUserManager; -use OCP\IUserSession; - -class ContactsStoreUserProvider implements IUserProvider -{ - - /** - * @var \OCP\Contacts\ContactsMenu\IContactsStore - */ - private $contactsStore; - - /** - * @var User[] $cache - */ - private static $cache = null; - - /** - * @var IUserSession - */ - private $userSession; - - /** - * @var IUserManager - */ - private $userManager; - - /** - * @var IGroupManager - */ - private $groupManager; - - /** - * @var IConfig - */ - private $config; - - public function __construct($contactsStore, IUserSession $userSession, IUserManager $userManager, IGroupManager $groupManager, IConfig $config) - { - $this->contactsStore = $contactsStore; - $this->userSession = $userSession; - $this->userManager = $userManager; - $this->groupManager = $groupManager; - $this->config = $config; - } - - public function getAllUsers() - { - if (is_null(self::$cache)) { - $result = []; - $contacts = $this->contactsStore->getContacts($this->userSession->getUser(), ''); - foreach ($contacts as $contact) { - $uid = $contact->getProperty('UID'); - $user = $this->userManager->get($uid); - if ($contact->getProperty('isLocalSystemBook') - && !$this->isUserExcluded($uid) - && !is_null($user) - && $user->isEnabled()) { - $result[] = new User($uid, $contact->getFullName(), $contact); - } - } - self::$cache = $result; - } - - return self::$cache; - } - - public function hasUser(User $user) - { - return !is_null($this->contactsStore->findOne($this->userSession->getUser(), 0, $user->getUid())); - } - - public function hasUserByUID($uid) - { - return !is_null($this->contactsStore->findOne($this->userSession->getUser(), 0, $uid)); - } - - public function getAllUsersForUser(User $user) - { - return $this->getAllUsersForUserByUID($user->getUid()); - } - - public function getAllUsersForUserByUID($uid) - { - $result = []; - $contacts = $this->contactsStore->getContacts($this->userManager->get($uid), ''); - foreach ($contacts as $contact) { - if ($contact->getProperty('isLocalSystemBook')) { - $result[] = new User($contact->getProperty('UID'), $contact->getFullName(), $contact); - } - } - return $result; - } - - public function hasUserForUser(User $user1, User $user2) - { - return !is_null($this->contactsStore->findOne($this->userManager->get($user1->getUid()), 0, $user2->getUid())); - } - - public function hasUserForUserByUID($uid1, $uid2) - { - return !is_null($this->contactsStore->findOne($this->userManager->get($uid1), 0, $uid2)); - } - - public function isUserExcluded($userId) - { - if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') { - $user = $this->userManager->get($userId); - $user_groups = $this->groupManager->getUserGroupIds($user); - $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); - $decodedExcludeGroups = json_decode($excludedGroups, true); - $excludeGroupsList = ($decodedExcludeGroups !== null) ? $decodedExcludeGroups : []; - - if (count(array_intersect($excludeGroupsList, $user_groups)) !== 0) { - // a group of the current user is excluded -> filter all local users - return true; - } - } - return false; - } -} diff --git a/lib/Controller/HttpBindController.php b/lib/Controller/HttpBindController.php deleted file mode 100644 index c010db7..0000000 --- a/lib/Controller/HttpBindController.php +++ /dev/null @@ -1,255 +0,0 @@ -<?php - -namespace OCA\OJSXC\Controller; - -use OCA\OJSXC\Db\Presence; -use OCA\OJSXC\Db\PresenceMapper; -use OCA\OJSXC\Db\StanzaMapper; -use OCA\OJSXC\Exceptions\TerminateException; -use OCA\OJSXC\Http\XMPPResponse; -use OCA\OJSXC\ILock; -use OCA\OJSXC\NewContentContainer; -use OCA\OJSXC\StanzaHandlers\IQ; -use OCA\OJSXC\StanzaHandlers\Message; -use OCA\OJSXC\StanzaHandlers\Presence as PresenceHandler; -use OCA\OJSXC\StanzaLogger; -use OCP\AppFramework\Controller; -use OCP\AppFramework\Db\DoesNotExistException; -use OCP\IRequest; -use Sabre\Xml\Reader; -use Sabre\Xml\LibXMLException; - -/** - * Class HttpBindController - * - * @package OCA\OJSXC\Controller - */ -class HttpBindController extends Controller -{ - const MESSAGE = 0; - const IQ = 1; - const PRESENCE = 2; - const BODY = 2; - - - /** - * @var string $userId - */ - private $userId; - - /** - * @var StanzaMapper OCA\OJSXC\Db\StanzaMapper - */ - private $stanzaMapper; - - /** - * @var XMPPResponse - */ - private $response; - - /** - * @var IQ - */ - private $iqHandler; - - /** - * @var Message - */ - private $messageHandler; - - /** @var string */ - private $body; - - /** - * @var int SleepTime - */ - private $sleepTime; - - /** - * @var int - */ - private $maxCicles; - - /** - * @var ILock - */ - private $lock; - - /** - * @var PresenceHandler $presenceHandler - */ - private $presenceHandler; - - /** - * @var PresenceMapper $presenceMapper - */ - private $presenceMapper; - - /** - * @var NewContentContainer $newContentContainer - */ - private $newContentContainer; - - /** - * @var StanzaLogger - */ - private $stanzaLogger; - - /** - * HttpBindController constructor. - * - * @param string $appName - * @param IRequest $request - * @param string $userId - * @param StanzaMapper $stanzaMapper - * @param IQ $iqHandler - * @param Message $messageHandler - * @param ILock $lock - * @param PresenceHandler $presenceHandler - * @param PresenceMapper $presenceMapper - * @param string $body - * @param int $sleepTime - * @param int $maxCicles - * @param NewContentContainer $newContentContainer - */ - public function __construct( - $appName, - IRequest $request, - $userId, - StanzaMapper $stanzaMapper, - IQ $iqHandler, - Message $messageHandler, - ILock $lock, - PresenceHandler $presenceHandler, - PresenceMapper $presenceMapper, - $body, - $sleepTime, - $maxCicles, - NewContentContainer $newContentContainer, - StanzaLogger $stanzaLogger - ) { - parent::__construct($appName, $request); - $this->userId = $userId; - $this->stanzaMapper = $stanzaMapper; - $this->iqHandler = $iqHandler; - $this->messageHandler = $messageHandler; - $this->body = $body; - $this->sleepTime = $sleepTime; - $this->maxCicles = $maxCicles; - $this->response = new XMPPResponse($stanzaLogger); - $this->lock = $lock; - $this->presenceHandler = $presenceHandler; - $this->presenceMapper = $presenceMapper; - $this->newContentContainer = $newContentContainer; - $this->stanzaLogger = $stanzaLogger; - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @return XMPPResponse - */ - public function index() - { - $this->lock->setLock(); - $this->presenceMapper->updatePresence(); - $input = $this->body; - $longpoll = true; // set to false when the response should directly be returned and no polling should be done - $longpollStart = true; // start the first long poll cycle - try { - if (!empty($input)) { - // replace invalid XML by valid XML one - $input = str_replace("<vCard xmlns='vcard-temp'/>", "<vCard xmlns='jabber:vcard-temp'/>", $input); - $reader = new Reader(); - $reader->xml($input); - $reader->elementMap = [ - '{jabber:client}message' => 'Sabre\Xml\Element\KeyValue', - '{jabber:client}presence' => function (Reader $reader) { - return Presence::createFromXml($reader, $this->userId); - } - ]; - $parsedInput = null; - try { - $parsedInput = $reader->parse(); - } catch (LibXMLException $e) { - } - if (!is_null($parsedInput) - && is_array($parsedInput['value']) - && count($parsedInput['value']) > 0) { - $this->stanzaLogger->logRaw($input, StanzaLogger::RECEIVING); - - $stanzas = $parsedInput['value']; - foreach ($stanzas as $stanza) { - $stanzaType = $this->getStanzaType($stanza); - if ($stanzaType === self::MESSAGE) { - $this->messageHandler->handle($stanza); - } elseif ($stanzaType === self::IQ) { - $result = $this->iqHandler->handle($stanza); - if (!is_null($result)) { - $longpoll = false; - $this->response->write($result); - } - } elseif ($stanza['value'] instanceof Presence) { - $results = $this->presenceHandler->handle($stanza['value']); - if (!is_null($results) && is_array($results)) { - $longpoll = false; - $longpollStart = false; - foreach ($results as $r) { - $this->response->write($r); - } - } - } - } - } - } - } catch (TerminateException $e) { - $this->response->terminate(); - return $this->response; - } - - // Start long polling - $this->presenceMapper->setActive($this->userId); - if ($this->newContentContainer->getCount() > 0) { - foreach ($this->newContentContainer->getStanzas() as $stanz) { - $this->response->write($stanz); - } - $longpoll = false; // make sure we poll only one times for the fastes reponse - } - $recordFound = false; - $cicles = 0; - if ($longpollStart) { - do { - try { - $cicles++; - $stanzas = $this->stanzaMapper->findByTo($this->userId); - foreach ($stanzas as $stanz) { - $this->response->write($stanz); - } - $recordFound = true; - } catch (DoesNotExistException $e) { - sleep($this->sleepTime); - $recordFound = false; - } - } while ($recordFound === false && $cicles < $this->maxCicles && $longpoll && $this->lock->stillLocked()); - } - - return $this->response; - } - - /** - * @param $stanza - * @return int|null - * @codeCoverageIgnore - */ - private function getStanzaType($stanza) - { - switch ($stanza['name']) { - case '{jabber:client}message': - return self::MESSAGE; - case '{jabber:client}iq': - return self::IQ; - case '{jabber:client}presence': - return self::PRESENCE; - } - } -} diff --git a/lib/Controller/JavascriptController.php b/lib/Controller/JavascriptController.php index 877857e..d1b2276 100644 --- a/lib/Controller/JavascriptController.php +++ b/lib/Controller/JavascriptController.php @@ -26,7 +26,7 @@ class JavascriptController extends Controller */ public function generalConfig() { - $serverType = $this->config->getAppValue(Config::XMPP_SERVER_TYPE, Application::INTERNAL); + $serverType = $this->config->getAppValue(Config::XMPP_SERVER_TYPE, Application::NOT_CONFIGURED); $startMinimized = $this->config->getBooleanAppValue(Config::XMPP_START_MINIMIZED); $loginFormEnable = $this->config->getBooleanAppValue(Config::XMPP_START_ON_LOGIN, true); diff --git a/lib/Controller/SettingsController.php b/lib/Controller/SettingsController.php index a43ae60..c4b416c 100644 --- a/lib/Controller/SettingsController.php +++ b/lib/Controller/SettingsController.php @@ -51,34 +51,21 @@ class SettingsController extends Controller $currentUID = $currentUser->getUID(); $config = $this->config; - $serverType = $config->getAppValue(Config::XMPP_SERVER_TYPE, Application::INTERNAL); - - $data = [ - 'disabled' => !$config->getBooleanAppValue(Config::XMPP_START_ON_LOGIN, true), - ]; - - if ($serverType === Application::INTERNAL) { - $serverHost = $this->request->getServerHost(); - $domain = parse_url($serverHost, PHP_URL_HOST); - - if ($domain === null) { - $domain = !empty($serverHost) ? $serverHost : 'jsxc.nextcloud'; - } - - $data['xmpp'] = [ - 'defaultDomain' => $domain, - 'url' => \OC::$server->getURLGenerator()->linkToRouteAbsolute('ojsxc.http_bind.index'), - 'node' => $currentUID, - 'domain' => $domain, - 'resource' => 'internal' - ]; + $serverType = $config->getAppValue(Config::XMPP_SERVER_TYPE, Application::NOT_CONFIGURED); + if ($serverType !== Application::EXTERNAL && $serverType !== Application::MANAGED) { return [ - 'result' => 'success', - 'data' => $data, + 'result' => SUCCESS, + 'data' => [ + 'disabled' => true, + ], ]; } + $data = [ + 'disabled' => !$config->getBooleanAppValue(Config::XMPP_START_ON_LOGIN, true), + ]; + $data ['xmpp'] = [ 'url' => $config->getAppValue(Config::XMPP_URL), 'domain' => $config->getAppValue(Config::XMPP_DOMAIN), @@ -295,7 +282,7 @@ class SettingsController extends Controller */ public function getServerType() { - return ["serverType" => $this->config->getAppValue(Config::XMPP_SERVER_TYPE, Application::INTERNAL)]; + return ["serverType" => $this->config->getAppValue(Config::XMPP_SERVER_TYPE, Application::NOT_CONFIGURED)]; } private function getCurrentUser() diff --git a/lib/Db/IQNotImplemented.php b/lib/Db/IQNotImplemented.php deleted file mode 100644 index 1683b6b..0000000 --- a/lib/Db/IQNotImplemented.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php - -namespace OCA\OJSXC\Db; - -use Sabre\Xml\Writer; -use Sabre\Xml\XmlSerializable; - -/** - * This is an entity used by the IqHandler, but not stored/mapped in the database. - * Class IQRoster - * - * @package OCA\OJSXC\Db - * @method void setQid($qid) - * @method string getQid() - */ -class IQNotImplemented extends Stanza implements XmlSerializable -{ - - /** - * @var string $qid - */ - public $qid; - - public function xmlSerialize(Writer $writer) - { - $writer->write([ - [ - 'name' => 'iq', - 'attributes' => [ - 'type' => 'error', - 'id' => $this->qid - ], - 'value' => [[ - 'name' => 'error', - 'attributes' => [ - 'type' => 'cancel', - ], - 'value' => [ - 'name' => 'feature-not-implemented', - 'attributes' => [ - 'xmlns' => 'urn:ietf:params:xml:ns:xmpp-stanzas' - ] - ] - ]] - ] - ]); - } -} diff --git a/lib/Db/IQRoster.php b/lib/Db/IQRoster.php deleted file mode 100644 index 4c6e8c6..0000000 --- a/lib/Db/IQRoster.php +++ /dev/null @@ -1,77 +0,0 @@ -<?php - -namespace OCA\OJSXC\Db; - -use Sabre\Xml\Reader; -use Sabre\Xml\Writer; -use Sabre\Xml\XmlDeserializable; -use Sabre\Xml\XmlSerializable; - -/** - * This is an entity used by the IqHandler, but not stored/mapped in the database. - * Class IQRoster - * - * @package OCA\OJSXC\Db - * @method void setType(string $type) - * @method void setQid(string $qid) - * @method void setItems(array $items) - * @method string getType() - * @method string getQid() - * @method array getItems() - */ -class IQRoster extends Stanza implements XmlSerializable -{ - - /** - * @var string $type - */ - public $type; - - /** - * @var string $qid - */ - public $qid; - - /** - * @var array $items - */ - public $items; - - public function xmlSerialize(Writer $writer) - { - $writer->write([ - [ - 'name' => 'iq', - 'attributes' => [ - 'to' => $this->to, - 'type' => $this->type, - 'id' => $this->qid - ], - 'value' => [[ - 'name' => 'query', - 'attributes' => [ - 'xmlns' => 'jabber:iq:roster', - ], - 'value' => $this->items - ]] - ] - ]); - } - - /** - * @param string $jid - * @param string $name - */ - public function addItem($jid, $name) - { - $this->items[] = [ - "name" => "item", - "attributes" => [ - "jid" => $jid, - "name" => $name, - "subscription" => "both" - ], - "value" => '' - ]; - } -} diff --git a/lib/Db/IQRosterPush.php b/lib/Db/IQRosterPush.php deleted file mode 100644 index def5485..0000000 --- a/lib/Db/IQRosterPush.php +++ /dev/null @@ -1,90 +0,0 @@ -<?php - -namespace OCA\OJSXC\Db; - -use OCA\OJSXC\AppInfo\Application; -use Sabre\Xml\Reader; -use Sabre\Xml\Writer; -use Sabre\Xml\XmlDeserializable; -use Sabre\Xml\XmlSerializable; - -/** - * This entity represents a roster push. - * @see https://tools.ietf.org/html/rfc6121#section-2.1.6 - * Class IQRosterPush - * - * @package OCA\OJSXC\Db - * @method void setName($name) - * @method void setSubscription($subscription) - * @method string getJid() - * @method string getName() - * @method string getSubscription() - */ -class IQRosterPush extends Stanza implements XmlSerializable -{ - - /** - * @var string jid of the user, when inserting this into the DB, only userid - * is needed. - */ - public $jid; - - /** - * @var string displayname of the user - */ - public $name; - - /** - * @var string subscription type. Both and remove are used. - */ - public $subscription; - - /** - * Sets the to user as a `user`. - * - * @see setFullJid - * @param $userId - * @param null $host_and_or_resource - */ - public function setJid($userId, $host_and_or_resource = null) - { - $this->jid = Application::sanitizeUserId($userId); - if (!is_null($host_and_or_resource)) { - $this->jid .= '@' . $host_and_or_resource; - } - } - - public function xmlSerialize(Writer $writer) - { - $item = [ - "name" => "item", - "attributes" => [ - "jid" => $this->jid, - "subscription" => $this->subscription - ], - "value" => '' - ]; - - if ($this->name !== null) { - $item['attributes']['name'] = $this->name; - } - - $writer->write([ - [ - 'name' => 'iq', - 'attributes' => [ - 'to' => $this->to, - 'type' => 'set', - 'id' => $this->attrId !== null ? $this->attrId : uniqid(), - ], - 'value' => [[ - 'name' => 'query', - 'attributes' => [ - 'xmlns' => 'jabber:iq:roster', - ], - 'value' => $item, - ]] - ] - ]); - } -} diff --git a/lib/Db/IQRosterPushMapper.php b/lib/Db/IQRosterPushMapper.php deleted file mode 100644 index 1b72ef4..0000000 --- a/lib/Db/IQRosterPushMapper.php +++ /dev/null @@ -1,12 +0,0 @@ -<?php - -namespace OCA\OJSXC\Db; - -/** - * Class IQRosterPushMapper - * - * @package OCA\OJSXC\Db - */ -class IQRosterPushMapper extends StanzaMapper -{ -} diff --git a/lib/Db/Message.php b/lib/Db/Message.php deleted file mode 100644 index c9ec997..0000000 --- a/lib/Db/Message.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php - -namespace OCA\OJSXC\Db; - -use Sabre\Xml\Reader; -use Sabre\Xml\Writer; -use Sabre\Xml\XmlSerializable; - -/** - * Class Message - * - * @package OCA\OJSXC\Db - * @method void setType($type) - * @method void setValue(array $value) - * @method string getType() - * @method array getValue() - */ -class Message extends Stanza implements XmlSerializable -{ - - /** - * @var string $type - */ - public $type; - - /** - * @var array $value - */ - public $value; - - public function xmlSerialize(Writer $writer) - { - $writer->write([ - [ - 'name' => 'message', - 'attributes' => [ - 'to' => $this->to, - 'from' => $this->from, - 'type' => $this->type, - 'xmlns' => 'jabber:client', - 'id' => $this->attrId !== null ? $this->attrId : uniqid(), - ], - 'value' => $this->value - ] - ]); - } -} diff --git a/lib/Db/MessageMapper.php b/lib/Db/MessageMapper.php deleted file mode 100644 index c3f2804..0000000 --- a/lib/Db/MessageMapper.php +++ /dev/null @@ -1,12 +0,0 @@ -<?php - -namespace OCA\OJSXC\Db; - -/** - * Class MessageMapper - * - * @package OCA\OJSXC\Db - */ -class MessageMapper extends StanzaMapper -{ -} diff --git a/lib/Db/Presence.php b/lib/Db/Presence.php deleted file mode 100644 index 08886b6..0000000 --- a/lib/Db/Presence.php +++ /dev/null @@ -1,142 +0,0 @@ -<?php - -namespace OCA\OJSXC\Db; - -use Sabre\Xml\XmlSerializable; -use Sabre\Xml\XmlDeserializable; -use Sabre\Xml\Writer; -use Sabre\Xml\Reader; -use Sabre\Xml\Element\Base; -use Sabre\Xml\Element\keyValue; - -/** - * Class Presence - * - * This class is used for input AND output! It can be inserted into the ojsxc_presence table - * and the ojsxc_stanza table. Use the presenceMapper and Stanzamapper respective. - * - * @package OCA\OJSXC\Db - * @method void setUserid($userid) - * @method void setPresence($presence) - * @method void setLastActive($lastActive) - * @method string getUserid() - * @method string getPresence() - * @method int getLastActive() - */ -class Presence extends Stanza implements XmlSerializable, XmlDeserializable -{ - - /** - * @var string $userid - */ - public $userid; - - /** - * @var string $presence - */ - public $presence; - - /** - * @var int last_active - */ - public $lastActive; - - public function __construct() - { - $this->addType('lastActive', 'integer'); - } - - /** - * @param Writer $writer - */ - public function xmlSerialize(Writer $writer) - { - if ($this->presence === 'online' || $this->presence === '') { - $writer->write([ - [ - 'name' => 'presence', - 'attributes' => [ - 'xmlns' => 'jabber:client', - 'from' => $this->from, - 'to' => $this->to, - ], - 'value' => null - ] - ]); - } elseif ($this->presence === 'unavailable') { - $writer->write([ - [ - 'name' => 'presence', - 'attributes' => [ - 'type' => 'unavailable', - 'from' => $this->from, - 'to' => $this->to, - 'xmlns' => 'jabber:client', - ], - 'value' => null - ] - ]); - } else { - $writer->write([ - [ - 'name' => 'presence', - 'attributes' => [ - 'from' => $this->from, - 'to' => $this->to, - 'xmlns' => 'jabber:client', - ], - 'value' => [ [ - 'name' => 'show', - 'attributes' => [], - 'value' => $this->presence - ]] - ] - ]); - } - } - - /** - * @brief Factory function to create an instance of this Entity from a xml string - * which was given to a Reader object. - * @param Reader $reader - * @param string $userId - * @return Presence - */ - public static function createFromXml(Reader $reader, $userId) - { - $newElement = self::xmlDeserialize($reader); - $newElement->setUserid($userId); - return $newElement; - } - - /** - * @param Reader $reader - * @return Presence - */ - public static function xmlDeserialize(Reader $reader) - { - $newElement = new self(); - $attributes = $reader->parseAttributes(); - $children = $reader->parseInnerTree(); - if (key_exists('type', $attributes) && $attributes['type'] === 'unavailable') { - $newElement->presence = 'unavailable'; - } elseif (is_null($children)) { - // this match elements which don't have children -> online - $newElement->presence = 'online'; - } else { - // this match elements who does have children but no "show" element -> online - $foundShow = false; - foreach ($children as $child) { - if ($child['name'] === '{jabber:client}show') { - $newElement->presence = $child['value']; - $foundShow = true; - } - } - if (!$foundShow) { - $newElement->presence = 'online'; - } - } - $newElement->lastActive = time(); - return $newElement; - } -} diff --git a/lib/Db/PresenceMapper.php b/lib/Db/PresenceMapper.php deleted file mode 100644 index ea0af41..0000000 --- a/lib/Db/PresenceMapper.php +++ /dev/null @@ -1,235 +0,0 @@ -<?php - -namespace OCA\OJSXC\Db; - -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\Db\Presence as PresenceEntity; -use OCA\OJSXC\IUserProvider; -use OCA\OJSXC\NewContentContainer; -use OCP\AppFramework\Db\Mapper; -use OCP\IDBConnection; -use Sabre\Xml\Service; -use OCP\IDb; - -/** - * Class PresenceMapper - * - * @package OCA\OJSXC\Db - */ -class PresenceMapper extends Mapper -{ - - /** - * @var bool this value indicates if we already have updated the presence - * of other users so we don't do this more than 1 one times per request. - * TODO We could introduce a variable in the DB which indicates this already - * TODO happened x minutes ago so we shouldn't do this every request. - */ - private static $updatedPresence = false; - - /** - * @var array of userid's which are connected. - */ - private static $connectedUsers = []; - - /** - * @var bool indicates wherever we already fetched the connected users - */ - private static $fetchedConnectedUsers = false; - - /** - * @var MessageMapper $messageMapper - */ - private $messageMapper; - - /** - * @var NewContentContainer $newContentContainer - */ - private $newContentContainer; - - /** - * @var int $timeout - */ - private $timeout; - - /** - * @var string the current host which the user is connected to - */ - private $host; - - /** - * @var null|string the userId of the current user - */ - private $userId; - - - /** - * @var IUserProvider - */ - private $userProvider; - - /** - * PresenceMapper constructor. - * - * @param IDBConnection $db - * @param string $host - * @param null|string $userId - * @param MessageMapper $messageMapper - * @param NewContentContainer $newContentContainer - * @param int $timeout - * @param IUserProvider $userProvider - */ - public function __construct(IDBConnection $db, $host, $userId, MessageMapper $messageMapper, NewContentContainer $newContentContainer, $timeout, IUserProvider $userProvider) - { - parent::__construct($db, 'ojsxc_presence'); - $this->host = $host; - $this->userId = $userId; - $this->messageMapper = $messageMapper; - $this->newContentContainer = $newContentContainer; - $this->timeout = $timeout; - $this->userProvider = $userProvider; - } - - /** - * @brief This function sets or update the presence of a user. - * @param PresenceEntity $stanza - */ - public function setPresence(PresenceEntity $stanza) - { - $sql = "UPDATE `*PREFIX*ojsxc_presence` SET `presence`=?, `last_active`=? WHERE `userid` = ?"; - - $q = $this->db->prepare($sql); - $q->execute([$stanza->getPresence(), $stanza->getLastActive(), $stanza->getUserid()]); - - - if ($q->rowCount() === 0) { - $sql = "INSERT INTO `*PREFIX*ojsxc_presence` (`userid`, `presence`, `last_active`) VALUES(?,?,?)"; - $q = $this->db->prepare($sql); - $q->execute([$stanza->getUserid(), $stanza->getPresence(), $stanza->getLastActive()]); - } - } - - /** - * @brief this function will fetch all the presences of users except - * the current user. - * @return array - */ - public function getPresences() - { - $stmt = $this->execute("SELECT * FROM `*PREFIX*ojsxc_presence`"); - $results = []; - while ($row = $stmt->fetch()) { - $row['from'] = [$row['userid'], $this->host . '/internal']; - $row['to'] = [$this->userId, $this->host . '/internal']; - $results[] = $this->mapRowToEntity($row); - } - $stmt->closeCursor(); - - return $results; - } - - /** - * @brief fetch the users who are connected with the server. - * - online - * - chatty - * - away - * - extended away - * - do not disturb - * and return it as an array of the userids. - * @return array - */ - public function getConnectedUsers() - { - if (!self::$fetchedConnectedUsers) { - self::$fetchedConnectedUsers = true; - - $stmt = $this->execute("SELECT `userid` FROM `*PREFIX*ojsxc_presence` WHERE `presence` != 'unavailable' AND `userid` != ?", [$this->userId]); - $results = []; - while ($row = $stmt->fetch()) { - if (!$this->userProvider->hasUserByUID(Application::deSanitize($row['userid']))) { - continue; - } - $results[] = $row['userid']; - } - $stmt->closeCursor(); - - self::$connectedUsers = $results; - return $results; - } else { - return self::$connectedUsers; - } - } - - /** - * @brief updates the last_active label in the DB. - * @param the user to update the last_active field - */ - public function setActive($user) - { - // just do an update since we can assume the user is already online - // otherwise this wouldn't make sense - $sql = "UPDATE `*PREFIX*ojsxc_presence` SET `last_active`=? WHERE `userid` = ?"; - $q = $this->db->prepare($sql); - $q->execute([time(), $user]); - } - - - /** - * @brief this function will update the presence of users who doesn't - * contacted the server for $this->timeout seconds. - */ - public function updatePresence() - { - if (!self::$updatedPresence) { - self::$updatedPresence = true; - - $time = time() - $this->timeout; - - // first find all users who where offline for more than 30 seconds - $stmt = $this->execute( - "SELECT `userid` FROM `*PREFIX*ojsxc_presence` WHERE `presence` != 'unavailable' AND `userid` != ? AND `last_active` < ?", - [$this->userId, $time] - ); - - $inactiveUsers = []; - while ($row = $stmt->fetch()) { - $inactiveUsers[] = $row['userid']; - } - $stmt->closeCursor(); - - $this->execute("UPDATE `*PREFIX*ojsxc_presence` SET `presence` = 'unavailable' WHERE `presence` != 'unavailable' AND `userid` != ? AND `last_active` < ?", [$this->userId, $time]); - - // broadcast the new presence - $connectedUsers = $this->getConnectedUsers(); - - $onlineUsers = array_diff($connectedUsers, $inactiveUsers); // filter out the inactive users, since we use a cache mechanism - - foreach ($inactiveUsers as $inactiveUser) { - $presenceToSend = new PresenceEntity(); - $presenceToSend->setPresence('unavailable'); - $presenceToSend->setFrom($inactiveUser); - foreach ($onlineUsers as $user) { - // send to every online user (except the user who initiated the update) - $presenceToSend->setTo($user); - $this->messageMapper->insert($presenceToSend); - } - // and now send it to the user who initiated the update - $presenceToSend->setTo($this->userId, $this->host . '/internal'); - $presenceToSend->setFrom($inactiveUser, $this->host . '/internal'); - $this->newContentContainer->addStanza($presenceToSend); - } - } - } - - /** - * @brief Deletes the presence records of a user. - * @param string $user - */ - public function deletePresence($user) - { - $sql = "DELETE FROM `*PREFIX*ojsxc_presence` WHERE `userid` = ?"; - - $q = $this->db->prepare($sql); - $q->execute([$user]); - } -} diff --git a/lib/Db/README.md b/lib/Db/README.md deleted file mode 100644 index 8dea934..0000000 --- a/lib/Db/README.md +++ /dev/null @@ -1,26 +0,0 @@ -lib/db -=== - -This are the Entity and Mappers of the different stanza types. -The entities are used to: - - store them in the DB. (e.g. the Message entity, the Presence entity) - - to easily return them to the client via the polling system - (e.g. Message entity, Presence entity (these are stored inside the ojsxc_stanza table.) - - directly return them to te client (e.g. IQRoster entity) - - parse an incoming stanza to an object (This is currently only done for the - incoming Presence stanza.) - -The following mappers are used: - - StanzaMapper -> parent of all the other mappers - - MessageMapper -> used to store Message entities inside the longpolling table. - - PresenceMapper -> used to save, update and fetch presences of the users - - IQRoster doesn't have a mapper since this won't be saved in the DB. - - -# Important note on userids and jid's - -When users and Stanza's containing users are stored inside the database this must be done using the Nextcloud userid -and not using a jid! So at all times the user 'admin' must be stored as 'admin' and not as 'admin@localhost/internal' even -in the `to` and `from` parameters of raw xml stanzas. This to support multiple domain Nextcloud instances. -The userId's are escaped using the `OCA\OJSXC\AppInfo\Appplication::sanitizeUserId` function to support the XMPP standards. -When the userId is available inside the class the `OJSXC_UserId` paramter of `OCA\OJSXC\AppInfo\Appplication` must be used.
\ No newline at end of file diff --git a/lib/Db/Stanza.php b/lib/Db/Stanza.php deleted file mode 100644 index a3e5145..0000000 --- a/lib/Db/Stanza.php +++ /dev/null @@ -1,116 +0,0 @@ -<?php - -namespace OCA\OJSXC\Db; - -use OCA\OJSXC\AppInfo\Application; -use \OCP\AppFramework\Db\Entity; -use Sabre\Xml\Reader; -use Sabre\Xml\Writer; -use Sabre\Xml\XmlDeserializable; -use Sabre\Xml\XmlSerializable; - -/** - * Class Stanza - * @package OCA\OJSXC\Db - * @brief this class is used as the entity which is fetched from the stanza table OR extended by a specific stanza - * for inserting into the stanza table - * @method string getStanza() - * @method void setStanza($stanza) - * @method void setAttrId(string $id) - */ -class Stanza extends Entity implements XmlSerializable -{ - public function __construct($stanza = '') - { - $this->setStanza($stanza); - } - - /** - * @var string - */ - public $attrId; - - /** - * @var string $to The sanitized userId of the recipient of this stanza. - */ - public $to; - - /** - * @var string $from The sanitized userId of the sender of this stanza. - */ - public $from; - - /** - * @var string $to The userId (as stored in NC) of the recipient of this stanza. - */ - public $unSanitizedTo; - - /** - * @var string $from The userId (as stored in NC) of the sender of this stanza. - */ - public $unSanitizedFrom; - - /** - * @var string $stanza - */ - public $stanza; - - public function getUnSanitizedTo() - { - return $this->unSanitizedTo; - } - - /** - * Sets the to user as a `user`. - * - * @see setFullTo - * @param string $userId - * @param string $host_and_or_resource - */ - public function setTo($userId, ?string $host_and_or_resource = null) - { - if (is_array($userId)) { - // support mapFromRow - $host_and_or_resource = $userId[1]; - $userId = $userId[0]; - } - - $this->unSanitizedTo = $userId; - $this->to = Application::sanitizeUserId($userId); - if (!is_null($host_and_or_resource)) { - $this->to .= '@' . $host_and_or_resource; - } - } - - /** - * Sets the from user as a `user`. - * - * @see setFullFrom - * @param $userId - * @param string $host_and_or_resource - */ - public function setFrom($userId, ?string $host_and_or_resource = null) - { - if (is_array($userId)) { - // support mapFromRow - $host_and_or_resource = $userId[1]; - $userId = $userId[0]; - } - - $this->unSanitizedFrom = $userId; - $this->from = Application::sanitizeUserId($userId); - if (!is_null($host_and_or_resource)) { - $this->from .= '@' . $host_and_or_resource; - } - } - - public function getUnSanitizedFrom() - { - return $this->unSanitizedFrom; - } - - public function xmlSerialize(Writer $writer) - { - $writer->writeRaw($this->getStanza()); - } -} diff --git a/lib/Db/StanzaMapper.php b/lib/Db/StanzaMapper.php deleted file mode 100644 index 28b56f8..0000000 --- a/lib/Db/StanzaMapper.php +++ /dev/null @@ -1,95 +0,0 @@ -<?php - -namespace OCA\OJSXC\Db; - -use OCA\OJSXC\StanzaLogger; -use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; -use OCP\AppFramework\Db\Mapper; -use OCP\IDb; -use OCP\IDBConnection; -use Sabre\Xml\Writer; - -/** - * Class StanzaMapper - * - * @package OCA\OJSXC\Db - */ -class StanzaMapper extends Mapper -{ - private $host; - - /** - * @var StanzaLogger - */ - private $stanzaLogger; - - /** - * StanzaMapper constructor. - * - * @param IDBConnection $db - * @param string $host - */ - public function __construct(IDBConnection $db, $host, StanzaLogger $stanzaLogger) - { - parent::__construct($db, 'ojsxc_stanzas'); - $this->host = $host; - $this->stanzaLogger = $stanzaLogger; - } - - /** - * @param Entity $entity - * @return void - */ - public function insert(Entity $entity) - { - $writer = new Writer(); - $writer->openMemory(); - $writer->write($entity); - $xml = $writer->outputMemory(); - - $this->stanzaLogger->logRaw($xml, StanzaLogger::STORING); - - $sql = "INSERT INTO `*PREFIX*ojsxc_stanzas` (`to`, `from`, `stanza`) VALUES(?,?,?)"; - $q = $this->db->prepare($sql); - $q->execute([$entity->getUnSanitizedTo(), $entity->getUnSanitizedFrom(), $xml]); - } - - - /** - * @param string $to - * @return Stanza[] - * @throws DoesNotExistException - */ - public function findByTo($to) - { - $stmt = $this->execute("SELECT stanza, id FROM *PREFIX*ojsxc_stanzas WHERE `to`=?", [$to]); - $results = []; - while ($row = $stmt->fetch()) { - $row['stanza'] = preg_replace('/to="([^"]*)"/', "to=\"$1@" .$this->host ."/internal\"", $row['stanza']); - $row['stanza'] = preg_replace('/from="([^"]*)"/', "from=\"$1@" .$this->host ."/internal\"", $row['stanza']); - $row['stanza'] = preg_replace('/jid="([^"]*)"/', "jid=\"$1@" .$this->host ."\"", $row['stanza']); - $results[] = $this->mapRowToEntity($row); - } - $stmt->closeCursor(); - - if (count($results) === 0) { - throw new DoesNotExistException('Not Found'); - } - - foreach ($results as $result) { - $this->delete($result); - } - - return $results; - } - - /** - * @brief Deletes all stanzas addressed to a user. - * @param $uid - */ - public function deleteByTo($uid) - { - $this->execute("DELETE FROM *PREFIX*ojsxc_stanzas WHERE `to`=?", [$uid]); - } -} diff --git a/lib/DbLock.php b/lib/DbLock.php deleted file mode 100644 index 45a511c..0000000 --- a/lib/DbLock.php +++ /dev/null @@ -1,61 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -use OCP\IConfig; -use OCP\IDBConnection; - -/** - * Class DbLock - * - * @package OCA\OJSXC - */ -class DbLock implements ILock -{ - /** - * @var IConfig $config - */ - private $config; - - /** - * @var string $userId - */ - private $userId; - - /** - * @var string $pollingId - */ - private $pollingId; - - /** @var IDBConnection */ - private $con; - - /** - * DbLock constructor. - * - * @param string $userId - * @param IConfig $config - */ - public function __construct($userId, IConfig $config, IDBConnection $con) - { - $this->userId = $userId; - $this->config = $config; - $this->pollingId = microtime(); - $this->con = $con; - } - - public function setLock() - { - $this->config->setUserValue($this->userId, 'ojsxc', 'longpolling', $this->pollingId); - } - - /** - * @return bool - */ - public function stillLocked() - { - $storedPollingId = $this->config->getUserValue($this->userId, 'ojsxc', 'longpolling'); - - return $storedPollingId === $this->pollingId; - } -} diff --git a/lib/Hooks.php b/lib/Hooks.php deleted file mode 100644 index bde830c..0000000 --- a/lib/Hooks.php +++ /dev/null @@ -1,166 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\Db\PresenceMapper; -use OCA\OJSXC\Db\StanzaMapper; -use OCP\IGroup; -use OCP\IGroupManager; -use OCP\IUserManager; - -use OCP\IUser; -use OCP\IUserSession; - -class Hooks -{ - - /** - * @var IUserManager - */ - private $userManager; - - /** - * @var IUserSession - */ - private $userSession; - - /** - * @var PresenceMapper - */ - private $presenceMapper; - - /** - * @var StanzaMapper - */ - private $stanzaMapper; - - /** - * @var RosterPush - */ - private $rosterPush; - - /** - * @var IGroupManager - */ - private $groupManager; - - public function __construct( - IUserManager $userManager, - IUserSession $userSession, - RosterPush $rosterPush, - PresenceMapper $presenceMapper, - StanzaMapper $stanzaMapper, - IGroupManager $groupManager - ) { - $this->userManager = $userManager; - $this->userSession = $userSession; - $this->rosterPush = $rosterPush; - $this->presenceMapper = $presenceMapper; - $this->stanzaMapper = $stanzaMapper; - $this->groupManager = $groupManager; - } - - public static function getInstance() - { - $app = new Application(); - return $app->getContainer()->query('UserHooks'); - } - - public static function register() - { - \OC::$server->getUserManager()->listen('\OC\User', 'postCreateUser', function (IUser $user, $password) { - self::getInstance()->onCreateUser($user, $password); - }); - - \OC::$server->getUserManager()->listen('\OC\User', 'postDelete', function (IUser $user) { - self::getInstance()->onDeleteUser($user); - }); - - \OC::$server->getUserSession()->listen('\OC\User', 'changeUser', function (IUser $user, $feature, $value) { - self::getInstance()->onChangeUser($user, $feature, $value); - }); - - \OC::$server->getGroupManager()->listen('\OC\Group', 'postAddUser', function (IGroup $group, IUser $user) { - self::getInstance()->onAddUserToGroup($group, $user); - }); - - \OC::$server->getGroupManager()->listen('\OC\Group', 'postRemoveUser', function (IGroup $group, IUser $user) { - self::getInstance()->onRemoveUserFromGroup($group, $user); - }); - } - - /** - * @brief when a new user is created, the roster of the users must be updated, - * by sending a roster push. - * Note that this can still be useful when the roster and contacts menu are - * merged, for the internal state. - * @see https://tools.ietf.org/html/rfc6121#section-2.1.6 - * @param IUser $user - * @param string $password - */ - public function onCreateUser(IUser $user, $password) - { - $this->rosterPush->createOrUpdateRosterItem($user); - } - - /** - * @brief when a new user is created, the roster of the users must be updated, - * by sending a roster push. - * Note that this can still be useful when the roster and contacts menu are - * merged, for the internal state. E.g. JSXC removes a chat window, when it - * receives this stanza. - * @see https://tools.ietf.org/html/rfc6121#section-2.1.6 - * @param IUser $user - */ - public function onDeleteUser(IUser $user) - { - $this->rosterPush->removeRosterItem($user->getUID()); - - // delete the presence record of this user - $this->presenceMapper->deletePresence($user->getUID()); - - // delete all stanzas addressed to this user - $this->stanzaMapper->deleteByTo($user->getUID()); - } - - /** - * @brief when a use is changed, adapt the roster of the users. - * Note that this can still be useful when the roster and contacts menu are - * merged, for the internal state. E.g. JSXC removes a chat window, when it - * receives this stanza. - * @see https://tools.ietf.org/html/rfc6121#section-2.1.6 - * @param IUser $user - * @param string $feature feature which was changed. Enabled and displayName are supported. - * @param string $value - */ - public function onChangeUser(IUser $user, $feature, $value) - { - if ($feature === "enabled") { - if ($value === "true") { - // if user is enabled, add to roster - $this->onCreateUser($user, ''); - } elseif ($value === "false") { - // if user is enabled, remove from roster - $this->onDeleteUser($user); - } - } elseif ($feature === "displayName") { - // if the user was changed, resend the whole roster item - $this->onCreateUser($user, ''); - } - } - - public function onAddUserToGroup(IGroup $group, IUser $user) - { - $this->rosterPush->createOrUpdateRosterItem($user); - $this->rosterPush->addUserToGroup($user, $group); - } - - public function onRemoveUserFromGroup(IGroup $group, IUser $user) - { - if (Application::contactsStoreApiSupported()) { - $this->rosterPush->removeRosterItemForUsersInGroup($group, $user->getUID()); - } - $this->rosterPush->removeUserFromGroup($user, $group); - } -} diff --git a/lib/Http/XMPPResponse.php b/lib/Http/XMPPResponse.php deleted file mode 100644 index 8680bd7..0000000 --- a/lib/Http/XMPPResponse.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php -namespace OCA\OJSXC\Http; - -use OCA\OJSXC\StanzaLogger; -use OCP\AppFramework\Http\Response; -use Sabre\Xml\Writer; -use OCA\OJSXC\Db\Stanza; - -/** - * Class XMPPResponse - * - * @package OCA\OJSXC\Http - */ -class XMPPResponse extends Response -{ - - /** - * @var Writer $writer - */ - private $writer; - - /** - * @var StanzaLogger - */ - private $stanzaLogger; - - /** - * XMPPResponse constructor. - * - * @param Stanza|null $stanza - * @param StanzaLogger $stanzaLogger - */ - public function __construct(StanzaLogger $stanzaLogger, Stanza $stanza = null) - { - $this->addHeader('Content-Type', 'text/xml'); - $this->writer = new Writer(); - $this->writer->openMemory(); - $this->writer->startElement('body'); - $this->writer->writeAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); - if (!is_null($stanza)) { - $this->writer->write($stanza); - } - $this->stanzaLogger = $stanzaLogger; - } - - /** - * @param Stanza $input - */ - public function write(Stanza $input) - { - $this->stanzaLogger->log($input, StanzaLogger::SENDING); - $this->writer->write($input); - } - - /** - * @return string - */ - public function render() - { - $this->writer->endElement(); - return $this->writer->outputMemory(); - } - - /** - * Terminates the Chat connection with the `x-nc-not_allowed_to_chat` condition. - */ - public function terminate() - { - $this->writer = new Writer(); - $this->writer->openMemory(); - $this->writer->startElement('body'); - $this->writer->writeAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); - $this->writer->writeAttribute('type', 'terminate'); - $this->writer->writeAttribute('condition', 'x-nc-not_allowed_to_chat'); - } -} diff --git a/lib/ILock.php b/lib/ILock.php deleted file mode 100644 index 160e2f2..0000000 --- a/lib/ILock.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -/** - * Interface ILock - * - * @package OCA\OJSXC - */ -interface ILock -{ - - /** - * @return void - */ - public function setLock(); - - /** - * @return bool - */ - public function stillLocked(); -} diff --git a/lib/IUserProvider.php b/lib/IUserProvider.php deleted file mode 100644 index d8b3316..0000000 --- a/lib/IUserProvider.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php - - -namespace OCA\OJSXC; - -interface IUserProvider -{ - - /** - * @brief Search all users for which the current users has access to. - * @return User[] - */ - public function getAllUsers(); - - /** - * @brief Search all users for which the provided user has access to. - * @param User $user - * @return User[] - */ - public function getAllUsersForUser(User $user); - - /** - * @brief Search all users for which the provided user has access to. - * @param string $uid - * @return User[] - */ - public function getAllUsersForUserByUID($uid); - - /** - * @brief Checks if the current user can interact with the provided user - * @param User $user - * @return bool - */ - public function hasUser(User $user); - - /** - * @brief Checks if the current user can interact with the provided user identified by it's UID. - * @param string $uid the uid of the user - * @return bool - */ - public function hasUserByUID($uid); - - /** - * @brief Checks if user1 can interact with user2 - * @param User $user1 - * @param User $user2 - * @return bool - */ - public function hasUserForUser(User $user1, User $user2); - - /** - * @brief Checks if user1 can interact with the user2 identified by it's UID. - * @param string $uid1 - * @param string $uid2 - * @return bool - */ - public function hasUserForUserByUID($uid1, $uid2); - - /** - * @param string $userId - * @return bool whether $userId is excluded from chatting - */ - public function isUserExcluded($userId); -} diff --git a/lib/MemLock.php b/lib/MemLock.php deleted file mode 100644 index 902bfdd..0000000 --- a/lib/MemLock.php +++ /dev/null @@ -1,57 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -use OCP\ICache; - -/** - * Class MemLock - * - * @package OCA\OJSXC - */ -class MemLock implements ILock -{ - - /** - * @var ICache $memcache - */ - private $memcache; - - /** - * @var string $userId - */ - private $userId; - - /** - * @var string $pollingId - */ - private $pollingId; - - /** - * MemLock constructor. - * - * @param $userId - * @param ICache $cache - */ - public function __construct($userId, ICache $cache) - { - $this->userId = $userId; - $this->memcache = $cache; - $this->pollingId = microtime(); - } - - public function setLock() - { - $this->memcache->remove('-' . $this->userId . '-ojxsc-lock'); - $this->memcache->set('-' . $this->userId . '-ojxsc-lock', $this->pollingId); - } - - /** - * @return bool - */ - public function stillLocked() - { - $r = $this->memcache->get('-' . $this->userId . '-ojxsc-lock'); - return $r === $this->pollingId; - } -} diff --git a/lib/Migration/RefreshRoster.php b/lib/Migration/RefreshRoster.php deleted file mode 100644 index b4779ac..0000000 --- a/lib/Migration/RefreshRoster.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php - -namespace OCA\OJSXC\Migration; - -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\RosterPush; -use OCP\IConfig; -use OCP\ILogger; -use OCP\Migration\IOutput; -use OCP\Migration\IRepairStep; - -class RefreshRoster implements IRepairStep -{ - - /** - * @var RosterPush - */ - private $rosterPush; - - /** - * @var IConfig - */ - private $config; - - /** - * @var ILogger - */ - private $logger; - - /** - * RefreshRoster constructor. - * - * @param RosterPush $rosterPush - * @param IConfig $config - * @param ILogger $logger - */ - public function __construct(RosterPush $rosterPush, IConfig $config, ILogger $logger) - { - $this->rosterPush = $rosterPush; - $this->config = $config; - $this->logger = $logger; - } - - /** - * Returns the step's name - * - * @return string - */ - public function getName() - { - return "Refresh the roster of all users when the app has been installed before."; - } - - /** - * Run repair step. - * Must throw exception on error. - * - * @param IOutput $output - * @throws \Exception in case of failure - */ - public function run(IOutput $output) - { - /** - * We want only to refresh the rosters if this app was installed before, - * since only then the rosters can be outdated. - */ - if ($this->config->getAppValue('ojsxc', 'installed_version') !== '' - && Application::getServerType() === Application::INTERNAL) { - $stats = $this->rosterPush->refreshRoster(); - $output->info("Updated " . $stats["updated"] . " roster items"); - $this->logger->info("Updated " . $stats["updated"] . " roster items", ["app" => "OJSXC"]); - $output->info("Removed " . $stats["removed"] . " roster items"); - $this->logger->info("Removed " . $stats["removed"] . " roster items", ["app" => "OJSXC"]); - } - } -} diff --git a/lib/NewContentContainer.php b/lib/NewContentContainer.php deleted file mode 100644 index df70d01..0000000 --- a/lib/NewContentContainer.php +++ /dev/null @@ -1,38 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -use OCA\OJSXC\Db\Stanza; - -/** - * Class NewContentContainer - * Helper class to store new stanzas which will be returned in the current request. - * This way a random class can generate stanza's which are send to the same user - * without adding extra features/code to the `HTTPBindController` class. - * @package OCA\OJSXC - */ -class NewContentContainer -{ - - /** - * @var Stanza[] - */ - private static $stanzas = []; - - public function addStanza(Stanza $stanza) - { - self::$stanzas[] = $stanza; - } - - public function getStanzas() - { - $tmp = self::$stanzas; - self::$stanzas = []; - return $tmp; - } - - public function getCount() - { - return is_array(self::$stanzas)? count(self::$stanzas) : 0; - } -} diff --git a/lib/RosterPush.php b/lib/RosterPush.php deleted file mode 100644 index df98581..0000000 --- a/lib/RosterPush.php +++ /dev/null @@ -1,209 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -use OCA\OJSXC\Db\IQRosterPush; -use OCA\OJSXC\Db\IQRosterPushMapper; -use OCP\IDBConnection; -use OCP\IGroup; -use OCP\IUserManager; - -use OCP\IUser; - -class RosterPush -{ - - /** - * @var IUserManager - */ - private $userManager; - - /** - * @var IQRosterPushMapper - */ - private $iqRosterPushMapper; - - /** - * @var IDBConnection - */ - private $db; - - /** - * @var IUserProvider - */ - private $userProvider; - - /** - * RosterPush constructor. - * - * @param IUserManager $userManager - * @param IQRosterPushMapper $iqRosterPushMapper - * @param IDBConnection $db - * @param IUserProvider $userProvider - */ - public function __construct( - IUserManager $userManager, - IQRosterPushMapper $iqRosterPushMapper, - IDbConnection $db, - IUserProvider $userProvider - ) { - $this->userManager = $userManager; - $this->iqRosterPushMapper = $iqRosterPushMapper; - $this->db = $db; - $this->userProvider = $userProvider; - } - - /** - * @see https://tools.ietf.org/html/rfc6121#section-2.1.6 - * @param IUser $user - */ - public function createOrUpdateRosterItem(IUser $user) - { - $iq = new IQRosterPush(); - $iq->setJid($user->getUID()); - $iq->setName($user->getDisplayName()); - $iq->setSubscription('both'); - $iq->setFrom(''); - - - foreach ($this->userProvider->getAllUsersForUserByUID($user->getUID()) as $recipient) { - if ($recipient->getUID() !== $user->getUID()) { - $iq->setTo($recipient->getUID()); - $this->iqRosterPushMapper->insert($iq); - } - } - } - - /** - * @see https://tools.ietf.org/html/rfc6121#section-2.1.6 - * @param $userId - */ - public function removeRosterItem($userId) - { - $iq = new IQRosterPush(); - $iq->setJid($userId); - $iq->setSubscription('remove'); - $iq->setFrom(''); - - - foreach ($this->userManager->search('') as $recipient) { - if ($recipient->getUID() !== $userId) { - $iq->setTo($recipient->getUID()); - $this->iqRosterPushMapper->insert($iq); - } - } - } - - /** - * @brief performs a completely roster fresh of all users. This will send - * a rosterPush for every existing user and a rosterPush for every - * user which was ever deleted. The deleted user is fetched from the - * `addressbookchanges` table. - */ - public function refreshRoster() - { - $stats = [ - "updated" => 0, - "removed" => 0 - ]; - - - foreach ($this->userManager->search('') as $user) { - $this->createOrUpdateRosterItem($user); - $stats["updated"]++; - } - - /** - * Here we look into the addressbookchanges table for deletions - * of "contacts" in the system addressbook. This are actual users of the - * Nextcloud instance. Because this is a private API of Nextcloud it's - * encapsulated in a try/catch block. - */ - try { - $query = "SELECT `id` FROM `*PREFIX*addressbooks` WHERE `principaluri`='principals/system/system' LIMIT 1"; - $addressbooks = $this->db->executeQuery($query)->fetchAll(); - $id = $addressbooks[0]['id']; - - $query = "SELECT `uri` FROM `*PREFIX*addressbookchanges` AS ac1 WHERE `addressbookid` = ? AND `operation` = 3 AND `id`=(SELECT MAX(id) FROM `*PREFIX*addressbookchanges` AS ac2 WHERE `uri`=ac1.uri)"; // we use the subquery to always fetch the latest change - - // Fetching all changes - $deletions = $this->db->executeQuery($query, [$id])->fetchAll(); - - foreach ($deletions as $deletion) { - $userid = $deletion['uri']; - $colonPlace = strpos($userid, ':'); - $dotPlace = strrpos($userid, '.'); - $userid = substr($userid, $colonPlace + 1, strlen($userid) - $dotPlace - $colonPlace); - $this->removeRosterItem($userid); - $stats["removed"]++; - } - } catch (\Exception $e) { - \OC::$server->getLogger()->logException($e); - } - - return $stats; - } - - /** - * When a user is removed from a group, the roster items for the $userId must be removed for all users in the $group - * but only if $userId isn't accessible anymore for a user in $group. - * - * @param IGroup $group - * @param string $userId the user which is removed - */ - public function removeRosterItemForUsersInGroup(IGroup $group, $userId) - { - $iq = new IQRosterPush(); - $iq->setJid($userId); - $iq->setSubscription('remove'); - $iq->setFrom(''); - - - foreach ($group->getUsers() as $recipient) { - // check if $recipient can still chat with $userId - // if not -> remove $userId from $recipient's roster. - if ($recipient->getUID() !== $userId && !$this->userProvider->hasUserForUserByUID($recipient->getUID(), $userId)) { - $iq->setTo($recipient->getUID()); - $this->iqRosterPushMapper->insert($iq); - } - } - } - - /** - * When a user is added to a group, this user should get a rosterPush for all users in this group - * - * @param IUser $receiver - * @param IGroup $group - */ - public function addUserToGroup(IUser $receiver, IGroup $group) - { - $iq = new IQRosterPush(); - $iq->setSubscription('both'); - $iq->setFrom(''); - $iq->setTo($receiver->getUID()); - foreach ($group->getUsers() as $user) { - $iq->setJid($user->getUID()); - $iq->setName($user->getDisplayName()); - $this->iqRosterPushMapper->insert($iq); - } - } - - /** - * When a user is removed from a group, this user should get a rosterPush for all users in this group - * - * @param IUser $receiver - * @param IGroup $group - */ - public function removeUserFromGroup(IUser $receiver, IGroup $group) - { - $iq = new IQRosterPush(); - $iq->setSubscription('remove'); - $iq->setFrom(''); - $iq->setTo($receiver->getUID()); - foreach ($group->getUsers() as $user) { - $iq->setJid($user->getUID()); - $iq->setName($user->getDisplayName()); - $this->iqRosterPushMapper->insert($iq); - } - } -} diff --git a/lib/Settings/Personal.php b/lib/Settings/Personal.php index c57d317..eff912f 100644 --- a/lib/Settings/Personal.php +++ b/lib/Settings/Personal.php @@ -81,7 +81,7 @@ class Personal implements ISettings $xmppOverwrite = $this->config->getAppValue('ojsxc', Config::XMPP_ALLOW_OVERWRITE); $parameters['xmppUrl'] = $this->config->getAppValue('ojsxc', Config::XMPP_URL); - $parameters['externalConnectable'] = Application::getServerType() !== Application::INTERNAL; + $parameters['externalConnectable'] = Application::getServerType() === Application::MANAGED || Application::getServerType() === Application::EXTERNAL; $parameters['allowToOverwriteXMPPConfig'] = $xmppOverwrite === 'true' || $xmppOverwrite === true || $xmppOverwrite === 1 || $xmppOverwrite === '1'; $parameters['jid'] = $node . '@' . $domain; diff --git a/lib/StanzaHandlers/IQ.php b/lib/StanzaHandlers/IQ.php deleted file mode 100644 index 985eb0c..0000000 --- a/lib/StanzaHandlers/IQ.php +++ /dev/null @@ -1,99 +0,0 @@ -<?php - -namespace OCA\OJSXC\StanzaHandlers; - -use OCA\OJSXC\Db\IQRoster; -use OCA\OJSXC\Db\IQNotImplemented; -use OCA\OJSXC\Db\Stanza; -use OCA\OJSXC\Exceptions\TerminateException; -use OCA\OJSXC\IUserProvider; -use OCP\IConfig; -use OCP\IUserManager; - -/** - * Class IQ - * - * @package OCA\OJSXC\StanzaHandlers - */ -class IQ extends StanzaHandler -{ - - /** - * @var IUserManager - */ - private $userManager; - - /** - * @var IConfig - */ - private $config; - - /** - * @var IUserProvider - */ - private $userProvider; - - /** @var string */ - private $host; - - /** - * IQ constructor. - * - * @param string $userId - * @param string $host - * @param IUserManager $userManager - * @param IConfig $config - * @param IUserProvider $userProvider - */ - public function __construct($userId, string $host, IUserManager $userManager, IConfig $config, IUserProvider $userProvider) - { - parent::__construct($userId); - $this->userManager = $userManager; - $this->config = $config; - $this->userProvider = $userProvider; - $this->host = $host; - } - - - /** - * @param array $stanza - * @return Stanza|null - * @throws TerminateException - */ - public function handle(array $stanza) - { - $this->to = $this->getAttribute($stanza, 'to'); - - // if in debug mode we show the own username in the roster for testing - $debugMode = $this->config->getSystemValue("debug"); - - if ($stanza['value'][0]['name'] === '{http://jabber.org/protocol/disco#items}query' || $stanza['value'][0]['name'] === '{http://jabber.org/protocol/disco#info}query') { - // the disco queries are currently not implemented but these are the first stanzas send to the server so - // they are ideal to terminate the connection if a user is excluded from chatting. - if ($this->userProvider->isUserExcluded($this->userId)) { - throw new TerminateException(); - } - } elseif ($stanza['value'][0]['name'] === '{jabber:iq:roster}query') { - $id = $stanza['attributes']['id']; - $iqRoster = new IQRoster(); - $iqRoster->setType('result'); - $iqRoster->setTo($this->userId); - $iqRoster->setQid($id); - foreach ($this->userProvider->getAllUsers() as $user) { - if ($debugMode || $user->getUID() !== $this->userId) { - $iqRoster->addItem($user->getUID() . '@' . $this->host, $user->getFullName()); - } - } - return $iqRoster; - } elseif ($stanza['value'][0]['name'] === '{http://jabber.org/protocol/pubsub}pubsub') { - $id = $stanza['attributes']['id']; - $from = \array_key_exists('from', $stanza['attributes']) ? $stanza['attributes']['from'] : $this->userId; - - $iq = new IQNotImplemented(); - $iq->setTo($from); - $iq->setQid($id); - - return $iq; - } - } -} diff --git a/lib/StanzaHandlers/Message.php b/lib/StanzaHandlers/Message.php deleted file mode 100644 index 1412907..0000000 --- a/lib/StanzaHandlers/Message.php +++ /dev/null @@ -1,97 +0,0 @@ -<?php - -namespace OCA\OJSXC\StanzaHandlers; - -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\Db\MessageMapper; -use OCA\OJSXC\IUserProvider; -use OCP\ILogger; -use OCA\OJSXC\Db\Message as MessageEntity; - -/** - * Class Message - * - * @package OCA\OJSXC\StanzaHandlers - */ -class Message extends StanzaHandler -{ - - /** - * @var MessageMapper $messageMapper - */ - private $messageMapper; - - /** - * @var IUserProvider $userProvider - */ - private $userProvider; - - /** - * @var string $type - */ - private $type; - - /** - * @var array $values - */ - private $values; - - /** - * @var ILogger $logger - */ - private $logger; - - /** - * Message constructor. - * - * @param string $userId - * @param MessageMapper $messageMapper - * @param IUserProvider $userProvider - */ - public function __construct($userId, MessageMapper $messageMapper, IUserProvider $userProvider, ILogger $logger) - { - parent::__construct($userId); - $this->messageMapper = $messageMapper; - $this->userProvider = $userProvider; - $this->logger = $logger; - } - - /** - * @param array $stanza - */ - public function handle(array $stanza) - { - // Parse the username from the XML stanza to a NC userid - $to = $this->getAttribute($stanza, 'to'); - $pos = strrpos($to, '@'); - $this->to = substr($to, 0, $pos); - $this->to = Application::convertToRealUID(Application::deSanitize($this->to)); - - if (!$this->userProvider->hasUserByUID($this->to)) { - $this->logger->warning('User ' . $this->userId . ' is trying to send a message to ' . $this->to . ' but this isn\'t allowed'); - return; - } - - foreach ($stanza['value'] as $keyRaw => $value) { - // remove namespace from key as it is unneeded and cause problems - $key = substr($keyRaw, strpos($keyRaw, '}') + 1, strlen($keyRaw)); - // fetch namespace from key to read it - $ns = substr($keyRaw, 1, strpos($keyRaw, '}') - 1); - - $this->values[] = [ - "name" => $key, - "value" => (string)$value, - "attributes" => ["xmlns" => $ns] - ]; - } - $this->type = $this->getAttribute($stanza, 'type'); - - $message = new MessageEntity(); - $message->setTo($this->to); - $message->setFrom($this->userId); - $message->setValue($this->values); - $message->setType($this->type); - $this->messageMapper->insert($message); - $this->values = []; - } -} diff --git a/lib/StanzaHandlers/Presence.php b/lib/StanzaHandlers/Presence.php deleted file mode 100644 index 1f211da..0000000 --- a/lib/StanzaHandlers/Presence.php +++ /dev/null @@ -1,78 +0,0 @@ -<?php - -namespace OCA\OJSXC\StanzaHandlers; - -use OCA\OJSXC\Db\MessageMapper; -use OCA\OJSXC\Db\PresenceMapper; -use OCA\OJSXC\Exceptions\TerminateException; -use OCA\OJSXC\Db\Presence as PresenceEntity; - -/** - * Class Presence - * - * @package OCA\OJSXC\StanzaHandlers - */ -class Presence extends StanzaHandler -{ - - /** - * @var PresenceMapper $presenceMapper - */ - private $presenceMapper; - - /** - * @var MessageMapper $messageMapper - */ - private $messageMapper; - - /** - * Presence constructor. - * - * @param $userId - * @param PresenceMapper $presenceMapper - * @param MessageMapper $messageMapper - */ - public function __construct($userId, PresenceMapper $presenceMapper, MessageMapper $messageMapper) - { - parent::__construct($userId); - $this->presenceMapper = $presenceMapper; - $this->messageMapper = $messageMapper; - } - - /** - * This function is called when a client/user updates it's presence. - * This function should: - * - update the presence in the database - * - broadcast the presence - * - return the active presence if the type isn't equal to unavailable - * - * @param PresenceEntity $presence - * @return PresenceEntity[] - * @throws TerminateException - */ - public function handle(PresenceEntity $presence) - { - - // update the presence - $this->presenceMapper->setPresence($presence); - - // broadcast the presence - $connectedUsers = $this->presenceMapper->getConnectedUsers(); // fetch connected users - - // build stanza to send to the users - $presenceToSend = new PresenceEntity(); - $presenceToSend->setPresence($presence->getPresence()); - $presenceToSend->setFrom($this->userId); - foreach ($connectedUsers as $user) { - $presenceToSend->setTo($user); - $this->messageMapper->insert($presenceToSend); - } - - if ($presence->getPresence() !== 'unavailable') { - // return other users presence - return $this->presenceMapper->getPresences(); - } else { - return []; - } - } -} diff --git a/lib/StanzaHandlers/README.md b/lib/StanzaHandlers/README.md deleted file mode 100644 index acaccb6..0000000 --- a/lib/StanzaHandlers/README.md +++ /dev/null @@ -1,5 +0,0 @@ -#lib/stanzahandlers - -This are the objects which handle incoming stanza's. The classess are called -by the `HTTPBindController` controller. - diff --git a/lib/StanzaHandlers/StanzaHandler.php b/lib/StanzaHandlers/StanzaHandler.php deleted file mode 100644 index cbe9d60..0000000 --- a/lib/StanzaHandlers/StanzaHandler.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php -namespace OCA\OJSXC\StanzaHandlers; - -use Sabre\Xml\Reader; -use Sabre\Xml\Writer; - -/** - * Class StanzaHandler - * - * @package OCA\OJSXC\StanzaHandlers - */ -abstract class StanzaHandler -{ - - /** - * @var string $userId - */ - protected $userId; - - /** - * @var string $to - */ - protected $to; - - /** - * StanzaHandler constructor. - * - * @param string 1$userId - */ - public function __construct($userId) - { - $this->userId = $userId; - } - - /** - * @brief Gets an attribute $attr from $stanza, returns null if it doens't - * exists. - * @param $stanza - * @param $attr - * @return null|string - */ - protected function getAttribute($stanza, $attr) - { - return isset($stanza['attributes'][$attr]) ? (string) $stanza['attributes'][$attr] : null; - } -} diff --git a/lib/StanzaLogger.php b/lib/StanzaLogger.php deleted file mode 100644 index fa1c41e..0000000 --- a/lib/StanzaLogger.php +++ /dev/null @@ -1,55 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -use OCA\OJSXC\Db\Stanza; -use OCP\ILogger; -use Sabre\Xml\Writer; - -class StanzaLogger -{ - - /** - * @var ILogger - */ - private $logger; - - /** - * When a stanza is received by the server. - */ - const RECEIVING = "Receiving"; - - /** - * When the server directly sends a stanza to a client. - */ - const SENDING = "Sending"; - - /** - * When the server stores a message to send it using the longpoll table. - */ - const STORING = "Storing"; - private $userId; - - - public function __construct(ILogger $logger, $userId) - { - $this->logger = $logger; - $this->userId = $userId; - } - - public function log(Stanza $stanza, $action) - { - if (\OC::$server->getConfig()->getSystemValue('loglevel') === \OCP\Util::DEBUG) { - // only serialize when needed - $writer = new Writer(); - $writer->openMemory(); - $writer->write($stanza); - $this->logger->debug($action . " {" . $this->userId . "} : " . $writer->outputMemory(), ["app" => "ojsxc"]); - } - } - - public function logRaw($stanza, $action) - { - $this->logger->debug($action . " {" . $this->userId . "} : " . $stanza, ["app" => "ojsxc"]); - } -} diff --git a/lib/User.php b/lib/User.php deleted file mode 100644 index df7c10c..0000000 --- a/lib/User.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -use OCA\OJSXC\AppInfo\Application; -use OCP\IUser; - -class User -{ - - /** - * @var string - */ - private $uid; - - /** - * @var string - */ - private $fullName; - - - /** - * @brief The original object where this user is created from. - * @var IUser | \OCP\Contacts\ContactsMenu\IEntry - */ - private $origin; - - /** - * @param string $uid UID of the user - * @param string $fullName Fullname of the user - */ - public function __construct($uid, $fullName, $origin) - { - $this->uid = Application::sanitizeUserId($uid); - $this->fullName = $fullName; - $this->origin = $origin; - } - - /** - * @return string - */ - public function getUid() - { - return $this->uid; - } - - /** - * @param string $uid - */ - public function setUid($uid) - { - $this->uid = Application::sanitizeUserId($uid); - } - - /** - * @return string - */ - public function getFullName() - { - return $this->fullName; - } - - /** - * @param string $fullName - */ - public function setFullName($fullName) - { - $this->fullName = $fullName; - } -} diff --git a/lib/UserManagerUserProvider.php b/lib/UserManagerUserProvider.php deleted file mode 100644 index bcc7ce0..0000000 --- a/lib/UserManagerUserProvider.php +++ /dev/null @@ -1,85 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -use OCP\IUserManager; - -/** - * Class UserManagerUserProvider - * - * @package OCA\OJSXC - * @codeCoverageIgnore - */ -class UserManagerUserProvider implements IUserProvider -{ - - /** - * @var IUserManager - */ - private $userManager; - - /** - * @var User[] Cache - */ - private static $cache = null; - - public function __construct(IUserManager $userManager) - { - $this->userManager = $userManager; - } - - public function getAllUsers() - { - if (is_null(self::$cache)) { - $result = []; - foreach ($this->userManager->search('') as $user) { - if ($user->isEnabled()) { - $result[] = new User($user->getUID(), $user->getDisplayName(), $user); - } - } - - self::$cache = $result; - } - return self::$cache; - } - - public function hasUser(User $user) - { - return !is_null($this->userManager->get($user->getUid())); - } - - public function hasUserByUID($uid) - { - return !is_null($this->userManager->get($uid)); - } - - public function getAllUsersForUser(User $user) - { - // since we don't have access to the ContactsStore, we don't apply the enhancement privacy rules. - return $this->getAllUsers(); - } - - public function getAllUsersForUserByUID($uid) - { - // since we don't have access to the ContactsStore, we don't apply the enhancement privacy rules. - return $this->getAllUsers(); - } - - public function hasUserForUser(User $user1, User $user2) - { - // since we don't have access to the ContactsStore, we don't apply the enhancement privacy rules. - return $this->hasUser($user2); - } - - public function hasUserForUserByUID($uid1, $uid2) - { - // since we don't have access to the ContactsStore, we don't apply the enhancement privacy rules. - return $this->hasUserByUID($uid2); - } - - public function isUserExcluded($userId) - { - // to limit inconsistency we only support the settings in NC > 13.0.0 - return false; - } -} diff --git a/templates/settings/admin.php b/templates/settings/admin.php index 0f4f0e5..40b83fa 100644 --- a/templates/settings/admin.php +++ b/templates/settings/admin.php @@ -40,10 +40,9 @@ function printRadioInput($key, $value, $required=true) { <div class="form-group"> <label class="text-left form-no-padding"> <?php printRadioInput('serverType', 'internal'); ?> - Internal (deprecated) + Internal (removed) </label> - <em>Limited functionality only: No clients besides JSXC in Nextcloud, no multi-user chat, - no server-to-server federations.</em> + <em>We are sorry, but the internal server was removed. Please use the managed server or your own XMPP server.</em> </div> <div class="form-group"> <label class="text-left form-no-padding"> diff --git a/tests/Integration/ContactsStoreUserProviderTest.php b/tests/Integration/ContactsStoreUserProviderTest.php deleted file mode 100644 index 1c9bb91..0000000 --- a/tests/Integration/ContactsStoreUserProviderTest.php +++ /dev/null @@ -1,281 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Integration; - -use OC\Contacts\ContactsMenu\ContactsStore; -use OCA\DAV\CardDAV\AddressBookImpl; -use OCA\OJSXC\AppInfo\Application; -use OCP\Contacts\ContactsMenu\IContactsStore; -use OCP\Contacts\IManager; -use OCP\IConfig; -use OCP\IGroupManager; -use OCP\IUserManager; -use OCP\IUserSession; -use OCA\DAV\AppInfo\Application as DavApp; -use OCA\DAV\CardDAV\CardDavBackend; -use PHPUnit\Framework\Constraint\IsEqual; -use Sabre\VObject\Component\VCard; -use OCA\OJSXC\Tests\Utility\TestCase; - -class ContactsStoreUserProviderTest extends TestCase -{ - - /** - * @var ContactsStoreUserProvider - */ - private $contactsStoreUserProvider; - - /** - * @var IContactsStore - */ - private $contactsStore; - - /** - * @var IUserSession - */ - private $userSession; - - /** - * @var IUserManager - */ - private $userManager; - - /** - * @var IGroupManager - */ - private $groupManager; - - /** - * @var IConfig - */ - private $config; - - /** - * @var CardDavBackend - */ - private $cardDavBackend; - - /** - * @var IManager - */ - private $contactsManager; - - public function setUp(): void - { - if (!Application::contactsStoreApiSupported()) { - $this->markTestSkipped(); - return; - } - $this->config = \OC::$server->getConfig(); - $this->config->setAppValue('core', 'shareapi_only_share_with_group_members', 'no'); - foreach (\OC::$server->getUserManager()->search('') as $user) { - $user->delete(); - } - - $users[] = \OC::$server->getUserManager()->createUser('admin', 'admin'); - $users[] = \OC::$server->getUserManager()->createUser('derp', 'derp'); - $users[] = \OC::$server->getUserManager()->createUser('derpina', 'derpina'); - $users[] = \OC::$server->getUserManager()->createUser('herp', 'herp'); - $users[] = \OC::$server->getUserManager()->createUser('foo', 'foo'); - - $currentUser = \OC::$server->getUserManager()->createUser('autotest', 'autotest'); - $this->userSession = \OC::$server->getUserSession(); - $this->userSession->setUser($currentUser); - $this->userManager = \OC::$server->getUserManager(); - $this->groupManager = \OC::$server->getGroupManager(); - $this->contactsStore = \OC::$server->query(ContactsStore::class); - $this->contactsManager = \OC::$server->getContactsManager(); - - /** @var \OCA\DAV\CardDAV\SyncService $syncService */ - $syncService = \OC::$server->query('CardDAVSyncService'); - $syncService->getLocalSystemAddressBook(); - $syncService->updateUser($currentUser); - - - $davApp = new DavApp(); - - $this->cardDavBackend = $davApp->getContainer()->query(CardDavBackend::class); - - // create some contacts - $vCard = new VCard(); - $vCard->VERSION = '3.0'; - $vCard->UID = 'Test1'; - $vCard->FN = 'Test1'; - - $id = $this->setupAddressBook('autotest'); - $this->cardDavBackend->createCard($id, 'Alice.Test1.vcf', $vCard->serialize()); - - foreach ($users as $user) { - $syncService->updateUser($user); - } - - $davApp->setupSystemContactsProvider($this->contactsManager); - \OC_User::setIncognitoMode(false); - \OC::$server->getDatabaseConnection()->executeQuery("DELETE FROM *PREFIX*ojsxc_stanzas"); - - - $this->contactsStoreUserProvider = new ContactsStoreUserProvider( - $this->contactsStore, - $this->userSession, - $this->userManager, - $this->groupManager, - $this->config - ); - } - - private function setupAddressBook($userId) - { - $addressBooks = $this->cardDavBackend->getAddressBooksForUser("principals/users/$userId"); - foreach ($addressBooks as $addressBookInfo) { - $this->cardDavBackend->deleteAddressBook($addressBookInfo['id']); - } - $addressBookId = $this->cardDavBackend->createAddressBook('principals/users/' . $userId, 'principals/users/' . $userId, []); - - $addressBooks = $this->cardDavBackend->getAddressBooksForUser("principals/users/$userId"); - - foreach ($addressBooks as $addressBookInfo) { - $addressBook = new \OCA\DAV\CardDAV\AddressBook($this->cardDavBackend, $addressBookInfo, \OC::$server->getL10N('dav')); - $this->contactsManager->registerAddressBook( - new AddressBookImpl( - $addressBook, - $addressBookInfo, - $this->cardDavBackend, - \OC::$server->getURLGenerator() - ) - ); - } - - return $addressBookId; - } - - protected function tearDown(): void - { - $config = \OC::$server->getConfig(); - $config->setAppValue('core', 'shareapi_only_share_with_group_members', 'no'); - $config->setAppValue('core', 'shareapi_exclude_groups', 'no'); - $config->setAppValue('core', 'shareapi_exclude_groups_list', json_encode([])); - foreach (\OC::$server->getUserManager()->search('') as $user) { - $user->delete(); - } - } - - public function testNormalSituation() - { - - // no special settings set - $derp = new User('derp', 'derp', $this->contactsStore->findOne($this->userManager->get('autotest'), 6, 'derp')); - $derpina = new User('derpina', 'derpina', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'derpina')[0]); - $herp = new User('herp', 'herp', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'herp')[0]); - $foo = new User('foo', 'foo', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'foo')[0]); - $admin = new User('admin', 'admin', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'admin')[0]); - $autotest = new User('autotest', 'autotest', $this->contactsStore->getContacts($this->userManager->get('derpina'), 'autotest')[0]); - - $expected = [ - $foo, - $admin, - $derp, - $derpina, - $herp - ]; - - $this->assertCanonicalizeEquals($expected, $this->contactsStoreUserProvider->getAllUsers()); - $this->assertCanonicalizeEquals([$autotest, $derp, $herp, $foo, $admin], $this->contactsStoreUserProvider->getAllUsersForUserByUID('derpina')); - $this->assertCanonicalizeEquals([$autotest, $derp, $herp, $foo, $admin], $this->contactsStoreUserProvider->getAllUsersForUser($derpina)); - - $this->assertTrue($this->contactsStoreUserProvider->hasUserForUserByUID('derp', 'derpina')); - $this->assertTrue($this->contactsStoreUserProvider->hasUserForUser($derp, $derpina)); - $this->assertTrue($this->contactsStoreUserProvider->hasUserByUID('derpina')); - $this->assertTrue($this->contactsStoreUserProvider->hasUser($derpina)); - $this->assertFalse($this->contactsStoreUserProvider->isUserExcluded('derpina')); - } - - public function testGroupsOnly() - { - $this->setValueOfPrivateProperty($this->contactsStoreUserProvider, 'cache', null); - $group1 = $this->groupManager->createGroup('group1'); - $group2 = $this->groupManager->createGroup('group2'); - $group1->addUser($this->userManager->get('derp')); - $group1->addUser($this->userManager->get('foo')); - $group2->addUser($this->userManager->get('derpina')); - $group2->addUser($this->userManager->get('herp')); - - $this->config->setAppValue('core', 'shareapi_only_share_with_group_members', 'yes'); - - // no special settings set - $derp = new User('derp', 'derp', $this->contactsStore->getContacts($this->userManager->get('foo'), 'derp')[0]); - $derpina = new User('derpina', 'derpina', $this->contactsStore->getContacts($this->userManager->get('herp'), 'derpina')[0]); - $herp = new User('herp', 'herp', $this->contactsStore->getContacts($this->userManager->get('derpina'), 'herp')[0]); - $foo = new User('foo', 'foo', $this->contactsStore->getContacts($this->userManager->get('derp'), 'foo')[0]); - - $this->assertCanonicalizeEquals([], $this->contactsStoreUserProvider->getAllUsers()); // running as autotest -> not in any group - $this->assertCanonicalizeEquals([$herp], $this->contactsStoreUserProvider->getAllUsersForUserByUID('derpina')); - $this->assertCanonicalizeEquals([$herp], $this->contactsStoreUserProvider->getAllUsersForUser($derpina)); - $this->assertCanonicalizeEquals([$foo], $this->contactsStoreUserProvider->getAllUsersForUserByUID('derp')); - $this->assertCanonicalizeEquals([$foo], $this->contactsStoreUserProvider->getAllUsersForUser($derp)); - - $this->assertFalse($this->contactsStoreUserProvider->hasUserForUserByUID('derp', 'derpina')); - $this->assertFalse($this->contactsStoreUserProvider->hasUserForUser($derp, $derpina)); - $this->assertFalse($this->contactsStoreUserProvider->hasUserForUserByUID('derpina', 'derp')); - $this->assertFalse($this->contactsStoreUserProvider->hasUserForUser($derpina, $derp)); - - $this->assertTrue($this->contactsStoreUserProvider->hasUserForUserByUID('derp', 'foo')); - $this->assertTrue($this->contactsStoreUserProvider->hasUserForUser($derp, $foo)); - $this->assertTrue($this->contactsStoreUserProvider->hasUserForUserByUID('foo', 'derp')); - $this->assertTrue($this->contactsStoreUserProvider->hasUserForUser($foo, $derp)); - - $this->assertFalse($this->contactsStoreUserProvider->hasUserByUID('derpina')); - $this->assertFalse($this->contactsStoreUserProvider->hasUser($derpina)); - $this->assertFalse($this->contactsStoreUserProvider->isUserExcluded('derpina')); - } - - public function testExcluded() - { - $this->setValueOfPrivateProperty($this->contactsStoreUserProvider, 'cache', null); - $groupExcluded = $this->groupManager->createGroup('excluded'); - $this->config->setAppValue('core', 'shareapi_exclude_groups', 'yes'); - $this->config->setAppValue('core', 'shareapi_exclude_groups_list', json_encode(['excluded'])); - $groupExcluded->addUser($this->userManager->get('derp')); - $groupExcluded->addUser($this->userManager->get('derpina')); - - $herp = new User('herp', 'herp', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'herp')[0]); - $foo = new User('foo', 'foo', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'foo')[0]); - $admin = new User('admin', 'admin', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'admin')[0]); - $autotest = new User('autotest', 'autotest', $this->contactsStore->getContacts($this->userManager->get('admin'), 'autotest')[0]); - - $this->assertCanonicalizeEquals([$admin, $herp, $foo], $this->contactsStoreUserProvider->getAllUsers()); - $this->assertTrue($this->contactsStoreUserProvider->isUserExcluded('derp')); - $this->assertTrue($this->contactsStoreUserProvider->isUserExcluded('derpina')); - $this->assertFalse($this->contactsStoreUserProvider->isUserExcluded('autotest')); - $this->assertFalse($this->contactsStoreUserProvider->isUserExcluded('admin')); - $this->assertFalse($this->contactsStoreUserProvider->isUserExcluded('foo')); - $this->assertFalse($this->contactsStoreUserProvider->isUserExcluded('herp')); - - $this->config->setAppValue('core', 'shareapi_exclude_groups', 'no'); - $this->config->setAppValue('core', 'shareapi_exclude_groups_list', json_encode([])); - } - - public function testDisabled() - { - $this->setValueOfPrivateProperty($this->contactsStoreUserProvider, 'cache', null); - $derpina = new User('derpina', 'derpina', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'derpina')[0]); - $herp = new User('herp', 'herp', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'herp')[0]); - $foo = new User('foo', 'foo', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'foo')[0]); - $admin = new User('admin', 'admin', $this->contactsStore->getContacts($this->userManager->get('autotest'), 'admin')[0]); - - $this->userManager->get('derp')->setEnabled(false); - - $expected = [ - $admin, - $derpina, - $herp, - $foo - ]; - - $this->assertCanonicalizeEquals($expected, $this->contactsStoreUserProvider->getAllUsers()); - } - - private function assertCanonicalizeEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $ignoreCase = false) - { - $this->assertEquals($expected, $actual, $message, $delta, $maxDepth, true, $ignoreCase); - } -} diff --git a/tests/Integration/Db/IqRosterPushTest.php b/tests/Integration/Db/IqRosterPushTest.php deleted file mode 100644 index 9716a30..0000000 --- a/tests/Integration/Db/IqRosterPushTest.php +++ /dev/null @@ -1,39 +0,0 @@ -<?php -namespace OCA\OJSXC\Tests\Integration\Db; - -use Sabre\Xml\Writer; -use OCA\OJSXC\Tests\Utility\TestCase; -use OCA\OJSXC\Db\IQRosterPush; - -class IqRosterPushTest extends TestCase -{ - public function testIqRoster() - { - $writer = new Writer(); - $writer->openMemory(); - $writer->startElement('body'); - $writer->writeAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); - - $iqRosterPush = new IQRosterPush(); - $iqRosterPush->setAttrId('4'); - $iqRosterPush->setJid('john', 'localhost'); - $iqRosterPush->setTo('jan', 'localhost'); - $iqRosterPush->setName('john'); - $iqRosterPush->setSubscription('both'); - - $this->assertEquals('john@localhost', $iqRosterPush->getJid()); - $this->assertEquals('jan', $iqRosterPush->getUnSanitizedTo()); - $this->assertEquals('jan@localhost', $iqRosterPush->to); - $this->assertEquals('john', $iqRosterPush->getName()); - $this->assertEquals('both', $iqRosterPush->getSubscription()); - - $writer->write($iqRosterPush); // needed to test the xmlSerialize function - - $writer->endElement(); - $result = $writer->outputMemory(); - - $expected = '<body xmlns="http://jabber.org/protocol/httpbind"><iq to="jan@localhost" type="set" id="4"><query xmlns="jabber:iq:roster"><item jid="john@localhost" name="john" subscription="both"></item></query></iq></body>'; - - $this->assertXmlStringEqualsXmlString($expected, $result); - } -} diff --git a/tests/Integration/Db/IqRosterTest.php b/tests/Integration/Db/IqRosterTest.php deleted file mode 100644 index 3f3ff41..0000000 --- a/tests/Integration/Db/IqRosterTest.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -namespace OCA\OJSXC\Tests\Integration\Db; - -use Sabre\Xml\Writer; -use OCA\OJSXC\Tests\Utility\TestCase; -use OCA\OJSXC\Db\IQRoster; - -class IqRosterTest extends TestCase -{ - public function testIqRoster() - { - $writer = new Writer(); - $writer->openMemory(); - $writer->startElement('body'); - $writer->writeAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); - - $iqRoster = new IQRoster(); - $iqRoster->setType('result'); - $iqRoster->setTo('john', 'localhost'); - $iqRoster->setQid('4434'); - $iqRoster->addItem('test@test.be', 'Test Test'); - $iqRoster->addItem('test2@test.be', 'Test2 Test'); - - $this->assertEquals('result', $iqRoster->getType()); - $this->assertEquals('john', $iqRoster->getUnSanitizedTo()); - $this->assertEquals('john@localhost', $iqRoster->to); - $this->assertEquals('4434', $iqRoster->getQid()); - $this->assertEquals([ - [ - "name" => "item", - "attributes" => [ - "jid" => "test@test.be", - "name" => "Test Test", - "subscription" => "both" - ], - "value" => '' - ], - [ - "name" => "item", - "attributes" => [ - "jid" => "test2@test.be", - "name" => "Test2 Test", - "subscription" => "both" - ], - "value" => '' - ], - ], $iqRoster->getItems()); - - $writer->write($iqRoster); // needed to test the xmlSerialize function - - $writer->endElement(); - $result = $writer->outputMemory(); - - $expected = '<body xmlns="http://jabber.org/protocol/httpbind"><iq to="john@localhost" type="result" id="4434"><query xmlns="jabber:iq:roster"><item jid="test@test.be" name="Test Test" subscription="both"></item><item jid="test2@test.be" name="Test2 Test" subscription="both"></item></query></iq></body>'; - - $this->assertXmlStringEqualsXmlString($expected, $result); - } -} diff --git a/tests/Integration/Db/MessageMapperTest.php b/tests/Integration/Db/MessageMapperTest.php deleted file mode 100644 index 857d81e..0000000 --- a/tests/Integration/Db/MessageMapperTest.php +++ /dev/null @@ -1,171 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Integration\Db; - -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\Db\Message; -use OCA\OJSXC\Tests\Utility\MapperTestUtility; -use OCP\AppFramework\Db\DoesNotExistException; - -/** - * @group DB - */ -class MessageMapperTest extends MapperTestUtility -{ - - /** - * @var StanzaMapper - */ - protected $mapper; - - protected function setUp(): void - { - $this->entityName = 'OCA\OJSXC\Db\Message'; - $this->mapperName = 'MessageMapper'; - parent::setUp(); - } - - public function insertProvider() - { - return [ - [ - ['john', 'localhost'], - ['thomas', 'localhost'], - 'abcd', - 'test', - 'Test Message', - // save stanza without host or resource - '<message to="thomas" from="john" type="test" xmlns="jabber:client" id="4-msg">Test Message</message>' - ] - ]; - } - - /** - * @dataProvider insertProvider - */ - public function testInsert($from, $to, $data, $type, $msg, $expectedStanza) - { - $stanza = new Message(); - $stanza->setAttrId('4-msg'); - $stanza->setFrom($from[0]); - $stanza->setTo($to[0]); - $stanza->setStanza($data); - $stanza->setType($type); - $stanza->setValue($msg); - - $this->assertEquals($stanza->getUnSanitizedFrom(), $from[0]); - $this->assertEquals($stanza->getUnSanitizedTo(), $to[0]); - $this->assertEquals($stanza->getStanza(), $data); - $this->assertEquals($stanza->getType(), $type); - - $this->mapper->insert($stanza); - - $result = $this->fetchAll(); - - $this->assertCount(1, $result); - $this->assertEquals($stanza->getUnSanitizedFrom(), $result[0]->getFrom()); - $this->assertEquals($stanza->getUnSanitizedTo(), $result[0]->getTo()); - $this->assertEquals($expectedStanza, $result[0]->getStanza()); - $this->assertEquals(null, $result[0]->getType()); // type is saved into the XML string, not the DB. - } - - public function testFindByToNotFound() - { - $this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class); - - $this->mapper->findByTo('test'); - } - - public function testFindByToNotFound2() - { - $this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class); - - $stanza = new Message(); - $stanza->setFrom('john', 'localhost'); - $stanza->setTo('john', 'localhost'); - $stanza->setStanza('abcd'); - $stanza->setType('test'); - $stanza->setValue('message abc'); - $this->mapper->insert($stanza); - - $this->mapper->findByTo('test'); - } - - public function testFindByToFoundWithoutAtSign() - { - // when the username doesn't contain a @ the domain is removed and stored as such in the DB - // the resulting stanza then contains the full JID - $stanza1 = new Message(); - $stanza1->setAttrId('4'); - $stanza1->setFrom('jan'); - $stanza1->setTo('john'); - $stanza1->setType('test'); - $stanza1->setValue('Messageabc'); - $this->mapper->insert($stanza1); - - $stanza2 = new Message(); - $stanza2->setAttrId('5'); - $stanza2->setFrom('thomas'); - $stanza2->setTo('jan'); - $stanza2->setType('test2'); - $stanza2->setValue('Message'); - $this->mapper->insert($stanza2); - - - // check if two elements are inserted - $result = $this->fetchAll(); - $this->assertCount(2, $result); - - // check findByTo - $result = $this->mapper->findByTo('john'); - $this->assertCount(1, $result); - $this->assertEquals('<message to="john@localhost/internal" from="jan@localhost/internal" type="test" xmlns="jabber:client" id="4">Messageabc</message>', $result[0]->getStanza()); - - // check if element is deleted - $result = $this->fetchAll(); - $this->assertCount(1, $result); - $this->assertEquals($stanza2->getUnSanitizedFrom(), $result[0]->getFrom()); - $this->assertEquals($stanza2->getUnSanitizedTo(), $result[0]->getTo()); - $this->assertEquals('<message to="jan" from="thomas" type="test2" xmlns="jabber:client" id="5">Message</message>', $result[0]->getStanza()); // notice that the username isn't replaced by the JID since this tis the task of hte findByTo method - } - - public function testFindByToFoundWithAtSign() - { - // when the username does contain a @ the domain is removed and stored as such in the DB, but with the @ still - // in the username, the resulting stanza then contains the full JID - $stanza1 = new Message(); - $stanza1->setAttrId('4-msg'); - $stanza1->setFrom('jan@localhost.com'); - $stanza1->setTo('john@localhost.com'); - $stanza1->setStanza('abcd1'); - $stanza1->setType('test'); - $stanza1->setValue('Messageabc'); - $this->mapper->insert($stanza1); - - $stanza2 = new Message(); - $stanza2->setAttrId('4-msg'); - $stanza2->setFrom('thomas@localhost.com'); - $stanza2->setTo('jan@localhost.com'); - $stanza2->setStanza('abcd2'); - $stanza2->setType('test2'); - $stanza2->setValue('Message'); - $this->mapper->insert($stanza2); - - - // check if two elements are inserted - $result = $this->fetchAll(); - $this->assertCount(2, $result); - - // check findByTo - $result = $this->mapper->findByTo('john@localhost.com'); - $this->assertCount(1, $result); - $this->assertXmlStringEqualsXmlString('<message to="john_ojsxc_esc_at_localhost.com@localhost/internal" from="jan_ojsxc_esc_at_localhost.com@localhost/internal" type="test" xmlns="jabber:client" id="4-msg">Messageabc</message>', $result[0]->getStanza()); - - // check if element is deleted - $result = $this->fetchAll(); - $this->assertCount(1, $result); - $this->assertEquals($stanza2->getFrom(), $result[0]->getFrom()); - $this->assertEquals($stanza2->getTo(), $result[0]->getTo()); - $this->assertXmlStringEqualsXmlString('<message to="jan_ojsxc_esc_at_localhost.com" from="thomas_ojsxc_esc_at_localhost.com" type="test2" xmlns="jabber:client" id="4-msg">Message</message>', $result[0]->getStanza()); - } -} diff --git a/tests/Integration/Db/PresenceMapperTest.php b/tests/Integration/Db/PresenceMapperTest.php deleted file mode 100644 index c9161c7..0000000 --- a/tests/Integration/Db/PresenceMapperTest.php +++ /dev/null @@ -1,593 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Integration\Db; - -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\Db\Presence as PresenceEntity; -use OCA\OJSXC\NewContentContainer; -use OCA\OJSXC\Tests\Utility\MapperTestUtility; -use OCA\DAV\AppInfo\Application as DavApp; - -$time = 0; - -function time() -{ - global $time; - return $time; -} - - -/** - * @group DB - */ -class PresenceMapperTest extends MapperTestUtility -{ - - /** - * @var PresenceMapper - */ - protected $mapper; - - /** - * @var NewContentContainer $newContentContainer - */ - protected $newContentContainer; - - protected function setUp(): void - { - $this->entityName = 'OCA\OJSXC\Db\Presence'; - $this->mapperName = 'PresenceMapper'; - parent::setUp(); - $this->setValueOfPrivateProperty($this->mapper, 'updatedPresence', false); - $this->setValueOfPrivateProperty($this->mapper, 'fetchedConnectedUsers', false); - $this->setValueOfPrivateProperty($this->mapper, 'connectedUsers', []); - $this->setValueOfPrivateProperty($this->mapper, 'userId', 'admin'); - $this->newContentContainer = $this->container->query('NewContentContainer'); - $this->setValueOfPrivateProperty($this->newContentContainer, 'stanzas', []); - foreach (\OC::$server->getUserManager()->search('') as $user) { - $user->delete(); - } - } - - protected function tearDown(): void - { - foreach (\OC::$server->getUserManager()->search('') as $user) { - $user->delete(); - } - } - - public function setupContactsStoreAPI() - { - foreach (\OC::$server->getUserManager()->search('') as $user) { - $user->delete(); - } - - $users[] = \OC::$server->getUserManager()->createUser('admin', 'admin'); - $users[] = \OC::$server->getUserManager()->createUser('derp', 'derp'); - $users[] = \OC::$server->getUserManager()->createUser('derpina', 'derpina'); - $users[] = \OC::$server->getUserManager()->createUser('herp', 'herp'); - $users[] = \OC::$server->getUserManager()->createUser('foo', 'foo'); - - $currentUser = \OC::$server->getUserManager()->createUser('autotest', 'autotest'); - \OC::$server->getUserSession()->setUser($currentUser); - - if (Application::contactsStoreApiSupported()) { - /** @var \OCA\DAV\CardDAV\SyncService $syncService */ - $syncService = \OC::$server->query('CardDAVSyncService'); - $syncService->getLocalSystemAddressBook(); - $syncService->updateUser($currentUser); - - foreach ($users as $user) { - $syncService->updateUser($user); - } - - $cm = \OC::$server->getContactsManager(); - $davApp = new DavApp(); - $davApp->setupSystemContactsProvider($cm); - } - \OC_User::setIncognitoMode(false); - \OC::$server->getDatabaseConnection()->executeQuery("DELETE FROM *PREFIX*ojsxc_stanzas"); - } - - /** - * @return array - */ - public function presenceIfNotExitsProvider() - { - $input1 = new PresenceEntity(); - $input1->setPresence('online'); - $input1->setUserid('admin'); - $input1->setLastActive(23434); - - $input2 = new PresenceEntity(); - $input2->setPresence('unavailable'); - $input2->setUserid('derp'); - $input2->setLastActive(23434475); - - - $input3 = new PresenceEntity(); - $input3->setPresence('chat'); - $input3->setUserid('derpina'); - $input3->setLastActive(23445645634); - - return [ - [ - [$input1, $input2, $input3], - [ - [ - 'userid' => 'admin', - 'presence' => 'online', - 'last_active' => 23434, - ], - [ - 'userid' => 'derp', - 'presence' => 'unavailable', - 'last_active' => 23434475, - ], - [ - 'userid' => 'derpina', - 'presence' => 'chat', - 'last_active' => 23445645634 - ] - ] - ] - ]; - } - - /** - * @dataProvider presenceIfNotExitsProvider - * Test setting the presence if it doesn't exits. - * @param PresenceEntity[] $inputs - * @param array $expected - */ - public function testSetPresenceIfNotExists($inputs, $expected) - { - foreach ($inputs as $input) { - $this->mapper->setPresence($input); - } - $result = $this->fetchAllAsArray(); - - $this->assertArrayDbResultsEqual($expected, $result, ['userid', 'presence', 'last_active']); - } - - /** - * @return array - */ - public function presenceIfExitsProvider() - { - $input1 = new PresenceEntity(); - $input1->setPresence('online'); - $input1->setUserid('admin'); - $input1->setLastActive(23434); - - $input2 = new PresenceEntity(); - $input2->setPresence('unavailable'); - $input2->setUserid('derp'); - $input2->setLastActive(23434475); - - $input3 = new PresenceEntity(); - $input3->setPresence('chat'); - $input3->setUserid('derpina'); - $input3->setLastActive(23445645634); - - $input4 = new PresenceEntity(); - $input4->setPresence('chat'); - $input4->setUserid('admin'); - $input4->setLastActive(3234343424); - - $input5 = new PresenceEntity(); - $input5->setPresence('online'); - $input5->setUserid('derp'); - $input5->setLastActive(23434353); - - return [ - [ - [$input1, $input2, $input3, $input4, $input5], - [ - [ - 'userid' => 'admin', - 'presence' => 'chat', - 'last_active' => 3234343424, - ], - [ - 'userid' => 'derp', - 'presence' => 'online', - 'last_active' => 23434353, - ], - [ - 'userid' => 'derpina', - 'presence' => 'chat', - 'last_active' => 23445645634, - ] - ] - ] - ]; - } - - /** - * @dataProvider presenceIfExitsProvider - * Test setting the presence if it doesn't exits. - * @param PresenceEntity[] $inputs - * @param array $expected - */ - public function testSetPresenceIfExists($inputs, $expected) - { - foreach ($inputs as $input) { - $this->mapper->setPresence($input); - } - $result = $this->fetchAllAsArray(); - - - $this->assertArrayDbResultsEqual($expected, $result, ['userid', 'presence', 'last_active']); - } - - public function getPresenceProvider() - { - $input1 = new PresenceEntity(); - $input1->setPresence('online'); - $input1->setUserid('admin'); - $input1->setLastActive(23434); - - $input2 = new PresenceEntity(); - $input2->setPresence('unavailable'); - $input2->setUserid('derp'); - $input2->setLastActive(23434475); - - - $input3 = new PresenceEntity(); - $input3->setPresence('chat'); - $input3->setUserid('derpina'); - $input3->setLastActive(23445645634); - - $input4 = new PresenceEntity(); - $input4->setPresence('chat'); - $input4->setUserid('admin'); - $input4->setLastActive(3234343424); - - $input5 = new PresenceEntity(); - $input5->setPresence('online'); - $input5->setUserid('derp'); - $input5->setLastActive(23434353); - - $expected1 = new PresenceEntity(); - $expected1->setUserid('derp'); - $expected1->setPresence('online'); - $expected1->setLastActive(23434353); - $expected1->setTo('admin', 'localhost/internal'); - $expected1->setFrom('derp', 'localhost/internal'); - - $expected2 = new PresenceEntity(); - $expected2->setUserid('derpina'); - $expected2->setPresence('chat'); - $expected2->setLastActive(23445645634); - $expected2->setTo('admin', 'localhost/internal'); - $expected2->setFrom('derpina', 'localhost/internal'); - - $expected3 = new PresenceEntity(); - $expected3->setUserid('admin'); - $expected3->setPresence('chat'); - $expected3->setLastActive(3234343424); - $expected3->setTo('admin', 'localhost/internal'); - $expected3->setFrom('admin', 'localhost/internal'); - - return [ - [ - [$input1, $input2, $input3, $input4, $input5], - [$expected1, $expected2, $expected3] - ] - ]; - } - - /** - * @dataProvider getPresenceProvider - * @param $inputs - * @param $expected - */ - public function testGetPresence($inputs, $expected) - { - foreach ($inputs as $input) { - $this->mapper->setPresence($input); - } - - $result = $this->mapper->getPresences(); - - $this->assertObjectDbResultsEqual($expected, $result, ['userid', 'presence', 'lastActive', 'to', 'from']); - } - - public function getConnectedUsersProvider() - { - $input1 = new PresenceEntity(); - $input1->setPresence('online'); - $input1->setUserid('admin'); - $input1->setLastActive(23434); - - $input2 = new PresenceEntity(); - $input2->setPresence('unavailable'); - $input2->setUserid('derp'); - $input2->setLastActive(23434475); - - $input3 = new PresenceEntity(); - $input3->setPresence('chat'); - $input3->setUserid('derpina'); - $input3->setLastActive(23445645634); - - $input4 = new PresenceEntity(); - $input4->setPresence('chat'); - $input4->setUserid('admin'); - $input4->setLastActive(3234343424); - - $input5 = new PresenceEntity(); - $input5->setPresence('online'); - $input5->setUserid('derp'); - $input5->setLastActive(23434353); - - $input6 = new PresenceEntity(); - $input6->setPresence('unavailable'); - $input6->setUserid('herp'); - $input6->setLastActive(123); - - return [ - [ - [$input1, $input2, $input3, $input4, $input5, $input6], - ['derp', 'derpina'] - ] - ]; - } - - /** - * @dataProvider getConnectedUsersProvider - */ - public function testGetConnectedUsers($inputs, $expected) - { - $this->setupContactsStoreAPI(); - foreach ($inputs as $input) { - $this->mapper->setPresence($input); - } - - $result = $this->mapper->getConnectedUsers(); - - $this->assertCount(count($expected), $result); - sort($expected); - sort($result); - $this->assertEquals($expected, $result); - } - - public function testGetConnectedUsersIfUserHasNot() - { - $this->setValueOfPrivateProperty($this->mapper, 'connectedUsers', []); - $this->setupContactsStoreAPI(); - if (!Application::contactsStoreApiSupported()) { - $this->markTestSkipped(); - } - - $group = \OC::$server->getGroupManager()->createGroup('group1'); - $group->addUser(\OC::$server->getUserManager()->get('derp')); - - $group2 = \OC::$server->getGroupManager()->createGroup('group2'); - $group2->addUser(\OC::$server->getUserManager()->get('autotest')); - $group2->addUser(\OC::$server->getUserManager()->get('foo')); - $group2->addUser(\OC::$server->getUserManager()->get('admin')); - - \OC::$server->getConfig()->setAppValue('core', 'shareapi_only_share_with_group_members', 'yes'); - - $input1 = new PresenceEntity(); - $input1->setPresence('online'); - $input1->setUserid('foo'); - $input1->setLastActive(23434475); - - $input2 = new PresenceEntity(); - $input2->setPresence('online'); - $input2->setUserid('derp'); - $input2->setLastActive(23434475); - - $this->mapper->setPresence($input1); - $this->mapper->setPresence($input2); - - $expected = ['foo']; - - $result = $this->mapper->getConnectedUsers(); - - $this->assertCount(count($expected), $result); - sort($expected); - sort($result); - $this->assertEquals($expected, $result); - - \OC::$server->getConfig()->setAppValue('core', 'shareapi_only_share_with_group_members', 'no'); - - $group->removeUser(\OC::$server->getUserManager()->get('derp')); - $group->delete(); - $group2->removeUser(\OC::$server->getUserManager()->get('autotest')); - $group2->removeUser(\OC::$server->getUserManager()->get('admin')); - $group2->delete(); - } - - public function updatePresenceProvider() - { - $input1 = new PresenceEntity(); - $input1->setPresence('online'); - $input1->setUserid('admin'); - $input1->setLastActive(1000); - - $input2 = new PresenceEntity(); - $input2->setPresence('online'); - $input2->setUserid('foo'); - $input2->setLastActive(1000); - - $input3 = new PresenceEntity(); // will go offline - $input3->setPresence('xa'); - $input3->setUserid('derp'); - $input3->setLastActive(600); - - $input4 = new PresenceEntity(); // will go offline - $input4->setPresence('chat'); - $input4->setUserid('derpina'); - $input4->setLastActive(400); - - $expStanza1 = new PresenceEntity(); - $expStanza1->setPresence('unavailable'); - $expStanza1->setFrom('derp', 'localhost/internal'); - $expStanza1->setTo('admin', 'localhost/internal'); - - $expStanza2 = new PresenceEntity(); - $expStanza2->setPresence('unavailable'); - $expStanza2->setFrom('derpina', 'localhost/internal'); - $expStanza2->setTo('admin', 'localhost/internal'); - - return [ - [ - [$input1, $input2, $input3, $input4], - [ - [ - 'userid' => 'admin', - 'presence' => 'online', - 'last_active' => '1000' - ], - [ - 'userid' => 'foo', - 'presence' => 'online', - 'last_active' => '1000' - ], - [ - 'userid' => 'derp', - 'presence' => 'xa', - 'last_active' => '600' - ], - [ - 'userid' => 'derpina', - 'presence' => 'chat', - 'last_active' => '400' - ] - ], - ['foo', 'derp', 'derpina'], - [$expStanza1, $expStanza2], - 2, - [ - [ - "from" => 'derp', - "to" => "foo", - "stanza" => '<presence type="unavailable" from="derp" to="foo" xmlns="jabber:client"/>' - ], - [ - "from" => 'derpina', - "to" => "foo", - "stanza" => '<presence type="unavailable" from="derpina" to="foo" xmlns="jabber:client"/>' - ] - ] - ] - ]; - } - - public function setActiveProvider() - { - $input1 = new PresenceEntity(); - $input1->setPresence('online'); - $input1->setUserid('admin'); - $input1->setLastActive(1000); - - $input2 = new PresenceEntity(); - $input2->setPresence('unavailable'); - $input2->setUserid('foo'); - $input2->setLastActive(1000); - - $input3 = new PresenceEntity(); // will go offline - $input3->setPresence('xa'); - $input3->setUserid('derp'); - $input3->setLastActive(600); - - $input4 = new PresenceEntity(); // will go offline - $input4->setPresence('chat'); - $input4->setUserid('derpina'); - $input4->setLastActive(400); - - return [ - [ - [$input1, $input2, $input3, $input4], - [ - [ - 'userid' => 'admin', - 'presence' => 'online', - 'last_active' => '1010', - ], - [ - 'userid' => 'foo', - 'presence' => 'unavailable', - 'last_active' => '1000', - ], - [ - 'userid' => 'derp', - 'presence' => 'xa', - 'last_active' => '1020', - ], - [ - 'userid' => 'derpina', - 'presence' => 'chat', - 'last_active' => '400', - ], - ] - ] - ]; - } - - public function deletePresenceProvider() - { - $input1 = new PresenceEntity(); - $input1->setPresence('online'); - $input1->setUserid('admin'); - $input1->setLastActive(1000); - - $input2 = new PresenceEntity(); - $input2->setPresence('unavailable'); - $input2->setUserid('foo'); - $input2->setLastActive(1000); - - $input3 = new PresenceEntity(); - $input3->setPresence('xa'); - $input3->setUserid('derp'); - $input3->setLastActive(600); - - $input4 = new PresenceEntity(); - $input4->setPresence('chat'); - $input4->setUserid('derpina'); - $input4->setLastActive(400); - - return [ - [ - [$input1, $input2, $input3, $input4], - [ - [ - 'userid' => 'foo', - 'presence' => 'unavailable', - 'last_active' => '1000', - ], - [ - 'userid' => 'derp', - 'presence' => 'xa', - 'last_active' => '600', - ], - [ - 'userid' => 'derpina', - 'presence' => 'chat', - 'last_active' => '400', - ], - ] - ] - ]; - } - - /** - * @dataProvider deletePresenceProvider - */ - - public function testDeletePresence($inputs, $expected) - { - foreach ($inputs as $input) { - $this->mapper->setPresence($input); - } - - $this->mapper->deletePresence('admin'); - - $result = $this->fetchAllAsArray(); - - $this->assertArrayDbResultsEqual($expected, $result, ['userid', 'last_active', 'presence']); - } -} diff --git a/tests/Integration/Db/PresenceTest.php b/tests/Integration/Db/PresenceTest.php deleted file mode 100644 index 25fe2d0..0000000 --- a/tests/Integration/Db/PresenceTest.php +++ /dev/null @@ -1,146 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Integration\Db; - -use Sabre\Xml\Reader; -use Sabre\Xml\Writer; -use Sabre\Xml\LibXMLException; -use Sabre\Xml\ParseException; -use OCA\OJSXC\Tests\Utility\TestCase; -use OCA\OJSXC\Db\Presence; - -class PresenceTest extends TestCase -{ - private function generateFactoryData($xml, $from, $to, $presence, $userId) - { - $reader = new Reader(); - $reader->xml($xml); - $reader->elementMap = [ - '{jabber:client}presence' => function (Reader $reader) use ($userId) { - return Presence::createFromXml($reader, $userId); - } - ]; - - $expected = new Presence(); - $expected->setFrom($from); - $expected->setTo($to); - $expected->setPresence($presence); - $expected->setUserid($userId); - - return [ - $reader, - $userId, - $expected - ]; - } - - public function factoryProvider() - { - return [ - $this->generateFactoryData("<presence xmlns='jabber:client' type='unavailable'/>", null, null, 'unavailable', 'admin'), - $this->generateFactoryData("<presence xmlns='jabber:client' type='unavailable'></presence>", null, null, 'unavailable', 'admin'), - $this->generateFactoryData("<presence xmlns='jabber:client'/>", null, null, 'online', 'admin'), - $this->generateFactoryData("<presence xmlns='jabber:client'><test>ack</test></presence>", null, null, 'online', 'admin'), - $this->generateFactoryData("<presence xmlns='jabber:client'></presence>", null, null, 'online', 'admin'), - $this->generateFactoryData("<presence xmlns='jabber:client'><show>chat</show></presence>", null, null, 'chat', 'admin'), - $this->generateFactoryData("<presence xmlns='jabber:client'><show>dnd</show></presence>", null, null, 'dnd', 'admin'), - $this->generateFactoryData("<presence xmlns='jabber:client'><show>ea</show></presence>", null, null, 'ea', 'admin'), - $this->generateFactoryData("<presence xmlns='jabber:client'><show>away</show></presence>", null, null, 'away', 'admin'), - $this->generateFactoryData("<presence xmlns='jabber:client'><show>online</show></presence>", null, null, 'online', 'admin'), - ]; - } - - - /** - * @dataProvider factoryProvider - */ - public function testFactory($reader, $userid, Presence $expectedElement) - { - $result = $reader->parse(); - $result = $result['value']; - $this->assertEquals($expectedElement->getUnSanitizedTo(), $result->getTo()); - $this->assertEquals($expectedElement->getUnSanitizedFrom(), $result->getFrom()); - $this->assertEquals($expectedElement->getPresence(), $result->getPresence()); - $this->assertEquals($expectedElement->getUserid(), $result->getUserid()); - } - - - private function generateSerializeData($to, $from, $presence, $expected) - { - $writer = new Writer(); - $writer->openMemory(); - $writer->startElement('body'); - $writer->writeAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); - - $presenceEntity = new Presence(); - $presenceEntity->setPresence($presence); - $presenceEntity->setFrom($from); - $presenceEntity->setTo($to); - - return [ - $writer, - $presenceEntity, - $expected, - $to, - $from, - $presence - ]; - } - public function serializeProvider() - { - return [ - $this->generateSerializeData( - 'admin', - 'derp', - 'chat', - '<body xmlns="http://jabber.org/protocol/httpbind"><presence from="derp" to="admin" xmlns="jabber:client"><show>chat</show></presence></body>' - ), - $this->generateSerializeData( - 'admin', - 'derp', - 'online', - '<body xmlns="http://jabber.org/protocol/httpbind"><presence from="derp" to="admin" xmlns="jabber:client" /></body>' - ), - $this->generateSerializeData( - 'admin', - 'derp', - 'away', - '<body xmlns="http://jabber.org/protocol/httpbind"><presence from="derp" to="admin" xmlns="jabber:client"><show>away</show></presence></body>' - ), - $this->generateSerializeData( - 'admin', - 'derp', - 'unavailable', - '<body xmlns="http://jabber.org/protocol/httpbind"><presence from="derp" to="admin" xmlns="jabber:client" type="unavailable"/></body>' - ), - $this->generateSerializeData( - 'admin', - 'derp', - 'ea', - '<body xmlns="http://jabber.org/protocol/httpbind"><presence from="derp" to="admin" xmlns="jabber:client"><show>ea</show></presence></body>' - ), - $this->generateSerializeData( - 'admin', - 'derp', - 'dnd', - '<body xmlns="http://jabber.org/protocol/httpbind"><presence from="derp" to="admin" xmlns="jabber:client"><show>dnd</show></presence></body>' - ), - - ]; - } - - /** - * @dataProvider serializeProvider - */ - public function testSerialize(Writer $writer, Presence $presenceEntity, $expected, $to, $from, $presence) - { - $writer->write($presenceEntity); - $writer->endElement(); - $result = $writer->outputMemory(); - - $this->assertEquals($to, $presenceEntity->getUnSanitizedTo()); - $this->assertEquals($from, $presenceEntity->getUnSanitizedFrom()); - $this->assertEquals($presence, $presenceEntity->getPresence()); - $this->assertSabreXmlEqualsXml($expected, $result); - } -} diff --git a/tests/Integration/Db/StanzaMapperTest.php b/tests/Integration/Db/StanzaMapperTest.php deleted file mode 100644 index 69cdd26..0000000 --- a/tests/Integration/Db/StanzaMapperTest.php +++ /dev/null @@ -1,144 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Integration\Db; - -use OCA\OJSXC\Tests\Utility\MapperTestUtility; -use OCP\AppFramework\Db\DoesNotExistException; -use OCA\OJSXC\Db\Stanza; - -/** - * @group DB - */ -class StanzaMapperTest extends MapperTestUtility -{ - - /** - * @var StanzaMapper - */ - protected $mapper; - - protected function setUp(): void - { - $this->entityName = 'OCA\OJSXC\Db\Stanza'; - $this->mapperName = 'StanzaMapper'; - parent::setUp(); - } - - public function insertProvider() - { - return [ - [ - 'john', - 'thomas', - 'abcd' - ] - ]; - } - - /** - * @dataProvider insertProvider - */ - public function testInsert($from, $to, $data) - { - $stanza = new Stanza(); - $stanza->setFrom($from); - $stanza->setTo($to); - $stanza->setStanza($data); - - $this->assertEquals($stanza->getUnSanitizedFrom(), $from); - $this->assertEquals($stanza->getUnSanitizedTo(), $to); - $this->assertEquals($stanza->getStanza(), $data); - - $this->mapper->insert($stanza); - - $result = $this->fetchAll(); - - $this->assertCount(1, $result); - $this->assertEquals($stanza->getUnSanitizedFrom(), $result[0]->getFrom()); - $this->assertEquals($stanza->getUnSanitizedTo(), $result[0]->getTo()); - $this->assertEquals($stanza->getStanza(), $result[0]->getStanza()); - } - - public function testFindByToNotFound() - { - $this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class); - - $this->mapper->findByTo('test'); - } - - public function testFindByToNotFound2() - { - $this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class); - - $stanza = new Stanza(); - $stanza->setFrom('john@localhost'); - $stanza->setTo('john@localhost'); - $stanza->setStanza('abcd'); - $this->mapper->insert($stanza); - - $this->mapper->findByTo('test'); - } - - public function testFindByToFound() - { - $stanza1 = new Stanza(); - $stanza1->setFrom('jan'); - $stanza1->setTo('john'); - $stanza1->setStanza('abcd1'); - $this->mapper->insert($stanza1); - - $stanza2 = new Stanza(); - $stanza2->setFrom('thomas'); - $stanza2->setTo('jan'); - $stanza2->setStanza('abcd2'); - $this->mapper->insert($stanza2); - - - // check if two elements are inserted - $result = $this->fetchAll(); - $this->assertCount(2, $result); - - // check findByTo - $result = $this->mapper->findByTo('john'); - $this->assertCount(1, $result); - $this->assertEquals($stanza1->getStanza(), $result[0]->getStanza()); - - // check if element is deleted - $result = $this->fetchAll(); - $this->assertCount(1, $result); - $this->assertEquals($stanza2->getUnSanitizedFrom(), $result[0]->getFrom()); - $this->assertEquals($stanza2->getUnSanitizedTo(), $result[0]->getTo()); - $this->assertEquals($stanza2->getStanza(), $result[0]->getStanza()); - } - - - public function testDeleteByTo() - { - $stanza1 = new Stanza(); - $stanza1->setFrom('jan'); - $stanza1->setTo('john'); - $stanza1->setStanza('abcd1'); - $this->mapper->insert($stanza1); - - $stanza2 = new Stanza(); - $stanza2->setFrom('thomas'); - $stanza2->setTo('jan'); - $stanza2->setStanza('abcd2'); - $this->mapper->insert($stanza2); - - // check if two elements are inserted - $result = $this->fetchAllAsArray(); - $this->assertArrayDbResultsEqual([ - ['from' => 'jan', 'to' => 'john', 'stanza' => 'abcd1'], - ['from' => 'thomas', 'to' => 'jan', 'stanza' => 'abcd2'] - ], $result, ['from', 'to', 'stanza']); - - - $this->mapper->deleteByTo('jan'); - - $result = $this->fetchAllAsArray(); - $this->assertArrayDbResultsEqual([ - ['from' => 'jan', 'to' => 'john', 'stanza' => 'abcd1'] - ], $result, ['from', 'to', 'stanza']); - } -} diff --git a/tests/Integration/DbLockTest.php b/tests/Integration/DbLockTest.php deleted file mode 100644 index ab403b9..0000000 --- a/tests/Integration/DbLockTest.php +++ /dev/null @@ -1,95 +0,0 @@ -<?php -namespace OCA\OJSXC\Tests\Integration; - -use OCP\AppFramework\Db\DoesNotExistException; -use PHPUnit\Framework\TestCase; -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\DbLock; - -/** - * @group DB - */ -class DbLockTest extends TestCase -{ - - /** - * @var \OCA\OJSXC\DbLock - */ - private $dbLock; - - /** - * @var \OCA\OJSXC\DbLock - */ - private $dbLock2; - - /** - * @var \OCP\IDb - */ - private $con; - - - /** - * @var \OCP\AppFramework\IAppContainer - */ - private $container; - - public function setUp(): void - { - parent::setUp(); - $app = new Application(); - $this->container = $app->getContainer(); - $this->con = $this->container->getServer()->getDatabaseConnection(); - $this->con->executeQuery("DELETE FROM `*PREFIX*preferences` WHERE `appid`='ojsxc' AND `configkey`='longpolling'"); - } - - /** - * Tests the setLock and stillLocked function by setting up and lock - * and then setting a new lock. - */ - public function testLock() - { - $this->dbLock = new DbLock( - 'john', - $this->container->getServer()->getConfig(), - $this->container->getServer()->getDatabaseConnection() - ); - $this->dbLock->setLock(); - $result = $this->fetchLocks(); - $this->assertCount(1, $result); - $this->assertEquals($result[0]['userid'], 'john'); - $this->assertEquals($result[0]['appid'], 'ojsxc'); - $this->assertEquals($result[0]['configkey'], 'longpolling'); - $this->assertTrue($this->dbLock->stillLocked()); - - $this->dbLock2 = new DbLock( - 'john', - $this->container->getServer()->getConfig(), - $this->container->getServer()->getDatabaseConnection() - ); // simulate new lock/request - $this->dbLock2->setLock(); - - $this->assertFalse($this->dbLock->stillLocked()); - $this->assertTrue($this->dbLock2->stillLocked()); - - $result = $this->fetchLocks(); - $this->assertCount(1, $result); - $this->assertEquals($result[0]['userid'], 'john'); - $this->assertEquals($result[0]['appid'], 'ojsxc'); - $this->assertEquals($result[0]['configkey'], 'longpolling'); - $this->assertTrue($this->dbLock2->stillLocked()); - } - - private function fetchLocks() - { - $stmt = $this->con->executeQuery("SELECT * FROM `*PREFIX*preferences` WHERE `appid`='ojsxc' AND `configkey`='longpolling'"); - - $reuslt = []; - - while ($row = $stmt->fetch()) { - $result[] = $row; - } - - - return $result; - } -} diff --git a/tests/Integration/MemLockTest.php b/tests/Integration/MemLockTest.php deleted file mode 100644 index e8e0a80..0000000 --- a/tests/Integration/MemLockTest.php +++ /dev/null @@ -1,87 +0,0 @@ -<?php -namespace OCA\OJSXC\Tests\Integration; - -use OCP\AppFramework\Db\DoesNotExistException; -use PHPUnit\Framework\TestCase; -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\MemLock; - -//function time() { -// return DbLockTest::$time; -//} - -/** - * @group DB - */ -class MemLockTest extends TestCase -{ - - /** - * @var \OCA\OJSXC\MemLock - */ - private $memLock; - - /** - * @var \OCA\OJSXC\MemLock - */ - private $memLock2; - - /** - * @var \OCP\AppFramework\IAppContainer - */ - private $container; - - /** - * @var \OCP\ICache - */ - private $memCache; - - public static $time; - - public function setUp(): void - { - parent::setUp(); - $app = new Application(); - $this->container = $app->getContainer(); - } - - /** - * Tests the setLock and stillLocked function by setting up and lock - * and then setting a new lock. - */ - public function testLock() - { - $cache = $this->container->getServer()->getMemCacheFactory(); - if ($cache->isAvailable()) { - $this->memCache = $cache->create('ojsxc'); - } else { - $this->markTestSkipped(); - return; - } - - $this->memLock = new MemLock( - 'john', - $this->memCache - ); - $this->memLock->setLock(); - $this->assertTrue($this->memLock->stillLocked()); - - - $result = $this->fetchLock(); - - $this->memLock2 = new MemLock( - 'john', - $this->memCache - ); // simulate new lock/request - $this->memLock2->setLock(); - - $this->assertFalse($this->memLock->stillLocked()); - $this->assertTrue($this->memLock2->stillLocked()); - $result = $this->fetchLock(); - } - - private function fetchLock() - { - return $this->memCache->get('-john-ojxsc-lock'); - } -} diff --git a/tests/Integration/RosterPushTest.php b/tests/Integration/RosterPushTest.php deleted file mode 100644 index c9c5fe9..0000000 --- a/tests/Integration/RosterPushTest.php +++ /dev/null @@ -1,174 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Integration; - -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\Db\IQRosterPushMapper; -use OCP\Contacts\ContactsMenu\IContactsStore; -use OCP\IConfig; -use OCP\IDBConnection; -use OCP\IGroupManager; -use OCP\IUserManager; -use OCP\IUserSession; -use PHPUnit\Framework\TestCase; -use PHPUnit\Framework\MockObject\MockObject; - -class RosterPushTest extends TestCase -{ - - /** - * @var RosterPush - */ - private $rosterPush; - - /** - * @var IUserManager - */ - private $userManager; - - /** - * @var IGroupManager - */ - private $groupManager; - - /** - * @var IUserSession - */ - private $userSession; - - /** - * @var MockObject | IQRosterPushMapper - */ - private $iqRosterPushMapper; - - /** - * @var IDBConnection - */ - private $dbConnection; - - /** - * @var IUserProvider - */ - private $userProvider; - - /** - * @var IConfig - */ - private $config; - - /** - * @var MockObject | IContactsStore - */ - private $contactsStore; - - public function setUp(): void - { - if (!Application::contactsStoreApiSupported()) { - $this->markTestSkipped(); - return; - } - - $this->userManager = \OC::$server->getUserManager(); - $this->groupManager = \OC::$server->getGroupManager(); - $this->userSession = \OC::$server->getUserSession(); - $this->iqRosterPushMapper = $this->getMockBuilder(IQRosterPushMapper::class)->disableOriginalConstructor()->getMock(); - $this->dbConnection = \OC::$server->getDatabaseConnection(); - $this->config = \OC::$server->getConfig(); - $this->contactsStore = $this->getMockBuilder(IContactsStore::class)->disableOriginalConstructor()->getMock(); - - $this->userProvider = new ContactsStoreUserProvider( - $this->contactsStore, - $this->userSession, - $this->userManager, - $this->groupManager, - $this->config - ); - - $this->rosterPush = new RosterPush( - $this->userManager, - $this->userSession, - 'localhost', - $this->iqRosterPushMapper, - $this->dbConnection, - $this->userProvider - ); - - foreach (\OC::$server->getUserManager()->search('') as $user) { - $user->delete(); - } - foreach (\OC::$server->getGroupManager()->search('') as $group) { - $group->delete(); - } - } - - public function testRemoveRosterItemForUsersInGroup() - { - $group1 = $this->groupManager->createGroup('group1'); - $group2 = $this->groupManager->createGroup('group2'); - $group3 = $this->groupManager->createGroup('group3'); - $user1 = $this->userManager->createUser('user1', 'user1'); - $user2 = $this->userManager->createUser('user2', 'user2'); - $user3 = $this->userManager->createUser('user3', 'user3'); - $user4 = $this->userManager->createUser('user4', 'user4'); - - $group1->addUser($user1); - $group1->addUser($user2); - $group1->addUser($user3); - $group2->addUser($user1); - $group2->addUser($user2); - $group3->addUser($user4); - - // remove $user1 from $group1 - // when no special settings are set this should result in no rosterMessages - $this->iqRosterPushMapper->expects($this->never())->method('insert'); - $this->contactsStore->expects($this->at(0)) - ->method('findOne') - ->with($user2, 0, 'user1') - ->willReturn([$user2]); - $this->contactsStore->expects($this->at(1)) - ->method('findOne') - ->with($user3, 0, 'user1') - ->willReturn([$user3]); - $this->rosterPush->removeRosterItemForUsersInGroup($group1, 'user1'); - } - public function testRemoveRosterItemForUsersInGroupOwnGroups() - { - $group1 = $this->groupManager->createGroup('group1'); - $group2 = $this->groupManager->createGroup('group2'); - $group3 = $this->groupManager->createGroup('group3'); - $user1 = $this->userManager->createUser('user1', 'user1'); - $user2 = $this->userManager->createUser('user2', 'user2'); - $user3 = $this->userManager->createUser('user3', 'user3'); - $user4 = $this->userManager->createUser('user4', 'user4'); - - $group1->addUser($user1); - $group1->addUser($user2); - $group1->addUser($user3); - $group2->addUser($user1); - $group2->addUser($user2); - $group3->addUser($user4); - - $this->config->setAppValue('core', 'shareapi_only_share_with_group_members', 'yes'); - - // remove $user1 from $group1 - // users can only chat with users in their groups - // $user2 should still be reachable by $group2 - // $user3 should be become unreachable - // for $user4 nothing changes - $this->iqRosterPushMapper->expects($this->once())->method('insert'); - - $this->contactsStore->expects($this->at(0)) - ->method('findOne') - ->with($user2, 0, 'user1') - ->willReturn([$user2]); - - $this->contactsStore->expects($this->at(1)) - ->method('findOne') - ->with($user3, 0, 'user1') - ->willReturn(null); - - $this->rosterPush->removeRosterItemForUsersInGroup($group1, 'user1'); - - $this->config->setAppValue('core', 'shareapi_only_share_with_group_members', 'no'); - } -} diff --git a/tests/Integration/UserTest.php b/tests/Integration/UserTest.php deleted file mode 100644 index cf61cc7..0000000 --- a/tests/Integration/UserTest.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php -namespace OCA\OJSXC\Tests\Integration; - -use OCA\OJSXC\User; -use PHPUnit\Framework\TestCase; - -class UserTest extends TestCase -{ - public function test() - { - $user1 = new User(" test @ 'abc", 'Test123', null); - - $this->assertEquals($user1->getFullName(), 'Test123'); - $this->assertEquals($user1->getUid(), '_ojsxc_esc_space_test_ojsxc_esc_space__ojsxc_esc_at__ojsxc_esc_space__ojsxc_squote_space_abc'); - $user1->setUid('test1'); - $user1->setFullName('test2'); - $this->assertEquals($user1->getUid(), 'test1'); - $this->assertEquals($user1->getFullName(), 'test2'); - } -} diff --git a/tests/Utility/MapperTestUtility.php b/tests/Utility/MapperTestUtility.php deleted file mode 100644 index ef07d03..0000000 --- a/tests/Utility/MapperTestUtility.php +++ /dev/null @@ -1,86 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Utility; - -use OCA\OJSXC\AppInfo\Application; - -/** - * @group DB - */ -class MapperTestUtility extends TestCase -{ - - /** - * @var \OCP\AppFramework\IAppContainer - */ - protected $container; - - protected $entityName; - - protected $mapperName; - - protected $host; - - protected $userId; - - protected function setUp(): void - { - parent::setUp(); - $app = new Application(); - $this->overwriteApplicationService($app, 'Host', 'localhost'); - $this->overwriteApplicationService($app, 'UserId', 'admin'); - $this->container = $app->getContainer(); - $this->mapper = $this->container[$this->mapperName]; - - $this->host = 'localhost'; - $this->userId = 'admin'; - - $con = $this->container->getServer()->getDatabaseConnection(); - $con->executeQuery('DELETE FROM ' . $this->mapper->getTableName()); - } - - protected function tearDown(): void - { - $con = $this->container->getServer()->getDatabaseConnection(); - $con->executeQuery('DELETE FROM ' . $this->mapper->getTableName()); - } - - protected function fetchAll() - { - $con = $this->container->getServer()->getDatabaseConnection(); - $stmt = $con->executeQuery('SELECT * FROM ' . $this->mapper->getTableName()); - $entities = []; - - while ($row = $stmt->fetch()) { - $entities[] = call_user_func($this->entityName . '::fromRow', $row); - ; - } - - $stmt->closeCursor(); - - return $entities; - } - - protected function fetchAllAsArray($tableName = null) - { - if (is_null($tableName)) { - $tableName = $this->mapper->getTableName(); - } else { - } - $con = $this->container->getServer()->getDatabaseConnection(); - $stmt = $con->executeQuery('SELECT * FROM ' . $tableName); - - $result = []; - while ($row = $stmt->fetch()) { - $result[] = $row; - } - $stmt->closeCursor(); - - return $result; - } - - public function getLastInsertedId() - { - return $this->container->getServer()->getDatabaseConnection()->lastInsertId(); - } -} diff --git a/tests/Utility/TestCase.php b/tests/Utility/TestCase.php deleted file mode 100644 index a5caa8e..0000000 --- a/tests/Utility/TestCase.php +++ /dev/null @@ -1,92 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Utility; - -use OCA\OJSXC\AppInfo\Application; -use OCP\AppFramework\Db\Entity; -use Sabre\Xml\Service; -use PHPUnit\Framework\TestCase as CoreTestCase; - -class TestCase extends CoreTestCase -{ - public static function assertSabreXmlEqualsXml($expected, $actual) - { - $service = new Service(); - - $parsedExpected = $service->parse("<?xml version=\"1.0\" encoding=\"utf-8\"?><unit-wrapper>" . $expected . "</unit-wrapper>"); - $parsedActual = $service->parse("<?xml version=\"1.0\" encoding=\"utf-8\"?><unit-wrapper>" . $actual . "</unit-wrapper>"); - - self::assertEquals($parsedExpected, $parsedActual, 'Failed asserting that two XML strings are equal.'); - } - - /** - * @param Entity[] $expected - * @param Entity[] $actual - * @param array $fields Use camelCase for this instead of snake_case! - */ - public static function assertObjectDbResultsEqual($expected, $actual, array $fields) - { - $expectedArray = []; - $actualArray = []; - - foreach ($expected as $exp) { - $expectedArray[] = (array) $exp; - } - - foreach ($actual as $act) { - $actualArray[] = (array) $act; - } - - self::assertArrayDbResultsEqual($expectedArray, $actualArray, $fields); - } - - public static function assertArrayDbResultsEqual(array $expected, array $actual, array $fields) - { - $expectedFiltered = []; - $actualFiltered = []; - - foreach ($expected as $exp) { - $r = []; - foreach ($fields as $field) { - $r[$field] = $exp[$field]; - } - $expectedFiltered[] = $r; - } - - foreach ($actual as $exp) { - $r = []; - foreach ($fields as $field) { - $r[$field] = $exp[$field]; - } - $actualFiltered[] = $r; - } - - sort($actualFiltered); - sort($expectedFiltered); - - self::assertCount(count($expected), $actual); - self::assertEquals($expectedFiltered, $actualFiltered); - } - - public function overwriteApplicationService(Application $app, $name, $newService) - { - $app->getContainer()->registerService($name, function () use ($newService) { - return $newService; - }); - } - - /** - * @brief this function is needed to reset some private static propertires - * which ar used for e.g. caches. - * @param $name - * @param $newValue - */ - public function setValueOfPrivateProperty($obj, $name, $newValue) - { - $refl = new \ReflectionObject($obj); - $p = $refl->getProperty($name); - $p->setAccessible(true); - $p->setValue($obj, $newValue); - $p->setAccessible(false); - } -} diff --git a/tests/unit/HooksTest.php b/tests/unit/HooksTest.php deleted file mode 100644 index a0c4da8..0000000 --- a/tests/unit/HooksTest.php +++ /dev/null @@ -1,195 +0,0 @@ -<?php - - -namespace OCA\OJSXC\Tests\Unit; - -use OCA\OJSXC\AppInfo\Application; -use OCA\OJSXC\Db\Presence; -use OCA\OJSXC\Db\PresenceMapper; -use OCA\OJSXC\Db\StanzaMapper; -use OCA\OJSXC\Hooks; -use OCA\OJSXC\RosterPush; -use OCP\IGroup; -use OCP\IGroupManager; -use OCP\IUser; -use OCP\IUserManager; -use OCP\IUserSession; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class HooksTest extends TestCase -{ - - /** - * @var Hooks $hooks - */ - private $hooks; - - /** - * @var MockObject - */ - private $userManager; - - /** - * @var MockObject - */ - private $userSession; - - /** - * @var MockObject - */ - private $rosterPush; - - /** - * @var MockObject - */ - private $presenceMapper; - - /** - * @var MockObject - */ - private $stanzaMapper; - - /** - * @var MockObject - */ - private $groupManager; - - public function setUp(): void - { - /** @var IUserManager */ - $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock(); - /** @var IUserSession */ - $this->userSession = $this->getMockBuilder(IUserSession::class)->getMock(); - /** @var RosterPush */ - $this->rosterPush = $this->getMockBuilder(RosterPush::class)->disableOriginalConstructor()->getMock(); - /** @var PresenceMapper */ - $this->presenceMapper = $this->getMockBuilder(PresenceMapper::class)->disableOriginalConstructor()->getMock(); - /** @var StanzaMapper */ - $this->stanzaMapper = $this->getMockBuilder(StanzaMapper::class)->disableOriginalConstructor()->getMock(); - /** @var IGroupManager */ - $this->groupManager = $this->getMockBuilder(IGroupManager::class)->disableOriginalConstructor()->getMock(); - - $this->hooks = new Hooks( - $this->userManager, - $this->userSession, - $this->rosterPush, - $this->presenceMapper, - $this->stanzaMapper, - $this->groupManager - ); - } - - private function buildUser() - { - /** @var IUser */ - $user = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock(); - - return $user; - } - - public function testOnCreateUser() - { - $user = $this->buildUser(); - - $this->rosterPush->expects($this->once()) - ->method('createOrUpdateRosterItem') - ->with($user); - - $this->hooks->onCreateUser($user, 'abc'); - } - - public function testOnDeleteUser() - { - $user = $this->buildUser(); - - $user->expects($this->exactly(3)) - ->method('getUID') - ->willReturn('test'); - - $this->rosterPush->expects($this->once()) - ->method('removeRosterItem') - ->with('test'); - - $this->presenceMapper->expects($this->once()) - ->method('deletePresence') - ->with('test'); - - $this->stanzaMapper->expects($this->once()) - ->method('deleteByTo') - ->with('test'); - - $this->hooks->onDeleteUser($user); - } - - - public function testOnChangeUserEnabled() - { - $user = $this->buildUser(); - - $hooks = $this->getMockBuilder(Hooks::class)->disableOriginalConstructor()->setMethods(['onCreateUser'])->getMock(); - - $hooks->expects($this->once()) - ->method('onCreateUser') - ->with($user, ''); - - /** @var Hooks $hooks */ - $hooks->onChangeUser($user, 'enabled', 'true'); - } - - public function testOnChangeUserDisabled() - { - $user = $this->buildUser(); - - $hooks = $this->getMockBuilder(Hooks::class)->disableOriginalConstructor()->setMethods(['onDeleteUser'])->getMock(); - - $hooks->expects($this->once()) - ->method('onDeleteUser') - ->with($user); - - /** @var Hooks $hooks */ - $hooks->onChangeUser($user, 'enabled', 'false'); - } - - public function testOnChangeUserDisplayName() - { - $user = $this->buildUser(); - - $hooks = $this->getMockBuilder(Hooks::class)->disableOriginalConstructor()->setMethods(['onCreateUser'])->getMock(); - - $hooks->expects($this->once()) - ->method('onCreateUser') - ->with($user); - - /** @var Hooks $hooks */ - $hooks->onChangeUser($user, 'displayName', 'abc'); - } - - public function testOnAddUserToGroup() - { - $user = $this->buildUser(); - /** @var IGroup */ - $group = $this->getMockBuilder(IGroup::class)->disableOriginalConstructor()->getMock(); - - $this->rosterPush->expects($this->once())->method('createOrUpdateRosterItem')->with($user); - $this->rosterPush->expects($this->once())->method('addUserToGroup')->with($user, $group); - - $this->hooks->onAddUserToGroup($group, $user); - } - - public function testOnRemoveUserFromGroup() - { - $user = $this->buildUser(); - /** @var IGroup */ - $group = $this->getMockBuilder(IGroup::class)->disableOriginalConstructor()->getMock(); - - if (Application::contactsStoreApiSupported()) { - $user->expects($this->once())->method('getUID')->willReturn('uid1'); - $this->rosterPush->expects($this->once())->method('removeRosterItemForUsersInGroup')->with($group, 'uid1'); - } - - $this->rosterPush->expects($this->once())->method('removeUserFromGroup')->with($user, $group); - - $this->hooks->onRemoveUserFromGroup($group, $user); - } -} diff --git a/tests/unit/NewContentContainerTest.php b/tests/unit/NewContentContainerTest.php deleted file mode 100644 index 8250fd1..0000000 --- a/tests/unit/NewContentContainerTest.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php - -namespace OCA\OJSXC; - -use OCA\OJSXC\Db\Message; -use OCA\OJSXC\Db\Stanza; -use PHPUnit\Framework\TestCase; - -class NewContentContainerTest extends TestCase -{ - - /** - * @var NewContentContainer $newContentContainer - */ - private $newContentContainer; - - public function setUp(): void - { - $this->newContentContainer = new NewContentContainer(); - } - - public function datatestProvider() - { - $stanza1 = new Stanza(); - $stanza1->setFrom('test@own.dev'); - $stanza1->setTo('adsffdsst@own.dev'); - - $stanza2 = new Message(); - $stanza2->setFrom('test@own.dev'); - $stanza2->setTo('addsf@own.dev'); - $stanza2->setType('chat'); - $stanza2->setValue('abc'); - return [ - [ - [$stanza1, $stanza2], - 2 - ] - ]; - } - - /** - * @dataProvider datatestProvider - */ - public function test($stanzas, $count) - { - foreach ($stanzas as $stanza) { - $this->newContentContainer->addStanza($stanza); - } - $this->assertEquals($count, $this->newContentContainer->getCount()); - - $result = $this->newContentContainer->getStanzas(); - $this->assertEquals(sort($stanzas), sort($result)); - } -} diff --git a/tests/unit/RosterPushTest.php b/tests/unit/RosterPushTest.php deleted file mode 100644 index bdd8d80..0000000 --- a/tests/unit/RosterPushTest.php +++ /dev/null @@ -1,266 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Unit; - -use OCA\OJSXC\Db\IQRosterPush; -use OCA\OJSXC\Db\IQRosterPushMapper; -use OCA\OJSXC\IUserProvider; -use OCA\OJSXC\RosterPush; -use OCP\IDBConnection; -use OCP\IUser; -use OCP\IUserManager; -use PHPUnit\Framework\TestCase; - -class RosterPushTest extends TestCase -{ - - /** - * @var RosterPush - */ - private $rosterPush; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject | IUserManager - */ - private $userManager; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject | IQRosterPushMapper - */ - private $iqRosterPushMapper; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject | IDBConnection - */ - private $db; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject | IUserProvider - */ - private $userProvider; - - public function setUp(): void - { - /** @var IUserManager */ - $this->userManager = $this->getMockBuilder(IUserManager::class) - ->disableOriginalConstructor()->getMock(); - - /** @var IQRosterPushMapper */ - $this->iqRosterPushMapper = $this->getMockBuilder(IQRosterPushMapper::class) - ->disableOriginalConstructor()->getMock(); - - /** @var IDbConnection */ - $this->db = $this->getMockBuilder(IDbConnection::class) - ->disableOriginalConstructor()->getMock(); - - /** @var IUserProvider */ - $this->userProvider = $this->getMockBuilder(IUserProvider::class)->disableOriginalConstructor()->getMock(); - - $this->rosterPush = new RosterPush( - $this->userManager, - $this->iqRosterPushMapper, - $this->db, - $this->userProvider - ); - } - - public function testRefreshRoster() - { - - /** @var \PHPUnit_Framework_MockObject_MockObject | RosterPush $rosterPush */ - $rosterPush = $this->getMockBuilder('OCA\OJSXC\RosterPush') - ->setConstructorArgs([$this->userManager, $this->iqRosterPushMapper, $this->db, $this->userProvider]) - ->setMethods(['createOrUpdateRosterItem', 'removeRosterItem'])->getMock(); - - $user1 = $this->getMockBuilder('OCP\IUser')->getMock(); - $user2 = $this->getMockBuilder('OCP\IUser')->getMock(); - $user3 = $this->getMockBuilder('OCP\IUser')->getMock(); - - $this->userManager->expects($this->once()) - ->method('search') - ->willReturn([$user1, $user2, $user3]); - - $rosterPush->expects($this->at(0)) - ->method('createOrUpdateRosterItem') - ->with($user1); - - $rosterPush->expects($this->at(1)) - ->method('createOrUpdateRosterItem') - ->with($user2); - - $rosterPush->expects($this->at(2)) - ->method('createOrUpdateRosterItem') - ->with($user3); - - $resultStatement = interface_exists('OCP\DB\IResult') ? $this->getMockBuilder('OCP\DB\IResult')->getMock() : $this->getMockBuilder('Doctrine\DBAL\Driver\ResultStatement')->getMock(); - - $resultStatement->expects($this->at(0)) - ->method('fetchAll') - ->willReturn([["id" => 10]]); - - $resultStatement->expects($this->at(1)) - ->method('fetchAll') - ->willReturn([ - ["uri" => 'Database:user1.vcf'], - ["uri" => 'Database:user2.vcf'], - ["uri" => 'Database:user3.vcf'], - ["uri" => 'Database:user4.vcf'] - ]); - - $this->db->expects($this->at(0)) - ->method('executeQuery') - ->with('SELECT `id` FROM `*PREFIX*addressbooks` WHERE `principaluri`=\'principals/system/system\' LIMIT 1') - ->willReturn($resultStatement); - - $this->db->expects($this->at(1)) - ->method('executeQuery') - ->with('SELECT `uri` FROM `*PREFIX*addressbookchanges` AS ac1 WHERE `addressbookid` = ? AND `operation` = 3 AND `id`=(SELECT MAX(id) FROM `*PREFIX*addressbookchanges` AS ac2 WHERE `uri`=ac1.uri)', [10]) - ->willReturn($resultStatement); - - - $rosterPush->expects($this->at(3)) - ->method('removeRosterItem') - ->with('user1'); - - $rosterPush->expects($this->at(4)) - ->method('removeRosterItem') - ->with('user2'); - - $rosterPush->expects($this->at(5)) - ->method('removeRosterItem') - ->with('user3'); - - $rosterPush->expects($this->at(6)) - ->method('removeRosterItem') - ->with('user4'); - - $stats = $rosterPush->refreshRoster(); - - $this->assertEquals($stats, ["removed" => 4, "updated" => 3]); - } - - public function testRefreshRosterThrowsDuringRemove() - { - - /** @var \PHPUnit_Framework_MockObject_MockObject | RosterPush $rosterPush */ - $rosterPush = $this->getMockBuilder('OCA\OJSXC\RosterPush') - ->setConstructorArgs([$this->userManager, $this->iqRosterPushMapper, $this->db, $this->userProvider]) - ->setMethods(['createOrUpdateRosterItem', 'removeRosterItem'])->getMock(); - - $user1 = $this->getMockBuilder('OCP\IUser')->getMock(); - $user2 = $this->getMockBuilder('OCP\IUser')->getMock(); - $user3 = $this->getMockBuilder('OCP\IUser')->getMock(); - - $this->userManager->expects($this->once()) - ->method('search') - ->willReturn([$user1, $user2, $user3]); - - $rosterPush->expects($this->at(0)) - ->method('createOrUpdateRosterItem') - ->with($user1); - - $rosterPush->expects($this->at(1)) - ->method('createOrUpdateRosterItem') - ->with($user2); - - $rosterPush->expects($this->at(2)) - ->method('createOrUpdateRosterItem') - ->with($user3); - - $this->db->expects($this->at(0)) - ->method('executeQuery') - ->with('SELECT `id` FROM `*PREFIX*addressbooks` WHERE `principaluri`=\'principals/system/system\' LIMIT 1') - ->willThrowException(new \Exception("A random exception")); - - $stats = $rosterPush->refreshRoster(); - - $this->assertEquals($stats, ["removed" => 0, "updated" => 3]); - } - - public function testRemoveRosterItem() - { - $user1 = $this->getMockBuilder('OCP\IUser')->getMock(); - $user1->expects($this->once()) - ->method('getUID') - ->willReturn('user1'); - $user2 = $this->getMockBuilder('OCP\IUser')->getMock(); - $user2->expects($this->exactly(2)) - ->method('getUID') - ->willReturn('user2'); - $user3 = $this->getMockBuilder('OCP\IUser')->getMock(); - $user3->expects($this->exactly(2)) - ->method('getUID') - ->willReturn('user3'); - - $this->userManager->expects($this->once()) - ->method('search') - ->willReturn([$user1, $user2, $user3]); - - $stanza1 = new IQRosterPush(); - $stanza1->setJid('user1'); - $stanza1->setSubscription('remove'); - $stanza1->setFrom(''); - $stanza1->setTo('user2'); - - $stanza2 = new IQRosterPush(); - $stanza2->setJid('user1'); - $stanza2->setSubscription('remove'); - $stanza2->setFrom(''); - $stanza2->setTo('user3'); - - $this->iqRosterPushMapper->expects($this->at(0)) - ->method('insert') - ->with($stanza1); - - $this->iqRosterPushMapper->expects($this->at(1)) - ->method('insert') - ->with($stanza2); - - $this->rosterPush->removeRosterItem('user1'); - } - - public function testCreateOrUpdateRosterItem() - { - $user1 = $this->getMockBuilder('OCP\IUser')->getMock(); - $user1->expects($this->exactly(6)) - ->method('getUID') - ->willReturn('user1'); - $user2 = $this->getMockBuilder('OCP\IUser')->getMock(); - $user2->expects($this->exactly(2)) - ->method('getUID') - ->willReturn('user2'); - $user3 = $this->getMockBuilder('OCP\IUser')->getMock(); - $user3->expects($this->exactly(2)) - ->method('getUID') - ->willReturn('user3'); - - $this->userProvider->expects($this->once()) - ->method('getAllUsersForUserByUID') - ->willReturn([$user1, $user2, $user3]); - - $stanza1 = new IQRosterPush(); - $stanza1->setJid('user1'); - $stanza1->setSubscription('both'); - $stanza1->setFrom(''); - $stanza1->setTo('user2'); - - $stanza2 = new IQRosterPush(); - $stanza2->setJid('user1'); - $stanza2->setSubscription('both'); - $stanza2->setFrom(''); - $stanza2->setTo('user3'); - - $this->iqRosterPushMapper->expects($this->at(0)) - ->method('insert') - ->with($stanza1); - - $this->iqRosterPushMapper->expects($this->at(1)) - ->method('insert') - ->with($stanza2); - - /** @var IUser $user1 */ - $this->rosterPush->createOrUpdateRosterItem($user1); - } - - // removeRosterItemForUsersInGroup, addUserToGroup and removeUserFromGroup covered by integration tests -} diff --git a/tests/unit/UserTest.php b/tests/unit/UserTest.php deleted file mode 100644 index ae77bbe..0000000 --- a/tests/unit/UserTest.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php - - -use OCA\OJSXC\User; -use PHPUnit\Framework\TestCase; - -class UserTest extends TestCase -{ - public function test() - { - $user1 = new User(" test @ 'abc", 'Test123', null); - - $this->assertEquals($user1->getFullName(), 'Test123'); - $this->assertEquals($user1->getUid(), '_ojsxc_esc_space_test_ojsxc_esc_space__ojsxc_esc_at__ojsxc_esc_space__ojsxc_squote_space_abc'); - $user1->setUid('test1'); - $user1->setFullName('test2'); - $this->assertEquals($user1->getUid(), 'test1'); - $this->assertEquals($user1->getFullName(), 'test2'); - } -} diff --git a/tests/unit/controller/HttpBindControllerTest.php b/tests/unit/controller/HttpBindControllerTest.php deleted file mode 100644 index 45251ed..0000000 --- a/tests/unit/controller/HttpBindControllerTest.php +++ /dev/null @@ -1,621 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Unit\Controller; - -use OCA\OJSXC\Controller\HttpBindController; -use OCA\OJSXC\Db\Presence; -use OCA\OJSXC\Db\PresenceMapper; -use OCA\OJSXC\Db\Stanza; -use OCA\OJSXC\Db\StanzaMapper; -use OCA\OJSXC\Exceptions\TerminateException; -use OCA\OJSXC\Http\XMPPResponse; -use OCA\OJSXC\ILock; -use OCA\OJSXC\NewContentContainer; -use OCA\OJSXC\StanzaHandlers\IQ; -use OCA\OJSXC\StanzaHandlers\Message; -use OCA\OJSXC\StanzaHandlers\Presence as StanzaHandlersPresence; -use OCA\OJSXC\StanzaLogger; -use OCP\AppFramework\Db\DoesNotExistException; -use OCP\IRequest; -use PHPUnit\Framework\TestCase; -use Sabre\Xml\Writer; -use PHPUnit_Framework_MockObject_MockObject; - -class HttpBindControllerTest extends TestCase -{ - - /** - * @var HttpBindController - */ - private $controller; - - /** - * @var PHPUnit_Framework_MockObject_MockObject - */ - private $stanzaMapper; - - /** - * @var PHPUnit_Framework_MockObject_MockObject - */ - private $iqHandler; - - /** - * @var PHPUnit_Framework_MockObject_MockObject - */ - private $messageHandler; - - /** - * @var PHPUnit_Framework_MockObject_MockObject - */ - private $lock; - - /** - * @var PHPUnit_Framework_MockObject_MockObject - */ - private $presenceHandler; - - /** - * @var PHPUnit_Framework_MockObject_MockObject - */ - private $presenceMapper; - - private $userId = 'john'; - - /** - * @var PHPUnit_Framework_MockObject_MockObject - */ - private $newContentContainer; - - /** - * @var StanzaLogger - */ - private $stanzaLogger; - - public function setUp(): void - { - $this->stanzaLogger = $this->getMockBuilder('OCA\OJSXC\StanzaLogger')->disableOriginalConstructor()->getMock(); - } - - private function mockLock() - { - $this->lock->expects($this->any()) - ->method('setLock') - ->will($this->returnValue(null)); - - $this->lock->expects($this->any()) - ->method('stillLocked') - ->will($this->returnValue(true)); - } - - /** - * Helper function to set up the controller. This can't be done in the setUp, - * since the requestBody is different for every test. - * @param $requestBody - */ - private function setUpController($requestBody) - { - /** @var IRequest */ - $request = $this->getMockBuilder(IRequest::class)->disableOriginalConstructor()->getMock(); - - /** @var StanzaMapper */ - $this->stanzaMapper = $this->getMockBuilder(StanzaMapper::class)->disableOriginalConstructor()->getMock(); - - /** @var PresenceMapper */ - $this->presenceMapper = $this->getMockBuilder(PresenceMapper::class)->disableOriginalConstructor()->getMock(); - - /** @var IQ */ - $this->iqHandler = $this->getMockBuilder(IQ::class)->disableOriginalConstructor()->getMock(); - - /** @var Message */ - $this->messageHandler = $this->getMockBuilder(Message::class)->disableOriginalConstructor()->getMock(); - - /** @var StanzaHandlersPresence */ - $this->presenceHandler = $this->getMockBuilder(StanzaHandlersPresence::class)->disableOriginalConstructor()->getMock(); - - /** @var ILock */ - $this->lock = $this->getMockBuilder(ILock::class)->disableOriginalConstructor()->getMock(); - - /** @var NewContentContainer */ - $this->newContentContainer = $this->getMockBuilder(NewContentContainer::class)->disableOriginalConstructor()->getMock(); - - $this->controller = new HttpBindController( - 'ojsxc', - $request, - $this->userId, - $this->stanzaMapper, - $this->iqHandler, - $this->messageHandler, - $this->lock, - $this->presenceHandler, - $this->presenceMapper, - $requestBody, - 0, - 10, - $this->newContentContainer, - $this->stanzaLogger - ); - } - - public function testNewContentContainerNoNew() - { - $this->setUpController('<body xmlns=\'http://jabber.org/protocol/httpbind\'/>'); - $this->mockLock(); - $ex = new DoesNotExistException(''); - $expResponse = new XMPPResponse($this->stanzaLogger); - - $this->newContentContainer->expects($this->once()) - ->method('getCount') - ->will($this->returnValue(0)); - - $this->newContentContainer->expects($this->never()) - ->method('getStanzas'); - - $this->stanzaMapper->expects($this->exactly(10)) - ->method('findByTo') - ->with('john') - ->will($this->throwException($ex)); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - } - - public function testNewContentContainerNoNewWithDbResults() - { - $result = new Stanza('test'); - $this->setUpController('<body rid=\'897878797\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'/>'); - $this->mockLock(); - - $expResponse = new XMPPResponse($this->stanzaLogger, $result); - - $this->iqHandler->expects($this->never()) - ->method('handle') - ->will($this->returnValue($result)); - - $r1 = $this->getMockBuilder('OCA\OJSXC\Db\Stanza')->disableOriginalConstructor()->getMock(); - $r1->expects($this->once()) - ->method('xmlSerialize') - ->will($this->returnCallback(function (Writer $writer) { - $writer->write('test'); - })); - - $this->stanzaMapper->expects($this->once()) - ->method('findByTo') - ->with('john') - ->will($this->returnValue([$r1])); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $this->newContentContainer->expects($this->once()) - ->method('getCount') - ->will($this->returnValue(0)); - - $this->newContentContainer->expects($this->never()) - ->method('getStanzas'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } - - - public function testNewContentContainerWithNewWithDbResults() - { - $result = new Stanza('test'); - $this->setUpController('<body rid=\'897878797\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'/>'); - $this->mockLock(); - - $expResponse = new XMPPResponse($this->stanzaLogger, $result); - - $this->iqHandler->expects($this->never()) - ->method('handle') - ->will($this->returnValue($result)); - - $r1 = $this->getMockBuilder('OCA\OJSXC\Db\Stanza')->disableOriginalConstructor()->getMock(); - $r1->expects($this->once()) - ->method('xmlSerialize') - ->will($this->returnCallback(function (Writer $writer) { - $writer->write('test'); - })); - - $this->stanzaMapper->expects($this->once()) - ->method('findByTo') - ->with('john') - ->will($this->returnValue([$r1])); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $this->newContentContainer->expects($this->once()) - ->method('getCount') - ->will($this->returnValue(5)); - - $testStanza = new Stanza(); - $testStanza->setFrom('derp@own.dev'); - $testStanza->setTo('admin@own.dev'); - - $this->newContentContainer->expects($this->once()) - ->method('getStanzas') - ->will($this->returnValue([$testStanza,$testStanza, $testStanza, $testStanza, $testStanza ])); - - $expResponse->write($testStanza); - $expResponse->write($testStanza); - $expResponse->write($testStanza); - $expResponse->write($testStanza); - $expResponse->write($testStanza); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } - - - /** - * When invalid XML, just start long polling. - * Note: this test will cause some errors in the owncloud.log: - * {"reqId":"HmbEV6qTWF68ii1G\/kz1","remoteAddr":"","app":"PHP","message":"XMLReader::read(): An Error Occured while reading at \/var\/www\/owncloud\/apps\/ojsxc\/vendor\/sabre\/xml\/lib\/Reader.php#66","level":0,"time":"2016-01-30T14:52:44+00:00","method":"--","url":"--"} - * {"reqId":"HmbEV6qTWF68ii1G\/kz1","remoteAddr":"","app":"PHP","message":"XMLReader::read(): An Error Occured while reading at \/var\/www\/owncloud\/apps\/ojsxc\/vendor\/sabre\/xml\/lib\/Reader.php#145","level":0,"time":"2016-01-30T14:52:44+00:00","method":"--","url":"--"} - */ - public function testInvalidXML() - { - $ex = new DoesNotExistException(''); - $expResponse = new XMPPResponse($this->stanzaLogger); - - $this->setUpController('<x>'); - $this->mockLock(); - $this->stanzaMapper->expects($this->exactly(10)) - ->method('findByTo') - ->with('john') - ->will($this->throwException($ex)); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - } - - public function IQProvider() - { - $expStanza1 = new Stanza(); - $expStanza1->setStanza('<iq to="admin@localhost" type="result" id="2:sendIQ"><query xmlns="jabber:iq:roster"><item jid="derp@localhost" name="derp"></item></query></iq><iq to="admin@localhost" type="result" id="2:sendIQ"><query xmlns="jabber:iq:roster"><item jid="derp@localhost" name="derp"></item></query></iq><iq to="admin@localhost" type="result" id="2:sendIQ"><query xmlns="jabber:iq:roster"><item jid="derp@localhost" name="derp"></item></query></iq>'); - - $result1 = new Stanza(); - $result1->setStanza('<iq to="admin@localhost" type="result" id="2:sendIQ"><query xmlns="jabber:iq:roster"><item jid="derp@localhost" name="derp"></item></query></iq>'); - - $result2 = new Stanza(); - $result2->setStanza(null); - $expStanza2 = new Stanza(); - $expStanza2->setStanza(null); - return [ - [ - '<body rid=\'897878733\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'><iq from=\'admin@localhost\' to=\'localhost\' type=\'get\' xmlns=\'jabber:client\' id=\'1:sendIQ\'><query xmlns=\'http://jabber.org/protocol/disco#info\' node=\'undefined#undefined\'/></iq><iq type=\'get\' xmlns=\'jabber:client\' id=\'2:sendIQ\'><query xmlns=\'jabber:iq:roster\'/></iq><iq type=\'get\' to=\'admin@localhost\' xmlns=\'jabber:client\' id=\'3:sendIQ\'><vCard xmlns=\'vcard-temp\'/></iq></body>', - $result1, - $expStanza1, // we ask for 3 IQ's thus return 3 values - $this->once(), - $this->exactly(3) - ], - [ - '<body rid=\'897878734\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'><iq from=\'admin@localhost\' to=\'localhost\' type=\'get\' xmlns=\'jabber:client\' id=\'1:sendIQ\'><query xmlns=\'http://jabber.org/protocol/disco#info\' node=\'undefined#undefined\'/></iq><iq type=\'get\' xmlns=\'jabber:client\' id=\'2:sendIQ\'><query xmlns=\'jabber:iq:roster\'/></iq><iq type=\'get\' to=\'admin@localhost\' xmlns=\'jabber:client\' id=\'3:sendIQ\'><vCard xmlns=\'vcard-temp\'/></iq></body>', - $result2, - $expStanza2, - $this->once(), - $this->exactly(3) - ] - ]; - } - - /** - * @dataProvider IQProvider - */ - public function testIQHandlerWhenNoDbResults($body, $result, $expected, $pollCount, $handlerCount) - { - $ex = new DoesNotExistException(''); - $this->setUpController($body); - $this->mockLock(); - $expResponse = new XMPPResponse($this->stanzaLogger); - $expResponse->write($expected); - - $this->iqHandler->expects($handlerCount) - ->method('handle') - ->will($this->returnValue($result)); - - $this->stanzaMapper->expects($pollCount) - ->method('findByTo') - ->with('john') - ->will($this->throwException($ex)); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } - - public function testDbResults() - { - $result = new Stanza('test'); - $this->setUpController('<body rid=\'897878797\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'/>'); - $this->mockLock(); - - $expResponse = new XMPPResponse($this->stanzaLogger, $result); - - $this->iqHandler->expects($this->never()) - ->method('handle') - ->will($this->returnValue($result)); - - $r1 = $this->getMockBuilder('OCA\OJSXC\Db\Stanza')->disableOriginalConstructor()->getMock(); - $r1->expects($this->once()) - ->method('xmlSerialize') - ->will($this->returnCallback(function (Writer $writer) { - $writer->write('test'); - })); - - $this->stanzaMapper->expects($this->once()) - ->method('findByTo') - ->with('john') - ->will($this->returnValue([$r1])); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } - - public function testMessageNoDbHandler() - { - $body = '<body rid=\'897878959\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'><message to=\'derp@own.dev\' type=\'chat\' id=\'1452960296859-msg\' xmlns=\'jabber:client\'><body>abc</body><request xmlns=\'urn:xmpp:receipts\'/></message></body>'; - $ex = new DoesNotExistException(''); - $this->setUpController($body); - $this->mockLock(); - - $expResponse = new XMPPResponse($this->stanzaLogger); - - $this->messageHandler->expects($this->once()) - ->method('handle'); - - $this->stanzaMapper->expects($this->exactly(10)) - ->method('findByTo') - ->with('john') - ->will($this->throwException($ex)); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } - - - public function testMultipleMessageNoDbHandler() - { - $body = <<<XML - <body rid='897878959' xmlns='http://jabber.org/protocol/httpbind' sid='7862'> - <message to='derp@own.dev' type='chat' id='1452960296859-msg' xmlns='jabber:client'><body>abc</body></message> - <message to='derp@own.dev' type='chat' id='1452960296860-msg' xmlns='jabber:client'><body>abc2</body></message> - <message to='derp@own.dev' type='chat' id='1452960296861-msg' xmlns='jabber:client'><body>abc3</body></message> - </body> -XML; - $ex = new DoesNotExistException(''); - $this->setUpController($body); - $this->mockLock(); - - $expResponse = new XMPPResponse($this->stanzaLogger); - $this->messageHandler->expects($this->any()) - ->method('handle'); - - $this->messageHandler->expects($this->exactly(3)) - ->method('handle') - ->withConsecutive( - [$this->equalTo( - [ 'name' => '{jabber:client}message', - 'value' => [ - '{jabber:client}body' => 'abc', - ], - 'attributes' => [ - 'to' => 'derp@own.dev', - 'type' => 'chat', - 'id' => '1452960296859-msg', - ]] - )], - [$this->equalTo([ - 'name' => '{jabber:client}message', - 'value' => [ - '{jabber:client}body' => 'abc2', - ], - 'attributes' => [ - 'to' => 'derp@own.dev', - 'type' => 'chat', - 'id' => '1452960296860-msg', - ] - ])], - [$this->equalTo([ - 'name' => '{jabber:client}message', - 'value' => [ - '{jabber:client}body' => 'abc3', - ], - 'attributes' => [ - 'to' => 'derp@own.dev', - 'type' => 'chat', - 'id' => '1452960296861-msg', - ] - ])] - ); - - $this->stanzaMapper->expects($this->exactly(10)) - ->method('findByTo') - ->with('john') - ->will($this->throwException($ex)); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } - - public function testMessageDbHandler() - { - $body = '<body rid=\'897878959\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'><message to=\'derp@own.dev\' type=\'chat\' id=\'1452960296859-msg\' xmlns=\'jabber:client\'><body>abc</body><request xmlns=\'urn:xmpp:receipts\'/></message></body>'; - $this->setUpController($body); - $this->mockLock(); - - $expResponse = new XMPPResponse($this->stanzaLogger, new Stanza('test')); - - $this->messageHandler->expects($this->once()) - ->method('handle'); - - $r1 = $this->getMockBuilder('OCA\OJSXC\Db\Stanza')->disableOriginalConstructor()->getMock(); - $r1->expects($this->once()) - ->method('xmlSerialize') - ->will($this->returnCallback(function (Writer $writer) { - $writer->write('test'); - })); - - $this->stanzaMapper->expects($this->once()) - ->method('findByTo') - ->with('john') - ->will($this->returnValue([$r1])); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } - - public function testPresenceReturnNothingHandler() - { - $body = "<body xmlns='http://jabber.org/protocol/httpbind'><presence xmlns='jabber:client'><show>chat</show></presence></body>"; - $ex = new DoesNotExistException(''); - $expResponse = new XMPPResponse($this->stanzaLogger); - - $this->setUpController($body); - $this->mockLock(); - - $this->presenceHandler->expects($this->once()) - ->method('handle') - ->will($this->returnValue(null)); - - $this->stanzaMapper->expects($this->exactly(10)) - ->method('findByTo') - ->with('john') - ->will($this->throwException($ex)); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } - - public function testPresenceHandler() - { - $body = "<body xmlns='http://jabber.org/protocol/httpbind'><presence xmlns='jabber:client'><show>chat</show></presence></body>"; - $ex = new DoesNotExistException(''); - $expResponse = new XMPPResponse($this->stanzaLogger); - - $pres1 = new Presence(); - $pres1->setPresence('online'); - $pres1->setUserid('admin'); - $pres1->setTo('admin@localhost'); - $pres1->setFrom('derp@localhot'); - - $pres2 = new Presence(); - $pres2->setPresence('unavailable'); - $pres2->setUserid('herp'); - $pres2->setTo('admin@localhost'); - $pres2->setFrom('herp@localhot'); - - $expResponse->write($pres1); - $expResponse->write($pres2); - - $this->setUpController($body); - $this->mockLock(); - - $this->presenceHandler->expects($this->once()) - ->method('handle') - ->will($this->returnValue([$pres1, $pres2])); - - $this->stanzaMapper->expects($this->never()) - ->method('findByTo') - ->with('john') - ->will($this->throwException($ex)); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } - - public function testBodyHandler() - { - $ex = new DoesNotExistException(''); - $body = '<body rid=\'897878985\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'/>'; - $this->setUpController($body); - $this->mockLock(); - $expResponse = new XMPPResponse($this->stanzaLogger); - - $this->stanzaMapper->expects($this->exactly(10)) - ->method('findByTo') - ->with('john') - ->will($this->throwException($ex)); - - $this->presenceMapper->expects($this->once()) - ->method('setActive') - ->with('john'); - - $response = $this->controller->index(); - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } - - - public function testTerminateException() - { - $ex = new TerminateException(); - - $body = '<body rid=\'897878985\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'><iq from=\'test@test.local/internal\' to=\'test.local\' type=\'get\' - xmlns=\'jabber:client\' id=\'3b300f7c-1a38-4c1b-b66a-582895d12e47:sendIQ\'> - <query xmlns=\'http://jabber.org/protocol/disco#info\' - node=\'undefined#undefined\'/> - </iq></body>'; - $this->setUpController($body); - $this->mockLock(); - - $this->iqHandler->expects($this->once()) - ->method('handle') - ->will($this->throwException($ex)); - - $expResponse = new XMPPResponse($this->stanzaLogger); - $expResponse->terminate(); - - $response = $this->controller->index(); - - $this->assertEquals($expResponse, $response); - $this->assertEquals($expResponse->render(), $response->render()); - } -} diff --git a/tests/unit/controller/SettingsControllerTest.php b/tests/unit/controller/SettingsControllerTest.php index 9643ba0..be5ffc7 100644 --- a/tests/unit/controller/SettingsControllerTest.php +++ b/tests/unit/controller/SettingsControllerTest.php @@ -45,7 +45,7 @@ class SettingsControllerTest extends TestCase public function testIndexPreferPersonalEmail() { $mapGetAppValue = [ - [Config::XMPP_SERVER_TYPE, 'internal', 'external'], + [Config::XMPP_SERVER_TYPE, 'not-configured', 'external'], ]; $this->config->method('getBooleanAppValue')->will($this->returnValueMap([ @@ -58,7 +58,7 @@ class SettingsControllerTest extends TestCase $mapGetUserValue = [ ['Foo', 'settings', 'email', $node.'@'.$domain] - ]; + ]; $this->setUpAuthenticatedIndex($mapGetAppValue, $mapGetUserValue); @@ -72,7 +72,7 @@ class SettingsControllerTest extends TestCase public function testIndexTimeLimitedToken() { $mapGetAppValue = [ - [Config::XMPP_SERVER_TYPE, 'internal', 'external'], + [Config::XMPP_SERVER_TYPE, 'not-configured', 'external'], ['xmppDomain', null, 'localhost'] ]; @@ -143,17 +143,8 @@ class SettingsControllerTest extends TestCase public function testServerType() { $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with(Config::XMPP_SERVER_TYPE, 'internal') - ->willReturn('internal'); // default value - - $this->assertEquals($this->settingsController->getServerType(), ["serverType" => "internal"]); - - $this->config - ->expects($this->at(0)) ->method('getAppValue') - ->with(Config::XMPP_SERVER_TYPE, 'internal') + ->with(Config::XMPP_SERVER_TYPE, 'not-configured') ->willReturn('external'); $this->assertEquals($this->settingsController->getServerType(), ["serverType" => "external"]); diff --git a/tests/unit/db/README.md b/tests/unit/db/README.md deleted file mode 100644 index 35902a8..0000000 --- a/tests/unit/db/README.md +++ /dev/null @@ -1,4 +0,0 @@ -tests/unit/db -=== -Note that in this directory only Entity can be tests since this are unit tests. -Mapper tests should go into the integraion tests directory.
\ No newline at end of file diff --git a/tests/unit/http/XMPPResponseTest.php b/tests/unit/http/XMPPResponseTest.php deleted file mode 100644 index a0c00ac..0000000 --- a/tests/unit/http/XMPPResponseTest.php +++ /dev/null @@ -1,61 +0,0 @@ -<?php - -namespace OCA\OJSXC\Http { - - use OCA\OJSXC\Db\Message; - use OCA\OJSXC\Db\Stanza; - use PHPUnit\Framework\TestCase; - - class XMPPResponseTest extends TestCase - { - public function writingProvider() - { - $stanza1 = new Stanza(); - $stanza1->setFrom('test', 'test.be'); - $stanza1->setTo('test.be'); - $stanza1->setStanza('abc'); - - $stanza2 = new Message(); - $stanza2->setAttrId('4-msg'); - $stanza2->setFrom('test', 'test.be'); - $stanza2->setTo('test.be'); - $stanza2->setStanza('abc'); - $stanza2->setType('testtype'); - $stanza2->setValue('abcvalue'); - - return [ - [ - [new Stanza('')], - '<body xmlns="http://jabber.org/protocol/httpbind"></body>' - ], - [ - [$stanza1], - '<body xmlns="http://jabber.org/protocol/httpbind">abc</body>' - ], - [ - [$stanza1, $stanza2], - '<body xmlns="http://jabber.org/protocol/httpbind">abc<message to="test.be" from="test@test.be" type="testtype" xmlns="jabber:client" id="4-msg">abcvalue</message></body>' - ], - [ - [$stanza1, new Stanza(''), $stanza2], - '<body xmlns="http://jabber.org/protocol/httpbind">abc<message to="test.be" from="test@test.be" type="testtype" xmlns="jabber:client" id="4-msg">abcvalue</message></body>' - ], - ]; - } - - /** - * @dataProvider writingProvider - */ - public function testWriting($stanzas, $expected) - { - $stanzaLogger = $this->getMockBuilder('OCA\OJSXC\StanzaLogger')->disableOriginalConstructor()->getMock(); - $response = new XMPPResponse($stanzaLogger); - foreach ($stanzas as $stanza) { - $response->write($stanza); - } - $result = $response->render(); - $this->assertEquals($expected, $result); - } - } - -} diff --git a/tests/unit/stanzahandlers/IQTest.php b/tests/unit/stanzahandlers/IQTest.php deleted file mode 100644 index 37c10e4..0000000 --- a/tests/unit/stanzahandlers/IQTest.php +++ /dev/null @@ -1,234 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Unit\StanzaHandlers; - -use OCA\OJSXC\Db\IQRoster; -use OCA\OJSXC\Exceptions\TerminateException; -use OCA\OJSXC\IUserProvider; -use OCA\OJSXC\StanzaHandlers\IQ; -use OCA\OJSXC\User; -use OCP\IConfig; -use PHPUnit\Framework\TestCase; -use OCP\IUserManager; -use PHPUnit_Framework_MockObject_MockObject; - -class IQTest extends TestCase -{ - - /** - * @var IQ $iq - */ - private $iq; - - /** - * @var PHPUnit_Framework_MockObject_MockObject | IUserManager - */ - private $userManager; - - /** - * @var string userId - */ - private $userId; - - /** - * @var string $host ; - */ - private $host; - - /** - * @var PHPUnit_Framework_MockObject_MockObject | IConfig - */ - private $config; - - - /** - * @var \PHPUnit_Framework_MockObject_MockObject | IUserProvider - */ - private $userProvider; - - public function setUp(): void - { - $this->host = 'localhost'; - $this->userId = 'john'; - $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock(); - $this->config = $this->getMockBuilder(IConfig::class)->getMock(); - $this->userProvider = $this->getMockBuilder(IUserProvider::class)->getMock(); - - $this->iq = new IQ($this->userId, $this->host, $this->userManager, $this->config, $this->userProvider); - } - - public function iqRosterProvider() - { - $user1 = $this->getMockBuilder(User::class)->disableOriginalConstructor()->getMock(); - $user1->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('john')); - - $user1->expects($this->any()) - ->method('getFullName') - ->will($this->returnValue('John')); - - $user2 = $this->getMockBuilder(User::class)->disableOriginalConstructor()->getMock(); - $user2->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('richard')); - - $user2->expects($this->any()) - ->method('getFullName') - ->will($this->returnValue('Richard')); - - $expected1 = new IQRoster(); - $expected1->setType('result'); - $expected1->setTo('john'); - $expected1->setQid('f9a26583-3c59-4f09-89be-964ce265fbfd:sendIQ'); - $expected1->addItem('richard@localhost', 'Richard'); - - $expected2 = new IQRoster(); - $expected2->setType('result'); - $expected2->setTo('john'); - $expected2->setQid('f9a26583-3c59-4f09-89be-964ce265fbfa:sendIQ'); - - return [ - [ - ['name' => '{jabber:client}iq', - 'value' => [0 => [ - 'name' => '{http://jabber.org/protocol/disco#info}query', - 'value' => null, - 'attributes' => [ - 'node' => 'undefined#undefined', - ], - ]], - 'attributes' => [ - 'from' => 'admin@own.dev', - 'to' => 'own.dev', - 'type' => 'get', - 'id' => 'e4e3e333-1b72-4014-a191-8c157326e037:sendIQ', - ], - ], - [], - $this->never(), - null - ], - [ - [ - 'name' => '{jabber:client}iq', - 'value' => - [ - 0 => - [ - 'name' => '{jabber:iq:roster}query', - 'value' => null, - 'attributes' => - [ - ], - ] - ], - 'attributes' => - [ - 'type' => 'get', - 'id' => 'f9a26583-3c59-4f09-89be-964ce265fbfd:sendIQ', - ], - ], - [$user1, $user2], - $this->once(), - $expected1 - ], - [ - [ - 'name' => '{jabber:client}iq', - 'value' => - [ - 0 => - [ - 'name' => '{jabber:iq:roster}query', - 'value' => null, - 'attributes' => - [ - ], - ] - ], - 'attributes' => - [ - 'type' => 'get', - 'id' => 'f9a26583-3c59-4f09-89be-964ce265fbfa:sendIQ', - ], - ], - [], - $this->once(), - $expected2 - ] - ]; - } - - /** - * @dataProvider iqRosterProvider - */ - public function testIqRoster(array $stanza, array $users, $searchCount, $expected) - { - $this->config->expects($this->once()) - ->method('getSystemValue') - ->with('debug') - ->will($this->returnValue(false)); - - $this->userProvider->expects($searchCount) - ->method('getAllUsers') - ->will($this->returnValue($users)); - - $result = $this->iq->handle($stanza); - - if ($expected instanceof IQRoster) { - $this->assertEquals($expected->getUnSanitizedFrom(), $result->getUnSanitizedFrom()); - $this->assertEquals($expected->getId(), $result->getId()); - $this->assertEquals($expected->getItems(), $result->getItems()); - $this->assertEquals($expected->getQid(), $result->getQid()); - $this->assertEquals($expected->getUnSanitizedTo(), $result->getUnSanitizedTo()); - $this->assertEquals($expected->getType(), $result->getType()); - $this->assertEquals($expected->getStanza(), $result->getStanza()); - } else { - $this->assertEquals($expected, $result); - } - } - - public function testTerminateExceptionDiscoItems() - { - $stanza = ['name' => '{jabber:client}iq', - 'value' => [0 => [ - 'name' => '{http://jabber.org/protocol/disco#items}query', - 'value' => null, - 'attributes' => [ - 'node' => 'undefined#undefined', - ], - ]], - ]; - - $this->userProvider->expects($this->once()) - ->method('isUserExcluded') - ->with('john') - ->will($this->returnValue(true)); - - $this->expectException(TerminateException::class); - $this->iq->handle($stanza); - } - - public function testTerminateExceptionDiscoInfo() - { - $stanza = ['name' => '{jabber:client}iq', - 'value' => [0 => [ - 'name' => '{http://jabber.org/protocol/disco#info}query', - 'value' => null, - 'attributes' => [ - 'node' => 'undefined#undefined', - ], - ]], - ]; - - - $this->userProvider->expects($this->once()) - ->method('isUserExcluded') - ->with('john') - ->will($this->returnValue(true)); - - $this->expectException(TerminateException::class); - $this->iq->handle($stanza); - } -} diff --git a/tests/unit/stanzahandlers/MessageTest.php b/tests/unit/stanzahandlers/MessageTest.php deleted file mode 100644 index 0aec9cd..0000000 --- a/tests/unit/stanzahandlers/MessageTest.php +++ /dev/null @@ -1,147 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Unit\StanzaHandlers; - -use OCA\OJSXC\Db\Message as MessageEntity; -use PHPUnit\Framework\TestCase; -use OCA\OJSXC\Db\MessageMapper; -use OCA\OJSXC\IUserProvider; -use OCA\OJSXC\StanzaHandlers\Message; -use OCP\ILogger; -use PHPUnit_Framework_MockObject_MockObject; - -class MessageTest extends TestCase -{ - - /** - * @var Message $message - */ - private $message; - - /** - * @var PHPUnit_Framework_MockObject_MockObject | MessageMapper - */ - private $messageMapper; - - /** - * @var string userId - */ - private $userId; - - /** - * @var string $host - */ - private $host; - - /** - * @var PHPUnit_Framework_MockObject_MockObject | IUserProvider - */ - private $userProvider; - - /** - * @var PHPUnit_Framework_MockObject_MockObject | ILogger - */ - private $logger; - - public function setUp(): void - { - $this->host = 'localhost'; - $this->userId = 'john'; - - /** @var MessageMapper */ - $this->messageMapper = $this->getMockBuilder(MessageMapper::class)->disableOriginalConstructor()->getMock(); - - /** @var IUserProvider */ - $this->userProvider = $this->getMockBuilder(IUserProvider::class)->disableOriginalConstructor()->getMock(); - - /** @var ILogger */ - $this->logger = $this->getMockBuilder(ILogger::class)->disableOriginalConstructor()->getMock(); - - $this->message = new Message($this->userId, $this->messageMapper, $this->userProvider, $this->logger); - } - - public function messageProvider() - { - $values = [ - [ - "name" => "body", - "value" => 'abcèé³e¹³€{ë', - "attributes" => ["xmlns" => 'jabber:client'] - ], - [ - "name" => "request", - "value" => '', - "attributes" => ["xmlns" => 'urn:xmpp:receipts'] - ], - ]; - - $expected1 = new MessageEntity(); - $expected1->setTo('derp'); // hostname is stripped - $expected1->setFrom('john'); - $expected1->setValue($values); - $expected1->setType('chat'); - - return [ - [ - [ - 'name' => '{jabber:client}message', - 'value' => - [ - '{jabber:client}body' => 'abcèé³e¹³€{ë', - '{urn:xmpp:receipts}request' => null, - ], - 'attributes' => - [ - 'to' => 'derp@own.dev', - 'type' => 'chat', - ], - ], - $expected1 - ] - ]; - } - - /** - * @dataProvider messageProvider - */ - public function testMessage(array $stanza, $expected) - { - $this->messageMapper->expects($this->once()) - ->method('insert') - ->with($expected); - - $this->userProvider->expects($this->once()) - ->method('hasUserByUID') - ->with('derp') - ->willReturn(true); - - $this->message->handle($stanza); - } - - public function testNotAllowedToChat() - { - $this->messageMapper->expects($this->never()) - ->method('insert'); - - $this->userProvider->expects($this->once()) - ->method('hasUserByUID') - ->with('derp') - ->willReturn(false); - - $stanza = [ - 'name' => '{jabber:client}message', - 'value' => - [ - '{jabber:client}body' => 'abcèé³e¹³€{ë', - '{urn:xmpp:receipts}request' => null, - ], - 'attributes' => - [ - 'to' => 'derp@own.dev', - 'type' => 'chat', - ], - ]; - - $this->message->handle($stanza); - } -} diff --git a/tests/unit/stanzahandlers/PresenceTest.php b/tests/unit/stanzahandlers/PresenceTest.php deleted file mode 100644 index 32ca5ef..0000000 --- a/tests/unit/stanzahandlers/PresenceTest.php +++ /dev/null @@ -1,150 +0,0 @@ -<?php - -namespace OCA\OJSXC\Tests\Unit\StanzaHandlers; - -use OCA\OJSXC\Db\MessageMapper; -use OCA\OJSXC\StanzaHandlers\Presence; -use OCA\OJSXC\Db\Presence as PresenceEntity; -use OCA\OJSXC\Db\PresenceMapper; -use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; - -class PresenceTest extends TestCase -{ - private $host; - - private $userId; - - /** - * @var PHPUnit_Framework_MockObject_MockObject $presenceMapper - */ - private $presenceMapper; - - /** - * @var PHPUnit_Framework_MockObject_MockObject $presenceMapper - */ - private $messageMapper; - - /** - * @var Presence - */ - private $presence; - - public function setUp(): void - { - $this->host = 'localhost'; - $this->userId = 'john'; - - /** @var PresenceMapper */ - $this->presenceMapper = $this->getMockBuilder(PresenceMapper::class)->disableOriginalConstructor()->getMock(); - - /** @var MessageMapper */ - $this->messageMapper = $this->getMockBuilder(MessageMapper::class)->disableOriginalConstructor()->getMock(); - - $this->presence = new Presence($this->userId, $this->presenceMapper, $this->messageMapper); - } - - public function handleProvider() - { - $presence = new PresenceEntity(); - $presence->setPresence('online'); - $presence->setUserid('john'); - $presence->setLastActive(time()); - - // broadcast presence - $insert1 = new PresenceEntity(); - $insert1->setPresence('online'); - $insert1->setFrom('john'); - $insert1->setTo('derp'); - - $insert2 = new PresenceEntity(); - $insert2->setPresence('online'); - $insert2->setFrom('john'); - $insert2->setTo('herp'); - return [ - [ - $presence, - ['derp', 'herp'], - 'testValue', - [$insert1, $insert2] - ] - ]; - } - - /** - * @dataProvider handleProvider - */ - public function testHandle($presenceEntity, $connectedUsers, $presences, $insert) - { - $this->presenceMapper->expects($this->once()) - ->method('setPresence') - ->with($presenceEntity); - - $this->presenceMapper->expects($this->once()) - ->method('getConnectedUsers') - ->will($this->returnValue($connectedUsers)); - - $this->messageMapper->expects($this->exactly(2)) - ->method('insert'); - - $this->presenceMapper->expects($this->once()) - ->method('getPresences') - ->will($this->returnValue($presences)); - - $result = $this->presence->handle($presenceEntity); - $this->assertEquals($presences, $result); - } - - - public function unavailableHandleProvider() - { - $presence = new PresenceEntity(); - $presence->setPresence('unavailable'); - $presence->setUserid('john'); - $presence->setLastActive(time()); - - // broadcast presence - $insert1 = new PresenceEntity(); - $insert1->setPresence('unavailable'); - $insert1->setFrom('john'); - $insert1->setTo('derp'); - - $insert2 = new PresenceEntity(); - $insert2->setPresence('unavailable'); - $insert2->setFrom('john'); - $insert2->setTo('herp'); - - return [ - [ - $presence, - ['derp', 'herp'], - [], - [$insert1, $insert2] - ] - ]; - } - - /** - * @dataProvider UnavailableHandleProvider - */ - public function testUnavailableHandle($presenceEntity, $connectedUsers, $presences, $insert) - { - $this->presenceMapper->expects($this->once()) - ->method('setPresence') - ->with($presenceEntity); - - - $this->presenceMapper->expects($this->once()) - ->method('getConnectedUsers') - ->will($this->returnValue($connectedUsers)); - - $this->messageMapper->expects($this->exactly(2)) - ->method('insert'); - - $this->presenceMapper->expects($this->never()) - ->method('getPresences'); - - $result = $this->presence->handle($presenceEntity); - $this->assertEquals($presences, $result); - } -} diff --git a/ts/Bootstrap.ts b/ts/Bootstrap.ts index 9f60244..b215302 100644 --- a/ts/Bootstrap.ts +++ b/ts/Bootstrap.ts @@ -95,21 +95,6 @@ export default class Bootstrap { if (OC.getCurrentUser().uid) { this.jsxc.start(); } - - if (OJSXC_CONFIG.serverType === 'internal') { - let storage = Storage.get(); - let jid = storage.getItem('internal:jid'); - let url = storage.getItem('internal:url'); - - if (jid && url) { - console.log('Start connection to internal XMPP server'); - - this.jsxc.start(url, jid, 'sid', '1234'); - - storage.removeItem('internal:jid'); - storage.removeItem('internal:url'); - } - } } } @@ -156,11 +141,7 @@ export default class Bootstrap { jid += '/' + xmpp.resource; } - if (OJSXC_CONFIG.serverType === 'internal') { - this.jsxc.start(xmpp.url, jid, 'sid', '1234'); - } else { - this.jsxc.start(xmpp.url, jid, xmpp.password || ''); - } + this.jsxc.start(xmpp.url, jid, xmpp.password || ''); } catch (err) { console.log('Error during log in', err); diff --git a/ts/Settings.ts b/ts/Settings.ts index 78bfd4f..c066268 100644 --- a/ts/Settings.ts +++ b/ts/Settings.ts @@ -101,17 +101,6 @@ export default class Settings { storage.removeItem('loginForm:disable'); - if (OJSXC_CONFIG.serverType === 'internal') { - storage.removeItem('serverIsOmniscient'); - - if (!disabled) { - let jid = xmpp.node + '@' + xmpp.domain + '/' + xmpp.resource; - - storage.setItem('internal:jid', jid); - storage.setItem('internal:url', xmpp.url); - } - } - return { disabled, xmpp: { |