Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(client): Decouple WebDAV accounts integration from client initialization #31553

Merged
merged 5 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions apps/meteor/app/models/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { RoomRoles } from './models/RoomRoles';
import { UserAndRoom } from './models/UserAndRoom';
import { UserRoles } from './models/UserRoles';
import { Users } from './models/Users';
import { WebdavAccounts } from './models/WebdavAccounts';

export {
Base,
Expand All @@ -30,7 +29,6 @@ export {
ChatPermissions,
CustomSounds,
EmojiCustom,
WebdavAccounts,
/** @deprecated */
Users,
/** @deprecated */
Expand Down
9 changes: 0 additions & 9 deletions apps/meteor/app/models/client/models/WebdavAccounts.ts

This file was deleted.

47 changes: 0 additions & 47 deletions apps/meteor/app/webdav/client/actionButton.ts

This file was deleted.

15 changes: 0 additions & 15 deletions apps/meteor/app/webdav/client/index.js

This file was deleted.

20 changes: 0 additions & 20 deletions apps/meteor/app/webdav/client/startup/sync.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { useAutoTranslate } from '../../../views/room/MessageList/hooks/useAutoT
import { useChat } from '../../../views/room/contexts/ChatContext';
import { useRoomToolbox } from '../../../views/room/contexts/RoomToolboxContext';
import MessageActionMenu from './MessageActionMenu';
import { useWebDAVMessageAction } from './useWebDAVMessageAction';

const getMessageContext = (message: IMessage, room: IRoom, context?: MessageActionContext): MessageActionContext => {
if (context) {
Expand Down Expand Up @@ -72,6 +73,9 @@ const MessageToolbar = ({

const { messageToolbox: hiddenActions } = useLayoutHiddenActions();

// TODO: move this to another place
useWebDAVMessageAction();

const actionsQueryResult = useQuery(['rooms', room._id, 'messages', message._id, 'actions'] as const, async () => {
const props = { message, room, user, subscription, settings: mapSettings, chat };

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useSetModal, useSetting } from '@rocket.chat/ui-contexts';
import React, { useEffect } from 'react';

import { MessageAction } from '../../../../app/ui-utils/client/lib/MessageAction';
import { getURL } from '../../../../app/utils/client';
import { useWebDAVAccountIntegrationsQuery } from '../../../hooks/webdav/useWebDAVAccountIntegrationsQuery';
import { messageArgs } from '../../../lib/utils/messageArgs';
import SaveToWebdavModal from '../../../views/room/webdav/SaveToWebdavModal';

export const useWebDAVMessageAction = () => {
const enabled = useSetting<boolean>('Webdav_Integration_Enabled', false);

const { data } = useWebDAVAccountIntegrationsQuery({ enabled });

const setModal = useSetModal();

useEffect(() => {
if (!enabled) {
return;
}

MessageAction.addButton({
id: 'webdav-upload',
icon: 'upload',
label: 'Save_To_Webdav',
condition: ({ message, subscription }) => {
return !!subscription && !!data?.length && !!message.file;
},
action(_, props) {
const { message = messageArgs(this).msg } = props;
const [attachment] = message.attachments || [];
const url = getURL(attachment.title_link as string, { full: true });

setModal(<SaveToWebdavModal data={{ attachment, url }} onClose={() => setModal(undefined)} />);
},
order: 100,
group: 'menu',
});

return () => {
MessageAction.removeButton('webdav-upload');
};
}, [data?.length, enabled, setModal]);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import type { IWebdavAccountIntegration } from '@rocket.chat/core-typings';
import { useUserId, useEndpoint, useStream } from '@rocket.chat/ui-contexts';
import type { UseQueryOptions } from '@tanstack/react-query';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useMemo } from 'react';

type UseWebDAVAccountIntegrationsQueryOptions = Omit<
UseQueryOptions<IWebdavAccountIntegration[], unknown, IWebdavAccountIntegration[], readonly ['webdav', 'account-integrations']>,
'queryKey' | 'queryFn'
>;

export const useWebDAVAccountIntegrationsQuery = ({ enabled = true, ...options }: UseWebDAVAccountIntegrationsQueryOptions = {}) => {
const uid = useUserId();

const queryKey = useMemo(() => ['webdav', 'account-integrations'] as const, []);

const getMyAccounts = useEndpoint('GET', '/v1/webdav.getMyAccounts');

const integrationsQuery = useQuery({
queryKey,
queryFn: async (): Promise<IWebdavAccountIntegration[]> => {
const { accounts } = await getMyAccounts();
return accounts;
},
enabled: !!uid && enabled,
staleTime: Infinity,
...options,
});

const queryClient = useQueryClient();

const subscribeToNotifyUser = useStream('notify-user');

useEffect(() => {
if (!uid || !enabled) {
return;
}

return subscribeToNotifyUser(`${uid}/webdav`, ({ type, account }) => {
switch (type) {
case 'changed':
queryClient.invalidateQueries(queryKey);
break;

case 'removed':
queryClient.setQueryData<IWebdavAccountIntegration[]>(queryKey, (old = []) => {
return old.filter((oldAccount) => oldAccount._id !== account._id);
});
break;
}
});
}, [enabled, queryClient, queryKey, uid, subscribeToNotifyUser]);

return integrationsQuery;
};
1 change: 0 additions & 1 deletion apps/meteor/client/importPackages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import '../app/slashcommands-open/client';
import '../app/slashcommands-topic/client';
import '../app/slashcommands-unarchiveroom/client';
import '../app/tokenpass/client';
import '../app/webdav/client';
import '../app/webrtc/client';
import '../app/wordpress/client';
import '../app/e2e/client';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,49 +1,54 @@
import type { IWebdavAccountIntegration } from '@rocket.chat/core-typings';
import type { SelectOption } from '@rocket.chat/fuselage';
import { SelectLegacy, Box, Button, Field, FieldLabel, FieldRow } from '@rocket.chat/fuselage';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import { useEndpoint, useToastMessageDispatch, useTranslation } from '@rocket.chat/ui-contexts';
import type { ReactElement } from 'react';
import { useEffectEvent } from '@rocket.chat/fuselage-hooks';
import { useToastMessageDispatch, useTranslation } from '@rocket.chat/ui-contexts';
import React, { useMemo } from 'react';
import { useForm, Controller } from 'react-hook-form';

import { WebdavAccounts } from '../../../../app/models/client';
import { Page, PageHeader, PageScrollableContentWithShadow } from '../../../components/Page';
import { useReactiveValue } from '../../../hooks/useReactiveValue';
import { useWebDAVAccountIntegrationsQuery } from '../../../hooks/webdav/useWebDAVAccountIntegrationsQuery';
import { getWebdavServerName } from '../../../lib/getWebdavServerName';
import { useRemoveWebDAVAccountIntegrationMutation } from './hooks/useRemoveWebDAVAccountIntegrationMutation';

const getWebdavAccounts = (): IWebdavAccountIntegration[] => WebdavAccounts.find().fetch();
const AccountIntegrationsPage = () => {
const { data: webdavAccountIntegrations } = useWebDAVAccountIntegrationsQuery();

const AccountIntegrationsPage = (): ReactElement => {
const t = useTranslation();
const { handleSubmit, control } = useForm();
const dispatchToastMessage = useToastMessageDispatch();
const accounts = useReactiveValue(getWebdavAccounts);
const removeWebdavAccount = useEndpoint('POST', '/v1/webdav.removeWebdavAccount');
const { handleSubmit, control } = useForm<{ accountSelected: string }>();

const options: SelectOption[] = useMemo(
() => webdavAccountIntegrations?.map(({ _id, ...current }) => [_id, getWebdavServerName(current)]) ?? [],
[webdavAccountIntegrations],
);

const options: SelectOption[] = useMemo(() => accounts?.map(({ _id, ...current }) => [_id, getWebdavServerName(current)]), [accounts]);
const dispatchToastMessage = useToastMessageDispatch();
const t = useTranslation();

const handleClickRemove = useMutableCallback(({ accountSelected }) => {
try {
removeWebdavAccount({ accountId: accountSelected });
const removeMutation = useRemoveWebDAVAccountIntegrationMutation({
onSuccess: () => {
dispatchToastMessage({ type: 'success', message: t('Webdav_account_removed') });
} catch (error) {
dispatchToastMessage({ type: 'error', message: error as Error });
}
},
onError: (error) => {
dispatchToastMessage({ type: 'error', message: error });
},
});

const handleSubmitForm = useEffectEvent(({ accountSelected }) => {
removeMutation.mutate({ accountSelected });
});

return (
<Page>
<PageHeader title={t('Integrations')} />
<PageScrollableContentWithShadow>
<Box maxWidth='x600' w='full' alignSelf='center'>
<Box is='form' maxWidth='x600' w='full' alignSelf='center' onSubmit={handleSubmit(handleSubmitForm)}>
<Field>
<FieldLabel>{t('WebDAV_Accounts')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='accountSelected'
render={({ field: { onChange, value, name, ref } }): ReactElement => (
rules={{ required: true }}
render={({ field: { onChange, value, name, ref } }) => (
<SelectLegacy
ref={ref}
name={name}
Expand All @@ -54,7 +59,7 @@ const AccountIntegrationsPage = (): ReactElement => {
/>
)}
/>
<Button danger onClick={handleSubmit(handleClickRemove)}>
<Button type='submit' danger>
{t('Remove')}
</Button>
</FieldRow>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import NotAuthorizedPage from '../../notAuthorized/NotAuthorizedPage';
import AccountIntegrationsPage from './AccountIntegrationsPage';

const AccountIntegrationsRoute = (): ReactElement => {
const webdavEnabled = useSetting('Webdav_Integration_Enabled');
const webdavEnabled = useSetting<boolean>('Webdav_Integration_Enabled', false);

if (!webdavEnabled) {
return <NotAuthorizedPage />;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useEndpoint } from '@rocket.chat/ui-contexts';
import type { UseMutationOptions } from '@tanstack/react-query';
import { useMutation } from '@tanstack/react-query';

type UseRemoveWebDAVAccountIntegrationMutationOptions = Omit<UseMutationOptions<void, unknown, { accountSelected: string }>, 'mutationFn'>;

export const useRemoveWebDAVAccountIntegrationMutation = (options?: UseRemoveWebDAVAccountIntegrationMutationOptions) => {
const removeWebdavAccount = useEndpoint('POST', '/v1/webdav.removeWebdavAccount');

return useMutation({
mutationFn: async ({ accountSelected }: { accountSelected: string }) => {
await removeWebdavAccount({ accountId: accountSelected });
},
...options,
});
};
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import type { IWebdavAccountIntegration } from '@rocket.chat/core-typings';
import { useTranslation, useSetting, useSetModal } from '@rocket.chat/ui-contexts';
import { useSetModal, useSetting } from '@rocket.chat/ui-contexts';
import React from 'react';
import { useTranslation } from 'react-i18next';

import { WebdavAccounts } from '../../../../../../../app/models/client';
import type { GenericMenuItemProps } from '../../../../../../components/GenericMenu/GenericMenuItem';
import { useReactiveValue } from '../../../../../../hooks/useReactiveValue';
import { useWebDAVAccountIntegrationsQuery } from '../../../../../../hooks/webdav/useWebDAVAccountIntegrationsQuery';
import { useChat } from '../../../../contexts/ChatContext';
import AddWebdavAccountModal from '../../../../webdav/AddWebdavAccountModal';
import WebdavFilePickerModal from '../../../../webdav/WebdavFilePickerModal';

const getWebdavAccounts = (): IWebdavAccountIntegration[] => WebdavAccounts.find().fetch();

export const useWebdavActions = (): GenericMenuItemProps[] => {
const t = useTranslation();
const setModal = useSetModal();
const webDavEnabled = useSetting('Webdav_Integration_Enabled');
const webDavAccounts = useReactiveValue(getWebdavAccounts);
const enabled = useSetting<boolean>('Webdav_Integration_Enabled', false);

const { isSuccess, data } = useWebDAVAccountIntegrationsQuery({ enabled });

const chat = useChat();

const { t } = useTranslation();
const setModal = useSetModal();
const handleAddWebDav = () => setModal(<AddWebdavAccountModal onClose={() => setModal(null)} onConfirm={() => setModal(null)} />);

const handleUpload = async (file: File, description?: string) =>
Expand All @@ -33,11 +33,11 @@ export const useWebdavActions = (): GenericMenuItemProps[] => {
id: 'webdav-add',
content: t('Add_Server'),
icon: 'cloud-plus',
disabled: !webDavEnabled,
disabled: !isSuccess,
onClick: handleAddWebDav,
},
...(webDavEnabled && webDavAccounts.length > 0
? webDavAccounts.map((account) => ({
...(isSuccess
? data.map((account) => ({
id: account._id,
content: account.name,
icon: 'cloud-plus' as const,
Expand Down
Loading
Loading