feat: Add webhooks application

Signed-off-by: Côme Chilliet <come.chilliet@nextcloud.com>
pull/45475/head
Côme Chilliet 6 months ago committed by Côme Chilliet
parent d835d23e3a
commit aa974a4322
  1. 1
      .gitignore
  2. 25
      apps/webhooks/appinfo/info.xml
  3. 25
      apps/webhooks/composer/autoload.php
  4. 13
      apps/webhooks/composer/composer.json
  5. 18
      apps/webhooks/composer/composer.lock
  6. 579
      apps/webhooks/composer/composer/ClassLoader.php
  7. 359
      apps/webhooks/composer/composer/InstalledVersions.php
  8. 21
      apps/webhooks/composer/composer/LICENSE
  9. 18
      apps/webhooks/composer/composer/autoload_classmap.php
  10. 9
      apps/webhooks/composer/composer/autoload_namespaces.php
  11. 10
      apps/webhooks/composer/composer/autoload_psr4.php
  12. 37
      apps/webhooks/composer/composer/autoload_real.php
  13. 44
      apps/webhooks/composer/composer/autoload_static.php
  14. 5
      apps/webhooks/composer/composer/installed.json
  15. 23
      apps/webhooks/composer/composer/installed.php
  16. 1
      apps/webhooks/img/app-dark.svg
  17. 1
      apps/webhooks/img/app.svg
  18. 55
      apps/webhooks/lib/AppInfo/Application.php
  19. 49
      apps/webhooks/lib/BackgroundJobs/WebhookCall.php
  20. 83
      apps/webhooks/lib/Command/Index.php
  21. 193
      apps/webhooks/lib/Controller/WebhooksController.php
  22. 60
      apps/webhooks/lib/Db/WebhookListener.php
  23. 151
      apps/webhooks/lib/Db/WebhookListenerMapper.php
  24. 64
      apps/webhooks/lib/Listener/WebhooksEventListener.php
  25. 66
      apps/webhooks/lib/Migration/Version1000Date20240527153425.php
  26. 22
      apps/webhooks/lib/ResponseDefinitions.php
  27. 691
      apps/webhooks/openapi.json
  28. 61
      apps/webhooks/tests/Db/WebhookListenerMapperTest.php
  29. 1
      tests/enable_all.php

1
.gitignore vendored

@ -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

@ -0,0 +1,25 @@
<?xml version="1.0"?>
<info xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://apps.nextcloud.com/schema/apps/info.xsd">
<id>webhooks</id>
<name>Nextcloud webhook support</name>
<summary>Nextcloud webhook support</summary>
<description>Nextcloud webhook support</description>
<version>1.0.0-dev</version>
<licence>agpl</licence>
<author>Côme Chilliet</author>
<namespace>Webhooks</namespace>
<types>
<filesystem/>
</types>
<category>customization</category>
<website>https://github.com/nextcloud/server</website>
<bugs>https://github.com/nextcloud/server/issues</bugs>
<repository>https://github.com/nextcloud/server.git</repository>
<dependencies>
<nextcloud min-version="30" max-version="30"/>
</dependencies>
</info>

@ -0,0 +1,25 @@
<?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitWebhooks::getLoader();

@ -0,0 +1,13 @@
{
"config" : {
"vendor-dir": ".",
"optimize-autoloader": true,
"classmap-authoritative": true,
"autoloader-suffix": "Webhooks"
},
"autoload" : {
"psr-4": {
"OCA\\Webhooks\\": "../lib/"
}
}
}

@ -0,0 +1,18 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "d751713988987e9331980363e24189ce",
"packages": [],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": [],
"plugin-api-version": "2.1.0"
}

@ -0,0 +1,579 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* 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 <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @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<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var list<string>
*/
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<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var string|null */
private $apcuPrefix;
/**
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return list<string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array<string, string> $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>|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>|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>|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>|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<string, self>
*/
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);
}
}

@ -0,0 +1,359 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* 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<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
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<string>
*/
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<string>
*/
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<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
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<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
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<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
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<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $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<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array()) {
$installed[] = self::$installed;
}
return $installed;
}
}

@ -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.

@ -0,0 +1,18 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = $vendorDir;
return array(
'Composer\\InstalledVersions' => $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',
);

@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = $vendorDir;
return array(
);

@ -0,0 +1,10 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = $vendorDir;
return array(
'OCA\\Webhooks\\' => array($baseDir . '/../lib'),
);

@ -0,0 +1,37 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitWebhooks
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInitWebhooks', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInitWebhooks', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitWebhooks::getInitializer($loader));
$loader->setClassMapAuthoritative(true);
$loader->register(true);
return $loader;
}
}

@ -0,0 +1,44 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitWebhooks
{
public static $prefixLengthsPsr4 = array (
'O' =>
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);
}
}

@ -0,0 +1,5 @@
{
"packages": [],
"dev": false,
"dev-package-names": []
}

@ -0,0 +1,23 @@
<?php return array(
'root' => 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,
),
),
);

@ -0,0 +1 @@
<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="m3.084 3c-1.0027 0-1.834 0.83129-1.834 1.834v2.166h-0.23633c-1.3523-0.019125-1.3523 2.0191 0 2h0.23633v2.166c0 1.0027 0.83129 1.834 1.834 1.834h4.332c1.0027 0 1.834-0.83129 1.834-1.834v-2.166h3.3359l-1.7832 1.7832c-0.98163 0.94251 0.47151 2.3957 1.4141 1.4141l3.4902-3.4902c0.387-0.3878 0.391-1.0229 0-1.4141l-3.4902-3.4902c-0.1883-0.1935-0.4468-0.30271-0.7168-0.30273-0.8974 0-1.3404 1.0909-0.69727 1.7168l1.7832 1.7832h-3.3359v-2.166c0-1.0027-0.83129-1.834-1.834-1.834h-4.332zm0 1.5h4.332c0.19764 0 0.33398 0.13634 0.33398 0.33398v6.332c0 0.19764-0.13634 0.33398-0.33398 0.33398h-4.332c-0.19764 0-0.33398-0.13634-0.33398-0.33398v-6.332c0-0.19764 0.13634-0.33398 0.33398-0.33398z"/></svg>

After

Width:  |  Height:  |  Size: 796 B

@ -0,0 +1 @@
<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="m3.084 3c-1.0027 0-1.834 0.83129-1.834 1.834v2.166h-0.23633c-1.3523-0.019125-1.3523 2.0191 0 2h0.23633v2.166c0 1.0027 0.83129 1.834 1.834 1.834h4.332c1.0027 0 1.834-0.83129 1.834-1.834v-2.166h3.3359l-1.7832 1.7832c-0.98163 0.94251 0.47151 2.3957 1.4141 1.4141l3.4902-3.4902c0.387-0.3878 0.391-1.0229 0-1.4141l-3.4902-3.4902c-0.1883-0.1935-0.4468-0.30271-0.7168-0.30273-0.8974 0-1.3404 1.0909-0.69727 1.7168l1.7832 1.7832h-3.3359v-2.166c0-1.0027-0.83129-1.834-1.834-1.834h-4.332zm0 1.5h4.332c0.19764 0 0.33398 0.13634 0.33398 0.33398v6.332c0 0.19764-0.13634 0.33398-0.33398 0.33398h-4.332c-0.19764 0-0.33398-0.13634-0.33398-0.33398v-6.332c0-0.19764 0.13634-0.33398 0.33398-0.33398z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 808 B

@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Webhooks\AppInfo;
use OCA\Webhooks\Db\WebhookListenerMapper;
use OCA\Webhooks\Listener\WebhooksEventListener;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IBootstrap;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\EventDispatcher\IEventDispatcher;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
class Application extends App implements IBootstrap {
public const APP_ID = 'webhooks';
public function __construct() {
parent::__construct(self::APP_ID);
}
public function register(IRegistrationContext $context): void {
}
public function boot(IBootContext $context): void {
$context->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,
);
}
}
}

@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Webhooks\BackgroundJobs;
use OCA\Webhooks\Db\WebhookListenerMapper;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\QueuedJob;
use OCP\Http\Client\IClientService;
use Psr\Log\LoggerInterface;
class WebhookCall extends QueuedJob {
public function __construct(
private IClientService $clientService,
private WebhookListenerMapper $mapper,
private LoggerInterface $logger,
ITimeFactory $timeFactory,
) {
parent::__construct($timeFactory);
}
protected function run($argument): void {
[$event, $userId, $webhookId] = $argument;
$webhookListener = $this->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]);
}
}
}

@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Joas Schilling <coding@schilljs.com>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
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;
}
}

@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Webhooks\Controller;
use Doctrine\DBAL\Exception;
use OCA\Webhooks\Db\WebhookListenerMapper;
use OCP\AppFramework\Http\Attribute\ApiRoute;
use OCP\AppFramework\Http\Attribute\OpenAPI;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\AppFramework\OCS\OCSException;
use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCSController;
use OCP\IRequest;
use Psr\Log\LoggerInterface;
/**
* @psalm-import-type WebhooksListenerInfo from ResponseDefinitions
*/
#[OpenAPI(scope: OpenAPI::SCOPE_ADMINISTRATION)]
class WebhooksController extends OCSController {
public function __construct(
string $appName,
IRequest $request,
private LoggerInterface $logger,
private WebhookListenerMapper $mapper,
private ?string $userId,
) {
parent::__construct($appName, $request);
}
/**
* List registered webhooks
*
* @return DataResponse<Http::STATUS_OK, WebhooksListenerInfo[], array{}>
*
* 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<Http::STATUS_OK, WebhooksListenerInfo, array{}>
*
* 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<string,string> $headers Array of headers to send
* @param ?string $authMethod Authentication method to use. TODO
* @param ?array<string,mixed> $authData Array of data for authentication
*
* @return DataResponse<Http::STATUS_OK, WebhooksListenerInfo, array{}>
*
* 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<string,string> $headers Array of headers to send
* @param ?string $authMethod Authentication method to use. TODO
* @param ?array<string,mixed> $authData Array of data for authentication
*
* @return DataResponse<Http::STATUS_OK, WebhooksListenerInfo, array{}>
*
* 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<Http::STATUS_OK, bool, array{}>
*
* 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);
}
}
}

@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Webhooks\Db;
use OCP\AppFramework\Db\Entity;
/**
* @method void setUserId(string $userId)
* @method string getUserId()
*/
class WebhookListener extends Entity implements \JsonSerializable {
/** @var string id of the user who added the webhook listener */
protected $userId;
/** @var string */
protected $httpMethod;
/** @var string */
protected $uri;
/** @var string */
protected $event;
/** @var ?string */
protected $headers;
/** @var ?string */
protected $authMethod;
/** @var ?string */
protected $authData;
public function __construct() {
$this->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
)
);
}
}

@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Webhooks\Db;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\AppFramework\Db\QBMapper;
use OCP\DB\Exception;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
/**
* @template-extends QBMapper<WebhookListener>
*/
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<string>
* 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);
}
}

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Webhooks\Listener;
use OCA\Webhooks\BackgroundJobs\WebhookCall;
use OCA\Webhooks\Db\WebhookListenerMapper;
use OCP\BackgroundJob\IJobList;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use Psr\Log\LoggerInterface;
/**
* The class to handle the share events
* @template-implements IEventListener<Event>
*/
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;
}
}
}

@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Webhooks\Migration;
use Closure;
use OCA\Webhooks\Db\WebhookListenerMapper;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
class Version1000Date20240527153425 extends SimpleMigrationStep {
/**
* @param Closure(): ISchemaWrapper $schemaClosure
*/
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
if (!$schema->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;
}
}

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Webhooks;
/**
* @psalm-type WebhooksListenerInfo = array{
* id: string,
* userId: string,
* httpMethod: string,
* uri: string,
* event?: string,
* }
*/
class ResponseDefinitions {
}

@ -0,0 +1,691 @@
{
"openapi": "3.0.3",
"info": {
"title": "webhooks",
"version": "0.0.1",
"description": "Nextcloud webhook support",
"license": {
"name": "agpl"
}
},
"components": {
"securitySchemes": {
"basic_auth": {
"type": "http",
"scheme": "basic"
},
"bearer_auth": {
"type": "http",
"scheme": "bearer"
}
},
"schemas": {
"ListenerInfo": {
"type": "object",
"required": [
"id",
"userId",
"httpMethod",
"uri"
],
"properties": {
"id": {
"type": "string"
},
"userId": {
"type": "string"
},
"httpMethod": {
"type": "string"
},
"uri": {
"type": "string"
},
"event": {
"type": "string"
}
}
},
"OCSMeta": {
"type": "object",
"required": [
"status",
"statuscode"
],
"properties": {
"status": {
"type": "string"
},
"statuscode": {
"type": "integer"
},
"message": {
"type": "string"
},
"totalitems": {
"type": "string"
},
"itemsperpage": {
"type": "string"
}
}
}
}
},
"paths": {
"/ocs/v2.php/apps/webhooks/api/v1/webhooks": {
"get": {
"operationId": "webhooks-index",
"summary": "List registered webhooks",
"description": "This endpoint requires admin access",
"tags": [
"webhooks"
],
"security": [
{
"bearer_auth": []
},
{
"basic_auth": []
}
],
"parameters": [
{
"name": "OCS-APIRequest",
"in": "header",
"description": "Required to be true for the API request to pass",
"required": true,
"schema": {
"type": "boolean",
"default": true
}
}
],
"responses": {
"200": {
"description": "Webhook registrations returned",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ListenerInfo"
}
}
}
}
}
}
}
}
}
}
},
"post": {
"operationId": "webhooks-create",
"summary": "Register a new webhook",
"description": "This endpoint requires admin access",
"tags": [
"webhooks"
],
"security": [
{
"bearer_auth": []
},
{
"basic_auth": []
}
],
"parameters": [
{
"name": "httpMethod",
"in": "query",
"description": "HTTP method to use to contact the webhook",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "uri",
"in": "query",
"description": "Webhook URI endpoint",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "event",
"in": "query",
"description": "Event class name to listen to",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "headers",
"in": "query",
"description": "Array of headers to send",
"schema": {
"type": "string",
"nullable": true
}
},
{
"name": "authMethod",
"in": "query",
"description": "Authentication method to use. TODO",
"schema": {
"type": "string",
"nullable": true
}
},
{
"name": "authData",
"in": "query",
"description": "Array of data for authentication",
"schema": {
"type": "string",
"nullable": true
}
},
{
"name": "OCS-APIRequest",
"in": "header",
"description": "Required to be true for the API request to pass",
"required": true,
"schema": {
"type": "boolean",
"default": true
}
}
],
"responses": {
"200": {
"description": "Webhook registration returned",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {
"$ref": "#/components/schemas/ListenerInfo"
}
}
}
}
}
}
}
},
"400": {
"description": "Bad request",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {}
}
}
}
}
}
}
},
"403": {
"description": "Insufficient permissions",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {}
}
}
}
}
}
}
}
}
}
},
"/ocs/v2.php/apps/webhooks/api/v1/webhooks/{id}": {
"get": {
"operationId": "webhooks-show",
"summary": "Get details on a registered webhook",
"description": "This endpoint requires admin access",
"tags": [
"webhooks"
],
"security": [
{
"bearer_auth": []
},
{
"basic_auth": []
}
],
"parameters": [
{
"name": "id",
"in": "path",
"description": "id of the webhook",
"required": true,
"schema": {
"type": "integer",
"format": "int64"
}
},
{
"name": "OCS-APIRequest",
"in": "header",
"description": "Required to be true for the API request to pass",
"required": true,
"schema": {
"type": "boolean",
"default": true
}
}
],
"responses": {
"200": {
"description": "Webhook registration returned",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {
"$ref": "#/components/schemas/ListenerInfo"
}
}
}
}
}
}
}
}
}
},
"post": {
"operationId": "webhooks-update",
"summary": "Update an existing webhook registration",
"description": "This endpoint requires admin access",
"tags": [
"webhooks"
],
"security": [
{
"bearer_auth": []
},
{
"basic_auth": []
}
],
"parameters": [
{
"name": "httpMethod",
"in": "query",
"description": "HTTP method to use to contact the webhook",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "uri",
"in": "query",
"description": "Webhook URI endpoint",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "event",
"in": "query",
"description": "Event class name to listen to",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "headers",
"in": "query",
"description": "Array of headers to send",
"schema": {
"type": "string",
"nullable": true
}
},
{
"name": "authMethod",
"in": "query",
"description": "Authentication method to use. TODO",
"schema": {
"type": "string",
"nullable": true
}
},
{
"name": "authData",
"in": "query",
"description": "Array of data for authentication",
"schema": {
"type": "string",
"nullable": true
}
},
{
"name": "id",
"in": "path",
"description": "id of the webhook",
"required": true,
"schema": {
"type": "integer",
"format": "int64"
}
},
{
"name": "OCS-APIRequest",
"in": "header",
"description": "Required to be true for the API request to pass",
"required": true,
"schema": {
"type": "boolean",
"default": true
}
}
],
"responses": {
"200": {
"description": "Webhook registration returned",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {
"$ref": "#/components/schemas/ListenerInfo"
}
}
}
}
}
}
}
},
"400": {
"description": "Bad request",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {}
}
}
}
}
}
}
},
"403": {
"description": "Insufficient permissions",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {}
}
}
}
}
}
}
}
}
},
"delete": {
"operationId": "webhooks-destroy",
"summary": "Remove an existing webhook registration",
"description": "This endpoint requires admin access",
"tags": [
"webhooks"
],
"security": [
{
"bearer_auth": []
},
{
"basic_auth": []
}
],
"parameters": [
{
"name": "id",
"in": "path",
"description": "id of the webhook",
"required": true,
"schema": {
"type": "integer",
"format": "int64"
}
},
{
"name": "OCS-APIRequest",
"in": "header",
"description": "Required to be true for the API request to pass",
"required": true,
"schema": {
"type": "boolean",
"default": true
}
}
],
"responses": {
"200": {
"description": "Boolean returned whether something was deleted FIXME",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {
"type": "boolean"
}
}
}
}
}
}
}
},
"400": {
"description": "Bad request",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {}
}
}
}
}
}
}
},
"403": {
"description": "Insufficient permissions",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {}
}
}
}
}
}
}
}
}
}
}
},
"tags": []
}

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Webhooks\Tests\Db;
use OCA\Webhooks\Db\WebhookListenerMapper;
use OCP\IDBConnection;
use OCP\User\Events\UserCreatedEvent;
use Test\TestCase;
/**
* @group DB
*/
class WebhookListenerMapperTest extends TestCase {
private IDBConnection $connection;
private WebhookListenerMapper $mapper;
protected function setUp(): void {
parent::setUp();
$this->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);
}
}

@ -24,3 +24,4 @@ enableApp('provisioning_api');
enableApp('federation');
enableApp('federatedfilesharing');
enableApp('admin_audit');
enableApp('webhooks');

Loading…
Cancel
Save