diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 55c003a65790f..273ed8dde4c2f 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -11,6 +11,7 @@ /apps/federation/appinfo/info.xml @datenangebot /apps/files/appinfo/info.xml @skjnldsv @Pytal @ArtificialOwl @come-nc @artonge @icewind1991 @szaimen @susnux @Fenn-CS /apps/files_external/appinfo/info.xml @icewind1991 @artonge +/apps/files_reminders/appinfo/info.xml @Pytal /apps/files_sharing/appinfo/info.xml @skjnldsv @come-nc /apps/files_trashbin/appinfo/info.xml @Pytal @icewind1991 /apps/files_versions/appinfo/info.xml @artonge @icewind1991 diff --git a/.gitignore b/.gitignore index e05e79eec6dc5..f56382cc7a255 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,7 @@ !/apps/sharebymail !/apps/encryption !/apps/files_external +!/apps/files_reminders !/apps/files_sharing !/apps/files_trashbin !/apps/files_versions diff --git a/apps/files_reminders/appinfo/info.xml b/apps/files_reminders/appinfo/info.xml new file mode 100644 index 0000000000000..d0a69c1ae7c00 --- /dev/null +++ b/apps/files_reminders/appinfo/info.xml @@ -0,0 +1,32 @@ + + + files_reminders + File reminders + Set file reminders + + 0.1.0-dev + agpl + Christopher Ng + FilesReminders + + files + + https://github.com/nextcloud/server/issues + + + + + + + OCA\FilesReminders\BackgroundJob\CleanUpReminders + OCA\FilesReminders\BackgroundJob\ScheduledNotifications + + + + OCA\FilesReminders\Command\ListCommand + + diff --git a/apps/files_reminders/appinfo/routes.php b/apps/files_reminders/appinfo/routes.php new file mode 100644 index 0000000000000..8dfd785669ba1 --- /dev/null +++ b/apps/files_reminders/appinfo/routes.php @@ -0,0 +1,37 @@ + + * + * @author Christopher Ng + * + * @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 . + * + */ + +$requirements = [ + 'version' => '1', +]; + +return [ + 'ocs' => [ + ['name' => 'Api#get', 'url' => '/api/v{version}/get/{fileId}', 'verb' => 'GET', 'requirements' => $requirements], + ['name' => 'Api#set', 'url' => '/api/v{version}/set/{fileId}', 'verb' => 'PUT', 'requirements' => $requirements], + ['name' => 'Api#remove', 'url' => '/api/v{version}/remove/{fileId}', 'verb' => 'DELETE', 'requirements' => $requirements], + ], +]; diff --git a/apps/files_reminders/composer/autoload.php b/apps/files_reminders/composer/autoload.php new file mode 100644 index 0000000000000..ec4c8a9b85faa --- /dev/null +++ b/apps/files_reminders/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/files_reminders/composer/composer/InstalledVersions.php b/apps/files_reminders/composer/composer/InstalledVersions.php new file mode 100644 index 0000000000000..51e734a774b3e --- /dev/null +++ b/apps/files_reminders/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/files_reminders/composer/composer/LICENSE b/apps/files_reminders/composer/composer/LICENSE new file mode 100644 index 0000000000000..f27399a042d95 --- /dev/null +++ b/apps/files_reminders/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/files_reminders/composer/composer/autoload_classmap.php b/apps/files_reminders/composer/composer/autoload_classmap.php new file mode 100644 index 0000000000000..4f81cd387da29 --- /dev/null +++ b/apps/files_reminders/composer/composer/autoload_classmap.php @@ -0,0 +1,25 @@ + $vendorDir . '/composer/InstalledVersions.php', + 'OCA\\FilesReminders\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php', + 'OCA\\FilesReminders\\BackgroundJob\\CleanUpReminders' => $baseDir . '/../lib/BackgroundJob/CleanUpReminders.php', + 'OCA\\FilesReminders\\BackgroundJob\\ScheduledNotifications' => $baseDir . '/../lib/BackgroundJob/ScheduledNotifications.php', + 'OCA\\FilesReminders\\Command\\ListCommand' => $baseDir . '/../lib/Command/ListCommand.php', + 'OCA\\FilesReminders\\Controller\\ApiController' => $baseDir . '/../lib/Controller/ApiController.php', + 'OCA\\FilesReminders\\Db\\Reminder' => $baseDir . '/../lib/Db/Reminder.php', + 'OCA\\FilesReminders\\Db\\ReminderMapper' => $baseDir . '/../lib/Db/ReminderMapper.php', + 'OCA\\FilesReminders\\Exception\\NodeNotFoundException' => $baseDir . '/../lib/Exception/NodeNotFoundException.php', + 'OCA\\FilesReminders\\Exception\\UserNotFoundException' => $baseDir . '/../lib/Exception/UserNotFoundException.php', + 'OCA\\FilesReminders\\Listener\\NodeDeletedListener' => $baseDir . '/../lib/Listener/NodeDeletedListener.php', + 'OCA\\FilesReminders\\Listener\\UserDeletedListener' => $baseDir . '/../lib/Listener/UserDeletedListener.php', + 'OCA\\FilesReminders\\Migration\\Version10000Date20230725162149' => $baseDir . '/../lib/Migration/Version10000Date20230725162149.php', + 'OCA\\FilesReminders\\Model\\RichReminder' => $baseDir . '/../lib/Model/RichReminder.php', + 'OCA\\FilesReminders\\Notification\\Notifier' => $baseDir . '/../lib/Notification/Notifier.php', + 'OCA\\FilesReminders\\Service\\ReminderService' => $baseDir . '/../lib/Service/ReminderService.php', +); diff --git a/apps/files_reminders/composer/composer/autoload_namespaces.php b/apps/files_reminders/composer/composer/autoload_namespaces.php new file mode 100644 index 0000000000000..3f5c929625125 --- /dev/null +++ b/apps/files_reminders/composer/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($baseDir . '/../lib'), +); diff --git a/apps/files_reminders/composer/composer/autoload_real.php b/apps/files_reminders/composer/composer/autoload_real.php new file mode 100644 index 0000000000000..f7b0857737eb5 --- /dev/null +++ b/apps/files_reminders/composer/composer/autoload_real.php @@ -0,0 +1,37 @@ +setClassMapAuthoritative(true); + $loader->register(true); + + return $loader; + } +} diff --git a/apps/files_reminders/composer/composer/autoload_static.php b/apps/files_reminders/composer/composer/autoload_static.php new file mode 100644 index 0000000000000..eff14f8f56950 --- /dev/null +++ b/apps/files_reminders/composer/composer/autoload_static.php @@ -0,0 +1,51 @@ + + array ( + 'OCA\\FilesReminders\\' => 19, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'OCA\\FilesReminders\\' => + array ( + 0 => __DIR__ . '/..' . '/../lib', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'OCA\\FilesReminders\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php', + 'OCA\\FilesReminders\\BackgroundJob\\CleanUpReminders' => __DIR__ . '/..' . '/../lib/BackgroundJob/CleanUpReminders.php', + 'OCA\\FilesReminders\\BackgroundJob\\ScheduledNotifications' => __DIR__ . '/..' . '/../lib/BackgroundJob/ScheduledNotifications.php', + 'OCA\\FilesReminders\\Command\\ListCommand' => __DIR__ . '/..' . '/../lib/Command/ListCommand.php', + 'OCA\\FilesReminders\\Controller\\ApiController' => __DIR__ . '/..' . '/../lib/Controller/ApiController.php', + 'OCA\\FilesReminders\\Db\\Reminder' => __DIR__ . '/..' . '/../lib/Db/Reminder.php', + 'OCA\\FilesReminders\\Db\\ReminderMapper' => __DIR__ . '/..' . '/../lib/Db/ReminderMapper.php', + 'OCA\\FilesReminders\\Exception\\NodeNotFoundException' => __DIR__ . '/..' . '/../lib/Exception/NodeNotFoundException.php', + 'OCA\\FilesReminders\\Exception\\UserNotFoundException' => __DIR__ . '/..' . '/../lib/Exception/UserNotFoundException.php', + 'OCA\\FilesReminders\\Listener\\NodeDeletedListener' => __DIR__ . '/..' . '/../lib/Listener/NodeDeletedListener.php', + 'OCA\\FilesReminders\\Listener\\UserDeletedListener' => __DIR__ . '/..' . '/../lib/Listener/UserDeletedListener.php', + 'OCA\\FilesReminders\\Migration\\Version10000Date20230725162149' => __DIR__ . '/..' . '/../lib/Migration/Version10000Date20230725162149.php', + 'OCA\\FilesReminders\\Model\\RichReminder' => __DIR__ . '/..' . '/../lib/Model/RichReminder.php', + 'OCA\\FilesReminders\\Notification\\Notifier' => __DIR__ . '/..' . '/../lib/Notification/Notifier.php', + 'OCA\\FilesReminders\\Service\\ReminderService' => __DIR__ . '/..' . '/../lib/Service/ReminderService.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitFilesReminders::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitFilesReminders::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitFilesReminders::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/apps/files_reminders/composer/composer/installed.json b/apps/files_reminders/composer/composer/installed.json new file mode 100644 index 0000000000000..f20a6c47c6d4f --- /dev/null +++ b/apps/files_reminders/composer/composer/installed.json @@ -0,0 +1,5 @@ +{ + "packages": [], + "dev": false, + "dev-package-names": [] +} diff --git a/apps/files_reminders/composer/composer/installed.php b/apps/files_reminders/composer/composer/installed.php new file mode 100644 index 0000000000000..b962688d0b992 --- /dev/null +++ b/apps/files_reminders/composer/composer/installed.php @@ -0,0 +1,23 @@ + array( + 'name' => '__root__', + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => '5a11535c51ae0277f6bb0af048215e329b6068d0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../', + 'aliases' => array(), + 'dev' => false, + ), + 'versions' => array( + '__root__' => array( + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => '5a11535c51ae0277f6bb0af048215e329b6068d0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/apps/files_reminders/lib/AppInfo/Application.php b/apps/files_reminders/lib/AppInfo/Application.php new file mode 100644 index 0000000000000..d35bd5c5de2b3 --- /dev/null +++ b/apps/files_reminders/lib/AppInfo/Application.php @@ -0,0 +1,55 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\AppInfo; + +use OCA\FilesReminders\Listener\NodeDeletedListener; +use OCA\FilesReminders\Listener\UserDeletedListener; +use OCA\FilesReminders\Notification\Notifier; +use OCP\AppFramework\App; +use OCP\AppFramework\Bootstrap\IBootContext; +use OCP\AppFramework\Bootstrap\IBootstrap; +use OCP\AppFramework\Bootstrap\IRegistrationContext; +use OCP\Files\Events\Node\NodeDeletedEvent; +use OCP\User\Events\UserDeletedEvent; + +class Application extends App implements IBootstrap { + public const APP_ID = 'files_reminders'; + + public function __construct() { + parent::__construct(static::APP_ID); + } + + public function boot(IBootContext $context): void { + } + + public function register(IRegistrationContext $context): void { + $context->registerNotifierService(Notifier::class); + + $context->registerEventListener(NodeDeletedEvent::class, NodeDeletedListener::class); + $context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class); + } +} diff --git a/apps/files_reminders/lib/BackgroundJob/CleanUpReminders.php b/apps/files_reminders/lib/BackgroundJob/CleanUpReminders.php new file mode 100644 index 0000000000000..afa8c514a0aa2 --- /dev/null +++ b/apps/files_reminders/lib/BackgroundJob/CleanUpReminders.php @@ -0,0 +1,51 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\BackgroundJob; + +use OCA\FilesReminders\Service\ReminderService; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\BackgroundJob\IJob; +use OCP\BackgroundJob\TimedJob; + +class CleanUpReminders extends TimedJob { + public function __construct( + ITimeFactory $time, + private ReminderService $reminderService, + ) { + parent::__construct($time); + + $this->setInterval(24 * 60 * 60); // 1 day + $this->setTimeSensitivity(IJob::TIME_INSENSITIVE); + } + + /** + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + protected function run($argument) { + $this->reminderService->cleanUp(500); + } +} diff --git a/apps/files_reminders/lib/BackgroundJob/ScheduledNotifications.php b/apps/files_reminders/lib/BackgroundJob/ScheduledNotifications.php new file mode 100644 index 0000000000000..15ae56f069869 --- /dev/null +++ b/apps/files_reminders/lib/BackgroundJob/ScheduledNotifications.php @@ -0,0 +1,59 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\BackgroundJob; + +use OCA\FilesReminders\Db\ReminderMapper; +use OCA\FilesReminders\Service\ReminderService; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\BackgroundJob\Job; +use Psr\Log\LoggerInterface; + +class ScheduledNotifications extends Job { + public function __construct( + ITimeFactory $time, + protected ReminderMapper $reminderMapper, + protected ReminderService $reminderService, + protected LoggerInterface $logger, + ) { + parent::__construct($time); + } + + /** + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function run($argument) { + $reminders = $this->reminderMapper->findOverdue(); + foreach ($reminders as $reminder) { + try { + $this->reminderService->send($reminder); + } catch (DoesNotExistException $e) { + $this->logger->debug('Could not send notification for reminder with id ' . $reminder->getId()); + } + } + } +} diff --git a/apps/files_reminders/lib/Command/ListCommand.php b/apps/files_reminders/lib/Command/ListCommand.php new file mode 100644 index 0000000000000..3f3ce13b8578a --- /dev/null +++ b/apps/files_reminders/lib/Command/ListCommand.php @@ -0,0 +1,118 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Command; + +use DateTimeInterface; +use OC\Core\Command\Base; +use OCA\FilesReminders\Model\RichReminder; +use OCA\FilesReminders\Service\ReminderService; +use OCP\IUserManager; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; + +class ListCommand extends Base { + public function __construct( + private ReminderService $reminderService, + private IUserManager $userManager, + ) { + parent::__construct(); + } + + protected function configure(): void { + $this + ->setName('files:reminders') + ->setDescription('List file reminders') + ->addArgument( + 'user', + InputArgument::OPTIONAL, + 'list reminders for user', + ) + ->addOption( + 'output', + null, + InputOption::VALUE_OPTIONAL, + 'Output format (plain, json or json_pretty, default is plain)', + $this->defaultOutputFormat, + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int { + $io = new SymfonyStyle($input, $output); + + $uid = $input->getArgument('user'); + if ($uid !== null) { + /** @var string $uid */ + $user = $this->userManager->get($uid); + if ($user === null) { + $io->error("Unknown user <$uid>"); + return 1; + } + } + + $reminders = $this->reminderService->getAll($user ?? null); + if (empty($reminders)) { + $io->text('No reminders'); + return 0; + } + + $outputOption = $input->getOption('output'); + switch ($outputOption) { + case static::OUTPUT_FORMAT_JSON: + case static::OUTPUT_FORMAT_JSON_PRETTY: + $this->writeArrayInOutputFormat( + $input, + $io, + array_map( + fn (RichReminder $reminder) => $reminder->jsonSerialize(), + $reminders, + ), + '', + ); + return 0; + default: + $io->table( + ['User Id', 'File Id', 'Path', 'Due Date', 'Updated At', 'Created At', 'Notified'], + array_map( + fn (RichReminder $reminder) => [ + $reminder->getUserId(), + $reminder->getFileId(), + $reminder->getNode()->getPath(), + $reminder->getDueDate()->format(DateTimeInterface::ATOM), // ISO 8601 + $reminder->getUpdatedAt()->format(DateTimeInterface::ATOM), // ISO 8601 + $reminder->getCreatedAt()->format(DateTimeInterface::ATOM), // ISO 8601 + $reminder->getNotified() ? 'true' : 'false', + ], + $reminders, + ), + ); + return 0; + } + } +} diff --git a/apps/files_reminders/lib/Controller/ApiController.php b/apps/files_reminders/lib/Controller/ApiController.php new file mode 100644 index 0000000000000..873088177c195 --- /dev/null +++ b/apps/files_reminders/lib/Controller/ApiController.php @@ -0,0 +1,122 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Controller; + +use DateTime; +use DateTimeInterface; +use DateTimeZone; +use Exception; +use OCA\FilesReminders\Exception\NodeNotFoundException; +use OCA\FilesReminders\Service\ReminderService; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\DataResponse; +use OCP\AppFramework\OCSController; +use OCP\IRequest; +use OCP\IUserSession; +use Psr\Log\LoggerInterface; + +class ApiController extends OCSController { + public function __construct( + string $appName, + IRequest $request, + protected ReminderService $reminderService, + protected IUserSession $userSession, + protected LoggerInterface $logger, + ) { + parent::__construct($appName, $request); + } + + /** + * Get a reminder + */ + public function get(int $fileId): DataResponse { + $user = $this->userSession->getUser(); + if ($user === null) { + return new DataResponse([], Http::STATUS_UNAUTHORIZED); + } + + try { + $reminder = $this->reminderService->getDueForUser($user, $fileId); + $reminderData = [ + 'dueDate' => $reminder->getDueDate()->format(DateTimeInterface::ATOM), // ISO 8601 + ]; + return new DataResponse($reminderData, Http::STATUS_OK); + } catch (DoesNotExistException $e) { + $reminderData = [ + 'dueDate' => null, + ]; + return new DataResponse($reminderData, Http::STATUS_OK); + } + } + + /** + * Set a reminder + * + * @param string $dueDate ISO 8601 formatted date time string + */ + public function set(int $fileId, string $dueDate): DataResponse { + try { + $dueDate = (new DateTime($dueDate))->setTimezone(new DateTimeZone('UTC')); + } catch (Exception $e) { + $this->logger->error($e->getMessage(), ['exception' => $e]); + return new DataResponse([], Http::STATUS_BAD_REQUEST); + } + + $user = $this->userSession->getUser(); + if ($user === null) { + return new DataResponse([], Http::STATUS_UNAUTHORIZED); + } + + try { + $created = $this->reminderService->createOrUpdate($user, $fileId, $dueDate); + if ($created) { + return new DataResponse([], Http::STATUS_CREATED); + } + return new DataResponse([], Http::STATUS_OK); + } catch (NodeNotFoundException $e) { + return new DataResponse([], Http::STATUS_NOT_FOUND); + } + } + + /** + * Remove a reminder + */ + public function remove(int $fileId): DataResponse { + $user = $this->userSession->getUser(); + if ($user === null) { + return new DataResponse([], Http::STATUS_UNAUTHORIZED); + } + + try { + $this->reminderService->remove($user, $fileId); + return new DataResponse([], Http::STATUS_OK); + } catch (DoesNotExistException $e) { + return new DataResponse([], Http::STATUS_NOT_FOUND); + } + } +} diff --git a/apps/files_reminders/lib/Db/Reminder.php b/apps/files_reminders/lib/Db/Reminder.php new file mode 100644 index 0000000000000..36f967f1434b8 --- /dev/null +++ b/apps/files_reminders/lib/Db/Reminder.php @@ -0,0 +1,67 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Db; + +use DateTime; +use OCP\AppFramework\Db\Entity; + +/** + * @method void setUserId(string $userId) + * @method string getUserId() + * + * @method void setFileId(int $fileId) + * @method int getFileId() + * + * @method void setDueDate(DateTime $dueDate) + * @method DateTime getDueDate() + * + * @method void setUpdatedAt(DateTime $updatedAt) + * @method DateTime getUpdatedAt() + * + * @method void setCreatedAt(DateTime $createdAt) + * @method DateTime getCreatedAt() + * + * @method void setNotified(bool $notified) + * @method bool getNotified() + */ +class Reminder extends Entity { + protected $userId; + protected $fileId; + protected $dueDate; + protected $updatedAt; + protected $createdAt; + protected $notified = false; + + public function __construct() { + $this->addType('userId', 'string'); + $this->addType('fileId', 'integer'); + $this->addType('dueDate', 'datetime'); + $this->addType('updatedAt', 'datetime'); + $this->addType('createdAt', 'datetime'); + $this->addType('notified', 'boolean'); + } +} diff --git a/apps/files_reminders/lib/Db/ReminderMapper.php b/apps/files_reminders/lib/Db/ReminderMapper.php new file mode 100644 index 0000000000000..97f7ed0900b65 --- /dev/null +++ b/apps/files_reminders/lib/Db/ReminderMapper.php @@ -0,0 +1,152 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Db; + +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Db\QBMapper; +use OCP\DB\QueryBuilder\IQueryBuilder; +use OCP\Files\Node; +use OCP\IDBConnection; +use OCP\IUser; + +/** + * @template-extends QBMapper + */ +class ReminderMapper extends QBMapper { + public const TABLE_NAME = 'files_reminders'; + + public function __construct(IDBConnection $db) { + parent::__construct( + $db, + static::TABLE_NAME, + Reminder::class, + ); + } + + public function markNotified(Reminder $reminder): Reminder { + $reminderUpdate = new Reminder(); + $reminderUpdate->setId($reminder->getId()); + $reminderUpdate->setNotified(true); + return $this->update($reminderUpdate); + } + + public function find(int $id): Reminder { + $qb = $this->db->getQueryBuilder(); + + $qb->select('id', 'user_id', 'file_id', 'due_date', 'updated_at', 'created_at', 'notified') + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))); + + return $this->findEntity($qb); + } + + /** + * @throws DoesNotExistException + */ + public function findDueForUser(IUser $user, int $fileId): Reminder { + $qb = $this->db->getQueryBuilder(); + + $qb->select('id', 'user_id', 'file_id', 'due_date', 'updated_at', 'created_at', 'notified') + ->from($this->getTableName()) + ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($user->getUID(), IQueryBuilder::PARAM_STR))) + ->andWhere($qb->expr()->eq('file_id', $qb->createNamedParameter($fileId, IQueryBuilder::PARAM_INT))) + ->andWhere($qb->expr()->eq('notified', $qb->createNamedParameter(false, IQueryBuilder::PARAM_BOOL))); + + return $this->findEntity($qb); + } + + /** + * @return Reminder[] + */ + public function findAll() { + $qb = $this->db->getQueryBuilder(); + + $qb->select('id', 'user_id', 'file_id', 'due_date', 'updated_at', 'created_at', 'notified') + ->from($this->getTableName()) + ->orderBy('due_date', 'ASC'); + + return $this->findEntities($qb); + } + + /** + * @return Reminder[] + */ + public function findAllForUser(IUser $user) { + $qb = $this->db->getQueryBuilder(); + + $qb->select('id', 'user_id', 'file_id', 'due_date', 'updated_at', 'created_at', 'notified') + ->from($this->getTableName()) + ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($user->getUID(), IQueryBuilder::PARAM_STR))) + ->orderBy('due_date', 'ASC'); + + return $this->findEntities($qb); + } + + /** + * @return Reminder[] + */ + public function findAllForNode(Node $node) { + $qb = $this->db->getQueryBuilder(); + + $qb->select('id', 'user_id', 'file_id', 'due_date', 'updated_at', 'created_at', 'notified') + ->from($this->getTableName()) + ->where($qb->expr()->eq('file_id', $qb->createNamedParameter($node->getId(), IQueryBuilder::PARAM_INT))) + ->orderBy('due_date', 'ASC'); + + return $this->findEntities($qb); + } + + /** + * @return Reminder[] + */ + public function findOverdue() { + $qb = $this->db->getQueryBuilder(); + + $qb->select('id', 'user_id', 'file_id', 'due_date', 'updated_at', 'created_at', 'notified') + ->from($this->getTableName()) + ->where($qb->expr()->lt('due_date', $qb->createFunction('NOW()'))) + ->andWhere($qb->expr()->eq('notified', $qb->createNamedParameter(false, IQueryBuilder::PARAM_BOOL))) + ->orderBy('due_date', 'ASC'); + + return $this->findEntities($qb); + } + + /** + * @return Reminder[] + */ + public function findNotified(?int $limit = null) { + $qb = $this->db->getQueryBuilder(); + + $qb->select('id', 'user_id', 'file_id', 'due_date', 'updated_at', 'created_at', 'notified') + ->from($this->getTableName()) + ->where($qb->expr()->eq('notified', $qb->createNamedParameter(true, IQueryBuilder::PARAM_BOOL))) + ->orderBy('due_date', 'ASC') + ->setMaxResults($limit); + + return $this->findEntities($qb); + } +} diff --git a/apps/files_reminders/lib/Exception/NodeNotFoundException.php b/apps/files_reminders/lib/Exception/NodeNotFoundException.php new file mode 100644 index 0000000000000..5dfe784f5fc54 --- /dev/null +++ b/apps/files_reminders/lib/Exception/NodeNotFoundException.php @@ -0,0 +1,32 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Exception; + +use Exception; + +class NodeNotFoundException extends Exception { +} diff --git a/apps/files_reminders/lib/Exception/UserNotFoundException.php b/apps/files_reminders/lib/Exception/UserNotFoundException.php new file mode 100644 index 0000000000000..3c57ea475e994 --- /dev/null +++ b/apps/files_reminders/lib/Exception/UserNotFoundException.php @@ -0,0 +1,32 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Exception; + +use Exception; + +class UserNotFoundException extends Exception { +} diff --git a/apps/files_reminders/lib/Listener/NodeDeletedListener.php b/apps/files_reminders/lib/Listener/NodeDeletedListener.php new file mode 100644 index 0000000000000..460ddfd4abe78 --- /dev/null +++ b/apps/files_reminders/lib/Listener/NodeDeletedListener.php @@ -0,0 +1,53 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Listener; + +use OC\Files\Node\NonExistingFile; +use OC\Files\Node\NonExistingFolder; +use OCA\FilesReminders\Service\ReminderService; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventListener; +use OCP\Files\Events\Node\NodeDeletedEvent; + +class NodeDeletedListener implements IEventListener { + public function __construct( + private ReminderService $reminderService, + ) {} + + public function handle(Event $event): void { + if (!($event instanceof NodeDeletedEvent)) { + return; + } + + $node = $event->getNode(); + if ($node instanceof NonExistingFile || $node instanceof NonExistingFolder) { + return; + } + + $this->reminderService->removeAllForNode($node); + } +} diff --git a/apps/files_reminders/lib/Listener/UserDeletedListener.php b/apps/files_reminders/lib/Listener/UserDeletedListener.php new file mode 100644 index 0000000000000..b95102c1cc278 --- /dev/null +++ b/apps/files_reminders/lib/Listener/UserDeletedListener.php @@ -0,0 +1,47 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Listener; + +use OCA\FilesReminders\Service\ReminderService; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventListener; +use OCP\User\Events\UserDeletedEvent; + +class UserDeletedListener implements IEventListener { + public function __construct( + private ReminderService $reminderService, + ) {} + + public function handle(Event $event): void { + if (!($event instanceof UserDeletedEvent)) { + return; + } + + $user = $event->getUser(); + $this->reminderService->removeAllForUser($user); + } +} diff --git a/apps/files_reminders/lib/Migration/Version10000Date20230725162149.php b/apps/files_reminders/lib/Migration/Version10000Date20230725162149.php new file mode 100644 index 0000000000000..76999329d64f0 --- /dev/null +++ b/apps/files_reminders/lib/Migration/Version10000Date20230725162149.php @@ -0,0 +1,82 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Migration; + +use Closure; +use OCA\FilesReminders\Db\ReminderMapper; +use OCP\DB\ISchemaWrapper; +use OCP\DB\Types; +use OCP\Migration\IOutput; +use OCP\Migration\SimpleMigrationStep; + +class Version10000Date20230725162149 extends SimpleMigrationStep { + /** + * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper` + */ + public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { + /** @var ISchemaWrapper $schema */ + $schema = $schemaClosure(); + + if ($schema->hasTable(ReminderMapper::TABLE_NAME)) { + return null; + } + + $table = $schema->createTable(ReminderMapper::TABLE_NAME); + $table->addColumn('id', Types::BIGINT, [ + 'autoincrement' => true, + 'notnull' => true, + 'length' => 20, + 'unsigned' => true, + ]); + $table->addColumn('user_id', Types::STRING, [ + 'notnull' => true, + 'length' => 64, + ]); + $table->addColumn('file_id', Types::BIGINT, [ + 'notnull' => true, + 'length' => 20, + 'unsigned' => true, + ]); + $table->addColumn('due_date', Types::DATETIME, [ + 'notnull' => true, + ]); + $table->addColumn('updated_at', Types::DATETIME, [ + 'notnull' => true, + ]); + $table->addColumn('created_at', Types::DATETIME, [ + 'notnull' => true, + ]); + $table->addColumn('notified', Types::BOOLEAN, [ + 'notnull' => false, + 'default' => false, + ]); + $table->setPrimaryKey(['id']); + $table->addUniqueIndex(['user_id', 'file_id', 'due_date'], 'reminders_uniq_idx'); + + return $schema; + } +} diff --git a/apps/files_reminders/lib/Model/RichReminder.php b/apps/files_reminders/lib/Model/RichReminder.php new file mode 100644 index 0000000000000..10dc89799fe99 --- /dev/null +++ b/apps/files_reminders/lib/Model/RichReminder.php @@ -0,0 +1,75 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Model; + +use DateTimeInterface; +use JsonSerializable; +use OCA\FilesReminders\Db\Reminder; +use OCA\FilesReminders\Exception\NodeNotFoundException; +use OCP\Files\IRootFolder; +use OCP\Files\Node; + +class RichReminder extends Reminder implements JsonSerializable { + public function __construct( + private Reminder $reminder, + private IRootFolder $root, + ) { + parent::__construct(); + } + + /** + * @throws NodeNotFoundException + */ + public function getNode(): Node { + $nodes = $this->root->getUserFolder($this->getUserId())->getById($this->getFileId()); + if (empty($nodes)) { + throw new NodeNotFoundException(); + } + $node = reset($nodes); + return $node; + } + + protected function getter(string $name): mixed { + return $this->reminder->getter($name); + } + + public function __call(string $methodName, array $args) { + return $this->reminder->__call($methodName, $args); + } + + public function jsonSerialize(): array { + return [ + 'userId' => $this->getUserId(), + 'fileId' => $this->getFileId(), + 'path' => $this->getNode()->getPath(), + 'dueDate' => $this->getDueDate()->format(DateTimeInterface::ATOM), // ISO 8601 + 'updatedAt' => $this->getUpdatedAt()->format(DateTimeInterface::ATOM), // ISO 8601 + 'createdAt' => $this->getCreatedAt()->format(DateTimeInterface::ATOM), // ISO 8601 + 'notified' => $this->getNotified(), + ]; + } +} diff --git a/apps/files_reminders/lib/Notification/Notifier.php b/apps/files_reminders/lib/Notification/Notifier.php new file mode 100644 index 0000000000000..2a919d42cae83 --- /dev/null +++ b/apps/files_reminders/lib/Notification/Notifier.php @@ -0,0 +1,132 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Notification; + +use InvalidArgumentException; +use OCA\FilesReminders\AppInfo\Application; +use OCA\FilesReminders\Exception\NodeNotFoundException; +use OCA\FilesReminders\Service\ReminderService; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\Files\FileInfo; +use OCP\IURLGenerator; +use OCP\L10N\IFactory; +use OCP\Notification\IAction; +use OCP\Notification\INotification; +use OCP\Notification\INotifier; + +class Notifier implements INotifier { + public function __construct( + protected IFactory $l10nFactory, + protected IURLGenerator $urlGenerator, + protected ReminderService $reminderService, + ) {} + + public function getID(): string { + return Application::APP_ID; + } + + public function getName(): string { + return $this->l10nFactory->get(Application::APP_ID)->t('File reminders'); + } + + /** + * @throws InvalidArgumentException + */ + public function prepare(INotification $notification, string $languageCode): INotification { + $l = $this->l10nFactory->get(Application::APP_ID, $languageCode); + + if ($notification->getApp() !== Application::APP_ID) { + throw new InvalidArgumentException(); + } + + switch ($notification->getSubject()) { + case 'reminder-due': + $reminderId = (int)$notification->getObjectId(); + try { + $reminder = $this->reminderService->get($reminderId); + } catch (DoesNotExistException $e) { + throw new InvalidArgumentException(); + } + + try { + $node = $reminder->getNode(); + } catch (NodeNotFoundException $e) { + throw new InvalidArgumentException(); + } + $path = rtrim($node->getPath(), '/'); + if (strpos($path, '/' . $notification->getUser() . '/files/') === 0) { + // Remove /user/files/... + $fullPath = $path; + [,,, $path] = explode('/', $fullPath, 4); + } + + $link = $this->urlGenerator->linkToRouteAbsolute( + 'files.viewcontroller.showFile', + ['fileid' => $node->getId()], + ); + + // TRANSLATORS The name placeholder is for a file or folder name + $subject = $l->t('Reminder for {name}'); + $notification + ->setRichSubject( + $subject, + [ + 'name' => [ + 'type' => 'highlight', + 'id' => $node->getId(), + 'name' => $node->getName(), + ], + ], + ) + ->setLink($link); + + $label = match ($node->getType()) { + FileInfo::TYPE_FILE => $l->t('View file'), + FileInfo::TYPE_FOLDER => $l->t('View folder'), + }; + + $this->addActionButton($notification, $label); + break; + default: + throw new InvalidArgumentException(); + break; + } + + return $notification; + } + + protected function addActionButton(INotification $notification, string $label): void { + $action = $notification->createAction(); + + $action->setLabel($label) + ->setParsedLabel($label) + ->setLink($notification->getLink(), IAction::TYPE_WEB) + ->setPrimary(true); + + $notification->addParsedAction($action); + } +} diff --git a/apps/files_reminders/lib/Service/ReminderService.php b/apps/files_reminders/lib/Service/ReminderService.php new file mode 100644 index 0000000000000..5c7193259c12c --- /dev/null +++ b/apps/files_reminders/lib/Service/ReminderService.php @@ -0,0 +1,175 @@ + + * + * @author Christopher Ng + * + * @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\FilesReminders\Service; + +use DateTime; +use DateTimeZone; +use OCA\FilesReminders\AppInfo\Application; +use OCA\FilesReminders\Db\Reminder; +use OCA\FilesReminders\Db\ReminderMapper; +use OCA\FilesReminders\Exception\NodeNotFoundException; +use OCA\FilesReminders\Exception\UserNotFoundException; +use OCA\FilesReminders\Model\RichReminder; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\Files\IRootFolder; +use OCP\Files\Node; +use OCP\IURLGenerator; +use OCP\IUser; +use OCP\IUserManager; +use OCP\Notification\IManager as INotificationManager; +use Psr\Log\LoggerInterface; +use Throwable; + +class ReminderService { + public function __construct( + protected IUserManager $userManager, + protected IURLGenerator $urlGenerator, + protected INotificationManager $notificationManager, + protected ReminderMapper $reminderMapper, + protected IRootFolder $root, + protected LoggerInterface $logger, + ) {} + + /** + * @throws DoesNotExistException + */ + public function get(int $id): RichReminder { + $reminder = $this->reminderMapper->find($id); + return new RichReminder($reminder, $this->root); + } + + /** + * @throws DoesNotExistException + */ + public function getDueForUser(IUser $user, int $fileId): RichReminder { + $reminder = $this->reminderMapper->findDueForUser($user, $fileId); + return new RichReminder($reminder, $this->root); + } + + /** + * @return RichReminder[] + */ + public function getAll(?IUser $user = null) { + $reminders = ($user !== null) + ? $this->reminderMapper->findAllForUser($user) + : $this->reminderMapper->findAll(); + return array_map( + fn (Reminder $reminder) => new RichReminder($reminder, $this->root), + $reminders, + ); + } + + /** + * @return bool true if created, false if updated + * + * @throws NodeNotFoundException + */ + public function createOrUpdate(IUser $user, int $fileId, DateTime $dueDate): bool { + $now = new DateTime('now', new DateTimeZone('UTC')); + try { + $reminder = $this->reminderMapper->findDueForUser($user, $fileId); + $reminder->setDueDate($dueDate); + $reminder->setUpdatedAt($now); + $this->reminderMapper->update($reminder); + return false; + } catch (DoesNotExistException $e) { + $nodes = $this->root->getUserFolder($user->getUID())->getById($fileId); + if (empty($nodes)) { + throw new NodeNotFoundException(); + } + // Create new reminder if no reminder is found + $reminder = new Reminder(); + $reminder->setUserId($user->getUID()); + $reminder->setFileId($fileId); + $reminder->setDueDate($dueDate); + $reminder->setUpdatedAt($now); + $reminder->setCreatedAt($now); + $this->reminderMapper->insert($reminder); + return true; + } + } + + /** + * @throws DoesNotExistException + */ + public function remove(IUser $user, int $fileId): void { + $reminder = $this->reminderMapper->findDueForUser($user, $fileId); + $this->reminderMapper->delete($reminder); + } + + public function removeAllForNode(Node $node): void { + $reminders = $this->reminderMapper->findAllForNode($node); + foreach ($reminders as $reminder) { + $this->reminderMapper->delete($reminder); + } + } + + public function removeAllForUser(IUser $user): void { + $reminders = $this->reminderMapper->findAllForUser($user); + foreach ($reminders as $reminder) { + $this->reminderMapper->delete($reminder); + } + } + + /** + * @throws DoesNotExistException + * @throws UserNotFoundException + */ + public function send(Reminder $reminder): void { + if ($reminder->getNotified()) { + return; + } + + $user = $this->userManager->get($reminder->getUserId()); + if ($user === null) { + throw new UserNotFoundException(); + } + + $notification = $this->notificationManager->createNotification(); + $notification + ->setApp(Application::APP_ID) + ->setIcon($this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('files', 'folder.svg'))) + ->setUser($user->getUID()) + ->setObject('reminder', (string)$reminder->getId()) + ->setSubject('reminder-due') + ->setDateTime($reminder->getDueDate()); + + try { + $this->notificationManager->notify($notification); + $this->reminderMapper->markNotified($reminder); + } catch (Throwable $th) { + $this->logger->error($th->getMessage(), $th->getTrace()); + } + } + + public function cleanUp(?int $limit = null): void { + $reminders = $this->reminderMapper->findNotified($limit); + foreach ($reminders as $reminder) { + $this->reminderMapper->delete($reminder); + } + } +} diff --git a/build/integration/features/provisioning-v1.feature b/build/integration/features/provisioning-v1.feature index 5ba6b7f63dd4f..0d1d5b1a3455e 100644 --- a/build/integration/features/provisioning-v1.feature +++ b/build/integration/features/provisioning-v1.feature @@ -588,6 +588,7 @@ Feature: provisioning | federatedfilesharing | | federation | | files | + | files_reminders | | files_sharing | | files_trashbin | | files_versions | diff --git a/core/shipped.json b/core/shipped.json index c44d71c8103ed..2cd0fbd94667b 100644 --- a/core/shipped.json +++ b/core/shipped.json @@ -15,6 +15,7 @@ "files", "files_external", "files_pdfviewer", + "files_reminders", "files_rightclick", "files_sharing", "files_trashbin", @@ -59,6 +60,7 @@ "federation", "files", "files_pdfviewer", + "files_reminders", "files_rightclick", "files_sharing", "files_trashbin",