diff options
Diffstat (limited to 'apps/files_sharing/src/components')
17 files changed, 2008 insertions, 954 deletions
diff --git a/apps/files_sharing/src/components/ExternalShareAction.vue b/apps/files_sharing/src/components/ExternalShareAction.vue index 02b9eadd6e9..c2c86cc8679 100644 --- a/apps/files_sharing/src/components/ExternalShareAction.vue +++ b/apps/files_sharing/src/components/ExternalShareAction.vue @@ -1,24 +1,7 @@ <!-- - - @copyright Copyright (c) 2021 John Molakvoæ <skjnldsv@protonmail.com> - - - - @author John Molakvoæ <skjnldsv@protonmail.com> - - - - @license GNU AGPL version 3 or any later version - - - - This program is free software: you can redistribute it and/or modify - - it under the terms of the GNU Affero General Public License as - - published by the Free Software Foundation, either version 3 of the - - License, or (at your option) any later version. - - - - This program is distributed in the hope that it will be useful, - - but WITHOUT ANY WARRANTY; without even the implied warranty of - - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - - GNU Affero General Public License for more details. - - - - You should have received a copy of the GNU Affero General Public License - - along with this program. If not, see <http://www.gnu.org/licenses/>. - - - --> + - SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <template> <Component :is="data.is" @@ -29,7 +12,7 @@ </template> <script> -import Share from '../models/Share.js' +import Share from '../models/Share.ts' export default { name: 'ExternalShareAction', diff --git a/apps/files_sharing/src/components/FileListFilterAccount.vue b/apps/files_sharing/src/components/FileListFilterAccount.vue new file mode 100644 index 00000000000..150516e139b --- /dev/null +++ b/apps/files_sharing/src/components/FileListFilterAccount.vue @@ -0,0 +1,138 @@ +<!-- + - SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> +<template> + <FileListFilter class="file-list-filter-accounts" + :is-active="selectedAccounts.length > 0" + :filter-name="t('files_sharing', 'People')" + @reset-filter="resetFilter"> + <template #icon> + <NcIconSvgWrapper :path="mdiAccountMultipleOutline" /> + </template> + <NcActionInput v-if="availableAccounts.length > 1" + :label="t('files_sharing', 'Filter accounts')" + :label-outside="false" + :show-trailing-button="false" + type="search" + :value.sync="accountFilter" /> + <NcActionButton v-for="account of shownAccounts" + :key="account.id" + class="file-list-filter-accounts__item" + type="radio" + :model-value="selectedAccounts.includes(account)" + :value="account.id" + @click="toggleAccount(account.id)"> + <template #icon> + <NcAvatar class="file-list-filter-accounts__avatar" + v-bind="account" + :size="24" + disable-menu + :show-user-status="false" /> + </template> + {{ account.displayName }} + </NcActionButton> + </FileListFilter> +</template> + +<script setup lang="ts"> +import type { IAccountData } from '../files_filters/AccountFilter.ts' + +import { translate as t } from '@nextcloud/l10n' +import { mdiAccountMultipleOutline } from '@mdi/js' +import { computed, ref, watch } from 'vue' + +import FileListFilter from '../../../files/src/components/FileListFilter/FileListFilter.vue' +import NcActionButton from '@nextcloud/vue/components/NcActionButton' +import NcActionInput from '@nextcloud/vue/components/NcActionInput' +import NcAvatar from '@nextcloud/vue/components/NcAvatar' +import NcIconSvgWrapper from '@nextcloud/vue/components/NcIconSvgWrapper' + +interface IUserSelectData { + id: string + user: string + displayName: string +} + +const emit = defineEmits<{ + (event: 'update:accounts', value: IAccountData[]): void +}>() + +const accountFilter = ref('') +const availableAccounts = ref<IUserSelectData[]>([]) +const selectedAccounts = ref<IUserSelectData[]>([]) + +/** + * Currently shown accounts (filtered) + */ +const shownAccounts = computed(() => { + if (!accountFilter.value) { + return availableAccounts.value + } + const queryParts = accountFilter.value.toLocaleLowerCase().trim().split(' ') + return availableAccounts.value.filter((account) => + queryParts.every((part) => + account.user.toLocaleLowerCase().includes(part) + || account.displayName.toLocaleLowerCase().includes(part), + ), + ) +}) + +/** + * Toggle an account as selected + * @param accountId The account to toggle + */ +function toggleAccount(accountId: string) { + const account = availableAccounts.value.find(({ id }) => id === accountId) + if (account && selectedAccounts.value.includes(account)) { + selectedAccounts.value = selectedAccounts.value.filter(({ id }) => id !== accountId) + } else { + if (account) { + selectedAccounts.value = [...selectedAccounts.value, account] + } + } +} + +// Watch selected account, on change we emit the new account data to the filter instance +watch(selectedAccounts, () => { + // Emit selected accounts as account data + const accounts = selectedAccounts.value.map(({ id: uid, displayName }) => ({ uid, displayName })) + emit('update:accounts', accounts) +}) + +/** + * Reset this filter + */ +function resetFilter() { + selectedAccounts.value = [] + accountFilter.value = '' +} + +/** + * Update list of available accounts in current view. + * + * @param accounts - Accounts to use + */ +function setAvailableAccounts(accounts: IAccountData[]): void { + availableAccounts.value = accounts.map(({ uid, displayName }) => ({ displayName, id: uid, user: uid })) +} + +defineExpose({ + resetFilter, + setAvailableAccounts, + toggleAccount, +}) +</script> + +<style scoped lang="scss"> +.file-list-filter-accounts { + &__item { + min-width: 250px; + } + + &__avatar { + // 24px is the avatar size + margin: calc((var(--default-clickable-area) - 24px) / 2) + } +} +</style> diff --git a/apps/files_sharing/src/components/NewFileRequestDialog.vue b/apps/files_sharing/src/components/NewFileRequestDialog.vue new file mode 100644 index 00000000000..392f286e104 --- /dev/null +++ b/apps/files_sharing/src/components/NewFileRequestDialog.vue @@ -0,0 +1,468 @@ +<!-- + - SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> + +<template> + <NcDialog can-close + class="file-request-dialog" + data-cy-file-request-dialog + :close-on-click-outside="false" + :name="currentStep !== STEP.LAST ? t('files_sharing', 'Create a file request') : t('files_sharing', 'File request created')" + size="normal" + @closing="onCancel"> + <!-- Header --> + <NcNoteCard v-show="currentStep === STEP.FIRST" type="info" class="file-request-dialog__header"> + <p id="file-request-dialog-description" class="file-request-dialog__description"> + {{ t('files_sharing', 'Collect files from others even if they do not have an account.') }} + {{ t('files_sharing', 'To ensure you can receive files, verify you have enough storage available.') }} + </p> + </NcNoteCard> + + <!-- Main form --> + <form ref="form" + class="file-request-dialog__form" + aria-describedby="file-request-dialog-description" + :aria-label="t('files_sharing', 'File request')" + aria-live="polite" + data-cy-file-request-dialog-form + @submit.prevent.stop=""> + <FileRequestIntro v-show="currentStep === STEP.FIRST" + :context="context" + :destination.sync="destination" + :disabled="loading" + :label.sync="label" + :note.sync="note" /> + + <FileRequestDatePassword v-show="currentStep === STEP.SECOND" + :disabled="loading" + :expiration-date.sync="expirationDate" + :password.sync="password" /> + + <FileRequestFinish v-if="share" + v-show="currentStep === STEP.LAST" + :emails="emails" + :is-share-by-mail-enabled="isShareByMailEnabled" + :share="share" + @add-email="email => emails.push(email)" + @remove-email="onRemoveEmail" /> + </form> + + <!-- Controls --> + <template #actions> + <!-- Back --> + <NcButton v-show="currentStep === STEP.SECOND" + :aria-label="t('files_sharing', 'Previous step')" + :disabled="loading" + data-cy-file-request-dialog-controls="back" + type="tertiary" + @click="currentStep = STEP.FIRST"> + {{ t('files_sharing', 'Previous step') }} + </NcButton> + + <!-- Align right --> + <span class="dialog__actions-separator" /> + + <!-- Cancel the creation --> + <NcButton v-if="currentStep !== STEP.LAST" + :aria-label="t('files_sharing', 'Cancel')" + :disabled="loading" + :title="t('files_sharing', 'Cancel the file request creation')" + data-cy-file-request-dialog-controls="cancel" + type="tertiary" + @click="onCancel"> + {{ t('files_sharing', 'Cancel') }} + </NcButton> + + <!-- Cancel email and just close --> + <NcButton v-else-if="emails.length !== 0" + :aria-label="t('files_sharing', 'Close without sending emails')" + :disabled="loading" + :title="t('files_sharing', 'Close without sending emails')" + data-cy-file-request-dialog-controls="cancel" + type="tertiary" + @click="onCancel"> + {{ t('files_sharing', 'Close') }} + </NcButton> + + <!-- Next --> + <NcButton v-if="currentStep !== STEP.LAST" + :aria-label="t('files_sharing', 'Continue')" + :disabled="loading" + data-cy-file-request-dialog-controls="next" + @click="onPageNext"> + <template #icon> + <NcLoadingIcon v-if="loading" /> + <IconNext v-else :size="20" /> + </template> + {{ t('files_sharing', 'Continue') }} + </NcButton> + + <!-- Finish --> + <NcButton v-else + :aria-label="finishButtonLabel" + :disabled="loading" + data-cy-file-request-dialog-controls="finish" + type="primary" + @click="onFinish"> + <template #icon> + <NcLoadingIcon v-if="loading" /> + <IconCheck v-else :size="20" /> + </template> + {{ finishButtonLabel }} + </NcButton> + </template> + </NcDialog> +</template> + +<script lang="ts"> +import type { AxiosError } from '@nextcloud/axios' +import type { Folder, Node } from '@nextcloud/files' +import type { OCSResponse } from '@nextcloud/typings/ocs' +import type { PropType } from 'vue' + +import { defineComponent } from 'vue' +import { emit } from '@nextcloud/event-bus' +import { generateOcsUrl } from '@nextcloud/router' +import { Permission } from '@nextcloud/files' +import { ShareType } from '@nextcloud/sharing' +import { showError, showSuccess } from '@nextcloud/dialogs' +import { n, t } from '@nextcloud/l10n' +import axios from '@nextcloud/axios' + +import NcButton from '@nextcloud/vue/components/NcButton' +import NcDialog from '@nextcloud/vue/components/NcDialog' +import NcLoadingIcon from '@nextcloud/vue/components/NcLoadingIcon' +import NcNoteCard from '@nextcloud/vue/components/NcNoteCard' + +import IconCheck from 'vue-material-design-icons/Check.vue' +import IconNext from 'vue-material-design-icons/ArrowRight.vue' + +import Config from '../services/ConfigService' +import FileRequestDatePassword from './NewFileRequestDialog/NewFileRequestDialogDatePassword.vue' +import FileRequestFinish from './NewFileRequestDialog/NewFileRequestDialogFinish.vue' +import FileRequestIntro from './NewFileRequestDialog/NewFileRequestDialogIntro.vue' +import logger from '../services/logger' +import Share from '../models/Share.ts' + +enum STEP { + FIRST = 0, + SECOND = 1, + LAST = 2, +} + +const sharingConfig = new Config() + +export default defineComponent({ + name: 'NewFileRequestDialog', + + components: { + FileRequestDatePassword, + FileRequestFinish, + FileRequestIntro, + IconCheck, + IconNext, + NcButton, + NcDialog, + NcLoadingIcon, + NcNoteCard, + }, + + props: { + context: { + type: Object as PropType<Folder>, + required: true, + }, + content: { + type: Array as PropType<Node[]>, + required: true, + }, + }, + + setup() { + return { + STEP, + n, + t, + + isShareByMailEnabled: sharingConfig.isMailShareAllowed, + } + }, + + data() { + return { + currentStep: STEP.FIRST, + loading: false, + + destination: this.context.path || '/', + label: '', + note: '', + + expirationDate: null as Date | null, + password: null as string | null, + + share: null as Share | null, + emails: [] as string[], + } + }, + + computed: { + finishButtonLabel() { + if (this.emails.length === 0) { + return t('files_sharing', 'Close') + } + return n('files_sharing', 'Send email and close', 'Send {count} emails and close', this.emails.length, { count: this.emails.length }) + }, + }, + + methods: { + onPageNext() { + const form = this.$refs.form as HTMLFormElement + + // Reset custom validity + form.querySelectorAll('input').forEach(input => input.setCustomValidity('')) + + // custom destination validation + // cannot share root + if (this.destination === '/' || this.destination === '') { + const destinationInput = form.querySelector('input[name="destination"]') as HTMLInputElement + destinationInput?.setCustomValidity(t('files_sharing', 'Please select a folder, you cannot share the root directory.')) + form.reportValidity() + return + } + + // If the form is not valid, show the error message + if (!form.checkValidity()) { + form.reportValidity() + return + } + + if (this.currentStep === STEP.FIRST) { + this.currentStep = STEP.SECOND + return + } + + this.createShare() + }, + + onRemoveEmail(email: string) { + const index = this.emails.indexOf(email) + this.emails.splice(index, 1) + }, + + onCancel() { + this.$emit('close') + }, + + async onFinish() { + if (this.emails.length === 0 || this.isShareByMailEnabled === false) { + showSuccess(t('files_sharing', 'File request created')) + this.$emit('close') + return + } + + if (sharingConfig.isMailShareAllowed && this.emails.length > 0) { + await this.setShareEmails() + await this.sendEmails() + showSuccess(n('files_sharing', 'File request created and email sent', 'File request created and {count} emails sent', this.emails.length, { count: this.emails.length })) + } else { + showSuccess(t('files_sharing', 'File request created')) + } + + this.$emit('close') + }, + + async createShare() { + this.loading = true + + let expireDate = '' + if (this.expirationDate) { + const year = this.expirationDate.getFullYear() + const month = (this.expirationDate.getMonth() + 1).toString().padStart(2, '0') + const day = this.expirationDate.getDate().toString().padStart(2, '0') + + // Format must be YYYY-MM-DD + expireDate = `${year}-${month}-${day}` + } + const shareUrl = generateOcsUrl('apps/files_sharing/api/v1/shares') + try { + const request = await axios.post<OCSResponse>(shareUrl, { + // Always create a file request, but without mail share + // permissions, only a share link will be created. + shareType: sharingConfig.isMailShareAllowed ? ShareType.Email : ShareType.Link, + permissions: Permission.CREATE, + + label: this.label, + path: this.destination, + note: this.note, + + password: this.password || '', + expireDate: expireDate || '', + + // Empty string + shareWith: '', + attributes: JSON.stringify([{ + value: true, + key: 'enabled', + scope: 'fileRequest', + }]), + }) + + // If not an ocs request + if (!request?.data?.ocs) { + throw request + } + + const share = new Share(request.data.ocs.data) + this.share = share + + logger.info('New file request created', { share }) + emit('files_sharing:share:created', { share }) + + // Move to the last page + this.currentStep = STEP.LAST + } catch (error) { + const errorMessage = (error as AxiosError<OCSResponse>)?.response?.data?.ocs?.meta?.message + showError( + errorMessage + ? t('files_sharing', 'Error creating the share: {errorMessage}', { errorMessage }) + : t('files_sharing', 'Error creating the share'), + ) + logger.error('Error while creating share', { error, errorMessage }) + throw error + } finally { + this.loading = false + } + }, + + async setShareEmails() { + this.loading = true + + // This should never happen™ + if (!this.share || !this.share?.id) { + throw new Error('Share ID is missing') + } + + const shareUrl = generateOcsUrl('apps/files_sharing/api/v1/shares/{id}', { id: this.share.id }) + try { + // Convert link share to email share + const request = await axios.put<OCSResponse>(shareUrl, { + attributes: JSON.stringify([{ + value: this.emails, + key: 'emails', + scope: 'shareWith', + }, + { + value: true, + key: 'enabled', + scope: 'fileRequest', + }]), + }) + + // If not an ocs request + if (!request?.data?.ocs) { + throw request + } + } catch (error) { + this.onEmailSendError(error) + throw error + } finally { + this.loading = false + } + }, + + async sendEmails() { + this.loading = true + + // This should never happen™ + if (!this.share || !this.share?.id) { + throw new Error('Share ID is missing') + } + + const shareUrl = generateOcsUrl('apps/files_sharing/api/v1/shares/{id}/send-email', { id: this.share.id }) + try { + // Convert link share to email share + const request = await axios.post<OCSResponse>(shareUrl, { + password: this.password || undefined, + }) + + // If not an ocs request + if (!request?.data?.ocs) { + throw request + } + } catch (error) { + this.onEmailSendError(error) + throw error + } finally { + this.loading = false + } + }, + + onEmailSendError(error: AxiosError<OCSResponse>) { + const errorMessage = error.response?.data?.ocs?.meta?.message + showError( + errorMessage + ? t('files_sharing', 'Error sending emails: {errorMessage}', { errorMessage }) + : t('files_sharing', 'Error sending emails'), + ) + logger.error('Error while sending emails', { error, errorMessage }) + }, + }, +}) +</script> + +<style lang="scss"> +.file-request-dialog { + --margin: 18px; + + &__header { + margin: 0 var(--margin); + } + + &__form { + position: relative; + overflow: auto; + padding: var(--margin) var(--margin); + // overlap header bottom padding + margin-top: calc(-1 * var(--margin)); + } + + fieldset { + display: flex; + flex-direction: column; + width: 100%; + margin-top: var(--margin); + + legend { + display: flex; + align-items: center; + width: 100%; + } + } + + // Using a NcNoteCard was a bit much sometimes. + // Using a simple paragraph instead does it. + &__info { + color: var(--color-text-maxcontrast); + padding-block: 4px; + display: flex; + align-items: center; + .file-request-dialog__info-icon { + margin-inline-end: 8px; + } + } + + .dialog__actions { + width: auto; + margin-inline: 12px; + span.dialog__actions-separator { + margin-inline-start: auto; + } + } + + .input-field__helper-text-message { + // reduce helper text standing out + color: var(--color-text-maxcontrast); + } +} +</style> diff --git a/apps/files_sharing/src/components/NewFileRequestDialog/NewFileRequestDialogDatePassword.vue b/apps/files_sharing/src/components/NewFileRequestDialog/NewFileRequestDialogDatePassword.vue new file mode 100644 index 00000000000..7e6d56e8794 --- /dev/null +++ b/apps/files_sharing/src/components/NewFileRequestDialog/NewFileRequestDialogDatePassword.vue @@ -0,0 +1,258 @@ +<!-- + - SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> + +<template> + <div> + <!-- Password and expiration summary --> + <NcNoteCard v-if="passwordAndExpirationSummary" type="success"> + {{ passwordAndExpirationSummary }} + </NcNoteCard> + + <!-- Expiration date --> + <fieldset class="file-request-dialog__expiration" data-cy-file-request-dialog-fieldset="expiration"> + <!-- Enable expiration --> + <legend>{{ t('files_sharing', 'When should the request expire?') }}</legend> + <NcCheckboxRadioSwitch v-show="!isExpirationDateEnforced" + :checked="isExpirationDateEnforced || expirationDate !== null" + :disabled="disabled || isExpirationDateEnforced" + @update:checked="onToggleDeadline"> + {{ t('files_sharing', 'Set a submission expiration date') }} + </NcCheckboxRadioSwitch> + + <!-- Date picker --> + <NcDateTimePickerNative v-if="expirationDate !== null" + id="file-request-dialog-expirationDate" + :disabled="disabled" + :hide-label="true" + :label="t('files_sharing', 'Expiration date')" + :max="maxDate" + :min="minDate" + :placeholder="t('files_sharing', 'Select a date')" + :required="defaultExpireDateEnforced" + :value="expirationDate" + name="expirationDate" + type="date" + @input="$emit('update:expirationDate', $event)" /> + + <p v-if="defaultExpireDateEnforced" class="file-request-dialog__info"> + <IconInfo :size="18" class="file-request-dialog__info-icon" /> + {{ t('files_sharing', 'Your administrator has enforced a {count} days expiration policy.', { count: defaultExpireDate }) }} + </p> + </fieldset> + + <!-- Password --> + <fieldset class="file-request-dialog__password" data-cy-file-request-dialog-fieldset="password"> + <!-- Enable password --> + <legend>{{ t('files_sharing', 'What password should be used for the request?') }}</legend> + <NcCheckboxRadioSwitch v-show="!isPasswordEnforced" + :checked="isPasswordEnforced || password !== null" + :disabled="disabled || isPasswordEnforced" + @update:checked="onTogglePassword"> + {{ t('files_sharing', 'Set a password') }} + </NcCheckboxRadioSwitch> + + <div v-if="password !== null" class="file-request-dialog__password-field"> + <NcPasswordField ref="passwordField" + :check-password-strength="true" + :disabled="disabled" + :label="t('files_sharing', 'Password')" + :placeholder="t('files_sharing', 'Enter a valid password')" + :required="enforcePasswordForPublicLink" + :value="password" + name="password" + @update:value="$emit('update:password', $event)" /> + <NcButton :aria-label="t('files_sharing', 'Generate a new password')" + :title="t('files_sharing', 'Generate a new password')" + type="tertiary-no-background" + @click="onGeneratePassword"> + <template #icon> + <IconPasswordGen :size="20" /> + </template> + </NcButton> + </div> + + <p v-if="enforcePasswordForPublicLink" class="file-request-dialog__info"> + <IconInfo :size="18" class="file-request-dialog__info-icon" /> + {{ t('files_sharing', 'Your administrator has enforced a password protection.') }} + </p> + </fieldset> + </div> +</template> + +<script lang="ts"> +import { defineComponent, type PropType } from 'vue' +import { t } from '@nextcloud/l10n' + +import NcButton from '@nextcloud/vue/components/NcButton' +import NcCheckboxRadioSwitch from '@nextcloud/vue/components/NcCheckboxRadioSwitch' +import NcDateTimePickerNative from '@nextcloud/vue/components/NcDateTimePickerNative' +import NcNoteCard from '@nextcloud/vue/components/NcNoteCard' +import NcPasswordField from '@nextcloud/vue/components/NcPasswordField' + +import IconInfo from 'vue-material-design-icons/Information.vue' +import IconPasswordGen from 'vue-material-design-icons/AutoFix.vue' + +import Config from '../../services/ConfigService' +import GeneratePassword from '../../utils/GeneratePassword' + +const sharingConfig = new Config() + +export default defineComponent({ + name: 'NewFileRequestDialogDatePassword', + + components: { + IconInfo, + IconPasswordGen, + NcButton, + NcCheckboxRadioSwitch, + NcDateTimePickerNative, + NcNoteCard, + NcPasswordField, + }, + + props: { + disabled: { + type: Boolean, + required: false, + default: false, + }, + expirationDate: { + type: Date as PropType<Date | null>, + required: false, + default: null, + }, + password: { + type: String as PropType<string | null>, + required: false, + default: null, + }, + }, + + emits: [ + 'update:expirationDate', + 'update:password', + ], + + setup() { + return { + t, + + // Default expiration date if defaultExpireDateEnabled is true + defaultExpireDate: sharingConfig.defaultExpireDate, + // Default expiration date is enabled for public links (can be disabled) + defaultExpireDateEnabled: sharingConfig.isDefaultExpireDateEnabled, + // Default expiration date is enforced for public links (can't be disabled) + defaultExpireDateEnforced: sharingConfig.isDefaultExpireDateEnforced, + + // Default password protection is enabled for public links (can be disabled) + enableLinkPasswordByDefault: sharingConfig.enableLinkPasswordByDefault, + // Password protection is enforced for public links (can't be disabled) + enforcePasswordForPublicLink: sharingConfig.enforcePasswordForPublicLink, + } + }, + + data() { + return { + maxDate: null as Date | null, + minDate: new Date(new Date().setDate(new Date().getDate() + 1)), + } + }, + + computed: { + passwordAndExpirationSummary(): string { + if (this.expirationDate && this.password) { + return t('files_sharing', 'The request will expire on {date} at midnight and will be password protected.', { + date: this.expirationDate.toLocaleDateString(), + }) + } + + if (this.expirationDate) { + return t('files_sharing', 'The request will expire on {date} at midnight.', { + date: this.expirationDate.toLocaleDateString(), + }) + } + + if (this.password) { + return t('files_sharing', 'The request will be password protected.') + } + + return '' + }, + + isExpirationDateEnforced(): boolean { + // Both fields needs to be enabled in the settings + return this.defaultExpireDateEnabled + && this.defaultExpireDateEnforced + }, + + isPasswordEnforced(): boolean { + // Both fields needs to be enabled in the settings + return this.enableLinkPasswordByDefault + && this.enforcePasswordForPublicLink + }, + }, + + mounted() { + // If defined, we set the default expiration date + if (this.defaultExpireDate) { + this.$emit('update:expirationDate', sharingConfig.defaultExpirationDate) + } + + // If enforced, we cannot set a date before the default expiration days (see admin settings) + if (this.isExpirationDateEnforced) { + this.maxDate = sharingConfig.defaultExpirationDate + } + + // If enabled by default, we generate a valid password + if (this.isPasswordEnforced) { + this.generatePassword() + } + }, + + methods: { + onToggleDeadline(checked: boolean) { + this.$emit('update:expirationDate', checked ? (this.maxDate || this.minDate) : null) + }, + + async onTogglePassword(checked: boolean) { + if (checked) { + this.generatePassword() + return + } + this.$emit('update:password', null) + }, + + async onGeneratePassword() { + await this.generatePassword() + this.showPassword() + }, + + async generatePassword() { + await GeneratePassword().then(password => { + this.$emit('update:password', password) + }) + }, + + showPassword() { + // @ts-expect-error isPasswordHidden is private + this.$refs.passwordField.isPasswordHidden = false + }, + }, +}) +</script> + +<style scoped lang="scss"> +.file-request-dialog__password-field { + display: flex; + align-items: flex-start; + gap: 8px; + // Compensate label gab with legend + margin-top: 12px; + > div { + // Force margin to 0 as we handle it above + margin: 0; + } +} +</style> diff --git a/apps/files_sharing/src/components/NewFileRequestDialog/NewFileRequestDialogFinish.vue b/apps/files_sharing/src/components/NewFileRequestDialog/NewFileRequestDialogFinish.vue new file mode 100644 index 00000000000..7826aab581e --- /dev/null +++ b/apps/files_sharing/src/components/NewFileRequestDialog/NewFileRequestDialogFinish.vue @@ -0,0 +1,236 @@ +<!-- + - SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> + +<template> + <div> + <!-- Request note --> + <NcNoteCard type="success"> + {{ t('files_sharing', 'You can now share the link below to allow people to upload files to your directory.') }} + </NcNoteCard> + + <!-- Copy share link --> + <NcInputField ref="clipboard" + :value="shareLink" + :label="t('files_sharing', 'Share link')" + :readonly="true" + :show-trailing-button="true" + :trailing-button-label="t('files_sharing', 'Copy')" + data-cy-file-request-dialog-fieldset="link" + @click="copyShareLink" + @trailing-button-click="copyShareLink"> + <template #trailing-button-icon> + <IconCheck v-if="isCopied" :size="20" /> + <IconClipboard v-else :size="20" /> + </template> + </NcInputField> + + <template v-if="isShareByMailEnabled"> + <!-- Email share--> + <NcTextField :value.sync="email" + :label="t('files_sharing', 'Send link via email')" + :placeholder="t('files_sharing', 'Enter an email address or paste a list')" + data-cy-file-request-dialog-fieldset="email" + type="email" + @keypress.enter.stop="addNewEmail" + @paste.stop.prevent="onPasteEmails" + @focusout.native="addNewEmail" /> + + <!-- Email list --> + <div v-if="emails.length > 0" class="file-request-dialog__emails"> + <NcChip v-for="mail in emails" + :key="mail" + :aria-label-close="t('files_sharing', 'Remove email')" + :text="mail" + @close="$emit('remove-email', mail)"> + <template #icon> + <NcAvatar :disable-menu="true" + :disable-tooltip="true" + :display-name="mail" + :is-no-user="true" + :show-user-status="false" + :size="24" /> + </template> + </NcChip> + </div> + </template> + </div> +</template> + +<script lang="ts"> +import type { PropType } from 'vue' +import Share from '../../models/Share.ts' + +import { defineComponent } from 'vue' +import { generateUrl, getBaseUrl } from '@nextcloud/router' +import { showError, showSuccess } from '@nextcloud/dialogs' +import { n, t } from '@nextcloud/l10n' + +import NcAvatar from '@nextcloud/vue/components/NcAvatar' +import NcInputField from '@nextcloud/vue/components/NcInputField' +import NcNoteCard from '@nextcloud/vue/components/NcNoteCard' +import NcTextField from '@nextcloud/vue/components/NcTextField' +import NcChip from '@nextcloud/vue/components/NcChip' + +import IconCheck from 'vue-material-design-icons/Check.vue' +import IconClipboard from 'vue-material-design-icons/ClipboardText.vue' + +export default defineComponent({ + name: 'NewFileRequestDialogFinish', + + components: { + IconCheck, + IconClipboard, + NcAvatar, + NcInputField, + NcNoteCard, + NcTextField, + NcChip, + }, + + props: { + share: { + type: Object as PropType<Share>, + required: true, + }, + emails: { + type: Array as PropType<string[]>, + required: true, + }, + isShareByMailEnabled: { + type: Boolean, + required: true, + }, + }, + + emits: ['add-email', 'remove-email'], + + setup() { + return { + n, t, + } + }, + + data() { + return { + isCopied: false, + email: '', + } + }, + + computed: { + shareLink() { + return generateUrl('/s/{token}', { token: this.share.token }, { baseURL: getBaseUrl() }) + }, + }, + + methods: { + async copyShareLink(event: MouseEvent) { + if (this.isCopied) { + this.isCopied = false + return + } + + if (!navigator.clipboard) { + // Clipboard API not available + window.prompt(t('files_sharing', 'Automatically copying failed, please copy the share link manually'), this.shareLink) + return + } + + await navigator.clipboard.writeText(this.shareLink) + + showSuccess(t('files_sharing', 'Link copied')) + this.isCopied = true + event.target?.select?.() + + setTimeout(() => { + this.isCopied = false + }, 3000) + }, + + addNewEmail(e: KeyboardEvent) { + if (this.email.trim() === '') { + return + } + + if (e.target instanceof HTMLInputElement) { + // Reset the custom validity + e.target.setCustomValidity('') + + // Check if the field is valid + if (e.target.checkValidity() === false) { + e.target.reportValidity() + return + } + + // The email is already in the list + if (this.emails.includes(this.email.trim())) { + e.target.setCustomValidity(t('files_sharing', 'Email already added')) + e.target.reportValidity() + return + } + + // Check if the email is valid + if (!this.isValidEmail(this.email.trim())) { + e.target.setCustomValidity(t('files_sharing', 'Invalid email address')) + e.target.reportValidity() + return + } + + this.$emit('add-email', this.email.trim()) + this.email = '' + } + }, + + // Handle dumping a list of emails + onPasteEmails(e: ClipboardEvent) { + const clipboardData = e.clipboardData + if (!clipboardData) { + return + } + + const pastedText = clipboardData.getData('text') + const emails = pastedText.split(/[\s,;]+/).filter(Boolean).map((email) => email.trim()) + + const duplicateEmails = emails.filter((email) => this.emails.includes(email)) + const validEmails = emails.filter((email) => this.isValidEmail(email) && !duplicateEmails.includes(email)) + const invalidEmails = emails.filter((email) => !this.isValidEmail(email)) + validEmails.forEach((email) => this.$emit('add-email', email)) + + // Warn about invalid emails + if (invalidEmails.length > 0) { + showError(n('files_sharing', 'The following email address is not valid: {emails}', 'The following email addresses are not valid: {emails}', invalidEmails.length, { emails: invalidEmails.join(', ') })) + } + + // Warn about duplicate emails + if (duplicateEmails.length > 0) { + showError(n('files_sharing', '{count} email address already added', '{count} email addresses already added', duplicateEmails.length, { count: duplicateEmails.length })) + } + + if (validEmails.length > 0) { + showSuccess(n('files_sharing', '{count} email address added', '{count} email addresses added', validEmails.length, { count: validEmails.length })) + } + + this.email = '' + }, + + // No need to have a fancy regex, just check for an @ + isValidEmail(email: string): boolean { + return email.includes('@') + }, + }, +}) +</script> +<style scoped> +.input-field, +.file-request-dialog__emails { + margin-top: var(--margin); +} + +.file-request-dialog__emails { + display: flex; + gap: var(--default-grid-baseline); + flex-wrap: wrap; +} +</style> diff --git a/apps/files_sharing/src/components/NewFileRequestDialog/NewFileRequestDialogIntro.vue b/apps/files_sharing/src/components/NewFileRequestDialog/NewFileRequestDialogIntro.vue new file mode 100644 index 00000000000..5ac60c37e29 --- /dev/null +++ b/apps/files_sharing/src/components/NewFileRequestDialog/NewFileRequestDialogIntro.vue @@ -0,0 +1,166 @@ +<!-- + - SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> + +<template> + <div> + <!-- Request label --> + <fieldset class="file-request-dialog__label" data-cy-file-request-dialog-fieldset="label"> + <legend> + {{ t('files_sharing', 'What are you requesting?') }} + </legend> + <NcTextField :value="label" + :disabled="disabled" + :label="t('files_sharing', 'Request subject')" + :placeholder="t('files_sharing', 'Birthday party photos, History assignment…')" + :required="false" + name="label" + @update:value="$emit('update:label', $event)" /> + </fieldset> + + <!-- Request destination --> + <fieldset class="file-request-dialog__destination" data-cy-file-request-dialog-fieldset="destination"> + <legend> + {{ t('files_sharing', 'Where should these files go?') }} + </legend> + <NcTextField :value="destination" + :disabled="disabled" + :label="t('files_sharing', 'Upload destination')" + :minlength="2/* cannot share root */" + :placeholder="t('files_sharing', 'Select a destination')" + :readonly="false /* cannot validate a readonly input */" + :required="true /* cannot be empty */" + :show-trailing-button="destination !== context.path" + :trailing-button-icon="'undo'" + :trailing-button-label="t('files_sharing', 'Revert to default')" + name="destination" + @click="onPickDestination" + @keypress.prevent.stop="/* prevent typing in the input, we use the picker */" + @paste.prevent.stop="/* prevent pasting in the input, we use the picker */" + @trailing-button-click="$emit('update:destination', '')"> + <IconFolder :size="18" /> + </NcTextField> + + <p class="file-request-dialog__info"> + <IconLock :size="18" class="file-request-dialog__info-icon" /> + {{ t('files_sharing', 'The uploaded files are visible only to you unless you choose to share them.') }} + </p> + </fieldset> + + <!-- Request note --> + <fieldset class="file-request-dialog__note" data-cy-file-request-dialog-fieldset="note"> + <legend> + {{ t('files_sharing', 'Add a note') }} + </legend> + <NcTextArea :value="note" + :disabled="disabled" + :label="t('files_sharing', 'Note for recipient')" + :placeholder="t('files_sharing', 'Add a note to help people understand what you are requesting.')" + :required="false" + name="note" + @update:value="$emit('update:note', $event)" /> + + <p class="file-request-dialog__info"> + <IconInfo :size="18" class="file-request-dialog__info-icon" /> + {{ t('files_sharing', 'You can add links, date or any other information that will help the recipient understand what you are requesting.') }} + </p> + </fieldset> + </div> +</template> + +<script lang="ts"> +import type { PropType } from 'vue' +import type { Folder, Node } from '@nextcloud/files' + +import { defineComponent } from 'vue' +import { getFilePickerBuilder } from '@nextcloud/dialogs' +import { t } from '@nextcloud/l10n' + +import IconFolder from 'vue-material-design-icons/Folder.vue' +import IconInfo from 'vue-material-design-icons/InformationOutline.vue' +import IconLock from 'vue-material-design-icons/Lock.vue' +import NcTextArea from '@nextcloud/vue/components/NcTextArea' +import NcTextField from '@nextcloud/vue/components/NcTextField' + +export default defineComponent({ + name: 'NewFileRequestDialogIntro', + + components: { + IconFolder, + IconInfo, + IconLock, + NcTextArea, + NcTextField, + }, + + props: { + disabled: { + type: Boolean, + required: false, + default: false, + }, + context: { + type: Object as PropType<Folder>, + required: true, + }, + label: { + type: String, + required: true, + }, + destination: { + type: String, + required: true, + }, + note: { + type: String, + required: true, + }, + }, + + emits: [ + 'update:destination', + 'update:label', + 'update:note', + ], + + setup() { + return { + t, + } + }, + + methods: { + onPickDestination() { + const filepicker = getFilePickerBuilder(t('files_sharing', 'Select a destination')) + .addMimeTypeFilter('httpd/unix-directory') + .allowDirectories(true) + .addButton({ + label: t('files_sharing', 'Select'), + callback: this.onPickedDestination, + }) + .setFilter(node => node.path !== '/') + .startAt(this.destination) + .build() + try { + filepicker.pick() + } catch (e) { + // ignore cancel + } + }, + + onPickedDestination(nodes: Node[]) { + const node = nodes[0] + if (node) { + this.$emit('update:destination', node.path) + } + }, + }, +}) +</script> +<style scoped> +.file-request-dialog__note :deep(textarea) { + width: 100% !important; + min-height: 80px; +} +</style> diff --git a/apps/files_sharing/src/components/PersonalSettings.vue b/apps/files_sharing/src/components/PersonalSettings.vue index 7a14b015223..19c9c2aec87 100644 --- a/apps/files_sharing/src/components/PersonalSettings.vue +++ b/apps/files_sharing/src/components/PersonalSettings.vue @@ -1,24 +1,7 @@ <!-- - - @copyright 2019 Roeland Jago Douma <roeland@famdouma.nl> - - - - @author 2019 Roeland Jago Douma <roeland@famdouma.nl> - - @author Hinrich Mahler <nextcloud@mahlerhome.de> - - - - @license GNU AGPL version 3 or any later version - - - - This program is free software: you can redistribute it and/or modify - - it under the terms of the GNU Affero General Public License as - - published by the Free Software Foundation, either version 3 of the - - License, or (at your option) any later version. - - - - This program is distributed in the hope that it will be useful, - - but WITHOUT ANY WARRANTY; without even the implied warranty of - - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - - GNU Affero General Public License for more details. - - - - You should have received a copy of the GNU Affero General Public License - - along with this program. If not, see <http://www.gnu.org/licenses/>. - --> + - SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <template> <div v-if="!enforceAcceptShares || allowCustomDirectory" id="files-sharing-personal-settings" class="section"> @@ -29,7 +12,7 @@ class="checkbox" type="checkbox" @change="toggleEnabled"> - <label for="files-sharing-personal-settings-accept">{{ t('files_sharing', 'Accept user and group shares by default') }}</label> + <label for="files-sharing-personal-settings-accept">{{ t('files_sharing', 'Accept shares from other accounts and groups by default') }}</label> </p> <p v-if="allowCustomDirectory"> <SelectShareFolderDialogue /> diff --git a/apps/files_sharing/src/components/SelectShareFolderDialogue.vue b/apps/files_sharing/src/components/SelectShareFolderDialogue.vue index aa1d8f8aa37..959fecaa4a4 100644 --- a/apps/files_sharing/src/components/SelectShareFolderDialogue.vue +++ b/apps/files_sharing/src/components/SelectShareFolderDialogue.vue @@ -1,21 +1,7 @@ <!-- - - @copyright 2021 Hinrich Mahler <nextcloud@mahlerhome.de> - - - - @license GNU AGPL version 3 or any later version - - - - This program is free software: you can redistribute it and/or modify - - it under the terms of the GNU Affero General Public License as - - published by the Free Software Foundation, either version 3 of the - - License, or (at your option) any later version. - - - - This program is distributed in the hope that it will be useful, - - but WITHOUT ANY WARRANTY; without even the implied warranty of - - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - - GNU Affero General Public License for more details. - - - - You should have received a copy of the GNU Affero General Public License - - along with this program. If not, see <http://www.gnu.org/licenses/>. - --> + - SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <template> <div class="share-folder"> @@ -24,7 +10,7 @@ <NcTextField class="share-folder__picker" type="text" :label="t('files_sharing', 'Set default folder for accepted shares')" - :placeholder="readableDirectory" + :value="readableDirectory" @click.prevent="pickFolder" /> <!-- Show reset button if folder is different --> @@ -43,7 +29,7 @@ import path from 'path' import { generateUrl } from '@nextcloud/router' import { getFilePickerBuilder, showError } from '@nextcloud/dialogs' import { loadState } from '@nextcloud/initial-state' -import NcTextField from '@nextcloud/vue/dist/Components/NcTextField.js' +import NcTextField from '@nextcloud/vue/components/NcTextField' const defaultDirectory = loadState('files_sharing', 'default_share_folder', '/') const directory = loadState('files_sharing', 'share_folder', defaultDirectory) @@ -71,7 +57,7 @@ export default { async pickFolder() { // Setup file picker - const picker = getFilePickerBuilder(t('files', 'Choose a default folder for accepted shares')) + const picker = getFilePickerBuilder(t('files_sharing', 'Choose a default folder for accepted shares')) .startAt(this.readableDirectory) .setMultiSelect(false) .setType(1) @@ -83,7 +69,7 @@ export default { // Init user folder picking const dir = await picker.pick() || '/' if (!dir.startsWith('/')) { - throw new Error(t('files', 'Invalid path selected')) + throw new Error(t('files_sharing', 'Invalid path selected')) } // Fix potential path issues and save results @@ -92,7 +78,7 @@ export default { shareFolder: this.directory, }) } catch (error) { - showError(error.message || t('files', 'Unknown error')) + showError(error.message || t('files_sharing', 'Unknown error')) } }, diff --git a/apps/files_sharing/src/components/ShareExpiryTime.vue b/apps/files_sharing/src/components/ShareExpiryTime.vue new file mode 100644 index 00000000000..939142616e9 --- /dev/null +++ b/apps/files_sharing/src/components/ShareExpiryTime.vue @@ -0,0 +1,91 @@ +<!-- + - SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> +<template> + <div class="share-expiry-time"> + <NcPopover popup-role="dialog"> + <template #trigger> + <NcButton v-if="expiryTime" + class="hint-icon" + type="tertiary" + :aria-label="t('files_sharing', 'Share expiration: {date}', { date: new Date(expiryTime).toLocaleString() })"> + <template #icon> + <ClockIcon :size="20" /> + </template> + </NcButton> + </template> + <h3 class="hint-heading"> + {{ t('files_sharing', 'Share Expiration') }} + </h3> + <p v-if="expiryTime" class="hint-body"> + <NcDateTime :timestamp="expiryTime" + :format="timeFormat" + :relative-time="false" /> (<NcDateTime :timestamp="expiryTime" />) + </p> + </NcPopover> + </div> +</template> + +<script> +import NcButton from '@nextcloud/vue/components/NcButton' +import NcPopover from '@nextcloud/vue/components/NcPopover' +import NcDateTime from '@nextcloud/vue/components/NcDateTime' +import ClockIcon from 'vue-material-design-icons/Clock.vue' + +export default { + name: 'ShareExpiryTime', + + components: { + NcButton, + NcPopover, + NcDateTime, + ClockIcon, + }, + + props: { + share: { + type: Object, + required: true, + }, + }, + + computed: { + expiryTime() { + return this.share?.expireDate ? new Date(this.share.expireDate).getTime() : null + }, + timeFormat() { + return { dateStyle: 'full', timeStyle: 'short' } + }, + }, +} +</script> + +<style scoped lang="scss"> +.share-expiry-time { + display: inline-flex; + align-items: center; + justify-content: center; + + .hint-icon { + padding: 0; + margin: 0; + width: 24px; + height: 24px; + } +} + +.hint-heading { + text-align: center; + font-size: 1rem; + margin-top: 8px; + padding-bottom: 8px; + margin-bottom: 0; + border-bottom: 1px solid var(--color-border); +} + +.hint-body { + padding: var(--border-radius-element); + max-width: 300px; +} +</style> diff --git a/apps/files_sharing/src/components/SharePermissionsEditor.vue b/apps/files_sharing/src/components/SharePermissionsEditor.vue deleted file mode 100644 index cc1a150ecc1..00000000000 --- a/apps/files_sharing/src/components/SharePermissionsEditor.vue +++ /dev/null @@ -1,290 +0,0 @@ -<!-- - - @copyright Copyright (c) 2022 Louis Chmn <louis@chmn.me> - - - - @author Louis Chmn <louis@chmn.me> - - - - @license GNU AGPL version 3 or any later version - - - - This program is free software: you can redistribute it and/or modify - - it under the terms of the GNU Affero General Public License as - - published by the Free Software Foundation, either version 3 of the - - License, or (at your option) any later version. - - - - This program is distributed in the hope that it will be useful, - - but WITHOUT ANY WARRANTY; without even the implied warranty of - - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - - GNU Affero General Public License for more details. - - - - You should have received a copy of the GNU Affero General Public License - - along with this program. If not, see <http://www.gnu.org/licenses/>. - - - --> - -<template> - <li> - <ul> - <!-- file --> - <NcActionCheckbox v-if="!isFolder" - :checked="shareHasPermissions(atomicPermissions.UPDATE)" - @update:checked="toggleSharePermissions(atomicPermissions.UPDATE)"> - {{ t('files_sharing', 'Allow editing') }} - </NcActionCheckbox> - - <!-- folder --> - <template v-if="isFolder && fileHasCreatePermission && config.isPublicUploadEnabled"> - <template v-if="!showCustomPermissionsForm"> - <NcActionRadio :checked="sharePermissionEqual(bundledPermissions.READ_ONLY)" - :value="bundledPermissions.READ_ONLY" - :name="randomFormName" - @change="setSharePermissions(bundledPermissions.READ_ONLY)"> - {{ t('files_sharing', 'Read only') }} - </NcActionRadio> - - <NcActionRadio :checked="sharePermissionEqual(bundledPermissions.UPLOAD_AND_UPDATE)" - :value="bundledPermissions.UPLOAD_AND_UPDATE" - :name="randomFormName" - @change="setSharePermissions(bundledPermissions.UPLOAD_AND_UPDATE)"> - {{ t('files_sharing', 'Allow upload and editing') }} - </NcActionRadio> - <NcActionRadio :checked="sharePermissionEqual(bundledPermissions.FILE_DROP)" - :value="bundledPermissions.FILE_DROP" - :name="randomFormName" - class="sharing-entry__action--public-upload" - @change="setSharePermissions(bundledPermissions.FILE_DROP)"> - {{ t('files_sharing', 'File drop (upload only)') }} - </NcActionRadio> - - <!-- custom permissions button --> - <NcActionButton :title="t('files_sharing', 'Custom permissions')" - @click="showCustomPermissionsForm = true"> - <template #icon> - <Tune /> - </template> - {{ sharePermissionsIsBundle ? "" : sharePermissionsSummary }} - </NcActionButton> - </template> - - <!-- custom permissions --> - <span v-else :class="{error: !sharePermissionsSetIsValid}"> - <NcActionCheckbox :checked="shareHasPermissions(atomicPermissions.READ)" - :disabled="!canToggleSharePermissions(atomicPermissions.READ)" - @update:checked="toggleSharePermissions(atomicPermissions.READ)"> - {{ t('files_sharing', 'Read') }} - </NcActionCheckbox> - <NcActionCheckbox :checked="shareHasPermissions(atomicPermissions.CREATE)" - :disabled="!canToggleSharePermissions(atomicPermissions.CREATE)" - @update:checked="toggleSharePermissions(atomicPermissions.CREATE)"> - {{ t('files_sharing', 'Upload') }} - </NcActionCheckbox> - <NcActionCheckbox :checked="shareHasPermissions(atomicPermissions.UPDATE)" - :disabled="!canToggleSharePermissions(atomicPermissions.UPDATE)" - @update:checked="toggleSharePermissions(atomicPermissions.UPDATE)"> - {{ t('files_sharing', 'Edit') }} - </NcActionCheckbox> - <NcActionCheckbox :checked="shareHasPermissions(atomicPermissions.DELETE)" - :disabled="!canToggleSharePermissions(atomicPermissions.DELETE)" - @update:checked="toggleSharePermissions(atomicPermissions.DELETE)"> - {{ t('files_sharing', 'Delete') }} - </NcActionCheckbox> - - <NcActionButton @click="showCustomPermissionsForm = false"> - <template #icon> - <ChevronLeft /> - </template> - {{ t('files_sharing', 'Bundled permissions') }} - </NcActionButton> - </span> - </template> - </ul> - </li> -</template> - -<script> -import NcActionButton from '@nextcloud/vue/dist/Components/NcActionButton.js' -import NcActionRadio from '@nextcloud/vue/dist/Components/NcActionRadio.js' -import NcActionCheckbox from '@nextcloud/vue/dist/Components/NcActionCheckbox.js' - -import SharesMixin from '../mixins/SharesMixin.js' -import { - ATOMIC_PERMISSIONS, - BUNDLED_PERMISSIONS, - hasPermissions, - permissionsSetIsValid, - togglePermissions, - canTogglePermissions, -} from '../lib/SharePermissionsToolBox.js' - -import Tune from 'vue-material-design-icons/Tune.vue' -import ChevronLeft from 'vue-material-design-icons/ChevronLeft.vue' - -export default { - name: 'SharePermissionsEditor', - - components: { - NcActionButton, - NcActionCheckbox, - NcActionRadio, - Tune, - ChevronLeft, - }, - - mixins: [SharesMixin], - - data() { - return { - randomFormName: Math.random().toString(27).substring(2), - - showCustomPermissionsForm: false, - - atomicPermissions: ATOMIC_PERMISSIONS, - bundledPermissions: BUNDLED_PERMISSIONS, - } - }, - - computed: { - /** - * Return the summary of custom checked permissions. - * - * @return {string} - */ - sharePermissionsSummary() { - return Object.values(this.atomicPermissions) - .filter(permission => this.shareHasPermissions(permission)) - .map(permission => { - switch (permission) { - case this.atomicPermissions.CREATE: - return this.t('files_sharing', 'Upload') - case this.atomicPermissions.READ: - return this.t('files_sharing', 'Read') - case this.atomicPermissions.UPDATE: - return this.t('files_sharing', 'Edit') - case this.atomicPermissions.DELETE: - return this.t('files_sharing', 'Delete') - default: - return null - } - }) - .filter(permissionLabel => permissionLabel !== null) - .join(', ') - }, - - /** - * Return whether the share's permission is a bundle. - * - * @return {boolean} - */ - sharePermissionsIsBundle() { - return Object.values(BUNDLED_PERMISSIONS) - .map(bundle => this.sharePermissionEqual(bundle)) - .filter(isBundle => isBundle) - .length > 0 - }, - - /** - * Return whether the share's permission is valid. - * - * @return {boolean} - */ - sharePermissionsSetIsValid() { - return permissionsSetIsValid(this.share.permissions) - }, - - /** - * Is the current share a folder ? - * TODO: move to a proper FileInfo model? - * - * @return {boolean} - */ - isFolder() { - return this.fileInfo.type === 'dir' - }, - - /** - * Does the current file/folder have create permissions. - * TODO: move to a proper FileInfo model? - * - * @return {boolean} - */ - fileHasCreatePermission() { - return !!(this.fileInfo.permissions & ATOMIC_PERMISSIONS.CREATE) - }, - }, - - mounted() { - // Show the Custom Permissions view on open if the permissions set is not a bundle. - this.showCustomPermissionsForm = !this.sharePermissionsIsBundle - }, - - methods: { - /** - * Return whether the share has the exact given permissions. - * - * @param {number} permissions - the permissions to check. - * - * @return {boolean} - */ - sharePermissionEqual(permissions) { - // We use the share's permission without PERMISSION_SHARE as it is not relevant here. - return (this.share.permissions & ~ATOMIC_PERMISSIONS.SHARE) === permissions - }, - - /** - * Return whether the share has the given permissions. - * - * @param {number} permissions - the permissions to check. - * - * @return {boolean} - */ - shareHasPermissions(permissions) { - return hasPermissions(this.share.permissions, permissions) - }, - - /** - * Set the share permissions to the given permissions. - * - * @param {number} permissions - the permissions to set. - * - * @return {void} - */ - setSharePermissions(permissions) { - this.share.permissions = permissions - this.queueUpdate('permissions') - }, - - /** - * Return whether some given permissions can be toggled. - * - * @param {number} permissionsToToggle - the permissions to toggle. - * - * @return {boolean} - */ - canToggleSharePermissions(permissionsToToggle) { - return canTogglePermissions(this.share.permissions, permissionsToToggle) - }, - - /** - * Toggle a given permission. - * - * @param {number} permissions - the permissions to toggle. - * - * @return {void} - */ - toggleSharePermissions(permissions) { - this.share.permissions = togglePermissions(this.share.permissions, permissions) - - if (!permissionsSetIsValid(this.share.permissions)) { - return - } - - this.queueUpdate('permissions') - }, - }, -} -</script> -<style lang="scss" scoped> -.error { - ::v-deep .action-checkbox__label:before { - border: 1px solid var(--color-error); - } -} -</style> diff --git a/apps/files_sharing/src/components/SharingEntry.vue b/apps/files_sharing/src/components/SharingEntry.vue index 84525fa2f0c..342b40ce384 100644 --- a/apps/files_sharing/src/components/SharingEntry.vue +++ b/apps/files_sharing/src/components/SharingEntry.vue @@ -1,54 +1,40 @@ <!-- - - @copyright Copyright (c) 2019 John Molakvoæ <skjnldsv@protonmail.com> - - - - @author John Molakvoæ <skjnldsv@protonmail.com> - - - - @license GNU AGPL version 3 or any later version - - - - This program is free software: you can redistribute it and/or modify - - it under the terms of the GNU Affero General Public License as - - published by the Free Software Foundation, either version 3 of the - - License, or (at your option) any later version. - - - - This program is distributed in the hope that it will be useful, - - but WITHOUT ANY WARRANTY; without even the implied warranty of - - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - - GNU Affero General Public License for more details. - - - - You should have received a copy of the GNU Affero General Public License - - along with this program. If not, see <http://www.gnu.org/licenses/>. - - - --> + - SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <template> <li class="sharing-entry"> <NcAvatar class="sharing-entry__avatar" - :is-no-user="share.type !== SHARE_TYPES.SHARE_TYPE_USER" + :is-no-user="share.type !== ShareType.User" :user="share.shareWith" :display-name="share.shareWithDisplayName" :menu-position="'left'" :url="share.shareWithAvatar" /> - <div class="sharing-entry__summary" @click.prevent="toggleQuickShareSelect"> + <div class="sharing-entry__summary"> <component :is="share.shareWithLink ? 'a' : 'div'" :title="tooltip" :aria-label="tooltip" :href="share.shareWithLink" class="sharing-entry__summary__desc"> <span>{{ title }} - <span v-if="!isUnique" class="sharing-entry__summary__desc-unique"> ({{ - share.shareWithDisplayNameUnique }})</span> + <span v-if="!isUnique" class="sharing-entry__summary__desc-unique"> + ({{ share.shareWithDisplayNameUnique }}) + </span> <small v-if="hasStatus && share.status.message">({{ share.status.message }})</small> </span> </component> - <QuickShareSelect :share="share" + <SharingEntryQuickShareSelect :share="share" :file-info="fileInfo" - :toggle="showDropdown" @open-sharing-details="openShareDetailsForCustomSettings(share)" /> </div> - <NcButton class="sharing-entry__action" + <ShareExpiryTime v-if="share && share.expireDate" :share="share" /> + <NcButton v-if="share.canEdit" + class="sharing-entry__action" + data-cy-files-sharing-share-actions :aria-label="t('files_sharing', 'Open Sharing Details')" - type="tertiary-no-background" + type="tertiary" @click="openSharingDetails(share)"> <template #icon> <DotsHorizontalIcon :size="20" /> @@ -58,12 +44,15 @@ </template> <script> -import NcButton from '@nextcloud/vue/dist/Components/NcButton.js' -import NcSelect from '@nextcloud/vue/dist/Components/NcSelect.js' -import NcAvatar from '@nextcloud/vue/dist/Components/NcAvatar.js' +import { ShareType } from '@nextcloud/sharing' + +import NcButton from '@nextcloud/vue/components/NcButton' +import NcSelect from '@nextcloud/vue/components/NcSelect' +import NcAvatar from '@nextcloud/vue/components/NcAvatar' import DotsHorizontalIcon from 'vue-material-design-icons/DotsHorizontal.vue' -import QuickShareSelect from './SharingEntryQuickShareSelect.vue' +import ShareExpiryTime from './ShareExpiryTime.vue' +import SharingEntryQuickShareSelect from './SharingEntryQuickShareSelect.vue' import SharesMixin from '../mixins/SharesMixin.js' import ShareDetails from '../mixins/ShareDetails.js' @@ -76,30 +65,35 @@ export default { NcAvatar, DotsHorizontalIcon, NcSelect, - QuickShareSelect, + ShareExpiryTime, + SharingEntryQuickShareSelect, }, mixins: [SharesMixin, ShareDetails], - data() { - return { - showDropdown: false, - } - }, computed: { title() { let title = this.share.shareWithDisplayName - if (this.share.type === this.SHARE_TYPES.SHARE_TYPE_GROUP) { + + const showAsInternal = this.config.showFederatedSharesAsInternal + || (this.share.isTrustedServer && this.config.showFederatedSharesToTrustedServersAsInternal) + + if (this.share.type === ShareType.Group || (this.share.type === ShareType.RemoteGroup && showAsInternal)) { title += ` (${t('files_sharing', 'group')})` - } else if (this.share.type === this.SHARE_TYPES.SHARE_TYPE_ROOM) { + } else if (this.share.type === ShareType.Room) { title += ` (${t('files_sharing', 'conversation')})` - } else if (this.share.type === this.SHARE_TYPES.SHARE_TYPE_REMOTE) { + } else if (this.share.type === ShareType.Remote && !showAsInternal) { title += ` (${t('files_sharing', 'remote')})` - } else if (this.share.type === this.SHARE_TYPES.SHARE_TYPE_REMOTE_GROUP) { + } else if (this.share.type === ShareType.RemoteGroup) { title += ` (${t('files_sharing', 'remote group')})` - } else if (this.share.type === this.SHARE_TYPES.SHARE_TYPE_GUEST) { + } else if (this.share.type === ShareType.Guest) { title += ` (${t('files_sharing', 'guest')})` } + if (!this.isShareOwner && this.share.ownerDisplayName) { + title += ' ' + t('files_sharing', 'by {initiator}', { + initiator: this.share.ownerDisplayName, + }) + } return title }, tooltip() { @@ -110,9 +104,9 @@ export default { user: this.share.shareWithDisplayName, owner: this.share.ownerDisplayName, } - if (this.share.type === this.SHARE_TYPES.SHARE_TYPE_GROUP) { + if (this.share.type === ShareType.Group) { return t('files_sharing', 'Shared with the group {user} by {owner}', data) - } else if (this.share.type === this.SHARE_TYPES.SHARE_TYPE_ROOM) { + } else if (this.share.type === ShareType.Room) { return t('files_sharing', 'Shared with the conversation {user} by {owner}', data) } @@ -125,7 +119,7 @@ export default { * @return {boolean} */ hasStatus() { - if (this.share.type !== this.SHARE_TYPES.SHARE_TYPE_USER) { + if (this.share.type !== ShareType.User) { return false } @@ -140,9 +134,6 @@ export default { onMenuClose() { this.onNoteSubmit() }, - toggleQuickShareSelect() { - this.showDropdown = !this.showDropdown - }, }, } </script> @@ -154,10 +145,11 @@ export default { height: 44px; &__summary { padding: 8px; - padding-left: 10px; + padding-inline-start: 10px; display: flex; flex-direction: column; justify-content: center; + align-items: flex-start; flex: 1 0; min-width: 0; diff --git a/apps/files_sharing/src/components/SharingEntryInherited.vue b/apps/files_sharing/src/components/SharingEntryInherited.vue index 6a71b55d612..e7dfffd5776 100644 --- a/apps/files_sharing/src/components/SharingEntryInherited.vue +++ b/apps/files_sharing/src/components/SharingEntryInherited.vue @@ -1,24 +1,7 @@ <!-- - - @copyright Copyright (c) 2019 John Molakvoæ <skjnldsv@protonmail.com> - - - - @author John Molakvoæ <skjnldsv@protonmail.com> - - - - @license GNU AGPL version 3 or any later version - - - - This program is free software: you can redistribute it and/or modify - - it under the terms of the GNU Affero General Public License as - - published by the Free Software Foundation, either version 3 of the - - License, or (at your option) any later version. - - - - This program is distributed in the hope that it will be useful, - - but WITHOUT ANY WARRANTY; without even the implied warranty of - - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - - GNU Affero General Public License for more details. - - - - You should have received a copy of the GNU Affero General Public License - - along with this program. If not, see <http://www.gnu.org/licenses/>. - - - --> + - SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <template> <SharingEntrySimple :key="share.id" @@ -48,10 +31,10 @@ <script> import { generateUrl } from '@nextcloud/router' import { basename } from '@nextcloud/paths' -import NcAvatar from '@nextcloud/vue/dist/Components/NcAvatar.js' -import NcActionButton from '@nextcloud/vue/dist/Components/NcActionButton.js' -import NcActionLink from '@nextcloud/vue/dist/Components/NcActionLink.js' -import NcActionText from '@nextcloud/vue/dist/Components/NcActionText.js' +import NcAvatar from '@nextcloud/vue/components/NcAvatar' +import NcActionButton from '@nextcloud/vue/components/NcActionButton' +import NcActionLink from '@nextcloud/vue/components/NcActionLink' +import NcActionText from '@nextcloud/vue/components/NcActionText' // eslint-disable-next-line no-unused-vars import Share from '../models/Share.js' @@ -102,14 +85,14 @@ export default { flex-direction: column; justify-content: space-between; padding: 8px; - padding-left: 10px; + padding-inline-start: 10px; line-height: 1.2em; p { color: var(--color-text-maxcontrast); } } &__actions { - margin-left: auto; + margin-inline-start: auto; } } </style> diff --git a/apps/files_sharing/src/components/SharingEntryInternal.vue b/apps/files_sharing/src/components/SharingEntryInternal.vue index f6b900b8bf7..027d2a3d5c3 100644 --- a/apps/files_sharing/src/components/SharingEntryInternal.vue +++ b/apps/files_sharing/src/components/SharingEntryInternal.vue @@ -1,3 +1,7 @@ +<!-- + - SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <template> <ul> <SharingEntrySimple ref="shareEntrySimple" @@ -10,8 +14,14 @@ <NcActionButton :title="copyLinkTooltip" :aria-label="copyLinkTooltip" - :icon="copied && copySuccess ? 'icon-checkmark-color' : 'icon-clippy'" - @click="copyLink" /> + @click="copyLink"> + <template #icon> + <CheckIcon v-if="copied && copySuccess" + :size="20" + class="icon-checkmark-color" /> + <ClipboardIcon v-else :size="20" /> + </template> + </NcActionButton> </SharingEntrySimple> </ul> </template> @@ -19,7 +29,11 @@ <script> import { generateUrl } from '@nextcloud/router' import { showSuccess } from '@nextcloud/dialogs' -import NcActionButton from '@nextcloud/vue/dist/Components/NcActionButton.js' +import NcActionButton from '@nextcloud/vue/components/NcActionButton' + +import CheckIcon from 'vue-material-design-icons/Check.vue' +import ClipboardIcon from 'vue-material-design-icons/ContentCopy.vue' + import SharingEntrySimple from './SharingEntrySimple.vue' export default { @@ -28,6 +42,8 @@ export default { components: { NcActionButton, SharingEntrySimple, + CheckIcon, + ClipboardIcon, }, props: { @@ -67,14 +83,11 @@ export default { } return t('files_sharing', 'Cannot copy, please copy the link manually') } - return t('files_sharing', 'Copy internal link to clipboard') + return t('files_sharing', 'Copy internal link') }, internalLinkSubtitle() { - if (this.fileInfo.type === 'dir') { - return t('files_sharing', 'Only works for users with access to this folder') - } - return t('files_sharing', 'Only works for users with access to this file') + return t('files_sharing', 'For people who already have access') }, }, @@ -114,6 +127,7 @@ export default { } .icon-checkmark-color { opacity: 1; + color: var(--color-success); } } </style> diff --git a/apps/files_sharing/src/components/SharingEntryLink.vue b/apps/files_sharing/src/components/SharingEntryLink.vue index accc349f734..6865af1b864 100644 --- a/apps/files_sharing/src/components/SharingEntryLink.vue +++ b/apps/files_sharing/src/components/SharingEntryLink.vue @@ -1,64 +1,64 @@ <!-- - - @copyright Copyright (c) 2019 John Molakvoæ <skjnldsv@protonmail.com> - - - - @author John Molakvoæ <skjnldsv@protonmail.com> - - - - @license GNU AGPL version 3 or any later version - - - - This program is free software: you can redistribute it and/or modify - - it under the terms of the GNU Affero General Public License as - - published by the Free Software Foundation, either version 3 of the - - License, or (at your option) any later version. - - - - This program is distributed in the hope that it will be useful, - - but WITHOUT ANY WARRANTY; without even the implied warranty of - - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - - GNU Affero General Public License for more details. - - - - You should have received a copy of the GNU Affero General Public License - - along with this program. If not, see <http://www.gnu.org/licenses/>. - - - --> + - SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <template> - <li :class="{ 'sharing-entry--share': share }" class="sharing-entry sharing-entry__link"> + <li :class="{ 'sharing-entry--share': share }" + class="sharing-entry sharing-entry__link"> <NcAvatar :is-no-user="true" :icon-class="isEmailShareType ? 'avatar-link-share icon-mail-white' : 'avatar-link-share icon-public-white'" class="sharing-entry__avatar" /> <div class="sharing-entry__summary"> - <div class="sharing-entry__desc" @click.prevent="toggleQuickShareSelect"> + <div class="sharing-entry__desc"> <span class="sharing-entry__title" :title="title"> {{ title }} </span> <p v-if="subtitle"> {{ subtitle }} </p> - <QuickShareSelect v-if="share && share.permissions !== undefined" + <SharingEntryQuickShareSelect v-if="share && share.permissions !== undefined" :share="share" :file-info="fileInfo" - :toggle="showDropdown" @open-sharing-details="openShareDetailsForCustomSettings(share)" /> </div> - <!-- clipboard --> - <NcActions v-if="share && !isEmailShareType && share.token" ref="copyButton" class="sharing-entry__copy"> - <NcActionButton :title="copyLinkTooltip" - :aria-label="copyLinkTooltip" - :icon="copied && copySuccess ? 'icon-checkmark-color' : 'icon-clippy'" - @click.prevent="copyLink" /> - </NcActions> + <div class="sharing-entry__actions"> + <ShareExpiryTime v-if="share && share.expireDate" :share="share" /> + + <!-- clipboard --> + <div> + <NcActions v-if="share && (!isEmailShareType || isFileRequest) && share.token" ref="copyButton" class="sharing-entry__copy"> + <NcActionButton :aria-label="copyLinkTooltip" + :title="copyLinkTooltip" + :href="shareLink" + @click.prevent="copyLink"> + <template #icon> + <CheckIcon v-if="copied && copySuccess" + :size="20" + class="icon-checkmark-color" /> + <ClipboardIcon v-else :size="20" /> + </template> + </NcActionButton> + </NcActions> + </div> + </div> </div> <!-- pending actions --> - <NcActions v-if="!pending && (pendingPassword || pendingEnforcedPassword || pendingExpirationDate)" + <NcActions v-if="!pending && pendingDataIsMissing" class="sharing-entry__actions" :aria-label="actionsTooltip" menu-align="right" :open.sync="open" @close="onCancel"> <!-- pending data menu --> - <NcActionText v-if="errors.pending" icon="icon-error" :class="{ error: errors.pending }"> + <NcActionText v-if="errors.pending" + class="error"> + <template #icon> + <ErrorIcon :size="20" /> + </template> {{ errors.pending }} </NcActionText> <NcActionText v-else icon="icon-info"> @@ -66,35 +66,41 @@ </NcActionText> <!-- password --> - <NcActionText v-if="pendingEnforcedPassword" icon="icon-password"> - {{ t('files_sharing', 'Password protection (enforced)') }} - </NcActionText> - <NcActionCheckbox v-else-if="pendingPassword" + <NcActionCheckbox v-if="pendingPassword" :checked.sync="isPasswordProtected" :disabled="config.enforcePasswordForPublicLink || saving" class="share-link-password-checkbox" @uncheck="onPasswordDisable"> - {{ t('files_sharing', 'Password protection') }} + {{ config.enforcePasswordForPublicLink ? t('files_sharing', 'Password protection (enforced)') : t('files_sharing', 'Password protection') }} </NcActionCheckbox> - <NcActionInput v-if="pendingEnforcedPassword || share.password" + <NcActionInput v-if="pendingEnforcedPassword || isPasswordProtected" class="share-link-password" - :value.sync="share.password" + :label="t('files_sharing', 'Enter a password')" + :value.sync="share.newPassword" :disabled="saving" :required="config.enableLinkPasswordByDefault || config.enforcePasswordForPublicLink" :minlength="isPasswordPolicyEnabled && config.passwordPolicy.minLength" - icon="" autocomplete="new-password" - @submit="onNewLinkShare"> - {{ t('files_sharing', 'Enter a password') }} + @submit="onNewLinkShare(true)"> + <template #icon> + <LockIcon :size="20" /> + </template> </NcActionInput> + <NcActionCheckbox v-if="pendingDefaultExpirationDate" + :checked.sync="defaultExpirationDateEnabled" + :disabled="pendingEnforcedExpirationDate || saving" + class="share-link-expiration-date-checkbox" + @update:model-value="onExpirationDateToggleUpdate"> + {{ config.isDefaultExpireDateEnforced ? t('files_sharing', 'Enable link expiration (enforced)') : t('files_sharing', 'Enable link expiration') }} + </NcActionCheckbox> + <!-- expiration date --> - <NcActionText v-if="pendingExpirationDate" icon="icon-calendar-dark"> - {{ t('files_sharing', 'Expiration date (enforced)') }} - </NcActionText> - <NcActionInput v-if="pendingExpirationDate" + <NcActionInput v-if="(pendingDefaultExpirationDate || pendingEnforcedExpirationDate) && defaultExpirationDateEnabled" + data-cy-files-sharing-expiration-date-input class="share-link-expire-date" + :label="pendingEnforcedExpirationDate ? t('files_sharing', 'Enter expiration date (enforced)') : t('files_sharing', 'Enter expiration date')" :disabled="saving" :is-native-picker="true" :hide-label="true" @@ -102,16 +108,24 @@ type="date" :min="dateTomorrow" :max="maxExpirationDateEnforced" - @input="onExpirationChange"> - <!-- let's not submit when picked, the user - might want to still edit or copy the password --> - {{ t('files_sharing', 'Enter a date') }} + @update:model-value="onExpirationChange" + @change="expirationDateChanged"> + <template #icon> + <IconCalendarBlank :size="20" /> + </template> </NcActionInput> - <NcActionButton icon="icon-checkmark" @click.prevent.stop="onNewLinkShare"> + <NcActionButton :disabled="pendingEnforcedPassword && !share.newPassword" + @click.prevent.stop="onNewLinkShare(true)"> + <template #icon> + <CheckIcon :size="20" /> + </template> {{ t('files_sharing', 'Create share') }} </NcActionButton> - <NcActionButton icon="icon-close" @click.prevent.stop="onCancel"> + <NcActionButton @click.prevent.stop="onCancel"> + <template #icon> + <CloseIcon :size="20" /> + </template> {{ t('files_sharing', 'Cancel') }} </NcActionButton> </NcActions> @@ -125,14 +139,24 @@ @close="onMenuClose"> <template v-if="share"> <template v-if="share.canEdit && canReshare"> - <NcActionButton :disabled="saving" @click.prevent="openSharingDetails"> + <NcActionButton :disabled="saving" + :close-after-click="true" + @click.prevent="openSharingDetails"> <template #icon> - <Tune /> + <Tune :size="20" /> </template> {{ t('files_sharing', 'Customize link') }} </NcActionButton> </template> + <NcActionButton :close-after-click="true" + @click.prevent="showQRCode = true"> + <template #icon> + <IconQr :size="20" /> + </template> + {{ t('files_sharing', 'Generate QR code') }} + </NcActionButton> + <NcActionSeparator /> <!-- external actions --> @@ -144,8 +168,8 @@ :share="share" /> <!-- external legacy sharing via url (social...) --> - <NcActionLink v-for="({ icon, url, name }, index) in externalLegacyLinkActions" - :key="index" + <NcActionLink v-for="({ icon, url, name }, actionIndex) in externalLegacyLinkActions" + :key="actionIndex" :href="url(shareLink)" :icon="icon" target="_blank"> @@ -154,15 +178,19 @@ <NcActionButton v-if="!isEmailShareType && canReshare" class="new-share-link" - icon="icon-add" @click.prevent.stop="onNewLinkShare"> + <template #icon> + <PlusIcon :size="20" /> + </template> {{ t('files_sharing', 'Add another link') }} </NcActionButton> <NcActionButton v-if="share.canDelete" - icon="icon-close" :disabled="saving" @click.prevent="onDelete"> + <template #icon> + <CloseIcon :size="20" /> + </template> {{ t('files_sharing', 'Unshare') }} </NcActionButton> </template> @@ -178,32 +206,61 @@ <!-- loading indicator to replace the menu --> <div v-else class="icon-loading-small sharing-entry__loading" /> + + <!-- Modal to open whenever we have a QR code --> + <NcDialog v-if="showQRCode" + size="normal" + :open.sync="showQRCode" + :name="title" + :close-on-click-outside="true" + @close="showQRCode = false"> + <div class="qr-code-dialog"> + <VueQrcode tag="img" + :value="shareLink" + class="qr-code-dialog__img" /> + </div> + </NcDialog> </li> </template> <script> -import { generateUrl } from '@nextcloud/router' import { showError, showSuccess } from '@nextcloud/dialogs' -import { Type as ShareTypes } from '@nextcloud/sharing' -import Vue from 'vue' - -import NcActionButton from '@nextcloud/vue/dist/Components/NcActionButton.js' -import NcActionInput from '@nextcloud/vue/dist/Components/NcActionInput.js' -import NcActionLink from '@nextcloud/vue/dist/Components/NcActionLink.js' -import NcActionText from '@nextcloud/vue/dist/Components/NcActionText.js' -import NcActionSeparator from '@nextcloud/vue/dist/Components/NcActionSeparator.js' -import NcActions from '@nextcloud/vue/dist/Components/NcActions.js' -import NcAvatar from '@nextcloud/vue/dist/Components/NcAvatar.js' +import { emit } from '@nextcloud/event-bus' +import { t } from '@nextcloud/l10n' +import moment from '@nextcloud/moment' +import { generateUrl, getBaseUrl } from '@nextcloud/router' +import { ShareType } from '@nextcloud/sharing' + +import VueQrcode from '@chenfengyuan/vue-qrcode' +import NcActionButton from '@nextcloud/vue/components/NcActionButton' +import NcActionCheckbox from '@nextcloud/vue/components/NcActionCheckbox' +import NcActionInput from '@nextcloud/vue/components/NcActionInput' +import NcActionLink from '@nextcloud/vue/components/NcActionLink' +import NcActionText from '@nextcloud/vue/components/NcActionText' +import NcActionSeparator from '@nextcloud/vue/components/NcActionSeparator' +import NcActions from '@nextcloud/vue/components/NcActions' +import NcAvatar from '@nextcloud/vue/components/NcAvatar' +import NcDialog from '@nextcloud/vue/components/NcDialog' import Tune from 'vue-material-design-icons/Tune.vue' - -import QuickShareSelect from './SharingEntryQuickShareSelect.vue' +import IconCalendarBlank from 'vue-material-design-icons/CalendarBlankOutline.vue' +import IconQr from 'vue-material-design-icons/Qrcode.vue' +import ErrorIcon from 'vue-material-design-icons/Exclamation.vue' +import LockIcon from 'vue-material-design-icons/LockOutline.vue' +import CheckIcon from 'vue-material-design-icons/CheckBold.vue' +import ClipboardIcon from 'vue-material-design-icons/ContentCopy.vue' +import CloseIcon from 'vue-material-design-icons/Close.vue' +import PlusIcon from 'vue-material-design-icons/Plus.vue' + +import SharingEntryQuickShareSelect from './SharingEntryQuickShareSelect.vue' +import ShareExpiryTime from './ShareExpiryTime.vue' import ExternalShareAction from './ExternalShareAction.vue' -import GeneratePassword from '../utils/GeneratePassword.js' -import Share from '../models/Share.js' +import GeneratePassword from '../utils/GeneratePassword.ts' +import Share from '../models/Share.ts' import SharesMixin from '../mixins/SharesMixin.js' import ShareDetails from '../mixins/ShareDetails.js' +import logger from '../services/logger.ts' export default { name: 'SharingEntryLink', @@ -212,13 +269,25 @@ export default { ExternalShareAction, NcActions, NcActionButton, + NcActionCheckbox, NcActionInput, NcActionLink, NcActionText, NcActionSeparator, NcAvatar, + NcDialog, + VueQrcode, Tune, - QuickShareSelect, + IconCalendarBlank, + IconQr, + ErrorIcon, + LockIcon, + CheckIcon, + ClipboardIcon, + CloseIcon, + PlusIcon, + SharingEntryQuickShareSelect, + ShareExpiryTime, }, mixins: [SharesMixin, ShareDetails], @@ -236,15 +305,19 @@ export default { data() { return { - showDropdown: false, + shareCreationComplete: false, copySuccess: true, copied: false, + defaultExpirationDateEnabled: false, // Are we waiting for password/expiration date pending: false, ExternalLegacyLinkActions: OCA.Sharing.ExternalLinkActions.state, ExternalShareActions: OCA.Sharing.ExternalShareActions.state, + + // tracks whether modal should be opened or not + showQRCode: false, } }, @@ -255,6 +328,8 @@ export default { * @return {string} */ title() { + const l10nOptions = { escape: false /* no escape as this string is already escaped by Vue */ } + // if we have a valid existing share (not pending) if (this.share && this.share.id) { if (!this.isShareOwner && this.share.ownerDisplayName) { @@ -262,30 +337,46 @@ export default { return t('files_sharing', '{shareWith} by {initiator}', { shareWith: this.share.shareWith, initiator: this.share.ownerDisplayName, - }) + }, l10nOptions) } return t('files_sharing', 'Shared via link by {initiator}', { initiator: this.share.ownerDisplayName, - }) + }, l10nOptions) } if (this.share.label && this.share.label.trim() !== '') { if (this.isEmailShareType) { + if (this.isFileRequest) { + return t('files_sharing', 'File request ({label})', { + label: this.share.label.trim(), + }, l10nOptions) + } return t('files_sharing', 'Mail share ({label})', { label: this.share.label.trim(), - }) + }, l10nOptions) } return t('files_sharing', 'Share link ({label})', { label: this.share.label.trim(), - }) + }, l10nOptions) } if (this.isEmailShareType) { + if (!this.share.shareWith || this.share.shareWith.trim() === '') { + return this.isFileRequest + ? t('files_sharing', 'File request') + : t('files_sharing', 'Mail share') + } return this.share.shareWith } + + if (this.index === null) { + return t('files_sharing', 'Share link') + } } - if (this.index > 1) { + + if (this.index >= 1) { return t('files_sharing', 'Share link ({index})', { index: this.index }) } - return t('files_sharing', 'Share link') + + return t('files_sharing', 'Create public link') }, /** @@ -300,22 +391,6 @@ export default { } return null }, - /** - * Is the current share password protected ? - * - * @return {boolean} - */ - isPasswordProtected: { - get() { - return this.config.enforcePasswordForPublicLink - || !!this.share.password - }, - async set(enabled) { - // TODO: directly save after generation to make sure the share is always protected - Vue.set(this.share, 'password', enabled ? await GeneratePassword() : '') - Vue.set(this.share, 'newPassword', this.share.password) - }, - }, passwordExpirationTime() { if (this.share.passwordExpirationTime === null) { @@ -370,7 +445,7 @@ export default { */ isEmailShareType() { return this.share - ? this.share.type === this.SHARE_TYPES.SHARE_TYPE_EMAIL + ? this.share.type === ShareType.Email : false }, @@ -395,16 +470,50 @@ export default { * * @return {boolean} */ + pendingDataIsMissing() { + return this.pendingPassword || this.pendingEnforcedPassword || this.pendingDefaultExpirationDate || this.pendingEnforcedExpirationDate + }, pendingPassword() { - return this.config.enableLinkPasswordByDefault && this.share && !this.share.id + return this.config.enableLinkPasswordByDefault && this.isPendingShare }, pendingEnforcedPassword() { - return this.config.enforcePasswordForPublicLink && this.share && !this.share.id + return this.config.enforcePasswordForPublicLink && this.isPendingShare + }, + pendingEnforcedExpirationDate() { + return this.config.isDefaultExpireDateEnforced && this.isPendingShare + }, + pendingDefaultExpirationDate() { + return (this.config.defaultExpirationDate instanceof Date || !isNaN(new Date(this.config.defaultExpirationDate).getTime())) && this.isPendingShare }, - pendingExpirationDate() { - return this.config.isDefaultExpireDateEnforced && this.share && !this.share.id + isPendingShare() { + return !!(this.share && !this.share.id) }, + sharePolicyHasEnforcedProperties() { + return this.config.enforcePasswordForPublicLink || this.config.isDefaultExpireDateEnforced + }, + + enforcedPropertiesMissing() { + // Ensure share exist and the share policy has required properties + if (!this.sharePolicyHasEnforcedProperties) { + return false + } + if (!this.share) { + // if no share, we can't tell if properties are missing or not so we assume properties are missing + return true + } + + // If share has ID, then this is an incoming link share created from the existing link share + // Hence assume required properties + if (this.share.id) { + return true + } + // Check if either password or expiration date is missing and enforced + const isPasswordMissing = this.config.enforcePasswordForPublicLink && !this.share.password + const isExpireDateMissing = this.config.isDefaultExpireDateEnforced && !this.share.expireDate + + return isPasswordMissing || isExpireDateMissing + }, // if newPassword exists, but is empty, it means // the user deleted the original password hasUnsavedPassword() { @@ -417,7 +526,7 @@ export default { * @return {string} */ shareLink() { - return window.location.protocol + '//' + window.location.host + generateUrl('/s/') + this.share.token + return generateUrl('/s/{token}', { token: this.share.token }, { baseURL: getBaseUrl() }) }, /** @@ -441,7 +550,7 @@ export default { } return t('files_sharing', 'Cannot copy, please copy the link manually') } - return t('files_sharing', 'Copy public link of "{title}" to clipboard', { title: this.title }) + return t('files_sharing', 'Copy public link of "{title}"', { title: this.title }) }, /** @@ -460,10 +569,10 @@ export default { * @return {Array} */ externalLinkActions() { + const filterValidAction = (action) => (action.shareType.includes(ShareType.Link) || action.shareType.includes(ShareType.Email)) && !action.advanced // filter only the registered actions for said link return this.ExternalShareActions.actions - .filter(action => action.shareType.includes(ShareTypes.SHARE_TYPE_LINK) - || action.shareType.includes(ShareTypes.SHARE_TYPE_EMAIL)) + .filter(filterValidAction) }, isPasswordPolicyEnabled() { @@ -471,23 +580,48 @@ export default { }, canChangeHideDownload() { - const hasDisabledDownload = (shareAttribute) => shareAttribute.key === 'download' && shareAttribute.scope === 'permissions' && shareAttribute.enabled === false + const hasDisabledDownload = (shareAttribute) => shareAttribute.scope === 'permissions' && shareAttribute.key === 'download' && shareAttribute.value === false return this.fileInfo.shareAttributes.some(hasDisabledDownload) }, + + isFileRequest() { + return this.share.isFileRequest + }, + }, + mounted() { + this.defaultExpirationDateEnabled = this.config.defaultExpirationDate instanceof Date + if (this.share && this.isNewShare) { + this.share.expireDate = this.defaultExpirationDateEnabled ? this.formatDateToString(this.config.defaultExpirationDate) : '' + } }, methods: { /** + * Check if the share requires review + * + * @param {boolean} shareReviewComplete if the share was reviewed + * @return {boolean} + */ + shareRequiresReview(shareReviewComplete) { + // If a user clicks 'Create share' it means they have reviewed the share + if (shareReviewComplete) { + return false + } + return this.defaultExpirationDateEnabled || this.config.enableLinkPasswordByDefault + }, + /** * Create a new share link and append it to the list + * @param {boolean} shareReviewComplete if the share was reviewed */ - async onNewLinkShare() { + async onNewLinkShare(shareReviewComplete = false) { + logger.debug('onNewLinkShare called (with this.share)', this.share) // do not run again if already loading if (this.loading) { return } const shareDefaults = { - share_type: ShareTypes.SHARE_TYPE_LINK, + share_type: ShareType.Link, } if (this.config.isDefaultExpireDateEnforced) { // default is empty string if not set @@ -495,37 +629,25 @@ export default { shareDefaults.expiration = this.formatDateToString(this.config.defaultExpirationDate) } - // do not push yet if we need a password or an expiration date: show pending menu - if (this.config.enableLinkPasswordByDefault || this.config.enforcePasswordForPublicLink || this.config.isDefaultExpireDateEnforced) { + logger.debug('Missing required properties?', this.enforcedPropertiesMissing) + // Do not push yet if we need a password or an expiration date: show pending menu + // A share would require a review for example is default expiration date is set but not enforced, this allows + // the user to review the share and remove the expiration date if they don't want it + if ((this.sharePolicyHasEnforcedProperties && this.enforcedPropertiesMissing) || this.shareRequiresReview(shareReviewComplete === true)) { this.pending = true + this.shareCreationComplete = false - // if a share already exists, pushing it - if (this.share && !this.share.id) { - // if the share is valid, create it on the server - if (this.checkShare(this.share)) { - try { - await this.pushNewLinkShare(this.share, true) - } catch (e) { - this.pending = false - console.error(e) - return false - } - return true - } else { - this.open = true - OC.Notification.showTemporary(t('files_sharing', 'Error, please enter proper password and/or expiration date')) - return false - } - } + logger.info('Share policy requires a review or has mandated properties (password, expirationDate)...') // ELSE, show the pending popovermenu // if password default or enforced, pre-fill with random one if (this.config.enableLinkPasswordByDefault || this.config.enforcePasswordForPublicLink) { - shareDefaults.password = await GeneratePassword() + shareDefaults.password = await GeneratePassword(true) } // create share & close menu const share = new Share(shareDefaults) + share.newPassword = share.password const component = await new Promise(resolve => { this.$emit('add:share', share, resolve) }) @@ -538,8 +660,32 @@ export default { // Nothing is enforced, creating share directly } else { + + // if a share already exists, pushing it + if (this.share && !this.share.id) { + // if the share is valid, create it on the server + if (this.checkShare(this.share)) { + try { + logger.info('Sending existing share to server', this.share) + await this.pushNewLinkShare(this.share, true) + this.shareCreationComplete = true + logger.info('Share created on server', this.share) + } catch (e) { + this.pending = false + logger.error('Error creating share', e) + return false + } + return true + } else { + this.open = true + showError(t('files_sharing', 'Error, please enter proper password and/or expiration date')) + return false + } + } + const share = new Share(shareDefaults) await this.pushNewLinkShare(share) + this.shareCreationComplete = true } }, @@ -564,14 +710,14 @@ export default { const path = (this.fileInfo.path + '/' + this.fileInfo.name).replace('//', '/') const options = { path, - shareType: ShareTypes.SHARE_TYPE_LINK, + shareType: ShareType.Link, password: share.password, - expireDate: share.expireDate, + expireDate: share.expireDate ?? '', attributes: JSON.stringify(this.fileInfo.shareAttributes), // we do not allow setting the publicUpload // before the share creation. // Todo: We also need to fix the createShare method in - // lib/Controller/ShareAPIController.php to allow file drop + // lib/Controller/ShareAPIController.php to allow file requests // (currently not supported on create, only update) } @@ -579,8 +725,8 @@ export default { const newShare = await this.createShare(options) this.open = false + this.shareCreationComplete = true console.debug('Link share created', newShare) - // if share already exists, copy link directly on next tick let component if (update) { @@ -596,6 +742,9 @@ export default { }) } + await this.getNode() + emit('files:node:updated', this.node) + // Execute the copy link method // freshly created share component // ! somehow does not works on firefox ! @@ -622,8 +771,10 @@ export default { this.onSyncError('pending', message) } throw data + } finally { this.loading = false + this.shareCreationComplete = true } }, async copyLink() { @@ -689,7 +840,7 @@ export default { */ onPasswordSubmit() { if (this.hasUnsavedPassword) { - this.share.password = this.share.newPassword.trim() + this.share.newPassword = this.share.newPassword.trim() this.queueUpdate('password') } }, @@ -704,7 +855,7 @@ export default { */ onPasswordProtectedByTalkChange() { if (this.hasUnsavedPassword) { - this.share.password = this.share.newPassword.trim() + this.share.newPassword = this.share.newPassword.trim() } this.queueUpdate('sendPasswordByTalk', 'password') @@ -719,6 +870,19 @@ export default { }, /** + * @param enabled True if expiration is enabled + */ + onExpirationDateToggleUpdate(enabled) { + this.share.expireDate = enabled ? this.formatDateToString(this.config.defaultExpirationDate) : '' + }, + + expirationDateChanged(event) { + const value = event?.target?.value + const isValid = !!value && !isNaN(new Date(value).getTime()) + this.defaultExpirationDateEnabled = isValid + }, + + /** * Cancel the share creation * Used in the pending popover */ @@ -726,11 +890,9 @@ export default { // this.share already exists at this point, // but is incomplete as not pushed to server // YET. We can safely delete the share :) - this.$emit('remove:share', this.share) - }, - - toggleQuickShareSelect() { - this.showDropdown = !this.showDropdown + if (!this.shareCreationComplete) { + this.$emit('remove:share', this.share) + } }, }, } @@ -744,32 +906,34 @@ export default { &__summary { padding: 8px; - padding-left: 10px; + padding-inline-start: 10px; display: flex; justify-content: space-between; flex: 1 0; min-width: 0; + } - &__desc { - display: flex; - flex-direction: column; - line-height: 1.2em; + &__desc { + display: flex; + flex-direction: column; + line-height: 1.2em; - p { - color: var(--color-text-maxcontrast); - } + p { + color: var(--color-text-maxcontrast); + } - &__title { - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; + &__title { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + } } - } - - &__copy { - } - } + &__actions { + display: flex; + align-items: center; + margin-inline-start: auto; + } &:not(.sharing-entry--share) &__actions { .new-share-link { @@ -777,7 +941,7 @@ export default { } } - ::v-deep .avatar-link-share { + :deep(.avatar-link-share) { background-color: var(--color-primary-element); } @@ -790,7 +954,7 @@ export default { height: 44px; margin: 0; padding: 14px; - margin-left: auto; + margin-inline-start: auto; } // put menus to the left @@ -799,12 +963,25 @@ export default { ~.action-item, ~.sharing-entry__loading { - margin-left: 0; + margin-inline-start: 0; } } .icon-checkmark-color { opacity: 1; + color: var(--color-success); + } +} + +// styling for the qr-code container +.qr-code-dialog { + display: flex; + width: 100%; + justify-content: center; + + &__img { + width: 100%; + height: auto; } } </style> diff --git a/apps/files_sharing/src/components/SharingEntryQuickShareSelect.vue b/apps/files_sharing/src/components/SharingEntryQuickShareSelect.vue index 2bf30533b59..102eea63cb6 100644 --- a/apps/files_sharing/src/components/SharingEntryQuickShareSelect.vue +++ b/apps/files_sharing/src/components/SharingEntryQuickShareSelect.vue @@ -1,70 +1,80 @@ +<!-- + - SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <template> - <div ref="quickShareDropdownContainer" - :class="{ 'active': showDropdown, 'share-select': true }"> - <span :id="dropdownId" - class="trigger-text" - :aria-expanded="showDropdown" - :aria-haspopup="true" - aria-label="Quick share options dropdown" - @click="toggleDropdown"> - {{ selectedOption }} + <NcActions ref="quickShareActions" + class="share-select" + :menu-name="selectedOption" + :aria-label="ariaLabel" + type="tertiary-no-background" + :disabled="!share.canEdit" + force-name> + <template #icon> <DropdownIcon :size="15" /> - </span> - <div v-if="showDropdown" - ref="quickShareDropdown" - class="share-select-dropdown" - :aria-labelledby="dropdownId" - tabindex="0" - @keydown.down="handleArrowDown" - @keydown.up="handleArrowUp" - @keydown.esc="closeDropdown"> - <button v-for="option in options" - :key="option" - :class="{ 'dropdown-item': true, 'selected': option === selectedOption }" - :aria-selected="option === selectedOption" - @click="selectOption(option)"> - {{ option }} - </button> - </div> - </div> + </template> + <NcActionButton v-for="option in options" + :key="option.label" + type="radio" + :model-value="option.label === selectedOption" + close-after-click + @click="selectOption(option.label)"> + <template #icon> + <component :is="option.icon" /> + </template> + {{ option.label }} + </NcActionButton> + </NcActions> </template> <script> +import { ShareType } from '@nextcloud/sharing' +import { subscribe, unsubscribe } from '@nextcloud/event-bus' import DropdownIcon from 'vue-material-design-icons/TriangleSmallDown.vue' import SharesMixin from '../mixins/SharesMixin.js' import ShareDetails from '../mixins/ShareDetails.js' -import ShareTypes from '../mixins/ShareTypes.js' +import NcActions from '@nextcloud/vue/components/NcActions' +import NcActionButton from '@nextcloud/vue/components/NcActionButton' +import IconEyeOutline from 'vue-material-design-icons/EyeOutline.vue' +import IconPencil from 'vue-material-design-icons/PencilOutline.vue' +import IconFileUpload from 'vue-material-design-icons/FileUpload.vue' +import IconTune from 'vue-material-design-icons/Tune.vue' import { BUNDLED_PERMISSIONS, ATOMIC_PERMISSIONS, } from '../lib/SharePermissionsToolBox.js' -import { createFocusTrap } from 'focus-trap' - export default { + name: 'SharingEntryQuickShareSelect', + components: { DropdownIcon, + NcActions, + NcActionButton, }, - mixins: [SharesMixin, ShareDetails, ShareTypes], + + mixins: [SharesMixin, ShareDetails], + props: { share: { type: Object, required: true, }, - toggle: { - type: Boolean, - default: false, - }, }, + + emits: ['open-sharing-details'], + data() { return { selectedOption: '', - showDropdown: this.toggle, - focusTrap: null, } }, + computed: { + ariaLabel() { + return t('files_sharing', 'Quick share options, the current selected is "{selectedOption}"', { selectedOption: this.selectedOption }) + }, canViewText() { return t('files_sharing', 'View only') }, @@ -72,7 +82,7 @@ export default { return t('files_sharing', 'Can edit') }, fileDropText() { - return t('files_sharing', 'File drop') + return t('files_sharing', 'File request') }, customPermissionsText() { return t('files_sharing', 'Custom permissions') @@ -91,18 +101,30 @@ export default { }, options() { - const options = [this.canViewText, this.canEditText] + const options = [{ + label: this.canViewText, + icon: IconEyeOutline, + }, { + label: this.canEditText, + icon: IconPencil, + }] if (this.supportsFileDrop) { - options.push(this.fileDropText) + options.push({ + label: this.fileDropText, + icon: IconFileUpload, + }) } - options.push(this.customPermissionsText) + options.push({ + label: this.customPermissionsText, + icon: IconTune, + }) return options }, supportsFileDrop() { if (this.isFolder && this.config.isPublicUploadEnabled) { const shareType = this.share.type ?? this.share.shareType - return [this.SHARE_TYPES.SHARE_TYPE_LINK, this.SHARE_TYPES.SHARE_TYPE_EMAIL].includes(shareType) + return [ShareType.Link, ShareType.Email].includes(shareType) } return false }, @@ -119,96 +141,33 @@ export default { return BUNDLED_PERMISSIONS.READ_ONLY } }, - dropdownId() { - // Generate a unique ID for ARIA attributes - return `dropdown-${Math.random().toString(36).substr(2, 9)}` - }, }, - watch: { - toggle(toggleValue) { - this.showDropdown = toggleValue - }, + + created() { + this.selectedOption = this.preSelectedOption }, mounted() { - this.initializeComponent() - window.addEventListener('click', this.handleClickOutside) + subscribe('update:share', (share) => { + if (share.id === this.share.id) { + this.share.permissions = share.permissions + this.selectedOption = this.preSelectedOption + } + }) }, - beforeDestroy() { - // Remove the global click event listener to prevent memory leaks - window.removeEventListener('click', this.handleClickOutside) + unmounted() { + unsubscribe('update:share') }, methods: { - toggleDropdown() { - this.showDropdown = !this.showDropdown - if (this.showDropdown) { - this.$nextTick(() => { - this.useFocusTrap() - }) - } else { - this.clearFocusTrap() - } - }, - closeDropdown() { - this.clearFocusTrap() - this.showDropdown = false - }, - selectOption(option) { - this.selectedOption = option - if (option === this.customPermissionsText) { + selectOption(optionLabel) { + this.selectedOption = optionLabel + if (optionLabel === this.customPermissionsText) { this.$emit('open-sharing-details') } else { this.share.permissions = this.dropDownPermissionValue this.queueUpdate('permissions') + // TODO: Add a focus method to NcActions or configurable returnFocus enabling to NcActionButton with closeAfterClick + this.$refs.quickShareActions.$refs.menuButton.$el.focus() } - this.showDropdown = false - }, - initializeComponent() { - this.selectedOption = this.preSelectedOption - }, - handleClickOutside(event) { - const dropdownContainer = this.$refs.quickShareDropdownContainer - - if (dropdownContainer && !dropdownContainer.contains(event.target)) { - this.showDropdown = false - } - }, - useFocusTrap() { - // Create global stack if undefined - // Use in with trapStack to avoid conflicting traps - Object.assign(window, { _nc_focus_trap: window._nc_focus_trap || [] }) - const dropdownElement = this.$refs.quickShareDropdown - this.focusTrap = createFocusTrap(dropdownElement, { - allowOutsideClick: true, - trapStack: window._nc_focus_trap, - }) - - this.focusTrap.activate() - }, - clearFocusTrap() { - this.focusTrap?.deactivate() - this.focusTrap = null - }, - shiftFocusForward() { - const currentElement = document.activeElement - let nextElement = currentElement.nextElementSibling - if (!nextElement) { - nextElement = this.$refs.quickShareDropdown.firstElementChild - } - nextElement.focus() - }, - shiftFocusBackward() { - const currentElement = document.activeElement - let previousElement = currentElement.previousElementSibling - if (!previousElement) { - previousElement = this.$refs.quickShareDropdown.lastElementChild - } - previousElement.focus() - }, - handleArrowUp() { - this.shiftFocusBackward() - }, - handleArrowDown() { - this.shiftFocusForward() }, }, @@ -217,65 +176,31 @@ export default { <style lang="scss" scoped> .share-select { - position: relative; - cursor: pointer; - - .trigger-text { - display: flex; - flex-direction: row; - align-items: center; - font-size: 12.5px; - gap: 2px; - color: var(--color-primary-element); - } - - .share-select-dropdown { - position: absolute; - display: flex; - flex-direction: column; - top: 100%; - left: 0; - background-color: var(--color-main-background); - border-radius: 8px; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); - border: 1px solid var(--color-border); - padding: 4px 0; - z-index: 1; - - .dropdown-item { - padding: 8px; - font-size: 12px; - background: none; - border: none; - border-radius: 0; - font: inherit; - cursor: pointer; - color: inherit; - outline: none; - width: 100%; - white-space: nowrap; - text-align: left; - - &:hover { - background-color: var(--color-background-dark); - } - - &.selected { - background-color: var(--color-background-dark); - } + display: block; + + // TODO: NcActions should have a slot for custom trigger button like NcPopover + // Overrider NcActionms button to make it small + :deep(.action-item__menutoggle) { + color: var(--color-primary-element) !important; + font-size: 12.5px !important; + height: auto !important; + min-height: auto !important; + + .button-vue__text { + font-weight: normal !important; } - } - /* Optional: Add a transition effect for smoother dropdown animation */ - .share-select-dropdown { - max-height: 0; - overflow: hidden; - transition: max-height 0.3s ease; - } + .button-vue__icon { + height: 24px !important; + min-height: 24px !important; + width: 24px !important; + min-width: 24px !important; + } - &.active .share-select-dropdown { - max-height: 200px; - /* Adjust the value to your desired height */ + .button-vue__wrapper { + // Emulate NcButton's alignment=center-reverse + flex-direction: row-reverse !important; + } } } </style> diff --git a/apps/files_sharing/src/components/SharingEntrySimple.vue b/apps/files_sharing/src/components/SharingEntrySimple.vue index 29464e88f34..a00333ba0ce 100644 --- a/apps/files_sharing/src/components/SharingEntrySimple.vue +++ b/apps/files_sharing/src/components/SharingEntrySimple.vue @@ -1,24 +1,7 @@ <!-- - - @copyright Copyright (c) 2019 John Molakvoæ <skjnldsv@protonmail.com> - - - - @author John Molakvoæ <skjnldsv@protonmail.com> - - - - @license GNU AGPL version 3 or any later version - - - - This program is free software: you can redistribute it and/or modify - - it under the terms of the GNU Affero General Public License as - - published by the Free Software Foundation, either version 3 of the - - License, or (at your option) any later version. - - - - This program is distributed in the hope that it will be useful, - - but WITHOUT ANY WARRANTY; without even the implied warranty of - - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - - GNU Affero General Public License for more details. - - - - You should have received a copy of the GNU Affero General Public License - - along with this program. If not, see <http://www.gnu.org/licenses/>. - - - --> + - SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <template> <li class="sharing-entry"> @@ -40,7 +23,7 @@ </template> <script> -import NcActions from '@nextcloud/vue/dist/Components/NcActions.js' +import NcActions from '@nextcloud/vue/components/NcActions' export default { name: 'SharingEntrySimple', @@ -87,7 +70,7 @@ export default { min-height: 44px; &__desc { padding: 8px; - padding-left: 10px; + padding-inline-start: 10px; line-height: 1.2em; position: relative; flex: 1 1; @@ -103,7 +86,7 @@ export default { max-width: inherit; } &__actions { - margin-left: auto !important; + margin-inline-start: auto !important; } } </style> diff --git a/apps/files_sharing/src/components/SharingInput.vue b/apps/files_sharing/src/components/SharingInput.vue index 1de28abef82..6fb33aba6b2 100644 --- a/apps/files_sharing/src/components/SharingInput.vue +++ b/apps/files_sharing/src/components/SharingInput.vue @@ -1,31 +1,17 @@ <!-- - - @copyright Copyright (c) 2019 John Molakvoæ <skjnldsv@protonmail.com> - - - - @author John Molakvoæ <skjnldsv@protonmail.com> - - - - @license GNU AGPL version 3 or any later version - - - - This program is free software: you can redistribute it and/or modify - - it under the terms of the GNU Affero General Public License as - - published by the Free Software Foundation, either version 3 of the - - License, or (at your option) any later version. - - - - This program is distributed in the hope that it will be useful, - - but WITHOUT ANY WARRANTY; without even the implied warranty of - - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - - GNU Affero General Public License for more details. - - - - You should have received a copy of the GNU Affero General Public License - - along with this program. If not, see <http://www.gnu.org/licenses/>. - - - --> + - SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <template> <div class="sharing-search"> - <label for="sharing-search-input">{{ t('files_sharing', 'Search for share recipients') }}</label> + <label class="hidden-visually" :for="shareInputId"> + {{ isExternal ? t('files_sharing', 'Enter external recipients') + : t('files_sharing', 'Search for internal recipients') }} + </label> <NcSelect ref="select" v-model="value" - input-id="sharing-search-input" + :input-id="shareInputId" class="sharing-search__input" :disabled="!canReshare" :loading="loading" @@ -34,10 +20,11 @@ :clear-search-on-blur="() => false" :user-select="true" :options="options" + :label-outside="true" @search="asyncFind" - @option:selected="openSharingDetails"> + @option:selected="onSelected"> <template #no-options="{ search }"> - {{ search ? noResultText : t('files_sharing', 'No recommendations. Start typing.') }} + {{ search ? noResultText : placeholder }} </template> </NcSelect> </div> @@ -49,14 +36,13 @@ import { getCurrentUser } from '@nextcloud/auth' import { getCapabilities } from '@nextcloud/capabilities' import axios from '@nextcloud/axios' import debounce from 'debounce' -import NcSelect from '@nextcloud/vue/dist/Components/NcSelect.js' +import NcSelect from '@nextcloud/vue/components/NcSelect' -import Config from '../services/ConfigService.js' -import GeneratePassword from '../utils/GeneratePassword.js' -import Share from '../models/Share.js' +import Config from '../services/ConfigService.ts' +import Share from '../models/Share.ts' import ShareRequests from '../mixins/ShareRequests.js' -import ShareTypes from '../mixins/ShareTypes.js' import ShareDetails from '../mixins/ShareDetails.js' +import { ShareType } from '@nextcloud/sharing' export default { name: 'SharingInput', @@ -65,7 +51,7 @@ export default { NcSelect, }, - mixins: [ShareTypes, ShareRequests, ShareDetails], + mixins: [ShareRequests, ShareDetails], props: { shares: { @@ -91,6 +77,20 @@ export default { type: Boolean, required: true, }, + isExternal: { + type: Boolean, + default: false, + }, + placeholder: { + type: String, + default: '', + }, + }, + + setup() { + return { + shareInputId: `share-input-${Math.random().toString(36).slice(2, 7)}`, + } }, data() { @@ -123,6 +123,10 @@ export default { if (!this.canReshare) { return t('files_sharing', 'Resharing is not allowed') } + if (this.placeholder) { + return this.placeholder + } + // We can always search with email addresses for users too if (!allowRemoteSharing) { return t('files_sharing', 'Name or email …') @@ -151,10 +155,18 @@ export default { }, mounted() { - this.getRecommendations() + if (!this.isExternal) { + // We can only recommend users, groups etc for internal shares + this.getRecommendations() + } }, methods: { + onSelected(option) { + this.value = null // Reset selected option + this.openSharingDetails(option) + }, + async asyncFind(query) { // save current query to check if we display // recommendations or search results @@ -180,20 +192,37 @@ export default { lookup = true } - const shareType = [ - this.SHARE_TYPES.SHARE_TYPE_USER, - this.SHARE_TYPES.SHARE_TYPE_GROUP, - this.SHARE_TYPES.SHARE_TYPE_REMOTE, - this.SHARE_TYPES.SHARE_TYPE_REMOTE_GROUP, - this.SHARE_TYPES.SHARE_TYPE_CIRCLE, - this.SHARE_TYPES.SHARE_TYPE_ROOM, - this.SHARE_TYPES.SHARE_TYPE_GUEST, - this.SHARE_TYPES.SHARE_TYPE_DECK, - this.SHARE_TYPES.SHARE_TYPE_SCIENCEMESH, - ] - - if (getCapabilities().files_sharing.public.enabled === true) { - shareType.push(this.SHARE_TYPES.SHARE_TYPE_EMAIL) + const remoteTypes = [ShareType.Remote, ShareType.RemoteGroup] + const shareType = [] + + const showFederatedAsInternal = this.config.showFederatedSharesAsInternal + || this.config.showFederatedSharesToTrustedServersAsInternal + + // For internal users, add remote types if config says to show them as internal + const shouldAddRemoteTypes = (!this.isExternal && showFederatedAsInternal) + // For external users, add them if config *doesn't* say to show them as internal + || (this.isExternal && !showFederatedAsInternal) + // Edge case: federated-to-trusted is a separate "add" trigger for external users + || (this.isExternal && this.config.showFederatedSharesToTrustedServersAsInternal) + + if (this.isExternal) { + if (getCapabilities().files_sharing.public.enabled === true) { + shareType.push(ShareType.Email) + } + } else { + shareType.push( + ShareType.User, + ShareType.Group, + ShareType.Team, + ShareType.Room, + ShareType.Guest, + ShareType.Deck, + ShareType.ScienceMesh, + ) + } + + if (shouldAddRemoteTypes) { + shareType.push(...remoteTypes) } let request = null @@ -213,13 +242,10 @@ export default { return } - const data = request.data.ocs.data - const exact = request.data.ocs.data.exact - data.exact = [] // removing exact from general results - + const { exact, ...data } = request.data.ocs.data // flatten array of arrays - const rawExactSuggestions = Object.values(exact).reduce((arr, elem) => arr.concat(elem), []) - const rawSuggestions = Object.values(data).reduce((arr, elem) => arr.concat(elem), []) + const rawExactSuggestions = Object.values(exact).flat() + const rawSuggestions = Object.values(data).flat() // remove invalid data and format to user-select layout const exactSuggestions = this.filterOutExistingShares(rawExactSuggestions) @@ -238,7 +264,7 @@ export default { lookupEntry.push({ id: 'global-lookup', isNoUser: true, - displayName: t('files_sharing', 'Search globally'), + displayName: t('files_sharing', 'Search everywhere'), lookup: true, }) } @@ -330,7 +356,7 @@ export default { return arr } try { - if (share.value.shareType === this.SHARE_TYPES.SHARE_TYPE_USER) { + if (share.value.shareType === ShareType.User) { // filter out current user if (share.value.shareWith === getCurrentUser().uid) { return arr @@ -343,7 +369,12 @@ export default { } // filter out existing mail shares - if (share.value.shareType === this.SHARE_TYPES.SHARE_TYPE_EMAIL) { + if (share.value.shareType === ShareType.Email) { + // When sharing internally, we don't want to suggest email addresses + // that the user previously created shares to + if (!this.isExternal) { + return arr + } const emails = this.linkShares.map(elem => elem.shareWith) if (emails.indexOf(share.value.shareWith.trim()) !== -1) { return arr @@ -381,42 +412,42 @@ export default { */ shareTypeToIcon(type) { switch (type) { - case this.SHARE_TYPES.SHARE_TYPE_GUEST: + case ShareType.Guest: // default is a user, other icons are here to differentiate // themselves from it, so let's not display the user icon - // case this.SHARE_TYPES.SHARE_TYPE_REMOTE: - // case this.SHARE_TYPES.SHARE_TYPE_USER: + // case ShareType.Remote: + // case ShareType.User: return { icon: 'icon-user', iconTitle: t('files_sharing', 'Guest'), } - case this.SHARE_TYPES.SHARE_TYPE_REMOTE_GROUP: - case this.SHARE_TYPES.SHARE_TYPE_GROUP: + case ShareType.RemoteGroup: + case ShareType.Group: return { icon: 'icon-group', iconTitle: t('files_sharing', 'Group'), } - case this.SHARE_TYPES.SHARE_TYPE_EMAIL: + case ShareType.Email: return { icon: 'icon-mail', iconTitle: t('files_sharing', 'Email'), } - case this.SHARE_TYPES.SHARE_TYPE_CIRCLE: + case ShareType.Team: return { - icon: 'icon-circle', - iconTitle: t('files_sharing', 'Circle'), + icon: 'icon-teams', + iconTitle: t('files_sharing', 'Team'), } - case this.SHARE_TYPES.SHARE_TYPE_ROOM: + case ShareType.Room: return { icon: 'icon-room', iconTitle: t('files_sharing', 'Talk conversation'), } - case this.SHARE_TYPES.SHARE_TYPE_DECK: + case ShareType.Deck: return { icon: 'icon-deck', iconTitle: t('files_sharing', 'Deck board'), } - case this.SHARE_TYPES.SHARE_TYPE_SCIENCEMESH: + case ShareType.Sciencemesh: return { icon: 'icon-sciencemesh', iconTitle: t('files_sharing', 'ScienceMesh'), @@ -433,105 +464,35 @@ export default { * @return {object} */ formatForMultiselect(result) { - let subtitle - if (result.value.shareType === this.SHARE_TYPES.SHARE_TYPE_USER && this.config.shouldAlwaysShowUnique) { - subtitle = result.shareWithDisplayNameUnique ?? '' - } else if ((result.value.shareType === this.SHARE_TYPES.SHARE_TYPE_REMOTE - || result.value.shareType === this.SHARE_TYPES.SHARE_TYPE_REMOTE_GROUP - ) && result.value.server) { - subtitle = t('files_sharing', 'on {server}', { server: result.value.server }) - } else if (result.value.shareType === this.SHARE_TYPES.SHARE_TYPE_EMAIL) { - subtitle = result.value.shareWith + let subname + let displayName = result.name || result.label + + if (result.value.shareType === ShareType.User && this.config.shouldAlwaysShowUnique) { + subname = result.shareWithDisplayNameUnique ?? '' + } else if (result.value.shareType === ShareType.Email) { + subname = result.value.shareWith + } else if (result.value.shareType === ShareType.Remote || result.value.shareType === ShareType.RemoteGroup) { + if (this.config.showFederatedSharesAsInternal) { + subname = result.extra?.email?.value ?? '' + displayName = result.extra?.name?.value ?? displayName + } else if (result.value.server) { + subname = t('files_sharing', 'on {server}', { server: result.value.server }) + } } else { - subtitle = result.shareWithDescription ?? '' + subname = result.shareWithDescription ?? '' } return { shareWith: result.value.shareWith, shareType: result.value.shareType, user: result.uuid || result.value.shareWith, - isNoUser: result.value.shareType !== this.SHARE_TYPES.SHARE_TYPE_USER, - displayName: result.name || result.label, - subtitle, + isNoUser: result.value.shareType !== ShareType.User, + displayName, + subname, shareWithDisplayNameUnique: result.shareWithDisplayNameUnique || '', ...this.shareTypeToIcon(result.value.shareType), } }, - - /** - * Process the new share request - * - * @param {object} value the multiselect option - */ - async addShare(value) { - // Clear the displayed selection - this.value = null - - if (value.lookup) { - await this.getSuggestions(this.query, true) - - this.$nextTick(() => { - // open the dropdown again - this.$refs.select.$children[0].open = true - }) - return true - } - - // handle externalResults from OCA.Sharing.ShareSearch - if (value.handler) { - const share = await value.handler(this) - this.$emit('add:share', new Share(share)) - return true - } - - this.loading = true - console.debug('Adding a new share from the input for', value) - try { - let password = null - - if (this.config.enforcePasswordForPublicLink - && value.shareType === this.SHARE_TYPES.SHARE_TYPE_EMAIL) { - password = await GeneratePassword() - } - - const path = (this.fileInfo.path + '/' + this.fileInfo.name).replace('//', '/') - const share = await this.createShare({ - path, - shareType: value.shareType, - shareWith: value.shareWith, - password, - permissions: this.fileInfo.sharePermissions & getCapabilities().files_sharing.default_permissions, - attributes: JSON.stringify(this.fileInfo.shareAttributes), - }) - - // If we had a password, we need to show it to the user as it was generated - if (password) { - share.newPassword = password - // Wait for the newly added share - const component = await new Promise(resolve => { - this.$emit('add:share', share, resolve) - }) - - // open the menu on the - // freshly created share component - component.open = true - } else { - // Else we just add it normally - this.$emit('add:share', share) - } - - await this.getRecommendations() - } catch (error) { - this.$nextTick(() => { - // open the dropdown again on error - this.$refs.select.$children[0].open = true - }) - this.query = value.shareWith - console.error('Error while adding new share', error) - } finally { - this.loading = false - } - }, }, } </script> |