diff --git a/.gitignore b/.gitignore index 06cb1ac1eccfb..603d63ad54fcc 100644 --- a/.gitignore +++ b/.gitignore @@ -17,16 +17,17 @@ node_modules/ # ignore all apps except core ones /apps*/* +!/apps/admin_audit +!/apps/appstore !/apps/cloud_federation_api !/apps/comments !/apps/contactsinteraction !/apps/dashboard !/apps/dav -!/apps/files +!/apps/encryption !/apps/federation !/apps/federatedfilesharing -!/apps/sharebymail -!/apps/encryption +!/apps/files !/apps/files_external !/apps/files_reminders !/apps/files_sharing @@ -38,9 +39,9 @@ node_modules/ !/apps/profile !/apps/provisioning_api !/apps/settings +!/apps/sharebymail !/apps/systemtags !/apps/testing -!/apps/admin_audit !/apps/updatenotification !/apps/theming !/apps/twofactor_backupcodes diff --git a/apps/appstore/appinfo/info.xml b/apps/appstore/appinfo/info.xml new file mode 100644 index 0000000000000..9b6c801bab30b --- /dev/null +++ b/apps/appstore/appinfo/info.xml @@ -0,0 +1,22 @@ + + + + settings + Nextcloud Appstore + Nextcloud Appstore + Nextcloud Appstore + 1.0.0 + agpl + Nextcloud + Appstore + + customization + https://github.com/nextcloud/server/issues + + + + diff --git a/apps/appstore/composer/autoload.php b/apps/appstore/composer/autoload.php new file mode 100644 index 0000000000000..6c9b0406c7749 --- /dev/null +++ b/apps/appstore/composer/autoload.php @@ -0,0 +1,22 @@ + + * 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/appstore/composer/composer/InstalledVersions.php b/apps/appstore/composer/composer/InstalledVersions.php new file mode 100644 index 0000000000000..2052022fd8e1e --- /dev/null +++ b/apps/appstore/composer/composer/InstalledVersions.php @@ -0,0 +1,396 @@ + + * 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 string|null if set (by reflection by Composer), this should be set to the path where this class is being copied to + * @internal + */ + private static $selfDir = null; + + /** + * @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 + */ + private static $installedIsLocalDir; + + /** + * @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(); + + // when using reload, we disable the duplicate protection to ensure that self::$installed data is + // always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not, + // so we have to assume it does not, and that may result in duplicate data being returned when listing + // all installed packages for example + self::$installedIsLocalDir = false; + } + + /** + * @return string + */ + private static function getSelfDir() + { + if (self::$selfDir === null) { + self::$selfDir = strtr(__DIR__, '\\', '/'); + } + + return self::$selfDir; + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + $copiedLocalDir = false; + + if (self::$canGetVendors) { + $selfDir = self::getSelfDir(); + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + $vendorDir = strtr($vendorDir, '\\', '/'); + 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'; + self::$installedByVendor[$vendorDir] = $required; + $installed[] = $required; + if (self::$installed === null && $vendorDir.'/composer' === $selfDir) { + self::$installed = $required; + self::$installedIsLocalDir = true; + } + } + if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) { + $copiedLocalDir = true; + } + } + } + + 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() && !$copiedLocalDir) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/apps/appstore/composer/composer/LICENSE b/apps/appstore/composer/composer/LICENSE new file mode 100644 index 0000000000000..f27399a042d95 --- /dev/null +++ b/apps/appstore/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/appstore/composer/composer/autoload_classmap.php b/apps/appstore/composer/composer/autoload_classmap.php new file mode 100644 index 0000000000000..b84e2600e431a --- /dev/null +++ b/apps/appstore/composer/composer/autoload_classmap.php @@ -0,0 +1,15 @@ + $vendorDir . '/composer/InstalledVersions.php', + 'OCA\\Appstore\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php', + 'OCA\\Appstore\\Controller\\ApiController' => $baseDir . '/../lib/Controller/ApiController.php', + 'OCA\\Appstore\\Controller\\DiscoverController' => $baseDir . '/../lib/Controller/DiscoverController.php', + 'OCA\\Appstore\\Controller\\PageController' => $baseDir . '/../lib/Controller/PageController.php', + 'OCA\\Appstore\\Search\\AppSearch' => $baseDir . '/../lib/Search/AppSearch.php', +); diff --git a/apps/appstore/composer/composer/autoload_namespaces.php b/apps/appstore/composer/composer/autoload_namespaces.php new file mode 100644 index 0000000000000..3f5c929625125 --- /dev/null +++ b/apps/appstore/composer/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($baseDir . '/../lib'), +); diff --git a/apps/appstore/composer/composer/autoload_real.php b/apps/appstore/composer/composer/autoload_real.php new file mode 100644 index 0000000000000..7d3ecc79600ce --- /dev/null +++ b/apps/appstore/composer/composer/autoload_real.php @@ -0,0 +1,37 @@ +setClassMapAuthoritative(true); + $loader->register(true); + + return $loader; + } +} diff --git a/apps/appstore/composer/composer/autoload_static.php b/apps/appstore/composer/composer/autoload_static.php new file mode 100644 index 0000000000000..564b5859cb343 --- /dev/null +++ b/apps/appstore/composer/composer/autoload_static.php @@ -0,0 +1,41 @@ + + array ( + 'OCA\\Appstore\\' => 13, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'OCA\\Appstore\\' => + array ( + 0 => __DIR__ . '/..' . '/../lib', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'OCA\\Appstore\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php', + 'OCA\\Appstore\\Controller\\ApiController' => __DIR__ . '/..' . '/../lib/Controller/ApiController.php', + 'OCA\\Appstore\\Controller\\DiscoverController' => __DIR__ . '/..' . '/../lib/Controller/DiscoverController.php', + 'OCA\\Appstore\\Controller\\PageController' => __DIR__ . '/..' . '/../lib/Controller/PageController.php', + 'OCA\\Appstore\\Search\\AppSearch' => __DIR__ . '/..' . '/../lib/Search/AppSearch.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitAppstore::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitAppstore::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitAppstore::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/apps/appstore/composer/composer/installed.json b/apps/appstore/composer/composer/installed.json new file mode 100644 index 0000000000000..f20a6c47c6d4f --- /dev/null +++ b/apps/appstore/composer/composer/installed.json @@ -0,0 +1,5 @@ +{ + "packages": [], + "dev": false, + "dev-package-names": [] +} diff --git a/apps/appstore/composer/composer/installed.php b/apps/appstore/composer/composer/installed.php new file mode 100644 index 0000000000000..1f633b95afd69 --- /dev/null +++ b/apps/appstore/composer/composer/installed.php @@ -0,0 +1,23 @@ + array( + 'name' => '__root__', + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => '3efb1d80e9851e0c33311a7722f523e020654691', + 'type' => 'library', + 'install_path' => __DIR__ . '/../', + 'aliases' => array(), + 'dev' => false, + ), + 'versions' => array( + '__root__' => array( + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => '3efb1d80e9851e0c33311a7722f523e020654691', + 'type' => 'library', + 'install_path' => __DIR__ . '/../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/apps/settings/img/apps.svg b/apps/appstore/img/apps.svg similarity index 100% rename from apps/settings/img/apps.svg rename to apps/appstore/img/apps.svg diff --git a/apps/appstore/l10n/.gitkeep b/apps/appstore/l10n/.gitkeep new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/apps/appstore/lib/AppInfo/Application.php b/apps/appstore/lib/AppInfo/Application.php new file mode 100644 index 0000000000000..e25bbd9bc5735 --- /dev/null +++ b/apps/appstore/lib/AppInfo/Application.php @@ -0,0 +1,30 @@ +l10nFactory->findLanguage(), 0, 2); + + $categories = $this->categoryFetcher->get(); + $categories = array_map(fn ($category) => [ + 'id' => $category['id'], + 'displayName' => $category['translations'][$currentLanguage]['name'] ?? $category['translations']['en']['name'], + ], $categories); + + return new DataResponse(array_values($categories)); + } + + /** + * Get all available apps + */ + #[ApiRoute('GET', '/api/v1/apps')] + public function listApps(): DataResponse { + $apps = $this->getAllApps(); + + $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []); + if (!is_array($ignoreMaxApps)) { + $this->logger->warning('The value given for app_install_overwrite is not an array. Ignoring...'); + $ignoreMaxApps = []; + } + + // Extend existing app details + $apps = array_map(function (array $appData) use ($ignoreMaxApps) { + if (isset($appData['appstoreData'])) { + $appstoreData = $appData['appstoreData']; + $appData['screenshot'] = $this->createProxyPreviewUrl($appstoreData['screenshots'][0]['url'] ?? ''); + $appData['category'] = $appstoreData['categories']; + $appData['releases'] = $appstoreData['releases']; + } + + $newVersion = $this->installer->isUpdateAvailable($appData['id']); + if ($newVersion) { + $appData['update'] = $newVersion; + } + + // fix groups to be an array + $groups = []; + if (is_string($appData['groups'])) { + $groups = json_decode($appData['groups']); + // ensure 'groups' is an array + if (!is_array($groups)) { + $groups = [$groups]; + } + } + $appData['groups'] = $groups; + $appData['canUnInstall'] = !$appData['active'] && $appData['removable']; + + // analyze dependencies + $ignoreMax = in_array($appData['id'], $ignoreMaxApps); + $missing = $this->dependencyAnalyzer->analyze($appData, $ignoreMax); + $appData['canInstall'] = empty($missing); + $appData['missingDependencies'] = $missing; + + $appData['missingMinOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['min-version']); + $appData['missingMaxOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['max-version']); + $appData['isCompatible'] = $this->dependencyAnalyzer->isMarkedCompatible($appData); + + return $appData; + }, $apps); + + usort($apps, $this->sortApps(...)); + + return new DataResponse(array_values($apps)); + } + + /** + * Enable one apps + * + * App will be enabled for specific groups only if $groups is defined + * + * @param string $appId - The app to enable + * @param array $groups - The groups to enable the app for + * @return DataResponse + */ + #[PasswordConfirmationRequired] + #[ApiRoute('POST', '/api/v1/apps/enable')] + public function enableApp(string $appId, array $groups = []): DataResponse { + try { + $updateRequired = false; + + $appId = $this->appManager->cleanAppId($appId); + + // Check if app is already downloaded + if (!$this->installer->isDownloaded($appId)) { + $this->installer->downloadApp($appId); + } + + $this->installer->installApp($appId); + + if (count($groups) > 0) { + $this->appManager->enableAppForGroups($appId, $this->getGroupList($groups)); + } else { + $this->appManager->enableApp($appId); + } + $updateRequired = $updateRequired || $this->appManager->isUpgradeRequired($appId); + return new DataResponse(['update_required' => $updateRequired]); + } catch (\Throwable $e) { + $this->logger->error('could not enable app', ['exception' => $e]); + throw new OCSException('could not enable app', Http::STATUS_INTERNAL_SERVER_ERROR, $e); + } + } + + /** + * Disable an app + */ + #[PasswordConfirmationRequired] + #[ApiRoute('POST', '/api/v1/apps/disable')] + public function disableApp(string $appId): DataResponse { + try { + $appId = $this->appManager->cleanAppId($appId); + $this->appManager->disableApp($appId); + return new DataResponse([]); + } catch (\Exception $e) { + $this->logger->error('could not disable app', ['exception' => $e]); + throw new OCSException('could not disable app', Http::STATUS_INTERNAL_SERVER_ERROR, $e); + } + } + + /** + * Uninstall an app + */ + #[PasswordConfirmationRequired] + #[ApiRoute('POST', '/api/v1/apps/uninstall')] + public function uninstallApp(string $appId): DataResponse { + $appId = $this->appManager->cleanAppId($appId); + $result = $this->installer->removeApp($appId); + if ($result !== false) { + // If this app was force enabled, remove the force-enabled-state + $this->appManager->removeOverwriteNextcloudRequirement($appId); + $this->appManager->clearAppsCache(); + return new DataResponse([]); + } + throw new OCSException('could not remove app', Http::STATUS_INTERNAL_SERVER_ERROR); + } + + /** + * Update an app + */ + #[PasswordConfirmationRequired] + #[ApiRoute('POST', '/api/v1/apps/update')] + public function updateApp(string $appId): DataResponse { + $appId = $this->appManager->cleanAppId($appId); + + $this->config->setSystemValue('maintenance', true); + try { + $result = $this->installer->updateAppstoreApp($appId); + $this->config->setSystemValue('maintenance', false); + if ($result === false) { + throw new \Exception('Update failed'); + } + } catch (\Exception $ex) { + $this->config->setSystemValue('maintenance', false); + throw new OCSException('could not update app', Http::STATUS_INTERNAL_SERVER_ERROR, $ex); + } + + return new DataResponse([]); + } + /** + * Force enable an app. + * + * @return JSONResponse + */ + #[PasswordConfirmationRequired] + #[ApiRoute('POST', '/api/v1/apps/force')] + public function force(string $appId): DataResponse { + $appId = $this->appManager->cleanAppId($appId); + $this->appManager->overwriteNextcloudRequirement($appId); + return new DataResponse([]); + } + + /** + * Convert URL to proxied URL so CSP is no problem + */ + private function createProxyPreviewUrl(string $url): string { + if ($url === '') { + return ''; + } + return 'https://usercontent.apps.nextcloud.com/' . base64_encode($url); + } + + private function fetchApps() { + $appClass = new \OC_App(); + $apps = $appClass->listAllApps(); + foreach ($apps as $app) { + $app['installed'] = true; + + if (isset($app['screenshot'][0])) { + $appScreenshot = $app['screenshot'][0] ?? null; + if (is_array($appScreenshot)) { + // Screenshot with thumbnail + $appScreenshot = $appScreenshot['@value']; + } + + $app['screenshot'] = $this->createProxyPreviewUrl($appScreenshot); + } + $this->allApps[$app['id']] = $app; + } + + $apps = $this->getAppsForCategory(''); + $supportedApps = $this->subscriptionRegistry->delegateGetSupportedApps(); + foreach ($apps as $app) { + $app['appstore'] = true; + if (!array_key_exists($app['id'], $this->allApps)) { + $this->allApps[$app['id']] = $app; + } else { + $this->allApps[$app['id']] = array_merge($app, $this->allApps[$app['id']]); + } + + if (in_array($app['id'], $supportedApps)) { + $this->allApps[$app['id']]['level'] = \OC_App::supportedApp; + } + } + + // add bundle information + $bundles = $this->bundleFetcher->getBundles(); + foreach ($bundles as $bundle) { + foreach ($bundle->getAppIdentifiers() as $identifier) { + foreach ($this->allApps as &$app) { + if ($app['id'] === $identifier) { + $app['bundleIds'][] = $bundle->getIdentifier(); + continue; + } + } + } + } + } + + private function getAllApps() { + if (empty($this->allApps)) { + $this->fetchApps(); + } + return $this->allApps; + } + + /** + * Get all apps for a category from the app store + * + * @param string $requestedCategory + * @return array + * @throws \Exception + */ + private function getAppsForCategory($requestedCategory = ''): array { + $versionParser = new VersionParser(); + $formattedApps = []; + $apps = $this->appFetcher->get(); + foreach ($apps as $app) { + // Skip all apps not in the requested category + if ($requestedCategory !== '') { + $isInCategory = false; + foreach ($app['categories'] as $category) { + if ($category === $requestedCategory) { + $isInCategory = true; + } + } + if (!$isInCategory) { + continue; + } + } + + if (!isset($app['releases'][0]['rawPlatformVersionSpec'])) { + continue; + } + $nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']); + $nextCloudVersionDependencies = []; + if ($nextCloudVersion->getMinimumVersion() !== '') { + $nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion(); + } + if ($nextCloudVersion->getMaximumVersion() !== '') { + $nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion(); + } + $phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']); + + try { + $this->appManager->getAppPath($app['id']); + $existsLocally = true; + } catch (AppPathNotFoundException) { + $existsLocally = false; + } + + $phpDependencies = []; + if ($phpVersion->getMinimumVersion() !== '') { + $phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion(); + } + if ($phpVersion->getMaximumVersion() !== '') { + $phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion(); + } + if (isset($app['releases'][0]['minIntSize'])) { + $phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize']; + } + $authors = ''; + foreach ($app['authors'] as $key => $author) { + $authors .= $author['name']; + if ($key !== count($app['authors']) - 1) { + $authors .= ', '; + } + } + + $currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2); + $enabledValue = $this->appConfig->getValueString($app['id'], 'enabled', 'no'); + $groups = null; + if ($enabledValue !== 'no' && $enabledValue !== 'yes') { + $groups = $enabledValue; + } + + $currentVersion = ''; + if ($this->appManager->isEnabledForAnyone($app['id'])) { + $currentVersion = $this->appManager->getAppVersion($app['id']); + } else { + $currentVersion = $app['releases'][0]['version']; + } + + $formattedApps[] = [ + 'id' => $app['id'], + 'app_api' => false, + 'name' => $app['translations'][$currentLanguage]['name'] ?? $app['translations']['en']['name'], + 'description' => $app['translations'][$currentLanguage]['description'] ?? $app['translations']['en']['description'], + 'summary' => $app['translations'][$currentLanguage]['summary'] ?? $app['translations']['en']['summary'], + 'license' => $app['releases'][0]['licenses'], + 'author' => $authors, + 'shipped' => $this->appManager->isShipped($app['id']), + 'version' => $currentVersion, + 'types' => [], + 'documentation' => [ + 'admin' => $app['adminDocs'], + 'user' => $app['userDocs'], + 'developer' => $app['developerDocs'] + ], + 'website' => $app['website'], + 'bugs' => $app['issueTracker'], + 'dependencies' => array_merge( + $nextCloudVersionDependencies, + $phpDependencies + ), + 'level' => ($app['isFeatured'] === true) ? 200 : 100, + 'missingMaxOwnCloudVersion' => false, + 'missingMinOwnCloudVersion' => false, + 'canInstall' => true, + 'screenshot' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/' . base64_encode($app['screenshots'][0]['url']) : '', + 'score' => $app['ratingOverall'], + 'ratingNumOverall' => $app['ratingNumOverall'], + 'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5, + 'removable' => $existsLocally, + 'active' => $this->appManager->isEnabledForUser($app['id']), + 'needsDownload' => !$existsLocally, + 'groups' => $groups, + 'fromAppStore' => true, + 'appstoreData' => $app, + ]; + } + + return $formattedApps; + } + + private function getGroupList(array $groups) { + $groupManager = Server::get(IGroupManager::class); + $groupsList = []; + foreach ($groups as $group) { + $groupItem = $groupManager->get($group); + if ($groupItem instanceof IGroup) { + $groupsList[] = $groupManager->get($group); + } + } + return $groupsList; + } + + private function sortApps($a, $b) { + $a = (string)$a['name']; + $b = (string)$b['name']; + if ($a === $b) { + return 0; + } + return ($a < $b) ? -1 : 1; + } +} diff --git a/apps/appstore/lib/Controller/DiscoverController.php b/apps/appstore/lib/Controller/DiscoverController.php new file mode 100644 index 0000000000000..181c621ff8c28 --- /dev/null +++ b/apps/appstore/lib/Controller/DiscoverController.php @@ -0,0 +1,181 @@ +appData = $appDataFactory->get(Application::APP_ID); + } + + /** + * Get all active entries for the app discover section + */ + #[NoCSRFRequired] + #[FrontpageRoute('GET', '/api/v1/discover')] + public function getAppDiscoverJSON(): JSONResponse { + $data = $this->discoverFetcher->get(true); + return new JSONResponse(array_values($data)); + } + + /** + * Get a image for the app discover section - this is proxied for privacy and CSP reasons + * + * @param string $fileName - The image file name + */ + #[NoCSRFRequired] + #[FrontpageRoute('GET', '/api/v1/discover/media')] + public function getAppDiscoverMedia(string $fileName, ILimiter $limiter, IUserSession $session): FileDisplayResponse|NotFoundResponse { + $getEtag = $this->discoverFetcher->getETag() ?? date('Y-m'); + $etag = trim($getEtag, '"'); + + $folder = null; + try { + $folder = $this->appData->getFolder('app-discover-cache'); + $this->cleanUpImageCache($folder, $etag); + } catch (\Throwable $e) { + $folder = $this->appData->newFolder('app-discover-cache'); + } + + // Get the current cache folder + try { + $folder = $folder->getFolder($etag); + } catch (NotFoundException $e) { + $folder = $folder->newFolder($etag); + } + + $info = pathinfo($fileName); + $hashName = md5($fileName); + $allFiles = $folder->getDirectoryListing(); + // Try to find the file + $file = array_filter($allFiles, function (ISimpleFile $file) use ($hashName) { + return str_starts_with($file->getName(), $hashName); + }); + // Get the first entry + $file = reset($file); + // If not found request from Web + if ($file === false) { + $user = $session->getUser(); + // this route is not public thus we can assume a user is logged-in + assert($user !== null); + // Register a user request to throttle fetching external data + // this will prevent using the server for DoS of other systems. + $limiter->registerUserRequest( + 'settings-discover-media', + // allow up to 24 media requests per hour + // this should be a sane default when a completely new section is loaded + // keep in mind browsers request all files from a source-set + 24, + 60 * 60, + $user, + ); + + if (!$this->checkCanDownloadMedia($fileName)) { + $this->logger->warning('Tried to load media files for app discover section from untrusted source'); + return new NotFoundResponse(Http::STATUS_BAD_REQUEST); + } + + try { + $client = $this->clientService->newClient(); + $fileResponse = $client->get($fileName); + $contentType = $fileResponse->getHeader('Content-Type'); + $extension = $info['extension'] ?? ''; + $file = $folder->newFile($hashName . '.' . base64_encode($contentType) . '.' . $extension, $fileResponse->getBody()); + } catch (\Throwable $e) { + $this->logger->warning('Could not load media file for app discover section', ['media_src' => $fileName, 'exception' => $e]); + return new NotFoundResponse(); + } + } else { + // File was found so we can get the content type from the file name + $contentType = base64_decode(explode('.', $file->getName())[1] ?? ''); + } + + $response = new FileDisplayResponse($file, Http::STATUS_OK, ['Content-Type' => $contentType]); + // cache for 7 days + $response->cacheFor(604800, false, true); + return $response; + } + + private function checkCanDownloadMedia(string $filename): bool { + $urlInfo = parse_url($filename); + if (!isset($urlInfo['host']) || !isset($urlInfo['path'])) { + return false; + } + + // Always allowed hosts + if ($urlInfo['host'] === 'nextcloud.com') { + return true; + } + + // Hosts that need further verification + // Github is only allowed if from our organization + $ALLOWED_HOSTS = ['github.com', 'raw.githubusercontent.com']; + if (!in_array($urlInfo['host'], $ALLOWED_HOSTS)) { + return false; + } + + if (str_starts_with($urlInfo['path'], '/nextcloud/') || str_starts_with($urlInfo['path'], '/nextcloud-gmbh/')) { + return true; + } + + return false; + } + + /** + * Remove orphaned folders from the image cache that do not match the current etag + * @param ISimpleFolder $folder The folder to clear + * @param string $etag The etag (directory name) to keep + */ + private function cleanUpImageCache(ISimpleFolder $folder, string $etag): void { + // Cleanup old cache folders + $allFiles = $folder->getDirectoryListing(); + foreach ($allFiles as $dir) { + try { + if ($dir->getName() !== $etag) { + $dir->delete(); + } + } catch (NotPermittedException $e) { + // ignore folder for now + } + } + } +} diff --git a/apps/appstore/lib/Controller/PageController.php b/apps/appstore/lib/Controller/PageController.php new file mode 100644 index 0000000000000..5462494d46a9d --- /dev/null +++ b/apps/appstore/lib/Controller/PageController.php @@ -0,0 +1,110 @@ + ''], root: '')] + #[FrontpageRoute('GET', '/settings/apps/{category}/{id}', defaults: ['category' => '', 'id' => ''], root: '')] + public function viewApps(): TemplateResponse { + $this->navigationManager->setActiveEntry('core_apps'); + + $this->initialState->provideInitialState('appstoreEnabled', $this->config->getSystemValueBool('appstoreenabled', true)); + $this->initialState->provideInitialState('appstoreBundles', $this->getBundles()); + $this->initialState->provideInitialState('appstoreDeveloperDocs', $this->urlGenerator->linkToDocs('developer-manual')); + $this->initialState->provideInitialState('appstoreUpdateCount', count($this->getAppsWithUpdates())); + + if ($this->appManager->isEnabledForAnyone('app_api')) { + try { + Server::get(ExAppsPageService::class)->provideAppApiState($this->initialState); + } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) { + } + } + + $policy = new ContentSecurityPolicy(); + $policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com'); + + $templateResponse = new TemplateResponse(Application::APP_ID, 'empty', ['pageTitle' => $this->l10n->t('App store')]); + $templateResponse->setContentSecurityPolicy($policy); + + Util::addStyle(Application::APP_ID, 'main'); + Util::addScript(Application::APP_ID, 'main'); + + return $templateResponse; + } + + + private function getAppsWithUpdates() { + $appClass = new \OC_App(); + $apps = $appClass->listAllApps(); + foreach ($apps as $key => $app) { + $newVersion = $this->installer->isUpdateAvailable($app['id']); + if ($newVersion === false) { + unset($apps[$key]); + } + } + return $apps; + } + + private function getBundles() { + $result = []; + $bundles = $this->bundleFetcher->getBundles(); + foreach ($bundles as $bundle) { + $result[] = [ + 'name' => $bundle->getName(), + 'id' => $bundle->getIdentifier(), + 'appIdentifiers' => $bundle->getAppIdentifiers() + ]; + } + return $result; + } +} diff --git a/apps/settings/lib/Search/AppSearch.php b/apps/appstore/lib/Search/AppSearch.php similarity index 90% rename from apps/settings/lib/Search/AppSearch.php rename to apps/appstore/lib/Search/AppSearch.php index 19c2bce5451a7..3efa8dca35316 100644 --- a/apps/settings/lib/Search/AppSearch.php +++ b/apps/appstore/lib/Search/AppSearch.php @@ -6,8 +6,9 @@ * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ -namespace OCA\Settings\Search; +namespace OCA\Appstore\Search; +use OCA\Appstore\AppInfo\Application; use OCP\IL10N; use OCP\INavigationManager; use OCP\IUser; @@ -24,7 +25,7 @@ public function __construct( } public function getId(): string { - return 'settings_apps'; + return Application::APP_ID; } public function getName(): string { @@ -32,7 +33,7 @@ public function getName(): string { } public function getOrder(string $route, array $routeParameters): int { - return $route === 'settings.AppSettings.viewApps' ? -50 : 100; + return $route === 'appstore.AppSettings.viewApps' ? -50 : 100; } public function search(IUser $user, ISearchQuery $query): SearchResult { diff --git a/apps/appstore/openapi-administration.json b/apps/appstore/openapi-administration.json new file mode 100644 index 0000000000000..6e099465cb9e8 --- /dev/null +++ b/apps/appstore/openapi-administration.json @@ -0,0 +1,104 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "settings-administration", + "version": "0.0.1", + "description": "Nextcloud settings", + "license": { + "name": "agpl" + } + }, + "components": { + "securitySchemes": { + "basic_auth": { + "type": "http", + "scheme": "basic" + }, + "bearer_auth": { + "type": "http", + "scheme": "bearer" + } + }, + "schemas": {} + }, + "paths": { + "/index.php/settings/admin/log/download": { + "get": { + "operationId": "log_settings-download", + "summary": "download logfile", + "description": "This endpoint requires admin access", + "tags": [ + "log_settings" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "responses": { + "200": { + "description": "Logfile returned", + "headers": { + "Content-Disposition": { + "schema": { + "type": "string", + "enum": [ + "attachment; filename=\"nextcloud.log\"" + ] + } + } + }, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + }, + "403": { + "description": "Logged in account must be an admin", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "tags": [] +} diff --git a/apps/appstore/openapi-administration.json.license b/apps/appstore/openapi-administration.json.license new file mode 100644 index 0000000000000..83559daa9dcb7 --- /dev/null +++ b/apps/appstore/openapi-administration.json.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/apps/appstore/openapi-full.json b/apps/appstore/openapi-full.json new file mode 100644 index 0000000000000..33ffe61ea04aa --- /dev/null +++ b/apps/appstore/openapi-full.json @@ -0,0 +1,709 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "settings-full", + "version": "0.0.1", + "description": "Nextcloud settings", + "license": { + "name": "agpl" + } + }, + "components": { + "securitySchemes": { + "basic_auth": { + "type": "http", + "scheme": "basic" + }, + "bearer_auth": { + "type": "http", + "scheme": "bearer" + } + }, + "schemas": { + "DeclarativeForm": { + "type": "object", + "required": [ + "id", + "priority", + "section_type", + "section_id", + "storage_type", + "title", + "app", + "fields" + ], + "properties": { + "id": { + "type": "string" + }, + "priority": { + "type": "integer", + "format": "int64" + }, + "section_type": { + "type": "string", + "enum": [ + "admin", + "personal" + ] + }, + "section_id": { + "type": "string" + }, + "storage_type": { + "type": "string", + "enum": [ + "internal", + "external" + ] + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "doc_url": { + "type": "string" + }, + "app": { + "type": "string" + }, + "fields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DeclarativeFormField" + } + } + } + }, + "DeclarativeFormField": { + "type": "object", + "required": [ + "id", + "title", + "type", + "default", + "value" + ], + "properties": { + "id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "text", + "password", + "email", + "tel", + "url", + "number", + "checkbox", + "multi-checkbox", + "radio", + "select", + "multi-select" + ] + }, + "placeholder": { + "type": "string" + }, + "label": { + "type": "string" + }, + "default": { + "type": "object" + }, + "options": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "object", + "required": [ + "name", + "value" + ], + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "object" + } + } + } + ] + } + }, + "value": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "format": "int64" + }, + { + "type": "number", + "format": "double" + }, + { + "type": "boolean" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "sensitive": { + "type": "boolean" + } + } + }, + "OCSMeta": { + "type": "object", + "required": [ + "status", + "statuscode" + ], + "properties": { + "status": { + "type": "string" + }, + "statuscode": { + "type": "integer" + }, + "message": { + "type": "string" + }, + "totalitems": { + "type": "string" + }, + "itemsperpage": { + "type": "string" + } + } + } + } + }, + "paths": { + "/index.php/settings/admin/log/download": { + "get": { + "operationId": "log_settings-download", + "summary": "download logfile", + "description": "This endpoint requires admin access", + "tags": [ + "log_settings" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "responses": { + "200": { + "description": "Logfile returned", + "headers": { + "Content-Disposition": { + "schema": { + "type": "string", + "enum": [ + "attachment; filename=\"nextcloud.log\"" + ] + } + } + }, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + }, + "403": { + "description": "Logged in account must be an admin", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + }, + "/ocs/v2.php/settings/api/declarative/value": { + "post": { + "operationId": "declarative_settings-set-value", + "summary": "Sets a declarative settings value", + "tags": [ + "declarative_settings" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "app", + "formId", + "fieldId", + "value" + ], + "properties": { + "app": { + "type": "string", + "description": "ID of the app" + }, + "formId": { + "type": "string", + "description": "ID of the form" + }, + "fieldId": { + "type": "string", + "description": "ID of the field" + }, + "value": { + "type": "object", + "description": "Value to be saved" + } + } + } + } + } + }, + "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": "Value set successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "nullable": true + } + } + } + } + } + } + } + }, + "500": { + "description": "Not logged in or not an admin user", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid arguments to save value", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "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/settings/api/declarative/value-sensitive": { + "post": { + "operationId": "declarative_settings-set-sensitive-value", + "summary": "Sets a declarative settings value. Password confirmation is required for sensitive values.", + "description": "This endpoint requires password confirmation", + "tags": [ + "declarative_settings" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "app", + "formId", + "fieldId", + "value" + ], + "properties": { + "app": { + "type": "string", + "description": "ID of the app" + }, + "formId": { + "type": "string", + "description": "ID of the form" + }, + "fieldId": { + "type": "string", + "description": "ID of the field" + }, + "value": { + "type": "object", + "description": "Value to be saved" + } + } + } + } + } + }, + "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": "Value set successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "nullable": true + } + } + } + } + } + } + } + }, + "500": { + "description": "Not logged in or not an admin user", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid arguments to save value", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "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/settings/api/declarative/forms": { + "get": { + "operationId": "declarative_settings-get-forms", + "summary": "Gets all declarative forms with the values prefilled.", + "tags": [ + "declarative_settings" + ], + "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": "Forms 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/DeclarativeForm" + } + } + } + } + } + } + } + } + }, + "500": { + "description": "", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + } + }, + "tags": [] +} diff --git a/apps/appstore/openapi-full.json.license b/apps/appstore/openapi-full.json.license new file mode 100644 index 0000000000000..83559daa9dcb7 --- /dev/null +++ b/apps/appstore/openapi-full.json.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/apps/appstore/openapi.json b/apps/appstore/openapi.json new file mode 100644 index 0000000000000..c23971fbe269b --- /dev/null +++ b/apps/appstore/openapi.json @@ -0,0 +1,632 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "settings", + "version": "0.0.1", + "description": "Nextcloud settings", + "license": { + "name": "agpl" + } + }, + "components": { + "securitySchemes": { + "basic_auth": { + "type": "http", + "scheme": "basic" + }, + "bearer_auth": { + "type": "http", + "scheme": "bearer" + } + }, + "schemas": { + "DeclarativeForm": { + "type": "object", + "required": [ + "id", + "priority", + "section_type", + "section_id", + "storage_type", + "title", + "app", + "fields" + ], + "properties": { + "id": { + "type": "string" + }, + "priority": { + "type": "integer", + "format": "int64" + }, + "section_type": { + "type": "string", + "enum": [ + "admin", + "personal" + ] + }, + "section_id": { + "type": "string" + }, + "storage_type": { + "type": "string", + "enum": [ + "internal", + "external" + ] + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "doc_url": { + "type": "string" + }, + "app": { + "type": "string" + }, + "fields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DeclarativeFormField" + } + } + } + }, + "DeclarativeFormField": { + "type": "object", + "required": [ + "id", + "title", + "type", + "default", + "value" + ], + "properties": { + "id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "text", + "password", + "email", + "tel", + "url", + "number", + "checkbox", + "multi-checkbox", + "radio", + "select", + "multi-select" + ] + }, + "placeholder": { + "type": "string" + }, + "label": { + "type": "string" + }, + "default": { + "type": "object" + }, + "options": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "object", + "required": [ + "name", + "value" + ], + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "object" + } + } + } + ] + } + }, + "value": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "format": "int64" + }, + { + "type": "number", + "format": "double" + }, + { + "type": "boolean" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "sensitive": { + "type": "boolean" + } + } + }, + "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/settings/api/declarative/value": { + "post": { + "operationId": "declarative_settings-set-value", + "summary": "Sets a declarative settings value", + "tags": [ + "declarative_settings" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "app", + "formId", + "fieldId", + "value" + ], + "properties": { + "app": { + "type": "string", + "description": "ID of the app" + }, + "formId": { + "type": "string", + "description": "ID of the form" + }, + "fieldId": { + "type": "string", + "description": "ID of the field" + }, + "value": { + "type": "object", + "description": "Value to be saved" + } + } + } + } + } + }, + "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": "Value set successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "nullable": true + } + } + } + } + } + } + } + }, + "500": { + "description": "Not logged in or not an admin user", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid arguments to save value", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "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/settings/api/declarative/value-sensitive": { + "post": { + "operationId": "declarative_settings-set-sensitive-value", + "summary": "Sets a declarative settings value. Password confirmation is required for sensitive values.", + "description": "This endpoint requires password confirmation", + "tags": [ + "declarative_settings" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "app", + "formId", + "fieldId", + "value" + ], + "properties": { + "app": { + "type": "string", + "description": "ID of the app" + }, + "formId": { + "type": "string", + "description": "ID of the form" + }, + "fieldId": { + "type": "string", + "description": "ID of the field" + }, + "value": { + "type": "object", + "description": "Value to be saved" + } + } + } + } + } + }, + "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": "Value set successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "nullable": true + } + } + } + } + } + } + } + }, + "500": { + "description": "Not logged in or not an admin user", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid arguments to save value", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "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/settings/api/declarative/forms": { + "get": { + "operationId": "declarative_settings-get-forms", + "summary": "Gets all declarative forms with the values prefilled.", + "tags": [ + "declarative_settings" + ], + "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": "Forms 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/DeclarativeForm" + } + } + } + } + } + } + } + } + }, + "500": { + "description": "", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + } + }, + "tags": [] +} diff --git a/apps/appstore/openapi.json.license b/apps/appstore/openapi.json.license new file mode 100644 index 0000000000000..83559daa9dcb7 --- /dev/null +++ b/apps/appstore/openapi.json.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/apps/appstore/src/AppstoreApp.vue b/apps/appstore/src/AppstoreApp.vue new file mode 100644 index 0000000000000..e54ccdec7b691 --- /dev/null +++ b/apps/appstore/src/AppstoreApp.vue @@ -0,0 +1,48 @@ + + + + + + + diff --git a/apps/appstore/src/apps-discover.d.ts b/apps/appstore/src/apps-discover.d.ts new file mode 100644 index 0000000000000..d9bb560a80477 --- /dev/null +++ b/apps/appstore/src/apps-discover.d.ts @@ -0,0 +1,112 @@ +/*! + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +/** + * Helper for localized values + */ +export type ILocalizedValue = Record & { en: T } + +export interface IAppDiscoverElement { + /** + * Type of the element + */ + type: typeof APP_DISCOVER_KNOWN_TYPES[number] + + /** + * Identifier for this element + */ + id: string + + /** + * Order of this element to pin elements (smaller = shown on top) + */ + order?: number + + /** + * Optional, localized, headline for the element + */ + headline?: ILocalizedValue + + /** + * Optional link target for the element + */ + link?: string + + /** + * Optional date when this element will get valid (only show since then) + */ + date?: number + + /** + * Optional date when this element will be invalid (only show until then) + */ + expiryDate?: number +} + +/** Wrapper for media source and MIME type */ +type MediaSource = { src: string, mime: string } + +/** + * Media content type for posts + */ +interface IAppDiscoverMediaContent { + /** + * The media source to show - either one or a list of sources with their MIME type for fallback options + */ + src: MediaSource | MediaSource[] + + /** + * Alternative text for the media + */ + alt: string + + /** + * Optional link target for the media (e.g. to the full video) + */ + link?: string +} + +/** + * Wrapper for post media + */ +interface IAppDiscoverMedia { + /** + * The alignment of the media element + */ + alignment?: 'start' | 'end' | 'center' + + /** + * The (localized) content + */ + content: ILocalizedValue +} + +/** + * An app element only used for the showcase type + */ +export interface IAppDiscoverApp { + /** The App ID */ + type: 'app' + appId: string +} + +export interface IAppDiscoverPost extends IAppDiscoverElement { + type: 'post' + text?: ILocalizedValue + media?: IAppDiscoverMedia +} + +export interface IAppDiscoverShowcase extends IAppDiscoverElement { + type: 'showcase' + content: (IAppDiscoverPost | IAppDiscoverApp)[] +} + +export interface IAppDiscoverCarousel extends IAppDiscoverElement { + type: 'carousel' + text?: ILocalizedValue + content: IAppDiscoverPost[] +} + +export type IAppDiscoverElements = IAppDiscoverPost | IAppDiscoverCarousel | IAppDiscoverShowcase diff --git a/apps/settings/src/app-types.ts b/apps/appstore/src/apps.d.ts similarity index 78% rename from apps/settings/src/app-types.ts rename to apps/appstore/src/apps.d.ts index 97dbecf31c4c6..a457ed91b8668 100644 --- a/apps/settings/src/app-types.ts +++ b/apps/appstore/src/apps.d.ts @@ -27,7 +27,16 @@ export interface IAppstoreAppRelease { } } -export interface IAppstoreApp { +export interface IAppstoreAppData extends Record { + ratingOverall: number + ratingNumOverall: number + ratingRecent: number + ratingNumRecent: number + + releases: IAppstoreAppRelease[] +} + +export interface IAppstoreAppResponse { id: string name: string summary: string @@ -38,10 +47,12 @@ export interface IAppstoreApp { version: string category: string | string[] - preview?: string screenshot?: string - app_api: boolean + score: number + ratingNumThresholdReached: boolean + + app_api: false active: boolean internal: boolean removable: boolean @@ -52,10 +63,14 @@ export interface IAppstoreApp { needsDownload: boolean update?: string - appstoreData: Record + appstoreData?: IAppstoreAppData releases?: IAppstoreAppRelease[] } +export interface IAppstoreApp extends IAppstoreAppResponse { + loading?: boolean +} + export interface IComputeDevice { id: string label: string @@ -81,10 +96,10 @@ export interface IDeployDaemon { export interface IExAppStatus { action: string deploy: number - deploy_start_time: number - error: string + deploy_start_time?: number + error?: string init: number - init_start_time: number + init_start_time?: number type: string } @@ -111,8 +126,9 @@ export interface IAppstoreExAppRelease extends IAppstoreAppRelease { } export interface IAppstoreExApp extends IAppstoreApp { + app_api: true daemon: IDeployDaemon | null | undefined status: IExAppStatus | Record - error: string + error?: string releases: IAppstoreExAppRelease[] } diff --git a/apps/settings/src/components/AppList/AppDaemonBadge.vue b/apps/appstore/src/components/AppDaemonBadge.vue similarity index 100% rename from apps/settings/src/components/AppList/AppDaemonBadge.vue rename to apps/appstore/src/components/AppDaemonBadge.vue diff --git a/apps/appstore/src/components/AppImage.vue b/apps/appstore/src/components/AppImage.vue new file mode 100644 index 0000000000000..6912c9f9843d2 --- /dev/null +++ b/apps/appstore/src/components/AppImage.vue @@ -0,0 +1,61 @@ + + + + + diff --git a/apps/settings/src/components/AppList/AppLevelBadge.vue b/apps/appstore/src/components/AppLevelBadge.vue similarity index 100% rename from apps/settings/src/components/AppList/AppLevelBadge.vue rename to apps/appstore/src/components/AppLevelBadge.vue diff --git a/apps/appstore/src/components/AppLink.vue b/apps/appstore/src/components/AppLink.vue new file mode 100644 index 0000000000000..107a8dc24814a --- /dev/null +++ b/apps/appstore/src/components/AppLink.vue @@ -0,0 +1,83 @@ + + + + + diff --git a/apps/settings/src/components/AppList.vue b/apps/appstore/src/components/AppList.vue similarity index 99% rename from apps/settings/src/components/AppList.vue rename to apps/appstore/src/components/AppList.vue index f2892854b4355..09096dc9965ca 100644 --- a/apps/settings/src/components/AppList.vue +++ b/apps/appstore/src/components/AppList.vue @@ -150,7 +150,7 @@ import { subscribe, unsubscribe } from '@nextcloud/event-bus' import pLimit from 'p-limit' import NcButton from '@nextcloud/vue/components/NcButton' import AppItem from './AppList/AppItem.vue' -import logger from '../logger.ts' +import logger from '../utils/logger.ts' import AppManagement from '../mixins/AppManagement.js' import { useAppApiStore } from '../store/app-api-store.ts' import { useAppsStore } from '../store/apps-store.ts' diff --git a/apps/appstore/src/components/AppList/AppListItem.vue b/apps/appstore/src/components/AppList/AppListItem.vue new file mode 100644 index 0000000000000..860ea051fa815 --- /dev/null +++ b/apps/appstore/src/components/AppList/AppListItem.vue @@ -0,0 +1,108 @@ + + + + + + diff --git a/apps/appstore/src/components/AppList/AppListVersion.vue b/apps/appstore/src/components/AppList/AppListVersion.vue new file mode 100644 index 0000000000000..35a2f0dd27bce --- /dev/null +++ b/apps/appstore/src/components/AppList/AppListVersion.vue @@ -0,0 +1,22 @@ + + + + + diff --git a/apps/settings/src/components/AppList/AppItem.vue b/apps/appstore/src/components/AppList/AppTable.vue similarity index 94% rename from apps/settings/src/components/AppList/AppItem.vue rename to apps/appstore/src/components/AppList/AppTable.vue index ba95d924a9c59..fbe2c882ae489 100644 --- a/apps/settings/src/components/AppList/AppItem.vue +++ b/apps/appstore/src/components/AppList/AppTable.vue @@ -129,7 +129,7 @@ @@ -139,13 +139,12 @@ import { mdiCogOutline } from '@mdi/js' import NcButton from '@nextcloud/vue/components/NcButton' import NcIconSvgWrapper from '@nextcloud/vue/components/NcIconSvgWrapper' -import DaemonSelectionDialog from '../AppAPI/DaemonSelectionDialog.vue' -import SvgFilterMixin from '../SvgFilterMixin.vue' +import DaemonSelectionDialog from '../DaemonSelectionDialog/DaemonSelectionDialog.vue' import AppLevelBadge from './AppLevelBadge.vue' import AppScore from './AppScore.vue' import AppManagement from '../../mixins/AppManagement.js' -import { useAppApiStore } from '../../store/app-api-store.ts' -import { useAppsStore } from '../../store/apps-store.js' +import { useAppsStore } from '../../store/apps.ts' +import { useAppApiStore } from '../../store/exApps.ts' export default { name: 'AppItem', @@ -157,7 +156,7 @@ export default { DaemonSelectionDialog, }, - mixins: [AppManagement, SvgFilterMixin], + mixins: [AppManagement], props: { app: { type: Object, @@ -281,7 +280,6 @@ export default { diff --git a/apps/settings/src/composables/useAppIcon.ts b/apps/appstore/src/composables/useAppIcon.ts similarity index 84% rename from apps/settings/src/composables/useAppIcon.ts rename to apps/appstore/src/composables/useAppIcon.ts index 533363d17e38b..d5bb53ceffe05 100644 --- a/apps/settings/src/composables/useAppIcon.ts +++ b/apps/appstore/src/composables/useAppIcon.ts @@ -1,14 +1,15 @@ -/** +/*! * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ + import type { Ref } from 'vue' -import type { IAppstoreApp } from '../app-types.ts' +import type { IAppstoreApp, IAppstoreExApp } from '../apps.d.ts' import { mdiCog, mdiCogOutline } from '@mdi/js' import { computed, ref, watchEffect } from 'vue' -import AppstoreCategoryIcons from '../constants/AppstoreCategoryIcons.ts' -import logger from '../logger.ts' +import { APPSTORE_CATEGORY_ICONS } from '../constants.ts' +import logger from '../utils/logger.ts' /** * Get the app icon raw SVG for use with `NcIconSvgWrapper` (do never use without sanitizing) @@ -16,7 +17,7 @@ import logger from '../logger.ts' * * @param app The app to get the icon for */ -export function useAppIcon(app: Ref) { +export function useAppIcon(app: Ref) { const appIcon = ref(null) /** @@ -29,7 +30,7 @@ export function useAppIcon(app: Ref) { path = mdiCogOutline } else { path = [app.value?.category ?? []].flat() - .map((name) => AppstoreCategoryIcons[name]) + .map((name) => APPSTORE_CATEGORY_ICONS[name]) .filter((icon) => !!icon) .at(0) ?? (!app.value?.app_api ? mdiCog : mdiCogOutline) diff --git a/apps/settings/src/composables/useGetLocalizedValue.ts b/apps/appstore/src/composables/useGetLocalizedValue.ts similarity index 73% rename from apps/settings/src/composables/useGetLocalizedValue.ts rename to apps/appstore/src/composables/useGetLocalizedValue.ts index 17d8b56b308cc..16bfa84750457 100644 --- a/apps/settings/src/composables/useGetLocalizedValue.ts +++ b/apps/appstore/src/composables/useGetLocalizedValue.ts @@ -1,23 +1,13 @@ -/** +/*! * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ -import type { ILocalizedValue } from '../constants/AppDiscoverTypes.ts' - -import { getLanguage } from '@nextcloud/l10n' -import { - type Ref, - computed, -} from 'vue' +import type { Ref } from 'vue' +import type { ILocalizedValue } from '../apps-discover.d.ts' -/** - * Helper to get the localized value for the current users language - * - * @param dict The dictionary to get the value from - * @param language The language to use - */ -const getLocalizedValue = (dict: ILocalizedValue, language: string) => dict[language] ?? dict[language.split('_')[0]] ?? dict.en ?? null +import { getLanguage } from '@nextcloud/l10n' +import { computed } from 'vue' /** * Get the localized value of the dictionary provided @@ -33,3 +23,13 @@ export function useLocalizedValue(dict: Ref | return computed(() => !dict?.value ? null : getLocalizedValue(dict.value as ILocalizedValue, language)) } + +/** + * Helper to get the localized value for the current users language + * + * @param dict The dictionary to get the value from + * @param language The language to use + */ +function getLocalizedValue(dict: ILocalizedValue, language: string) { + return dict[language] ?? dict[language.split('_')[0]!] ?? dict.en ?? null +} diff --git a/apps/appstore/src/composables/useMarkdown.spec.ts b/apps/appstore/src/composables/useMarkdown.spec.ts new file mode 100644 index 0000000000000..e518da81aa1fd --- /dev/null +++ b/apps/appstore/src/composables/useMarkdown.spec.ts @@ -0,0 +1,52 @@ +/*! + * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { expect, test } from 'vitest' +import { useMarkdown } from './useMarkdown.ts' + +test('renders links', () => { + const rendered = useMarkdown('This is [a link](http://example.com)!') + expect(rendered.value).toMatchInlineSnapshot('"

This is a link!

\n"') +}) + +test('removes links with invalid URL', () => { + const rendered = useMarkdown('This is [a link](ftp://example.com)!') + expect(rendered.value).toMatchInlineSnapshot('"

This is !

\n"') +}) + +test('renders images', () => { + const rendered = useMarkdown('![alt text](http://example.com/image.jpg)') + expect(rendered.value).toMatchInlineSnapshot('"

alt text

\n"') +}) + +test('renders images with title', () => { + const rendered = useMarkdown('![](http://example.com/image.jpg "Title")') + expect(rendered.value).toMatchInlineSnapshot('"

Title

\n"') +}) + +test('renders images with alt text and title', () => { + const rendered = useMarkdown('![alt text](http://example.com/image.jpg "Title")') + expect(rendered.value).toMatchInlineSnapshot(` + "

alt text

\n" + `) +}) + +test('renders block quotes', () => { + const rendered = useMarkdown('> This is a block quote') + expect(rendered.value).toMatchInlineSnapshot('"
This is a block quote
"') +}) + +test('renders headings', () => { + const rendered = useMarkdown('# level 1\n## level 2\n### level 3\n#### level 4\n##### level 5\n###### level 6\n') + expect(rendered.value).toMatchInlineSnapshot('"

level 1

level 2

level 3

level 4

level 5
level 6
"') +}) + +test('renders headings with minHeadingLevel', () => { + const rendered = useMarkdown( + '# level 1\n## level 2\n### level 3\n#### level 4\n##### level 5\n###### level 6\n', + { minHeadingLevel: 4 }, + ) + expect(rendered.value).toMatchInlineSnapshot('"

level 1

level 2
level 3
level 4
level 5
level 6
"') +}) diff --git a/apps/appstore/src/composables/useMarkdown.ts b/apps/appstore/src/composables/useMarkdown.ts new file mode 100644 index 0000000000000..26eb66acdfbcb --- /dev/null +++ b/apps/appstore/src/composables/useMarkdown.ts @@ -0,0 +1,129 @@ +import type { Tokens } from 'marked' +import type { MaybeRefOrGetter } from 'vue' + +import dompurify from 'dompurify' +import { marked } from 'marked' +import { computed, toValue } from 'vue' + +export interface MarkdownOptions { + minHeadingLevel?: number +} + +/** + * Render Markdown to HTML + * + * @param text - The Markdown source + * @param options - Markdown options + */ +export function useMarkdown(text: MaybeRefOrGetter, options?: MarkdownOptions) { + const renderer = new marked.Renderer() + renderer.blockquote = markedBlockquote + renderer.link = markedLink + renderer.image = markedImage + + return computed(() => { + const minHeading = options?.minHeadingLevel ?? 1 + renderer.heading = getMarkedHeading(minHeading) + const markdown = toValue(text).trim() + + return dompurify.sanitize( + marked(markdown, { + async: false, + renderer, + gfm: false, + breaks: false, + pedantic: false, + }), + { + ALLOWED_TAGS: [ + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'strong', + 'p', + 'a', + 'ul', + 'ol', + 'li', + 'em', + 'del', + 'blockquote', + ], + }, + ) + }) +} + +/** + * Custom link renderer that only allows http and https links + * + * @param ctx - The render context + * @param ctx.href - The link href + * @param ctx.title - The link title + * @param ctx.text - The link text + */ +function markedLink({ href, title, text }: Tokens.Link) { + let url: URL + try { + url = new URL(href) + } catch { + return '' + } + + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + return '' + } + + let out = '' + return out +} + +/** + * Only render image alt text or title + * + * @param ctx - The render context + * @param ctx.title - The image title + * @param ctx.text - The image alt text + */ +function markedImage({ title, text }: Tokens.Image): string { + if (text) { + return text + } + return title ?? '' +} + +/** + * Render block quotes without any special styling + * + * @param ctx - The render context + * @param ctx.text - The blockquote text + */ +function markedBlockquote({ text }: Tokens.Blockquote): string { + return `
${text}
` +} + +/** + * Get a custom heading renderer that clamps heading levels + * + * @param minHeading - The heading to clamp to + */ +function getMarkedHeading(minHeading: number) { + /** + * Custom heading renderer that adjusts heading levels + * + * @param ctx - The render context + * @param ctx.text - The heading text + * @param ctx.depth - The heading depth + */ + return ({ text, depth }: Tokens.Heading): string => { + depth = Math.min(6, depth + (minHeading - 1)) + return `${text}` + } +} diff --git a/apps/appstore/src/constants.ts b/apps/appstore/src/constants.ts new file mode 100644 index 0000000000000..c7ef0ba1f6c5a --- /dev/null +++ b/apps/appstore/src/constants.ts @@ -0,0 +1,84 @@ +/** + * SPDX-FileCopyrightText: Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { + mdiAccountMultipleOutline, + mdiAccountOutline, + mdiArchiveOutline, + mdiCheck, + mdiClipboardFlowOutline, + mdiClose, + mdiCogOutline, + mdiControllerClassicOutline, + mdiCreationOutline, + mdiDownload, + mdiFileDocumentEdit, + mdiFolder, + mdiKeyOutline, + mdiMagnify, + mdiMonitorEye, + mdiMultimedia, + mdiOfficeBuildingOutline, + mdiOpenInApp, + mdiSecurity, + mdiStar, + mdiStarCircleOutline, + mdiStarShootingOutline, + mdiTools, + mdiViewColumnOutline, +} from '@mdi/js' +import { t } from '@nextcloud/l10n' + +/** + * The names of the special appstore sections + */ +export const APPSTORE_CATEGORY_NAMES = Object.freeze({ + discover: t('settings', 'Discover'), + installed: t('settings', 'Your apps'), + enabled: t('settings', 'Active apps'), + disabled: t('settings', 'Disabled apps'), + updates: t('settings', 'Updates'), + 'app-bundles': t('settings', 'App bundles'), + featured: t('settings', 'Featured apps'), + supported: t('settings', 'Supported apps'), // From subscription +}) + +/** + * SVG paths used for appstore category icons + */ +export const APPSTORE_CATEGORY_ICONS = Object.freeze({ + // system special categories + discover: mdiStarCircleOutline, + installed: mdiAccountOutline, + enabled: mdiCheck, + disabled: mdiClose, + bundles: mdiArchiveOutline, + supported: mdiStarShootingOutline, + featured: mdiStar, + updates: mdiDownload, + + // generic category + ai: mdiCreationOutline, + auth: mdiKeyOutline, + customization: mdiCogOutline, + dashboard: mdiViewColumnOutline, + files: mdiFolder, + games: mdiControllerClassicOutline, + integration: mdiOpenInApp, + monitoring: mdiMonitorEye, + multimedia: mdiMultimedia, + office: mdiFileDocumentEdit, + organization: mdiOfficeBuildingOutline, + search: mdiMagnify, + security: mdiSecurity, + social: mdiAccountMultipleOutline, + tools: mdiTools, + workflow: mdiClipboardFlowOutline, +}) + +/** + * Currently known types of app discover section elements + */ +export const APP_DISCOVER_KNOWN_TYPES = ['post', 'showcase', 'carousel'] as const diff --git a/apps/appstore/src/main.ts b/apps/appstore/src/main.ts new file mode 100644 index 0000000000000..79b66f2a90c9d --- /dev/null +++ b/apps/appstore/src/main.ts @@ -0,0 +1,17 @@ +/** + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { createPinia } from 'pinia' +import { createApp } from 'vue' +import AppstoreApp from './AppstoreApp.vue' +import router from './router/index.ts' + +import 'vite/modulepreload-polyfill' + +const pinia = createPinia() +const app = createApp(AppstoreApp) +app.use(pinia) +app.use(router) +app.mount('#content') diff --git a/apps/settings/src/mixins/AppManagement.js b/apps/appstore/src/mixins/AppManagement.js similarity index 94% rename from apps/settings/src/mixins/AppManagement.js rename to apps/appstore/src/mixins/AppManagement.js index f8b53f41fbf75..6e60877765e32 100644 --- a/apps/settings/src/mixins/AppManagement.js +++ b/apps/appstore/src/mixins/AppManagement.js @@ -4,7 +4,7 @@ */ import { showError } from '@nextcloud/dialogs' -import rebuildNavigation from '../service/rebuild-navigation.js' +import { rebuildNavigation } from '../service/rebuild-navigation.ts' const productName = window.OC.theme.productName @@ -253,19 +253,5 @@ export default { .catch((error) => { showError(error) }) } }, - update(appId) { - if (this.app?.app_api) { - this.appApiStore.updateApp(appId) - .then(() => { rebuildNavigation() }) - .catch((error) => { showError(error) }) - } else { - this.$store.dispatch('updateApp', { appId }) - .catch((error) => { showError(error) }) - .then(() => { - rebuildNavigation() - this.store.updateCount = Math.max(this.store.updateCount - 1, 0) - }) - } - }, }, } diff --git a/apps/appstore/src/router/index.ts b/apps/appstore/src/router/index.ts new file mode 100644 index 0000000000000..8649d76c039af --- /dev/null +++ b/apps/appstore/src/router/index.ts @@ -0,0 +1,16 @@ +/** + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { generateUrl } from '@nextcloud/router' +import { createRouter, createWebHistory } from 'vue-router' +import routes from './routes.ts' + +const router = createRouter({ + history: createWebHistory(generateUrl('')), + linkActiveClass: 'active', + routes, +}) + +export default router diff --git a/apps/appstore/src/router/routes.ts b/apps/appstore/src/router/routes.ts new file mode 100644 index 0000000000000..bba01686200d1 --- /dev/null +++ b/apps/appstore/src/router/routes.ts @@ -0,0 +1,50 @@ +/*! + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { RouteRecordRaw } from 'vue-router' + +import { loadState } from '@nextcloud/initial-state' +import { defineAsyncComponent } from 'vue' +const appstoreEnabled = loadState('settings', 'appstoreEnabled', true) + +// Dynamic loading +const AppstoreDiscover = defineAsyncComponent(() => import('../views/AppstoreDiscover.vue')) + +// const AppStore = () => import(/* webpackChunkName: 'settings-apps-view' */'../views/AppStore.vue') +// const AppStoreNavigation = () => import(/* webpackChunkName: 'settings-apps-view' */'../views/AppStoreNavigation.vue') +// const AppStoreSidebar = () => import(/* webpackChunkName: 'settings-apps-view' */'../views/AppStoreSidebar.vue') + +const routes: RouteRecordRaw[] = [ + { + path: '/:index(index.php/)?settings/apps', + name: 'apps', + redirect: appstoreEnabled + ? { + name: 'apps-discover', + } + : { + name: 'apps-category', + params: { category: 'installed' }, + }, + children: [ + { + path: 'discover/:id?', + name: 'apps-discover', + component: AppstoreDiscover, + }, + { + path: ':category', + name: 'apps-category', + children: [{ + path: ':id', + name: 'apps-details', + component: {}, + }], + }, + ], + }, +] + +export default routes diff --git a/apps/appstore/src/service/api.ts b/apps/appstore/src/service/api.ts new file mode 100644 index 0000000000000..338d885355e61 --- /dev/null +++ b/apps/appstore/src/service/api.ts @@ -0,0 +1,51 @@ +/** + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { OCSResponse } from '@nextcloud/typings/ocs' +import type { IAppstoreApp, IAppstoreCategory } from '../apps.d.ts' + +import axios from '@nextcloud/axios' +import { confirmPassword } from '@nextcloud/password-confirmation' +import { generateOcsUrl } from '@nextcloud/router' +import { APPSTORE_CATEGORY_ICONS } from '../constants.ts' + +const BASE_URL = generateOcsUrl('apps/appstore/api/v1') +const Url = Object.freeze({ + apps: `${BASE_URL}/apps`, + categories: `${BASE_URL}/apps/categories`, + enable: `${BASE_URL}/apps/enable`, + disable: `${BASE_URL}/apps/disable`, + uninstall: `${BASE_URL}/apps/uninstall`, + update: `${BASE_URL}/apps/update`, +}) + +/** + * Update an app by its app id + * + * @param appId - The app id to update + */ +export async function updateApp(appId: string) { + await confirmPassword() + await axios.post(Url.update, { appId }) +} + +/** + * Get all apps from the appstore + */ +export async function getApps() { + const { data } = await axios.get>(Url.apps) + return data.ocs.data +} + +/** + * Get app categories + */ +export async function getCategories() { + const { data } = await axios.get>(Url.categories) + for (const category of data.ocs.data) { + category.icon = APPSTORE_CATEGORY_ICONS[category.id] ?? '' + } + return data.ocs.data +} diff --git a/apps/appstore/src/service/app-discover.ts b/apps/appstore/src/service/app-discover.ts new file mode 100644 index 0000000000000..4516e53be91eb --- /dev/null +++ b/apps/appstore/src/service/app-discover.ts @@ -0,0 +1,50 @@ +/*! + * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' +import { filterElements, parseApiResponse } from '../utils/appDiscoverParser.ts' + +/** + * Get app discover elements + */ +export async function getDiscoverElements() { + const data = await loadDiscoverElements() + if (data.length === 0) { + throw new Error('No app discover elements available (empty response)') + } + + // Parse data to ensure dates are useable and then filter out expired or future elements + const parsedElements = data.map(parseApiResponse) + .filter(filterElements) + + // Shuffle elements to make it looks more interesting + const shuffledElements = shuffleArray(parsedElements) + // Sort pinned elements first + shuffledElements.sort((a, b) => (a.order ?? Infinity) < (b.order ?? Infinity) ? -1 : 1) + return shuffledElements +} + +/** + * Shuffle using the Fisher-Yates algorithm + * + * @param array The array to shuffle (in place) + */ +function shuffleArray(array: T[]): T[] { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j]!, array[i]!] + } + return array +} + +/** + * Load discover elements from the API + */ +async function loadDiscoverElements() { + const url = generateUrl('/apps/appstore/api/v1/discover') + const { data } = await axios.get[]>(url) + return data +} diff --git a/apps/appstore/src/service/rebuild-navigation.ts b/apps/appstore/src/service/rebuild-navigation.ts new file mode 100644 index 0000000000000..e3ff425cbd6b2 --- /dev/null +++ b/apps/appstore/src/service/rebuild-navigation.ts @@ -0,0 +1,23 @@ +/*! + * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { OCSResponse } from '@nextcloud/typings/ocs' + +import axios from '@nextcloud/axios' +import { emit } from '@nextcloud/event-bus' +import { generateOcsUrl } from '@nextcloud/router' + +/** + * Rebuilds the app navigation menu + */ +export async function rebuildNavigation() { + const { data } = await axios.get(generateOcsUrl('core/navigation/apps?format=json')) + if (data.ocs.meta.statuscode !== 200) { + return + } + + emit('nextcloud:app-menu.refresh', { apps: data.ocs.data }) + window.dispatchEvent(new Event('resize')) +} diff --git a/apps/appstore/src/settings.ts b/apps/appstore/src/settings.ts new file mode 100644 index 0000000000000..17cd8f82fbe7f --- /dev/null +++ b/apps/appstore/src/settings.ts @@ -0,0 +1,11 @@ +/** + * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { rebuildNavigation } from './service/rebuild-navigation.ts' + +window.OC.Settings ??= {} +window.OC.Settings.Apps ??= { + rebuildNavigation, +} diff --git a/apps/settings/src/store/apps.js b/apps/appstore/src/store/apps.js similarity index 99% rename from apps/settings/src/store/apps.js rename to apps/appstore/src/store/apps.js index 53f66424c0ea2..fc5253164b4b4 100644 --- a/apps/settings/src/store/apps.js +++ b/apps/appstore/src/store/apps.js @@ -8,7 +8,7 @@ import { showError, showInfo } from '@nextcloud/dialogs' import { loadState } from '@nextcloud/initial-state' import { generateUrl } from '@nextcloud/router' import Vue from 'vue' -import logger from '../logger.ts' +import logger from '../utils/logger.ts' import api from './api.js' const state = { @@ -18,7 +18,7 @@ const state = { updateCount: loadState('settings', 'appstoreUpdateCount', 0), loading: {}, gettingCategoriesPromise: null, - appApiEnabled: loadState('settings', 'appApiEnabled', false), + appApiEnabled: , } const mutations = { diff --git a/apps/appstore/src/store/apps.ts b/apps/appstore/src/store/apps.ts new file mode 100644 index 0000000000000..85a1dae374e3b --- /dev/null +++ b/apps/appstore/src/store/apps.ts @@ -0,0 +1,112 @@ +/** + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { IAppstoreApp, IAppstoreCategory, IAppstoreExApp } from '../apps.d.ts' + +import { showError } from '@nextcloud/dialogs' +import { t } from '@nextcloud/l10n' +import { defineStore } from 'pinia' +import { computed, ref } from 'vue' +import * as api from '../service/api.ts' +import logger from '../utils/logger.ts' +import { useExAppsStore } from './exApps.ts' + +export const useAppsStore = defineStore('apps', () => { + const exApps = useExAppsStore() + + /** + * All apps available in the appstore + */ + const appstoreApps = ref([]) + /** + * All app categories available in the appstore + */ + const categories = ref([]) + /** + * Loading state of the store + */ + const isLoadingApps = ref(false) + const isLoadingCategories = ref(false) + + /** + * All apps available + */ + const apps = computed(() => [...appstoreApps.value, ...(exApps.isEnabled ? exApps.apps : [])]) + + /** + * Get a category by its id + * + * @param categoryId - The id of the category + */ + function getCategoryById(categoryId: string) { + return categories.value.find(({ id }) => id === categoryId) ?? null + } + + /** + * Get an app by its id + * + * @param appId - The id of the app + */ + function getAppById(appId: string): IAppstoreApp | IAppstoreExApp | null { + return apps.value.find(({ id }) => id === appId) ?? null + } + + /** + * + * @param appId - The app to update + * @param groups - The new groups + */ + function updateAppGroups(appId: string, groups: string[]) { + const app = apps.value.find(({ id }) => id === appId) + if (app) { + app.groups = [...groups] + } + } + + /** + * Load the app categories from the backend + */ + async function loadCategories() { + try { + isLoadingCategories.value = true + categories.value = await api.getCategories() + } catch (error) { + logger.error('Failed to load app categories', { error }) + showError(t('settings', 'Could not load app categories. Please try again later.')) + } finally { + isLoadingCategories.value = false + } + } + + /** + * Load the apps from the backend + */ + async function loadApps() { + try { + isLoadingApps.value = true + appstoreApps.value = await api.getApps() + } catch (error) { + logger.error('Failed to load apps list', { error }) + showError(t('settings', 'Could not load apps list. Please try again later.')) + } finally { + isLoadingApps.value = false + } + } + + // initialize store + loadApps() + loadCategories() + + return { + apps, + categories, + isLoadingApps, + isLoadingCategories, + + getAppById, + getCategoryById, + updateAppGroups, + } +}) diff --git a/apps/settings/src/store/app-api-store.ts b/apps/appstore/src/store/exApps.ts similarity index 65% rename from apps/settings/src/store/app-api-store.ts rename to apps/appstore/src/store/exApps.ts index ba14956bf5e09..cd83e011b80af 100644 --- a/apps/settings/src/store/app-api-store.ts +++ b/apps/appstore/src/store/exApps.ts @@ -3,77 +3,92 @@ * SPDX-License-Identifier: AGPL-3.0-or-later */ -import type { IAppstoreExApp, IDeployDaemon, IDeployOptions, IExAppStatus } from '../app-types.ts' +import type { IAppstoreExApp, IDeployDaemon, IExAppStatus } from '../apps.d.ts' import axios from '@nextcloud/axios' -import { showError, showInfo } from '@nextcloud/dialogs' +import { showError } from '@nextcloud/dialogs' import { loadState } from '@nextcloud/initial-state' -import { translate as t } from '@nextcloud/l10n' -import { confirmPassword } from '@nextcloud/password-confirmation' +import { t } from '@nextcloud/l10n' import { generateUrl } from '@nextcloud/router' import { defineStore } from 'pinia' -import Vue from 'vue' -import logger from '../logger.ts' -import api from './api.js' +import { computed, ref } from 'vue' +import logger from '../utils/logger.ts' -interface AppApiState { - apps: IAppstoreExApp[] - updateCount: number - loading: Record - loadingList: boolean - statusUpdater: number | null | undefined - daemonAccessible: boolean - defaultDaemon: IDeployDaemon | null - dockerDaemons: IDeployDaemon[] -} +export const useExAppsStore = defineStore('external-apps', () => { + /** + * Is the App API enabled + */ + const isEnabled = loadState('settings', 'appApiEnabled', false) -export const useAppApiStore = defineStore('app-api-apps', { - state: (): AppApiState => ({ - apps: [], - updateCount: loadState('settings', 'appstoreExAppUpdateCount', 0), - loading: {}, - loadingList: false, - statusUpdater: null, - daemonAccessible: loadState('settings', 'defaultDaemonConfigAccessible', false), - defaultDaemon: loadState('settings', 'defaultDaemonConfig', null), - dockerDaemons: [], - }), + const apps = ref([]) + const updateCount = ref(loadState('settings', 'appstoreExAppUpdateCount', 0)) + const loading = ref>({}) + const loadingList = ref(false) + const statusUpdater = ref(null) + const daemonAccessible = ref(loadState('settings', 'defaultDaemonConfigAccessible', false)) + const defaultDaemon = ref(loadState('settings', 'defaultDaemonConfig', null)) + const dockerDaemons = ref([]) - getters: { - getLoading: (state) => (id: string) => state.loading[id] ?? false, - getAllApps: (state) => state.apps, - getUpdateCount: (state) => state.updateCount, - getDaemonAccessible: (state) => state.daemonAccessible, - getDefaultDaemon: (state) => state.defaultDaemon, - getAppStatus: (state) => (appId: string) => state.apps.find((app) => app.id === appId)?.status || null, - getStatusUpdater: (state) => state.statusUpdater, - getInitializingOrDeployingApps: (state) => state.apps.filter((app) => app?.status?.action - && (app?.status?.action === 'deploy' || app.status.action === 'init' || app.status.action === 'healthcheck') - && app.status.type !== ''), - }, + const initializingOrDeployingApps = computed(() => apps.value.filter((app) => app?.status?.action + && (app?.status?.action === 'deploy' || app.status.action === 'init' || app.status.action === 'healthcheck') + && app.status.type !== '')) - actions: { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - appsApiFailure(error: any) { - showError(t('settings', 'An error occurred during the request. Unable to proceed.') + '
' + error.error.response.data.data.message, { isHTML: true }) - logger.error(error) - }, + /** + * Get an external app by its ID + * + * @param appId - The app ID + */ + function getById(appId: string): IAppstoreExApp | null { + return apps.value.find(({ id }) => id === appId) ?? null + } - setLoading(id: string, value: boolean) { - Vue.set(this.loading, id, value) - }, + /** + * Update an external app + * + * @param appId - The app ID + */ + async function updateApp(appId: string) { + const app = getById(appId) + if (!app) { + throw new Error(`App with id ${appId} not found`) + } - setError(appId: string | string[], error: string) { - const appIds = Array.isArray(appId) ? appId : [appId] - appIds.forEach((_id) => { - const app = this.apps.find((app) => app.id === _id) - if (app) { - app.error = error - } - }) - }, + app.loading = true + try { + await axios.get(generateUrl(`/apps/app_api/apps/update/${appId}`)) + app.version = app.update || app.version + app.status = { + type: 'update', + action: 'deploy', + init: 0, + deploy: 0, + } satisfies IExAppStatus + delete app.update + delete app.error + updateCount.value-- + // Trigger status updates + // updateAppsStatus() + } catch (error) { + logger.error('Failed to update ex app', { appId, error }) + showError(t('settings', 'Could not update the app. Please try again later.')) + } finally { + app.loading = false + } + } - enableApp(appId: string, daemon: IDeployDaemon, deployOptions: IDeployOptions) { + return { + isEnabled, + + apps, + updateCount, + defaultDaemon, + dockerDaemons, + + getById, + updateApp, + } + + /* enableApp(appId: string, daemon: IDeployDaemon, deployOptions: IDeployOptions) { this.setLoading(appId, true) this.setLoading('install', true) return confirmPassword().then(() => { @@ -207,42 +222,6 @@ export const useAppApiStore = defineStore('app-api-apps', { }) }, - updateApp(appId: string) { - this.setLoading(appId, true) - this.setLoading('install', true) - return confirmPassword().then(() => { - return api.get(generateUrl(`/apps/app_api/apps/update/${appId}`)) - .then(() => { - this.setLoading(appId, false) - this.setLoading('install', false) - const app = this.apps.find((app) => app.id === appId) - if (app) { - const version = app.update - app.update = undefined - app.version = version || app.version - app.status = { - type: 'update', - action: 'deploy', - init: 0, - deploy: 0, - } as IExAppStatus - app.error = '' - } - this.updateCount-- - this.updateAppsStatus() - return true - }) - .catch((error) => { - this.setLoading(appId, false) - this.setLoading('install', false) - this.appsApiFailure({ appId, error }) - }) - }).catch(() => { - this.setLoading(appId, false) - this.setLoading('install', false) - }) - }, - async fetchAllApps() { this.loadingList = true try { @@ -311,5 +290,5 @@ export const useAppApiStore = defineStore('app-api-apps', { }) }, 2000) as unknown as number }, - }, + }, */ }) diff --git a/apps/appstore/src/store/updates.ts b/apps/appstore/src/store/updates.ts new file mode 100644 index 0000000000000..8b57c761d8553 --- /dev/null +++ b/apps/appstore/src/store/updates.ts @@ -0,0 +1,63 @@ +/*! + * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { showError } from '@nextcloud/dialogs' +import { loadState } from '@nextcloud/initial-state' +import { t } from '@nextcloud/l10n' +import { defineStore } from 'pinia' +import { computed, ref } from 'vue' +import * as api from '../service/api.ts' +import { rebuildNavigation } from '../service/rebuild-navigation.ts' +import logger from '../utils/logger.ts' +import { useAppsStore } from './apps.ts' +import { useExAppsStore } from './exApps.ts' + +export const useUpdatesStore = defineStore('updates', () => { + const exApps = useExAppsStore() + + /** + * Number of apps with available updates + */ + const internalUpdateCount = ref(loadState('settings', 'appstoreUpdateCount', 0)) + + /** + * Total number of apps with available updates + */ + const updateCount = computed(() => internalUpdateCount.value + exApps.updateCount) + + /** + * Update the given app + * + * @param appId - The app id to update + * @throws {Error} if the app is not found + */ + async function updateApp(appId: string) { + const store = useAppsStore() + + const app = store.getAppById(appId) + if (!app) { + throw new Error(`App with id ${appId} not found`) + } + + try { + if ('app_api' in app && app.app_api) { + await exApps.updateApp(appId) + } else { + await api.updateApp(appId) + internalUpdateCount.value = Math.max(internalUpdateCount.value - 1, 0) + } + + rebuildNavigation() + } catch (error) { + logger.error('Failed to update app', { appId, error }) + showError(t('settings', 'Could not update the app. Please try again later.')) + } + } + + return { + updateCount, + updateApp, + } +}) diff --git a/apps/settings/src/utils/appDiscoverParser.spec.ts b/apps/appstore/src/utils/appDiscoverParser.spec.ts similarity index 100% rename from apps/settings/src/utils/appDiscoverParser.spec.ts rename to apps/appstore/src/utils/appDiscoverParser.spec.ts diff --git a/apps/settings/src/utils/appDiscoverParser.ts b/apps/appstore/src/utils/appDiscoverParser.ts similarity index 100% rename from apps/settings/src/utils/appDiscoverParser.ts rename to apps/appstore/src/utils/appDiscoverParser.ts diff --git a/apps/appstore/src/utils/handlers.ts b/apps/appstore/src/utils/handlers.ts new file mode 100644 index 0000000000000..e608e95571555 --- /dev/null +++ b/apps/appstore/src/utils/handlers.ts @@ -0,0 +1,33 @@ +/** + * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { AxiosError } from '@nextcloud/axios' + +import { showError } from '@nextcloud/dialogs' +import { translate as t } from '@nextcloud/l10n' +import logger from '../utils/logger.ts' + +/** + * @param error the error + * @param message the message to display + */ +export function handleError(error: AxiosError, message: string) { + let fullMessage = '' + + if (message) { + fullMessage += message + } + + if (error.response?.status === 429) { + if (fullMessage) { + fullMessage += '\n' + } + fullMessage += t('settings', 'There were too many requests from your network. Retry later or contact your administrator if this is an error.') + } + + fullMessage = fullMessage || t('settings', 'Error') + showError(fullMessage) + logger.error(fullMessage, { error }) +} diff --git a/apps/appstore/src/utils/logger.ts b/apps/appstore/src/utils/logger.ts new file mode 100644 index 0000000000000..45dab72807d1f --- /dev/null +++ b/apps/appstore/src/utils/logger.ts @@ -0,0 +1,11 @@ +/** + * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { getLoggerBuilder } from '@nextcloud/logger' + +export default getLoggerBuilder() + .setApp('appstore') + .detectUser() + .build() diff --git a/apps/appstore/src/utils/sorting.ts b/apps/appstore/src/utils/sorting.ts new file mode 100644 index 0000000000000..88f877733ccc3 --- /dev/null +++ b/apps/appstore/src/utils/sorting.ts @@ -0,0 +1,14 @@ +/** + * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { getCanonicalLocale, getLanguage } from '@nextcloud/l10n' + +export const naturalCollator = Intl.Collator( + [getLanguage(), getCanonicalLocale()], + { + numeric: true, + usage: 'sort', + }, +) diff --git a/apps/appstore/src/utils/userUtils.ts b/apps/appstore/src/utils/userUtils.ts new file mode 100644 index 0000000000000..957688d20e66e --- /dev/null +++ b/apps/appstore/src/utils/userUtils.ts @@ -0,0 +1,28 @@ +/** + * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { translate as t } from '@nextcloud/l10n' + +export const unlimitedQuota = { + id: 'none', + label: t('settings', 'Unlimited'), +} + +export const defaultQuota = { + id: 'default', + label: t('settings', 'Default quota'), +} + +/** + * Return `true` if the logged in user does not have permissions to view the + * data of `user` + * + * @param user The user to check + * @param user.id Id of the user + */ +export function isObfuscated(user: { id: string, [key: string]: unknown }) { + const keys = Object.keys(user) + return keys.length === 1 && keys.at(0) === 'id' +} diff --git a/apps/appstore/src/utils/validate.js b/apps/appstore/src/utils/validate.js new file mode 100644 index 0000000000000..a9e0da458472d --- /dev/null +++ b/apps/appstore/src/utils/validate.js @@ -0,0 +1,79 @@ +/** + * SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +/* + * Frontend validators, less strict than backend validators + * + * TODO add nice validation errors for Profile page settings modal + */ + +import { VALIDATE_EMAIL_REGEX } from '../constants/AccountPropertyConstants.ts' + +/** + * Validate the email input + * + * Compliant with PHP core FILTER_VALIDATE_EMAIL validator* + * + * Reference implementation https://github.com/mpyw/FILTER_VALIDATE_EMAIL.js/blob/71e62ca48841d2246a1b531e7e84f5a01f15e615/src/index.ts* + * + * @param {string} input the input + * @return {boolean} + */ +export function validateEmail(input) { + return typeof input === 'string' + && VALIDATE_EMAIL_REGEX.test(input) + && input.slice(-1) !== '\n' + && input.length <= 320 + && encodeURIComponent(input).replace(/%../g, 'x').length <= 320 +} + +/** + * Validate the URL input + * + * @param {string} input the input + * @return {boolean} + */ +export function validateUrl(input) { + try { + new URL(input) + return true + } catch { + return false + } +} + +/** + * Validate the language input + * + * @param {object} input the input + * @return {boolean} + */ +export function validateLanguage(input) { + return input.code !== '' + && input.name !== '' + && input.name !== undefined +} + +/** + * Validate the locale input + * + * @param {object} input the input + * @return {boolean} + */ +export function validateLocale(input) { + return input.code !== '' + && input.name !== '' + && input.name !== undefined +} + +/** + * Validate boolean input + * + * @param {boolean} input the input + * @return {boolean} + */ +export function validateBoolean(input) { + return typeof input === 'boolean' +} diff --git a/apps/appstore/src/views/AppstoreBrowse.vue b/apps/appstore/src/views/AppstoreBrowse.vue new file mode 100644 index 0000000000000..7518923c65d78 --- /dev/null +++ b/apps/appstore/src/views/AppstoreBrowse.vue @@ -0,0 +1,83 @@ + + + + + + + diff --git a/apps/appstore/src/views/AppstoreDiscover.vue b/apps/appstore/src/views/AppstoreDiscover.vue new file mode 100644 index 0000000000000..ca135fadf2f4d --- /dev/null +++ b/apps/appstore/src/views/AppstoreDiscover.vue @@ -0,0 +1,97 @@ + + + + + + diff --git a/apps/settings/src/views/AppStore.vue b/apps/appstore/src/views/AppstoreManage.vue similarity index 93% rename from apps/settings/src/views/AppStore.vue rename to apps/appstore/src/views/AppstoreManage.vue index 1e26d394e3f78..c456add5f5022 100644 --- a/apps/settings/src/views/AppStore.vue +++ b/apps/appstore/src/views/AppstoreManage.vue @@ -33,7 +33,7 @@ import NcEmptyContent from '@nextcloud/vue/components/NcEmptyContent' import NcLoadingIcon from '@nextcloud/vue/components/NcLoadingIcon' import AppList from '../components/AppList.vue' import AppStoreDiscoverSection from '../components/AppStoreDiscover/AppStoreDiscoverSection.vue' -import { APPS_SECTION_ENUM } from '../constants/AppsConstants.js' +import { APPSTORE_CATEGORY_NAMES } from '../constants.ts' import { useAppApiStore } from '../store/app-api-store.ts' import { useAppsStore } from '../store/apps-store.ts' @@ -46,7 +46,7 @@ const appApiStore = useAppApiStore() */ const currentCategory = computed(() => route.params?.category ?? 'discover') -const viewLabel = computed(() => APPS_SECTION_ENUM[currentCategory.value] ?? store.getCategoryById(currentCategory.value)?.displayName) +const viewLabel = computed(() => APPSTORE_CATEGORY_NAMES[currentCategory.value] ?? store.getCategoryById(currentCategory.value)?.displayName) const pageHeading = t('settings', 'App Store') const pageTitle = computed(() => `${viewLabel.value} - ${pageHeading}`) // NcAppContent automatically appends the instance name diff --git a/apps/settings/src/views/AppStoreNavigation.vue b/apps/appstore/src/views/AppstoreNavigation.vue similarity index 82% rename from apps/settings/src/views/AppStoreNavigation.vue rename to apps/appstore/src/views/AppstoreNavigation.vue index b33636cdb7bf7..108fa24676150 100644 --- a/apps/settings/src/views/AppStoreNavigation.vue +++ b/apps/appstore/src/views/AppstoreNavigation.vue @@ -9,8 +9,8 @@ + :to="{ name: 'apps-discover' }" + :name="APPSTORE_CATEGORY_NAMES.discover"> @@ -18,7 +18,7 @@ + :name="APPSTORE_CATEGORY_NAMES.installed"> @@ -26,7 +26,7 @@ + :name="APPSTORE_CATEGORY_NAMES.enabled"> @@ -34,18 +34,18 @@ + :name="APPSTORE_CATEGORY_NAMES.disabled"> + :name="APPSTORE_CATEGORY_NAMES.updates">