Compare commits

..
Author SHA1 Message Date
ishabaral 1e22ec2c80 build(deps): bump pnpm dependencies 2026-07-27 11:46:03 +05:45
101 changed files with 814 additions and 8074 deletions

No files matched your search

@@ -1,15 +0,0 @@
Bugfix: Prevent deleting your own account in the user management
In the admin settings user management, the account you are currently logged in
as could be selected and included in a delete action, even though the backend
always rejects self-deletion. Deleting a selection that included your own
account produced a "Failed to delete 1 user" error and made your own row
temporarily disappear from the list until the page was refreshed.
The delete action now excludes the current user from the request, so all other
selected users are deleted while your own account is left untouched. When your
own account is part of the selection, the delete confirmation dialog shows a
hint that it will not be deleted.
https://github.com/owncloud/ocis/pull/12657
https://github.com/owncloud/ocis/issues/12582
@@ -1,12 +0,0 @@
Bugfix: Announce IDP sign-in errors and fix keyboard use
The login, consent, and account chooser pages did not announce error
messages when they appeared, and invalid username/password fields gave no
indication of their error state. The consent screen's scope list also had no
programmatic link between each entry and its checkbox, and the account
chooser's "continue as" and "use another account" entries could not be
reached or activated with a keyboard. A visible focus outline on the login
form's input fields had also been removed with no replacement. All of these
have been fixed.
https://github.com/owncloud/ocis/pull/12649
@@ -1,10 +0,0 @@
Bugfix: Return the created user in the invitation response
The invitations service created the guest account but returned the original request
body unchanged, so the `invitedUser` relation defined by the Graph invitation
response was always empty. Clients had no way to learn the identity of the user that
was just created. The service now populates `invitedUser` with the created user (id,
email address and user type), where the id is the OWNCLOUD_ID that oCIS uses once the
guest is provisioned locally.
https://github.com/owncloud/ocis/pull/12467
@@ -1,13 +0,0 @@
Bugfix: Sync the `.psec` file name when a password-protected folder is renamed
Renaming a password-protected folder did not update its `.psec` pointer file,
so the main file listing kept showing the old name. This happened both when
renaming the folder via the hidden `.PasswordProtectedFolders` location and
when renaming it from inside the folder-view modal.
Renaming the real folder now also renames its `.psec` counterpart. Inside the
folder-view modal, the framed public-link session notifies the parent window
at the moment of rename, so the pointer file stays in sync even on refresh or
another device.
https://github.com/owncloud/ocis/pull/12684
@@ -1,12 +0,0 @@
Enhancement: Add EPUB library
The EPUB reader now includes a library for discovering and organizing books
stored across accessible personal and project spaces. The library extracts
metadata and cover images in the browser and supports search, sorting, filters,
favorites, custom shelves, reading statuses, grid and list views, and resuming
from the reader's saved position.
Book metadata and covers are cached locally. Library preferences are stored in
the browser and are not synchronized between browsers or devices.
https://github.com/owncloud/ocis/pull/12648
@@ -1,16 +0,0 @@
Enhancement: Configurable Keycloak invitation actions and working ocis_full SMTP
The invitations service now lets operators configure the Keycloak required actions
that are sent to invited guests via the execute-actions email, using the new
`INVITATIONS_KEYCLOAK_EXECUTE_ACTIONS` environment variable. It defaults to
`UPDATE_PASSWORD,VERIFY_EMAIL`; configured values are passed to Keycloak as-is, and
the service falls back to the defaults when none are configured, so an invited guest
always has a way to set up their account.
The Keycloak realm shipped with the `ocis_full` example deployment now points its
SMTP server at the bundled mailpit instance. Previously the realm shipped with an
empty SMTP configuration, so Keycloak silently dropped every mail it tried to send
(including the guest invitation email) even though the invitations service
correctly requested it.
https://github.com/owncloud/ocis/pull/12467
@@ -1,8 +0,0 @@
Enhancement: Use a more distinctive icon for the software license link
The "Software License Information" entry in the help menu and apps menu used
the generic "scales" icon, which is easy to confuse with other justice- or
balance-related icons. It now uses the "file-shield" icon, which better
conveys a legal/license document.
https://github.com/owncloud/ocis/pull/12669
@@ -1,12 +0,0 @@
Enhancement: Add "Undo" action to the delete success notification
Deleting a file or folder now shows an "Undo" action alongside the
"moved to trash bin" notification, letting users restore the deleted
resources directly from the toast instead of navigating to the trash
bin. The action is only shown when the resources can be resolved in
the trash and the space supports restoring from it. The notification
pauses its auto-dismiss timer while hovered or focused, so it does not
disappear before the action can be used. Pressing Ctrl+Z (or Cmd+Z on
macOS) while the notification is visible triggers the same undo.
https://github.com/owncloud/ocis/pull/12650
@@ -1,18 +0,0 @@
Bugfix: Fix concurrent map access when listing shares
Listing shares could abort the whole oCIS process with the Go runtime error
"fatal error: concurrent map read and map write". This is an unrecoverable
runtime fault, so it could not be caught and recovered from, and it dropped all
connections that were in flight at that moment.
When converting CS3 shares into Graph DriveItems, the worker goroutines read
from the shared driveItems map while the collecting loop was already writing
results into the very same map. The results channel is buffered, so the workers
never blocked when handing over an item and the collecting loop started writing
while workers were still running. The results are now collected after all
workers have finished, which removes the overlapping access.
Note that lowering the maximum concurrency did not avoid this, as a single
worker could still run concurrently with the collecting loop.
https://github.com/owncloud/ocis/pull/12674
@@ -1,18 +0,0 @@
Bugfix: Log unmapped thumbnail errors and always report a sabredav exception
The webdav service logged failures of the thumbnails service at debug level only.
Errors which are not a property of the requested file, such as the thumbnails
service being unreachable, were therefore invisible at production log levels: a
complete preview outage produced HTTP 500 responses without a single log line
explaining them. Unmapped errors are now logged at error level, while expected
per-file outcomes such as an unsupported file type or a file still being
processed stay at debug level. Two of the four thumbnail handlers also logged
without the request context, so their messages carried no request id.
In addition, `codesEnum` only mapped four status codes, so error responses for
all other codes were rendered with an empty `<s:exception></s:exception>`
element. The missing entries for 403, 425 and 429 have been added and any
remaining unmapped code now falls back to a generic exception name, so clients
always receive a usable exception.
https://github.com/owncloud/ocis/pull/12668
@@ -1,14 +0,0 @@
Enhancement: Add audience restriction for OIDC access tokens
We added a new proxy configuration option `PROXY_OIDC_ACCESS_TOKEN_VERIFY_AUD`
which lets operators restrict the JWT access tokens that are accepted to a list
of allowed audiences. When set, a token is only accepted if one of the
configured values is present in its `aud` (audience) claim or matches its `azp`
(authorized party) claim. This is useful when the OIDC provider (IDP) is shared
between multiple applications, so that tokens issued for another application are
not accepted by ownCloud Infinite Scale.
The check is disabled by default (empty list) to preserve the existing behavior.
https://github.com/owncloud/ocis/pull/12634
@@ -1964,15 +1964,7 @@
"contentSecurityPolicy": "frame-src 'self'; frame-ancestors 'self'; object-src 'none';",
"strictTransportSecurity": "max-age=31536000; includeSubDomains"
},
"smtpServer": {
"host": "mailserver",
"port": "1025",
"from": "keycloak@owncloud.test",
"fromDisplayName": "oCIS",
"ssl": "false",
"starttls": "false",
"auth": "false"
},
"smtpServer": {},
"eventsEnabled": false,
"eventsListeners": [
"jboss-logging"
@@ -2,7 +2,7 @@
printenv
# replace oCIS domain in keycloak realm import
mkdir /opt/keycloak/data/import
sed -e "s/ocis.owncloud.test/${OCIS_DOMAIN}/g" -e "s/ocis.ocm.owncloud.test/${OCIS_OCM_DOMAIN}/g" /opt/keycloak/data/import-dist/ocis-realm.json > /opt/keycloak/data/import/oCIS-realm.json
sed -e "s/ocis.owncloud.test/${OCIS_DOMAIN}/g" /opt/keycloak/data/import-dist/ocis-realm.json > /opt/keycloak/data/import/oCIS-realm.json
# sed -e "s/ocis.ocm.owncloud.test/${OCIS_OCM_DOMAIN}/g" /opt/keycloak/data/import-dist/ocis-realm.json > /opt/keycloak/data/import/oCIS-realm.json
# run original docker-entrypoint
@@ -192,8 +192,7 @@ services:
OCIS_LDAP_BIND_PASSWORD: ${LDAP_ADMIN_PASSWORD:-admin}
OCIS_LDAP_GROUP_BASE_DN: "ou=groups,dc=owncloud,dc=com"
GRAPH_LDAP_GROUP_CREATE_BASE_DN: "ou=groups-8d24cb5f-6ee6-4b98-86df-c4c268dddb46,ou=groups,dc=owncloud,dc=com"
OCIS_LDAP_GROUP_OBJECTCLASS: "groupOfNames"
OCIS_LDAP_GROUP_ADDITIONAL_OBJECTCLASSES: "ownCloudGroup"
OCIS_LDAP_GROUP_OBJECTCLASS: "owncloudGroup"
OCIS_LDAP_USER_BASE_DN: "ou=users,dc=owncloud,dc=com"
OCIS_LDAP_USER_OBJECTCLASS: "inetOrgPerson"
LDAP_LOGIN_ATTRIBUTES: "uid"
@@ -273,7 +272,6 @@ services:
- "./config/keycloak/ocis-realm.dist.json:/opt/keycloak/data/import-dist/ocis-realm.json"
environment:
OCIS_DOMAIN: ${OCIS_DOMAIN:-ocis.owncloud.test}
OCIS_OCM_DOMAIN: ${OCIS_OCM_DOMAIN:-ocis.ocm.owncloud.test}
KC_HOSTNAME: ${KEYCLOAK_DOMAIN:-keycloak.owncloud.test}
KC_DB: postgres
KC_DB_URL: "jdbc:postgresql://postgres:5432/keycloak"
+101 -137
View File
@@ -6130,10 +6130,10 @@ IDM_ADMIN_USER_ID:
removalVersion: ""
deprecationInfo: ""
IDM_CREATE_DEMO_USERS:
name: IDM_CREATE_DEMO_USERS
name: SETTINGS_SETUP_DEFAULT_ASSIGNMENTS;IDM_CREATE_DEMO_USERS
defaultValue: "false"
type: bool
description: Flag to enable or disable the creation of the demo users.
description: The default role assignments the demo users should be setup.
introductionVersion: pre5.0
deprecationVersion: ""
removalVersion: ""
@@ -7974,12 +7974,12 @@ OCDAV_WEBDAV_NAMESPACE:
removalVersion: ""
deprecationInfo: ""
OCIS_ADMIN_USER_ID:
name: OCIS_ADMIN_USER_ID;IDM_ADMIN_USER_ID
name: OCIS_ADMIN_USER_ID;STORAGE_USERS_PURGE_TRASH_BIN_USER_ID
defaultValue: ""
type: string
description: ID of the user that should receive admin privileges. Consider that
the UUID can be encoded in some LDAP deployment configurations like in .ldif files.
These need to be decoded beforehand.
description: ID of the user who collects all necessary information for deletion.
Consider that the UUID can be encoded in some LDAP deployment configurations like
in .ldif files. These need to be decoded beforehand.
introductionVersion: pre5.0
deprecationVersion: ""
removalVersion: ""
@@ -8004,28 +8004,28 @@ OCIS_ASYNC_UPLOADS:
removalVersion: ""
deprecationInfo: ""
OCIS_CACHE_AUTH_PASSWORD:
name: OCIS_CACHE_AUTH_PASSWORD;GATEWAY_PROVIDER_CACHE_AUTH_PASSWORD
name: OCIS_CACHE_AUTH_PASSWORD;STORAGE_SYSTEM_CACHE_AUTH_PASSWORD
defaultValue: ""
type: string
description: The password to use for authentication. Only applies when store type
'nats-js-kv' is configured.
description: Password for the configured store. Only applies when store type 'nats-js-kv'
is configured.
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_CACHE_AUTH_USERNAME:
name: OCIS_CACHE_AUTH_USERNAME;GATEWAY_PROVIDER_CACHE_AUTH_USERNAME
name: OCIS_CACHE_AUTH_USERNAME;STORAGE_SYSTEM_CACHE_AUTH_USERNAME
defaultValue: ""
type: string
description: The username to use for authentication. Only applies when store type
'nats-js-kv' is configured.
description: Username for the configured store. Only applies when store type 'nats-js-kv'
is configured.
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_CACHE_DATABASE:
name: OCIS_CACHE_DATABASE
defaultValue: cache-providers
defaultValue: storage-system
type: string
description: The database name the configured store should use.
introductionVersion: pre5.0
@@ -8033,18 +8033,18 @@ OCIS_CACHE_DATABASE:
removalVersion: ""
deprecationInfo: ""
OCIS_CACHE_DISABLE_PERSISTENCE:
name: OCIS_CACHE_DISABLE_PERSISTENCE;GATEWAY_PROVIDER_CACHE_DISABLE_PERSISTENCE
name: OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_SYSTEM_CACHE_DISABLE_PERSISTENCE
defaultValue: "false"
type: bool
description: Disables persistence of the provider cache. Only applies when store
type 'nats-js-kv' is configured. Defaults to false.
description: Disables persistence of the cache. Only applies when store type 'nats-js-kv'
is configured. Defaults to false.
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_CACHE_STORE:
name: OCIS_CACHE_STORE;GATEWAY_PROVIDER_CACHE_STORE
defaultValue: noop
name: OCIS_CACHE_STORE;STORAGE_SYSTEM_CACHE_STORE
defaultValue: memory
type: string
description: 'The type of the cache store. Supported values are: ''memory'', ''redis-sentinel'',
''nats-js-kv'', ''noop''. See the text description for details.'
@@ -8053,7 +8053,7 @@ OCIS_CACHE_STORE:
removalVersion: ""
deprecationInfo: ""
OCIS_CACHE_STORE_NODES:
name: OCIS_CACHE_STORE_NODES;GATEWAY_PROVIDER_CACHE_STORE_NODES
name: OCIS_CACHE_STORE_NODES;STORAGE_SYSTEM_CACHE_STORE_NODES
defaultValue: '[127.0.0.1:9233]'
type: '[]string'
description: A list of nodes to access the configured store. This has no effect
@@ -8065,11 +8065,11 @@ OCIS_CACHE_STORE_NODES:
removalVersion: ""
deprecationInfo: ""
OCIS_CACHE_TTL:
name: OCIS_CACHE_TTL;GATEWAY_PROVIDER_CACHE_TTL
defaultValue: 5m0s
name: OCIS_CACHE_TTL;STORAGE_SYSTEM_CACHE_TTL
defaultValue: 24m0s
type: Duration
description: Default time to live for user info in the cache. Only applied when
access tokens has no expiration. See the Environment Variable Types description
description: Default time to live for user info in the user info cache. Only applied
when access tokens has no expiration. See the Environment Variable Types description
for more details.
introductionVersion: pre5.0
deprecationVersion: ""
@@ -8113,46 +8113,46 @@ OCIS_CLAIM_MANAGED_SPACES_REGEXP:
removalVersion: ""
deprecationInfo: ""
OCIS_CORS_ALLOW_CREDENTIALS:
name: OCIS_CORS_ALLOW_CREDENTIALS;ACTIVITYLOG_CORS_ALLOW_CREDENTIALS
name: OCIS_CORS_ALLOW_CREDENTIALS;SSE_CORS_ALLOW_CREDENTIALS
defaultValue: "true"
type: bool
description: 'Allow credentials for CORS.See following chapter for more details:
*Access-Control-Allow-Credentials* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials.'
introductionVersion: pre5.0
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_CORS_ALLOW_HEADERS:
name: OCIS_CORS_ALLOW_HEADERS;ACTIVITYLOG_CORS_ALLOW_HEADERS
name: OCIS_CORS_ALLOW_HEADERS;SSE_CORS_ALLOW_HEADERS
defaultValue: '[Authorization Origin Content-Type Accept X-Requested-With X-Request-Id
Ocs-Apirequest]'
type: '[]string'
description: 'A list of allowed CORS headers. See following chapter for more details:
*Access-Control-Request-Headers* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers.
See the Environment Variable Types description for more details.'
introductionVersion: pre5.0
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_CORS_ALLOW_METHODS:
name: OCIS_CORS_ALLOW_METHODS;ACTIVITYLOG_CORS_ALLOW_METHODS
name: OCIS_CORS_ALLOW_METHODS;SSE_CORS_ALLOW_METHODS
defaultValue: '[GET]'
type: '[]string'
description: 'A list of allowed CORS methods. See following chapter for more details:
*Access-Control-Request-Method* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Method.
See the Environment Variable Types description for more details.'
introductionVersion: pre5.0
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_CORS_ALLOW_ORIGINS:
name: OCIS_CORS_ALLOW_ORIGINS;ACTIVITYLOG_CORS_ALLOW_ORIGINS
name: OCIS_CORS_ALLOW_ORIGINS;SSE_CORS_ALLOW_ORIGINS
defaultValue: '[*]'
type: '[]string'
description: 'A list of allowed CORS origins. See following chapter for more details:
*Access-Control-Allow-Origin* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin.
See the Environment Variable Types description for more details.'
introductionVersion: pre5.0
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
@@ -8196,7 +8196,7 @@ OCIS_DEFAULT_LANGUAGE:
type: string
description: The default language used by services and the WebUI. If not defined,
English will be used as default. See the documentation for more details.
introductionVersion: 7.0.0
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
@@ -8242,7 +8242,7 @@ OCIS_DISABLE_VERSIONING:
removalVersion: ""
deprecationInfo: ""
OCIS_EDITION:
name: OCIS_EDITION;OCDAV_EDITION
name: OCIS_EDITION;FRONTEND_EDITION
defaultValue: Community
type: string
description: Edition of oCIS. Used for branding purposes.
@@ -8260,48 +8260,27 @@ OCIS_EMAIL_TEMPLATE_PATH:
removalVersion: ""
deprecationInfo: ""
OCIS_ENABLE_OCM:
name: OCIS_ENABLE_OCM;GRAPH_INCLUDE_OCM_SHAREES
name: OCIS_ENABLE_OCM
defaultValue: "false"
type: bool
description: Include OCM sharees when listing users.
description: Include OCM sharees when listing sharees.
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_ENABLE_PUBLIC_SHARING:
name: OCIS_ENABLE_PUBLIC_SHARING
defaultValue: "true"
type: bool
description: Enables public link sharing. When disabled, creating new public links
is rejected. Direct sharing with users and groups is not affected.
introductionVersion: '%%NEXT_PRODUCTION_VERSION%%'
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_ENABLE_USER_SHARING:
name: OCIS_ENABLE_USER_SHARING
defaultValue: "true"
type: bool
description: Enables direct sharing with users and groups. When disabled, creating
new user, group or federated shares via the drive item invite endpoints is rejected.
Public link sharing and space membership are not affected.
introductionVersion: '%%NEXT_PRODUCTION_VERSION%%'
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_ENABLE_VAULT_MODE:
name: OCIS_ENABLE_VAULT_MODE;GATEWAY_ENABLE_VAULT_MODE
name: OCIS_ENABLE_VAULT_MODE;FRONTEND_ENABLE_VAULT_MODE
defaultValue: "false"
type: bool
description: Set this to true to enable the default rule for vault storage provider
configuration. Only applicable if the storage-users-vault service, a specially
configured storage-users service, is configured.
description: Enable vault mode. When enabled, the capabilities endpoint will report
vault as enabled and the capabilities?vault=true endpoint will return capabilities
with public sharing and federation disabled.
introductionVersion: 8.1.0
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_EVENTS_AUTH_PASSWORD:
name: OCIS_EVENTS_AUTH_PASSWORD
name: OCIS_EVENTS_AUTH_PASSWORD;SSE_EVENTS_AUTH_PASSWORD
defaultValue: ""
type: string
description: The password to authenticate with the events broker. The events broker
@@ -8311,7 +8290,7 @@ OCIS_EVENTS_AUTH_PASSWORD:
removalVersion: ""
deprecationInfo: ""
OCIS_EVENTS_AUTH_USERNAME:
name: OCIS_EVENTS_AUTH_USERNAME
name: OCIS_EVENTS_AUTH_USERNAME;SSE_EVENTS_AUTH_USERNAME
defaultValue: ""
type: string
description: The username to authenticate with the events broker. The events broker
@@ -8321,7 +8300,7 @@ OCIS_EVENTS_AUTH_USERNAME:
removalVersion: ""
deprecationInfo: ""
OCIS_EVENTS_CLUSTER:
name: OCIS_EVENTS_CLUSTER
name: OCIS_EVENTS_CLUSTER;SSE_EVENTS_CLUSTER
defaultValue: ocis-cluster
type: string
description: The clusterID of the event system. The event system is the message
@@ -8332,7 +8311,7 @@ OCIS_EVENTS_CLUSTER:
removalVersion: ""
deprecationInfo: ""
OCIS_EVENTS_ENABLE_TLS:
name: OCIS_EVENTS_ENABLE_TLS
name: OCIS_EVENTS_ENABLE_TLS;SSE_EVENTS_ENABLE_TLS
defaultValue: "false"
type: bool
description: Enable TLS for the connection to the events broker. The events broker
@@ -8342,7 +8321,7 @@ OCIS_EVENTS_ENABLE_TLS:
removalVersion: ""
deprecationInfo: ""
OCIS_EVENTS_ENDPOINT:
name: OCIS_EVENTS_ENDPOINT
name: OCIS_EVENTS_ENDPOINT;SSE_EVENTS_ENDPOINT
defaultValue: 127.0.0.1:9233
type: string
description: The address of the event system. The event system is the message queuing
@@ -8352,21 +8331,21 @@ OCIS_EVENTS_ENDPOINT:
removalVersion: ""
deprecationInfo: ""
OCIS_EVENTS_TLS_ROOT_CA_CERTIFICATE:
name: OCIS_EVENTS_TLS_ROOT_CA_CERTIFICATE
name: OCIS_EVENTS_TLS_ROOT_CA_CERTIFICATE;SSE_EVENTS_TLS_ROOT_CA_CERTIFICATE
defaultValue: ""
type: string
description: The root CA certificate used to validate the server's TLS certificate.
If provided NOTIFICATIONS_EVENTS_TLS_INSECURE will be seen as false.
If provided SSE_EVENTS_TLS_INSECURE will be seen as false.
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_GATEWAY_GRPC_ADDR:
name: OCIS_GATEWAY_GRPC_ADDR;GATEWAY_GRPC_ADDR
name: OCIS_GATEWAY_GRPC_ADDR;STORAGE_USERS_GATEWAY_GRPC_ADDR
defaultValue: 127.0.0.1:9142
type: string
description: The bind address of the GRPC service.
introductionVersion: pre5.0
description: The bind address of the gateway GRPC address.
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
@@ -8434,7 +8413,7 @@ OCIS_HTTP_TLS_KEY:
removalVersion: ""
deprecationInfo: ""
OCIS_INSECURE:
name: OCIS_INSECURE
name: OCIS_INSECURE;SSE_EVENTS_TLS_INSECURE
defaultValue: "false"
type: bool
description: Whether to verify the server TLS certificates.
@@ -8754,7 +8733,7 @@ OCIS_LDAP_PRECISE_SEARCH_ATTRIBUTE:
removalVersion: ""
deprecationInfo: ""
OCIS_LDAP_SERVER_WRITE_ENABLED:
name: OCIS_LDAP_SERVER_WRITE_ENABLED;GRAPH_LDAP_SERVER_WRITE_ENABLED
name: OCIS_LDAP_SERVER_WRITE_ENABLED;FRONTEND_LDAP_SERVER_WRITE_ENABLED
defaultValue: "true"
type: bool
description: Allow creating, modifying and deleting LDAP users via the GRAPH API.
@@ -8851,7 +8830,7 @@ OCIS_LDAP_USER_SCHEMA_DISPLAYNAME:
introductionVersion: pre5.0
deprecationVersion: ""
removalVersion: ""
deprecationInfo: 'LDAP_USER_SCHEMA_DISPLAY_NAME changing name for consistency | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | '
deprecationInfo: 'LDAP_USER_SCHEMA_DISPLAY_NAME changing name for consistency | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | '
OCIS_LDAP_USER_SCHEMA_EXTERNAL_ID:
name: OCIS_LDAP_USER_SCHEMA_EXTERNAL_ID;GRAPH_LDAP_EXTERNAL_ID_ATTRIBUTE
defaultValue: owncloudExternalID
@@ -8960,23 +8939,23 @@ OCIS_LOG_PRETTY:
removalVersion: ""
deprecationInfo: ""
OCIS_MACHINE_AUTH_API_KEY:
name: OCIS_MACHINE_AUTH_API_KEY;AUTH_MACHINE_API_KEY
name: OCIS_MACHINE_AUTH_API_KEY;FRONTEND_MACHINE_AUTH_API_KEY
defaultValue: ""
type: string
description: Machine auth API key used to validate internal requests necessary for
the access to resources from other services.
description: The machine auth API key used to validate internal requests necessary
to access resources from other services.
introductionVersion: pre5.0
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_MAX_CONCURRENCY:
name: OCIS_MAX_CONCURRENCY;STORAGE_USERS_S3NG_MAX_CONCURRENCY
defaultValue: "5"
name: OCIS_MAX_CONCURRENCY;FRONTEND_MAX_CONCURRENCY
defaultValue: "1"
type: int
description: Maximum number of concurrent go-routines. Higher values can potentially
get work done faster but will also cause more load on the system. Values of 0
or below will be ignored and the default value of 100 will be used.
introductionVersion: pre5.0
or below will be ignored and the default value will be used.
introductionVersion: 7.0.0
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
@@ -9007,8 +8986,8 @@ OCIS_MFA_ENABLED:
name: OCIS_MFA_ENABLED
defaultValue: "false"
type: bool
description: Enable MFA enforcement. If enabled users need to complete MFA before
they can access specific paths
description: Set to true to enable multi factor authentication. See the documentation
for more details.
introductionVersion: 7.3.0
deprecationVersion: ""
removalVersion: ""
@@ -9018,8 +8997,9 @@ OCIS_MFA_SESSION_DURATION:
defaultValue: "3600"
type: int
description: The duration in seconds that a multi-factor authentication session
is valid for non-OIDC requests. Defaults to 3600 (1 hour).
introductionVersion: 7.3.0
is valid. After this time the user will be prompted to re-authenticate. Defaults
to 3600 (1 hour).
introductionVersion: 8.1.0
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
@@ -9110,7 +9090,7 @@ OCIS_OIDC_ISSUER:
removalVersion: ""
deprecationInfo: ""
OCIS_PASSWORD_POLICY_BANNED_PASSWORDS_LIST:
name: OCIS_PASSWORD_POLICY_BANNED_PASSWORDS_LIST;SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST
name: OCIS_PASSWORD_POLICY_BANNED_PASSWORDS_LIST;FRONTEND_PASSWORD_POLICY_BANNED_PASSWORDS_LIST
defaultValue: ""
type: string
description: Path to the 'banned passwords list' file. This only impacts public
@@ -9120,7 +9100,7 @@ OCIS_PASSWORD_POLICY_BANNED_PASSWORDS_LIST:
removalVersion: ""
deprecationInfo: ""
OCIS_PASSWORD_POLICY_DISABLED:
name: OCIS_PASSWORD_POLICY_DISABLED;SHARING_PASSWORD_POLICY_DISABLED
name: OCIS_PASSWORD_POLICY_DISABLED;FRONTEND_PASSWORD_POLICY_DISABLED
defaultValue: "false"
type: bool
description: Disable the password policy. Defaults to false if not set.
@@ -9129,7 +9109,7 @@ OCIS_PASSWORD_POLICY_DISABLED:
removalVersion: ""
deprecationInfo: ""
OCIS_PASSWORD_POLICY_MIN_CHARACTERS:
name: OCIS_PASSWORD_POLICY_MIN_CHARACTERS;SHARING_PASSWORD_POLICY_MIN_CHARACTERS
name: OCIS_PASSWORD_POLICY_MIN_CHARACTERS;FRONTEND_PASSWORD_POLICY_MIN_CHARACTERS
defaultValue: "8"
type: int
description: Define the minimum password length. Defaults to 8 if not set.
@@ -9138,7 +9118,7 @@ OCIS_PASSWORD_POLICY_MIN_CHARACTERS:
removalVersion: ""
deprecationInfo: ""
OCIS_PASSWORD_POLICY_MIN_DIGITS:
name: OCIS_PASSWORD_POLICY_MIN_DIGITS;SHARING_PASSWORD_POLICY_MIN_DIGITS
name: OCIS_PASSWORD_POLICY_MIN_DIGITS;FRONTEND_PASSWORD_POLICY_MIN_DIGITS
defaultValue: "1"
type: int
description: Define the minimum number of digits. Defaults to 1 if not set.
@@ -9147,7 +9127,7 @@ OCIS_PASSWORD_POLICY_MIN_DIGITS:
removalVersion: ""
deprecationInfo: ""
OCIS_PASSWORD_POLICY_MIN_LOWERCASE_CHARACTERS:
name: OCIS_PASSWORD_POLICY_MIN_LOWERCASE_CHARACTERS;SHARING_PASSWORD_POLICY_MIN_LOWERCASE_CHARACTERS
name: OCIS_PASSWORD_POLICY_MIN_LOWERCASE_CHARACTERS;FRONTEND_PASSWORD_POLICY_MIN_LOWERCASE_CHARACTERS
defaultValue: "1"
type: int
description: Define the minimum number of uppercase letters. Defaults to 1 if not
@@ -9157,7 +9137,7 @@ OCIS_PASSWORD_POLICY_MIN_LOWERCASE_CHARACTERS:
removalVersion: ""
deprecationInfo: ""
OCIS_PASSWORD_POLICY_MIN_SPECIAL_CHARACTERS:
name: OCIS_PASSWORD_POLICY_MIN_SPECIAL_CHARACTERS;SHARING_PASSWORD_POLICY_MIN_SPECIAL_CHARACTERS
name: OCIS_PASSWORD_POLICY_MIN_SPECIAL_CHARACTERS;FRONTEND_PASSWORD_POLICY_MIN_SPECIAL_CHARACTERS
defaultValue: "1"
type: int
description: Define the minimum number of characters from the special characters
@@ -9167,7 +9147,7 @@ OCIS_PASSWORD_POLICY_MIN_SPECIAL_CHARACTERS:
removalVersion: ""
deprecationInfo: ""
OCIS_PASSWORD_POLICY_MIN_UPPERCASE_CHARACTERS:
name: OCIS_PASSWORD_POLICY_MIN_UPPERCASE_CHARACTERS;SHARING_PASSWORD_POLICY_MIN_UPPERCASE_CHARACTERS
name: OCIS_PASSWORD_POLICY_MIN_UPPERCASE_CHARACTERS;FRONTEND_PASSWORD_POLICY_MIN_UPPERCASE_CHARACTERS
defaultValue: "1"
type: int
description: Define the minimum number of lowercase letters. Defaults to 1 if not
@@ -9177,7 +9157,7 @@ OCIS_PASSWORD_POLICY_MIN_UPPERCASE_CHARACTERS:
removalVersion: ""
deprecationInfo: ""
OCIS_PERSISTENT_STORE:
name: OCIS_PERSISTENT_STORE;ACTIVITYLOG_STORE
name: OCIS_PERSISTENT_STORE;EVENTHISTORY_STORE
defaultValue: nats-js-kv
type: string
description: 'The type of the store. Supported values are: ''memory'', ''nats-js-kv'',
@@ -9187,7 +9167,7 @@ OCIS_PERSISTENT_STORE:
removalVersion: ""
deprecationInfo: ""
OCIS_PERSISTENT_STORE_AUTH_PASSWORD:
name: OCIS_PERSISTENT_STORE_AUTH_PASSWORD;ACTIVITYLOG_STORE_AUTH_PASSWORD
name: OCIS_PERSISTENT_STORE_AUTH_PASSWORD;EVENTHISTORY_STORE_AUTH_PASSWORD
defaultValue: ""
type: string
description: The password to authenticate with the store. Only applies when store
@@ -9197,7 +9177,7 @@ OCIS_PERSISTENT_STORE_AUTH_PASSWORD:
removalVersion: ""
deprecationInfo: ""
OCIS_PERSISTENT_STORE_AUTH_USERNAME:
name: OCIS_PERSISTENT_STORE_AUTH_USERNAME;ACTIVITYLOG_STORE_AUTH_USERNAME
name: OCIS_PERSISTENT_STORE_AUTH_USERNAME;EVENTHISTORY_STORE_AUTH_USERNAME
defaultValue: ""
type: string
description: The username to authenticate with the store. Only applies when store
@@ -9207,7 +9187,7 @@ OCIS_PERSISTENT_STORE_AUTH_USERNAME:
removalVersion: ""
deprecationInfo: ""
OCIS_PERSISTENT_STORE_NODES:
name: OCIS_PERSISTENT_STORE_NODES;ACTIVITYLOG_STORE_NODES
name: OCIS_PERSISTENT_STORE_NODES;EVENTHISTORY_STORE_NODES
defaultValue: '[127.0.0.1:9233]'
type: '[]string'
description: A list of nodes to access the configured store. This has no effect
@@ -9219,11 +9199,11 @@ OCIS_PERSISTENT_STORE_NODES:
removalVersion: ""
deprecationInfo: ""
OCIS_PERSISTENT_STORE_TTL:
name: OCIS_PERSISTENT_STORE_TTL;ACTIVITYLOG_STORE_TTL
defaultValue: 0s
name: OCIS_PERSISTENT_STORE_TTL;EVENTHISTORY_STORE_TTL
defaultValue: 336h0m0s
type: Duration
description: Time to live for events in the store. See the Environment Variable
Types description for more details.
description: Time to live for events in the store. Defaults to '336h' (2 weeks).
See the Environment Variable Types description for more details.
introductionVersion: pre5.0
deprecationVersion: ""
removalVersion: ""
@@ -9269,7 +9249,7 @@ OCIS_REVA_GATEWAY_TLS_MODE:
removalVersion: ""
deprecationInfo: ""
OCIS_SERVICE_ACCOUNT_ID:
name: OCIS_SERVICE_ACCOUNT_ID;ACTIVITYLOG_SERVICE_ACCOUNT_ID
name: OCIS_SERVICE_ACCOUNT_ID;FRONTEND_SERVICE_ACCOUNT_ID
defaultValue: ""
type: string
description: The ID of the service account the service should use. See the 'auth-service'
@@ -9279,7 +9259,7 @@ OCIS_SERVICE_ACCOUNT_ID:
removalVersion: ""
deprecationInfo: ""
OCIS_SERVICE_ACCOUNT_SECRET:
name: OCIS_SERVICE_ACCOUNT_SECRET;ACTIVITYLOG_SERVICE_ACCOUNT_SECRET
name: OCIS_SERVICE_ACCOUNT_SECRET;FRONTEND_SERVICE_ACCOUNT_SECRET
defaultValue: ""
type: string
description: The service account secret.
@@ -9288,7 +9268,7 @@ OCIS_SERVICE_ACCOUNT_SECRET:
removalVersion: ""
deprecationInfo: ""
OCIS_SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD:
name: OCIS_SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD;SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD
name: OCIS_SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD
defaultValue: "true"
type: bool
description: Set this to true if you want to enforce passwords on all public shares.
@@ -9297,22 +9277,21 @@ OCIS_SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD:
removalVersion: ""
deprecationInfo: ""
OCIS_SHARING_PUBLIC_WRITEABLE_SHARE_MUST_HAVE_PASSWORD:
name: OCIS_SHARING_PUBLIC_WRITEABLE_SHARE_MUST_HAVE_PASSWORD;SHARING_PUBLIC_WRITEABLE_SHARE_MUST_HAVE_PASSWORD
name: OCIS_SHARING_PUBLIC_WRITEABLE_SHARE_MUST_HAVE_PASSWORD
defaultValue: "false"
type: bool
description: Set this to true if you want to enforce passwords on Uploader, Editor
or Contributor shares.
description: Set this to true if you want to enforce passwords for writable shares.
Only effective if the setting for 'passwords on all public shares' is set to false.
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_SPACES_MAX_QUOTA:
name: OCIS_SPACES_MAX_QUOTA;STORAGE_USERS_OCIS_MAX_QUOTA
name: OCIS_SPACES_MAX_QUOTA;FRONTEND_MAX_QUOTA
defaultValue: "0"
type: uint64
description: Set a global max quota for spaces in bytes. A value of 0 equals unlimited.
If not using the global OCIS_SPACES_MAX_QUOTA, you must define the FRONTEND_MAX_QUOTA
in the frontend service.
description: Set the global max quota value in bytes. A value of 0 equals unlimited.
The value is provided via capabilities.
introductionVersion: pre5.0
deprecationVersion: ""
removalVersion: ""
@@ -9339,7 +9318,7 @@ OCIS_SYSTEM_USER_ID:
removalVersion: ""
deprecationInfo: ""
OCIS_SYSTEM_USER_IDP:
name: OCIS_SYSTEM_USER_IDP;SETTINGS_SYSTEM_USER_IDP
name: OCIS_SYSTEM_USER_IDP;SHARING_PUBLIC_CS3_SYSTEM_USER_IDP
defaultValue: internal
type: string
description: IDP of the oCIS STORAGE-SYSTEM system user.
@@ -9389,19 +9368,19 @@ OCIS_TRANSFER_SECRET:
name: OCIS_TRANSFER_SECRET
defaultValue: ""
type: string
description: The storage transfer secret.
description: Transfer secret for signing file up- and download requests.
introductionVersion: pre5.0
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_TRANSLATION_PATH:
name: OCIS_TRANSLATION_PATH;ACTIVITYLOG_TRANSLATION_PATH
name: OCIS_TRANSLATION_PATH;USERLOG_TRANSLATION_PATH
defaultValue: ""
type: string
description: (optional) Set this to a path with custom translations to overwrite
the builtin translations. Note that file and folder naming rules apply, see the
documentation for more details.
introductionVersion: 7.0.0
introductionVersion: pre5.0
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
@@ -9416,21 +9395,20 @@ OCIS_URL:
removalVersion: ""
deprecationInfo: ""
OCIS_USER_SEARCH_DISPLAYED_ATTRIBUTES:
name: OCIS_USER_SEARCH_DISPLAYED_ATTRIBUTES
name: OCIS_USER_SEARCH_DISPLAYED_ATTRIBUTES;FRONTEND_USER_SEARCH_DISPLAYED_ATTRIBUTES
defaultValue: '[]'
type: '[]string'
description: The attributes to display in the user search results.
description: A list of user attributes to display in the user search results.
introductionVersion: 7.3.0
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
OCIS_WOPI_DISABLE_CHAT:
name: COLLABORATION_WOPI_DISABLE_CHAT;OCIS_WOPI_DISABLE_CHAT
name: APP_PROVIDER_WOPI_DISABLE_CHAT;OCIS_WOPI_DISABLE_CHAT
defaultValue: "false"
type: bool
description: Disable chat in the office web frontend. This feature applies to OnlyOffice
and Microsoft.
introductionVersion: 7.0.0
description: Disable the chat functionality of the office app.
introductionVersion: pre5.0
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
@@ -11008,28 +10986,13 @@ PROXY_MACHINE_AUTH_API_KEY:
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
PROXY_OIDC_ACCESS_TOKEN_VERIFY_AUD:
name: PROXY_OIDC_ACCESS_TOKEN_VERIFY_AUD
defaultValue: '[]'
type: '[]string'
description: A list of accepted audiences for OIDC access tokens, usually the OIDC
client IDs used to access ownCloud (for example the web and desktop client IDs).
When set, a JWT access token is only accepted if one of these values is present
in its 'aud' claim or matches its 'azp' claim. This prevents tokens issued for
other applications of a shared IDP from being accepted. When set via the environment
variable, use a comma-separated list. Has no effect when 'access_token_verify_method'
is 'none'. Leave empty to disable the check (default).
introductionVersion: 8.2.0
deprecationVersion: ""
removalVersion: ""
deprecationInfo: ""
PROXY_OIDC_ACCESS_TOKEN_VERIFY_METHOD:
name: PROXY_OIDC_ACCESS_TOKEN_VERIFY_METHOD
defaultValue: jwt
type: string
description: Sets how OIDC access tokens should be verified. Possible values are
'none' and 'jwt'. When using 'none', no special validation apart from using it
for accessing the IDP's userinfo endpoint will be done. When using 'jwt', it tries
for accessing the IPD's userinfo endpoint will be done. When using 'jwt', it tries
to parse the access token as a jwt token and verifies the signature using the
keys published on the IDP's 'jwks_uri'.
introductionVersion: pre5.0
@@ -11203,8 +11166,9 @@ PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE:
name: OCIS_CACHE_STORE;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE
defaultValue: nats-js-kv
type: string
description: 'The type of the signing key store. Supported values are: ''redis-sentinel''
and ''nats-js-kv''. See the text description for details.'
description: 'The type of the signing key store. Supported values are: ''redis-sentinel'',
''nats-js-kv'' and ''ocisstoreservice'' (deprecated). See the text description
for details.'
introductionVersion: "5.0"
deprecationVersion: ""
removalVersion: ""
@@ -1,7 +1,7 @@
// # Added Variables between oCIS 8.1.0 and oCIS 8.2.0
// commenting the headline to make it better includable
// table created per 2026.07.15
// table created per 2026.07.09
// the table should be recreated/updated on source () changes
[width="100%",cols="~,~,~,~",options="header"]
@@ -23,9 +23,5 @@
| The maximum duration to wait for the storage to respond while resolving a single received share's resource when listing 'sharedWithMe'. Bounding each resource lookup individually prevents one slow or unreachable resource from consuming the request deadline shared by all the other shares. A share whose resource cannot be statted within this time is still listed as a degraded item instead of being dropped. Defaults to '10s'. See the Environment Variable Types description for more details.
| 10s
| xref:{s-path}/proxy.adoc[Proxy]
| PROXY_OIDC_ACCESS_TOKEN_VERIFY_AUD
| A list of accepted audiences for OIDC access tokens, usually the OIDC client IDs used to access ownCloud (for example the web and desktop client IDs). When set, a JWT access token is only accepted if one of these values is present in its 'aud' claim or matches its 'azp' claim. This prevents tokens issued for other applications of a shared IDP from being accepted. When set via the environment variable, use a comma-separated list. Has no effect when 'PROXY_OIDC_ACCESS_TOKEN_VERIFY_METHOD' is set to 'none'. Leave empty to disable the check (default).
|
|===
+1 -1
View File
@@ -213,7 +213,7 @@ func (c *ConcreteClient) getKeyCloakID(u *libregraph.User) (string, error) {
func convertUserActions(userActions []UserAction) *[]string {
stringActions := make([]string, len(userActions))
for i, a := range userActions {
stringActions[i] = string(a)
stringActions[i] = userActionsToString[a]
}
return &stringActions
}
+11 -26
View File
@@ -7,38 +7,23 @@ import (
libregraph "github.com/owncloud/libre-graph-api-go"
)
// UserAction is a Keycloak required-action provider ID. It is a free-form
// string so operators can configure any action Keycloak supports; it is passed
// to Keycloak verbatim. The constants below are the common built-ins, provided
// for convenience only - the list does not need to be exhaustive or kept in
// sync with Keycloak.
type UserAction string
// UserAction defines a type for user actions
type UserAction int8
// An incomplete list of UserActions
const (
// UserActionUpdatePassword sets it that the user needs to change their password.
UserActionUpdatePassword UserAction = "UPDATE_PASSWORD"
UserActionUpdatePassword UserAction = iota
// UserActionVerifyEmail sets it that the user needs to verify their email address.
UserActionVerifyEmail UserAction = "VERIFY_EMAIL"
// UserActionUpdateProfile sets it that the user needs to update their profile.
UserActionUpdateProfile UserAction = "UPDATE_PROFILE"
// UserActionConfigureTOTP sets it that the user needs to configure a one-time password.
UserActionConfigureTOTP UserAction = "CONFIGURE_TOTP"
// UserActionTermsAndConditions sets it that the user needs to accept the terms and conditions.
UserActionTermsAndConditions UserAction = "TERMS_AND_CONDITIONS"
// UserActionVerifyProfile sets it that the user needs to verify their profile.
UserActionVerifyProfile UserAction = "VERIFY_PROFILE"
// UserActionDeleteAccount sets it that the user is allowed to delete their account.
UserActionDeleteAccount UserAction = "delete_account"
// UserActionUpdateLocale sets it that the user needs to update their locale.
UserActionUpdateLocale UserAction = "update_user_locale"
// UserActionWebauthnRegister sets it that the user needs to register a WebAuthn authenticator.
UserActionWebauthnRegister UserAction = "webauthn-register"
// UserActionWebauthnRegisterPasswordless sets it that the user needs to register a passwordless WebAuthn authenticator.
UserActionWebauthnRegisterPasswordless UserAction = "webauthn-register-passwordless"
// UserActionConfigureRecoveryAuthnCodes sets it that the user needs to configure recovery authentication codes.
UserActionConfigureRecoveryAuthnCodes UserAction = "CONFIGURE_RECOVERY_AUTHN_CODES"
UserActionVerifyEmail
)
// A lookup table to translate user actions to their string equivalents
var userActionsToString = map[UserAction]string{
UserActionUpdatePassword: "UPDATE_PASSWORD",
UserActionVerifyEmail: "VERIFY_EMAIL",
}
// PIIReport is a structure of all the PersonalIdentifiableInformation contained in keycloak.
type PIIReport struct {
UserData *libregraph.User
-21
View File
@@ -1,21 +0,0 @@
package keycloak_test
import (
"testing"
"github.com/owncloud/ocis/v2/ocis-pkg/keycloak"
"github.com/stretchr/testify/assert"
)
func TestUserActionStringValues(t *testing.T) {
// UserAction is a free-form string passed to Keycloak verbatim; the
// convenience constants must carry the exact Keycloak required-action
// provider IDs.
assert.Equal(t, "UPDATE_PASSWORD", string(keycloak.UserActionUpdatePassword))
assert.Equal(t, "VERIFY_EMAIL", string(keycloak.UserActionVerifyEmail))
assert.Equal(t, "delete_account", string(keycloak.UserActionDeleteAccount))
assert.Equal(t, "webauthn-register", string(keycloak.UserActionWebauthnRegister))
// Arbitrary, non-builtin actions are valid - there is no allowlist.
assert.Equal(t, "CUSTOM_ACTION", string(keycloak.UserAction("CUSTOM_ACTION")))
}
+17 -53
View File
@@ -8,7 +8,6 @@ import (
"io"
"mime"
"net/http"
"slices"
"strconv"
"strings"
"sync"
@@ -54,14 +53,13 @@ type oidcClient struct {
// Logger to use for logging, must be set
Logger log.Logger
issuer string
provider *ProviderMetadata
providerLock *sync.Mutex
skipIssuerValidation bool
accessTokenVerifyMethod string
accessTokenVerifyAudiences []string
remoteKeySet KeySet
algorithms []string
issuer string
provider *ProviderMetadata
providerLock *sync.Mutex
skipIssuerValidation bool
accessTokenVerifyMethod string
remoteKeySet KeySet
algorithms []string
JWKSOptions config.JWKS
JWKS *keyfunc.JWKS
@@ -90,17 +88,16 @@ func NewOIDCClient(opts ...Option) OIDCClient {
options := newOptions(opts...)
return &oidcClient{
Logger: options.Logger,
issuer: options.OIDCIssuer,
httpClient: options.HTTPClient,
accessTokenVerifyMethod: options.AccessTokenVerifyMethod,
accessTokenVerifyAudiences: options.AccessTokenVerifyAudiences,
JWKSOptions: options.JWKSOptions, // TODO I don't like that we pass down config options ...
JWKS: options.JWKS,
providerLock: &sync.Mutex{},
jwksLock: &sync.Mutex{},
remoteKeySet: options.KeySet,
provider: options.ProviderMetadata,
Logger: options.Logger,
issuer: options.OIDCIssuer,
httpClient: options.HTTPClient,
accessTokenVerifyMethod: options.AccessTokenVerifyMethod,
JWKSOptions: options.JWKSOptions, // TODO I don't like that we pass down config options ...
JWKS: options.JWKS,
providerLock: &sync.Mutex{},
jwksLock: &sync.Mutex{},
remoteKeySet: options.KeySet,
provider: options.ProviderMetadata,
}
}
@@ -317,42 +314,9 @@ func (c *oidcClient) verifyAccessTokenJWT(token string) (RegClaimsWithSID, jwt.M
return claims, mapClaims, err
}
// Verify the token was issued for this instance. Keycloak puts a generic
// value (e.g. "account") in "aud" and the real client id in "azp", so we
// accept the token when the allowlist matches either claim.
if err := c.verifyAudience(claims.Audience, azpFromClaims(mapClaims)); err != nil {
c.Logger.Info().Err(err).Msg("Access token rejected: audience not allowed.")
return claims, mapClaims, err
}
return claims, mapClaims, nil
}
// verifyAudience checks that the token's "aud" or "azp" claim matches the
// configured allowlist. An empty allowlist disables the check.
func (c *oidcClient) verifyAudience(audiences jwt.ClaimStrings, azp string) error {
if len(c.accessTokenVerifyAudiences) == 0 {
return nil
}
for _, allowed := range c.accessTokenVerifyAudiences {
allowed = strings.TrimSpace(allowed)
if allowed == "" {
continue
}
if allowed == azp || slices.Contains(audiences, allowed) {
return nil
}
}
return errors.New("oidc: access token audience is not allowed")
}
func azpFromClaims(claims jwt.MapClaims) string {
if azp, ok := claims["azp"].(string); ok {
return azp
}
return ""
}
func (c *oidcClient) VerifyLogoutToken(ctx context.Context, rawToken string) (*LogoutToken, error) {
var claims LogoutToken
if err := c.lookupWellKnownOpenidConfiguration(ctx); err != nil {
-115
View File
@@ -9,7 +9,6 @@ import (
"github.com/MicahParks/keyfunc/v2"
"github.com/golang-jwt/jwt/v5"
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
"github.com/owncloud/ocis/v2/services/proxy/pkg/config"
)
type signingKey struct {
@@ -187,120 +186,6 @@ func (l logoutVerificationTest) run(t *testing.T) {
}
}
func TestVerifyAccessTokenAudience(t *testing.T) {
const issuer = "https://foo"
key := newRSAKey(t)
tests := []struct {
name string
// allowlist configured on the client (empty disables the check)
verifyAud []string
// claims of the presented access token
aud interface{}
azp string
wantErr bool
}{
{
name: "check disabled accepts foreign audience",
verifyAud: nil,
aud: "account",
azp: "evil-app",
wantErr: false,
},
{
name: "rejects foreign azp with generic aud (keycloak style)",
verifyAud: []string{"web"},
aud: "account",
azp: "evil-app",
wantErr: true,
},
{
name: "accepts matching azp with generic aud (keycloak style)",
verifyAud: []string{"web"},
aud: "account",
azp: "web",
wantErr: false,
},
{
name: "accepts matching aud (builtin idp style)",
verifyAud: []string{"web"},
aud: "web",
azp: "",
wantErr: false,
},
{
name: "accepts when one of multiple audiences matches",
verifyAud: []string{"desktop", "web"},
aud: []string{"account", "web"},
azp: "evil-app",
wantErr: false,
},
{
name: "rejects when neither aud nor azp match",
verifyAud: []string{"web", "desktop"},
aud: []string{"account", "other"},
azp: "evil-app",
wantErr: true,
},
{
name: "rejects when azp is empty and aud does not match",
verifyAud: []string{"web", "desktop"},
aud: []string{"account", "other"},
azp: "",
wantErr: true,
},
{
name: "tolerates whitespace around configured audience",
verifyAud: []string{" web ", "desktop"},
aud: "account",
azp: "web",
wantErr: false,
},
{
name: "blank configured audience does not match missing azp",
verifyAud: []string{" "},
aud: "account",
azp: "",
wantErr: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
claims := jwt.MapClaims{
"iss": issuer,
"sub": "einstein",
"aud": tc.aud,
}
if tc.azp != "" {
claims["azp"] = tc.azp
}
tok := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
tok.Header["kid"] = "1"
signed, err := tok.SignedString(key.priv)
if err != nil {
t.Fatal(err)
}
client := oidc.NewOIDCClient(
oidc.WithOidcIssuer(issuer),
oidc.WithJWKS(key.jwks),
oidc.WithProviderMetadata(&oidc.ProviderMetadata{}),
oidc.WithAccessTokenVerifyMethod(config.AccessTokenVerificationJWT),
oidc.WithAccessTokenVerifyAudiences(tc.verifyAud),
)
_, _, err = client.VerifyAccessToken(context.Background(), signed)
if tc.wantErr && err == nil {
t.Errorf("expected error, got nil")
}
if !tc.wantErr && err != nil {
t.Errorf("expected no error, got %v", err)
}
})
}
}
func newRSAKey(t testing.TB) *signingKey {
priv, err := rsa.GenerateKey(rand.Reader, 1028)
if err != nil {
-13
View File
@@ -35,11 +35,6 @@ type Options struct {
// AccessTokenVerifyMethod to use when verifying access tokens
// TODO pass a function or interface to verify? an AccessTokenVerifier?
AccessTokenVerifyMethod string
// AccessTokenVerifyAudiences is the list of accepted audiences for JWT
// access tokens. When non-empty, a token is only accepted if one of these
// values is present in its "aud" claim or matches its "azp" claim. An empty
// list disables the check.
AccessTokenVerifyAudiences []string
// Config to use
Config *goidc.Config
@@ -79,14 +74,6 @@ func WithAccessTokenVerifyMethod(val string) Option {
}
}
// WithAccessTokenVerifyAudiences provides a function to set the
// accessTokenVerifyAudiences option.
func WithAccessTokenVerifyAudiences(val []string) Option {
return func(o *Options) {
o.AccessTokenVerifyAudiences = val
}
}
// WithHTTPClient provides a function to set the httpClient option.
func WithHTTPClient(val *http.Client) Option {
return func(o *Options) {
+27 -27
View File
@@ -435,20 +435,20 @@ func (g BaseGraphService) cs3UserSharesToDriveItems(ctx context.Context, shares
return nil
})
}
// Wait for all workers to finish before collecting the results. The workers
// read from driveItems, so writing to it below must not overlap with them.
// The results channel is buffered with len(shares), which is at least the
// number of items the workers can send, so they never block on the handover.
if err := errg.Wait(); err != nil {
return nil, err
}
close(results)
// Wait for things to settle down, then close results chan
go func() {
_ = errg.Wait() // error is checked later
close(results)
}()
for item := range results {
driveItems[item.GetId()] = *item
}
if err := errg.Wait(); err != nil {
return nil, err
}
return driveItems, nil
}
@@ -535,20 +535,20 @@ func (g BaseGraphService) cs3OCMSharesToDriveItems(ctx context.Context, shares [
return nil
})
}
// Wait for all workers to finish before collecting the results. The workers
// read from driveItems, so writing to it below must not overlap with them.
// The results channel is buffered with len(shares), which is at least the
// number of items the workers can send, so they never block on the handover.
if err := errg.Wait(); err != nil {
return nil, err
}
close(results)
// Wait for things to settle down, then close results chan
go func() {
_ = errg.Wait() // error is checked later
close(results)
}()
for item := range results {
driveItems[item.GetId()] = *item
}
if err := errg.Wait(); err != nil {
return nil, err
}
return driveItems, nil
}
@@ -797,20 +797,20 @@ func (g BaseGraphService) cs3PublicSharesToDriveItems(ctx context.Context, share
return nil
})
}
// Wait for all workers to finish before collecting the results. The workers
// read from driveItems, so writing to it below must not overlap with them.
// The results channel is buffered with len(shares), which is at least the
// number of items the workers can send, so they never block on the handover.
if err := errg.Wait(); err != nil {
return nil, err
}
close(results)
// Wait for things to settle down, then close results chan
go func() {
_ = errg.Wait() // error is checked later
close(results)
}()
for item := range results {
driveItems[item.GetId()] = *item
}
if err := errg.Wait(); err != nil {
return nil, err
}
return driveItems, nil
}
@@ -1,159 +0,0 @@
package svc
import (
"context"
"fmt"
"testing"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
storageprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
libregraph "github.com/owncloud/libre-graph-api-go"
"github.com/owncloud/ocis/v2/services/graph/pkg/config/defaults"
"github.com/owncloud/ocis/v2/services/graph/pkg/identity"
"github.com/owncloud/reva/v2/pkg/conversions"
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
)
// numRaceTestResources needs to be comfortably larger than the number of
// workers so that some workers are still reading from the driveItems map while
// the collecting loop has already started writing to it.
const numRaceTestResources = 200
// newRaceTestService builds a BaseGraphService with a mocked gateway that can
// stat any resource and resolve any user.
func newRaceTestService(t *testing.T, maxConcurrency int) BaseGraphService {
t.Helper()
selectorName := fmt.Sprintf("GatewaySelectorRace%d", maxConcurrency)
pool.RemoveSelector(selectorName + "com.owncloud.api.gateway")
gatewayClient := &cs3mocks.GatewayAPIClient{}
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(
func(_ context.Context, req *storageprovider.StatRequest, _ ...grpc.CallOption) *storageprovider.StatResponse {
return &storageprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: &storageprovider.ResourceInfo{
Id: req.GetRef().GetResourceId(),
Type: storageprovider.ResourceType_RESOURCE_TYPE_CONTAINER,
},
}
},
nil,
)
gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(
&userpb.GetUserResponse{
Status: status.NewOK(context.Background()),
User: &userpb.User{
Id: &userpb.UserId{Idp: "idp", OpaqueId: "user-id"},
DisplayName: "User Name",
},
},
nil,
)
gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(
&link.GetPublicShareResponse{Status: status.NewOK(context.Background())},
nil,
)
gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient](
selectorName,
"com.owncloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return gatewayClient
},
)
cfg := defaults.FullDefaultConfig()
cfg.Identity.LDAP.CACert = ""
cfg.TokenManager.JWTSecret = "loremipsum"
cfg.MaxConcurrency = maxConcurrency
logger := log.NewLogger()
return BaseGraphService{
logger: &logger,
gatewaySelector: gatewaySelector,
identityCache: identity.NewIdentityCache(identity.IdentityCacheWithGatewaySelector(gatewaySelector)),
config: cfg,
}
}
// raceTestShares returns one user share per resource, all distinct resources so
// that every share becomes its own unit of work.
func raceTestShares() []*collaboration.Share {
editorResourcePermissions := conversions.NewEditorRole().CS3ResourcePermissions()
shares := make([]*collaboration.Share, 0, numRaceTestResources)
for i := 0; i < numRaceTestResources; i++ {
shares = append(shares, &collaboration.Share{
Id: &collaboration.ShareId{OpaqueId: fmt.Sprintf("share-id-%d", i)},
ResourceId: &storageprovider.ResourceId{
StorageId: "storageid",
SpaceId: "spaceid",
OpaqueId: fmt.Sprintf("opaqueid-%d", i),
},
Grantee: &storageprovider.Grantee{
Type: storageprovider.GranteeType_GRANTEE_TYPE_USER,
Id: &storageprovider.Grantee_UserId{
UserId: &userpb.UserId{OpaqueId: "user-id"},
},
},
Permissions: &collaboration.SharePermissions{Permissions: editorResourcePermissions},
})
}
return shares
}
// TestCS3UserSharesToDriveItemsConcurrentMapAccess reproduces OCISDEV-1088: the
// errgroup workers read the driveItems map while the collecting loop writes to
// it, which makes the Go runtime abort the process with
// "fatal error: concurrent map read and map write".
//
// Run with -race to catch it deterministically.
func TestCS3UserSharesToDriveItemsConcurrentMapAccess(t *testing.T) {
// A non-empty map is required: the workers only read the map when looking
// for an already known drive item, and an empty map read is not enough for
// the race detector to flag a conflicting access pattern on every run.
driveItems := make(driveItemsByResourceID, numRaceTestResources)
for i := 0; i < numRaceTestResources; i++ {
driveItems[fmt.Sprintf("storageid$spaceid!seed-%d", i)] = libregraph.DriveItem{}
}
g := newRaceTestService(t, defaults.FullDefaultConfig().MaxConcurrency)
items, err := g.cs3UserSharesToDriveItems(context.Background(), raceTestShares(), driveItems)
require.NoError(t, err)
require.Len(t, items, numRaceTestResources+numRaceTestResources)
}
// TestCS3UserSharesToDriveItemsConcurrentMapAccessMaxConcurrencyOne covers the
// single worker path.
//
// This case exists because lowering OCIS_MAX_CONCURRENCY /
// GRAPH_MAX_CONCURRENCY to 1 looks like an obvious operational workaround for
// OCISDEV-1088, but it never was one: even with a single worker the map was
// still read concurrently with the collecting loop, because the results channel
// is buffered and the worker never blocks handing off an item. Before the fix
// this test failed under -race exactly like the one above.
func TestCS3UserSharesToDriveItemsConcurrentMapAccessMaxConcurrencyOne(t *testing.T) {
driveItems := make(driveItemsByResourceID, numRaceTestResources)
for i := 0; i < numRaceTestResources; i++ {
driveItems[fmt.Sprintf("storageid$spaceid!seed-%d", i)] = libregraph.DriveItem{}
}
g := newRaceTestService(t, 1)
items, err := g.cs3UserSharesToDriveItems(context.Background(), raceTestShares(), driveItems)
require.NoError(t, err)
require.Len(t, items, numRaceTestResources+numRaceTestResources)
}
@@ -14,16 +14,16 @@
<div class="oc-login-form" id="chooseaccount-root">
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
<p id="oc-chooseaccount-error" class="oc-error-message" role="alert" aria-live="assertive" hidden></p>
<p id="oc-chooseaccount-error" class="oc-error-message" hidden></p>
<div id="chooseaccount-body" hidden>
<p class="oc-light oc-consent-headline" id="chooseaccount-title">{{.HeadlineSub}}</p>
<ul class="oc-consent-scopes" id="account-list">
<li class="oc-chooseaccount-item" id="item-current" role="button" tabindex="0">
<span class="oc-chooseaccount-avatar" id="avatar-current" aria-hidden="true"></span>
<li class="oc-chooseaccount-item" id="item-current">
<span class="oc-chooseaccount-avatar" id="avatar-current"></span>
<span class="oc-light oc-chooseaccount-label" id="label-current"></span>
</li>
<li class="oc-chooseaccount-item" id="item-other" role="button" tabindex="0">
<span class="oc-chooseaccount-avatar" aria-hidden="true">?</span>
<li class="oc-chooseaccount-item" id="item-other">
<span class="oc-chooseaccount-avatar">?</span>
<span class="oc-light oc-chooseaccount-label">{{.UseAnotherLabel}}</span>
</li>
</ul>
@@ -77,15 +77,6 @@
catch (_) { return false; }
}
function onKeyActivate(el, handler) {
el.addEventListener("keydown", function(e) {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handler();
}
});
}
var helloReq = {
state: qs("state"),
flow: qs("flow") || "oidc",
@@ -115,7 +106,7 @@
bodyEl.hidden = false;
// "Continue as current user" — mode=0 logon (cookie re-auth, no password)
function activateCurrent() {
itemCurrent.addEventListener("click", function() {
itemCurrent.style.opacity = "0.5";
itemOther.style.pointerEvents = "none";
fetchApi("/_/logon", { state: helloReq.state, params: [data.username, "", "0"], hello: helloReq })
@@ -142,16 +133,14 @@
resetSignInState();
})
.catch(resetSignInState);
}
itemCurrent.addEventListener("click", activateCurrent);
onKeyActivate(itemCurrent, activateCurrent);
});
})
.catch(function() {
window.location.href = pathPrefix + '/identifier' + window.location.search;
});
// "Use another account" — invalidate current session then go to login form
function activateOther() {
itemOther.addEventListener("click", function() {
var loginParams = new URLSearchParams(window.location.search);
loginParams.set("prompt", "login");
loginParams.delete("flow");
@@ -159,9 +148,7 @@
fetchApi("/_/logoff", { state: helloReq.state }).then(function() {
window.location.href = target;
});
}
itemOther.addEventListener("click", activateOther);
onKeyActivate(itemOther, activateOther);
});
})();
</script>
</body>
+2 -5
View File
@@ -14,7 +14,7 @@
<div class="oc-login-form" id="consent-root">
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
<p id="oc-consent-error-message" class="oc-error-message" role="alert" aria-live="assertive" hidden></p>
<p id="oc-consent-error-message" class="oc-error-message" hidden></p>
<div id="consent-body" hidden>
<p id="consent-display-name" class="oc-light oc-consent-headline"></p>
<p id="consent-username" class="oc-light oc-consent-username"></p>
@@ -127,16 +127,13 @@
if (!desc) desc = "Scope: " + scope;
var li = document.createElement("li");
li.className = "oc-consent-scope-item";
var scopeId = "consent-scope-" + alias;
var cb = document.createElement("input");
cb.type = "checkbox";
cb.id = scopeId;
cb.checked = true;
cb.disabled = true;
cb.className = "oc-consent-checkbox";
var label = document.createElement("label");
var label = document.createElement("span");
label.className = "oc-light";
label.setAttribute("for", scopeId);
label.textContent = desc;
li.appendChild(cb);
li.appendChild(label);
+1 -1
View File
@@ -14,8 +14,8 @@
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
<p class="oc-message">{{.Message}}</p>
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
</div>
</main>
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
</body>
</html>
+3 -7
View File
@@ -23,12 +23,12 @@
data-msg-sign-in="{{.ButtonSignIn}}">
<div>
<label class="oc-label" for="oc-login-username">{{.LabelUsername}}</label>
<input class="oc-input" type="text" id="oc-login-username" name="username" autocomplete="username" placeholder="{{.LabelUsername}}" aria-describedby="oc-login-error-message" required>
<input class="oc-input" type="text" id="oc-login-username" name="username" autocomplete="username" placeholder="{{.LabelUsername}}" required>
</div>
<div>
<label class="oc-label" for="oc-login-password">{{.LabelPassword}}</label>
<input class="oc-input" type="password" id="oc-login-password" name="password" autocomplete="current-password" placeholder="{{.LabelPassword}}" aria-describedby="oc-login-error-message" required>
<p id="oc-login-error-message" class="oc-error-message" role="alert" aria-live="assertive" hidden></p>
<input class="oc-input" type="password" id="oc-login-password" name="password" autocomplete="current-password" placeholder="{{.LabelPassword}}" required>
<p id="oc-login-error-message" class="oc-error-message" hidden></p>
</div>
<div>
<button class="oc-button-primary" type="submit" id="submit-btn">{{.ButtonSignIn}}</button>
@@ -103,16 +103,12 @@
errorEl.hidden = false;
usernameEl.classList.add("error");
passwordEl.classList.add("error");
usernameEl.setAttribute("aria-invalid", "true");
passwordEl.setAttribute("aria-invalid", "true");
}
function hideError() {
errorEl.hidden = true;
usernameEl.classList.remove("error");
passwordEl.classList.remove("error");
usernameEl.removeAttribute("aria-invalid");
passwordEl.removeAttribute("aria-invalid");
}
function setLoading(loading) {
@@ -297,19 +297,10 @@ main {
}
.oc-input:focus {
outline: 2px solid #00b3f0;
outline-offset: 1px;
outline: none;
border: 1px solid #fff;
}
.oc-chooseaccount-item:focus-visible,
.oc-button-primary:focus-visible,
.oc-button-cancel:focus-visible,
.oc-button-consent:focus-visible {
outline: 2px solid #00b3f0;
outline-offset: 2px;
}
.oc-button-primary {
display: block;
width: 100%;
+1 -1
View File
@@ -14,8 +14,8 @@
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
<p class="oc-message">{{.Message}}</p>
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
</div>
</main>
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
</body>
</html>
@@ -3,7 +3,6 @@ package keycloak
import (
"context"
"strings"
"github.com/google/uuid"
libregraph "github.com/owncloud/libre-graph-api-go"
@@ -16,20 +15,16 @@ const (
userType = "Guest"
)
// defaultUserActions are the Keycloak required actions used when no valid
// actions are configured. They ensure an invited guest can always set a
// password and verify their email address.
var defaultUserActions = []keycloak.UserAction{
var userRequiredActions = []keycloak.UserAction{
keycloak.UserActionUpdatePassword,
keycloak.UserActionVerifyEmail,
}
// Backend represents the keycloak backend.
type Backend struct {
logger log.Logger
client keycloak.Client
userRealm string
userActions []keycloak.UserAction
logger log.Logger
client keycloak.Client
userRealm string
}
// New instantiates a new keycloak.Backend with a default gocloak client.
@@ -37,7 +32,6 @@ func New(
logger log.Logger,
baseURL, clientID, clientSecret, clientRealm, userRealm string,
insecureSkipVerify bool,
executeActions []string,
) *Backend {
logger = log.Logger{
Logger: logger.With().
@@ -48,7 +42,7 @@ func New(
Logger(),
}
client := keycloak.New(baseURL, clientID, clientSecret, clientRealm, insecureSkipVerify)
return NewWithClient(logger, client, userRealm, parseUserActions(executeActions))
return NewWithClient(logger, client, userRealm)
}
// NewWithClient creates a new backend with the supplied keycloak client.
@@ -56,16 +50,11 @@ func NewWithClient(
logger log.Logger,
client keycloak.Client,
userRealm string,
userActions []keycloak.UserAction,
) *Backend {
if len(userActions) == 0 {
userActions = defaultUserActions
}
return &Backend{
logger: logger,
client: client,
userRealm: userRealm,
userActions: userActions,
logger: logger,
client: client,
userRealm: userRealm,
}
}
@@ -84,7 +73,7 @@ func (b Backend) CreateUser(ctx context.Context, invitation *invitations.Invitat
UserType: stringP(userType),
}
id, err := b.client.CreateUser(ctx, b.userRealm, user, b.userActions)
id, err := b.client.CreateUser(ctx, b.userRealm, user, userRequiredActions)
if err != nil {
b.logger.Error().
Str("userID", u.String()).
@@ -94,12 +83,6 @@ func (b Backend) CreateUser(ctx context.Context, invitation *invitations.Invitat
return "", err
}
// Record the created user on the invitation so the service can return it as
// the invitedUser relation of the Graph invitation response. user.Id holds the
// OWNCLOUD_ID, i.e. the identity oCIS uses once the guest is provisioned locally
// (not the Keycloak-internal id returned for sending the actions mail).
invitation.InvitedUser = user
return id, nil
}
@@ -108,28 +91,7 @@ func (b Backend) CanSendMail() bool { return true }
// SendMail sends a mail to the user with details on how to redeem the invitation.
func (b Backend) SendMail(ctx context.Context, id string) error {
return b.client.SendActionsMail(ctx, b.userRealm, id, b.userActions)
}
// parseUserActions converts the configured Keycloak required-action strings
// into UserActions. Each non-empty value is passed through to Keycloak as-is
// (Keycloak validates the actions), so operators can configure any action their
// Keycloak supports without this list having to be kept in sync. If none are
// configured, the defaults (UPDATE_PASSWORD, VERIFY_EMAIL) are used so an
// invited guest always has a way to set up their account.
func parseUserActions(executeActions []string) []keycloak.UserAction {
actions := make([]keycloak.UserAction, 0, len(executeActions))
for _, a := range executeActions {
a = strings.TrimSpace(a)
if a == "" {
continue
}
actions = append(actions, keycloak.UserAction(a))
}
if len(actions) == 0 {
return defaultUserActions
}
return actions
return b.client.SendActionsMail(ctx, b.userRealm, id, userRequiredActions)
}
func boolP(b bool) *bool { return &b }
@@ -36,20 +36,18 @@ func TestBackend_CreateUser(t *testing.T) {
tests := []struct {
name string
args args
userActions []kcpkg.UserAction
want string
clientMocks []mockInputs
assertion assert.ErrorAssertionFunc
}{
{
name: "nil actions fall back to the default actions",
name: "Test without diplay name",
args: args{
invitation: &invitations.Invitation{
InvitedUserEmailAddress: "test@example.org",
},
},
userActions: nil,
want: "test-id",
want: "test-id",
clientMocks: []mockInputs{
{
funcName: "CreateUser",
@@ -72,36 +70,6 @@ func TestBackend_CreateUser(t *testing.T) {
return assert.Nil(t, err, args...)
},
},
{
name: "configured actions are passed through to keycloak",
args: args{
invitation: &invitations.Invitation{
InvitedUserEmailAddress: "test@example.org",
},
},
userActions: []kcpkg.UserAction{kcpkg.UserActionUpdatePassword},
want: "test-id",
clientMocks: []mockInputs{
{
funcName: "CreateUser",
args: []interface{}{
mock.Anything,
userRealm,
mock.Anything,
[]kcpkg.UserAction{
kcpkg.UserActionUpdatePassword,
},
},
returns: []interface{}{
"test-id",
nil,
},
},
},
assertion: func(t assert.TestingT, err error, args ...interface{}) bool {
return assert.Nil(t, err, args...)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -110,16 +78,10 @@ func TestBackend_CreateUser(t *testing.T) {
for _, m := range tt.clientMocks {
c.On(m.funcName, m.args...).Return(m.returns...)
}
b := keycloak.NewWithClient(log.NopLogger(), c, userRealm, tt.userActions)
b := keycloak.NewWithClient(log.NopLogger(), c, userRealm)
got, err := b.CreateUser(ctx, tt.args.invitation)
tt.assertion(t, err)
assert.Equal(t, tt.want, got)
// On success the created user is recorded on the invitation as invitedUser.
if err == nil && assert.NotNil(t, tt.args.invitation.InvitedUser) {
assert.Equal(t, tt.args.invitation.InvitedUserEmailAddress, tt.args.invitation.InvitedUser.GetMail())
assert.Equal(t, "Guest", tt.args.invitation.InvitedUser.GetUserType())
assert.NotEmpty(t, tt.args.invitation.InvitedUser.GetId())
}
})
}
}
@@ -136,16 +98,14 @@ func TestBackend_SendMail(t *testing.T) {
tests := []struct {
name string
args args
userActions []kcpkg.UserAction
clientMocks []mockInputs
assertion assert.ErrorAssertionFunc
}{
{
name: "mail successfully sent with default actions",
name: "Mail successfully sent",
args: args{
id: "test-id",
},
userActions: nil,
clientMocks: []mockInputs{
{
funcName: "SendActionsMail",
@@ -167,32 +127,6 @@ func TestBackend_SendMail(t *testing.T) {
return assert.Nil(t, err, args...)
},
},
{
name: "mail sent with only the configured action",
args: args{
id: "test-id",
},
userActions: []kcpkg.UserAction{kcpkg.UserActionUpdatePassword},
clientMocks: []mockInputs{
{
funcName: "SendActionsMail",
args: []interface{}{
mock.Anything,
userRealm,
"test-id",
[]kcpkg.UserAction{
kcpkg.UserActionUpdatePassword,
},
},
returns: []interface{}{
nil,
},
},
},
assertion: func(t assert.TestingT, err error, args ...interface{}) bool {
return assert.Nil(t, err, args...)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -201,7 +135,7 @@ func TestBackend_SendMail(t *testing.T) {
for _, m := range tt.clientMocks {
c.On(m.funcName, m.args...).Return(m.returns...)
}
b := keycloak.NewWithClient(log.NopLogger(), c, userRealm, tt.userActions)
b := keycloak.NewWithClient(log.NopLogger(), c, userRealm)
tt.assertion(t, b.SendMail(ctx, tt.args.id))
})
}
+6 -7
View File
@@ -26,11 +26,10 @@ type Config struct {
// Keycloak configuration
type Keycloak struct {
BasePath string `yaml:"base_path" env:"OCIS_KEYCLOAK_BASE_PATH;INVITATIONS_KEYCLOAK_BASE_PATH" desc:"The URL to access keycloak." introductionVersion:"pre5.0"`
ClientID string `yaml:"client_id" env:"OCIS_KEYCLOAK_CLIENT_ID;INVITATIONS_KEYCLOAK_CLIENT_ID" desc:"The client ID to authenticate with keycloak." introductionVersion:"pre5.0"`
ClientSecret string `yaml:"client_secret" env:"OCIS_KEYCLOAK_CLIENT_SECRET;INVITATIONS_KEYCLOAK_CLIENT_SECRET" desc:"The client secret to use in authentication." introductionVersion:"pre5.0"`
ClientRealm string `yaml:"client_realm" env:"OCIS_KEYCLOAK_CLIENT_REALM;INVITATIONS_KEYCLOAK_CLIENT_REALM" desc:"The realm the client is defined in." introductionVersion:"pre5.0"`
UserRealm string `yaml:"user_realm" env:"OCIS_KEYCLOAK_USER_REALM;INVITATIONS_KEYCLOAK_USER_REALM" desc:"The realm users are defined." introductionVersion:"pre5.0"`
InsecureSkipVerify bool `yaml:"insecure_skip_verify" env:"OCIS_KEYCLOAK_INSECURE_SKIP_VERIFY;INVITATIONS_KEYCLOAK_INSECURE_SKIP_VERIFY" desc:"Disable TLS certificate validation for Keycloak connections. Do not set this in production environments." introductionVersion:"pre5.0"`
ExecuteActions []string `yaml:"execute_actions" env:"INVITATIONS_KEYCLOAK_EXECUTE_ACTIONS" desc:"A comma-separated list of Keycloak required actions sent to invited guests via the execute-actions email. Values are passed to Keycloak as-is. Defaults to 'UPDATE_PASSWORD,VERIFY_EMAIL'. See the Environment Variable Types description for more details." introductionVersion:"NEXT"`
BasePath string `yaml:"base_path" env:"OCIS_KEYCLOAK_BASE_PATH;INVITATIONS_KEYCLOAK_BASE_PATH" desc:"The URL to access keycloak." introductionVersion:"pre5.0"`
ClientID string `yaml:"client_id" env:"OCIS_KEYCLOAK_CLIENT_ID;INVITATIONS_KEYCLOAK_CLIENT_ID" desc:"The client ID to authenticate with keycloak." introductionVersion:"pre5.0"`
ClientSecret string `yaml:"client_secret" env:"OCIS_KEYCLOAK_CLIENT_SECRET;INVITATIONS_KEYCLOAK_CLIENT_SECRET" desc:"The client secret to use in authentication." introductionVersion:"pre5.0"`
ClientRealm string `yaml:"client_realm" env:"OCIS_KEYCLOAK_CLIENT_REALM;INVITATIONS_KEYCLOAK_CLIENT_REALM" desc:"The realm the client is defined in." introductionVersion:"pre5.0"`
UserRealm string `yaml:"user_realm" env:"OCIS_KEYCLOAK_USER_REALM;INVITATIONS_KEYCLOAK_USER_REALM" desc:"The realm users are defined." introductionVersion:"pre5.0"`
InsecureSkipVerify bool `yaml:"insecure_skip_verify" env:"OCIS_KEYCLOAK_INSECURE_SKIP_VERIFY;INVITATIONS_KEYCLOAK_INSECURE_SKIP_VERIFY" desc:"Disable TLS certificate validation for Keycloak connections. Do not set this in production environments." introductionVersion:"pre5.0"`
}
@@ -33,12 +33,11 @@ func DefaultConfig() *config.Config {
Name: "invitations",
},
Keycloak: config.Keycloak{
BasePath: "",
ClientID: "",
ClientSecret: "",
ClientRealm: "",
UserRealm: "",
ExecuteActions: []string{"UPDATE_PASSWORD", "VERIFY_EMAIL"},
BasePath: "",
ClientID: "",
ClientSecret: "",
ClientRealm: "",
UserRealm: "",
},
}
}
@@ -57,7 +57,6 @@ func New(opts ...Option) (Service, error) {
options.Config.Keycloak.ClientRealm,
options.Config.Keycloak.UserRealm,
options.Config.Keycloak.InsecureSkipVerify,
options.Config.Keycloak.ExecuteActions,
)
return svc{
-2
View File
@@ -109,7 +109,6 @@ func Server(cfg *config.Config) *cli.Command {
oidcClient := oidc.NewOIDCClient(
oidc.WithAccessTokenVerifyMethod(cfg.OIDC.AccessTokenVerifyMethod),
oidc.WithAccessTokenVerifyAudiences(cfg.OIDC.AccessTokenVerifyAud),
oidc.WithLogger(logger),
oidc.WithHTTPClient(oidcHTTPClient),
oidc.WithOidcIssuer(cfg.OIDC.Issuer),
@@ -302,7 +301,6 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
middleware.OIDCIss(cfg.OIDC.Issuer),
middleware.OIDCClient(oidc.NewOIDCClient(
oidc.WithAccessTokenVerifyMethod(cfg.OIDC.AccessTokenVerifyMethod),
oidc.WithAccessTokenVerifyAudiences(cfg.OIDC.AccessTokenVerifyAud),
oidc.WithLogger(logger),
oidc.WithHTTPClient(oidcHTTPClient),
oidc.WithOidcIssuer(cfg.OIDC.Issuer),
+7 -8
View File
@@ -113,14 +113,13 @@ const (
// OIDC is the config for the OpenID-Connect middleware. If set the proxy will try to authenticate every request
// with the configured oidc-provider
type OIDC struct {
Issuer string `yaml:"issuer" env:"OCIS_URL;OCIS_OIDC_ISSUER;PROXY_OIDC_ISSUER" desc:"URL of the OIDC issuer. It defaults to URL of the builtin IDP." introductionVersion:"pre5.0"`
Insecure bool `yaml:"insecure" env:"OCIS_INSECURE;PROXY_OIDC_INSECURE" desc:"Disable TLS certificate validation for connections to the IDP. Note that this is not recommended for production environments." introductionVersion:"pre5.0"`
AccessTokenVerifyMethod string `yaml:"access_token_verify_method" env:"PROXY_OIDC_ACCESS_TOKEN_VERIFY_METHOD" desc:"Sets how OIDC access tokens should be verified. Possible values are 'none' and 'jwt'. When using 'none', no special validation apart from using it for accessing the IDP's userinfo endpoint will be done. When using 'jwt', it tries to parse the access token as a jwt token and verifies the signature using the keys published on the IDP's 'jwks_uri'." introductionVersion:"pre5.0"`
AccessTokenVerifyAud []string `yaml:"access_token_verify_aud" env:"PROXY_OIDC_ACCESS_TOKEN_VERIFY_AUD" desc:"A list of accepted audiences for OIDC access tokens, usually the OIDC client IDs used to access ownCloud (for example the web and desktop client IDs). When set, a JWT access token is only accepted if one of these values is present in its 'aud' claim or matches its 'azp' claim. This prevents tokens issued for other applications of a shared IDP from being accepted. When set via the environment variable, use a comma-separated list. Has no effect when 'PROXY_OIDC_ACCESS_TOKEN_VERIFY_METHOD' is set to 'none'. Leave empty to disable the check (default)." introductionVersion:"8.2.0"`
SkipUserInfo bool `yaml:"skip_user_info" env:"PROXY_OIDC_SKIP_USER_INFO" desc:"Do not look up user claims at the userinfo endpoint and directly read them from the access token. Incompatible with 'PROXY_OIDC_ACCESS_TOKEN_VERIFY_METHOD=none'." introductionVersion:"pre5.0"`
UserinfoCache *Cache `yaml:"user_info_cache"`
JWKS JWKS `yaml:"jwks"`
RewriteWellKnown bool `yaml:"rewrite_well_known" env:"PROXY_OIDC_REWRITE_WELLKNOWN" desc:"Enables rewriting the /.well-known/openid-configuration to the configured OIDC issuer. Needed by the Desktop Client, Android Client and iOS Client to discover the OIDC provider." introductionVersion:"pre5.0"`
Issuer string `yaml:"issuer" env:"OCIS_URL;OCIS_OIDC_ISSUER;PROXY_OIDC_ISSUER" desc:"URL of the OIDC issuer. It defaults to URL of the builtin IDP." introductionVersion:"pre5.0"`
Insecure bool `yaml:"insecure" env:"OCIS_INSECURE;PROXY_OIDC_INSECURE" desc:"Disable TLS certificate validation for connections to the IDP. Note that this is not recommended for production environments." introductionVersion:"pre5.0"`
AccessTokenVerifyMethod string `yaml:"access_token_verify_method" env:"PROXY_OIDC_ACCESS_TOKEN_VERIFY_METHOD" desc:"Sets how OIDC access tokens should be verified. Possible values are 'none' and 'jwt'. When using 'none', no special validation apart from using it for accessing the IPD's userinfo endpoint will be done. When using 'jwt', it tries to parse the access token as a jwt token and verifies the signature using the keys published on the IDP's 'jwks_uri'." introductionVersion:"pre5.0"`
SkipUserInfo bool `yaml:"skip_user_info" env:"PROXY_OIDC_SKIP_USER_INFO" desc:"Do not look up user claims at the userinfo endpoint and directly read them from the access token. Incompatible with 'PROXY_OIDC_ACCESS_TOKEN_VERIFY_METHOD=none'." introductionVersion:"pre5.0"`
UserinfoCache *Cache `yaml:"user_info_cache"`
JWKS JWKS `yaml:"jwks"`
RewriteWellKnown bool `yaml:"rewrite_well_known" env:"PROXY_OIDC_REWRITE_WELLKNOWN" desc:"Enables rewriting the /.well-known/openid-configuration to the configured OIDC issuer. Needed by the Desktop Client, Android Client and iOS Client to discover the OIDC provider." introductionVersion:"pre5.0"`
}
type JWKS struct {
-332
View File
@@ -1,332 +0,0 @@
package svc
import (
"context"
"encoding/xml"
"net/http"
"path"
"strconv"
"strings"
"time"
gatewayv1beta1 "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
grpcmetadata "google.golang.org/grpc/metadata"
"github.com/owncloud/ocis/v2/services/webdav/pkg/constants"
"github.com/owncloud/ocis/v2/services/webdav/pkg/net"
"github.com/owncloud/ocis/v2/services/webdav/pkg/prop"
"github.com/owncloud/ocis/v2/services/webdav/pkg/propfind"
"github.com/owncloud/reva/v2/pkg/conversions"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/permission"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/utils"
)
const propOcFavorite = "http://owncloud.org/ns/favorite"
// maxFavoriteContainers bounds how many ListContainer calls a single filter-files REPORT
// will make (across all spaces and pagination pages) before giving up on collecting further
// favorites. Without this, a user with a very large or deeply nested tree could turn a single
// "list my favorites" request into an unbounded number of backend round-trips. Hitting the
// limit returns whatever favorites were already found rather than failing the request.
//
// A var, not a const, so tests can lower it temporarily to exercise the cutoff without
// needing to construct thousands of fake containers.
var maxFavoriteContainers = 5000
// favoriteInfo holds a ResourceInfo and the resolved path for href construction.
type favoriteInfo struct {
info *provider.ResourceInfo
// href-ready path relative to the space root, e.g. "Documents/notes.md"
relativePath string
// hrefPrefix is the DAV prefix for constructing hrefs, e.g.
// "/dav/files/admin" for personal/share spaces or
// "/dav/spaces/<storageId>$<spaceId>" for project spaces.
hrefPrefix string
}
// handleFilterFiles handles REPORT requests with oc:filter-files / oc:filter-rules.
func (g Webdav) handleFilterFiles(w http.ResponseWriter, r *http.Request, ff *reportFilterFiles) {
logger := g.log.SubloggerWithRequestID(r.Context())
if !ff.Rules.Favorite {
// Only favorites filtering is supported; return empty 207.
g.sendFavoritesResponse(nil, w, r)
return
}
t := r.Header.Get(revactx.TokenHeader)
ctx := revactx.ContextSetToken(r.Context(), t)
ctx = grpcmetadata.AppendToOutgoingContext(ctx, revactx.TokenHeader, t)
gwClient, err := g.gatewaySelector.Next()
if err != nil {
logger.Error().Err(err).Msg("error selecting gateway client")
renderError(w, r, errInternalError("could not get gateway client"))
return
}
// Get current user — needed both for CheckPermission (which reads the
// user from the context) and for href construction later.
whoAmI, err := gwClient.WhoAmI(ctx, &gatewayv1beta1.WhoAmIRequest{Token: t})
if err != nil {
logger.Error().Err(err).Msg("error getting current user")
renderError(w, r, errInternalError("could not get current user"))
return
}
if whoAmI.Status.Code != rpcv1beta1.Code_CODE_OK {
logger.Error().Str("status", whoAmI.Status.Message).Msg("could not get current user")
renderError(w, r, errInternalError("could not get current user"))
return
}
ctx = revactx.ContextSetUser(ctx, whoAmI.User)
username := whoAmI.User.Username
// Check permission
ok, err := utils.CheckPermission(ctx, permission.ListFavorites, gwClient)
if err != nil {
logger.Error().Err(err).Msg("error checking list favorites permission")
renderError(w, r, errInternalError("error checking permission"))
return
}
if !ok {
logger.Debug().Msg("user not allowed to list favorites")
renderError(w, r, errPermissionDenied("permission denied"))
return
}
// List user's storage spaces. ListStorageSpaces is paginated, so keep fetching pages
// until the server reports no more are available — otherwise spaces beyond the first
// page would be silently skipped.
var storageSpaces []*provider.StorageSpace
pageToken := ""
for {
spacesResp, err := gwClient.ListStorageSpaces(ctx, &provider.ListStorageSpacesRequest{
Filters: []*provider.ListStorageSpacesRequest_Filter{
{
Type: provider.ListStorageSpacesRequest_Filter_TYPE_USER,
Term: &provider.ListStorageSpacesRequest_Filter_Owner{
Owner: whoAmI.User.Id,
},
},
},
PageToken: pageToken,
})
if err != nil {
logger.Error().Err(err).Msg("error listing storage spaces")
renderError(w, r, errInternalError("could not list storage spaces"))
return
}
if spacesResp.Status.Code != rpcv1beta1.Code_CODE_OK {
logger.Error().Str("status", spacesResp.Status.Message).Msg("could not list storage spaces")
renderError(w, r, errInternalError("could not list storage spaces"))
return
}
storageSpaces = append(storageSpaces, spacesResp.StorageSpaces...)
if spacesResp.NextPageToken == "" {
break
}
pageToken = spacesResp.NextPageToken
}
// Build the /dav/files/<user> href prefix.
// The frontend expects all hrefs under this prefix when it sends
// REPORT to /dav/files/<user>. Project spaces are not addressable
// under this path and are skipped for now.
filesPrefix := path.Join("/dav/files", username)
if strings.HasPrefix(r.URL.Path, "/remote.php/") {
filesPrefix = path.Join("/remote.php/dav/files", username)
}
// Collect favorites across personal and share spaces. visited is a shared budget of
// remaining ListContainer calls (see maxFavoriteContainers) spent across every space,
// not per space, so one space with a huge tree can't starve the others.
var favorites []favoriteInfo
visited := 0
for _, space := range storageSpaces {
if space.Root == nil {
continue
}
var pathPrefix string
switch space.SpaceType {
case "personal":
pathPrefix = ""
case "mountpoint", "grant":
// Mounted shares appear under "Shares/<name>"
name := space.Name
if name == "" {
name = space.Id.OpaqueId
}
pathPrefix = path.Join("Shares", name)
default:
// Project spaces and other types don't appear under
// /dav/files/<user>/ — skip for now.
continue
}
g.collectFavorites(ctx, gwClient, &provider.Reference{ResourceId: space.Root}, pathPrefix, filesPrefix, &favorites, &visited)
}
g.sendFavoritesResponse(favorites, w, r)
}
// collectFavorites recursively walks a storage space, collecting resources that have the
// oc:favorite metadata set. visited tracks how many ListContainer calls have been made so
// far against the shared maxFavoriteContainers budget (see that const's doc comment); it's
// checked before every call, including subsequent pages of the same container, since those
// are just as costly on the backend as a fresh container.
func (g Webdav) collectFavorites(
ctx context.Context,
client gatewayv1beta1.GatewayAPIClient,
ref *provider.Reference,
pathPrefix string,
hrefPrefix string,
results *[]favoriteInfo,
visited *int,
) {
pageToken := ""
for {
if *visited >= maxFavoriteContainers {
g.log.Warn().Int("limit", maxFavoriteContainers).Msg("favorites collection hit its container-visit limit; returning partial results")
return
}
*visited++
resp, err := client.ListContainer(ctx, &provider.ListContainerRequest{
Ref: ref,
ArbitraryMetadataKeys: []string{propOcFavorite},
PageToken: pageToken,
})
if err != nil {
g.log.Error().Err(err).Msg("error listing container for favorites")
return
}
if resp.Status.Code != rpcv1beta1.Code_CODE_OK {
// Skip spaces/directories we cannot access
return
}
for _, info := range resp.Infos {
childPath := path.Join(pathPrefix, info.GetName())
// Check if this resource is favorited
if md := info.GetArbitraryMetadata().GetMetadata(); md != nil {
if fav, ok := md[propOcFavorite]; ok && fav != "" && fav != "0" {
*results = append(*results, favoriteInfo{
info: info,
relativePath: childPath,
hrefPrefix: hrefPrefix,
})
}
}
// Recurse into directories
if info.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
g.collectFavorites(ctx, client, &provider.Reference{ResourceId: info.Id}, childPath, hrefPrefix, results, visited)
}
}
if resp.NextPageToken == "" {
break
}
pageToken = resp.NextPageToken
}
}
// sendFavoritesResponse writes a 207 Multi-Status response for the collected favorites.
func (g Webdav) sendFavoritesResponse(favorites []favoriteInfo, w http.ResponseWriter, r *http.Request) {
logger := g.log.SubloggerWithRequestID(r.Context())
responses := make([]*propfind.ResponseXML, 0, len(favorites))
for i := range favorites {
resp := favoriteInfoToPropResponse(&favorites[i])
responses = append(responses, resp)
}
msr := propfind.NewMultiStatusResponseXML()
msr.Responses = responses
msg, err := xml.Marshal(msr)
if err != nil {
logger.Error().Err(err).Msg("error marshaling favorites response")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set(net.HeaderDav, "1, 3, extended-mkcol")
w.Header().Set(net.HeaderContentType, "application/xml; charset=utf-8")
w.WriteHeader(http.StatusMultiStatus)
if _, err := w.Write(msg); err != nil {
logger.Err(err).Msg("error writing favorites response")
}
}
// favoriteInfoToPropResponse converts a favoriteInfo into a ResponseXML.
func favoriteInfoToPropResponse(fav *favoriteInfo) *propfind.ResponseXML {
info := fav.info
response := &propfind.ResponseXML{
Href: net.EncodePath(path.Join(fav.hrefPrefix, fav.relativePath)),
Propstat: []propfind.PropstatXML{},
}
propstatOK := propfind.PropstatXML{
Status: "HTTP/1.1 200 OK",
Prop: []prop.PropertyXML{},
}
// oc:fileid
if info.Id != nil {
propstatOK.Prop = append(propstatOK.Prop, prop.Escaped("oc:fileid", storagespace.FormatResourceID(info.Id)))
}
// oc:name
propstatOK.Prop = append(propstatOK.Prop, prop.Escaped("oc:name", info.GetName()))
// d:getlastmodified
if info.Mtime != nil {
t := time.Unix(int64(info.Mtime.Seconds), int64(info.Mtime.Nanos))
propstatOK.Prop = append(propstatOK.Prop, prop.Escaped("d:getlastmodified", t.UTC().Format(constants.RFC1123)))
}
// d:getcontenttype
propstatOK.Prop = append(propstatOK.Prop, prop.Escaped("d:getcontenttype", info.GetMimeType()))
// d:getetag
if info.Etag != "" {
propstatOK.Prop = append(propstatOK.Prop, prop.Escaped("d:getetag", "\""+info.Etag+"\""))
}
// oc:permissions
if info.PermissionSet != nil {
role := conversions.RoleFromResourcePermissions(info.PermissionSet, false)
isDir := info.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER
wdp := role.WebDAVPermissions(isDir, false, false, false)
propstatOK.Prop = append(propstatOK.Prop, prop.Escaped("oc:permissions", wdp))
}
// oc:favorite (always "1" since we only return favorites)
propstatOK.Prop = append(propstatOK.Prop, prop.Escaped("oc:favorite", "1"))
// d:resourcetype + size
size := strconv.FormatUint(info.Size, 10)
if info.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
propstatOK.Prop = append(propstatOK.Prop, prop.Raw("d:resourcetype", "<d:collection/>"))
propstatOK.Prop = append(propstatOK.Prop, prop.Escaped("oc:size", size))
} else {
propstatOK.Prop = append(propstatOK.Prop,
prop.Escaped("d:resourcetype", ""),
prop.Escaped("d:getcontentlength", size),
)
}
if len(propstatOK.Prop) > 0 {
response.Propstat = append(response.Propstat, propstatOK)
}
return response
}
@@ -1,701 +0,0 @@
package svc
import (
"context"
"encoding/xml"
"net/http"
"net/http/httptest"
"strings"
"testing"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
"github.com/stretchr/testify/mock"
"google.golang.org/grpc"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/webdav/pkg/constants"
"github.com/owncloud/ocis/v2/services/webdav/pkg/propfind"
)
const filterFilesBody = `<?xml version="1.0" encoding="utf-8" ?>
<oc:filter-files xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
<d:prop>
<d:getlastmodified />
<d:getetag />
<d:getcontenttype />
<d:getcontentlength />
<oc:size />
<d:resourcetype />
<oc:fileid />
<oc:favorite />
<oc:permissions />
</d:prop>
<oc:filter-rules>
<oc:favorite>1</oc:favorite>
</oc:filter-rules>
</oc:filter-files>`
func setupTestWebdav(t *testing.T, gwClient *cs3mocks.GatewayAPIClient) Webdav {
t.Helper()
pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
selector := pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"com.owncloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return gwClient
},
)
return Webdav{
log: log.NopLogger(),
gatewaySelector: selector,
}
}
func newFilterFilesRequest(username string) *http.Request {
r := httptest.NewRequest("REPORT", "/dav/files/"+username, strings.NewReader(filterFilesBody))
ctx := context.WithValue(r.Context(), constants.ContextKeyID, username)
ctx = revactx.ContextSetToken(ctx, "test-token")
ctx = revactx.ContextSetUser(ctx, &userpb.User{
Id: &userpb.UserId{OpaqueId: username},
Username: username,
})
r.Header.Set(revactx.TokenHeader, "test-token")
return r.WithContext(ctx)
}
// mustParseFilterFiles reads and decodes a filter-files REPORT body, failing the test
// immediately (rather than risking a nil-pointer panic later) if decoding errors or the
// filter-files element wasn't present.
func mustParseFilterFiles(t *testing.T, r *http.Request) *reportFilterFiles {
t.Helper()
rep, err := readReport(r.Body)
if err != nil {
t.Fatalf("readReport: %v", err)
}
if rep.FilterFiles == nil {
t.Fatal("expected FilterFiles to be parsed")
}
return rep.FilterFiles
}
func okStatus() *rpcv1beta1.Status {
return &rpcv1beta1.Status{Code: rpcv1beta1.Code_CODE_OK}
}
func mockCheckPermission(gwClient *cs3mocks.GatewayAPIClient, allowed bool) {
code := rpcv1beta1.Code_CODE_OK
if !allowed {
code = rpcv1beta1.Code_CODE_PERMISSION_DENIED
}
gwClient.On("CheckPermission", mock.Anything, mock.Anything).Return(
&permissions.CheckPermissionResponse{
Status: &rpcv1beta1.Status{Code: code},
}, nil,
)
}
func mockWhoAmI(gwClient *cs3mocks.GatewayAPIClient, username string) {
gwClient.On("WhoAmI", mock.Anything, mock.Anything).Return(
&gateway.WhoAmIResponse{
Status: okStatus(),
User: &userpb.User{
Id: &userpb.UserId{OpaqueId: username},
Username: username,
},
}, nil,
)
}
func mockListStorageSpaces(gwClient *cs3mocks.GatewayAPIClient, spaces []*provider.StorageSpace) {
gwClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(
&provider.ListStorageSpacesResponse{
Status: okStatus(),
StorageSpaces: spaces,
}, nil,
)
}
func personalSpace(spaceID string) *provider.StorageSpace {
return &provider.StorageSpace{
Id: &provider.StorageSpaceId{OpaqueId: spaceID},
SpaceType: "personal",
Name: "alice",
Root: &provider.ResourceId{
StorageId: "storage1",
SpaceId: spaceID,
OpaqueId: spaceID,
},
}
}
func TestFilterFilesReturns207WithFavorites(t *testing.T) {
gwClient := cs3mocks.NewGatewayAPIClient(t)
svc := setupTestWebdav(t, gwClient)
mockCheckPermission(gwClient, true)
mockWhoAmI(gwClient, "alice")
mockListStorageSpaces(gwClient, []*provider.StorageSpace{personalSpace("space1")})
// Root listing returns a favorited file and a non-favorited directory
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "space1"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{
{
Id: &provider.ResourceId{StorageId: "storage1", SpaceId: "space1", OpaqueId: "file1"},
Name: "favorite-doc.txt",
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
MimeType: "text/plain",
Size: 1024,
Etag: "abc123",
Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000},
PermissionSet: &provider.ResourcePermissions{
GetPath: true,
Stat: true,
InitiateFileDownload: true,
},
ArbitraryMetadata: &provider.ArbitraryMetadata{
Metadata: map[string]string{
"http://owncloud.org/ns/favorite": "1",
},
},
},
{
Id: &provider.ResourceId{StorageId: "storage1", SpaceId: "space1", OpaqueId: "dir1"},
Name: "not-favorite-dir",
Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER,
Size: 0,
Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000},
PermissionSet: &provider.ResourcePermissions{
GetPath: true,
Stat: true,
},
},
},
}, nil)
// Recursive listing of the non-favorite directory: empty
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "dir1"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{},
}, nil)
r := newFilterFilesRequest("alice")
filterFiles := mustParseFilterFiles(t, r)
// Re-create request since body was consumed
r = newFilterFilesRequest("alice")
rr := httptest.NewRecorder()
svc.handleFilterFiles(rr, r, filterFiles)
if rr.Code != http.StatusMultiStatus {
t.Errorf("expected 207, got %d: %s", rr.Code, rr.Body.String())
}
// Verify XML response
var ms propfind.MultiStatusResponseUnmarshalXML
if err := xml.Unmarshal(rr.Body.Bytes(), &ms); err != nil {
t.Fatalf("unmarshal response: %v", err)
}
if len(ms.Responses) != 1 {
t.Fatalf("expected 1 favorite response, got %d", len(ms.Responses))
}
// Check href — personal space favorites use /dav/files/<user>/ format
expectedHref := "/dav/files/alice/favorite-doc.txt"
if ms.Responses[0].Href != expectedHref {
t.Errorf("expected href %q, got %q", expectedHref, ms.Responses[0].Href)
}
}
func TestFilterFilesEmptyFavoritesReturns207(t *testing.T) {
gwClient := cs3mocks.NewGatewayAPIClient(t)
svc := setupTestWebdav(t, gwClient)
mockCheckPermission(gwClient, true)
mockWhoAmI(gwClient, "alice")
mockListStorageSpaces(gwClient, []*provider.StorageSpace{personalSpace("space1")})
// Root listing: no files at all
gwClient.On("ListContainer", mock.Anything, mock.Anything).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{},
}, nil)
r := newFilterFilesRequest("alice")
filterFiles := mustParseFilterFiles(t, r)
r = newFilterFilesRequest("alice")
rr := httptest.NewRecorder()
svc.handleFilterFiles(rr, r, filterFiles)
if rr.Code != http.StatusMultiStatus {
t.Errorf("expected 207, got %d: %s", rr.Code, rr.Body.String())
}
var ms propfind.MultiStatusResponseUnmarshalXML
if err := xml.Unmarshal(rr.Body.Bytes(), &ms); err != nil {
t.Fatalf("unmarshal response: %v", err)
}
if len(ms.Responses) != 0 {
t.Errorf("expected 0 responses, got %d", len(ms.Responses))
}
}
func TestFilterFilesReturnsBothFileAndFolderFavorites(t *testing.T) {
gwClient := cs3mocks.NewGatewayAPIClient(t)
svc := setupTestWebdav(t, gwClient)
mockCheckPermission(gwClient, true)
mockWhoAmI(gwClient, "alice")
mockListStorageSpaces(gwClient, []*provider.StorageSpace{personalSpace("space1")})
favMeta := &provider.ArbitraryMetadata{
Metadata: map[string]string{propOcFavorite: "1"},
}
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "space1"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{
{
Id: &provider.ResourceId{StorageId: "s1", SpaceId: "space1", OpaqueId: "file1"},
Name: "my-file.pdf",
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
Size: 2048,
MimeType: "application/pdf",
Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000},
ArbitraryMetadata: favMeta,
},
{
Id: &provider.ResourceId{StorageId: "s1", SpaceId: "space1", OpaqueId: "dir1"},
Name: "my-folder",
Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER,
Size: 4096,
Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000},
ArbitraryMetadata: favMeta,
},
},
}, nil)
// Recursive listing of the favorite folder: empty
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "dir1"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{},
}, nil)
r := newFilterFilesRequest("alice")
filterFiles := mustParseFilterFiles(t, r)
r = newFilterFilesRequest("alice")
rr := httptest.NewRecorder()
svc.handleFilterFiles(rr, r, filterFiles)
if rr.Code != http.StatusMultiStatus {
t.Fatalf("expected 207, got %d", rr.Code)
}
var ms propfind.MultiStatusResponseUnmarshalXML
if err := xml.Unmarshal(rr.Body.Bytes(), &ms); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if len(ms.Responses) != 2 {
t.Fatalf("expected 2 favorites (file + folder), got %d", len(ms.Responses))
}
// Verify one is a file (no collection) and one is a folder (collection)
var hasFile, hasFolder bool
for _, resp := range ms.Responses {
if strings.Contains(resp.Href, "my-file.pdf") {
hasFile = true
}
if strings.Contains(resp.Href, "my-folder") {
hasFolder = true
}
}
if !hasFile {
t.Error("expected file favorite in response")
}
if !hasFolder {
t.Error("expected folder favorite in response")
}
}
func TestFilterFilesHrefsUseFilesPrefix(t *testing.T) {
gwClient := cs3mocks.NewGatewayAPIClient(t)
svc := setupTestWebdav(t, gwClient)
mockCheckPermission(gwClient, true)
mockWhoAmI(gwClient, "bob")
mockListStorageSpaces(gwClient, []*provider.StorageSpace{personalSpace("space1")})
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "space1"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{
{
Id: &provider.ResourceId{StorageId: "s1", SpaceId: "space1", OpaqueId: "nested"},
Name: "Documents",
Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER,
Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000},
},
},
}, nil)
// Nested file that is a favorite
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "nested"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{
{
Id: &provider.ResourceId{StorageId: "s1", SpaceId: "space1", OpaqueId: "deepfile"},
Name: "notes.md",
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
Size: 512,
MimeType: "text/markdown",
Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000},
ArbitraryMetadata: &provider.ArbitraryMetadata{
Metadata: map[string]string{propOcFavorite: "1"},
},
},
},
}, nil)
r := newFilterFilesRequest("bob")
filterFiles := mustParseFilterFiles(t, r)
r = newFilterFilesRequest("bob")
rr := httptest.NewRecorder()
svc.handleFilterFiles(rr, r, filterFiles)
if rr.Code != http.StatusMultiStatus {
t.Fatalf("expected 207, got %d", rr.Code)
}
var ms propfind.MultiStatusResponseUnmarshalXML
if err := xml.Unmarshal(rr.Body.Bytes(), &ms); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if len(ms.Responses) != 1 {
t.Fatalf("expected 1 response, got %d", len(ms.Responses))
}
// Personal space favorites use /dav/files/<user>/ format
expectedHref := "/dav/files/bob/Documents/notes.md"
if ms.Responses[0].Href != expectedHref {
t.Errorf("expected href %q, got %q", expectedHref, ms.Responses[0].Href)
}
}
func TestFilterFilesSkipsProjectSpaces(t *testing.T) {
gwClient := cs3mocks.NewGatewayAPIClient(t)
svc := setupTestWebdav(t, gwClient)
mockCheckPermission(gwClient, true)
mockWhoAmI(gwClient, "alice")
projectSpace := &provider.StorageSpace{
Id: &provider.StorageSpaceId{OpaqueId: "proj-space"},
SpaceType: "project",
Name: "Engineering",
Root: &provider.ResourceId{
StorageId: "storage1",
SpaceId: "proj-space",
OpaqueId: "proj-space",
},
}
mockListStorageSpaces(gwClient, []*provider.StorageSpace{projectSpace})
// No ListContainer mock needed — project spaces should be skipped entirely
r := newFilterFilesRequest("alice")
filterFiles := mustParseFilterFiles(t, r)
r = newFilterFilesRequest("alice")
rr := httptest.NewRecorder()
svc.handleFilterFiles(rr, r, filterFiles)
if rr.Code != http.StatusMultiStatus {
t.Fatalf("expected 207, got %d: %s", rr.Code, rr.Body.String())
}
var ms propfind.MultiStatusResponseUnmarshalXML
if err := xml.Unmarshal(rr.Body.Bytes(), &ms); err != nil {
t.Fatalf("unmarshal: %v", err)
}
// Project spaces are not addressable under /dav/files/<user>/,
// so they should be skipped — no favorites returned.
if len(ms.Responses) != 0 {
t.Fatalf("expected 0 responses (project spaces skipped), got %d", len(ms.Responses))
}
}
func TestFilterFilesPermissionDenied(t *testing.T) {
gwClient := cs3mocks.NewGatewayAPIClient(t)
svc := setupTestWebdav(t, gwClient)
mockWhoAmI(gwClient, "alice")
mockCheckPermission(gwClient, false)
r := newFilterFilesRequest("alice")
filterFiles := mustParseFilterFiles(t, r)
r = newFilterFilesRequest("alice")
rr := httptest.NewRecorder()
svc.handleFilterFiles(rr, r, filterFiles)
if rr.Code != http.StatusForbidden {
t.Errorf("expected 403, got %d: %s", rr.Code, rr.Body.String())
}
}
// favoritedFile builds a minimal favorited ResourceInfo for pagination tests, where the
// exact prop values don't matter beyond being present and distinguishable by name.
func favoritedFile(storageID, spaceID, opaqueID, name string) *provider.ResourceInfo {
return &provider.ResourceInfo{
Id: &provider.ResourceId{StorageId: storageID, SpaceId: spaceID, OpaqueId: opaqueID},
Name: name,
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
MimeType: "text/plain",
Size: 1,
Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000},
ArbitraryMetadata: &provider.ArbitraryMetadata{
Metadata: map[string]string{propOcFavorite: "1"},
},
}
}
// TestFilterFilesListStorageSpacesPagination regression-tests that ListStorageSpaces'
// pagination is followed to completion: without it, favorites in any space beyond the
// first page would be silently omitted.
func TestFilterFilesListStorageSpacesPagination(t *testing.T) {
gwClient := cs3mocks.NewGatewayAPIClient(t)
svc := setupTestWebdav(t, gwClient)
mockCheckPermission(gwClient, true)
mockWhoAmI(gwClient, "alice")
gwClient.On("ListStorageSpaces", mock.Anything, mock.MatchedBy(func(req *provider.ListStorageSpacesRequest) bool {
return req.PageToken == ""
})).Return(&provider.ListStorageSpacesResponse{
Status: okStatus(),
StorageSpaces: []*provider.StorageSpace{personalSpace("space1")},
NextPageToken: "page2",
}, nil)
gwClient.On("ListStorageSpaces", mock.Anything, mock.MatchedBy(func(req *provider.ListStorageSpacesRequest) bool {
return req.PageToken == "page2"
})).Return(&provider.ListStorageSpacesResponse{
Status: okStatus(),
StorageSpaces: []*provider.StorageSpace{{
Id: &provider.StorageSpaceId{OpaqueId: "space2"},
SpaceType: "personal",
Name: "alice-second-space",
Root: &provider.ResourceId{StorageId: "storage1", SpaceId: "space2", OpaqueId: "space2"},
}},
NextPageToken: "",
}, nil)
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "space1"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{favoritedFile("storage1", "space1", "file-in-space1", "from-space-1.txt")},
}, nil)
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "space2"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{favoritedFile("storage1", "space2", "file-in-space2", "from-space-2.txt")},
}, nil)
r := newFilterFilesRequest("alice")
filterFiles := mustParseFilterFiles(t, r)
r = newFilterFilesRequest("alice")
rr := httptest.NewRecorder()
svc.handleFilterFiles(rr, r, filterFiles)
if rr.Code != http.StatusMultiStatus {
t.Fatalf("expected 207, got %d: %s", rr.Code, rr.Body.String())
}
var ms propfind.MultiStatusResponseUnmarshalXML
if err := xml.Unmarshal(rr.Body.Bytes(), &ms); err != nil {
t.Fatalf("unmarshal: %v", err)
}
// A favorite from the second page of storage spaces must be present, proving
// ListStorageSpaces' NextPageToken was followed rather than stopping at page one.
if len(ms.Responses) != 2 {
t.Fatalf("expected 2 favorites (one per space, across two ListStorageSpaces pages), got %d: %+v", len(ms.Responses), ms.Responses)
}
var hasSpace1, hasSpace2 bool
for _, resp := range ms.Responses {
if strings.Contains(resp.Href, "from-space-1.txt") {
hasSpace1 = true
}
if strings.Contains(resp.Href, "from-space-2.txt") {
hasSpace2 = true
}
}
if !hasSpace1 || !hasSpace2 {
t.Fatalf("expected favorites from both spaces, got hasSpace1=%v hasSpace2=%v (responses: %+v)", hasSpace1, hasSpace2, ms.Responses)
}
}
// TestFilterFilesListContainerPagination regression-tests that a single container's own
// ListContainer pagination is followed to completion, and that a subdirectory only present
// on a later page is still recursed into — without it, favorites (and whole subtrees) beyond
// a container's first page would be silently omitted.
func TestFilterFilesListContainerPagination(t *testing.T) {
gwClient := cs3mocks.NewGatewayAPIClient(t)
svc := setupTestWebdav(t, gwClient)
mockCheckPermission(gwClient, true)
mockWhoAmI(gwClient, "alice")
mockListStorageSpaces(gwClient, []*provider.StorageSpace{personalSpace("space1")})
// Root container, page 1: one favorite, plus a NextPageToken.
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "space1" && req.PageToken == ""
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{favoritedFile("storage1", "space1", "file-a", "file-a.txt")},
NextPageToken: "root-page2",
}, nil)
// Root container, page 2: another favorite, plus a subdirectory that only appears here.
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "space1" && req.PageToken == "root-page2"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{
favoritedFile("storage1", "space1", "file-b", "file-b.txt"),
{
Id: &provider.ResourceId{StorageId: "storage1", SpaceId: "space1", OpaqueId: "subdir"},
Name: "subdir-from-page-2",
Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER,
Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000},
},
},
}, nil)
// The subdirectory discovered only on the root's second page.
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "subdir"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{favoritedFile("storage1", "space1", "file-c", "file-c.txt")},
}, nil)
r := newFilterFilesRequest("alice")
filterFiles := mustParseFilterFiles(t, r)
r = newFilterFilesRequest("alice")
rr := httptest.NewRecorder()
svc.handleFilterFiles(rr, r, filterFiles)
if rr.Code != http.StatusMultiStatus {
t.Fatalf("expected 207, got %d: %s", rr.Code, rr.Body.String())
}
var ms propfind.MultiStatusResponseUnmarshalXML
if err := xml.Unmarshal(rr.Body.Bytes(), &ms); err != nil {
t.Fatalf("unmarshal: %v", err)
}
// file-a.txt (page 1), file-b.txt (page 2), and file-c.txt (inside the subdir only
// discoverable via page 2) must all be present.
if len(ms.Responses) != 3 {
t.Fatalf("expected 3 favorites (2 from paginated root + 1 nested), got %d: %+v", len(ms.Responses), ms.Responses)
}
var hasA, hasB, hasC bool
for _, resp := range ms.Responses {
hasA = hasA || strings.Contains(resp.Href, "file-a.txt")
hasB = hasB || strings.Contains(resp.Href, "file-b.txt")
hasC = hasC || strings.Contains(resp.Href, "file-c.txt")
}
if !hasA || !hasB || !hasC {
t.Fatalf("expected file-a.txt, file-b.txt and file-c.txt all present, got hasA=%v hasB=%v hasC=%v (responses: %+v)", hasA, hasB, hasC, ms.Responses)
}
}
// TestFilterFilesRespectsContainerVisitLimit regression-tests maxFavoriteContainers: once the
// budget of ListContainer calls is exhausted, collection must stop cleanly (partial results,
// no error) rather than continuing to recurse without bound. The test lowers the limit to 2
// so it can prove the cutoff with a small, fast fixture instead of a real 5000-container tree.
func TestFilterFilesRespectsContainerVisitLimit(t *testing.T) {
original := maxFavoriteContainers
maxFavoriteContainers = 2
t.Cleanup(func() { maxFavoriteContainers = original })
gwClient := cs3mocks.NewGatewayAPIClient(t)
svc := setupTestWebdav(t, gwClient)
mockCheckPermission(gwClient, true)
mockWhoAmI(gwClient, "alice")
mockListStorageSpaces(gwClient, []*provider.StorageSpace{personalSpace("space1")})
// Root container: three non-favorited subdirectories, none of which are favorited
// themselves — every favorite in this fixture lives one level deeper.
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "space1"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{
{Id: &provider.ResourceId{StorageId: "storage1", SpaceId: "space1", OpaqueId: "dirA"}, Name: "dirA", Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER, Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000}},
{Id: &provider.ResourceId{StorageId: "storage1", SpaceId: "space1", OpaqueId: "dirB"}, Name: "dirB", Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER, Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000}},
{Id: &provider.ResourceId{StorageId: "storage1", SpaceId: "space1", OpaqueId: "dirC"}, Name: "dirC", Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER, Mtime: &typesv1beta1.Timestamp{Seconds: 1700000000}},
},
}, nil)
// Only dirA should ever be queried: the root call plus dirA's call already consume the
// budget of 2, so dirB/dirC must never be requested. If the code regresses and queries
// them anyway, this test fails via the mock's unexpected-call panic (no .On(...) is
// registered for dirB/dirC), not just via the assertion below.
gwClient.On("ListContainer", mock.Anything, mock.MatchedBy(func(req *provider.ListContainerRequest) bool {
return req.Ref.ResourceId.OpaqueId == "dirA"
})).Return(&provider.ListContainerResponse{
Status: okStatus(),
Infos: []*provider.ResourceInfo{favoritedFile("storage1", "space1", "deep-file", "deep-file.txt")},
}, nil)
r := newFilterFilesRequest("alice")
filterFiles := mustParseFilterFiles(t, r)
r = newFilterFilesRequest("alice")
rr := httptest.NewRecorder()
svc.handleFilterFiles(rr, r, filterFiles)
// The request must still succeed (partial results), not error out.
if rr.Code != http.StatusMultiStatus {
t.Fatalf("expected 207 even when the container-visit limit is hit, got %d: %s", rr.Code, rr.Body.String())
}
gwClient.AssertNumberOfCalls(t, "ListContainer", 2)
var ms propfind.MultiStatusResponseUnmarshalXML
if err := xml.Unmarshal(rr.Body.Bytes(), &ms); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if len(ms.Responses) != 1 {
t.Fatalf("expected exactly 1 favorite (from dirA, before the budget ran out), got %d: %+v", len(ms.Responses), ms.Responses)
}
if !strings.Contains(ms.Responses[0].Href, "deep-file.txt") {
t.Fatalf("expected the favorite found in dirA, got %+v", ms.Responses[0])
}
}
+38 -40
View File
@@ -27,7 +27,7 @@ import (
const (
elementNameSearchFiles = "search-files"
elementNameFilterFiles = "filter-files"
// TODO elementNameFilterFiles = "filter-files"
)
// Search is the endpoint for retrieving search results for REPORT requests
@@ -40,39 +40,35 @@ func (g Webdav) Search(w http.ResponseWriter, r *http.Request) {
return
}
switch {
case rep.SearchFiles != nil:
t := r.Header.Get(revactx.TokenHeader)
ctx := revactx.ContextSetToken(r.Context(), t)
ctx = metadata.Set(ctx, revactx.TokenHeader, t)
req := &searchsvc.SearchRequest{
Query: rep.SearchFiles.Search.Pattern,
PageSize: int32(rep.SearchFiles.Search.Limit),
}
rsp, err := g.searchClient.Search(ctx, req)
if err != nil {
e := merrors.Parse(err.Error())
switch e.Code {
case http.StatusBadRequest:
renderError(w, r, errBadRequest(e.Detail))
default:
// Don't reflect the raw upstream error back to the caller — same fix
// as landed independently on master; keep it when merging.
renderError(w, r, errInternalError("could not get search results"))
}
logger.Error().Err(err).Msg("could not get search results")
return
}
g.sendSearchResponse(rsp, w, r)
case rep.FilterFiles != nil:
g.handleFilterFiles(w, r, rep.FilterFiles)
default:
renderError(w, r, errBadRequest("missing search-files or filter-files element"))
logger.Debug().Msg("error reading report: no recognized element")
if rep.SearchFiles == nil {
renderError(w, r, errBadRequest("missing search-files tag"))
logger.Debug().Err(err).Msg("error reading report")
return
}
t := r.Header.Get(revactx.TokenHeader)
ctx := revactx.ContextSetToken(r.Context(), t)
ctx = metadata.Set(ctx, revactx.TokenHeader, t)
req := &searchsvc.SearchRequest{
Query: rep.SearchFiles.Search.Pattern,
PageSize: int32(rep.SearchFiles.Search.Limit),
}
rsp, err := g.searchClient.Search(ctx, req)
if err != nil {
e := merrors.Parse(err.Error())
switch e.Code {
case http.StatusBadRequest:
renderError(w, r, errBadRequest(e.Detail))
default:
renderError(w, r, errInternalError("could not get search results"))
}
logger.Error().Err(err).Msg("could not get search results")
return
}
g.sendSearchResponse(rsp, w, r)
}
func (g Webdav) sendSearchResponse(rsp *searchsvc.SearchResponse, w http.ResponseWriter, r *http.Request) {
@@ -358,13 +354,15 @@ func readReport(r io.Reader) (rep *report, err error) {
return nil, err
}
rep.SearchFiles = &repSF
} else if v.Name.Local == elementNameFilterFiles {
var repFF reportFilterFiles
err = decoder.DecodeElement(&repFF, &v)
if err != nil {
return nil, err
}
rep.FilterFiles = &repFF
/*
} else if v.Name.Local == elementNameFilterFiles {
var repFF reportFilterFiles
err = decoder.DecodeElement(&repFF, &v)
if err != nil {
return nil, http.StatusBadRequest, err
}
rep.FilterFiles = &repFF
*/
}
}
}
+3 -30
View File
@@ -41,14 +41,7 @@ var (
http.StatusUnauthorized: "Sabre\\DAV\\Exception\\NotAuthenticated",
http.StatusNotFound: "Sabre\\DAV\\Exception\\NotFound",
http.StatusMethodNotAllowed: "Sabre\\DAV\\Exception\\MethodNotAllowed",
http.StatusForbidden: "Sabre\\DAV\\Exception\\Forbidden",
http.StatusTooEarly: "Sabre\\DAV\\Exception\\TooEarly",
http.StatusTooManyRequests: "Sabre\\DAV\\Exception\\TooManyRequests",
}
// defaultException is used for status codes which have no dedicated sabredav
// exception name, so that clients always receive a non-empty exception.
defaultException = "Sabre\\DAV\\Exception"
)
// Service defines the extension handlers.
@@ -274,11 +267,7 @@ func (g Webdav) SpacesThumbnail(w http.ResponseWriter, r *http.Request) {
case http.StatusForbidden:
renderError(w, r, errPermissionDenied(e.Detail))
default:
// an unmapped error is an infrastructure problem, not a property of the
// requested file: log it at error level so it is visible in production.
logger.Error().Err(err).Msg("could not get thumbnail")
renderError(w, r, errInternalError("could not get thumbnail"))
return
}
logger.Debug().Err(err).Msg("could not get thumbnail")
return
@@ -376,13 +365,9 @@ func (g Webdav) Thumbnail(w http.ResponseWriter, r *http.Request) {
case http.StatusForbidden:
renderError(w, r, errPermissionDenied(e.Detail))
default:
// an unmapped error is an infrastructure problem, not a property of the
// requested file: log it at error level so it is visible in production.
logger.Error().Err(err).Msg("could not get thumbnail")
renderError(w, r, errInternalError("could not get thumbnail"))
return
}
logger.Debug().Err(err).Msg("could not get thumbnail")
g.log.Error().Err(err).Msg("could not get thumbnail")
return
}
@@ -425,13 +410,9 @@ func (g Webdav) PublicThumbnail(w http.ResponseWriter, r *http.Request) {
addRetryAfterHeader(w)
renderError(w, r, errTooManyRequests(e.Detail))
default:
// an unmapped error is an infrastructure problem, not a property of the
// requested file: log it at error level so it is visible in production.
logger.Error().Err(err).Msg("could not get thumbnail")
renderError(w, r, errInternalError("could not get thumbnail"))
return
}
logger.Debug().Err(err).Msg("could not get thumbnail")
g.log.Error().Err(err).Msg("could not get thumbnail")
return
}
@@ -474,11 +455,7 @@ func (g Webdav) PublicThumbnailHead(w http.ResponseWriter, r *http.Request) {
addRetryAfterHeader(w)
renderError(w, r, errTooManyRequests(e.Detail))
default:
// an unmapped error is an infrastructure problem, not a property of the
// requested file: log it at error level so it is visible in production.
logger.Error().Err(err).Msg("could not get thumbnail")
renderError(w, r, errInternalError("could not get thumbnail"))
return
}
logger.Debug().Err(err).Msg("could not get thumbnail")
return
@@ -550,15 +527,11 @@ type errResponse struct {
}
func newErrResponse(statusCode int, msg string) *errResponse {
exception, ok := codesEnum[statusCode]
if !ok {
exception = defaultException
}
rsp := &errResponse{
HTTPStatusCode: statusCode,
Xmlnsd: "DAV",
Xmlnss: "http://sabredav.org/ns",
Exception: exception,
Exception: codesEnum[statusCode],
}
if msg != "" {
rsp.Message = msg
@@ -1,50 +0,0 @@
package svc
import (
"net/http"
"testing"
)
func TestNewErrResponseException(t *testing.T) {
tests := []struct {
name string
statusCode int
expected string
}{
{"bad request", http.StatusBadRequest, "Sabre\\DAV\\Exception\\BadRequest"},
{"unauthorized", http.StatusUnauthorized, "Sabre\\DAV\\Exception\\NotAuthenticated"},
{"not found", http.StatusNotFound, "Sabre\\DAV\\Exception\\NotFound"},
{"method not allowed", http.StatusMethodNotAllowed, "Sabre\\DAV\\Exception\\MethodNotAllowed"},
{"forbidden", http.StatusForbidden, "Sabre\\DAV\\Exception\\Forbidden"},
{"too early", http.StatusTooEarly, "Sabre\\DAV\\Exception\\TooEarly"},
{"too many requests", http.StatusTooManyRequests, "Sabre\\DAV\\Exception\\TooManyRequests"},
// unmapped codes must still yield a non-empty exception
{"internal server error", http.StatusInternalServerError, defaultException},
{"not implemented", http.StatusNotImplemented, defaultException},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rsp := newErrResponse(tt.statusCode, "some message")
if rsp.Exception != tt.expected {
t.Errorf("expected exception %q, got %q", tt.expected, rsp.Exception)
}
if rsp.HTTPStatusCode != tt.statusCode {
t.Errorf("expected status code %d, got %d", tt.statusCode, rsp.HTTPStatusCode)
}
if rsp.Message != "some message" {
t.Errorf("expected message to be set, got %q", rsp.Message)
}
})
}
}
func TestNewErrResponseEmptyMessage(t *testing.T) {
rsp := newErrResponse(http.StatusNotFound, "")
if rsp.Message != "" {
t.Errorf("expected empty message, got %q", rsp.Message)
}
if rsp.Exception != "Sabre\\DAV\\Exception\\NotFound" {
t.Errorf("unexpected exception %q", rsp.Exception)
}
}
+42 -59
View File
@@ -211,18 +211,12 @@ class GraphHelper {
/**
* @param string $baseUrl
* @param string $path
* @param boolean $isVault
*
* @return string
*/
public static function getBetaFullUrl(string $baseUrl, string $path, bool $isVault = false): string {
public static function getBetaFullUrl(string $baseUrl, string $path): string {
$baseUrl = rtrim($baseUrl, "/");
if ($isVault) {
$fullUrl = $baseUrl . '/vault/graph/v1beta1/' . $path;
} else {
$fullUrl = $baseUrl . '/graph/v1beta1/' . $path;
}
return $fullUrl;
return $baseUrl . '/graph/v1beta1/' . $path;
}
/**
@@ -335,28 +329,36 @@ class GraphHelper {
/**
* @param string $baseUrl
* @param string|null $adminUser
* @param string|null $adminPassword
* @param string $adminUser
* @param string $adminPassword
* @param string $userName
* @param array $headers
*
* @return ResponseInterface
* @throws GuzzleException
*/
public static function getUser(
string $baseUrl,
?string $adminUser,
?string $adminPassword,
string $adminUser,
string $adminPassword,
string $userName,
array $headers = [],
): ResponseInterface {
$url = self::getFullUrl($baseUrl, 'users/' . $userName);
$requestHeaders = array_merge(self::getRequestHeaders(), $headers);
if (KeycloakHelper::isTestingWithKeycloak()) {
return HttpRequestHelper::get(
$url,
null,
null,
[
'Authorization' => 'Bearer ' . KeycloakHelper::getAdminAccessToken(),
'Content-Type' => 'application/json',
],
);
}
return HttpRequestHelper::get(
$url,
$adminUser,
$adminPassword,
$requestHeaders,
self::getRequestHeaders(),
);
}
@@ -1067,30 +1069,25 @@ class GraphHelper {
/**
*
* @param string $baseUrl
* @param string|null $user
* @param string|null $password
* @param string $user
* @param string $password
* @param string $spaceId
* @param array $headers
* @param boolean $isVault
*
* @return ResponseInterface
* @throws GuzzleException
*/
public static function disableSpace(
string $baseUrl,
?string $user,
?string $password,
string $user,
string $password,
string $spaceId,
array $headers = [],
bool $isVault = false,
): ResponseInterface {
$url = self::getFullUrl($baseUrl, 'drives/' . $spaceId, $isVault);
$url = self::getFullUrl($baseUrl, 'drives/' . $spaceId);
return HttpRequestHelper::delete(
$url,
$user,
$password,
$headers,
);
}
@@ -1098,31 +1095,27 @@ class GraphHelper {
* send delete space request
*
* @param string $baseUrl
* @param string|null $user
* @param string|null $password
* @param string $user
* @param string $password
* @param string $spaceId
* @param array $headers
* @param boolean $isVault
*
* @return ResponseInterface
* @throws GuzzleException
*/
public static function deleteSpace(
string $baseUrl,
?string $user,
?string $password,
string $user,
string $password,
string $spaceId,
array $headers = [],
bool $isVault = false,
): ResponseInterface {
$url = self::getFullUrl($baseUrl, 'drives/' . $spaceId, $isVault);
$headers["Purge"] = "T";
$url = self::getFullUrl($baseUrl, 'drives/' . $spaceId);
$header = ["Purge" => "T"];
return HttpRequestHelper::delete(
$url,
$user,
$password,
$headers,
$header,
);
}
@@ -1744,8 +1737,8 @@ class GraphHelper {
/**
* @param string $baseUrl
* @param string|null $user
* @param string|null $password
* @param string $user
* @param string $password
* @param string $spaceId
* @param string $itemId
* @param array $shareeIds
@@ -1753,8 +1746,6 @@ class GraphHelper {
* @param string|null $permissionsRole
* @param string|null $permissionsAction
* @param string|null $expirationDateTime
* @param array $headers
* @param boolean $isVault
*
* @return ResponseInterface
* @throws \JsonException
@@ -1762,8 +1753,8 @@ class GraphHelper {
*/
public static function sendSharingInvitation(
string $baseUrl,
?string $user,
?string $password,
string $user,
string $password,
string $spaceId,
string $itemId,
array $shareeIds,
@@ -1771,10 +1762,8 @@ class GraphHelper {
?string $permissionsRole,
?string $permissionsAction,
?string $expirationDateTime,
array $headers,
bool $isVault = false,
): ResponseInterface {
$url = self::getBetaFullUrl($baseUrl, "drives/$spaceId/items/$itemId/invite", $isVault);
$url = self::getBetaFullUrl($baseUrl, "drives/$spaceId/items/$itemId/invite");
$body = self::createShareInviteBody(
$shareeIds,
$shareTypes,
@@ -1782,12 +1771,11 @@ class GraphHelper {
$permissionsAction,
$expirationDateTime,
);
$requestHeaders = array_merge(self::getRequestHeaders(), $headers);
return HttpRequestHelper::post(
$url,
$user,
$password,
$requestHeaders,
self::getRequestHeaders(),
\json_encode($body),
);
}
@@ -2148,34 +2136,30 @@ class GraphHelper {
/**
* @param string $baseUrl
* @param string|null $user
* @param string|null $password
* @param string $user
* @param string $password
* @param string $spaceId
* @param array $shareeIds
* @param array $shareTypes
* @param string|null $permissionsRole
* @param string|null $permissionsAction
* @param string|null $expirationDateTime
* @param array $headers
* @param boolean $isVault
*
* @return ResponseInterface
* @throws \Exception|GuzzleException
*/
public static function sendSharingInvitationForDrive(
string $baseUrl,
?string $user,
?string $password,
string $user,
string $password,
string $spaceId,
array $shareeIds,
array $shareTypes,
?string $permissionsRole,
?string $permissionsAction,
?string $expirationDateTime,
array $headers = [],
bool $isVault = false,
): ResponseInterface {
$url = self::getBetaFullUrl($baseUrl, "drives/$spaceId/root/invite", $isVault);
$url = self::getBetaFullUrl($baseUrl, "drives/$spaceId/root/invite");
$body = self::createShareInviteBody(
$shareeIds,
$shareTypes,
@@ -2184,12 +2168,11 @@ class GraphHelper {
$expirationDateTime,
);
$requestHeaders = array_merge(self::getRequestHeaders(), $headers);
return HttpRequestHelper::post(
$url,
$user,
$password,
$requestHeaders,
self::getRequestHeaders(),
\json_encode($body),
);
}
+23 -120
View File
@@ -95,14 +95,6 @@ class KeycloakHelper {
return (string)self::$adminAccessToken;
}
/**
* @return array
* @throws GuzzleException
*/
private static function getAuthorizationHeader(): array {
return [ 'Authorization' => 'Bearer ' . self::getAdminAccessToken() ];
}
/**
* @param string $roleName
*
@@ -133,16 +125,17 @@ class KeycloakHelper {
?string $email = null,
?string $displayName = null,
): ResponseInterface {
$accessToken = self::getAdminAccessToken();
$url = self::getKeycloakUrl() . '/admin/realms/oCIS/users';
return HttpRequestHelper::post(
$url,
null,
null,
array_merge(
self::getAuthorizationHeader(),
[ 'Content-Type' => 'application/json' ],
),
[
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json',
],
self::prepareCreateUserPayload($username, $password, $email, $displayName),
);
}
@@ -170,40 +163,10 @@ class KeycloakHelper {
$url,
null,
null,
array_merge(
self::getAuthorizationHeader(),
[ 'Content-Type' => 'application/json' ],
),
json_encode($body, JSON_THROW_ON_ERROR),
);
}
/**
* @param string $uuid
* @param string $role
*
* @return ResponseInterface
* @throws GuzzleException
* @throws JsonException
*/
public static function unassignRole(
string $uuid,
string $role,
): ResponseInterface {
$url = self::getKeycloakUrl() . "/admin/realms/oCIS/users/" . $uuid . "/role-mappings/realm";
$ocisRole = self::OCIS_KEYCLOAK_USER_ROLES[$role]
?? throw new InvalidArgumentException("Unknown oCIS role: $role");
$body = [
self::getRealmRole($ocisRole),
];
return HttpRequestHelper::delete(
$url,
null,
null,
array_merge(
self::getAuthorizationHeader(),
[ 'Content-Type' => 'application/json' ],
),
[
"Content-Type" => "application/json",
"Authorization" => "Bearer " . self::getAdminAccessToken(),
],
json_encode($body, JSON_THROW_ON_ERROR),
);
}
@@ -403,7 +366,9 @@ class KeycloakHelper {
$url,
null,
null,
self::getAuthorizationHeader(),
[
'Authorization' => 'Bearer ' . self::getAdminAccessToken(),
],
);
if ($response->getStatusCode() !== 200) {
throw new Exception("Failed to get realm roles.");
@@ -428,10 +393,10 @@ class KeycloakHelper {
$url,
null,
null,
array_merge(
self::getAuthorizationHeader(),
[ 'Content-Type' => 'application/json' ],
),
[
'Authorization' => 'Bearer ' . self::getAdminAccessToken(),
'Content-Type' => 'application/json',
],
json_encode(['attributes' => $attributes], JSON_THROW_ON_ERROR),
);
}
@@ -452,78 +417,14 @@ class KeycloakHelper {
$url,
null,
null,
array_merge(
self::getAuthorizationHeader(),
[ 'Content-Type' => 'application/json' ],
),
[
'Authorization' => 'Bearer ' . self::getAdminAccessToken(),
'Content-Type' => 'application/json',
],
json_encode(['attributes' => $attributes], JSON_THROW_ON_ERROR),
);
}
/**
* @param string $username
*
* @return string
* @throws GuzzleException
* @throws JsonException
* @throws Exception
*/
public static function getUserIdByUsername(string $username): string {
$url = self::getKeycloakUrl() . '/admin/realms/oCIS/users?username=' . \urlencode($username) . '&exact=true';
$response = HttpRequestHelper::get(
$url,
null,
null,
self::getAuthorizationHeader(),
);
if ($response->getStatusCode() !== 200) {
throw new Exception("Failed to look up Keycloak user '$username', status: " . $response->getStatusCode());
}
$users = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
if (empty($users)) {
throw new Exception("Keycloak user '$username' not found.");
}
return $users[0]['id'];
}
/**
* Deletes all OTP/TOTP credentials for a Keycloak user, so MFA can be set up fresh.
*
* @param string $username
*
* @return void
* @throws GuzzleException
* @throws JsonException
* @throws Exception
*/
public static function deleteUserTotpCredentials(string $username): void {
$uuid = self::getUserIdByUsername($username);
$url = self::getKeycloakUrl() . '/admin/realms/oCIS/users/' . $uuid . '/credentials';
$response = HttpRequestHelper::get(
$url,
null,
null,
self::getAuthorizationHeader(),
);
if ($response->getStatusCode() !== 200) {
throw new Exception("Failed to list credentials for Keycloak user '$username'.");
}
$credentials = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
foreach ($credentials as $credential) {
if (isset($credential['type']) && \in_array($credential['type'], ['otp', 'totp'], true)) {
$deleteUrl = self::getKeycloakUrl()
. '/admin/realms/oCIS/users/' . $uuid
. '/credentials/' . $credential['id'];
HttpRequestHelper::delete(
$deleteUrl,
null,
null,
self::getAuthorizationHeader(),
);
}
}
}
/**
* @param string $uuid
*
@@ -536,7 +437,9 @@ class KeycloakHelper {
$url,
null,
null,
self::getAuthorizationHeader(),
[
"Authorization" => "Bearer " . self::getAdminAccessToken(),
],
);
}
}
+4 -34
View File
@@ -240,22 +240,11 @@ class GraphContext implements Context {
$user = $this->featureContext->getActualUsername($user);
$userId = $this->featureContext->getAttributeOfCreatedUser($user, "id");
$userId = $userId ?: $user;
$adminUser = $this->featureContext->getAdminUsername();
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$accessToken = $this->featureContext->getOcisUserToken($adminUser)["token"]["accessToken"];
$headers['Authorization'] = 'Bearer ' . $accessToken;
$adminUser = null;
$adminPassword = null;
} else {
$adminPassword = $this->featureContext->getAdminPassword();
}
return GraphHelper::getUser(
$this->featureContext->getBaseUrl(),
$adminUser,
$adminPassword,
$this->featureContext->getAdminUsername(),
$this->featureContext->getAdminPassword(),
$userId,
$headers,
);
}
@@ -1826,27 +1815,9 @@ class GraphContext implements Context {
* @throws Exception
*/
public function theAdministratorHasGivenTheRoleUsingTheGraphApi(string $role, string $user): void {
$userId = $this->featureContext->getAttributeOfCreatedUser($user, 'id') ?: $user;
if (KeycloakHelper::isTestingWithKeycloak()) {
$userAttribute = $this->featureContext->getCreatedKeycloakUsers();
$userId = $userAttribute[strtolower($user)]['id'];
$currentRole = $userAttribute[strtolower($user)]['role'];
/*
* The oCIS API request for assigning roles allows only one role per user,
* whereas the Keycloak API request can assign multiple roles to a user.
* If multiple roles are assigned to a user in Keycloak,
* oCIS map the highest priority role among Keycloak assigned roles.
* Therefore, we need to unassign the previous role before
* assigning a new one when using the Keycloak API.
*/
$res = KeycloakHelper::unassignRole($userId, $currentRole);
Assert::assertEquals(
204,
$res->getStatusCode(),
__METHOD__
. "\nExpected status code '204' but got '" . $res->getStatusCode() . "'",
);
$response = KeycloakHelper::assignRole($userId, $role);
$response = KeycloakHelper::assignrole($userId, $role);
Assert::assertEquals(
204,
$response->getStatusCode(),
@@ -1854,7 +1825,6 @@ class GraphContext implements Context {
. "\nExpected status code '204' but got '" . $response->getStatusCode() . "'",
);
} else {
$userId = $this->featureContext->getAttributeOfCreatedUser($user, 'id') ?: $user;
if (empty($this->appEntity)) {
$this->setApplicationEntity();
}
+22 -90
View File
@@ -47,7 +47,6 @@ trait Provisioning {
private array $createdRemoteGroups = [];
private array $createdGroups = [];
private array $userTokens = [];
private array $createdKeycloakUsers = [];
/**
* @param array $user
@@ -112,13 +111,6 @@ trait Provisioning {
return $this->createdUsers;
}
/**
* @return array
*/
public function getCreatedKeycloakUsers(): array {
return $this->createdKeycloakUsers;
}
/**
* @return array
*/
@@ -592,6 +584,13 @@ trait Provisioning {
}
$locationHeader = explode("/", $response->getHeader("Location")[0]);
$uuid = end($locationHeader);
$this->addUserToCreatedUsersList(
$userAttributes['userid'],
$userAttributes['password'],
$userAttributes['displayName'],
$userAttributes['email'],
$uuid,
);
// assign default ocisUser role to newly created user
$res = KeycloakHelper::assignRole($uuid, "User");
@@ -603,15 +602,6 @@ trait Provisioning {
"\nHTTP status " . $res->getStatusCode() .
"\nKeycloak response " . (string)$res->getBody(),
);
$this->addUserToCreatedKeycloakUsersList(
$userAttributes['userid'],
$userAttributes['password'],
$userAttributes['displayName'],
$userAttributes['email'],
$uuid,
"User",
);
}
/**
@@ -632,12 +622,7 @@ trait Provisioning {
"email" => "admin@example.org",
"actualUsername" => "admin",
];
$state = WebUIHelper::setUpUser(
$this->getBaseUrl(),
$adminUser["actualUsername"],
$adminUser["password"],
);
$tokenData = \json_decode($state['origins'][0]['localStorage'][2]['value']);
$tokenData = KeycloakHelper::setAccessTokenForKeycloakOcisUser($adminUser);
$this->setOcisUserToken($adminUser, $tokenData);
}
@@ -651,27 +636,17 @@ trait Provisioning {
*
* @return void
* @throws Exception
* @throws GuzzleException
*/
public function userHasLoggedInViaWebUI(string $user): void {
$createdUsers = $this->getCreatedKeycloakUsers();
$userAttribute = $createdUsers[strtolower($user)];
$createdUsers = $this->getCreatedUsers();
$user = $createdUsers[strtolower($user)];
$state = WebUIHelper::setUpUser(
$this->getBaseUrl(),
$userAttribute["actualUsername"],
$userAttribute["password"],
$user["actualUsername"],
$user["password"],
);
$stateData = \json_decode($state['origins'][0]['localStorage'][2]['value']);
$this->setOcisUserToken($userAttribute, $stateData);
$response = $this->graphContext->adminHasRetrievedUserUsingTheGraphApi($user);
$userAttribute['id'] = $this->getJsonDecodedResponse($response)['id'];
$this->addUserToCreatedUsersList(
$user,
$userAttribute['password'],
$userAttribute['displayName'],
$userAttribute['email'],
$userAttribute['id'],
);
$this->setOcisUserToken($user, $stateData);
}
/**
@@ -1140,37 +1115,6 @@ trait Provisioning {
}
}
/**
* @param string $user
* @param string $password
* @param string $displayname
* @param string $email
* @param string $userId
* @param string $role
*
* @return void
* @throws JsonException
*/
public function addUserToCreatedKeycloakUsersList(
string $user,
string $password,
string $displayname,
string $email,
string $userId,
string $role,
): void {
$user = $this->getActualUsername($user);
$normalizedUsername = $this->normalizeUsername($user);
$this->createdKeycloakUsers[$normalizedUsername] = [
"password" => $password,
"displayName" => $displayname,
"actualUsername" => $user,
"email" => $email,
"id" => $userId,
"role" => $role,
];
}
/**
* remember the password of a user that already exists so that you can use
* ordinary test steps after changing their password.
@@ -1283,12 +1227,6 @@ trait Provisioning {
__METHOD__ . " cannot create a LDAP user with provided data. Error: $exception",
);
}
} elseif (KeycloakHelper::isTestingWithKeycloak()) {
$setting["userid"] = $user;
$setting["displayName"] = $displayName;
$setting["password"] = $password;
$setting["email"] = $email;
$this->createKeycloakUser($setting);
} else {
$reqUser = $byUser ? $this->getActualUsername($byUser) : $this->getAdminUsername();
$response = GraphHelper::createUser(
@@ -1309,16 +1247,14 @@ trait Provisioning {
$userId = $this->getJsonDecodedResponse($response)['id'];
}
if (!KeycloakHelper::isTestingWithKeycloak()) {
$this->addUserToCreatedUsersList($user, $password, $displayName, $email, $userId);
$this->addUserToCreatedUsersList($user, $password, $displayName, $email, $userId);
Assert::assertTrue(
$this->userExists($user),
"User '$user' should exist but does not exist",
);
Assert::assertTrue(
$this->userExists($user),
"User '$user' should exist but does not exist",
);
$this->initializeUser($user, $password);
}
$this->initializeUser($user, $password);
}
/**
@@ -2155,16 +2091,12 @@ trait Provisioning {
$this->userExists($user),
"User '$user' should not exist but does exist",
);
}
// delete users from keycloak
if (KeycloakHelper::isTestingWithKeycloak()) {
foreach ($this->createdKeycloakUsers as $userData) {
// delete user from keycloak
if (KeycloakHelper::isTestingWithKeycloak()) {
$res = KeycloakHelper::deleteKeycloakUser($userData['id']);
$user = $userData['actualUsername'];
$this->theHTTPStatusCodeShouldBe(204, "Failed to delete keycloak user '$user'", $res);
}
// Clean up any existing TOTP credentials for admin user so MFA can be set up fresh in every scenario.
KeycloakHelper::deleteUserTotpCredentials('admin');
}
$this->usingServer($previousServer);
}
@@ -26,7 +26,6 @@ use GuzzleHttp\Exception\GuzzleException;
use PHPUnit\Framework\Assert;
use Psr\Http\Message\ResponseInterface;
use TestHelpers\GraphHelper;
use TestHelpers\KeycloakHelper;
use TestHelpers\WebDavHelper;
use TestHelpers\HttpRequestHelper;
use TestHelpers\BehatHelper;
@@ -331,8 +330,7 @@ class SharingNgContext implements Context {
?string $fileId = null,
bool $federatedShare = false,
): ResponseInterface {
$isVault = isset($shareInfo['storage']) && $shareInfo['storage'] === 'vault';
$space = $this->spacesContext->getSpaceByName($user, $shareInfo['space'], $isVault);
$space = $this->spacesContext->getSpaceByName($user, $shareInfo['space']);
$spaceId = $space['id'];
// $fileId is used for trying to share deleted files
@@ -345,7 +343,7 @@ class SharingNgContext implements Context {
if ($resource === '' && !\in_array($shareInfo['space'], ['Personal', 'Shares'])) {
$itemId = $space['fileId'];
} else {
$itemId = $this->spacesContext->getResourceId($user, $shareInfo['space'], $resource, $isVault);
$itemId = $this->spacesContext->getResourceId($user, $shareInfo['space'], $resource);
}
}
@@ -383,19 +381,10 @@ class SharingNgContext implements Context {
$permissionsAction = $shareInfo['permissionsAction'] ?? null;
$expirationDateTime = $shareInfo["expirationDateTime"] ?? null;
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$accessToken = $this->featureContext->getOcisUserToken($user)['token']['accessToken'];
$headers['Authorization'] = 'Bearer ' . $accessToken;
$user = null;
$password = null;
} else {
$password = $this->featureContext->getPasswordForUser($user);
}
$response = GraphHelper::sendSharingInvitation(
$this->featureContext->getBaseUrl(),
$user,
$password,
$this->featureContext->getPasswordForUser($user),
$spaceId,
$itemId,
$shareeIds,
@@ -403,8 +392,6 @@ class SharingNgContext implements Context {
$permissionsRole,
$permissionsAction,
$expirationDateTime,
$headers,
$isVault,
);
if ($response->getStatusCode() === 200) {
$this->featureContext->shareNgAddToCreatedUserGroupShares(
@@ -435,8 +422,7 @@ class SharingNgContext implements Context {
bool $federatedShare = false,
): ResponseInterface {
$shareeIds = [];
$isVault = isset($rows['storage']) && $rows['storage'] === 'vault';
$space = $this->spacesContext->getSpaceByName($user, $rows['space'], $isVault);
$space = $this->spacesContext->getSpaceByName($user, $rows['space']);
$spaceId = $space['id'];
$sharees = array_map('trim', explode(',', $rows['sharee']));
@@ -466,28 +452,16 @@ class SharingNgContext implements Context {
$permissionsAction = $rows['permissionsAction'] ?? null;
$expirationDateTime = $rows["expirationDateTime"] ?? null;
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$accessToken = $this->featureContext->getOcisUserToken($user)['token']['accessToken'];
$headers['Authorization'] = 'Bearer ' . $accessToken;
$user = null;
$password = null;
} else {
$password = $this->featureContext->getPasswordForUser($user);
}
return GraphHelper::sendSharingInvitationForDrive(
$this->featureContext->getBaseUrl(),
$user,
$password,
$this->featureContext->getPasswordForUser($user),
$spaceId,
$shareeIds,
$shareTypes,
$permissionsRole,
$permissionsAction,
$expirationDateTime,
$headers,
$isVault,
);
}
+28 -175
View File
@@ -384,7 +384,6 @@ class SpacesContext implements Context {
* @param string $spaceName
* @param string $fileName
* @param bool $federatedShare
* @param bool $isVault
*
* @return ResponseInterface
* @throws GuzzleException
@@ -394,7 +393,6 @@ class SpacesContext implements Context {
string $spaceName,
string $fileName,
bool $federatedShare = false,
bool $isVault = false,
): ResponseInterface {
$baseUrl = $this->featureContext->getBaseUrl();
@@ -402,27 +400,18 @@ class SpacesContext implements Context {
$remoteItemId = $this->getSharesRemoteItemId($user, $spaceName);
$spaceId = \rawurlencode($remoteItemId);
} else {
$space = $this->getSpaceByName($user, $spaceName, $isVault);
$space = $this->getSpaceByName($user, $spaceName);
$spaceId = $space["id"];
}
$davPath = WebdavHelper::getDavPath(WebDavHelper::DAV_VERSION_SPACES, $spaceId);
$fullUrl = "$baseUrl/$davPath/$fileName";
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$accessToken = $this->featureContext->getOcisUserToken($user)['token']['accessToken'];
$headers['Authorization'] = 'Bearer ' . $accessToken;
$user = null;
$password = null;
} else {
$password = $this->featureContext->getPasswordForUser($user);
}
return HttpRequestHelper::get(
$fullUrl,
$user,
$password,
$headers,
$this->featureContext->getPasswordForUser($user),
[],
"{}",
);
}
@@ -448,13 +437,12 @@ class SpacesContext implements Context {
* @param string $user
* @param string $spaceName
* @param string $folderName
* @param boolean $isVault
*
* @return string
* @throws GuzzleException
*/
public function getResourceId(string $user, string $spaceName, string $folderName, bool $isVault = false): string {
$space = $this->getSpaceByName($user, $spaceName, $isVault);
public function getResourceId(string $user, string $spaceName, string $folderName): string {
$space = $this->getSpaceByName($user, $spaceName);
// For a level 1 folder, the parent is space so $folderName = ''
if ($folderName === $space["name"]) {
$folderName = '';
@@ -465,21 +453,12 @@ class SpacesContext implements Context {
$davPath = WebDavHelper::getDavPath(WebDavHelper::DAV_VERSION_SPACES, $space["id"]);
$fullUrl = "$baseUrl/$davPath/$encodedName";
$headers = ['Depth' => '0'];
if (KeycloakHelper::isTestingWithKeycloak()) {
$accessToken = $this->featureContext->getOcisUserToken($user)['token']['accessToken'];
$headers['Authorization'] = 'Bearer ' . $accessToken;
$user = null;
$password = null;
} else {
$password = $this->featureContext->getPasswordForUser($user);
}
$response = HttpRequestHelper::sendRequest(
$fullUrl,
'PROPFIND',
$user,
$password,
$headers,
$this->featureContext->getPasswordForUser($user),
['Depth' => '0'],
);
$this->featureContext->theHttpStatusCodeShouldBe(207, '', $response);
@@ -972,12 +951,11 @@ class SpacesContext implements Context {
}
/**
* @Then /^for user "([^"]*)" folder "([^"]*)" of the space "([^"]*)"(| in vault)? should (not|)\s?contain these (?:files|entries):$/
* @Then /^for user "([^"]*)" folder "([^"]*)" of the space "([^"]*)" should (not|)\s?contain these (?:files|entries):$/
*
* @param string $user
* @param string $folderPath
* @param string $spaceName
* @param string $isVault
* @param string $shouldOrNot (not|)
* @param TableNode $expectedFiles
*
@@ -989,13 +967,11 @@ class SpacesContext implements Context {
string $user,
string $folderPath,
string $spaceName,
string $isVault,
string $shouldOrNot,
TableNode $expectedFiles,
): void {
$isVault = trim($isVault) === 'in vault';
$space = $this->getSpaceByName($user, $spaceName, $isVault);
$this->featureContext->setResponse($this->propfindSpace($user, $spaceName, $folderPath, $isVault));
$space = $this->getSpaceByName($user, $spaceName);
$this->featureContext->setResponse($this->propfindSpace($user, $spaceName, $folderPath));
$this->featureContext->propfindResultShouldContainEntries(
$shouldOrNot,
$expectedFiles,
@@ -1007,12 +983,11 @@ class SpacesContext implements Context {
}
/**
* @Then /^for user "([^"]*)" the content of the file "([^"]*)" of the space "([^"]*)"(| in vault) should be "([^"]*)"$/
* @Then /^for user "([^"]*)" the content of the file "([^"]*)" of the space "([^"]*)" should be "([^"]*)"$/
*
* @param string $user
* @param string $file
* @param string $spaceName
* @param string $isVault
* @param string $fileContent
*
* @return void
@@ -1023,11 +998,9 @@ class SpacesContext implements Context {
string $user,
string $file,
string $spaceName,
string $isVault,
string $fileContent,
): void {
$isVault = trim($isVault) === 'in vault';
$actualFileContent = $this->getFileData($user, $spaceName, $file, false, $isVault)->getBody()->getContents();
$actualFileContent = $this->getFileData($user, $spaceName, $file)->getBody()->getContents();
Assert::assertEquals($fileContent, $actualFileContent, "$file does not contain $fileContent");
}
@@ -2107,15 +2080,15 @@ class SpacesContext implements Context {
}
/**
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)"(| in vault)? to "([^"]*)" inside space "([^"]*)"(| in vault)? using the WebDAV API$/
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)" to "([^"]*)" inside space "([^"]*)" using the WebDAV API$/
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)" to "([^"]*)" inside space "([^"]*)"(?: with following headers) using the WebDAV API$/
*
* @param string $user
* @param string $fileSource
* @param string $fromSpaceName
* @param string $isSourceVault
* @param string $fileDestination
* @param string $toSpaceName
* @param string $isDestinationVault
* @param TableNode|null $table
*
* @return void
* @throws GuzzleException
@@ -2124,86 +2097,15 @@ class SpacesContext implements Context {
string $user,
string $fileSource,
string $fromSpaceName,
string $isSourceVault,
string $fileDestination,
string $toSpaceName,
string $isDestinationVault,
): void {
$isSourceVault = trim($isSourceVault) === "in vault";
$isDestinationVault = trim($isDestinationVault) === "in vault";
$this->copyFileBetweenSpaces(
$user,
$fileSource,
$fromSpaceName,
$fileDestination,
$toSpaceName,
$isSourceVault,
$isDestinationVault,
);
}
/**
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)" to "([^"]*)" inside space "([^"]*)" with following headers using the WebDAV API$/
*
* @param string $user
* @param string $fileSource
* @param string $fromSpaceName
* @param string $fileDestination
* @param string $toSpaceName
* @param TableNode $table
*
* @return void
* @throws GuzzleException
*/
public function userCopiesFileFromAndToSpaceBetweenSpacesWithHeaders(
string $user,
string $fileSource,
string $fromSpaceName,
string $fileDestination,
string $toSpaceName,
TableNode $table,
): void {
$this->copyFileBetweenSpaces(
$user,
$fileSource,
$fromSpaceName,
$fileDestination,
$toSpaceName,
false,
false,
$table,
);
}
/**
* @param string $user
* @param string $fileSource
* @param string $fromSpaceName
* @param string $fileDestination
* @param string $toSpaceName
* @param boolean $isSourceVault
* @param boolean $isDestinationVault
* @param TableNode|null $table
*
* @return void
* @throws GuzzleException
*/
private function copyFileBetweenSpaces(
string $user,
string $fileSource,
string $fromSpaceName,
string $fileDestination,
string $toSpaceName,
?bool $isSourceVault = false,
?bool $isDestinationVault = false,
?TableNode $table = null,
): void {
$space = $this->getSpaceByName($user, $fromSpaceName, $isSourceVault);
$space = $this->getSpaceByName($user, $fromSpaceName);
$headers['Destination'] = $this->destinationHeaderValueWithSpaceName(
$user,
$fileDestination,
$toSpaceName,
$isDestinationVault,
);
if ($table !== null) {
@@ -2379,7 +2281,6 @@ class SpacesContext implements Context {
* @param string $user
* @param string $fileDestination
* @param string $spaceName
* @param boolean $isVault
* @param string|null $endPath
*
* @return string
@@ -2389,10 +2290,9 @@ class SpacesContext implements Context {
string $user,
string $fileDestination,
string $spaceName,
bool $isVault = false,
?string $endPath = null,
): string {
$space = $this->getSpaceByName($user, $spaceName, $isVault);
$space = $this->getSpaceByName($user, $spaceName);
$fileDestination = $this->escapePath(\ltrim($fileDestination, "/"));
$baseUrl = $this->featureContext->getBaseUrl();
$davPath = WebdavHelper::getDavPath(WebDavHelper::DAV_VERSION_SPACES, $space["id"]);
@@ -2410,19 +2310,11 @@ class SpacesContext implements Context {
* @throws GuzzleException
*/
public function copyFilesAndFoldersRequest(string $user, string $fullUrl, array $headers): ResponseInterface {
if (KeycloakHelper::isTestingWithKeycloak()) {
$access_token = $this->featureContext->getOcisUserToken($user)["token"]["accessToken"];
$headers['Authorization'] = 'Bearer ' . $access_token;
$user = null;
$password = null;
} else {
$password = $this->featureContext->getPasswordForUser($user);
}
return HttpRequestHelper::sendRequest(
$fullUrl,
'COPY',
$user,
$password,
$this->featureContext->getPasswordForUser($user),
$headers,
);
}
@@ -2462,7 +2354,6 @@ class SpacesContext implements Context {
$user,
$fileDestination,
$toSpaceName,
false,
$fileId,
);
}
@@ -2510,7 +2401,6 @@ class SpacesContext implements Context {
$user,
$fileDestination,
$spaceName,
false,
$fileId,
);
}
@@ -2555,7 +2445,6 @@ class SpacesContext implements Context {
$user,
$fileDestination,
$spaceName,
false,
$fileId,
);
}
@@ -2604,7 +2493,6 @@ class SpacesContext implements Context {
$user,
$fileDestination,
$spaceName,
false,
$fileId,
);
}
@@ -2660,13 +2548,12 @@ class SpacesContext implements Context {
}
/**
* @Given /^user "([^"]*)" has uploaded a file inside space "([^"]*)" with content "([^"]*)" to "([^"]*)"(| in vault)?$/
* @Given /^user "([^"]*)" has uploaded a file inside space "([^"]*)" with content "([^"]*)" to "([^"]*)"$/
*
* @param string $user
* @param string $spaceName
* @param string $fileContent
* @param string $destination
* @param string $isVault
*
* @return array
* @throws GuzzleException
@@ -2676,10 +2563,8 @@ class SpacesContext implements Context {
string $spaceName,
string $fileContent,
string $destination,
string $isVault,
): array {
$isVault = trim($isVault) === "in vault";
$space = $this->getSpaceByName($user, $spaceName, $isVault);
$space = $this->getSpaceByName($user, $spaceName);
$response = $this->featureContext->uploadFileWithContent(
$user,
$fileContent,
@@ -3208,11 +3093,10 @@ class SpacesContext implements Context {
}
/**
* @Given /^user "([^"]*)" has deleted a space "([^"]*)"(| in vault)?$/
* @Given /^user "([^"]*)" has deleted a space "([^"]*)"$/
*
* @param string $user
* @param string $spaceName
* @param string $isVault
*
* @return void
* @throws GuzzleException
@@ -3220,10 +3104,8 @@ class SpacesContext implements Context {
public function userHasDeletedASpaceOwnedByUser(
string $user,
string $spaceName,
string $isVault,
): void {
$isVault = trim($isVault) === 'in vault';
$response = $this->deleteSpace($user, $spaceName, '', $isVault);
$response = $this->deleteSpace($user, $spaceName);
$this->featureContext->theHTTPStatusCodeShouldBe(
204,
"Expected response status code should be 200",
@@ -3235,7 +3117,6 @@ class SpacesContext implements Context {
* @param string $user
* @param string $spaceName
* @param string $owner
* @param boolean $isVault
*
* @return ResponseInterface
* @throws GuzzleException
@@ -3244,25 +3125,13 @@ class SpacesContext implements Context {
string $user,
string $spaceName,
string $owner = '',
bool $isVault = false,
): ResponseInterface {
$space = $this->getSpaceByName(($owner !== "") ? $owner : $user, $spaceName, $isVault);
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$accessToken = $this->featureContext->getOcisUserToken(strtolower($user))['token']['accessToken'];
$headers['Authorization'] = 'Bearer ' . $accessToken;
$user = null;
$password = null;
} else {
$password = $this->featureContext->getPasswordForUser($user);
}
$space = $this->getSpaceByName(($owner !== "") ? $owner : $user, $spaceName);
return GraphHelper::disableSpace(
$this->featureContext->getBaseUrl(),
$user,
$password,
$this->featureContext->getPasswordForUser($user),
$space["id"],
$headers,
$isVault,
);
}
@@ -3312,11 +3181,10 @@ class SpacesContext implements Context {
}
/**
* @Given /^user "([^"]*)" has disabled a space "([^"]*)"(| in vault)?$/
* @Given /^user "([^"]*)" has disabled a space "([^"]*)"$/
*
* @param string $user
* @param string $spaceName
* @param string $isVault
*
* @return void
* @throws GuzzleException
@@ -3324,10 +3192,8 @@ class SpacesContext implements Context {
public function sendUserHasDisabledSpaceRequest(
string $user,
string $spaceName,
string $isVault,
): void {
$isVault = trim($isVault) === 'in vault';
$response = $this->disableSpace($user, $spaceName, '', $isVault);
$response = $this->disableSpace($user, $spaceName);
$expectedHTTPStatus = "204";
$this->featureContext->theHTTPStatusCodeShouldBe(
$expectedHTTPStatus,
@@ -3368,7 +3234,6 @@ class SpacesContext implements Context {
* @param string $user
* @param string $spaceName
* @param string $owner
* @param boolean $isVault
*
* @return ResponseInterface
* @throws GuzzleException
@@ -3377,26 +3242,14 @@ class SpacesContext implements Context {
string $user,
string $spaceName,
string $owner = '',
bool $isVault = false,
): ResponseInterface {
$space = $this->getSpaceByName(($owner !== "") ? $owner : $user, $spaceName, $isVault);
$space = $this->getSpaceByName(($owner !== "") ? $owner : $user, $spaceName);
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$accessToken = $this->featureContext->getOcisUserToken(strtolower($user))['token']['accessToken'];
$headers['Authorization'] = 'Bearer ' . $accessToken;
$user = null;
$password = null;
} else {
$password = $this->featureContext->getPasswordForUser($user);
}
return GraphHelper::deleteSpace(
$this->featureContext->getBaseUrl(),
$user,
$password,
$this->featureContext->getPasswordForUser($user),
$space["id"],
$headers,
$isVault,
);
}
@@ -25,6 +25,7 @@ declare(strict_types=1);
use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use GuzzleHttp\Exception\GuzzleException;
use JsonException;
use PHPUnit\Framework\Assert;
use TestHelpers\BehatHelper;
use TestHelpers\KeycloakHelper;
@@ -182,531 +182,3 @@ Feature: vault
}
}
"""
Scenario: user copies folder from drive to vault
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
When user "Alice" copies folder "driveFolder" from space "Personal" to "driveFolder" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the space "Personal" in vault should contain these entries:
| driveFolder |
And for user "Alice" the space "Personal" should contain these entries:
| driveFolder |
Scenario: user copies file from drive to vault
Given user "Alice" has logged in via web UI
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "testfile.txt"
When user "Alice" copies file "testfile.txt" from space "Personal" to "testfile.txt" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the content of the file "testfile.txt" of the space "Personal" in vault should be "some content"
And for user "Alice" the space "Personal" should contain these entries:
| testfile.txt |
Scenario: user tries to copy folder from vault to drive
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "vaultFolder" in space "Personal" in vault
When user "Alice" copies folder "vaultFolder" from space "Personal" in vault to "vaultFolder" inside space "Personal" using the WebDAV API
Then the HTTP status code should be "409"
And for user "Alice" the space "Personal" should not contain these entries:
| vaultFolder |
And for user "Alice" the space "Personal" in vault should contain these entries:
| vaultFolder |
Scenario: user tries to copy file from vault to drive
Given user "Alice" has logged in via web UI
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "testfile.txt" in vault
When user "Alice" copies file "testfile.txt" from space "Personal" in vault to "testfile.txt" inside space "Personal" using the WebDAV API
Then the HTTP status code should be "409"
And for user "Alice" the space "Personal" should not contain these entries:
| testfile.txt |
And for user "Alice" the space "Personal" in vault should contain these entries:
| testfile.txt |
Scenario: user copies sub-folder from drive to vault
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
And user "Alice" has created a folder "driveFolder/subFolder" in space "Personal"
When user "Alice" copies folder "driveFolder/subFolder" from space "Personal" to "subFolder" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the space "Personal" in vault should contain these entries:
| subFolder |
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
| subFolder |
Scenario: user copies file inside folder from drive to vault
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "driveFolder/testfile.txt"
When user "Alice" copies file "driveFolder/testfile.txt" from space "Personal" to "testfile.txt" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the content of the file "testfile.txt" of the space "Personal" in vault should be "some content"
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
| testfile.txt |
Scenario: user copies sub-folder from drive to a folder in vault
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
And user "Alice" has created a folder "driveFolder/subFolder" in space "Personal"
And user "Alice" has created a folder "vaultFolder" in space "Personal" in vault
When user "Alice" copies folder "driveFolder/subFolder" from space "Personal" to "vaultFolder/subFolder" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" folder "vaultFolder" of the space "Personal" in vault should contain these entries:
| subFolder |
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
| subFolder |
Scenario: user copies file inside folder from drive to a folder in vault
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "driveFolder/testfile.txt"
And user "Alice" has created a folder "vaultFolder" in space "Personal" in vault
When user "Alice" copies file "driveFolder/testfile.txt" from space "Personal" to "vaultFolder/testfile.txt" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the content of the file "vaultFolder/testfile.txt" of the space "Personal" in vault should be "some content"
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
| testfile.txt |
Scenario Outline: send share invitation for project space in vault to user with different roles (permissions endpoint)
Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API
And user "Alice" has logged in via web UI
And user "Brian" has been created with default attributes
And user "Brian" has logged in via web UI
And user "Alice" has created a space "new-space" in vault with the default quota using the Graph API
When user "Alice" sends the following space share invitation using permissions endpoint of the Graph API:
| space | new-space |
| sharee | Brian |
| shareType | user |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "200"
And the JSON data of the response should match
"""
{
"type": "object",
"required": [
"value"
],
"properties": {
"value": {
"type": "array",
"minItems": 1,
"maxItems": 1,
"items": {
"type": "object",
"required": [
"grantedToV2",
"roles"
],
"properties": {
"grantedToV2": {
"type": "object",
"required": [
"user"
],
"properties": {
"user": {
"type": "object",
"required": [
"displayName",
"id"
],
"properties": {
"displayName": {
"const": "Brian Murphy"
},
"id": {
"type": "string",
"pattern": "^%user_id_pattern%$"
}
}
}
}
},
"roles": {
"type": "array",
"minItems": 1,
"maxItems": 1,
"items": {
"type": "string",
"pattern": "^%role_id_pattern%$"
}
}
}
}
}
}
}
"""
Examples:
| permissions-role |
| Space Viewer |
| Space Editor |
| Manager |
Scenario Outline: send share invitation for disabled project space in vault to user with different roles (permissions endpoint)
Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API
And user "Alice" has logged in via web UI
And user "Brian" has been created with default attributes
And user "Brian" has logged in via web UI
And user "Alice" has created a space "new-space" in vault with the default quota using the Graph API
And user "Admin" has disabled a space "new-space" in vault
When user "Alice" sends the following space share invitation using permissions endpoint of the Graph API:
| space | new-space |
| sharee | Brian |
| shareType | user |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "404"
And the JSON data of the response should match
"""
{
"type": "object",
"required": [
"error"
],
"properties": {
"error": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"const": "itemNotFound"
},
"message": {
"type": "string",
"pattern": "^stat: error: not found: %user_id_pattern%$"
}
}
}
}
}
"""
Examples:
| permissions-role |
| Space Viewer |
| Space Editor |
| Manager |
Scenario Outline: send share invitation for deleted project space in vault to user with different roles (permissions endpoint)
Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API
And user "Alice" has logged in via web UI
And user "Brian" has been created with default attributes
And user "Brian" has logged in via web UI
And user "Alice" has created a space "new-space" in vault with the default quota using the Graph API
And user "Admin" has disabled a space "new-space" in vault
And user "Admin" has deleted a space "new-space" in vault
When user "Alice" sends the following space share invitation using permissions endpoint of the Graph API:
| space | new-space |
| sharee | Brian |
| shareType | user |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "404"
And the JSON data of the response should match
"""
{
"type": "object",
"required": [
"error"
],
"properties": {
"error": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"const": "itemNotFound"
},
"message": {
"const": "stat: error: not found: "
}
}
}
}
}
"""
Examples:
| permissions-role |
| Space Viewer |
| Space Editor |
| Manager |
Scenario Outline: try to send share invitation for personal space in vault to user with different roles (permissions endpoint)
Given user "Alice" has logged in via web UI
And user "Brian" has been created with default attributes
And user "Brian" has logged in via web UI
When user "Alice" sends the following space share invitation using permissions endpoint of the Graph API:
| space | Personal |
| sharee | Brian |
| shareType | user |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "400"
And the JSON data of the response should match
"""
{
"type": "object",
"required": ["error"],
"properties": {
"error": {
"type": "object",
"required": ["code", "innererror", "message"],
"properties": {
"code": {
"const": "invalidRequest"
},
"innererror": {
"type": "object",
"required": [
"date",
"request-id"
]
},
"message": {
"const": "space type is not eligible for sharing"
}
}
}
}
}
"""
Examples:
| permissions-role |
| Space Viewer |
| Space Editor |
| Manager |
Scenario Outline: try to share Shares space in vault with a user (permissions endpoint)
Given user "Alice" has logged in via web UI
And user "Brian" has been created with default attributes
And user "Brian" has logged in via web UI
When user "Alice" sends the following space share invitation using permissions endpoint of the Graph API:
| space | Shares |
| sharee | Brian |
| shareType | user |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "400"
And the JSON data of the response should match
"""
{
"type": "object",
"required": ["error"],
"properties": {
"error": {
"type": "object",
"required": ["code", "innererror", "message"],
"properties": {
"code": {
"const": "invalidRequest"
},
"innererror": {
"type": "object",
"required": [
"date",
"request-id"
]
},
"message": {
"const": "<error-message>"
}
}
}
}
}
"""
Examples:
| permissions-role | error-message |
| Space Viewer | role not applicable to this resource |
| Space Editor | role not applicable to this resource |
| Manager | role not applicable to this resource |
Scenario Outline: invite user to a project space in vault with different roles using root endpoint
Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API
And user "Alice" has logged in via web UI
And user "Brian" has been created with default attributes
And user "Brian" has logged in via web UI
And user "Alice" has created a space "new-space" in vault with the default quota using the Graph API
When user "Alice" sends the following space share invitation using root endpoint of the Graph API:
| space | new-space |
| sharee | Brian |
| shareType | user |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "200"
And the JSON data of the response should match
"""
{
"type": "object",
"required": [
"value"
],
"properties": {
"value": {
"type": "array",
"minItems": 1,
"maxItems": 1,
"items": {
"type": "object",
"required": [
"grantedToV2",
"roles"
],
"properties": {
"grantedToV2": {
"type": "object",
"required": [
"user"
],
"properties": {
"user": {
"type": "object",
"required": [
"displayName",
"id"
],
"properties": {
"displayName": {
"type": "string",
"const": "Brian Murphy"
},
"id": {
"type": "string",
"pattern": "^%user_id_pattern%$"
}
}
}
}
},
"roles": {
"type": "array",
"minItems": 1,
"maxItems": 1,
"items": {
"type": "string",
"pattern": "^%role_id_pattern%$"
}
}
}
}
}
}
}
"""
Examples:
| permissions-role |
| Space Viewer |
| Space Editor |
| Manager |
Scenario Outline: try to invite user to personal drive in vault with different roles using root endpoint
Given user "Alice" has logged in via web UI
And user "Brian" has been created with default attributes
And user "Brian" has logged in via web UI
When user "Alice" tries to send the following space share invitation using root endpoint of the Graph API:
| space | Personal |
| sharee | Brian |
| shareType | user |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "400"
And the JSON data of the response should match
"""
{
"type": "object",
"required": ["error"],
"properties": {
"error": {
"type": "object",
"required": ["code", "innererror", "message"],
"properties": {
"code": {
"const": "invalidRequest"
},
"innererror": {
"type": "object",
"required": [
"date",
"request-id"
]
},
"message": {
"const": "unsupported space type"
}
}
}
}
}
"""
Examples:
| permissions-role |
| Space Viewer |
| Space Editor |
| Manager |
Scenario Outline: try to invite user to Shares drive in vault with different roles using root endpoint
Given user "Alice" has logged in via web UI
And user "Brian" has been created with default attributes
And user "Brian" has logged in via web UI
When user "Alice" tries to send the following space share invitation using root endpoint of the Graph API:
| space | Shares |
| sharee | Brian |
| shareType | user |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "400"
And the JSON data of the response should match
"""
{
"type": "object",
"required": ["error"],
"properties": {
"error": {
"type": "object",
"required": ["code", "innererror", "message"],
"properties": {
"code": {
"const": "invalidRequest"
},
"innererror": {
"type": "object",
"required": [
"date",
"request-id"
]
},
"message": {
"const": "unsupported space type"
}
}
}
}
}
"""
Examples:
| permissions-role |
| Space Viewer |
| Space Editor |
| Manager |
+3 -2
View File
@@ -112,9 +112,10 @@
"immutable": "5.1.8",
"js-cookie": "3.0.7",
"linkify-it": "5.0.2",
"minimatch": "10.2.5",
"brace-expansion": "5.0.8",
"minimatch@>=9.0.0 <9.0.7": "9.0.7",
"ws": "8.21.0",
"brace-expansion@1": "1.1.16",
"brace-expansion@2": "2.1.2",
"js-yaml": "4.3.0"
},
"patchedDependencies": {
@@ -110,113 +110,15 @@ describe('OcNotificationMessage', () => {
expect(wrapper.emitted('close')).toBeTruthy()
})
describe('actions prop', () => {
it('should not render actions if none are provided', () => {
const wrapper = getWrapper()
expect(wrapper.find(selectors.actionButton).exists()).toBeFalsy()
})
it('should render an action button for each action', () => {
const actions = [
{ label: 'Undo', ariaLabel: 'Undo delete', onClick: vi.fn() },
{ label: 'Retry', onClick: vi.fn() }
]
const wrapper = getWrapper({ actions })
const buttons = wrapper.findAll(selectors.actionButton)
expect(buttons.length).toBe(2)
expect(buttons[0].text()).toBe('Undo')
expect(buttons[0].attributes('aria-label')).toBe('Undo delete')
expect(buttons[1].attributes('aria-label')).toBe('Retry')
})
it('should call onClick when an action button is clicked', async () => {
const onClick = vi.fn()
const wrapper = getWrapper({ actions: [{ label: 'Undo', onClick }] })
await wrapper.find(selectors.actionButton).trigger('click')
expect(onClick).toHaveBeenCalledTimes(1)
})
it('should close the notification when an action button is clicked, so it cannot be clicked twice', async () => {
const onClick = vi.fn()
const wrapper = getWrapper({ actions: [{ label: 'Undo', onClick }] })
await wrapper.find(selectors.actionButton).trigger('click')
expect(wrapper.emitted('close')).toBeTruthy()
expect(wrapper.emitted('close').length).toBe(1)
})
it('should not move focus into the notification on mount', () => {
const wrapper = getWrapper(
{ actions: [{ label: 'Undo', onClick: vi.fn() }] },
{ attachTo: document.body }
)
expect(document.activeElement).toBe(document.body)
wrapper.unmount()
})
})
describe('auto-dismiss pause/resume', () => {
it('should pause the dismiss timer on hover and resume on mouse leave', async () => {
const wrapper = getWrapper({ timeout: 10 })
const interactiveEl = wrapper.find(selectors.interactiveWrapper)
await interactiveEl.trigger('mouseenter')
vi.advanceTimersByTime(10000)
expect(wrapper.emitted('close')).toBeFalsy()
await interactiveEl.trigger('mouseleave')
vi.advanceTimersByTime(10000)
expect(wrapper.emitted('close')).toBeTruthy()
})
it('should pause the dismiss timer on focus and resume on blur', async () => {
const wrapper = getWrapper({ timeout: 10 })
const interactiveEl = wrapper.find(selectors.interactiveWrapper)
await interactiveEl.trigger('focusin')
vi.advanceTimersByTime(10000)
expect(wrapper.emitted('close')).toBeFalsy()
await interactiveEl.trigger('focusout')
vi.advanceTimersByTime(10000)
expect(wrapper.emitted('close')).toBeTruthy()
})
it('should still auto-dismiss after hover and focus overlap (e.g. clicking a button)', async () => {
const wrapper = getWrapper({ timeout: 10 })
const interactiveEl = wrapper.find(selectors.interactiveWrapper)
// hover and focus both engage (as happens when clicking an action button by mouse)
await interactiveEl.trigger('mouseenter')
await interactiveEl.trigger('focusin')
// then only the mouse leaves, focus remains (e.g. keyboard user tabs through)
await interactiveEl.trigger('mouseleave')
vi.advanceTimersByTime(10000)
expect(wrapper.emitted('close')).toBeFalsy()
await interactiveEl.trigger('focusout')
vi.advanceTimersByTime(10000)
expect(wrapper.emitted('close')).toBeTruthy()
})
})
const selectors = {
messageTitle: '.oc-notification-message-title',
messageContent: '.oc-notification-message-content',
messageWrapper: '.oc-notification-message div',
interactiveWrapper: '.oc-notification-message-interactive',
errorLog: '.oc-error-log',
errorLogToggleButton: '.oc-notification-message-error-log-toggle-button',
actionButton: '.oc-notification-message-action-button'
errorLogToggleButton: '.oc-notification-message-error-log-toggle-button'
}
function getWrapper(props = {}, mountOptions = {}) {
function getWrapper(props = {}) {
return mount(OcNotificationMessage, {
props: {
...props,
@@ -227,8 +129,7 @@ describe('OcNotificationMessage', () => {
'oc-icon': true
},
plugins: defaultPlugins()
},
...mountOptions
}
})
}
})
@@ -4,40 +4,16 @@
:class="classes"
>
<div class="oc-flex oc-flex-wrap oc-flex-middle oc-flex-1" :role="role" :aria-live="ariaLive">
<div class="oc-flex oc-flex-middle oc-width-1-1">
<oc-icon :variation="iconVariation" name="information" fill-type="line" class="oc-mr-s" />
<div class="oc-notification-message-title oc-flex-1">
{{ title }}
</div>
<!-- eslint-disable-next-line vuejs-accessibility/no-static-element-interactions -->
<div
class="oc-notification-message-interactive oc-flex oc-flex-middle oc-ml-m"
@mouseenter="onMouseEnter"
@mouseleave="onMouseLeave"
@focusin="onFocusIn"
@focusout="onFocusOut"
>
<div v-if="actions.length" class="oc-notification-message-actions oc-flex oc-flex-middle">
<oc-button
v-for="(action, index) in actions"
:key="index"
appearance="raw"
variation="primary"
class="oc-notification-message-action-button"
:aria-label="action.ariaLabel || action.label"
@click="onActionClick(action)"
>
<span class="oc-notification-message-action-button-label">{{ action.label }}</span>
</oc-button>
<div class="oc-flex oc-flex-middle oc-flex-between oc-width-1-1">
<div class="oc-flex oc-flex-middle">
<oc-icon :variation="iconVariation" name="information" fill-type="line" class="oc-mr-s" />
<div class="oc-notification-message-title">
{{ title }}
</div>
<oc-button
class="oc-notification-message-close-button oc-ml-s"
appearance="raw"
:aria-label="$gettext('Close')"
@click="close"
><oc-icon name="close"
/></oc-button>
</div>
<oc-button appearance="raw" :aria-label="$gettext('Close')" @click="close"
><oc-icon name="close"
/></oc-button>
</div>
<div v-if="message || errorLogContent" class="oc-flex oc-flex-between oc-width-1-1 oc-mt-s">
<span
@@ -86,7 +62,6 @@ import OcErrorLog from '../OcErrorLog/OcErrorLog.vue'
* @props {string} [errorLogContent=null] - The error log content to display when the "Details" button is clicked.
* @props {number} [timeout=5] - The number of seconds the notification is displayed before auto-dismiss.
* If set to 0, the notification will not auto-dismiss.
* @props {array} [actions=[]] - Optional action buttons rendered in the notification, e.g. an "Undo" action.
*
* @emits {void} close - Emitted when the user clicks the close button or when the notification auto-dismisses.
*
@@ -101,19 +76,12 @@ import OcErrorLog from '../OcErrorLog/OcErrorLog.vue'
*
*/
export interface OcNotificationMessageAction {
label: string
ariaLabel?: string
onClick: () => void
}
interface Props {
status?: 'passive' | 'primary' | 'success' | 'warning' | 'danger'
title: string
message?: string
errorLogContent?: string
timeout?: number
actions?: OcNotificationMessageAction[]
}
interface Emits {
(e: 'close'): void
@@ -129,8 +97,7 @@ const {
title,
message = null,
errorLogContent = null,
timeout = 5,
actions = []
timeout = 5
} = defineProps<Props>()
const emit = defineEmits<Emits>()
@@ -144,11 +111,6 @@ function close() {
emit('close')
}
function onActionClick(action: OcNotificationMessageAction) {
action.onClick()
close()
}
const classes = computed(() => {
return `oc-notification-message-${status}`
})
@@ -165,57 +127,15 @@ const ariaLive = computed(() => {
return isStatusDanger.value ? 'assertive' : 'polite'
})
let remainingTime = timeout * 1000
let timeoutStartedAt = 0
let timeoutHandle: ReturnType<typeof setTimeout> = null
let isHovering = false
let isFocused = false
function startTimeout() {
if (timeout === 0 || remainingTime <= 0 || timeoutHandle || isHovering || isFocused) {
return
}
timeoutStartedAt = Date.now()
timeoutHandle = setTimeout(() => {
timeoutHandle = null
close()
}, remainingTime)
}
function pauseTimeout() {
if (timeout === 0 || !timeoutHandle) {
return
}
clearTimeout(timeoutHandle)
timeoutHandle = null
remainingTime -= Date.now() - timeoutStartedAt
}
function onMouseEnter() {
isHovering = true
pauseTimeout()
}
function onMouseLeave() {
isHovering = false
startTimeout()
}
function onFocusIn() {
isFocused = true
pauseTimeout()
}
function onFocusOut() {
isFocused = false
startTimeout()
}
onMounted(() => {
/**
* Notification will be destroyed if timeout is set
*/
startTimeout()
if (timeout !== 0) {
setTimeout(() => {
close()
}, timeout * 1000)
}
})
</script>
@@ -228,19 +148,10 @@ onMounted(() => {
&-title {
font-size: 1.15rem;
min-width: 0;
}
&-error-log-toggle-button {
word-break: keep-all;
}
&-interactive {
flex-shrink: 0;
}
&-action-button-label {
white-space: nowrap;
}
}
</style>
@@ -1,44 +0,0 @@
<template>
<div>
<p class="oc-mt-rm oc-mb-rm" v-text="message" />
<p
v-if="currentUserSelected"
class="delete-user-own-account-hint oc-mt-s oc-mb-rm"
v-text="$gettext('Your own account will not be deleted.')"
/>
</div>
</template>
<script lang="ts" setup>
import { computed } from 'vue'
import { useGettext } from 'vue3-gettext'
import { User } from '@ownclouders/web-client/graph/generated'
import { Modal, useUserStore } from '@ownclouders/web-pkg'
interface Props {
modal: Modal
users: User[]
}
const props = defineProps<Props>()
const { $gettext, $ngettext } = useGettext()
const userStore = useUserStore()
const currentUserSelected = computed(() =>
props.users.some((user) => user.id === userStore.user.id)
)
const message = computed(() =>
$ngettext(
'Are you sure you want to delete this user?',
'Are you sure you want to delete the %{userCount} selected users?',
props.users.length,
{ userCount: props.users.length.toString() }
)
)
</script>
<style lang="scss" scoped>
.delete-user-own-account-hint {
color: var(--oc-color-swatch-warning-default);
}
</style>
@@ -4,15 +4,13 @@ import {
useCapabilityStore,
useMessages,
useModals,
useRouteQuery,
useUserStore
useRouteQuery
} from '@ownclouders/web-pkg'
import { useClientService } from '@ownclouders/web-pkg'
import { UserAction, UserActionOptions } from '@ownclouders/web-pkg'
import { useGettext } from 'vue3-gettext'
import { User } from '@ownclouders/web-client/graph/generated'
import { useUserSettingsStore } from '../../stores/userSettings'
import DeleteUserModal from '../../../components/Users/DeleteUserModal.vue'
export const useUserActionsDelete = () => {
const { showMessage, showErrorMessage } = useMessages()
@@ -20,7 +18,6 @@ export const useUserActionsDelete = () => {
const { $gettext, $ngettext } = useGettext()
const clientService = useClientService()
const { dispatchModal } = useModals()
const userStore = useUserStore()
const userSettingsStore = useUserSettingsStore()
const currentPageQuery = useRouteQuery('page', '1')
@@ -34,18 +31,15 @@ export const useUserActionsDelete = () => {
})
const deleteUsers = async (users: User[]) => {
const affectedUsers = users.filter((user) => user.id !== userStore.user.id)
const graphClient = clientService.graphAuthenticated
const promises = affectedUsers.map((user) => graphClient.users.deleteUser(user.id))
const promises = users.map((user) => graphClient.users.deleteUser(user.id))
const results = await Promise.allSettled(promises)
const succeeded = results.filter((r) => r.status === 'fulfilled')
if (succeeded.length) {
const title =
succeeded.length === 1 && affectedUsers.length === 1
? $gettext('User "%{user}" was deleted successfully', {
user: affectedUsers[0].displayName
})
succeeded.length === 1 && users.length === 1
? $gettext('User "%{user}" was deleted successfully', { user: users[0].displayName })
: $ngettext(
'%{userCount} user was deleted successfully',
'%{userCount} users were deleted successfully',
@@ -60,8 +54,8 @@ export const useUserActionsDelete = () => {
failed.forEach(console.error)
const title =
failed.length === 1 && affectedUsers.length === 1
? $gettext('Failed to delete user "%{user}"', { user: affectedUsers[0].displayName })
failed.length === 1 && users.length === 1
? $gettext('Failed to delete user "%{user}"', { user: users[0].displayName })
: $ngettext(
'Failed to delete %{userCount} user',
'Failed to delete %{userCount} users',
@@ -74,7 +68,7 @@ export const useUserActionsDelete = () => {
})
}
userSettingsStore.removeUsers(affectedUsers)
userSettingsStore.removeUsers(users)
userSettingsStore.setSelectedUsers([])
const pageCount = Math.ceil(userSettingsStore.users.length / unref(itemsPerPage))
@@ -96,8 +90,14 @@ export const useUserActionsDelete = () => {
userCount: resources.length.toString()
}),
confirmText: $gettext('Delete'),
customComponent: DeleteUserModal,
customComponentAttrs: () => ({ users: resources }),
message: $ngettext(
'Are you sure you want to delete this user?',
'Are you sure you want to delete the %{userCount} selected users?',
resources.length,
{
userCount: resources.length.toString()
}
),
hasInput: false,
onConfirm: () => deleteUsers(resources)
})
@@ -1,35 +0,0 @@
import DeleteUserModal from '../../../../src/components/Users/DeleteUserModal.vue'
import { defaultComponentMocks, defaultPlugins, shallowMount } from '@ownclouders/web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { User } from '@ownclouders/web-client/graph/generated'
import { Modal } from '@ownclouders/web-pkg'
describe('DeleteUserModal', () => {
it('shows a hint when the current user is part of the selection', () => {
// the default mocked user store uses id '1'
const { wrapper } = getWrapper([mock<User>({ id: '1' }), mock<User>({ id: '2' })])
expect(wrapper.find('.delete-user-own-account-hint').exists()).toBe(true)
})
it('does not show a hint when the current user is not part of the selection', () => {
const { wrapper } = getWrapper([mock<User>({ id: '2' })])
expect(wrapper.find('.delete-user-own-account-hint').exists()).toBe(false)
})
})
function getWrapper(users = [mock<User>()]) {
const mocks = defaultComponentMocks()
return {
mocks,
wrapper: shallowMount(DeleteUserModal, {
props: {
modal: mock<Modal>(),
users
},
global: {
provide: mocks,
plugins: [...defaultPlugins()]
}
})
}
}
@@ -1,10 +1,8 @@
import { useUserActionsDelete } from '../../../../../src/composables/actions/users/useUserActionsDelete'
import DeleteUserModal from '../../../../../src/components/Users/DeleteUserModal.vue'
import { mock } from 'vitest-mock-extended'
import { Mock } from 'vitest'
import { unref } from 'vue'
import { User } from '@ownclouders/web-client/graph/generated'
import { useCapabilityStore, useModals } from '@ownclouders/web-pkg'
import { useCapabilityStore } from '@ownclouders/web-pkg'
import {
defaultComponentMocks,
getComposableWrapper,
@@ -57,58 +55,11 @@ describe('useUserActionsDelete', () => {
}
})
})
it('should not delete the current user when included in the selection', () => {
getWrapper({
currentUserId: 'self',
setup: async ({ deleteUsers }, { clientService }) => {
const currentUser = mock<User>({ id: 'self' })
const otherUser = mock<User>({ id: 'other' })
await deleteUsers([currentUser, otherUser])
expect(clientService.graphAuthenticated.users.deleteUser).toHaveBeenCalledWith(
otherUser.id
)
expect(clientService.graphAuthenticated.users.deleteUser).not.toHaveBeenCalledWith(
currentUser.id
)
}
})
})
it('should do nothing when the current user is the only selected user', () => {
getWrapper({
currentUserId: 'self',
setup: async ({ deleteUsers }, { clientService }) => {
const currentUser = mock<User>({ id: 'self' })
await deleteUsers([currentUser])
expect(clientService.graphAuthenticated.users.deleteUser).not.toHaveBeenCalled()
}
})
})
})
describe('method "handler"', () => {
it('dispatches the delete modal with the selected users', () => {
getWrapper({
setup: ({ actions }) => {
const { dispatchModal } = useModals()
const resources = [mock<User>({ id: 'self' }), mock<User>({ id: 'other' })]
unref(actions)[0].handler({ resources })
expect(dispatchModal).toHaveBeenCalledWith(
expect.objectContaining({
variation: 'danger',
customComponent: DeleteUserModal,
customComponentAttrs: expect.any(Function)
})
)
const attrs = (dispatchModal as unknown as Mock).mock.calls[0][0].customComponentAttrs()
expect(attrs.users).toEqual(resources)
}
})
})
})
})
function getWrapper({
setup,
currentUserId = '0'
setup
}: {
setup: (
instance: ReturnType<typeof useUserActionsDelete>,
@@ -118,7 +69,6 @@ function getWrapper({
clientService: ReturnType<typeof defaultComponentMocks>['$clientService']
}
) => void
currentUserId?: string
}) {
const mocks = defaultComponentMocks()
return {
@@ -127,15 +77,7 @@ function getWrapper({
const instance = useUserActionsDelete()
setup(instance, { clientService: mocks.$clientService })
},
{
mocks,
provide: mocks,
pluginOptions: {
piniaOptions: {
userState: { user: { id: currentUserId } as User }
}
}
}
{ mocks, provide: mocks }
)
}
}
@@ -1,41 +0,0 @@
# EPUB Reader and Library
The ownCloud Web EPUB app combines the built-in EPUB reader with a visual library for books
stored across accessible personal and project spaces.
## Library features
- Discover EPUB files across accessible spaces
- Extract embedded metadata and cover images in the browser
- Search by title, author, publisher, or subject
- Sort and filter by collection, reading status, author, subject, language, and space
- Organize books with favorites and custom shelves
- Switch between grid and list layouts
- Continue from the location saved by the EPUB reader
- Open the containing folder, download a book, or copy its private link
- Cache metadata and covers in IndexedDB
EPUB contents and metadata are not sent to an external metadata service. Favorites, shelves,
reading-status labels, and the selected layout are stored in browser local storage and do not
currently synchronize between browsers or devices.
## Usage
1. Upload EPUB files through the Files app.
2. Open **Library** from the application switcher.
3. Select a cover to open the book, or use its information button for metadata and file actions.
4. Use search, sorting, and filters to organize the library.
The library combines WebDAV search with a recursive scan so newly uploaded books can appear
before search indexing completes. Metadata cache entries are invalidated when file metadata
changes.
## Development
Run commands from the `web` directory:
```bash
pnpm --filter epub-reader test:unit -- --run
pnpm check:types
pnpm eslint 'packages/web-app-epub-reader/**/*.{ts,vue}' --max-warnings=0
```
@@ -8,9 +8,7 @@
"test:unit": "NODE_OPTIONS=--unhandled-rejections=throw vitest"
},
"dependencies": {
"@zip.js/zip.js": "2.8.33",
"epubjs": "^0.3.93",
"focus-trap-vue": "^4.1.0"
"epubjs": "^0.3.93"
},
"devDependencies": {
"@ownclouders/web-test-helpers": "workspace:*"
@@ -1,535 +0,0 @@
<template>
<div class="book-details-backdrop">
<button
type="button"
class="backdrop-dismiss"
tabindex="-1"
:aria-label="$gettext('Close book details')"
@click="emit('close')"
/>
<!-- eslint-disable vuejs-accessibility/no-static-element-interactions -->
<focus-trap :active="true">
<aside
class="book-details oc-background-default oc-box-shadow-large"
role="dialog"
aria-modal="true"
aria-labelledby="book-details-title"
tabindex="-1"
@keydown.esc="emit('close')"
>
<header class="details-header oc-flex oc-flex-between oc-flex-middle oc-p-m">
<h2 id="book-details-title" class="oc-m-rm">{{ $gettext('Book details') }}</h2>
<oc-button appearance="raw" :aria-label="$gettext('Close')" @click="emit('close')">
<oc-icon name="close" />
</oc-button>
</header>
<div class="details-content oc-p-m">
<div class="details-hero">
<div class="details-cover">
<img v-if="book.coverUrl" :src="book.coverUrl" :alt="''" />
<div v-else class="details-cover-fallback">
<oc-icon name="book" size="xlarge" />
<span>{{ book.title }}</span>
</div>
</div>
<div class="details-hero-copy">
<button
type="button"
class="favorite-button"
:class="{ 'favorite-button-active': book.favorite }"
:aria-label="book.favorite ? $gettext('Remove favorite') : $gettext('Add favorite')"
:aria-pressed="book.favorite"
@click="emit('toggle-favorite')"
>
<oc-icon name="star" size="small" variation="inherit" />
<span>{{ book.favorite ? $gettext('Favorited') : $gettext('Favorite') }}</span>
</button>
<h3 class="oc-mb-xs">{{ book.title }}</h3>
<p class="oc-text-muted oc-m-rm">
{{ book.authors.join(', ') || $gettext('Unknown author') }}
</p>
<p v-if="book.published" class="oc-text-muted oc-mt-xs">
{{ book.published }}
</p>
<span class="status-badge oc-mt-s">{{ currentStatusLabel }}</span>
</div>
</div>
<div class="primary-action oc-mt-l">
<oc-button class="reading-action" @click="emit('open')">
<oc-icon name="book" size="small" />
{{ openActionLabel }}
</oc-button>
</div>
<div class="secondary-actions oc-flex oc-mt-s oc-mb-l">
<oc-button appearance="outline" @click="emit('show-in-files')">
<oc-icon name="folder" size="small" />
{{ $gettext('Show in folder') }}
</oc-button>
<oc-button appearance="outline" @click="emit('download')">
<oc-icon name="download" size="small" />
{{ $gettext('Download') }}
</oc-button>
<oc-button appearance="outline" @click="emit('copy-link')">
<oc-icon name="link" size="small" />
<span aria-live="polite">{{
copied ? $gettext('Copied') : $gettext('Copy link')
}}</span>
</oc-button>
</div>
<section v-if="book.description" class="details-section description-section">
<h3>{{ $gettext('About this book') }}</h3>
<p class="details-description">{{ book.description }}</p>
</section>
<section class="organization-card oc-mt-l">
<div class="organization-block">
<fieldset class="status-fieldset">
<legend>{{ $gettext('Reading status') }}</legend>
<div class="status-options">
<label
v-for="option in statusOptions"
:key="option.value"
class="status-option"
:class="{ 'status-option-selected': book.readingStatus === option.value }"
>
<input
type="radio"
name="epub-reading-status"
:value="option.value"
:checked="book.readingStatus === option.value"
@change="emit('set-status', option.value)"
/>
<span>{{ option.label }}</span>
</label>
</div>
</fieldset>
</div>
<div class="organization-block shelves-block">
<h3>{{ $gettext('Shelves') }}</h3>
<p v-if="!shelves.length" class="oc-text-muted">
{{ $gettext('Create a shelf to organize this book.') }}
</p>
<div v-else class="shelf-options oc-flex oc-flex-wrap">
<label v-for="shelf in shelves" :key="shelf.id" class="shelf-option">
<input
type="checkbox"
:checked="book.shelfIds.includes(shelf.id)"
@change="emit('toggle-shelf', shelf.id)"
/>
<span>{{ shelf.name }}</span>
</label>
</div>
<div class="new-shelf oc-flex oc-mt-m">
<oc-text-input
v-model="newShelfName"
:label="$gettext('New shelf')"
:placeholder="$gettext('Shelf name')"
@keydown.enter="createShelf"
/>
<oc-button
class="add-shelf-button"
size="small"
variant="primary"
:disabled="!newShelfName.trim()"
@click="createShelf"
>
{{ $gettext('Add shelf') }}
</oc-button>
</div>
</div>
</section>
<section v-if="hasPublicationMetadata" class="details-section oc-mt-l">
<h3>{{ $gettext('Publication') }}</h3>
<dl class="book-metadata">
<template v-if="book.publisher">
<dt>{{ $gettext('Publisher') }}</dt>
<dd>{{ book.publisher }}</dd>
</template>
<template v-if="book.language">
<dt>{{ $gettext('Language') }}</dt>
<dd>{{ book.language }}</dd>
</template>
<template v-if="book.subjects.length">
<dt>{{ $gettext('Subjects') }}</dt>
<dd>{{ book.subjects.join(', ') }}</dd>
</template>
</dl>
</section>
<details class="file-details oc-mt-l">
<summary>{{ $gettext('File details') }}</summary>
<dl class="file-metadata">
<dt>{{ $gettext('File name') }}</dt>
<dd>{{ book.resource.name }}</dd>
<dt>{{ $gettext('Location') }}</dt>
<dd>{{ locationLabel }}</dd>
<dt v-if="book.resource.size">{{ $gettext('Size') }}</dt>
<dd v-if="book.resource.size">{{ formattedSize }}</dd>
</dl>
</details>
</div>
</aside>
</focus-trap>
<!-- eslint-enable vuejs-accessibility/no-static-element-interactions -->
</div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useGettext } from 'vue3-gettext'
import { FocusTrap } from 'focus-trap-vue'
import type { LibraryBook, LibraryShelf, ReadingStatus } from '../types'
const props = defineProps<{ book: LibraryBook; copied?: boolean; shelves: LibraryShelf[] }>()
const emit = defineEmits<{
(event: 'close' | 'open' | 'show-in-files' | 'download' | 'copy-link'): void
(event: 'toggle-favorite'): void
(event: 'set-status', status: ReadingStatus): void
(event: 'toggle-shelf', shelfId: string): void
(event: 'create-shelf', name: string): void
}>()
const { $gettext } = useGettext()
const newShelfName = ref('')
const statusOptions: { label: string; value: ReadingStatus }[] = [
{ label: $gettext('Unread'), value: 'unread' },
{ label: $gettext('Reading'), value: 'reading' },
{ label: $gettext('Finished'), value: 'finished' }
]
const currentStatusLabel = computed(
() => statusOptions.find(({ value }) => value === props.book.readingStatus)?.label ?? ''
)
const hasPublicationMetadata = computed(() =>
Boolean(props.book.publisher || props.book.language || props.book.subjects.length)
)
const openActionLabel = computed(() => {
if (props.book.readingProgress === 100) return $gettext('Open finished book')
if (!props.book.hasReadingPosition) return $gettext('Start reading')
if (props.book.readingProgress === undefined) return $gettext('Continue reading')
return $gettext('Continue reading · %{progress}%', {
progress: String(props.book.readingProgress)
})
})
const locationLabel = computed(() => {
const path = props.book.resource.path.replace(/^\/+/, '')
return path ? `${props.book.space.name} / ${path}` : props.book.space.name
})
const formattedSize = computed(() => {
const bytes = Number(props.book.resource.size || 0)
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
})
function createShelf(): void {
const name = newShelfName.value.trim()
if (!name) return
emit('create-shelf', name)
newShelfName.value = ''
}
</script>
<style scoped>
.book-details-backdrop {
backdrop-filter: blur(2px);
background: rgb(0 0 0 / 32%);
display: flex;
inset: 0;
justify-content: flex-end;
position: fixed;
z-index: 1000;
}
.book-details {
border-radius: 14px 0 0 14px;
height: 100%;
max-width: 100%;
overflow-y: auto;
position: relative;
width: 34rem;
z-index: 1;
}
.backdrop-dismiss {
background: transparent;
border: 0;
cursor: default;
inset: 0;
padding: 0;
position: absolute;
}
.details-header {
background: var(--oc-color-background-default);
border-bottom: 1px solid var(--oc-color-background-muted);
position: sticky;
top: 0;
z-index: 1;
}
.details-hero {
align-items: start;
display: grid;
gap: var(--oc-space-medium);
grid-template-columns: 8rem minmax(0, 1fr);
padding: var(--oc-space-medium);
background: var(--oc-color-background-muted);
border-radius: 12px;
position: relative;
}
.details-hero-copy h3 {
padding-right: 7rem;
}
.favorite-button {
align-items: center;
background: var(--oc-color-background-default);
border: 1px solid var(--oc-color-swatch-passive-default);
border-radius: 999px;
color: inherit;
cursor: pointer;
display: inline-flex;
gap: var(--oc-space-xsmall);
min-height: 2rem;
padding: 0 var(--oc-space-small);
position: absolute;
right: var(--oc-space-small);
top: var(--oc-space-small);
}
.favorite-button-active {
background: var(--oc-color-swatch-primary-default);
border-color: var(--oc-color-swatch-primary-default);
color: var(--oc-color-swatch-primary-contrast);
}
.favorite-button:focus-visible {
outline: 3px solid var(--oc-color-swatch-primary-default);
outline-offset: 2px;
}
.favorite-button:hover {
border-color: var(--oc-color-swatch-primary-default);
box-shadow: 0 0 0 2px var(--oc-color-background-highlight);
}
.details-cover {
aspect-ratio: 2 / 3;
background: var(--oc-color-background-muted);
border-radius: 8px;
overflow: hidden;
box-shadow: 0 3px 8px 1px rgb(0 0 0 / 14%);
}
.details-cover img {
height: 100%;
object-fit: cover;
width: 100%;
}
.details-cover-fallback {
align-items: center;
display: flex;
flex-direction: column;
gap: var(--oc-space-small);
height: 100%;
justify-content: center;
padding: var(--oc-space-small);
text-align: center;
}
.secondary-actions {
gap: var(--oc-space-small);
}
.reading-action {
justify-content: center;
width: 100%;
}
.secondary-actions > * {
flex: 1;
}
.status-badge {
background: var(--oc-color-swatch-primary-default);
border-radius: 999px;
color: var(--oc-color-swatch-primary-contrast);
display: inline-flex;
font-size: var(--oc-font-size-small);
font-weight: 600;
padding: var(--oc-space-xsmall) var(--oc-space-small);
}
.new-shelf {
gap: var(--oc-space-small);
}
.organization-card {
background: var(--oc-color-background-muted);
border-radius: 10px;
padding: var(--oc-space-medium);
}
.status-fieldset {
border: 0;
margin: 0;
padding: 0;
}
.status-fieldset legend {
font-weight: 600;
margin-bottom: var(--oc-space-small);
}
.status-options {
display: grid;
gap: var(--oc-space-small);
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.status-option {
align-items: center;
background: var(--oc-color-background-default);
border: 2px solid transparent;
border-radius: 8px;
cursor: pointer;
display: grid;
gap: var(--oc-space-small);
grid-template-columns: auto minmax(0, 1fr) auto;
min-height: 2.75rem;
padding: 0 var(--oc-space-small);
}
.status-option:hover {
border-color: var(--oc-color-swatch-primary-default);
box-shadow: 0 0 0 2px var(--oc-color-background-highlight);
}
.status-option:focus-within {
outline: 3px solid var(--oc-color-swatch-primary-default);
outline-offset: 2px;
}
.status-option-selected {
background: var(--oc-color-background-highlight);
border-color: var(--oc-color-swatch-primary-default);
font-weight: 600;
}
.organization-block + .organization-block {
border-top: 1px solid var(--oc-color-background-default);
margin-top: var(--oc-space-medium);
padding-top: var(--oc-space-medium);
}
.new-shelf {
align-items: end;
}
.new-shelf > :first-child {
flex: 1;
}
.add-shelf-button {
min-height: 2.5rem;
}
.add-shelf-button:hover:not(:disabled) {
box-shadow: 0 0 0 3px var(--oc-color-background-highlight);
filter: brightness(0.88);
}
.add-shelf-button:focus-visible {
outline: 3px solid var(--oc-color-swatch-primary-default);
outline-offset: 2px;
}
.shelf-options {
gap: var(--oc-space-small);
}
.shelf-option {
align-items: center;
display: flex;
gap: var(--oc-space-small);
background: var(--oc-color-background-default);
border-radius: 999px;
cursor: pointer;
padding: var(--oc-space-xsmall) var(--oc-space-small);
}
.shelf-option:hover {
box-shadow: inset 0 0 0 2px var(--oc-color-swatch-primary-default);
}
.shelf-option:focus-within {
outline: 3px solid var(--oc-color-swatch-primary-default);
outline-offset: 2px;
}
.details-description {
line-height: 1.6;
white-space: pre-line;
}
.book-metadata,
.file-metadata {
display: grid;
gap: var(--oc-space-small) var(--oc-space-medium);
grid-template-columns: max-content minmax(0, 1fr);
}
.book-metadata {
margin: 0;
}
.file-details {
background: var(--oc-color-background-muted);
border-radius: 10px;
padding: var(--oc-space-medium);
}
.file-details summary {
cursor: pointer;
font-weight: 600;
}
.file-metadata {
margin: var(--oc-space-medium) 0 0;
}
.book-metadata dt,
.file-metadata dt {
font-weight: 600;
}
.book-metadata dd,
.file-metadata dd {
margin: 0;
overflow-wrap: anywhere;
}
@media (max-width: 520px) {
.book-details {
width: 100%;
}
.status-options {
grid-template-columns: 1fr;
}
.secondary-actions {
flex-wrap: wrap;
}
.secondary-actions > * {
flex: 1 0 45%;
}
}
</style>
@@ -1,334 +0,0 @@
import type { Resource, SpaceResource } from '@ownclouders/web-client'
import { DavProperties } from '@ownclouders/web-client/webdav'
import {
encodePath,
useCapabilityStore,
useClientService,
useClipboard,
useDownloadFile,
useFolderLink,
useMessages,
useRouter,
useSpacesStore
} from '@ownclouders/web-pkg'
import { computed, onUnmounted, ref } from 'vue'
import { useGettext } from 'vue3-gettext'
import type { LibraryBook, LibraryShelf, LibrarySort, ReadingStatus } from '../types'
import { getCachedMetadata, setCachedMetadata } from '../utils/cache'
import { extractEpubMetadata, titleFromFileName } from '../utils/epub'
import {
getBookPreferences,
loadShelves,
saveBookPreferences,
saveShelves
} from '../utils/preferences'
import { getReaderProgress } from '../utils/readerProgress'
const SEARCH_LIMIT = 500
const METADATA_WORKERS = 4
const MAX_SCANNED_FOLDERS = 2000
const EPUB_SEARCH_PATTERN = 'name:*.epub'
export function useLibrary() {
const { $gettext } = useGettext()
const { showErrorMessage } = useMessages()
const clientService = useClientService()
const capabilityStore = useCapabilityStore()
const spacesStore = useSpacesStore()
const router = useRouter()
const { downloadFile } = useDownloadFile()
const { copyToClipboard } = useClipboard()
const { getParentFolderLink } = useFolderLink()
const searchAvailable = computed(() => !!capabilityStore.davReports?.includes('search-files'))
const books = ref<LibraryBook[]>([])
const loading = ref(false)
const error = ref('')
const query = ref('')
const sort = ref<LibrarySort>('recent')
const shelves = ref<LibraryShelf[]>(loadShelves())
const visibleBooks = computed(() => {
const needle = query.value.trim().toLocaleLowerCase()
const filtered = needle
? books.value.filter((book) =>
[book.title, ...book.authors, book.publisher, ...book.subjects]
.join(' ')
.toLocaleLowerCase()
.includes(needle)
)
: [...books.value]
return filtered.sort((left, right) => {
if (sort.value === 'title') return left.title.localeCompare(right.title)
if (sort.value === 'author') {
return (left.authors[0] ?? '').localeCompare(right.authors[0] ?? '')
}
return (
new Date(right.resource.mdate ?? 0).getTime() - new Date(left.resource.mdate ?? 0).getTime()
)
})
})
async function searchBooks(): Promise<Resource[]> {
const { resources } = await clientService.webdav.search(EPUB_SEARCH_PATTERN, {
searchLimit: SEARCH_LIMIT,
davProperties: DavProperties.Default
})
return resources.filter((resource) => resource.name.toLowerCase().endsWith('.epub'))
}
async function scanSpace(space: SpaceResource): Promise<Resource[]> {
const pendingPaths = [space.path || '/']
const visitedPaths = new Set<string>()
const epubs: Resource[] = []
while (pendingPaths.length && visitedPaths.size < MAX_SCANNED_FOLDERS) {
const path = pendingPaths.shift()!
if (visitedPaths.has(path)) continue
visitedPaths.add(path)
const { children } = await clientService.webdav.listFiles(space, { path }, { depth: 1 })
for (const resource of children ?? []) {
if (resource.isFolder || resource.type === 'folder') {
if (resource.path && !visitedPaths.has(resource.path)) pendingPaths.push(resource.path)
continue
}
if (!resource.name.toLowerCase().endsWith('.epub')) continue
epubs.push({
...resource,
mimeType: resource.mimeType || 'application/epub+zip',
spaceId: resource.spaceId || space.id,
storageId: resource.storageId || space.id
})
}
}
if (visitedPaths.size >= MAX_SCANNED_FOLDERS && pendingPaths.length) {
console.warn(
`EPUB library scan reached the ${MAX_SCANNED_FOLDERS} folder limit in "${space.name}"; results may be incomplete.`
)
}
return epubs
}
async function scanSpaces(spaces: SpaceResource[]): Promise<Resource[]> {
const results = await Promise.allSettled(spaces.map(scanSpace))
const discovered = results.flatMap((result) =>
result.status === 'fulfilled' ? result.value : []
)
if (!discovered.length && results.every((result) => result.status === 'rejected')) {
throw (results[0] as PromiseRejectedResult).reason
}
return discovered
}
async function discoverBooks(spaces: SpaceResource[]): Promise<Resource[]> {
// Prefer the server-side search REPORT (fast, one request). Only walk every
// folder as a fallback when the server lacks search-files support or the
// search request fails, rather than always paying for both.
if (searchAvailable.value) {
try {
return await searchBooks()
} catch (cause) {
console.warn('EPUB library search failed, falling back to folder scan', cause)
}
}
return scanSpaces(spaces)
}
async function hydrateBook(book: LibraryBook): Promise<void> {
try {
const cachedMetadata = await getCachedMetadata(book.resource)
if (cachedMetadata) {
Object.assign(book, cachedMetadata)
updateReaderProgress(book)
return
}
const { response } = await clientService.webdav.getFileContents(
book.space,
{ path: book.resource.path },
{ responseType: 'blob' }
)
const metadata = await extractEpubMetadata(response.data as Blob, book.title)
Object.assign(book, metadata)
updateReaderProgress(book)
await setCachedMetadata(book.resource, metadata)
} catch (cause) {
console.warn(`Could not read EPUB metadata for ${book.resource.name}`, cause)
book.metadataError = $gettext('Metadata could not be read')
} finally {
book.loadingMetadata = false
}
}
function updateReaderProgress(book: LibraryBook): void {
const readerProgress = getReaderProgress(book.resource, book.spineItemCount)
book.hasReadingPosition = readerProgress.hasPosition
book.readingProgress = readerProgress.percentage
if (readerProgress.finished && book.readingStatus !== 'finished') {
book.readingStatus = 'finished'
persistBook(book)
}
}
async function hydrateBooks(items: LibraryBook[]): Promise<void> {
let next = 0
async function worker() {
while (next < items.length) {
const book = items[next++]
await hydrateBook(book)
}
}
await Promise.all(Array.from({ length: Math.min(METADATA_WORKERS, items.length) }, worker))
}
async function loadBooks(): Promise<void> {
if (loading.value) return
loading.value = true
error.value = ''
books.value.forEach((book) => book.coverUrl && URL.revokeObjectURL(book.coverUrl))
books.value = []
try {
const spaces = (spacesStore.spaces as SpaceResource[]).filter((space) => space.id)
if (!spaces.length) throw new Error($gettext('No file spaces are available'))
const spaceById = new Map(spaces.map((space) => [space.id, space]))
const discovered = await discoverBooks(spaces)
const resources = [
...new Map(
discovered
.filter((resource) => spaceById.has(resource.spaceId || resource.storageId || ''))
.map((resource) => [resource.id, resource])
).values()
]
books.value = resources.map((resource) => {
const preferences = getBookPreferences(resource)
const readerProgress = getReaderProgress(resource)
return {
id: resource.fileId || resource.id,
resource,
space: spaceById.get(resource.spaceId || resource.storageId || '')!,
title: titleFromFileName(resource.name),
authors: [],
description: '',
language: '',
publisher: '',
published: '',
subjects: [],
spineItemCount: 0,
loadingMetadata: true,
hasReadingPosition: readerProgress.hasPosition,
readingProgress: readerProgress.percentage,
...preferences
}
})
await hydrateBooks(books.value)
} catch (cause) {
error.value =
cause instanceof Error ? cause.message : $gettext('The library could not be loaded')
} finally {
loading.value = false
}
}
function openBook(book: LibraryBook): void {
const driveAliasAndItem = book.space.getDriveAliasAndItem(book.resource)
router.push(`/epub-reader/read/${encodePath(driveAliasAndItem)}`)
}
function showBookInFiles(book: LibraryBook): void {
router.push(getParentFolderLink(book.resource))
}
function downloadBook(book: LibraryBook): Promise<void> {
return downloadFile(book.space, book.resource)
}
async function copyBookLink(book: LibraryBook): Promise<boolean> {
const privateLink = book.resource.privateLink
if (!privateLink) {
showErrorMessage({ title: $gettext('The link could not be copied') })
return false
}
try {
await copyToClipboard(privateLink)
return true
} catch (cause) {
console.error(cause)
showErrorMessage({ title: $gettext('The link could not be copied'), errors: [cause] })
return false
}
}
function persistBook(book: LibraryBook): void {
saveBookPreferences(book.resource, {
favorite: book.favorite,
readingStatus: book.readingStatus,
shelfIds: book.shelfIds
})
}
function toggleFavorite(book: LibraryBook): void {
book.favorite = !book.favorite
persistBook(book)
}
function setReadingStatus(book: LibraryBook, status: ReadingStatus): void {
book.readingStatus = status
persistBook(book)
}
function toggleBookShelf(book: LibraryBook, shelfId: string): void {
book.shelfIds = book.shelfIds.includes(shelfId)
? book.shelfIds.filter((id) => id !== shelfId)
: [...book.shelfIds, shelfId]
persistBook(book)
}
function createShelf(name: string): LibraryShelf | null {
const trimmedName = name.trim()
if (!trimmedName) return null
const existing = shelves.value.find(
(shelf) => shelf.name.toLocaleLowerCase() === trimmedName.toLocaleLowerCase()
)
if (existing) return existing
const shelf = {
id: globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`,
name: trimmedName
}
shelves.value = [...shelves.value, shelf]
saveShelves(shelves.value)
return shelf
}
onUnmounted(() => {
books.value.forEach((book) => book.coverUrl && URL.revokeObjectURL(book.coverUrl))
})
return {
books,
copyBookLink,
downloadBook,
error,
loadBooks,
loading,
openBook,
query,
createShelf,
shelves,
showBookInFiles,
sort,
setReadingStatus,
toggleBookShelf,
toggleFavorite,
visibleBooks
}
}
@@ -1,157 +0,0 @@
import { computed, reactive, type Ref } from 'vue'
import { useGettext } from 'vue3-gettext'
import type { LibraryBook, LibraryShelf } from '../types'
export type LibraryFilterKey = 'collection' | 'author' | 'subject' | 'language' | 'space' | 'status'
interface FilterOption {
label: string
value: string
}
export interface LibraryFilter {
key: LibraryFilterKey
label: string
options: FilterOption[]
}
export interface ActiveLibraryFilter {
key: LibraryFilterKey
label: string
valueLabel: string
}
interface UseLibraryFiltersOptions {
books: Ref<LibraryBook[]>
visibleBooks: Ref<LibraryBook[]>
shelves: Ref<LibraryShelf[]>
query: Ref<string>
}
function uniqueOptions(values: string[]): FilterOption[] {
return [...new Set(values.filter(Boolean))]
.sort((left, right) => left.localeCompare(right))
.map((value) => ({ label: value, value }))
}
export function useLibraryFilters({
books,
visibleBooks,
shelves,
query
}: UseLibraryFiltersOptions) {
const { $gettext } = useGettext()
const filterValues = reactive<Record<LibraryFilterKey, string>>({
collection: 'all',
author: 'all',
subject: 'all',
language: 'all',
space: 'all',
status: 'all'
})
const filters = computed<LibraryFilter[]>(() => [
{
key: 'collection',
label: $gettext('Collection'),
options: [
{ label: $gettext('All books'), value: 'all' },
{ label: $gettext('Favorites'), value: 'favorites' },
...shelves.value.map(({ id, name }) => ({ label: name, value: `shelf:${id}` }))
]
},
{
key: 'author',
label: $gettext('Author'),
options: [
{ label: $gettext('All authors'), value: 'all' },
...uniqueOptions(books.value.flatMap(({ authors }) => authors))
]
},
{
key: 'subject',
label: $gettext('Subject'),
options: [
{ label: $gettext('All subjects'), value: 'all' },
...uniqueOptions(books.value.flatMap(({ subjects }) => subjects))
]
},
{
key: 'language',
label: $gettext('Language'),
options: [
{ label: $gettext('All languages'), value: 'all' },
...uniqueOptions(books.value.map(({ language }) => language))
]
},
{
key: 'space',
label: $gettext('Space'),
options: [
{ label: $gettext('All spaces'), value: 'all' },
...uniqueOptions(books.value.map(({ space }) => space.name))
]
},
{
key: 'status',
label: $gettext('Status'),
options: [
{ label: $gettext('All statuses'), value: 'all' },
{ label: $gettext('Unread'), value: 'unread' },
{ label: $gettext('Reading'), value: 'reading' },
{ label: $gettext('Finished'), value: 'finished' }
]
}
])
const filteredBooks = computed(() =>
visibleBooks.value.filter((book) => {
const collection = filterValues.collection
if (collection === 'favorites' && !book.favorite) return false
if (collection.startsWith('shelf:') && !book.shelfIds.includes(collection.slice(6))) {
return false
}
if (filterValues.author !== 'all' && !book.authors.includes(filterValues.author)) return false
if (filterValues.subject !== 'all' && !book.subjects.includes(filterValues.subject)) {
return false
}
if (filterValues.language !== 'all' && book.language !== filterValues.language) return false
if (filterValues.space !== 'all' && book.space.name !== filterValues.space) return false
return filterValues.status === 'all' || book.readingStatus === filterValues.status
})
)
const hasActiveFilters = computed(
() =>
Boolean(query.value.trim()) || Object.values(filterValues).some((value) => value !== 'all')
)
const activeFilters = computed<ActiveLibraryFilter[]>(() =>
filters.value.flatMap((filter) => {
const selectedValue = filterValues[filter.key]
if (selectedValue === 'all') return []
const selectedOption = filter.options.find(({ value }) => value === selectedValue)
return selectedOption
? [{ key: filter.key, label: filter.label, valueLabel: selectedOption.label }]
: []
})
)
function clearFilter(key: LibraryFilterKey): void {
filterValues[key] = 'all'
}
function resetFilters(): void {
Object.keys(filterValues).forEach((key) => (filterValues[key as LibraryFilterKey] = 'all'))
}
return {
activeFilters,
clearFilter,
filteredBooks,
filters,
filterValues,
hasActiveFilters,
resetFilters
}
}
+14 -40
View File
@@ -1,7 +1,6 @@
import { computed } from 'vue'
import { useGettext } from 'vue3-gettext'
import translations from '../l10n/translations.json'
import { AppMenuItemExtension, AppWrapperRoute, defineWebApplication } from '@ownclouders/web-pkg'
import { AppWrapperRoute, defineWebApplication } from '@ownclouders/web-pkg'
export default defineWebApplication({
setup() {
@@ -11,16 +10,7 @@ export default defineWebApplication({
const routes = [
{
path: '/',
component: () => import('./views/LibraryView.vue'),
name: 'epub-library',
meta: {
authContext: 'user',
title: $gettext('Library')
}
},
{
path: '/read/:driveAliasAndItem(.*)?',
path: '/:driveAliasAndItem(.*)?',
component: async () => {
// lazy loading to avoid loading the epubjs package on page load
const EpubReader = (await import('./App.vue')).default
@@ -40,36 +30,20 @@ export default defineWebApplication({
}
]
const appInfo = {
name: $gettext('Epub Reader'),
id: appId,
icon: 'book-read',
color: '#4f46e5',
extensions: [
{
extension: 'epub',
routeName: 'epub-reader'
}
]
}
const extensions = computed<AppMenuItemExtension[]>(() => [
{
id: `app.${appId}.menuItem`,
type: 'appMenuItem',
label: () => $gettext('Library'),
color: appInfo.color,
icon: 'book',
priority: 50,
path: `/${appId}`
}
])
return {
appInfo,
appInfo: {
name: $gettext('Epub Reader'),
id: appId,
icon: 'book-read',
extensions: [
{
extension: 'epub',
routeName: 'epub-reader'
}
]
},
routes,
translations,
extensions
translations
}
}
})
@@ -1,42 +0,0 @@
import type { Resource, SpaceResource } from '@ownclouders/web-client'
export interface EpubMetadata {
title: string
authors: string[]
description: string
language: string
publisher: string
published: string
subjects: string[]
spineItemCount: number
coverUrl?: string
coverBlob?: Blob
}
export interface LibraryBook extends EpubMetadata {
id: string
resource: Resource
space: SpaceResource
loadingMetadata: boolean
metadataError?: string
favorite: boolean
readingStatus: ReadingStatus
shelfIds: string[]
readingProgress?: number
hasReadingPosition: boolean
}
export type LibrarySort = 'recent' | 'title' | 'author'
export type ReadingStatus = 'unread' | 'reading' | 'finished'
export type LibraryViewMode = 'grid' | 'list'
export interface LibraryShelf {
id: string
name: string
}
export interface BookPreferences {
favorite: boolean
readingStatus: ReadingStatus
shelfIds: string[]
}
@@ -1,96 +0,0 @@
import type { Resource } from '@ownclouders/web-client'
import type { EpubMetadata } from '../types'
const DATABASE_NAME = 'ocis-epub-library'
const DATABASE_VERSION = 1
const STORE_NAME = 'metadata'
interface CachedMetadataRecord {
id: string
fingerprint: string
metadata: Omit<EpubMetadata, 'coverBlob' | 'coverUrl'>
coverBlob?: Blob
}
export function resourceCacheId(resource: Resource): string {
return resource.fileId || resource.id || `${resource.spaceId}:${resource.path}`
}
export function resourceFingerprint(resource: Resource): string {
return [resource.etag || '', resource.mdate || '', String(resource.size || 0)].join(':')
}
function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION)
request.onupgradeneeded = () => {
if (!request.result.objectStoreNames.contains(STORE_NAME)) {
request.result.createObjectStore(STORE_NAME, { keyPath: 'id' })
}
}
request.onsuccess = () => resolve(request.result)
request.onerror = () => reject(request.error)
})
}
export async function getCachedMetadata(resource: Resource): Promise<EpubMetadata | null> {
if (typeof indexedDB === 'undefined') return null
try {
const database = await openDatabase()
const record = await new Promise<CachedMetadataRecord | undefined>((resolve, reject) => {
const request = database
.transaction(STORE_NAME, 'readonly')
.objectStore(STORE_NAME)
.get(resourceCacheId(resource))
request.onsuccess = () => resolve(request.result as CachedMetadataRecord | undefined)
request.onerror = () => reject(request.error)
})
database.close()
if (
!record ||
record.fingerprint !== resourceFingerprint(resource) ||
typeof record.metadata.spineItemCount !== 'number'
) {
return null
}
return {
...record.metadata,
coverBlob: record.coverBlob,
coverUrl: record.coverBlob ? URL.createObjectURL(record.coverBlob) : undefined
}
} catch {
return null
}
}
export async function setCachedMetadata(resource: Resource, metadata: EpubMetadata): Promise<void> {
if (typeof indexedDB === 'undefined') return
try {
const database = await openDatabase()
const persistedMetadata: CachedMetadataRecord['metadata'] = {
authors: metadata.authors,
description: metadata.description,
language: metadata.language,
published: metadata.published,
publisher: metadata.publisher,
subjects: metadata.subjects,
spineItemCount: metadata.spineItemCount,
title: metadata.title
}
const record: CachedMetadataRecord = {
id: resourceCacheId(resource),
fingerprint: resourceFingerprint(resource),
metadata: persistedMetadata,
coverBlob: metadata.coverBlob
}
await new Promise<void>((resolve, reject) => {
const transaction = database.transaction(STORE_NAME, 'readwrite')
transaction.objectStore(STORE_NAME).put(record)
transaction.oncomplete = () => resolve()
transaction.onerror = () => reject(transaction.error)
})
database.close()
} catch (e) {
console.error('Failed to set cached metadata', e)
}
}
@@ -1,144 +0,0 @@
import * as zip from '@zip.js/zip.js'
import type { EpubMetadata } from '../types'
const textDecoder = new TextDecoder()
function normalizedPath(path: string): string {
const parts: string[] = []
for (const segment of path.split('/')) {
if (!segment || segment === '.') continue
if (segment === '..') parts.pop()
else parts.push(segment)
}
return parts.join('/')
}
function resolvePath(baseFile: string, relativePath: string): string {
const base = baseFile.includes('/') ? baseFile.slice(0, baseFile.lastIndexOf('/') + 1) : ''
return normalizedPath(`${base}${relativePath}`)
}
function elementsByLocalName(root: ParentNode, localName: string): Element[] {
return [...root.querySelectorAll('*')].filter(
(element) => element.localName === localName || element.tagName.split(':').pop() === localName
)
}
function firstText(document: Document, localName: string): string {
return elementsByLocalName(document, localName)[0]?.textContent?.trim() ?? ''
}
function allText(document: Document, localName: string): string[] {
return elementsByLocalName(document, localName)
.map((element) => element.textContent?.trim() ?? '')
.filter(Boolean)
}
export function metadataFromPackageDocument(
packageXml: string,
fallbackTitle: string
): EpubMetadata & { coverHref?: string; coverMediaType?: string } {
const document = new DOMParser().parseFromString(packageXml, 'application/xml')
if (document.querySelector('parsererror')) {
throw new Error('Invalid EPUB package document')
}
const metadataElements = elementsByLocalName(document, 'meta')
const manifestItems = elementsByLocalName(document, 'item')
const coverImageItem = manifestItems.find((element) =>
element.getAttribute('properties')?.split(/\s+/).includes('cover-image')
)
const coverId =
metadataElements
.find((element) => element.getAttribute('name') === 'cover')
?.getAttribute('content') ??
coverImageItem?.getAttribute('id') ??
''
const coverItem =
manifestItems.find((element) => element.getAttribute('id') === coverId) ?? coverImageItem
return {
title: firstText(document, 'title') || fallbackTitle,
authors: allText(document, 'creator'),
description: firstText(document, 'description'),
language: firstText(document, 'language'),
publisher: firstText(document, 'publisher'),
published: firstText(document, 'date'),
subjects: allText(document, 'subject'),
spineItemCount: elementsByLocalName(document, 'itemref').length,
coverHref: coverItem?.getAttribute('href') ?? undefined,
coverMediaType: coverItem?.getAttribute('media-type') ?? undefined
}
}
async function entryText(entry: zip.FileEntry): Promise<string> {
const data = await entry.getData(new zip.Uint8ArrayWriter())
return textDecoder.decode(data)
}
export async function extractEpubMetadata(
data: Blob,
fallbackTitle: string
): Promise<EpubMetadata> {
// Extensions are loaded as standalone bundles from oCIS. ZIP.js cannot
// reliably resolve its worker script from that runtime location, which can
// leave metadata extraction pending indefinitely. EPUB metadata is small
// enough to process on the main thread.
const reader = new zip.ZipReader(new zip.BlobReader(data), {
useWebWorkers: false
})
try {
const entries = (await reader.getEntries()).filter(
(entry): entry is zip.FileEntry => !entry.directory
)
const byName = new Map(entries.map((entry) => [normalizedPath(entry.filename), entry]))
const containerEntry = byName.get('META-INF/container.xml')
if (!containerEntry) throw new Error('EPUB container.xml is missing')
const container = new DOMParser().parseFromString(
await entryText(containerEntry),
'application/xml'
)
const packagePath = container.querySelector('rootfile')?.getAttribute('full-path')
if (!packagePath) throw new Error('EPUB package path is missing')
const normalizedPackagePath = normalizedPath(packagePath)
const packageEntry = byName.get(normalizedPackagePath)
if (!packageEntry) throw new Error('EPUB package document is missing')
const parsed = metadataFromPackageDocument(await entryText(packageEntry), fallbackTitle)
let coverUrl: string | undefined
let coverBlob: Blob | undefined
if (parsed.coverHref) {
const coverEntry = byName.get(resolvePath(normalizedPackagePath, parsed.coverHref))
if (coverEntry) {
coverBlob = await coverEntry.getData(new zip.BlobWriter(parsed.coverMediaType))
coverUrl = URL.createObjectURL(coverBlob)
}
}
return {
title: parsed.title,
authors: parsed.authors,
description: parsed.description,
language: parsed.language,
publisher: parsed.publisher,
published: parsed.published,
subjects: parsed.subjects,
spineItemCount: parsed.spineItemCount,
coverUrl,
coverBlob
}
} finally {
await reader.close()
}
}
export function titleFromFileName(name: string): string {
return name
.replace(/\.epub$/i, '')
.replace(/[._-]+/g, ' ')
.replace(/\s+/g, ' ')
.trim()
}
@@ -1,66 +0,0 @@
import type { Resource } from '@ownclouders/web-client'
import type { BookPreferences, LibraryShelf, LibraryViewMode } from '../types'
import { resourceCacheId } from './cache'
const STORAGE_KEY = 'ocis-epub-library-preferences-v1'
interface StoredPreferences {
books: Record<string, BookPreferences>
shelves: LibraryShelf[]
viewMode: LibraryViewMode
}
const defaults = (): StoredPreferences => ({ books: {}, shelves: [], viewMode: 'grid' })
function read(): StoredPreferences {
if (typeof localStorage === 'undefined') return defaults()
try {
return { ...defaults(), ...JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}') }
} catch {
return defaults()
}
}
function write(value: StoredPreferences): void {
if (typeof localStorage === 'undefined') return
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(value))
} catch {
// Preferences remain available for this session when browser storage is disabled.
}
}
export function getBookPreferences(resource: Resource): BookPreferences {
return {
favorite: false,
readingStatus: 'unread',
shelfIds: [],
...read().books[resourceCacheId(resource)]
}
}
export function saveBookPreferences(resource: Resource, preferences: BookPreferences): void {
const stored = read()
stored.books[resourceCacheId(resource)] = preferences
write(stored)
}
export function loadShelves(): LibraryShelf[] {
return read().shelves
}
export function saveShelves(shelves: LibraryShelf[]): void {
const stored = read()
stored.shelves = shelves
write(stored)
}
export function loadViewMode(): LibraryViewMode {
return read().viewMode
}
export function saveViewMode(viewMode: LibraryViewMode): void {
const stored = read()
stored.viewMode = viewMode
write(stored)
}
@@ -1,59 +0,0 @@
import type { Resource } from '@ownclouders/web-client'
interface ReaderLocation {
atEnd?: boolean
atStart?: boolean
start?: {
cfi?: string
displayed?: { page?: number; total?: number }
index?: number
percentage?: number
}
}
export interface ReaderProgress {
finished: boolean
hasPosition: boolean
percentage?: number
}
function fallbackPercentage(location: ReaderLocation, spineItemCount: number): number | undefined {
const { displayed, index } = location.start ?? {}
if (!spineItemCount || typeof index !== 'number') return undefined
const page = displayed?.page ?? 1
const totalPages = displayed?.total ?? 1
const chapterProgress = totalPages > 0 ? (page - 1) / totalPages : 0
const percentage = Math.round(((index + chapterProgress) / spineItemCount) * 100)
if (location.atEnd) return 100
if (location.atStart) return 0
return Math.max(1, Math.min(99, percentage))
}
export function getReaderProgress(resource: Resource, spineItemCount = 0): ReaderProgress {
if (typeof localStorage === 'undefined') return { finished: false, hasPosition: false }
try {
const storedValue = localStorage.getItem(`oc_epubReader_resource_${resource.id}`)
if (!storedValue) return { finished: false, hasPosition: false }
const location = (JSON.parse(storedValue) as { currentLocation?: ReaderLocation })
.currentLocation
if (!location?.start?.cfi) return { finished: false, hasPosition: false }
const savedPercentage = location.start.percentage
const percentage =
typeof savedPercentage === 'number' && savedPercentage > 0
? Math.round(savedPercentage * 100)
: fallbackPercentage(location, spineItemCount)
return {
finished: location.atEnd === true || percentage === 100,
hasPosition: true,
percentage:
typeof percentage === 'number' ? Math.max(0, Math.min(100, percentage)) : undefined
}
} catch {
return { finished: false, hasPosition: false }
}
}
@@ -1,872 +0,0 @@
<template>
<main class="library oc-p-m" :aria-label="$gettext('Library')">
<header class="library-header oc-flex oc-flex-between oc-flex-middle oc-mb-l">
<div>
<h1 class="oc-m-rm">{{ $gettext('Library') }}</h1>
<p class="oc-text-muted oc-m-rm">
{{ $gettext('Browse EPUB books stored in your ownCloud spaces.') }}
</p>
</div>
<oc-button appearance="outline" :disabled="loading" @click="loadBooks">
<oc-icon name="refresh" size="small" />
{{ $gettext('Refresh') }}
</oc-button>
</header>
<div class="library-controls oc-flex oc-flex-between oc-flex-middle oc-mb-l">
<oc-text-input
v-model="query"
class="library-search"
:label="$gettext('Search books')"
:placeholder="$gettext('Title, author, publisher or subject')"
/>
<oc-select
:model-value="selectedSortOption"
class="library-sort"
:label="$gettext('Sort by')"
:options="sortOptions"
option-label="label"
@update:model-value="onSortUpdate"
/>
</div>
<section
v-if="showContinueReading"
class="continue-section oc-mb-xl"
aria-labelledby="continue-reading-heading"
>
<div class="continue-section-heading oc-flex oc-flex-between oc-flex-middle oc-mb-m">
<div>
<h2 id="continue-reading-heading" class="oc-m-rm">
{{ $gettext('Continue reading') }}
</h2>
<p class="oc-text-muted oc-m-rm">{{ $gettext('Pick up where you left off.') }}</p>
</div>
</div>
<div class="continue-list">
<button
v-for="book in continueReadingBooks"
:key="book.id"
type="button"
class="continue-card"
:aria-label="$gettext('Continue reading %{title}', { title: book.title })"
@click="openBook(book)"
>
<span class="continue-cover">
<img v-if="book.coverUrl" :src="book.coverUrl" :alt="''" />
<oc-icon v-else name="book" size="large" />
</span>
<span class="continue-card-content">
<strong>{{ book.title }}</strong>
<span class="oc-text-muted">
{{ book.authors.join(', ') || $gettext('Unknown author') }}
</span>
<span class="continue-card-progress">
{{
book.readingProgress === undefined
? $gettext('Resume')
: $gettext('%{progress}% complete', { progress: String(book.readingProgress) })
}}
</span>
<span
v-if="book.readingProgress !== undefined"
class="reading-progress"
role="progressbar"
:aria-label="$gettext('Reading progress for %{title}', { title: book.title })"
aria-valuemin="0"
aria-valuemax="100"
:aria-valuenow="book.readingProgress"
>
<span :style="{ width: `${book.readingProgress}%` }" />
</span>
</span>
</button>
</div>
</section>
<div class="library-toolbar oc-flex oc-flex-between oc-flex-middle oc-mb-l">
<div class="library-filters">
<label v-for="filter in primaryFilters" :key="filter.key" class="library-filter">
<span>{{ filter.label }}</span>
<select v-model="filterValues[filter.key]">
<option v-for="option in filter.options" :key="option.value" :value="option.value">
{{ option.label }}
</option>
</select>
</label>
<oc-button
appearance="outline"
class="advanced-filter-toggle"
aria-controls="advanced-library-filters"
:aria-expanded="showAdvancedFilters"
@click="showAdvancedFilters = !showAdvancedFilters"
>
<oc-icon name="filter" size="small" />
{{ $gettext('More filters') }}
<span v-if="advancedFilterCount">({{ advancedFilterCount }})</span>
</oc-button>
</div>
<div class="view-toggle oc-flex" role="group" :aria-label="$gettext('View mode')">
<button
type="button"
class="view-toggle-button"
:class="{ 'view-toggle-button-selected': viewMode === 'grid' }"
:aria-pressed="viewMode === 'grid'"
@click="setViewMode('grid')"
>
{{ $gettext('Grid') }}
</button>
<button
type="button"
class="view-toggle-button"
:class="{ 'view-toggle-button-selected': viewMode === 'list' }"
:aria-pressed="viewMode === 'list'"
@click="setViewMode('list')"
>
{{ $gettext('List') }}
</button>
</div>
</div>
<div
v-if="showAdvancedFilters"
id="advanced-library-filters"
class="advanced-filters oc-mb-m oc-p-m"
>
<label v-for="filter in advancedFilters" :key="filter.key" class="library-filter">
<span>{{ filter.label }}</span>
<select v-model="filterValues[filter.key]">
<option v-for="option in filter.options" :key="option.value" :value="option.value">
{{ option.label }}
</option>
</select>
</label>
</div>
<div v-if="activeFilters.length" class="active-filters oc-flex oc-flex-wrap oc-mb-l">
<oc-button
v-for="filter in activeFilters"
:key="filter.key"
appearance="raw"
class="filter-chip"
:aria-label="
$gettext('Remove %{label} filter: %{value}', {
label: filter.label,
value: filter.valueLabel
})
"
@click="clearFilter(filter.key)"
>
<span>{{ filter.label }}: {{ filter.valueLabel }}</span>
<oc-icon name="close" size="small" />
</oc-button>
<oc-button appearance="raw" @click="resetFilters">{{ $gettext('Clear all') }}</oc-button>
</div>
<div v-if="loading && !books.length" class="library-state" role="status">
<oc-spinner size="large" />
<p>{{ $gettext('Finding EPUB books…') }}</p>
</div>
<div v-else-if="error" class="library-state" role="alert">
<oc-icon name="error-warning" size="xlarge" />
<h2>{{ $gettext('Library unavailable') }}</h2>
<p>{{ error }}</p>
<oc-button @click="loadBooks">{{ $gettext('Try again') }}</oc-button>
</div>
<div v-else-if="!filteredBooks.length" class="library-state">
<oc-icon name="book" size="xlarge" />
<h2>
{{ hasActiveFilters ? $gettext('No matching books') : $gettext('No EPUB books found') }}
</h2>
<p v-if="!hasActiveFilters">
{{ $gettext('Upload EPUB files to an accessible ownCloud space and refresh the library.') }}
</p>
</div>
<template v-else>
<p class="oc-text-muted oc-mb-m" role="status">
{{ $gettext('%{count} books', { count: String(filteredBooks.length) }) }}
<span v-if="loading"> · {{ $gettext('Reading metadata…') }}</span>
</p>
<div class="bookshelf" :class="`bookshelf-${viewMode}`">
<article v-for="book in filteredBooks" :key="book.id" class="book-card">
<oc-button
appearance="raw"
class="book-details-button"
:aria-label="$gettext('View details for %{title}', { title: book.title })"
@click="showDetails(book, $event)"
>
<oc-icon name="information" size="small" />
</oc-button>
<button
type="button"
class="book-open"
:aria-label="$gettext('Open %{title}', { title: book.title })"
@click="openBook(book)"
>
<span class="book-cover">
<img v-if="book.coverUrl" :src="book.coverUrl" :alt="''" />
<span v-else class="book-cover-fallback">
<oc-icon name="book" size="xlarge" />
<span>{{ book.title }}</span>
</span>
</span>
<span class="book-title">{{ book.title }}</span>
<span class="book-author">
{{ book.authors.join(', ') || $gettext('Unknown author') }}
</span>
<span v-if="book.hasReadingPosition" class="continue-reading">
<template v-if="book.readingProgress === 100">{{ $gettext('Finished') }}</template>
<template v-else>
{{ $gettext('Continue reading') }}
<span v-if="book.readingProgress !== undefined">
· {{ book.readingProgress }}%</span
>
</template>
</span>
<span
v-if="book.readingProgress !== undefined"
class="reading-progress"
role="progressbar"
:aria-label="$gettext('Reading progress for %{title}', { title: book.title })"
aria-valuemin="0"
aria-valuemax="100"
:aria-valuenow="book.readingProgress"
>
<span :style="{ width: `${book.readingProgress}%` }" />
</span>
<span v-if="book.loadingMetadata" class="book-status oc-text-muted">
{{ $gettext('Reading metadata…') }}
</span>
<span v-else-if="book.metadataError" class="book-status oc-text-muted">
{{ book.metadataError }}
</span>
<span v-else-if="book.published" class="book-status oc-text-muted">
{{ book.published.slice(0, 4) }}
</span>
</button>
<div class="book-card-meta">
<div
v-if="book.favorite || book.readingStatus !== 'unread'"
class="book-labels oc-flex oc-flex-wrap oc-mt-xs"
>
<span v-if="book.favorite" class="book-label">{{ $gettext('Favorite') }}</span>
<span v-if="book.readingStatus !== 'unread'" class="book-label">
{{ readingStatusLabel(book.readingStatus) }}
</span>
</div>
</div>
</article>
</div>
</template>
<book-details
v-if="selectedBook"
:book="selectedBook"
:copied="copied"
:shelves="shelves"
@close="closeDetails"
@open="openBook(selectedBook)"
@show-in-files="showBookInFiles(selectedBook)"
@download="downloadBook(selectedBook)"
@copy-link="copySelectedBookLink"
@toggle-favorite="toggleFavorite(selectedBook)"
@set-status="setReadingStatus(selectedBook, $event)"
@toggle-shelf="toggleBookShelf(selectedBook, $event)"
@create-shelf="createAndAssignShelf"
/>
</main>
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue'
import { useGettext } from 'vue3-gettext'
import BookDetails from '../components/BookDetails.vue'
import { useLibrary } from '../composables/useLibrary'
import { useLibraryFilters } from '../composables/useLibraryFilters'
import type { LibraryBook, LibrarySort, LibraryViewMode, ReadingStatus } from '../types'
import { loadViewMode, saveViewMode } from '../utils/preferences'
const { $gettext } = useGettext()
const {
books,
copyBookLink,
createShelf,
downloadBook,
error,
loadBooks,
loading,
openBook,
query,
shelves,
setReadingStatus,
showBookInFiles,
sort,
toggleBookShelf,
toggleFavorite,
visibleBooks
} = useLibrary()
const selectedBook = ref<LibraryBook | null>(null)
const copied = ref(false)
const viewMode = ref<LibraryViewMode>(loadViewMode())
const showAdvancedFilters = ref(false)
let copiedTimer: ReturnType<typeof setTimeout> | undefined
let detailsTrigger: HTMLElement | null = null
const {
activeFilters,
clearFilter,
filteredBooks,
filters,
filterValues,
hasActiveFilters,
resetFilters
} = useLibraryFilters({ books, query, shelves, visibleBooks })
const primaryFilters = computed(() =>
filters.value.filter(({ key }) => ['collection', 'status'].includes(key))
)
const advancedFilters = computed(() =>
filters.value.filter(({ key }) => !['collection', 'status'].includes(key))
)
const advancedFilterCount = computed(
() => advancedFilters.value.filter(({ key }) => filterValues[key] !== 'all').length
)
const continueReadingBooks = computed(() =>
books.value
.filter(
({ hasReadingPosition, readingProgress, readingStatus }) =>
hasReadingPosition && readingProgress !== 100 && readingStatus !== 'finished'
)
.sort((left, right) => (right.readingProgress ?? 0) - (left.readingProgress ?? 0))
.slice(0, 6)
)
const showContinueReading = computed(
() =>
!loading.value &&
!error.value &&
!hasActiveFilters.value &&
continueReadingBooks.value.length > 0
)
const sortOptions = [
{ label: $gettext('Recently added'), value: 'recent' },
{ label: $gettext('Title'), value: 'title' },
{ label: $gettext('Author'), value: 'author' }
]
const selectedSortOption = computed(
() => sortOptions.find((option) => option.value === sort.value) ?? sortOptions[0]
)
function onSortUpdate(option: { value: LibrarySort } | null): void {
if (option) sort.value = option.value
}
async function closeDetails(): Promise<void> {
selectedBook.value = null
copied.value = false
if (copiedTimer) clearTimeout(copiedTimer)
await nextTick()
detailsTrigger?.focus()
detailsTrigger = null
}
function showDetails(book: LibraryBook, event: MouseEvent): void {
detailsTrigger = event.currentTarget as HTMLElement
copied.value = false
selectedBook.value = book
}
function setViewMode(mode: LibraryViewMode): void {
viewMode.value = mode
saveViewMode(mode)
}
function readingStatusLabel(status: ReadingStatus): string {
return {
unread: $gettext('Unread'),
reading: $gettext('Reading'),
finished: $gettext('Finished')
}[status]
}
function createAndAssignShelf(name: string): void {
if (!selectedBook.value) return
const shelf = createShelf(name)
if (shelf && !selectedBook.value.shelfIds.includes(shelf.id)) {
toggleBookShelf(selectedBook.value, shelf.id)
}
}
async function copySelectedBookLink(): Promise<void> {
if (!selectedBook.value) return
const success = await copyBookLink(selectedBook.value)
if (!success) return
copied.value = true
if (copiedTimer) clearTimeout(copiedTimer)
copiedTimer = setTimeout(() => (copied.value = false), 2000)
}
onMounted(loadBooks)
</script>
<style scoped>
.library {
box-sizing: border-box;
height: 100%;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
width: 100%;
}
.library-header,
.library-controls {
gap: var(--oc-space-medium);
}
.library-toolbar {
align-items: end;
gap: var(--oc-space-medium);
}
.continue-section {
background: var(--oc-color-background-muted);
border-radius: 12px;
padding: var(--oc-space-medium);
}
.continue-list {
display: grid;
gap: var(--oc-space-medium);
grid-auto-columns: minmax(17rem, 21rem);
grid-auto-flow: column;
overflow-x: auto;
padding: var(--oc-space-xsmall) var(--oc-space-xsmall) var(--oc-space-small);
scroll-snap-type: x proximity;
}
.continue-card {
align-items: center;
background: var(--oc-color-background-default);
border: 0;
border-radius: 10px;
box-shadow: 0 2px 6px rgb(0 0 0 / 12%);
color: inherit;
cursor: pointer;
display: grid;
gap: var(--oc-space-medium);
grid-template-columns: 4.5rem minmax(0, 1fr);
padding: var(--oc-space-small);
scroll-snap-align: start;
text-align: left;
}
.continue-card:focus-visible {
outline: 3px solid var(--oc-color-swatch-primary-default);
outline-offset: 2px;
}
.continue-cover {
align-items: center;
aspect-ratio: 2 / 3;
background: var(--oc-color-background-muted);
border-radius: 6px;
display: flex;
justify-content: center;
overflow: hidden;
}
.continue-cover img {
height: 100%;
object-fit: cover;
width: 100%;
}
.continue-card-content,
.continue-card-content > span {
display: block;
min-width: 0;
}
.continue-card-content {
overflow: hidden;
}
.continue-card-content strong,
.continue-card-content > span:not(.reading-progress) {
display: block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.continue-card-progress {
color: var(--oc-color-swatch-primary-default);
font-size: var(--oc-font-size-small);
font-weight: 600;
margin-top: var(--oc-space-small);
}
.library-filters {
display: flex;
flex: 1;
flex-wrap: wrap;
gap: var(--oc-space-small);
}
.advanced-filter-toggle {
align-self: end;
}
.advanced-filters {
background: var(--oc-color-background-muted);
border-radius: 10px;
display: flex;
flex-wrap: wrap;
gap: var(--oc-space-medium);
}
.active-filters {
align-items: center;
gap: var(--oc-space-small);
}
.filter-chip {
background: var(--oc-color-background-muted);
border-radius: 999px;
gap: var(--oc-space-xsmall);
padding: var(--oc-space-xsmall) var(--oc-space-small);
}
.library-filter {
display: grid;
font-size: var(--oc-font-size-small);
gap: var(--oc-space-xsmall);
}
.library-filter select {
background: var(--oc-color-background-default);
border: 1px solid var(--oc-color-background-muted);
border-radius: 5px;
color: inherit;
min-height: 2.5rem;
padding: 0 var(--oc-space-small);
}
.view-toggle {
background: var(--oc-color-background-muted);
border-radius: 8px;
gap: var(--oc-space-xsmall);
padding: var(--oc-space-xsmall);
}
.view-toggle-button {
background: var(--oc-color-background-default);
border: 2px solid var(--oc-color-swatch-passive-default);
border-radius: 6px;
color: inherit;
cursor: pointer;
font: inherit;
font-weight: 600;
min-height: 2.5rem;
padding: 0 var(--oc-space-medium);
}
.view-toggle-button:hover {
border-color: var(--oc-color-swatch-primary-default);
box-shadow: 0 0 0 2px var(--oc-color-background-highlight);
}
.view-toggle-button:focus-visible {
outline: 3px solid var(--oc-color-swatch-primary-default);
outline-offset: 2px;
}
.view-toggle-button-selected {
background: var(--oc-color-swatch-primary-default);
border-color: var(--oc-color-swatch-primary-default);
color: var(--oc-color-swatch-primary-contrast);
}
.library-controls {
align-items: end;
}
.library-search {
max-width: 32rem;
width: 100%;
}
.library-sort {
min-width: 12rem;
}
.library-state {
align-items: center;
display: flex;
flex-direction: column;
justify-content: center;
min-height: 20rem;
text-align: center;
}
.bookshelf {
display: grid;
gap: var(--oc-space-large) var(--oc-space-medium);
grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr));
}
.book-card {
min-width: 0;
position: relative;
}
.book-labels {
gap: var(--oc-space-xsmall);
}
.book-label {
background: var(--oc-color-background-muted);
border-radius: 5px;
font-size: var(--oc-font-size-xsmall);
padding: 0 var(--oc-space-xsmall);
}
.bookshelf-list {
display: block;
}
.bookshelf-list .book-card {
align-items: stretch;
border-bottom: 1px solid var(--oc-color-background-muted);
display: grid;
gap: var(--oc-space-medium);
grid-template-columns: minmax(0, 1fr) minmax(10rem, 14rem);
padding: var(--oc-space-small) 0;
}
.bookshelf-list .book-open {
align-items: center;
column-gap: var(--oc-space-medium);
display: grid;
grid-template-areas:
'cover title continue'
'cover author progress'
'cover status status';
grid-template-columns: 3.5rem minmax(8rem, 2fr) minmax(7rem, 1fr);
row-gap: var(--oc-space-xsmall);
}
.bookshelf-list .book-cover {
grid-area: cover;
}
.bookshelf-list .book-title {
grid-area: title;
}
.bookshelf-list .book-author {
grid-area: author;
}
.bookshelf-list .book-status {
grid-area: status;
margin-top: 0;
}
.bookshelf-list .continue-reading {
grid-area: continue;
}
.bookshelf-list .reading-progress {
align-self: center;
grid-area: progress;
margin-top: 0;
width: 100%;
}
.bookshelf-list .book-card-meta {
align-items: center;
align-self: end;
display: flex;
gap: var(--oc-space-small);
justify-content: flex-end;
min-height: 1.5rem;
white-space: nowrap;
}
.bookshelf-list .book-labels {
margin-top: 0;
}
.bookshelf-list .book-labels {
flex-wrap: nowrap;
}
.bookshelf-list .book-title,
.bookshelf-list .book-author {
margin-top: 0;
}
.book-open {
background: transparent;
border: 0;
color: inherit;
cursor: pointer;
display: block;
padding: 0;
text-align: left;
width: 100%;
}
.book-open:focus-visible .book-cover {
outline: 3px solid var(--oc-color-swatch-primary-default);
outline-offset: 3px;
}
.book-cover {
aspect-ratio: 2 / 3;
background: var(--oc-color-background-muted);
border-radius: 8px;
box-shadow: 0 3px 8px 1px rgb(0 0 0 / 14%);
display: block;
overflow: hidden;
width: 100%;
}
.book-cover img {
height: 100%;
object-fit: cover;
width: 100%;
}
.book-cover-fallback {
align-items: center;
display: flex;
flex-direction: column;
gap: var(--oc-space-medium);
height: 100%;
justify-content: center;
padding: var(--oc-space-medium);
text-align: center;
}
.book-title,
.book-author,
.book-status {
display: block;
}
.book-details-button {
background: var(--oc-color-background-default);
border-radius: 50%;
box-shadow: 0 2px 6px rgb(0 0 0 / 18%);
min-height: 2rem;
min-width: 2rem;
padding: 0;
position: absolute;
right: var(--oc-space-small);
top: var(--oc-space-small);
z-index: 2;
}
.book-title {
font-weight: 600;
margin-top: var(--oc-space-small);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.book-author,
.book-status,
.continue-reading {
font-size: var(--oc-font-size-small);
margin-top: var(--oc-space-xsmall);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.continue-reading {
color: var(--oc-color-swatch-primary-default);
display: block;
font-size: var(--oc-font-size-small);
font-weight: 600;
margin-top: var(--oc-space-small);
}
.reading-progress {
background: var(--oc-color-background-muted);
border-radius: 999px;
display: block;
height: 0.25rem;
margin-top: var(--oc-space-xsmall);
overflow: hidden;
}
.reading-progress > span {
background: var(--oc-color-swatch-primary-default);
display: block;
height: 100%;
}
@media (max-width: 640px) {
.library-header,
.library-controls,
.library-toolbar {
align-items: stretch;
flex-direction: column;
}
.library-sort {
min-width: 0;
width: 100%;
}
.library-filters,
.library-filter,
.advanced-filter-toggle {
width: 100%;
}
.advanced-filters {
display: grid;
}
.view-toggle {
align-self: flex-end;
width: fit-content;
}
.continue-list {
grid-auto-columns: minmax(15rem, 85%);
}
.bookshelf-list .book-card {
grid-template-columns: 1fr;
}
.bookshelf-list .book-open {
grid-template-areas:
'cover title'
'cover author'
'cover status'
'cover continue'
'cover progress';
grid-template-columns: 3.5rem minmax(0, 1fr);
}
.bookshelf-list .book-title {
padding-right: 2.75rem;
}
.bookshelf-list .book-card-meta {
justify-content: flex-start;
}
}
</style>
@@ -1,78 +0,0 @@
import { mock } from 'vitest-mock-extended'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { defaultPlugins, mount, PartialComponentProps } from '@ownclouders/web-test-helpers'
import BookDetails from '../../src/components/BookDetails.vue'
import type { LibraryBook } from '../../src/types'
function libraryBook(overrides: Partial<LibraryBook> = {}): LibraryBook {
return {
id: 'file-1',
resource: mock<Resource>({ name: 'Book.epub', path: '/Books/Book.epub', size: '2048' }),
space: mock<SpaceResource>({ name: 'Personal' }),
title: 'A Book',
authors: ['Ada Lovelace'],
description: '',
language: '',
publisher: '',
published: '',
subjects: [],
spineItemCount: 1,
loadingMetadata: false,
favorite: false,
readingStatus: 'unread',
shelfIds: [],
hasReadingPosition: false,
...overrides
}
}
describe('BookDetails', () => {
it('renders the book title and author', () => {
const { wrapper } = getWrapper()
expect(wrapper.find('#book-details-title').exists()).toBe(true)
expect(wrapper.html()).toContain('A Book')
expect(wrapper.html()).toContain('Ada Lovelace')
})
it('emits "close" when Escape is pressed on the dialog', async () => {
const { wrapper } = getWrapper()
await wrapper.get('[role="dialog"]').trigger('keydown.esc')
expect(wrapper.emitted('close')).toBeTruthy()
})
it('emits action events from the secondary actions', async () => {
const { wrapper } = getWrapper()
const buttons = wrapper.findAll('.secondary-actions button')
await buttons[0].trigger('click')
await buttons[1].trigger('click')
await buttons[2].trigger('click')
expect(wrapper.emitted('show-in-files')).toBeTruthy()
expect(wrapper.emitted('download')).toBeTruthy()
expect(wrapper.emitted('copy-link')).toBeTruthy()
})
it('shows the copied state when the copied prop is set', () => {
const { wrapper } = getWrapper({ copied: true })
expect(wrapper.html()).toContain('Copied')
})
})
function getWrapper(props: PartialComponentProps<typeof BookDetails> = {}) {
return {
wrapper: mount(BookDetails, {
props: {
book: libraryBook(),
shelves: [],
...props
},
global: {
plugins: [...defaultPlugins()],
stubs: {
'focus-trap': {
template: '<slot />'
}
}
}
})
}
}
@@ -1,130 +0,0 @@
import { ref } from 'vue'
import { mock } from 'vitest-mock-extended'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { defaultPlugins, mount } from '@ownclouders/web-test-helpers'
import LibraryView from '../../src/views/LibraryView.vue'
import type { LibraryBook } from '../../src/types'
const { libraryState, loadBooks, openBook } = vi.hoisted(() => ({
libraryState: {
books: undefined as never,
visibleBooks: undefined as never,
shelves: undefined as never,
query: undefined as never,
sort: undefined as never,
loading: undefined as never,
error: undefined as never
},
loadBooks: vi.fn(),
openBook: vi.fn()
}))
vi.mock('../../src/composables/useLibrary', () => ({
useLibrary: () => ({
books: libraryState.books,
visibleBooks: libraryState.visibleBooks,
shelves: libraryState.shelves,
query: libraryState.query,
sort: libraryState.sort,
loading: libraryState.loading,
error: libraryState.error,
loadBooks,
openBook,
copyBookLink: vi.fn(),
createShelf: vi.fn(),
downloadBook: vi.fn(),
setReadingStatus: vi.fn(),
showBookInFiles: vi.fn(),
toggleBookShelf: vi.fn(),
toggleFavorite: vi.fn()
})
}))
function libraryBook(overrides: Partial<LibraryBook> = {}): LibraryBook {
return {
id: 'file-1',
resource: mock<Resource>({ name: 'Book.epub', path: '/Books/Book.epub' }),
space: mock<SpaceResource>({ name: 'Personal' }),
title: 'A Book',
authors: ['Ada Lovelace'],
description: '',
language: '',
publisher: '',
published: '',
subjects: [],
spineItemCount: 1,
loadingMetadata: false,
favorite: false,
readingStatus: 'unread',
shelfIds: [],
hasReadingPosition: false,
...overrides
}
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('LibraryView', () => {
it('loads books on mount', () => {
getWrapper()
expect(loadBooks).toHaveBeenCalled()
})
it('shows a loading state while loading with no books', () => {
const { wrapper } = getWrapper({ loading: true, books: [] })
expect(wrapper.find('.library-state[role="status"]').exists()).toBe(true)
})
it('shows an error state when loading fails', () => {
const { wrapper } = getWrapper({ error: 'Boom' })
const alert = wrapper.find('.library-state[role="alert"]')
expect(alert.exists()).toBe(true)
expect(alert.text()).toContain('Boom')
})
it('shows the empty state when there are no books', () => {
const { wrapper } = getWrapper({ books: [], visibleBooks: [] })
expect(wrapper.html()).toContain('No EPUB books found')
})
it('renders a card per visible book', () => {
const books = [libraryBook(), libraryBook({ id: 'file-2', title: 'Second' })]
const { wrapper } = getWrapper({ books, visibleBooks: books })
expect(wrapper.findAll('.book-card')).toHaveLength(2)
})
it('opens a book when its open button is clicked', async () => {
const books = [libraryBook()]
const { wrapper } = getWrapper({ books, visibleBooks: books })
await wrapper.find('.book-open').trigger('click')
expect(openBook).toHaveBeenCalledWith(books[0])
})
})
function getWrapper(
state: {
books?: LibraryBook[]
visibleBooks?: LibraryBook[]
loading?: boolean
error?: string
} = {}
) {
libraryState.books = ref(state.books ?? []) as never
libraryState.visibleBooks = ref(state.visibleBooks ?? state.books ?? []) as never
libraryState.shelves = ref([]) as never
libraryState.query = ref('') as never
libraryState.sort = ref('recent') as never
libraryState.loading = ref(state.loading ?? false) as never
libraryState.error = ref(state.error ?? '') as never
return {
wrapper: mount(LibraryView, {
global: {
plugins: [...defaultPlugins()],
stubs: { 'oc-select': true, 'oc-spinner': true, BookDetails: true }
}
})
}
}
@@ -1,26 +0,0 @@
import type { Resource } from '@ownclouders/web-client'
import { describe, expect, it } from 'vitest'
import { resourceCacheId, resourceFingerprint } from '../../src/utils/cache'
function resource(overrides: Partial<Resource> = {}): Resource {
return {
id: 'resource-id',
name: 'book.epub',
path: '/Books/book.epub',
type: 'file',
...overrides
} as Resource
}
describe('EPUB metadata cache keys', () => {
it('prefers the stable file id', () => {
expect(resourceCacheId(resource({ fileId: 'file-id' }))).toBe('file-id')
})
it('changes the fingerprint when file metadata changes', () => {
const original = resourceFingerprint(resource({ etag: 'one', size: 100 }))
const changed = resourceFingerprint(resource({ etag: 'two', size: 100 }))
expect(changed).not.toBe(original)
})
})
@@ -1,65 +0,0 @@
import * as zip from '@zip.js/zip.js'
import { describe, expect, it } from 'vitest'
import {
extractEpubMetadata,
metadataFromPackageDocument,
titleFromFileName
} from '../../src/utils/epub'
describe('EPUB metadata utilities', () => {
it('extracts Dublin Core metadata and cover information', () => {
const metadata = metadataFromPackageDocument(
`<?xml version="1.0"?>
<package xmlns="http://www.idpf.org/2007/opf" xmlns:dc="http://purl.org/dc/elements/1.1/">
<metadata>
<dc:title>A Wizard of Earthsea</dc:title>
<dc:creator>Ursula K. Le Guin</dc:creator>
<dc:language>en</dc:language>
<dc:publisher>Parnassus Press</dc:publisher>
<dc:subject>Fantasy</dc:subject>
<meta name="cover" content="cover-image" />
</metadata>
<manifest><item id="cover-image" href="images/cover.jpg" media-type="image/jpeg" /></manifest>
<spine><itemref idref="chapter-1" /><itemref idref="chapter-2" /></spine>
</package>`,
'Fallback title'
)
expect(metadata).toMatchObject({
title: 'A Wizard of Earthsea',
authors: ['Ursula K. Le Guin'],
language: 'en',
publisher: 'Parnassus Press',
subjects: ['Fantasy'],
spineItemCount: 2,
coverHref: 'images/cover.jpg'
})
})
it('creates a readable title from a filename', () => {
expect(titleFromFileName('the_left-hand.of-earthsea.epub')).toBe('the left hand of earthsea')
})
it('reads metadata from an EPUB archive without a web worker', async () => {
zip.configure({ useWebWorkers: false })
const writer = new zip.ZipWriter(new zip.BlobWriter('application/epub+zip'))
await writer.add(
'META-INF/container.xml',
new zip.TextReader(
'<container><rootfiles><rootfile full-path="OEBPS/content.opf" /></rootfiles></container>'
)
)
await writer.add(
'OEBPS/content.opf',
new zip.TextReader(
'<package><metadata><title>Frankenstein</title><creator>Mary Shelley</creator></metadata><manifest /></package>'
)
)
const epub = await writer.close()
await expect(extractEpubMetadata(epub, 'Fallback')).resolves.toMatchObject({
title: 'Frankenstein',
authors: ['Mary Shelley']
})
})
})
@@ -1,46 +0,0 @@
import type { Resource } from '@ownclouders/web-client'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
getBookPreferences,
loadShelves,
loadViewMode,
saveBookPreferences,
saveShelves,
saveViewMode
} from '../../src/utils/preferences'
const values = new Map<string, string>()
beforeEach(() => {
values.clear()
vi.stubGlobal('localStorage', {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value)
})
})
describe('library preferences', () => {
const resource = { id: 'book-1', path: '/Books/book.epub' } as Resource
it('persists per-book organization state', () => {
saveBookPreferences(resource, {
favorite: true,
readingStatus: 'reading',
shelfIds: ['classics']
})
expect(getBookPreferences(resource)).toEqual({
favorite: true,
readingStatus: 'reading',
shelfIds: ['classics']
})
})
it('persists shelves and view mode', () => {
saveShelves([{ id: 'classics', name: 'Classics' }])
saveViewMode('list')
expect(loadShelves()).toEqual([{ id: 'classics', name: 'Classics' }])
expect(loadViewMode()).toBe('list')
})
})
@@ -1,77 +0,0 @@
import type { Resource } from '@ownclouders/web-client'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { getReaderProgress } from '../../src/utils/readerProgress'
const values = new Map<string, string>()
const resource = { id: 'book-id' } as Resource
beforeEach(() => {
values.clear()
vi.stubGlobal('localStorage', {
getItem: (key: string) => values.get(key) ?? null
})
})
describe('EPUB reader progress', () => {
it('reads the location saved by the built-in EPUB reader', () => {
values.set(
'oc_epubReader_resource_book-id',
JSON.stringify({
currentLocation: {
start: { cfi: 'epubcfi(/6/4!/4/2)', percentage: 0.42 }
}
})
)
expect(getReaderProgress(resource)).toEqual({
finished: false,
hasPosition: true,
percentage: 42
})
})
it('returns an empty state for books that have not been opened', () => {
expect(getReaderProgress(resource)).toEqual({ finished: false, hasPosition: false })
})
it('estimates progress when EPUB.js leaves its percentage at zero', () => {
values.set(
'oc_epubReader_resource_book-id',
JSON.stringify({
currentLocation: {
atStart: false,
start: {
cfi: 'epubcfi(/6/8!/4/2)',
index: 2,
percentage: 0,
displayed: { page: 3, total: 10 }
}
}
})
)
expect(getReaderProgress(resource, 10)).toEqual({
finished: false,
hasPosition: true,
percentage: 22
})
})
it('marks a location at the end as finished', () => {
values.set(
'oc_epubReader_resource_book-id',
JSON.stringify({
currentLocation: {
atEnd: true,
start: { cfi: 'epubcfi(/6/20!/4/2)', index: 9, percentage: 0 }
}
})
)
expect(getReaderProgress(resource, 10)).toEqual({
finished: true,
hasPosition: true,
percentage: 100
})
})
})
@@ -1,287 +0,0 @@
import { mock } from 'vitest-mock-extended'
import { Resource, SearchResource, SpaceResource } from '@ownclouders/web-client'
import {
defaultComponentMocks,
getComposableWrapper,
nextTicks,
RouteLocation
} from '@ownclouders/web-test-helpers'
import { useLibrary } from '../../src/composables/useLibrary'
import * as cache from '../../src/utils/cache'
import * as epub from '../../src/utils/epub'
import * as preferences from '../../src/utils/preferences'
import * as readerProgress from '../../src/utils/readerProgress'
const { copyToClipboard, downloadFile, showErrorMessage } = vi.hoisted(() => ({
copyToClipboard: vi.fn(),
downloadFile: vi.fn(),
showErrorMessage: vi.fn()
}))
vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({
...(await importOriginal<typeof import('@ownclouders/web-pkg')>()),
useClipboard: () => ({ copyToClipboard }),
useDownloadFile: () => ({ downloadFile }),
useMessages: () => ({ showErrorMessage, showMessage: vi.fn() })
}))
vi.mock('../../src/utils/cache')
vi.mock('../../src/utils/epub')
vi.mock('../../src/utils/preferences')
vi.mock('../../src/utils/readerProgress')
const personalSpace = mock<SpaceResource>({ id: 'space-1', name: 'Personal', path: '/' })
const projectSpace = mock<SpaceResource>({ id: 'space-2', name: 'Project', path: '/' })
function epubResource(overrides: Partial<Resource> = {}): Resource {
return {
id: 'file-1',
fileId: 'file-1',
name: 'Book.epub',
path: '/Books/Book.epub',
spaceId: 'space-1',
storageId: 'space-1',
isFolder: false,
type: 'file',
mdate: 'Wed, 15 Jul 2026 10:00:00 GMT',
privateLink: 'https://cloud.example/f/file-1',
...overrides
} as Resource
}
function searchResult(resources: Resource[]) {
return {
resources: resources.map((resource) => ({ ...resource, highlights: '' })) as SearchResource[],
totalResults: resources.length
}
}
beforeEach(() => {
vi.clearAllMocks()
copyToClipboard.mockResolvedValue(undefined)
downloadFile.mockResolvedValue(undefined)
vi.mocked(cache.getCachedMetadata).mockResolvedValue(null)
vi.mocked(cache.setCachedMetadata).mockResolvedValue()
vi.mocked(epub.extractEpubMetadata).mockResolvedValue({
title: 'Book',
authors: ['Author'],
description: '',
language: '',
publisher: '',
published: '',
subjects: [],
spineItemCount: 1
})
vi.mocked(epub.titleFromFileName).mockImplementation((name: string) =>
name.replace(/\.epub$/, '')
)
vi.mocked(preferences.getBookPreferences).mockReturnValue({
favorite: false,
readingStatus: 'unread',
shelfIds: []
})
vi.mocked(preferences.loadShelves).mockReturnValue([])
vi.mocked(readerProgress.getReaderProgress).mockReturnValue({
finished: false,
hasPosition: false
})
})
describe('useLibrary', () => {
describe('discovery', () => {
it('uses webdav.search when search-files is available and skips the folder scan', async () => {
await withLibrary({ searchAvailable: true }, async ({ library, clientService }) => {
clientService.webdav.search.mockResolvedValue(searchResult([epubResource()]))
await library.loadBooks()
expect(clientService.webdav.search).toHaveBeenCalledWith(
'name:*.epub',
expect.objectContaining({ searchLimit: expect.any(Number) })
)
expect(clientService.webdav.listFiles).not.toHaveBeenCalled()
expect(library.books.value).toHaveLength(1)
})
})
it('falls back to scanning folders when search-files is not supported', async () => {
await withLibrary({ searchAvailable: false }, async ({ library, clientService }) => {
clientService.webdav.listFiles.mockResolvedValue({
resource: mock<Resource>(),
children: [epubResource()]
})
await library.loadBooks()
expect(clientService.webdav.search).not.toHaveBeenCalled()
expect(clientService.webdav.listFiles).toHaveBeenCalled()
expect(library.books.value).toHaveLength(1)
})
})
it('falls back to scanning folders when the search request fails', async () => {
await withLibrary({ searchAvailable: true }, async ({ library, clientService }) => {
clientService.webdav.search.mockRejectedValue(new Error('boom'))
clientService.webdav.listFiles.mockResolvedValue({
resource: mock<Resource>(),
children: [epubResource()]
})
await library.loadBooks()
expect(clientService.webdav.listFiles).toHaveBeenCalled()
expect(library.books.value).toHaveLength(1)
})
})
it('deduplicates books discovered under the same id', async () => {
await withLibrary({ searchAvailable: true }, async ({ library, clientService }) => {
clientService.webdav.search.mockResolvedValue(
searchResult([epubResource(), epubResource({ path: '/Other/Book.epub' })])
)
await library.loadBooks()
expect(library.books.value).toHaveLength(1)
})
})
it('drops results whose space is not available', async () => {
await withLibrary({ searchAvailable: true }, async ({ library, clientService }) => {
clientService.webdav.search.mockResolvedValue(
searchResult([
epubResource({ id: 'x', fileId: 'x', spaceId: 'unknown', storageId: 'unknown' })
])
)
await library.loadBooks()
expect(library.books.value).toHaveLength(0)
})
})
it('surfaces an error when all discovery fails', async () => {
await withLibrary({ searchAvailable: false }, async ({ library, clientService }) => {
clientService.webdav.listFiles.mockRejectedValue(new Error('unreachable'))
await library.loadBooks()
expect(library.error.value).toBe('unreachable')
expect(library.books.value).toHaveLength(0)
})
})
})
describe('hydration', () => {
it('reads metadata for every discovered book', async () => {
await withLibrary({ searchAvailable: true }, async ({ library, clientService }) => {
clientService.webdav.search.mockResolvedValue(
searchResult([
epubResource(),
epubResource({ id: 'file-2', fileId: 'file-2', path: '/Books/Second.epub' })
])
)
clientService.webdav.getFileContents.mockResolvedValue({
response: { data: new Blob() }
} as never)
await library.loadBooks()
expect(epub.extractEpubMetadata).toHaveBeenCalledTimes(2)
expect(library.books.value.every((book) => !book.loadingMetadata)).toBe(true)
})
})
it('records a metadata error without failing the whole load', async () => {
await withLibrary({ searchAvailable: true }, async ({ library, clientService }) => {
clientService.webdav.search.mockResolvedValue(searchResult([epubResource()]))
clientService.webdav.getFileContents.mockRejectedValue(new Error('no bytes'))
await library.loadBooks()
expect(library.books.value[0].metadataError).toBeTruthy()
expect(library.books.value[0].loadingMetadata).toBe(false)
})
})
})
describe('actions', () => {
it('copies the resource private link to the clipboard', async () => {
await withLibrary({ searchAvailable: true }, async ({ library }) => {
const book = { resource: epubResource(), space: personalSpace } as never
const success = await library.copyBookLink(book)
expect(success).toBe(true)
expect(copyToClipboard).toHaveBeenCalledWith('https://cloud.example/f/file-1')
})
})
it('reports an error when no private link is available', async () => {
await withLibrary({ searchAvailable: true }, async ({ library }) => {
const book = {
resource: epubResource({ privateLink: undefined }),
space: personalSpace
} as never
const success = await library.copyBookLink(book)
expect(success).toBe(false)
expect(copyToClipboard).not.toHaveBeenCalled()
expect(showErrorMessage).toHaveBeenCalled()
})
})
it('delegates downloads to useDownloadFile', async () => {
await withLibrary({ searchAvailable: true }, async ({ library }) => {
const resource = epubResource()
const book = { resource, space: personalSpace } as never
await library.downloadBook(book)
expect(downloadFile).toHaveBeenCalledWith(personalSpace, resource)
})
})
})
})
type LibraryInstance = ReturnType<typeof useLibrary>
async function withLibrary(
{ searchAvailable }: { searchAvailable: boolean },
scenario: (ctx: {
library: LibraryInstance
clientService: ReturnType<typeof defaultComponentMocks>['$clientService']
}) => Promise<void>
) {
const componentMocks = defaultComponentMocks({
currentRoute: mock<RouteLocation>({ name: 'epub-library' })
})
let library!: LibraryInstance
const wrapper = getComposableWrapper(
() => {
library = useLibrary()
},
{
mocks: componentMocks,
provide: componentMocks,
pluginOptions: {
piniaOptions: {
spacesState: { spaces: [personalSpace, projectSpace] },
capabilityState: {
capabilities: {
dav: { reports: searchAvailable ? ['search-files'] : [] }
} as never
}
}
}
}
)
try {
await scenario({ library, clientService: componentMocks.$clientService })
await nextTicks(2)
} finally {
wrapper.unmount()
}
}
@@ -17,7 +17,6 @@
<script lang="ts" setup>
import { ref } from 'vue'
import { PASSWORD_PROTECTED_FOLDER_VIEW_QUERY } from '@ownclouders/web-client'
import { Modal, useThemeStore } from '@ownclouders/web-pkg/src/composables'
import AppLoadingSpinner from '@ownclouders/web-pkg/src/components/AppLoadingSpinner.vue'
import { unref } from 'vue'
@@ -47,9 +46,6 @@ iframeUrl.searchParams.append('hide-app-switcher', 'true')
iframeUrl.searchParams.append('hide-account-menu', 'true')
iframeUrl.searchParams.append('hide-navigation', 'true')
iframeUrl.searchParams.append('lang', current)
// signals the framed app that it runs inside this modal, so it notifies us when the
// shared folder is renamed and we can keep the `.psec` pointer file in sync
iframeUrl.searchParams.append(PASSWORD_PROTECTED_FOLDER_VIEW_QUERY, 'true')
const onLoad = () => {
isLoading.value = false
@@ -1,17 +1,5 @@
import {
FileAction,
renameResource,
useClientService,
useConfigStore,
useModals,
useResourcesStore
} from '@ownclouders/web-pkg'
import {
PASSWORD_PROTECTED_FOLDER_FILE_EXTENSION,
PASSWORD_PROTECTED_FOLDER_RENAMED_MESSAGE
} from '@ownclouders/web-client'
import { FileAction, useClientService, useConfigStore, useModals } from '@ownclouders/web-pkg'
import { computed } from 'vue'
import { dirname, join } from 'path'
import { useGettext } from 'vue3-gettext'
import FolderViewModal from '../components/FolderViewModal.vue'
@@ -20,7 +8,6 @@ export const useOpenFolderAction = () => {
const { dispatchModal } = useModals()
const clientService = useClientService()
const configStore = useConfigStore()
const { upsertResource } = useResourcesStore()
const action = computed<FileAction>(() => ({
name: 'open-password-protected-folder',
@@ -39,8 +26,7 @@ export const useOpenFolderAction = () => {
)
)
}
const serverOrigin = new URL(configStore.serverUrl).origin
if (publicLinkUrl.origin !== serverOrigin) {
if (publicLinkUrl.origin !== new URL(configStore.serverUrl).origin) {
throw new Error(
$pgettext(
'Error shown when opening a password-protected folder fails because the stored link points to a different server.',
@@ -49,39 +35,6 @@ export const useOpenFolderAction = () => {
)
}
// The real folder is only reachable through the public link session running inside the
// modal, so it may be renamed there. The `.psec` pointer file cannot be re-resolved from
// the folder afterwards (the two are coupled only by name), so the framed app posts the
// new folder name to us at rename time and we keep the `.psec` file in sync here.
const onFolderRenamed = async (event: MessageEvent) => {
if (event.origin !== serverOrigin) {
return
}
if (event.data?.name !== PASSWORD_PROTECTED_FOLDER_RENAMED_MESSAGE) {
return
}
const newName = event.data?.data?.newName
const currentName = file.name.replace(
new RegExp(`\\.${PASSWORD_PROTECTED_FOLDER_FILE_EXTENSION}$`),
''
)
if (!newName || newName === currentName) {
return
}
const newPsecName = `${newName}.${PASSWORD_PROTECTED_FOLDER_FILE_EXTENSION}`
const newPsecPath = join(dirname(file.path), newPsecName)
await clientService.webdav.moveFiles(space, file, space, { path: newPsecPath })
const updatedFile = { ...file }
renameResource(space, updatedFile, newPsecPath)
upsertResource(updatedFile)
}
window.addEventListener('message', onFolderRenamed)
dispatchModal({
title: resources.at(0).name,
elementClass: 'folder-view-modal',
@@ -91,10 +44,7 @@ export const useOpenFolderAction = () => {
serverUrl: configStore.serverUrl
}),
hideConfirmButton: true,
cancelText: $gettext('Close folder'),
onCancel: () => {
window.removeEventListener('message', onFolderRenamed)
}
cancelText: $gettext('Close folder')
})
},
label: () => $gettext('Open folder'),
@@ -15,7 +15,7 @@ describe('FolderViewModal', () => {
const iframe = wrapper.find(SELECTORS.iframe)
expect(iframe.attributes('src')).toEqual(
'https://example.org/public-link?hide-logo=true&hide-app-switcher=true&hide-account-menu=true&hide-navigation=true&lang=en&password-protected-folder-view=true'
'https://example.org/public-link?hide-logo=true&hide-app-switcher=true&hide-account-menu=true&hide-navigation=true&lang=en'
)
})
@@ -1,44 +1,19 @@
import {
defaultComponentMocks,
flushPromises,
getComposableWrapper,
writable
} from '@ownclouders/web-test-helpers'
import { useOpenFolderAction } from '../../../src/composables/useOpenFolderAction'
import { unref } from 'vue'
import { mock } from 'vitest-mock-extended'
import {
PASSWORD_PROTECTED_FOLDER_RENAMED_MESSAGE,
Resource,
SpaceResource
} from '@ownclouders/web-client'
import { useConfigStore, useModals, useResourcesStore } from '@ownclouders/web-pkg'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { useConfigStore, useModals } from '@ownclouders/web-pkg'
import { MockedFunction } from 'vitest'
import FolderViewModal from '../../../src/components/FolderViewModal.vue'
const SERVER_URL = 'https://example.org/'
const SERVER_ORIGIN = 'https://example.org'
describe('openFolderAction', () => {
// the composable registers a `message` listener on `window`, which is shared across tests
// in the same jsdom environment. Track and remove them so a listener from one test cannot
// react to a message dispatched by another.
const trackedListeners: Array<[string, EventListenerOrEventListenerObject]> = []
const originalAddEventListener = window.addEventListener.bind(window)
beforeEach(() => {
trackedListeners.length = 0
vi.spyOn(window, 'addEventListener').mockImplementation((type, listener) => {
trackedListeners.push([type, listener])
originalAddEventListener(type, listener)
})
})
afterEach(() => {
trackedListeners.forEach(([type, listener]) => window.removeEventListener(type, listener))
vi.restoreAllMocks()
})
it('should open a modal with the public link', () => {
getWrapper({
async setup(instance) {
@@ -97,121 +72,6 @@ describe('openFolderAction', () => {
})
}
)
describe('sync of the .psec file when the folder is renamed inside the modal', () => {
const psecFile = mock<Resource>({ name: 'old.psec', path: '/old.psec' })
const renamedMessage = (newName: string, origin = SERVER_ORIGIN) =>
new MessageEvent('message', {
origin,
data: { name: PASSWORD_PROTECTED_FOLDER_RENAMED_MESSAGE, data: { newName } }
})
const openModal = (instance: ReturnType<typeof useOpenFolderAction>) =>
unref(instance).handler({
resources: [psecFile],
space: mock<SpaceResource>({ webDavPath: '/files/admin' })
})
it('renames the .psec file when the folder is renamed in the framed app', async () => {
let assertions: () => void
const { setupPromise } = getWrapper({
async setup(instance, mocks) {
await openModal(instance)
window.dispatchEvent(renamedMessage('new'))
await flushPromises()
assertions = () => {
expect(mocks.$clientService.webdav.moveFiles).toHaveBeenCalledWith(
expect.anything(),
psecFile,
expect.anything(),
{ path: '/new.psec' }
)
const { upsertResource } = useResourcesStore()
expect(upsertResource).toHaveBeenCalledTimes(1)
}
}
})
await setupPromise
assertions()
})
it('ignores messages from a foreign origin', async () => {
let assertions: () => void
const { setupPromise } = getWrapper({
async setup(instance, mocks) {
await openModal(instance)
window.dispatchEvent(renamedMessage('new', 'https://evil.example.com'))
await flushPromises()
assertions = () => expect(mocks.$clientService.webdav.moveFiles).not.toHaveBeenCalled()
}
})
await setupPromise
assertions()
})
it('ignores unrelated messages', async () => {
let assertions: () => void
const { setupPromise } = getWrapper({
async setup(instance, mocks) {
await openModal(instance)
window.dispatchEvent(
new MessageEvent('message', {
origin: SERVER_ORIGIN,
data: { name: 'some-other-message', data: { newName: 'new' } }
})
)
await flushPromises()
assertions = () => expect(mocks.$clientService.webdav.moveFiles).not.toHaveBeenCalled()
}
})
await setupPromise
assertions()
})
it('does nothing when the name is unchanged', async () => {
let assertions: () => void
const { setupPromise } = getWrapper({
async setup(instance, mocks) {
await openModal(instance)
window.dispatchEvent(renamedMessage('old'))
await flushPromises()
assertions = () => expect(mocks.$clientService.webdav.moveFiles).not.toHaveBeenCalled()
}
})
await setupPromise
assertions()
})
it('stops listening once the modal is closed', async () => {
let assertions: () => void
const { setupPromise } = getWrapper({
async setup(instance, mocks) {
await openModal(instance)
const { dispatchModal } = useModals()
const modalConfig = (dispatchModal as MockedFunction<typeof dispatchModal>).mock.calls
.at(0)
.at(0)
modalConfig.onCancel()
window.dispatchEvent(renamedMessage('new'))
await flushPromises()
assertions = () => expect(mocks.$clientService.webdav.moveFiles).not.toHaveBeenCalled()
}
})
await setupPromise
assertions()
})
})
})
function getWrapper({
@@ -227,19 +87,18 @@ function getWrapper({
const mocks = defaultComponentMocks()
mocks.$clientService.webdav.getFileContents.mockResolvedValue({ body })
let setupPromise: unknown
const wrapper = getComposableWrapper(
() => {
const configStore = useConfigStore()
writable(configStore).serverUrl = SERVER_URL
const instance = useOpenFolderAction()
setupPromise = setup(instance, mocks)
},
{
mocks,
provide: mocks
}
)
return { wrapper, setupPromise }
return {
wrapper: getComposableWrapper(
() => {
const configStore = useConfigStore()
writable(configStore).serverUrl = SERVER_URL
const instance = useOpenFolderAction()
setup(instance, mocks)
},
{
mocks,
provide: mocks
}
)
}
}
-16
View File
@@ -1,21 +1,5 @@
export const PASSWORD_PROTECTED_FOLDER_FILE_EXTENSION = 'psec'
/**
* Query param set on the public link opened inside the password-protected-folder view
* modal. It tells the framed app instance that it is running inside that modal, so it can
* notify the parent window when the shared folder is renamed (see the message name below).
*/
export const PASSWORD_PROTECTED_FOLDER_VIEW_QUERY = 'password-protected-folder-view'
/**
* postMessage name emitted by the framed public-link app when the password-protected folder
* (the public link root) is renamed inside the modal, so the parent window can keep the
* `.psec` pointer file in sync. The `.psec` file cannot be resolved from the folder's new
* name (the coupling is name-based), so the new name is delivered here at rename time.
*/
export const PASSWORD_PROTECTED_FOLDER_RENAMED_MESSAGE =
'owncloud-password-protected-folder:renamed'
/**
* List of file extensions that should be hidden from the user.
* Hiding the extension currently leads to hiding all actions except delete.
@@ -1,19 +1,13 @@
import { isSameResource } from '../../../helpers/resource'
import { isLocationTrashActive, isLocationSharesActive } from '../../../router'
import {
PASSWORD_PROTECTED_FOLDER_FILE_EXTENSION,
PASSWORD_PROTECTED_FOLDER_RENAMED_MESSAGE,
Resource
} from '@ownclouders/web-client'
import { Resource } from '@ownclouders/web-client'
import { dirname, join } from 'path'
import { WebDAV } from '@ownclouders/web-client/webdav'
import {
SpaceResource,
isPublicSpaceResource,
isShareSpaceResource,
extractNameWithoutExtension
} from '@ownclouders/web-client'
import { useResolvePasswordProtectedFolderCounterpart } from '../helpers'
import { createFileRouteOptions } from '../../../helpers/router'
import { renameResource as _renameResource } from '../../../helpers/resource'
import { computed } from 'vue'
@@ -44,7 +38,6 @@ export const useFileActionsRename = () => {
const resourcesStore = useResourcesStore()
const { setCurrentFolder, upsertResource } = resourcesStore
const { getPsecFile } = useResolvePasswordProtectedFolderCounterpart()
const getNameErrorMsg = (
resource: Resource,
@@ -100,56 +93,11 @@ export const useFileActionsRename = () => {
let currentFolder = resourcesStore.currentFolder
try {
// Renaming the real folder of a password protected folder must keep the `.psec`
// pointer file in sync. The pointer is named `<folderName>.psec` and may live in a
// different space than the folder (which always lives in the personal space), so it
// has to be resolved from the folder's current name *before* the folder is moved.
const isPasswordProtectedFolder =
resource.isFolder &&
resource.path.startsWith('/.PasswordProtectedFolders/projects/') &&
resource.name !== newName
const psecFilePromise = isPasswordProtectedFolder
? getPsecFile(resource)
: Promise.resolve(null)
const newPath = join(dirname(resource.path), newName)
await (clientService.webdav as WebDAV).moveFiles(space, resource, space, {
path: newPath
})
const resolvedPsecFile = await psecFilePromise
if (resolvedPsecFile) {
const { psecFile, space: psecSpace } = resolvedPsecFile
const newPsecName = `${newName}.${PASSWORD_PROTECTED_FOLDER_FILE_EXTENSION}`
const newPsecPath = join(dirname(psecFile.path), newPsecName)
await (clientService.webdav as WebDAV).moveFiles(psecSpace, psecFile, psecSpace, {
path: newPsecPath
})
const updatedPsecFile = { ...psecFile } as Resource
_renameResource(psecSpace, updatedPsecFile, newPsecPath)
upsertResource(updatedPsecFile)
}
// When this app instance runs framed inside the password-protected-folder view modal,
// renaming the shared folder (the public link root) here cannot update the owner's
// `.psec` pointer file: it lives in the parent window's session and is coupled only by
// name. Notify the parent so it can rename the `.psec` file at the same time. The check
// `resource.fileId === space.fileId` guarantees this only fires for the shared folder
// itself, never for a child resource renamed inside it.
if (
window.parent !== window &&
configStore.options.passwordProtectedFolderView &&
isPublicSpaceResource(space) &&
resource.fileId === space.fileId
) {
window.parent.postMessage(
{ name: PASSWORD_PROTECTED_FOLDER_RENAMED_MESSAGE, data: { newName } },
window.location.origin
)
}
const isCurrentFolder = isSameResource(resource, currentFolder)
if (isShareSpaceResource(space) && resource.isReceivedShare()) {
@@ -144,25 +144,8 @@ export const useFileActionsRestore = () => {
originalRoute.name === unref(router.currentRoute).name &&
originalRoute.query?.fileId === unref(router.currentRoute).query?.fileId
) {
if (isLocationTrashActive(router, 'files-trash-generic')) {
resourcesStore.removeResources(successful)
resourcesStore.resetSelection()
} else {
// restored items now live in the currently viewed folder, fetch their fresh info and show them.
// a single failing lookup must not abort the whole refresh, so upsert whatever resolves
const restoredResources = (
await Promise.allSettled(
successful.map((resource) =>
clientService.webdav.getFileInfo(space, { path: resource.path })
)
)
)
.filter((result) => result.status === 'fulfilled')
.map((result) => result.value)
if (restoredResources.length) {
resourcesStore.upsertResources(restoredResources)
}
}
resourcesStore.removeResources(successful)
resourcesStore.resetSelection()
}
// Reload quota
@@ -254,7 +237,6 @@ export const useFileActionsRestore = () => {
return {
actions,
handler,
// HACK: exported for unit tests:
restoreResources,
collectConflicts
@@ -1,5 +1,3 @@
export * from './useIsSearchActive'
export * from './useFileActionsDeleteResources'
export * from './useIsFilesAppActive'
export * from './useResolvePasswordProtectedFolderCounterpart'
export * from './useResolveRestorableResources'
@@ -29,8 +29,6 @@ import {
import { storeToRefs } from 'pinia'
import { useDeleteWorker } from '../../webWorkers'
import { captureException } from '@sentry/vue'
import { useResolveRestorableResources } from './useResolveRestorableResources'
import { useFileActionsRestore } from '../files/useFileActionsRestore'
export const useFileActionsDeleteResources = () => {
const configStore = useConfigStore()
@@ -46,8 +44,6 @@ export const useFileActionsDeleteResources = () => {
const { startWorker } = useDeleteWorker({
concurrentRequests: configStore.options.concurrentRequests.resourceBatchActions
})
const { resolveRestorableResources } = useResolveRestorableResources()
const { handler: restoreHandler } = useFileActionsRestore()
const resourcesStore = useResourcesStore()
const { currentFolder } = storeToRefs(resourcesStore)
@@ -295,32 +291,7 @@ export const useFileActionsDeleteResources = () => {
{ itemCount: successful.length.toString() }
)
const restorableResources = await resolveRestorableResources(
spaceForDeletion,
successful
)
messageStore.showMessage({
title,
...(restorableResources && {
timeout: 5,
actions: [
{
label: $gettext('Undo'),
ariaLabel:
restorableResources.length === 1
? $gettext('Undo delete of "%{item}"', {
item: restorableResources[0].name
})
: $gettext('Undo delete of %{itemCount} items', {
itemCount: restorableResources.length.toString()
}),
onClick: () =>
restoreHandler({ space: spaceForDeletion, resources: restorableResources })
}
]
})
})
messageStore.showMessage({ title })
}
resourcesStore.removeResourcesFromDeleteQueue(failed.map(({ resource }) => resource.id))
@@ -1,89 +0,0 @@
import {
DavHttpError,
PASSWORD_PROTECTED_FOLDER_FILE_EXTENSION,
Resource,
SpaceResource,
urlJoin
} from '@ownclouders/web-client'
import { captureException } from '@sentry/vue'
import { unref } from 'vue'
import { storeToRefs } from 'pinia'
import { useClientService } from '../../clientService'
import { useGetMatchingSpace } from '../../spaces'
import { useSpacesStore } from '../../piniaStores'
/**
* The `.psec` pointer file together with the space it lives in. The space is needed
* so callers can move/rename the file, since it may reside in a different space than
* the real folder (the folder always lives in the personal space).
*/
export type ResolvedPsecFile = { psecFile: Resource; space: SpaceResource }
/**
* A password protected folder is represented by two independent resources:
* the `.psec` pointer file (visible to the owner) and the real folder living under
* `/.PasswordProtectedFolders/projects/<space>/...` (accessible via the public link).
* This resolves one from the other so callers can keep both in sync.
*/
export const useResolvePasswordProtectedFolderCounterpart = () => {
const clientService = useClientService()
const { getMatchingSpace } = useGetMatchingSpace()
const spacesStore = useSpacesStore()
const { getSpacesByName } = spacesStore
const { personalSpace } = storeToRefs(spacesStore)
const getPasswordProtectedFolder = async (psecFile: Resource): Promise<Resource | null> => {
try {
const matchingSpace = getMatchingSpace(psecFile)
const folderPath = urlJoin(
'/.PasswordProtectedFolders/projects/',
matchingSpace.name,
psecFile.path.replace(psecFile.name, ''),
psecFile.name.replace(`.${PASSWORD_PROTECTED_FOLDER_FILE_EXTENSION}`, '')
)
return await clientService.webdav.getFileInfo(unref(personalSpace), { path: folderPath })
} catch (error) {
if (error instanceof DavHttpError && error.statusCode === 404) {
return null
}
console.error(error)
captureException(error)
return null
}
}
const getPsecFile = async (folder: Resource): Promise<ResolvedPsecFile | null> => {
const [spaceName, ...psecFilePathParts] = folder.path
.replace('/.PasswordProtectedFolders/projects/', '')
.split('/')
const matchingSpaces = getSpacesByName(spaceName)
if (matchingSpaces.length < 1) {
return null
}
for (const space of matchingSpaces) {
try {
const psecFile = await clientService.webdav.getFileInfo(space, {
path: urlJoin(...psecFilePathParts) + '.' + PASSWORD_PROTECTED_FOLDER_FILE_EXTENSION
})
return { psecFile, space }
} catch (error) {
if (error instanceof DavHttpError && error.statusCode === 404) {
continue
}
console.error(error)
captureException(error)
continue
}
}
return null
}
return { getPasswordProtectedFolder, getPsecFile }
}
@@ -1,68 +0,0 @@
import { User } from '@ownclouders/web-client/graph/generated'
import {
isProjectSpaceResource,
Resource,
SpaceResource,
TrashResource
} from '@ownclouders/web-client'
import { DavProperties } from '@ownclouders/web-client/webdav'
import { useClientService } from '../../clientService'
import { useUserStore } from '../../piniaStores'
export const useResolveRestorableResources = () => {
const clientService = useClientService()
const userStore = useUserStore()
const canRestoreDeleteForSpace = (space: SpaceResource, user: User) => {
if (!isProjectSpaceResource(space)) {
return true
}
return space.canRestoreFromTrashbin({ user })
}
/**
* Resolves the trash-bin entries for a batch of just-deleted resources within a single space.
* Returns null if the space doesn't support trash-restore, or if the trash listing fails.
*/
const resolveRestorableResources = async (
space: SpaceResource,
deletedResources: Resource[]
): Promise<TrashResource[] | null> => {
if (!canRestoreDeleteForSpace(space, userStore.user)) {
return null
}
let trashResources: TrashResource[]
try {
const { children } = await clientService.webdav.listFiles(
space,
{},
{ davProperties: DavProperties.Trashbin, isTrash: true }
)
trashResources = children as TrashResource[]
} catch {
return null
}
const resolved: TrashResource[] = []
for (const deleted of deletedResources) {
const candidates = trashResources.filter(
(t) => t.name === deleted.name && t.path === deleted.path
)
if (!candidates.length) {
continue
}
// pick the most recently deleted match
candidates.sort((a, b) => new Date(b.ddate).getTime() - new Date(a.ddate).getTime())
resolved.push(candidates[0])
}
if (resolved.length !== deletedResources.length) {
return null
}
return resolved
}
return { resolveRestorableResources }
}
@@ -12,7 +12,6 @@ export enum Key {
X = 'x',
A = 'a',
S = 's',
Z = 'z',
Space = ' ',
ArrowUp = 'ArrowUp',
ArrowDown = 'ArrowDown',
@@ -126,11 +126,6 @@ const OptionsConfigSchema = z.object({
hideAppSwitcher: z.boolean().optional(),
hideAccountMenu: z.boolean().optional(),
hideNavigation: z.boolean().optional(),
// set when this app instance runs framed inside the password-protected-folder view modal,
// so a rename of the shared folder can be reported to the parent window (see
// PASSWORD_PROTECTED_FOLDER_RENAMED_MESSAGE). Read once at bootstrap from a query param,
// because the router rewrites the URL query before a rename ever happens.
passwordProtectedFolderView: z.boolean().optional(),
defaultLanguage: z.string().optional()
})
@@ -5,12 +5,6 @@ import { HttpError } from '@ownclouders/web-client'
type MessageError = Error | HttpError
export interface MessageAction {
label: string
ariaLabel?: string
onClick: () => void
}
export interface Message {
id: string
title: string
@@ -19,7 +13,6 @@ export interface Message {
errorLogContent?: string
timeout?: number
status?: string
actions?: MessageAction[]
}
export const useMessages = defineStore('messages', () => {
@@ -60,28 +53,11 @@ export const useMessages = defineStore('messages', () => {
messages.value = unref(messages).filter(({ id }) => message.id !== id)
}
/**
* Runs the first action of the most recent message that has one (e.g. "Undo" on a
* delete notification) and dismisses that message. Used by the global Ctrl/Cmd+Z
* shortcut. Returns false if there is no message with an action to trigger.
*/
const triggerLatestAction = (): boolean => {
const message = [...unref(messages)].reverse().find((m) => m.actions?.length)
if (!message) {
return false
}
message.actions[0].onClick()
removeMessage(message)
return true
}
return {
messages,
showMessage,
showErrorMessage,
removeMessage,
triggerLatestAction
removeMessage
}
})
@@ -1,7 +1,5 @@
import { useFileActionsRename } from '../../../../../src/composables/actions'
import { useResolvePasswordProtectedFolderCounterpart } from '../../../../../src/composables/actions/helpers/useResolvePasswordProtectedFolderCounterpart'
import {
useConfigStore,
useMessages,
useModals,
useResourcesStore
@@ -11,10 +9,6 @@ import { Resource, SpaceResource } from '@ownclouders/web-client'
import { defaultComponentMocks, getComposableWrapper } from '@ownclouders/web-test-helpers'
import { unref } from 'vue'
vi.mock(
'../../../../../src/composables/actions/helpers/useResolvePasswordProtectedFolderCounterpart'
)
const currentFolder = {
id: '1',
path: '/folder',
@@ -169,221 +163,11 @@ describe('rename', () => {
}
})
})
describe('password protected folder sync', () => {
const passwordProtectedFolder = {
id: 'ppf',
isFolder: true,
name: 'test',
path: '/.PasswordProtectedFolders/projects/Personal/test',
spaceId: '1'
} as Resource
it('renames the .psec counterpart when the real folder is renamed', () => {
const psecSpace = mockDeep<SpaceResource>({ webDavPath: 'irrelevant' })
const psecFile = mock<Resource>({ id: 'psec', name: 'test.psec', path: '/test.psec' })
const getPsecFile = vi.fn().mockResolvedValue({ psecFile, space: psecSpace })
getWrapper({
getPsecFile,
setup: async ({ renameResource }, { space, clientService }) => {
await renameResource(space, passwordProtectedFolder, 'something')
expect(getPsecFile).toHaveBeenCalledWith(passwordProtectedFolder)
// both the folder itself and the .psec counterpart get moved
expect(clientService.webdav.moveFiles).toHaveBeenCalledWith(
psecSpace,
psecFile,
psecSpace,
{ path: '/something.psec' }
)
// the renamed folder + the renamed .psec file both get upserted
const { upsertResource } = useResourcesStore()
expect(upsertResource).toHaveBeenCalledTimes(2)
}
})
})
it('resolves the .psec counterpart before moving the folder (uses the old name)', () => {
const psecSpace = mockDeep<SpaceResource>({ webDavPath: 'irrelevant' })
const psecFile = mock<Resource>({ id: 'psec', name: 'test.psec', path: '/test.psec' })
const getPsecFile = vi.fn().mockResolvedValue({ psecFile, space: psecSpace })
getWrapper({
getPsecFile,
setup: async ({ renameResource }, { space, clientService }) => {
const callOrder: string[] = []
getPsecFile.mockImplementation(() => {
callOrder.push('getPsecFile')
return Promise.resolve({ psecFile, space: psecSpace })
})
clientService.webdav.moveFiles.mockImplementation(() => {
callOrder.push('moveFiles')
return Promise.resolve(undefined)
})
await renameResource(space, passwordProtectedFolder, 'something')
// getPsecFile must run before any move so it can derive the path from the old folder name
expect(callOrder[0]).toBe('getPsecFile')
}
})
})
it('does not resolve a .psec counterpart for a regular (non-ppf) rename', () => {
const getPsecFile = vi.fn().mockResolvedValue(null)
getWrapper({
getPsecFile,
setup: async ({ renameResource }, { space }) => {
const resource = {
id: '2',
isFolder: true,
name: 'folder',
path: '/folder',
spaceId: '1'
} as Resource
await renameResource(space, resource, 'new name')
expect(getPsecFile).not.toHaveBeenCalled()
}
})
})
it('does not resolve a .psec counterpart when the name is unchanged', () => {
const getPsecFile = vi.fn().mockResolvedValue(null)
getWrapper({
getPsecFile,
setup: async ({ renameResource }, { space }) => {
await renameResource(space, passwordProtectedFolder, passwordProtectedFolder.name)
expect(getPsecFile).not.toHaveBeenCalled()
}
})
})
it('renames the folder normally when no .psec counterpart is found', () => {
const getPsecFile = vi.fn().mockResolvedValue(null)
getWrapper({
getPsecFile,
setup: async ({ renameResource }, { space, clientService }) => {
await renameResource(space, passwordProtectedFolder, 'something')
expect(getPsecFile).toHaveBeenCalledWith(passwordProtectedFolder)
// only the folder itself is moved, no counterpart move
expect(clientService.webdav.moveFiles).toHaveBeenCalledTimes(1)
const { upsertResource } = useResourcesStore()
expect(upsertResource).toHaveBeenCalledTimes(1)
}
})
})
})
// When this app instance runs framed inside the password-protected-folder view modal, a
// rename of the shared folder (the public link root) is posted to the parent window so it
// can keep the owner's `.psec` pointer file in sync.
describe('password protected folder view modal notification', () => {
const publicSpace = mockDeep<SpaceResource>({
driveType: 'public',
webDavPath: 'irrelevant',
fileId: 'root-file-id'
})
const rootFolder = mock<Resource>({
fileId: 'root-file-id',
isFolder: true,
name: 'shared',
path: '/shared'
})
let parentSpy: ReturnType<typeof vi.spyOn>
let originalParent: Window
beforeEach(() => {
originalParent = window.parent
// jsdom sets window.parent === window; simulate being framed
Object.defineProperty(window, 'parent', {
value: { postMessage: vi.fn() },
configurable: true
})
parentSpy = vi.spyOn(window.parent, 'postMessage')
})
afterEach(() => {
Object.defineProperty(window, 'parent', { value: originalParent, configurable: true })
})
it('notifies the parent window when the shared folder is renamed', () => {
getWrapper({
passwordProtectedFolderView: true,
setup: async ({ renameResource }) => {
await renameResource(publicSpace, rootFolder, 'renamed')
expect(parentSpy).toHaveBeenCalledWith(
{
name: 'owncloud-password-protected-folder:renamed',
data: { newName: 'renamed' }
},
window.location.origin
)
}
})
})
it('does not notify for a child resource inside the shared folder', () => {
const childResource = mock<Resource>({
fileId: 'child-file-id',
isFolder: true,
name: 'child',
path: '/child'
})
getWrapper({
passwordProtectedFolderView: true,
setup: async ({ renameResource }) => {
await renameResource(publicSpace, childResource, 'renamed')
expect(parentSpy).not.toHaveBeenCalled()
}
})
})
it('does not notify when not running inside the folder view modal', () => {
getWrapper({
passwordProtectedFolderView: false,
setup: async ({ renameResource }) => {
await renameResource(publicSpace, rootFolder, 'renamed')
expect(parentSpy).not.toHaveBeenCalled()
}
})
})
it('does not notify for a non-public space', () => {
const personalSpace = mockDeep<SpaceResource>({
driveType: 'personal',
webDavPath: 'irrelevant',
fileId: 'root-file-id'
})
getWrapper({
passwordProtectedFolderView: true,
setup: async ({ renameResource }) => {
await renameResource(personalSpace, rootFolder, 'renamed')
expect(parentSpy).not.toHaveBeenCalled()
}
})
})
})
})
})
function getWrapper({
setup,
getPsecFile = vi.fn().mockResolvedValue(null),
passwordProtectedFolderView = false
setup
}: {
setup: (
instance: ReturnType<typeof useFileActionsRename>,
@@ -395,14 +179,7 @@ function getWrapper({
clientService: ReturnType<typeof defaultComponentMocks>['$clientService']
}
) => void
getPsecFile?: ReturnType<typeof vi.fn>
passwordProtectedFolderView?: boolean
}) {
vi.mocked(useResolvePasswordProtectedFolderCounterpart).mockReturnValue({
getPasswordProtectedFolder: vi.fn().mockResolvedValue(null),
getPsecFile
} as unknown as ReturnType<typeof useResolvePasswordProtectedFolderCounterpart>)
const mocks = {
...defaultComponentMocks(),
space: mockDeep<SpaceResource>({
@@ -414,8 +191,6 @@ function getWrapper({
mocks,
wrapper: getComposableWrapper(
() => {
const configStore = useConfigStore()
configStore.options = { ...configStore.options, passwordProtectedFolderView }
const instance = useFileActionsRename()
setup(instance, { space: mocks.space, clientService: mocks.$clientService })
},
@@ -90,49 +90,6 @@ describe('restore', () => {
})
})
it('should upsert restored resources into the current view when not in the trash bin', async () => {
const resourcesToRestore = [{ id: '1', path: '/1', name: 'file1' }] as TrashResource[]
const restoredResource = mock<Resource>({ id: '1', path: '/1', name: 'file1' })
const { getWorkerCallbackDone } = getWrapper({
invalidLocation: true,
setup: ({ restoreResources }, { space }) => {
restoreResources(space, resourcesToRestore, [])
},
restoreResult: { successful: resourcesToRestore, failed: [] },
getFileInfoResult: restoredResource
})
await getWorkerCallbackDone()
const { removeResources, upsertResources } = useResourcesStore()
expect(removeResources).toHaveBeenCalledTimes(0)
expect(upsertResources).toHaveBeenCalledWith([restoredResource])
})
it('should upsert the resolvable resources even when one lookup fails', async () => {
const resourcesToRestore = [
{ id: '1', path: '/1', name: 'file1' },
{ id: '2', path: '/2', name: 'file2' }
] as TrashResource[]
const restoredResource = mock<Resource>({ id: '2', path: '/2', name: 'file2' })
const { getWorkerCallbackDone } = getWrapper({
invalidLocation: true,
setup: ({ restoreResources }, { space }) => {
restoreResources(space, resourcesToRestore, [])
},
restoreResult: { successful: resourcesToRestore, failed: [] },
getFileInfoImplementation: (_, { path }) =>
path === '/2'
? Promise.resolve(restoredResource)
: Promise.reject(new Error('network error'))
})
await getWorkerCallbackDone()
const { upsertResources } = useResourcesStore()
expect(upsertResources).toHaveBeenCalledWith([restoredResource])
})
it('should show message on error', () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
const resourcesToRestore = [{ id: '1', path: '/1' }] as TrashResource[]
@@ -196,8 +153,6 @@ function getWrapper({
invalidLocation = false,
driveType = 'personal',
restoreResult = { successful: [], failed: [] },
getFileInfoResult,
getFileInfoImplementation,
setup
}: {
invalidLocation?: boolean
@@ -206,8 +161,6 @@ function getWrapper({
successful: TrashResource[]
failed: { resource: TrashResource; error: HttpError }[]
}
getFileInfoResult?: Resource
getFileInfoImplementation?: (...args: any[]) => Promise<Resource>
setup: (
instance: ReturnType<typeof useFileActionsRestore>,
{
@@ -219,10 +172,9 @@ function getWrapper({
}
) => void
}) {
let workerCallbackDone: Promise<unknown> = Promise.resolve()
vi.mocked(useRestoreWorker).mockReturnValue({
startWorker: vi.fn().mockImplementation((_, callback) => {
workerCallbackDone = Promise.resolve(callback(restoreResult))
callback(restoreResult)
})
})
@@ -237,16 +189,10 @@ function getWrapper({
mocks.$clientService.webdav.listFiles.mockImplementation(() => {
return Promise.resolve({ resource: mock<Resource>(), children: [] })
})
if (getFileInfoImplementation) {
mocks.$clientService.webdav.getFileInfo.mockImplementation(getFileInfoImplementation)
} else {
mocks.$clientService.webdav.getFileInfo.mockResolvedValue(getFileInfoResult)
}
mocks.$clientService.graphAuthenticated.drives.getDrive.mockResolvedValue(mock<SpaceResource>())
return {
mocks,
getWorkerCallbackDone: () => workerCallbackDone,
wrapper: getComposableWrapper(
() => {
const instance = useFileActionsRestore()
@@ -1,23 +1,17 @@
import { useFileActionsDeleteResources } from '../../../../../src/composables/actions'
import { mock, mockDeep } from 'vitest-mock-extended'
import { FolderResource, Resource, SpaceResource, TrashResource } from '@ownclouders/web-client'
import { FolderResource, Resource, SpaceResource } from '@ownclouders/web-client'
import {
defaultComponentMocks,
getComposableWrapper,
useGetMatchingSpaceMock
} from '@ownclouders/web-test-helpers'
import { useDeleteWorker } from '../../../../../src/composables/webWorkers/deleteWorker'
import { useRestoreWorker } from '../../../../../src/composables/webWorkers/restoreWorker'
import { useGetMatchingSpace } from '../../../../../src/composables/spaces/useGetMatchingSpace'
import {
useMessages,
useResourcesStore,
useSpacesStore
} from '../../../../../src/composables/piniaStores'
import { useResourcesStore, useSpacesStore } from '../../../../../src/composables/piniaStores'
import { MockedFunction } from 'vitest'
vi.mock('../../../../../src/composables/webWorkers/deleteWorker')
vi.mock('../../../../../src/composables/webWorkers/restoreWorker')
vi.mock('../../../../../src/composables/spaces/useGetMatchingSpace')
const currentFolder = {
@@ -136,107 +130,6 @@ describe('deleteResources', () => {
}
})
})
describe('undo action on the success message', () => {
const deletedFile = mock<Resource>({
id: '2',
name: 'fileToDelete.txt',
path: '/folder/fileToDelete.txt',
storageId: 'personal',
spaceId: '1'
})
it('is included when the space allows trash-restore and the trash entry resolves', async () => {
const trashEntry = mock<TrashResource>({
name: deletedFile.name,
path: deletedFile.path,
ddate: '2026-01-01T00:00:00Z'
})
const { getWorkerCallbackDone } = getWrapper({
currentFolder,
result: [deletedFile],
listFilesResult: { resource: mock<Resource>(), children: [trashEntry] },
setup: ({ filesList_delete }) => {
filesList_delete([deletedFile])
}
})
await getWorkerCallbackDone()
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalledWith(
expect.objectContaining({
timeout: 5,
actions: [expect.objectContaining({ label: 'Undo' })]
})
)
})
it('is omitted when the trash entry cannot be resolved', async () => {
const { getWorkerCallbackDone } = getWrapper({
currentFolder,
result: [deletedFile],
listFilesResult: { resource: mock<Resource>(), children: [] },
setup: ({ filesList_delete }) => {
filesList_delete([deletedFile])
}
})
await getWorkerCallbackDone()
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalledWith(
expect.not.objectContaining({ actions: expect.anything() })
)
})
it('is omitted when the space does not allow trash-restore', async () => {
const { getWorkerCallbackDone } = getWrapper({
currentFolder,
result: [deletedFile],
spaceDriveType: 'project',
canRestoreFromTrashbin: false,
setup: ({ filesList_delete }) => {
filesList_delete([deletedFile])
}
})
await getWorkerCallbackDone()
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalledWith(
expect.not.objectContaining({ actions: expect.anything() })
)
})
it('restores the resolved trash entry when clicked', async () => {
const trashEntry = mock<TrashResource>({
name: deletedFile.name,
path: deletedFile.path,
ddate: '2026-01-01T00:00:00Z'
})
let spaceUnderTest: SpaceResource
const { getWorkerCallbackDone } = getWrapper({
currentFolder,
result: [deletedFile],
listFilesResult: { resource: mock<Resource>(), children: [trashEntry] },
setup: ({ filesList_delete }, { space }) => {
spaceUnderTest = space
filesList_delete([deletedFile])
}
})
await getWorkerCallbackDone()
const { showMessage } = useMessages()
const call = (showMessage as MockedFunction<typeof showMessage>).mock.calls[0][0]
await call.actions[0].onClick()
const { startWorker } = vi.mocked(useRestoreWorker)()
expect(startWorker).toHaveBeenCalledWith(
expect.objectContaining({ space: spaceUnderTest, resources: [trashEntry] }),
expect.any(Function)
)
})
})
})
})
@@ -244,10 +137,7 @@ function getWrapper({
currentFolder,
setup,
result = [],
getFileInfoResult,
listFilesResult = { resource: mock<Resource>(), children: [] },
spaceDriveType = 'personal',
canRestoreFromTrashbin = true
getFileInfoResult
}: {
currentFolder: FolderResource
setup: (
@@ -262,37 +152,17 @@ function getWrapper({
) => void
result?: Resource[]
getFileInfoResult?: Resource
listFilesResult?: { resource: Resource; children: Resource[] }
spaceDriveType?: string
canRestoreFromTrashbin?: boolean
}) {
const mocks = {
...defaultComponentMocks(),
space: mockDeep<SpaceResource>({
id: 'personal',
driveType: spaceDriveType,
canRestoreFromTrashbin: () => canRestoreFromTrashbin
})
space: mockDeep<SpaceResource>({ id: 'personal' })
}
mocks.$clientService.webdav.deleteFile.mockResolvedValue(undefined)
mocks.$clientService.webdav.getFileInfo.mockResolvedValue(getFileInfoResult)
mocks.$clientService.webdav.listFiles.mockImplementation((_, __, opts) => {
if (opts?.isTrash) {
return Promise.resolve(listFilesResult)
}
return Promise.resolve({ resource: mock<Resource>(), children: [] })
})
let workerCallbackDone: Promise<unknown> = Promise.resolve()
vi.mocked(useDeleteWorker).mockReturnValue({
startWorker: vi.fn().mockImplementation((_, callback) => {
workerCallbackDone = Promise.resolve(callback({ successful: result, failed: [] }))
})
})
vi.mocked(useRestoreWorker).mockReturnValue({
startWorker: vi.fn().mockImplementation((_, callback) => {
callback({ successful: [], failed: [] })
callback({ successful: result, failed: [] })
})
})
@@ -305,7 +175,6 @@ function getWrapper({
return {
mocks,
getWorkerCallbackDone: () => workerCallbackDone,
wrapper: getComposableWrapper(
() => {
const instance = useFileActionsDeleteResources()
@@ -1,133 +0,0 @@
import { mock } from 'vitest-mock-extended'
import { Resource, SpaceResource, TrashResource } from '@ownclouders/web-client'
import { defaultComponentMocks, getComposableWrapper } from '@ownclouders/web-test-helpers'
import { useUserStore } from '../../../../../src/composables/piniaStores'
import { useResolveRestorableResources } from '../../../../../src/composables/actions/helpers/useResolveRestorableResources'
describe('resolveRestorableResources', () => {
it('returns null when the space does not allow trash-restore', () => {
const space = mock<SpaceResource>({ driveType: 'project', canRestoreFromTrashbin: () => false })
const deleted = [mock<Resource>({ name: 'file.txt', path: '/file.txt' })]
getWrapper({
setup: async ({ resolveRestorableResources }, { clientService }) => {
const result = await resolveRestorableResources(space, deleted)
expect(result).toBeNull()
expect(clientService.webdav.listFiles).not.toHaveBeenCalled()
}
})
})
it('returns null when listing the trash bin fails', () => {
const space = mock<SpaceResource>({ driveType: 'personal' })
const deleted = [mock<Resource>({ name: 'file.txt', path: '/file.txt' })]
getWrapper({
setup: async ({ resolveRestorableResources }) => {
const result = await resolveRestorableResources(space, deleted)
expect(result).toBeNull()
},
listFilesImplementation: () => Promise.reject(new Error('network error'))
})
})
it('returns null when not every deleted resource has a matching trash entry', () => {
const space = mock<SpaceResource>({ driveType: 'personal' })
const deleted = [
mock<Resource>({ name: 'file.txt', path: '/file.txt' }),
mock<Resource>({ name: 'other.txt', path: '/other.txt' })
]
const trashEntry = mock<TrashResource>({
name: 'file.txt',
path: '/file.txt',
ddate: '2026-01-01T00:00:00Z'
})
getWrapper({
setup: async ({ resolveRestorableResources }) => {
const result = await resolveRestorableResources(space, deleted)
expect(result).toBeNull()
},
listFilesImplementation: () =>
Promise.resolve({ resource: mock<Resource>(), children: [trashEntry] })
})
})
it('resolves the matching trash entries for all deleted resources', () => {
const space = mock<SpaceResource>({ driveType: 'personal' })
const deleted = [mock<Resource>({ name: 'file.txt', path: '/file.txt' })]
const trashEntry = mock<TrashResource>({
name: 'file.txt',
path: '/file.txt',
ddate: '2026-01-01T00:00:00Z'
})
getWrapper({
setup: async ({ resolveRestorableResources }) => {
const result = await resolveRestorableResources(space, deleted)
expect(result).toEqual([trashEntry])
},
listFilesImplementation: () =>
Promise.resolve({ resource: mock<Resource>(), children: [trashEntry] })
})
})
it('picks the most recently deleted match when there are duplicates', () => {
const space = mock<SpaceResource>({ driveType: 'personal' })
const deleted = [mock<Resource>({ name: 'file.txt', path: '/file.txt' })]
const olderEntry = mock<TrashResource>({
name: 'file.txt',
path: '/file.txt',
ddate: '2025-01-01T00:00:00Z'
})
const newerEntry = mock<TrashResource>({
name: 'file.txt',
path: '/file.txt',
ddate: '2026-01-01T00:00:00Z'
})
getWrapper({
setup: async ({ resolveRestorableResources }) => {
const result = await resolveRestorableResources(space, deleted)
expect(result).toEqual([newerEntry])
},
listFilesImplementation: () =>
Promise.resolve({ resource: mock<Resource>(), children: [olderEntry, newerEntry] })
})
})
})
function getWrapper({
setup,
listFilesImplementation,
user
}: {
setup: (
instance: ReturnType<typeof useResolveRestorableResources>,
{ clientService }: { clientService: ReturnType<typeof defaultComponentMocks>['$clientService'] }
) => void
listFilesImplementation?: () => Promise<any>
user?: any
}) {
const mocks = defaultComponentMocks()
mocks.$clientService.webdav.listFiles.mockImplementation(
listFilesImplementation || (() => Promise.resolve({ resource: mock<Resource>(), children: [] }))
)
return {
mocks,
wrapper: getComposableWrapper(
() => {
if (user) {
useUserStore().setUser(user)
}
const instance = useResolveRestorableResources()
setup(instance, { clientService: mocks.$clientService })
},
{
mocks,
provide: mocks
}
)
}
}
@@ -1,78 +0,0 @@
import { getComposableWrapper } from '@ownclouders/web-test-helpers'
import { useMessages } from '../../../../src/composables/piniaStores'
import { createPinia, setActivePinia } from 'pinia'
describe('useMessages', () => {
beforeEach(() => {
setActivePinia(createPinia())
})
describe('method "triggerLatestAction"', () => {
it('returns false when there are no messages', () => {
getWrapper({
setup: (instance) => {
expect(instance.triggerLatestAction()).toBe(false)
}
})
})
it('returns false when no message has an action', () => {
getWrapper({
setup: (instance) => {
instance.showMessage({ title: 'plain message' })
expect(instance.triggerLatestAction()).toBe(false)
}
})
})
it('runs the action of the most recent message that has one and dismisses it', () => {
getWrapper({
setup: (instance) => {
const onClick = vi.fn()
instance.showMessage({ title: 'plain message' })
const withAction = instance.showMessage({
title: 'undoable message',
actions: [{ label: 'Undo', onClick }]
})
const triggered = instance.triggerLatestAction()
expect(triggered).toBe(true)
expect(onClick).toHaveBeenCalledTimes(1)
expect(instance.messages.find((m) => m.id === withAction.id)).toBeUndefined()
}
})
})
it('skips messages without an action in favor of an earlier one that has one', () => {
getWrapper({
setup: (instance) => {
const onClick = vi.fn()
const withAction = instance.showMessage({
title: 'undoable message',
actions: [{ label: 'Undo', onClick }]
})
instance.showMessage({ title: 'later plain message' })
const triggered = instance.triggerLatestAction()
expect(triggered).toBe(true)
expect(onClick).toHaveBeenCalledTimes(1)
expect(instance.messages.find((m) => m.id === withAction.id)).toBeUndefined()
}
})
})
})
})
function getWrapper({ setup }: { setup: (instance: ReturnType<typeof useMessages>) => void }) {
return {
wrapper: getComposableWrapper(
() => {
const instance = useMessages()
setup(instance)
},
{ pluginOptions: { pinia: false } }
)
}
}
@@ -8,7 +8,6 @@
:status="item.status"
:timeout="item.timeout"
:error-log-content="item.errorLogContent"
:actions="item.actions"
@close="deleteMessage(item)"
/>
</oc-notifications>
@@ -26,7 +26,7 @@
rel="noopener noreferrer"
data-testid="help-menu-software-license-link"
>
<oc-icon name="file-shield" fill-type="line" />
<oc-icon name="scales" fill-type="line" />
<span
v-text="
$pgettext(
@@ -77,7 +77,7 @@ import {
SseEventWrapperOptions
} from './sse'
import { loadAppTranslations } from '../helpers/language'
import { PASSWORD_PROTECTED_FOLDER_VIEW_QUERY, urlJoin } from '@ownclouders/web-client'
import { urlJoin } from '@ownclouders/web-client'
import { supportedLanguages } from '../defaults'
const getEmbedConfigFromQuery = (
@@ -174,7 +174,6 @@ export const announceConfiguration = async ({
hideAppSwitcher: getQueryParam('hide-app-switcher') === 'true',
hideAccountMenu: getQueryParam('hide-account-menu') === 'true',
hideNavigation: getQueryParam('hide-navigation') === 'true',
passwordProtectedFolderView: getQueryParam(PASSWORD_PROTECTED_FOLDER_VIEW_QUERY) === 'true',
defaultLanguage
}
@@ -19,7 +19,7 @@ export const buildStaticAppMenuItems = (
'Apps menu: link label; opens the software license information page.',
'Software License Information'
),
icon: 'file-shield',
icon: 'scales',
priority: 900,
url: softwareLicenseUrl
})
@@ -57,13 +57,10 @@ import {
CustomComponentTarget,
Extension,
ExtensionPoint,
Key,
Modifier,
useAppsStore,
useAuthStore,
useConfigStore,
useExtensionRegistry,
useKeyboardActions,
useLocalStorage
} from '@ownclouders/web-pkg'
import TopBar from '../components/Topbar/TopBar.vue'
@@ -114,14 +111,6 @@ export default defineComponent({
const extensionRegistry = useExtensionRegistry()
const messageStore = useMessages()
// global shortcut so users can undo the most recent undoable action (e.g. delete)
// via keyboard, not just by clicking "Undo" on its notification. bypasses the
// default input-field guard, matching how Ctrl+S (save) is handled in AppWrapper.vue.
const { bindKeyAction } = useKeyboardActions({ skipDisabledKeyBindingsCheck: true })
bindKeyAction({ modifier: Modifier.Ctrl, primary: Key.Z }, () => {
messageStore.triggerLatestAction()
})
const allMessages = ref<{ id: string; title: string; desc?: string }[]>([])
watch(
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more