From aa974a4322170ae3b489607967801ba84ccc63b4 Mon Sep 17 00:00:00 2001 From: =?utf8?q?C=C3=B4me=20Chilliet?= Date: Tue, 28 May 2024 10:07:04 +0200 Subject: [PATCH] feat: Add webhooks application MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Côme Chilliet --- .gitignore | 1 + apps/webhooks/appinfo/info.xml | 25 + apps/webhooks/composer/autoload.php | 25 + apps/webhooks/composer/composer.json | 13 + apps/webhooks/composer/composer.lock | 18 + .../composer/composer/ClassLoader.php | 579 +++++++++++++++ .../composer/composer/InstalledVersions.php | 359 +++++++++ apps/webhooks/composer/composer/LICENSE | 21 + .../composer/composer/autoload_classmap.php | 18 + .../composer/composer/autoload_namespaces.php | 9 + .../composer/composer/autoload_psr4.php | 10 + .../composer/composer/autoload_real.php | 37 + .../composer/composer/autoload_static.php | 44 ++ .../webhooks/composer/composer/installed.json | 5 + apps/webhooks/composer/composer/installed.php | 23 + apps/webhooks/img/app-dark.svg | 1 + apps/webhooks/img/app.svg | 1 + apps/webhooks/lib/AppInfo/Application.php | 55 ++ .../lib/BackgroundJobs/WebhookCall.php | 49 ++ apps/webhooks/lib/Command/Index.php | 83 +++ .../lib/Controller/WebhooksController.php | 193 +++++ apps/webhooks/lib/Db/WebhookListener.php | 60 ++ .../webhooks/lib/Db/WebhookListenerMapper.php | 151 ++++ .../lib/Listener/WebhooksEventListener.php | 64 ++ .../Version1000Date20240527153425.php | 66 ++ apps/webhooks/lib/ResponseDefinitions.php | 22 + apps/webhooks/openapi.json | 691 ++++++++++++++++++ .../tests/Db/WebhookListenerMapperTest.php | 61 ++ tests/enable_all.php | 1 + 29 files changed, 2685 insertions(+) create mode 100644 apps/webhooks/appinfo/info.xml create mode 100644 apps/webhooks/composer/autoload.php create mode 100644 apps/webhooks/composer/composer.json create mode 100644 apps/webhooks/composer/composer.lock create mode 100644 apps/webhooks/composer/composer/ClassLoader.php create mode 100644 apps/webhooks/composer/composer/InstalledVersions.php create mode 100644 apps/webhooks/composer/composer/LICENSE create mode 100644 apps/webhooks/composer/composer/autoload_classmap.php create mode 100644 apps/webhooks/composer/composer/autoload_namespaces.php create mode 100644 apps/webhooks/composer/composer/autoload_psr4.php create mode 100644 apps/webhooks/composer/composer/autoload_real.php create mode 100644 apps/webhooks/composer/composer/autoload_static.php create mode 100644 apps/webhooks/composer/composer/installed.json create mode 100644 apps/webhooks/composer/composer/installed.php create mode 100644 apps/webhooks/img/app-dark.svg create mode 100644 apps/webhooks/img/app.svg create mode 100644 apps/webhooks/lib/AppInfo/Application.php create mode 100644 apps/webhooks/lib/BackgroundJobs/WebhookCall.php create mode 100644 apps/webhooks/lib/Command/Index.php create mode 100644 apps/webhooks/lib/Controller/WebhooksController.php create mode 100644 apps/webhooks/lib/Db/WebhookListener.php create mode 100644 apps/webhooks/lib/Db/WebhookListenerMapper.php create mode 100644 apps/webhooks/lib/Listener/WebhooksEventListener.php create mode 100755 apps/webhooks/lib/Migration/Version1000Date20240527153425.php create mode 100644 apps/webhooks/lib/ResponseDefinitions.php create mode 100644 apps/webhooks/openapi.json create mode 100644 apps/webhooks/tests/Db/WebhookListenerMapperTest.php diff --git a/.gitignore b/.gitignore index 2e73df093df..e9a27c5d68a 100644 --- a/.gitignore +++ b/.gitignore @@ -45,6 +45,7 @@ !/apps/twofactor_backupcodes !/apps/user_status !/apps/weather_status +!/apps/webhooks !/apps/workflowengine /apps/files_external/3rdparty/irodsphp/PHPUnitTest /apps/files_external/3rdparty/irodsphp/web diff --git a/apps/webhooks/appinfo/info.xml b/apps/webhooks/appinfo/info.xml new file mode 100644 index 00000000000..8e1d706d06f --- /dev/null +++ b/apps/webhooks/appinfo/info.xml @@ -0,0 +1,25 @@ + + + webhooks + Nextcloud webhook support + Nextcloud webhook support + Nextcloud webhook support + 1.0.0-dev + agpl + Côme Chilliet + Webhooks + + + + + + customization + https://github.com/nextcloud/server + https://github.com/nextcloud/server/issues + https://github.com/nextcloud/server.git + + + + + diff --git a/apps/webhooks/composer/autoload.php b/apps/webhooks/composer/autoload.php new file mode 100644 index 00000000000..81ca3547149 --- /dev/null +++ b/apps/webhooks/composer/autoload.php @@ -0,0 +1,25 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var string|null */ + private $vendorDir; + + // PSR-4 + /** + * @var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var list + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * List of PSR-0 prefixes + * + * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) + * + * @var array>> + */ + private $prefixesPsr0 = array(); + /** + * @var list + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var array + */ + private $missingClasses = array(); + + /** @var string|null */ + private $apcuPrefix; + + /** + * @var array + */ + private static $registeredLoaders = array(); + + /** + * @param string|null $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return array> + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return list + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return list + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return array Array of classname => path + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + $includeFile = self::$includeFile; + $includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders keyed by their corresponding vendor directories. + * + * @return array + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/apps/webhooks/composer/composer/InstalledVersions.php b/apps/webhooks/composer/composer/InstalledVersions.php new file mode 100644 index 00000000000..51e734a774b --- /dev/null +++ b/apps/webhooks/composer/composer/InstalledVersions.php @@ -0,0 +1,359 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints((string) $constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + $installed[] = self::$installedByVendor[$vendorDir] = $required; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (self::$installed !== array()) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/apps/webhooks/composer/composer/LICENSE b/apps/webhooks/composer/composer/LICENSE new file mode 100644 index 00000000000..f27399a042d --- /dev/null +++ b/apps/webhooks/composer/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/apps/webhooks/composer/composer/autoload_classmap.php b/apps/webhooks/composer/composer/autoload_classmap.php new file mode 100644 index 00000000000..64646e93a02 --- /dev/null +++ b/apps/webhooks/composer/composer/autoload_classmap.php @@ -0,0 +1,18 @@ + $vendorDir . '/composer/InstalledVersions.php', + 'OCA\\Webhooks\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php', + 'OCA\\Webhooks\\BackgroundJobs\\WebhookCall' => $baseDir . '/../lib/BackgroundJobs/WebhookCall.php', + 'OCA\\Webhooks\\Controller\\WebhooksController' => $baseDir . '/../lib/Controller/WebhooksController.php', + 'OCA\\Webhooks\\Db\\WebhookListener' => $baseDir . '/../lib/Db/WebhookListener.php', + 'OCA\\Webhooks\\Db\\WebhookListenerMapper' => $baseDir . '/../lib/Db/WebhookListenerMapper.php', + 'OCA\\Webhooks\\Listener\\WebhooksEventListener' => $baseDir . '/../lib/Listener/WebhooksEventListener.php', + 'OCA\\Webhooks\\Migration\\Version1000Date20240527153425' => $baseDir . '/../lib/Migration/Version1000Date20240527153425.php', + 'OCA\\Webhooks\\ResponseDefinitions' => $baseDir . '/../lib/ResponseDefinitions.php', +); diff --git a/apps/webhooks/composer/composer/autoload_namespaces.php b/apps/webhooks/composer/composer/autoload_namespaces.php new file mode 100644 index 00000000000..3f5c9296251 --- /dev/null +++ b/apps/webhooks/composer/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($baseDir . '/../lib'), +); diff --git a/apps/webhooks/composer/composer/autoload_real.php b/apps/webhooks/composer/composer/autoload_real.php new file mode 100644 index 00000000000..1b1742c422e --- /dev/null +++ b/apps/webhooks/composer/composer/autoload_real.php @@ -0,0 +1,37 @@ +setClassMapAuthoritative(true); + $loader->register(true); + + return $loader; + } +} diff --git a/apps/webhooks/composer/composer/autoload_static.php b/apps/webhooks/composer/composer/autoload_static.php new file mode 100644 index 00000000000..ef878885cab --- /dev/null +++ b/apps/webhooks/composer/composer/autoload_static.php @@ -0,0 +1,44 @@ + + array ( + 'OCA\\Webhooks\\' => 13, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'OCA\\Webhooks\\' => + array ( + 0 => __DIR__ . '/..' . '/../lib', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'OCA\\Webhooks\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php', + 'OCA\\Webhooks\\BackgroundJobs\\WebhookCall' => __DIR__ . '/..' . '/../lib/BackgroundJobs/WebhookCall.php', + 'OCA\\Webhooks\\Controller\\WebhooksController' => __DIR__ . '/..' . '/../lib/Controller/WebhooksController.php', + 'OCA\\Webhooks\\Db\\WebhookListener' => __DIR__ . '/..' . '/../lib/Db/WebhookListener.php', + 'OCA\\Webhooks\\Db\\WebhookListenerMapper' => __DIR__ . '/..' . '/../lib/Db/WebhookListenerMapper.php', + 'OCA\\Webhooks\\Listener\\WebhooksEventListener' => __DIR__ . '/..' . '/../lib/Listener/WebhooksEventListener.php', + 'OCA\\Webhooks\\Migration\\Version1000Date20240527153425' => __DIR__ . '/..' . '/../lib/Migration/Version1000Date20240527153425.php', + 'OCA\\Webhooks\\ResponseDefinitions' => __DIR__ . '/..' . '/../lib/ResponseDefinitions.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitWebhooks::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitWebhooks::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitWebhooks::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/apps/webhooks/composer/composer/installed.json b/apps/webhooks/composer/composer/installed.json new file mode 100644 index 00000000000..f20a6c47c6d --- /dev/null +++ b/apps/webhooks/composer/composer/installed.json @@ -0,0 +1,5 @@ +{ + "packages": [], + "dev": false, + "dev-package-names": [] +} diff --git a/apps/webhooks/composer/composer/installed.php b/apps/webhooks/composer/composer/installed.php new file mode 100644 index 00000000000..1a66c7f2416 --- /dev/null +++ b/apps/webhooks/composer/composer/installed.php @@ -0,0 +1,23 @@ + array( + 'name' => '__root__', + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => 'b1797842784b250fb01ed5e3bf130705eb94751b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../', + 'aliases' => array(), + 'dev' => false, + ), + 'versions' => array( + '__root__' => array( + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => 'b1797842784b250fb01ed5e3bf130705eb94751b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/apps/webhooks/img/app-dark.svg b/apps/webhooks/img/app-dark.svg new file mode 100644 index 00000000000..148495ade91 --- /dev/null +++ b/apps/webhooks/img/app-dark.svg @@ -0,0 +1 @@ + diff --git a/apps/webhooks/img/app.svg b/apps/webhooks/img/app.svg new file mode 100644 index 00000000000..8d98fac4b69 --- /dev/null +++ b/apps/webhooks/img/app.svg @@ -0,0 +1 @@ + diff --git a/apps/webhooks/lib/AppInfo/Application.php b/apps/webhooks/lib/AppInfo/Application.php new file mode 100644 index 00000000000..a8836a25f54 --- /dev/null +++ b/apps/webhooks/lib/AppInfo/Application.php @@ -0,0 +1,55 @@ +injectFn($this->registerRuleListeners(...)); + } + + private function registerRuleListeners( + IEventDispatcher $dispatcher, + ContainerInterface $container, + LoggerInterface $logger, + ): void { + /** @var WebhookListenerMapper */ + $mapper = $container->get(WebhookListenerMapper::class); + + /* Listen to all events with at least one webhook configured */ + $configuredEvents = $mapper->getAllConfiguredEvents(); + foreach ($configuredEvents as $eventName) { + // $logger->error($eventName.' '.\OCP\Files\Events\Node\NodeWrittenEvent::class, ['exception' => new \Exception('coucou')]); + $dispatcher->addServiceListener( + $eventName, + WebhooksEventListener::class, + -1, + ); + } + } +} diff --git a/apps/webhooks/lib/BackgroundJobs/WebhookCall.php b/apps/webhooks/lib/BackgroundJobs/WebhookCall.php new file mode 100644 index 00000000000..9b113a5c1fc --- /dev/null +++ b/apps/webhooks/lib/BackgroundJobs/WebhookCall.php @@ -0,0 +1,49 @@ +mapper->getById($webhookId); + $client = $this->clientService->newClient(); + $options = []; + $options['body'] = json_encode([ + 'event' => $event, + 'userid' => $userId, + ]); + try { + $response = $client->request($webhookListener->getHttpMethod(), $webhookListener->getUri(), $options); + $statusCode = $response->getStatusCode(); + if ($statusCode >= 200 && $statusCode < 300) { + $this->logger->warning('Webhook returned unexpected status code '.$statusCode, ['body' => $response->getBody()]); + } else { + $this->logger->debug('Webhook returned status code '.$statusCode, ['body' => $response->getBody()]); + } + } catch (\Exception $e) { + $this->logger->error('Webhook call failed: '.$e->getMessage(), ['exception' => $e]); + } + } +} diff --git a/apps/webhooks/lib/Command/Index.php b/apps/webhooks/lib/Command/Index.php new file mode 100644 index 00000000000..4f418b4ffc7 --- /dev/null +++ b/apps/webhooks/lib/Command/Index.php @@ -0,0 +1,83 @@ + + * + * @author Arthur Schiwon + * @author Joas Schilling + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ +namespace OCA\WorkflowEngine\Command; + +use OCA\WorkflowEngine\Helper\ScopeContext; +use OCA\WorkflowEngine\Manager; +use OCP\WorkflowEngine\IManager; +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 Index extends Command { + + /** @var Manager */ + private $manager; + + public function __construct(Manager $manager) { + $this->manager = $manager; + parent::__construct(); + } + + protected function configure() { + $this + ->setName('workflows:list') + ->setDescription('Lists configured workflows') + ->addArgument( + 'scope', + InputArgument::OPTIONAL, + 'Lists workflows for "admin", "user"', + 'admin' + ) + ->addArgument( + 'scopeId', + InputArgument::OPTIONAL, + 'User IDs when the scope is "user"', + null + ); + } + + protected function mappedScope(string $scope): int { + static $scopes = [ + 'admin' => IManager::SCOPE_ADMIN, + 'user' => IManager::SCOPE_USER, + ]; + return $scopes[$scope] ?? -1; + } + + protected function execute(InputInterface $input, OutputInterface $output): int { + $ops = $this->manager->getAllOperations( + new ScopeContext( + $this->mappedScope($input->getArgument('scope')), + $input->getArgument('scopeId') + ) + ); + $output->writeln(\json_encode($ops)); + return 0; + } +} diff --git a/apps/webhooks/lib/Controller/WebhooksController.php b/apps/webhooks/lib/Controller/WebhooksController.php new file mode 100644 index 00000000000..b5aa14449ec --- /dev/null +++ b/apps/webhooks/lib/Controller/WebhooksController.php @@ -0,0 +1,193 @@ + + * + * 200: Webhook registrations returned + */ + #[ApiRoute(verb: 'GET', url: '/api/v1/webhooks')] + public function index(): DataResponse { + $webhookListeners = $this->mapper->getAll(); + + return new DataResponse($webhookListeners); + } + + /** + * Get details on a registered webhook + * + * @param int $id id of the webhook + * + * @return DataResponse + * + * 200: Webhook registration returned + */ + #[ApiRoute(verb: 'GET', url: '/api/v1/webhooks/{id}')] + public function show(int $id): DataResponse { + return new DataResponse($this->mapper->getById($id)); + } + + /** + * Register a new webhook + * + * @param string $httpMethod HTTP method to use to contact the webhook + * @param string $uri Webhook URI endpoint + * @param string $event Event class name to listen to + * @param ?array $headers Array of headers to send + * @param ?string $authMethod Authentication method to use. TODO + * @param ?array $authData Array of data for authentication + * + * @return DataResponse + * + * 200: Webhook registration returned + * + * @throws OCSBadRequestException Bad request + * @throws OCSForbiddenException Insufficient permissions + * @throws OCSException Other error + */ + #[ApiRoute(verb: 'POST', url: '/api/v1/webhooks')] + public function create( + string $httpMethod, + string $uri, + string $event, + ?array $headers, + ?string $authMethod, + ?array $authData, + ): DataResponse { + try { + $webhookListener = $this->mapper->addWebhookListener( + $this->userId, + $httpMethod, + $uri, + $event, + $headers, + $authMethod, + $authData, + ); + return new DataResponse($webhookListener); + } catch (\UnexpectedValueException $e) { + throw new OCSBadRequestException($e->getMessage(), $e); + } catch (\DomainException $e) { + throw new OCSForbiddenException($e->getMessage(), $e); + } catch (\Exception $e) { + $this->logger->error('Error when inserting webhook', ['exception' => $e]); + throw new OCSException('An internal error occurred', $e->getCode(), $e); + } + } + + /** + * Update an existing webhook registration + * + * @param int $id id of the webhook + * @param string $httpMethod HTTP method to use to contact the webhook + * @param string $uri Webhook URI endpoint + * @param string $event Event class name to listen to + * @param ?array $headers Array of headers to send + * @param ?string $authMethod Authentication method to use. TODO + * @param ?array $authData Array of data for authentication + * + * @return DataResponse + * + * 200: Webhook registration returned + * + * @throws OCSBadRequestException Bad request + * @throws OCSForbiddenException Insufficient permissions + * @throws OCSException Other error + */ + #[ApiRoute(verb: 'POST', url: '/api/v1/webhooks/{id}')] + public function update( + int $id, + string $httpMethod, + string $uri, + string $event, + ?array $headers, + ?string $authMethod, + ?array $authData, + ): DataResponse { + try { + $webhookListener = $this->mapper->updateWebhookListener( + $id, + $this->userId, + $httpMethod, + $uri, + $event, + $headers, + $authMethod, + $authData, + ); + return new DataResponse($webhookListener); + } catch (\UnexpectedValueException $e) { + throw new OCSBadRequestException($e->getMessage(), $e); + } catch (\DomainException $e) { + throw new OCSForbiddenException($e->getMessage(), $e); + } catch (\Exception $e) { + $this->logger->error('Error when updating flow with id ' . $id, ['exception' => $e]); + throw new OCSException('An internal error occurred', $e->getCode(), $e); + } + } + + /** + * Remove an existing webhook registration + * + * @param int $id id of the webhook + * + * @return DataResponse + * + * 200: Boolean returned whether something was deleted FIXME + * + * @throws OCSBadRequestException Bad request + * @throws OCSForbiddenException Insufficient permissions + * @throws OCSException Other error + */ + #[ApiRoute(verb: 'DELETE', url: '/api/v1/webhooks/{id}')] + public function destroy(int $id): DataResponse { + try { + $deleted = $this->mapper->deleteById($id); + return new DataResponse($deleted); + } catch (\UnexpectedValueException $e) { + throw new OCSBadRequestException($e->getMessage(), $e); + } catch (\DomainException $e) { + throw new OCSForbiddenException($e->getMessage(), $e); + } catch (Exception $e) { + $this->logger->error('Error when deleting flow with id ' . $id, ['exception' => $e]); + throw new OCSException('An internal error occurred', $e->getCode(), $e); + } + } +} diff --git a/apps/webhooks/lib/Db/WebhookListener.php b/apps/webhooks/lib/Db/WebhookListener.php new file mode 100644 index 00000000000..0d731e72d7f --- /dev/null +++ b/apps/webhooks/lib/Db/WebhookListener.php @@ -0,0 +1,60 @@ +addType('userId', 'string'); + $this->addType('httpMethod', 'string'); + $this->addType('uri', 'string'); + $this->addType('event', 'string'); + $this->addType('headers', 'json'); + $this->addType('authMethod', 'string'); + $this->addType('authData', 'json'); + } + + public function jsonSerialize(): array { + $fields = array_keys($this->getFieldTypes()); + return array_combine( + $fields, + array_map( + fn ($field) => $this->getter($field), + $fields + ) + ); + } +} diff --git a/apps/webhooks/lib/Db/WebhookListenerMapper.php b/apps/webhooks/lib/Db/WebhookListenerMapper.php new file mode 100644 index 00000000000..773358d671c --- /dev/null +++ b/apps/webhooks/lib/Db/WebhookListenerMapper.php @@ -0,0 +1,151 @@ + + */ +class WebhookListenerMapper extends QBMapper { + public const TABLE_NAME = 'webhook_listeners'; + + public function __construct(IDBConnection $db) { + parent::__construct($db, self::TABLE_NAME, WebhookListener::class); + } + + /** + * @throws DoesNotExistException + * @throws MultipleObjectsReturnedException + * @throws Exception + */ + public function getById(int $id): WebhookListener { + $qb = $this->db->getQueryBuilder(); + + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))); + + return $this->findEntity($qb); + } + + /** + * @throws DoesNotExistException + * @throws MultipleObjectsReturnedException + * @throws Exception + * @return WebhookListener[] + */ + public function getAll(): array { + $qb = $this->db->getQueryBuilder(); + + $qb->select('*') + ->from($this->getTableName()); + + return $this->findEntities($qb); + } + + public function addWebhookListener( + string $userId, + string $httpMethod, + string $uri, + string $event, + ?array $headers, + ?string $authMethod, + ?array $authData, + ) { + $webhookListener = WebhookListener::fromParams( + [ + 'userId' => $userId, + 'httpMethod' => $httpMethod, + 'uri' => $uri, + 'event' => $event, + 'headers' => $headers, + 'authMethod' => $authMethod ?? 'none', + 'authData' => $authData, + ] + ); + return $this->insert($webhookListener); + } + + public function updateWebhookListener( + int $id, + string $userId, + string $httpMethod, + string $uri, + string $event, + ?array $headers, + ?string $authMethod, + ?array $authData, + ) { + $webhookListener = WebhookListener::fromParams( + [ + 'id' => $id, + 'userId' => $userId, + 'httpMethod' => $httpMethod, + 'uri' => $uri, + 'event' => $event, + 'headers' => $headers, + 'authMethod' => $authMethod, + 'authData' => $authData, + ] + ); + return $this->update($webhookListener); + } + + /** + * @throws DoesNotExistException + * @throws MultipleObjectsReturnedException + * @throws Exception + */ + public function deleteById(int $id): bool { + $qb = $this->db->getQueryBuilder(); + + $qb->delete($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))); + + return ($qb->executeStatement() > 0); + } + + /** + * @return list + * TODO cache + */ + public function getAllConfiguredEvents(): array { + $qb = $this->db->getQueryBuilder(); + + $qb->selectDistinct('event') + ->from($this->getTableName()); + + $result = $qb->executeQuery(); + + $configuredEvents = []; + + while (($event = $result->fetchOne()) !== false) { + $configuredEvents[] = $event; + } + + return $configuredEvents; + } + + public function getByEvent(string $event): array { + $qb = $this->db->getQueryBuilder(); + + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('event', $qb->createNamedParameter($event, IQueryBuilder::PARAM_STR))); + + return $this->findEntities($qb); + } +} diff --git a/apps/webhooks/lib/Listener/WebhooksEventListener.php b/apps/webhooks/lib/Listener/WebhooksEventListener.php new file mode 100644 index 00000000000..8e935f1d0ce --- /dev/null +++ b/apps/webhooks/lib/Listener/WebhooksEventListener.php @@ -0,0 +1,64 @@ + + */ +class WebhooksEventListener implements IEventListener { + public function __construct( + private WebhookListenerMapper $mapper, + private IJobList $jobList, + private LoggerInterface $logger, + private ?string $userId, + ) { + } + + public function handle(Event $event): void { + $webhookListeners = $this->mapper->getByEvent($event::class); + + foreach ($webhookListeners as $webhookListener) { + $this->jobList->add(WebhookCall::class, [$this->serializeEvent($event), $this->userId, $webhookListener->getId(), time()]); + } + } + + private function serializeEvent(Event $event): array|\JsonSerializable { + if ($event instanceof \JsonSerializable) { + return $event; + } else { + /* Event is not serializable, we fallback to reflection to still send something */ + $data = ['class' => $event::class]; + $ref = new \ReflectionClass($event); + foreach ($ref->getMethods() as $method) { + if (str_starts_with($method->getName(), 'get')) { + $key = strtolower(substr($method->getName(), 3)); + $value = $method->invoke($event); + if ($value instanceof \OCP\Files\FileInfo) { + $value = [ + 'id' => $value->getId(), + 'path' => $value->getPath(), + ]; + } + $data[$key] = $value; + } + } + $this->logger->debug('Webhook had to use fallback to serialize event '.$event::class); + return $data; + } + } +} diff --git a/apps/webhooks/lib/Migration/Version1000Date20240527153425.php b/apps/webhooks/lib/Migration/Version1000Date20240527153425.php new file mode 100755 index 00000000000..18f8b545ddf --- /dev/null +++ b/apps/webhooks/lib/Migration/Version1000Date20240527153425.php @@ -0,0 +1,66 @@ +hasTable(WebhookListenerMapper::TABLE_NAME)) { + $table = $schema->createTable(WebhookListenerMapper::TABLE_NAME); + $table->addColumn('id', Types::INTEGER, [ + 'autoincrement' => true, + 'notnull' => true, + 'length' => 4, + ]); + $table->addColumn('user_id', Types::STRING, [ + 'notnull' => true, + 'length' => 64, + ]); + $table->addColumn('http_method', Types::STRING, [ + 'notnull' => true, + 'length' => 32, + ]); + $table->addColumn('uri', Types::STRING, [ + 'notnull' => true, + 'length' => 256, + ]); + $table->addColumn('event', Types::TEXT, [ + 'notnull' => true, + ]); + $table->addColumn('headers', Types::TEXT, [ + 'notnull' => false, + ]); + // TODO decide if string or int with an Enum + $table->addColumn('auth_method', Types::STRING, [ + 'notnull' => true, + 'length' => 16, + 'default' => '', + ]); + $table->addColumn('auth_data', Types::TEXT, [ + 'notnull' => false, + ]); + $table->setPrimaryKey(['id']); + return $schema; + } + return null; + } +} diff --git a/apps/webhooks/lib/ResponseDefinitions.php b/apps/webhooks/lib/ResponseDefinitions.php new file mode 100644 index 00000000000..d730c0d9e2c --- /dev/null +++ b/apps/webhooks/lib/ResponseDefinitions.php @@ -0,0 +1,22 @@ +connection = \OCP\Server::get(IDBConnection::class); + $this->pruneTables(); + + $this->mapper = new WebhookListenerMapper( + $this->connection, + ); + } + + protected function tearDown(): void { + $this->pruneTables(); + parent::tearDown(); + } + + protected function pruneTables() { + $query = $this->connection->getQueryBuilder(); + $query->delete(WebhookListenerMapper::TABLE_NAME)->executeStatement(); + } + + public function testInsertListenerAndGetIt() { + $listener1 = $this->mapper->addWebhookListener( + 'bob', + 'POST', + 'https://webhook.example.com/endpoint', + UserCreatedEvent::class, + null, + null, + null, + ); + + $listener2 = $this->mapper->getById($listener1->getId()); + + $listener1->resetUpdatedFields(); + $this->assertEquals($listener1, $listener2); + } +} diff --git a/tests/enable_all.php b/tests/enable_all.php index b95f00f767e..35217db079a 100644 --- a/tests/enable_all.php +++ b/tests/enable_all.php @@ -24,3 +24,4 @@ enableApp('provisioning_api'); enableApp('federation'); enableApp('federatedfilesharing'); enableApp('admin_audit'); +enableApp('webhooks'); -- 2.39.5