snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,170 @@
import type { IOutgoingIntegration, OutgoingIntegrationEvent, Serialized } from '@rocket.chat/core-typings';
import { Button, ButtonGroup, Tabs, TabsItem } from '@rocket.chat/fuselage';
import { GenericModal, Page, PageHeader, PageScrollableContentWithShadow, PageFooter } from '@rocket.chat/ui-client';
import { useSetModal, useTranslation, useRouter, useRouteParameter } from '@rocket.chat/ui-contexts';
import { useId, useCallback } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import OutgoingWebhookForm from './OutgoingWebhookForm';
import { triggerWordsToArray, triggerWordsToString } from '../helpers/triggerWords';
import { useCreateIntegration } from '../hooks/useCreateIntegration';
import { useDeleteIntegration } from '../hooks/useDeleteIntegration';
import { useUpdateIntegration } from '../hooks/useUpdateIntegration';
type EditOutgoingWebhookFormData = {
enabled: boolean;
impersonateUser: boolean;
event: OutgoingIntegrationEvent;
urls: string;
token: string;
triggerWords: string;
targetRoom: string;
channel: string;
username: string;
name: string;
alias: string;
avatar: string;
emoji: string;
scriptEnabled: boolean;
scriptEngine: 'isolated-vm';
script: string;
retryFailedCalls: boolean;
retryCount: number;
retryDelay: string;
triggerWordAnywhere: boolean;
runOnEdits: boolean;
};
const getInitialValue = (webhookData: Serialized<IOutgoingIntegration> | undefined, defaultToken: string): EditOutgoingWebhookFormData => ({
enabled: webhookData?.enabled ?? true,
impersonateUser: webhookData?.impersonateUser ?? false,
event: webhookData?.event ?? 'sendMessage',
urls: webhookData?.urls?.join('\n') ?? '',
token: webhookData?.token ?? defaultToken,
triggerWords: triggerWordsToString(webhookData?.triggerWords) ?? '',
targetRoom: webhookData?.targetRoom ?? '',
channel: webhookData?.channel.join(', ') ?? '',
username: webhookData?.username ?? '',
name: webhookData?.name ?? '',
alias: webhookData?.alias ?? '',
avatar: webhookData?.avatar ?? '',
emoji: webhookData?.emoji ?? '',
scriptEnabled: webhookData?.scriptEnabled ?? false,
scriptEngine: webhookData?.scriptEngine ?? 'isolated-vm',
script: webhookData?.script ?? '',
retryFailedCalls: webhookData?.retryFailedCalls ?? true,
retryCount: webhookData?.retryCount ?? 6,
retryDelay: webhookData?.retryDelay ?? 'powers-of-ten',
triggerWordAnywhere: webhookData?.triggerWordAnywhere ?? false,
runOnEdits: webhookData?.runOnEdits ?? true,
});
const OUTGOING_TYPE = 'webhook-outgoing';
export type EditOutgoingWebhookProps = {
webhookData?: Serialized<IOutgoingIntegration>;
};
const EditOutgoingWebhook = ({ webhookData }: EditOutgoingWebhookProps) => {
const t = useTranslation();
const setModal = useSetModal();
const router = useRouter();
const tab = useRouteParameter('type');
const defaultToken = useId();
const methods = useForm<EditOutgoingWebhookFormData>({ mode: 'onBlur', values: getInitialValue(webhookData, defaultToken) });
const {
reset,
handleSubmit,
formState: { isDirty },
watch,
} = methods;
const deleteIntegration = useDeleteIntegration(OUTGOING_TYPE);
const createIntegration = useCreateIntegration(OUTGOING_TYPE);
const updateIntegration = useUpdateIntegration(OUTGOING_TYPE);
const handleDeleteIntegration = useCallback(() => {
const onDelete = async () => {
deleteIntegration.mutate({ type: OUTGOING_TYPE, integrationId: webhookData?._id });
};
setModal(
<GenericModal variant='danger' onConfirm={onDelete} onCancel={() => setModal(null)} confirmText={t('Delete')}>
{t('Integration_Delete_Warning')}
</GenericModal>,
);
}, [webhookData?._id, deleteIntegration, setModal, t]);
const { urls, triggerWords } = watch();
const handleSave = useCallback(
async (formValues: EditOutgoingWebhookFormData) => {
if (webhookData?._id) {
return updateIntegration.mutate({
type: OUTGOING_TYPE,
integrationId: webhookData?._id,
...formValues,
triggerWords: triggerWordsToArray(triggerWords),
urls: urls.split('\n'),
});
}
return createIntegration.mutate({
type: OUTGOING_TYPE,
...formValues,
triggerWords: triggerWordsToArray(triggerWords),
urls: urls.split('\n'),
});
},
[webhookData?._id, createIntegration, updateIntegration, triggerWords, urls],
);
const formId = useId();
return (
<Page flexDirection='column'>
<PageHeader title={t('Integration_Outgoing_WebHook')} onClickBack={() => router.navigate('/admin/integrations/webhook-outgoing')}>
<ButtonGroup>
{webhookData?._id && (
<Button onClick={() => router.navigate(`/admin/integrations/history/outgoing/${webhookData._id}`)}>{t('History')}</Button>
)}
{webhookData?._id && (
<Button danger onClick={handleDeleteIntegration}>
{t('Delete')}
</Button>
)}
</ButtonGroup>
</PageHeader>
{!webhookData?._id && (
<Tabs>
<TabsItem selected={tab === 'incoming'} onClick={() => router.navigate('/admin/integrations/new/incoming')}>
{t('Incoming')}
</TabsItem>
<TabsItem selected={tab === 'outgoing'} onClick={() => router.navigate('/admin/integrations/new/outgoing')}>
{t('Outgoing')}
</TabsItem>
</Tabs>
)}
<PageScrollableContentWithShadow is='form' id={formId} onSubmit={handleSubmit(handleSave)}>
<FormProvider {...methods}>
<OutgoingWebhookForm />
</FormProvider>
</PageScrollableContentWithShadow>
<PageFooter isDirty={isDirty}>
<ButtonGroup>
<Button type='reset' onClick={() => reset()}>
{t('Cancel')}
</Button>
<Button form={formId} primary type='submit'>
{t('Save')}
</Button>
</ButtonGroup>
</PageFooter>
</Page>
);
};
export default EditOutgoingWebhook;

View File

@@ -0,0 +1,527 @@
import type { IOutgoingIntegration } from '@rocket.chat/core-typings';
import type { SelectOption } from '@rocket.chat/fuselage';
import {
FieldError,
AccordionItem,
FieldHint,
FieldLabel,
FieldRow,
Field,
TextInput,
Box,
ToggleSwitch,
Icon,
TextAreaInput,
FieldGroup,
Select,
Accordion,
NumberInput,
} from '@rocket.chat/fuselage';
import DOMPurify from 'dompurify';
import { useId, useMemo } from 'react';
import { useFormContext, Controller } from 'react-hook-form';
import { Trans, useTranslation } from 'react-i18next';
import { outgoingEvents } from '../../../../../app/integrations/lib/outgoingEvents';
import { useHighlightedCode } from '../../../../hooks/useHighlightedCode';
import { useExampleData } from '../hooks/useExampleIncomingData';
type EditOutgoingWebhookPayload = Pick<
IOutgoingIntegration,
| 'enabled'
| 'impersonateUser'
| 'event'
| 'urls'
| 'token'
| 'triggerWords'
| 'targetRoom'
| 'channel'
| 'username'
| 'name'
| 'alias'
| 'avatar'
| 'emoji'
| 'scriptEnabled'
| 'scriptEngine'
| 'script'
| 'retryFailedCalls'
| 'retryCount'
| 'retryDelay'
| 'triggerWordAnywhere'
| 'runOnEdits'
>;
const OutgoingWebhookForm = () => {
const { t } = useTranslation();
const {
control,
watch,
formState: { errors },
} = useFormContext<EditOutgoingWebhookPayload>();
const { event, alias, emoji, avatar } = watch();
const retryDelayOptions: SelectOption[] = useMemo(
() => [
['powers-of-ten', t('powers-of-ten')],
['powers-of-two', t('powers-of-two')],
['increments-of-two', t('increments-of-two')],
],
[t],
);
const eventOptions: SelectOption[] = useMemo(() => Object.entries(outgoingEvents).map(([key, val]) => [key, t(val.label)]), [t]);
const scriptEngineOptions: SelectOption[] = useMemo(() => [['isolated-vm', t('Script_Engine_isolated_vm')]], [t]);
const showChannel = useMemo(() => outgoingEvents[event].use.channel, [event]);
const showTriggerWords = useMemo(() => outgoingEvents[event].use.triggerWords, [event]);
const showTargetRoom = useMemo(() => outgoingEvents[event].use.targetRoom, [event]);
const additionalFields = useMemo(
() => ({
...(alias && { alias }),
...(emoji && { emoji }),
...(avatar && { avatar }),
}),
[alias, avatar, emoji],
);
const [exampleData] = useExampleData({
additionalFields,
url: '',
});
const hilightedExampleJson = useHighlightedCode('json', JSON.stringify(exampleData, null, 2));
const eventField = useId();
const enabledField = useId();
const nameField = useId();
const channelField = useId();
const triggerWordsField = useId();
const targetRoomField = useId();
const urlsField = useId();
const impersonateUserField = useId();
const usernameField = useId();
const aliasField = useId();
const avatarField = useId();
const emojiField = useId();
const tokenField = useId();
const scriptEnabledField = useId();
const scriptEngineField = useId();
const scriptField = useId();
const retryFailedCallsField = useId();
const retryCountField = useId();
const retryDelayField = useId();
const triggerWordAnywhereField = useId();
const runOnEditsField = useId();
return (
<Box maxWidth='x600' alignSelf='center' width='full'>
<Accordion>
<AccordionItem defaultExpanded title={t('Settings')}>
<FieldGroup>
<Field>
<FieldLabel htmlFor={eventField}>{t('Event_Trigger')}</FieldLabel>
<FieldRow>
<Controller
name='event'
control={control}
render={({ field }) => (
<Select id={eventField} {...field} options={eventOptions} aria-description={`${eventField}-hint`} />
)}
/>
</FieldRow>
<FieldHint id={`${eventField}-hint`}>{t('Event_Trigger_Description')}</FieldHint>
</Field>
<Field>
<FieldRow>
<FieldLabel htmlFor={enabledField}>{t('Enabled')}</FieldLabel>
<Controller
name='enabled'
control={control}
render={({ field: { value, ...field } }) => <ToggleSwitch id={enabledField} {...field} checked={value} />}
/>
</FieldRow>
</Field>
<Field>
<FieldLabel htmlFor={nameField}>{t('Name')}</FieldLabel>
<FieldRow>
<Controller
name='name'
control={control}
render={({ field }) => <TextInput id={nameField} {...field} aria-describedby={`${nameField}-hint`} />}
/>
</FieldRow>
<FieldHint id={`${nameField}-hint`}>{t('You_should_name_it_to_easily_manage_your_integrations')}</FieldHint>
</Field>
{showChannel && (
<Field>
<FieldLabel htmlFor={channelField}>{t('Channel')}</FieldLabel>
<FieldRow>
<Controller
name='channel'
control={control}
render={({ field }) => (
<TextInput
id={channelField}
{...field}
endAddon={<Icon name='at' size='x20' />}
aria-describedby={`${channelField}-hint-1 ${channelField}-hint-2 ${channelField}-hint-3`}
/>
)}
/>
</FieldRow>
<FieldHint id={`${channelField}-hint-1`}>{t('Channel_to_listen_on')}</FieldHint>
<FieldHint id={`${channelField}-hint-2`}>
<Trans i18nKey='Start_with_s_for_user_or_s_for_channel_Eg_s_or_s' components={{ code: <code className='inline' /> }} />
</FieldHint>
<FieldHint id={`${channelField}-hint-3`}>
<Trans i18nKey='Integrations_for_all_channels' />
</FieldHint>
</Field>
)}
{showTriggerWords && (
<Field>
<FieldLabel htmlFor={triggerWordsField}>{t('Trigger_Words')}</FieldLabel>
<FieldRow>
<Controller
name='triggerWords'
control={control}
render={({ field }) => (
<TextInput
id={triggerWordsField}
{...field}
aria-describedby={`${triggerWordsField}-hint-1 ${triggerWordsField}-hint-2`}
/>
)}
/>
</FieldRow>
<FieldHint id={`${triggerWordsField}-hint-1`}>
{t('When_a_line_starts_with_one_of_there_words_post_to_the_URLs_below')}
</FieldHint>
<FieldHint id={`${triggerWordsField}-hint-2`}>{t('Separate_multiple_words_with_commas')}</FieldHint>
</Field>
)}
{showTargetRoom && (
<Field>
<FieldLabel htmlFor={targetRoomField}>{t('TargetRoom')}</FieldLabel>
<FieldRow>
<Controller
name='targetRoom'
control={control}
render={({ field }) => (
<TextInput id={targetRoomField} {...field} aria-describedby={`${targetRoomField}-hint-1 ${targetRoomField}-hint-2`} />
)}
/>
</FieldRow>
<FieldHint id={`${targetRoomField}-hint-1`}>{t('TargetRoom_Description')}</FieldHint>
<FieldHint id={`${targetRoomField}-hint-2`}>
<Trans i18nKey='Start_with_s_for_user_or_s_for_channel_Eg_s_or_s' components={{ code: <code className='inline' /> }} />
</FieldHint>
</Field>
)}
<Field>
<FieldLabel htmlFor={urlsField} required>
{t('URLs')}
</FieldLabel>
<FieldRow>
<Controller
name='urls'
control={control}
rules={{ required: t('Required_field', { field: t('URLs') }) }}
render={({ field }) => (
<TextAreaInput
id={urlsField}
{...field}
rows={10}
endAddon={<Icon name='permalink' size='x20' />}
aria-describedby={`${urlsField}-error`}
aria-required={true}
aria-invalid={Boolean(errors?.urls)}
/>
)}
/>
</FieldRow>
{errors?.urls && (
<FieldError aria-live='assertive' id={`${urlsField}-error`}>
{errors?.urls.message}
</FieldError>
)}
</Field>
<Field>
<FieldRow>
<FieldLabel htmlFor={impersonateUserField}>{t('Impersonate_user')}</FieldLabel>
<Controller
name='impersonateUser'
control={control}
render={({ field: { value, ...field } }) => <ToggleSwitch id={impersonateUserField} {...field} checked={value} />}
/>
</FieldRow>
</Field>
<Field>
<FieldLabel htmlFor={usernameField} required>
{t('Post_as')}
</FieldLabel>
<FieldRow>
<Controller
name='username'
control={control}
rules={{ required: t('Required_field', { field: t('Post_as') }) }}
render={({ field }) => (
<TextInput
id={usernameField}
{...field}
endAddon={<Icon name='user' size='x20' />}
aria-describedby={`${usernameField}-hint-1 ${usernameField}-hint-2 ${usernameField}-error`}
aria-required={true}
aria-invalid={Boolean(errors?.username)}
/>
)}
/>
</FieldRow>
<FieldHint id={`${usernameField}-hint-1`}>{t('Choose_the_username_that_this_integration_will_post_as')}</FieldHint>
<FieldHint id={`${usernameField}-hint-2`}>{t('Should_exists_a_user_with_this_username')}</FieldHint>
{errors?.username && (
<FieldError aria-live='assertive' id={`${usernameField}-error`}>
{errors?.username.message}
</FieldError>
)}
</Field>
<Field>
<FieldLabel htmlFor={aliasField}>{t('Alias')}</FieldLabel>
<FieldRow>
<Controller
name='alias'
control={control}
render={({ field }) => (
<TextInput
id={aliasField}
{...field}
endAddon={<Icon name='edit' size='x20' />}
aria-describedby={`${aliasField}-hint`}
/>
)}
/>
</FieldRow>
<FieldHint id={`${aliasField}-hint`}>{t('Choose_the_alias_that_will_appear_before_the_username_in_messages')}</FieldHint>
</Field>
<Field>
<FieldLabel htmlFor={avatarField}>{t('Avatar_URL')}</FieldLabel>
<FieldRow>
<Controller
name='avatar'
control={control}
render={({ field }) => (
<TextInput
id={avatarField}
{...field}
endAddon={
<Icon
name='user-rounded'
size='x20'
alignSelf='center'
aria-describedby={`${avatarField}-hint-1 ${avatarField}-hint-2`}
/>
}
/>
)}
/>
</FieldRow>
<FieldHint id={`${avatarField}-hint-1`}>{t('You_can_change_a_different_avatar_too')}</FieldHint>
<FieldHint id={`${avatarField}-hint-2`}>{t('Should_be_a_URL_of_an_image')}</FieldHint>
</Field>
<Field>
<FieldLabel htmlFor={emojiField}>{t('Emoji')}</FieldLabel>
<FieldRow>
<Controller
name='emoji'
control={control}
render={({ field }) => (
<TextInput
id={emojiField}
{...field}
endAddon={
<Icon name='emoji' size='x20' alignSelf='center' aria-describedby={`${emojiField}-hint-1 ${emojiField}-hint-2`} />
}
/>
)}
/>
</FieldRow>
<FieldHint id={`${emojiField}-hint-1`}>{t('You_can_use_an_emoji_as_avatar')}</FieldHint>
<FieldHint id={`${emojiField}-hint-2`}>
<Trans i18nKey='Example_s' values={{ value: ':ghost:' }} components={{ code: <code className='inline' /> }} />
</FieldHint>
</Field>
<Field>
<FieldLabel htmlFor={tokenField} required>
{t('Token')}
</FieldLabel>
<FieldRow>
<Controller
name='token'
control={control}
rules={{ required: t('Required_field', { field: t('Token') }) }}
render={({ field }) => (
<TextInput
id={tokenField}
{...field}
endAddon={<Icon name='key' size='x20' />}
aria-describedby={`${tokenField}-error`}
aria-invalid={Boolean(errors?.token)}
aria-required={true}
/>
)}
/>
</FieldRow>
{errors?.token && (
<FieldError aria-live='assertive' id={`${tokenField}-error`}>
{errors?.token.message}
</FieldError>
)}
</Field>
<Field>
<FieldRow>
<FieldLabel htmlFor={scriptEnabledField}>{t('Script_Enabled')}</FieldLabel>
<Controller
name='scriptEnabled'
control={control}
render={({ field: { value, ...field } }) => <ToggleSwitch id={scriptEnabledField} {...field} checked={value} />}
/>
</FieldRow>
</Field>
<Field>
<FieldLabel htmlFor={scriptEngineField}>{t('Script_Engine')}</FieldLabel>
<FieldRow>
<Controller
name='scriptEngine'
control={control}
render={({ field }) => (
<Select
id={scriptEngineField}
{...field}
options={scriptEngineOptions}
aria-describedby={`${scriptEngineField}-hint`}
/>
)}
/>
</FieldRow>
<FieldHint id={`${scriptEngineField}-hint`}>{t('Script_Engine_Description')}</FieldHint>
</Field>
<Field>
<FieldLabel htmlFor={scriptField}>{t('Script')}</FieldLabel>
<FieldRow>
<Controller
name='script'
control={control}
render={({ field }) => (
<TextAreaInput id={scriptField} rows={10} {...field} endAddon={<Icon name='code' size='x20' alignSelf='center' />} />
)}
/>
</FieldRow>
</Field>
<Field>
<FieldLabel>{t('Responding')}</FieldLabel>
<FieldHint>{t('Response_description_pre')}</FieldHint>
<FieldRow>
<Box fontScale='p2' withRichContent flexGrow={1}>
<pre>
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(hilightedExampleJson) }}></code>
</pre>
</Box>
</FieldRow>
<FieldHint>{t('Response_description_post')}</FieldHint>
</Field>
</FieldGroup>
</AccordionItem>
<AccordionItem title={t('Integration_Advanced_Settings')}>
<FieldGroup>
<Field>
<FieldRow>
<FieldLabel htmlFor={retryFailedCallsField}>{t('Integration_Retry_Failed_Url_Calls')}</FieldLabel>
<Controller
name='retryFailedCalls'
control={control}
render={({ field: { value, ...field } }) => (
<ToggleSwitch
id={retryFailedCallsField}
{...field}
checked={value}
aria-describedby={`${retryFailedCallsField}-hint`}
/>
)}
/>
</FieldRow>
<FieldHint id={`${retryFailedCallsField}-hint`}>{t('Integration_Retry_Failed_Url_Calls_Description')}</FieldHint>
</Field>
<Field>
<FieldLabel htmlFor={retryCountField}>{t('Retry_Count')}</FieldLabel>
<FieldRow>
<Controller
name='retryCount'
control={control}
render={({ field }) => (
<NumberInput {...field} id={retryCountField} min='0' step='1' aria-describedby={`${retryCountField}-hint`} />
)}
/>
</FieldRow>
<FieldHint id={`${retryCountField}-hint`}>{t('Integration_Retry_Count_Description')}</FieldHint>
</Field>
<Field>
<FieldLabel htmlFor={retryDelayField}>{t('Integration_Retry_Delay')}</FieldLabel>
<FieldRow>
<Controller
name='retryDelay'
control={control}
render={({ field }) => (
<Select id={retryDelayField} {...field} options={retryDelayOptions} aria-describedby={`${retryDelayField}-hint`} />
)}
/>
</FieldRow>
<FieldHint id={`${retryDelayField}-hint`}>
<Trans i18nKey='Integration_Retry_Delay_Description' components={{ code: <code className='inline' /> }} />
</FieldHint>
</Field>
{event === 'sendMessage' && (
<FieldGroup>
<Field>
<FieldRow>
<FieldLabel htmlFor={triggerWordAnywhereField}>{t('Integration_Word_Trigger_Placement')}</FieldLabel>
<Controller
name='triggerWordAnywhere'
control={control}
render={({ field: { value, ...field } }) => (
<ToggleSwitch
id={triggerWordAnywhereField}
{...field}
checked={value}
aria-describedby={`${triggerWordAnywhereField}-hint`}
/>
)}
/>
</FieldRow>
<FieldHint id={`${triggerWordAnywhereField}-hint`}>{t('Integration_Word_Trigger_Placement_Description')}</FieldHint>
</Field>
<Field>
<FieldRow>
<FieldLabel htmlFor={runOnEditsField}>{t('Integration_Run_When_Message_Is_Edited')}</FieldLabel>
<Controller
name='runOnEdits'
control={control}
render={({ field: { value, ...field } }) => (
<ToggleSwitch id={runOnEditsField} {...field} checked={value} aria-describedby={`${runOnEditsField}-hint`} />
)}
/>
</FieldRow>
<FieldHint id={`${runOnEditsField}-hint`}>{t('Integration_Run_When_Message_Is_Edited_Description')}</FieldHint>
</Field>
</FieldGroup>
)}
</FieldGroup>
</AccordionItem>
</Accordion>
</Box>
);
};
export default OutgoingWebhookForm;

View File

@@ -0,0 +1,40 @@
import type { IIntegrationHistory, Serialized } from '@rocket.chat/core-typings';
import { Skeleton, Box, Accordion } from '@rocket.chat/fuselage';
import { useTranslation } from 'react-i18next';
import HistoryItem from './HistoryItem';
export type HistoryContentProps = { data: Serialized<IIntegrationHistory>[]; isLoading: boolean };
const HistoryContent = ({ data, isLoading }: HistoryContentProps) => {
const { t } = useTranslation();
if (isLoading) {
return (
<Box width='full' paddingBlock={24}>
<Skeleton marginBlockEnd={4} />
<Skeleton marginBlockEnd={8} />
<Skeleton marginBlockEnd={4} />
<Skeleton marginBlockEnd={8} />
<Skeleton marginBlockEnd={4} />
<Skeleton marginBlockEnd={8} />
</Box>
);
}
if (data.length < 1) {
return <Box marginBlockStart={16}>{t('Integration_Outgoing_WebHook_No_History')}</Box>;
}
return (
<Box display='flex' alignItems='center' flexDirection='column'>
<Accordion width='full' maxWidth='x600' alignSelf='center' key='content'>
{data.map((current) => (
<HistoryItem data={current} key={current._id} />
))}
</Accordion>
</Box>
);
};
export default HistoryContent;

View File

@@ -0,0 +1,210 @@
import type { IIntegrationHistory, Serialized } from '@rocket.chat/core-typings';
import { Button, Icon, Box, AccordionItem, Field, FieldGroup, FieldLabel, FieldRow } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { useEndpoint } from '@rocket.chat/ui-contexts';
import DOMPurify from 'dompurify';
import type { MouseEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { outgoingEvents } from '../../../../../../app/integrations/lib/outgoingEvents';
import { useFormatDateAndTime } from '../../../../../hooks/useFormatDateAndTime';
import { useHighlightedCode } from '../../../../../hooks/useHighlightedCode';
export type HistoryItemProps = { data: Serialized<IIntegrationHistory> };
const HistoryItem = ({ data }: HistoryItemProps) => {
const { t } = useTranslation();
const replayOutgoingIntegration = useEndpoint('POST', '/v1/integrations.replayOutgoing');
const {
_id,
_createdAt,
_updatedAt,
httpResult,
event,
step,
httpCallData,
data: dataSentToTrigger,
prepareSentMessage,
processSentMessage,
url,
httpError,
errorStack,
error,
integration: { _id: integrationId },
} = data;
const createdAt = typeof _createdAt === 'string' ? _createdAt : (_createdAt as Date).toISOString();
const updatedAt = typeof _updatedAt === 'string' ? _updatedAt : (_updatedAt as Date).toISOString();
const handleClickReplay = useStableCallback((e: MouseEvent) => {
e.stopPropagation();
replayOutgoingIntegration({ integrationId, historyId: _id });
});
const formatDateAndTime = useFormatDateAndTime();
const dataSentToTriggerCode = useHighlightedCode('json', JSON.stringify(dataSentToTrigger || '', null, 2));
const prepareSentMessageCode = useHighlightedCode('json', JSON.stringify(prepareSentMessage || '', null, 2));
const processSentMessageCode = useHighlightedCode('json', JSON.stringify(processSentMessage || '', null, 2));
const httpCallDataCode = useHighlightedCode('json', JSON.stringify(httpCallData || '', null, 2));
const httpErrorCode = useHighlightedCode('json', JSON.stringify(httpError || '', null, 2));
const httpResultCode = useHighlightedCode('json', JSON.stringify(httpResult || '', null, 2));
const errorStackCode = useHighlightedCode('json', JSON.stringify(errorStack || '', null, 2));
return (
<AccordionItem
title={
<Box display='inline-flex' width='full' flexDirection='row' justifyContent='space-between'>
<Box display='flex' flexDirection='row' alignItems='center'>
<Icon name='info-circled' size='x16' marginInlineEnd={4} />
{formatDateAndTime(_createdAt)}
</Box>
<Button secondary onClick={handleClickReplay}>
{t('Replay')}
</Button>
</Box>
}
>
<FieldGroup>
<Field>
<FieldLabel>{t('Status')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<code>{error ? t('Failure') : t('Success')}</code>
</Box>
</FieldRow>
</Field>
<Field>
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Time_Triggered')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<code>{createdAt}</code>
</Box>
</FieldRow>
</Field>
<Field>
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Time_Ended_Or_Error')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<code>{updatedAt}</code>
</Box>
</FieldRow>
</Field>
<Field>
<FieldLabel>{t('Event_Trigger')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<code>{t(outgoingEvents[event].label)}</code>
</Box>
</FieldRow>
</Field>
<Field>
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Trigger_Step')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<code>{step}</code>
</Box>
</FieldRow>
</Field>
{dataSentToTrigger && (
<Field>
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Data_Passed_To_Trigger')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<pre>
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(dataSentToTriggerCode) }}></code>
</pre>
</Box>
</FieldRow>
</Field>
)}
{prepareSentMessage && (
<Field>
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Messages_Sent_From_Prepare_Script')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<pre>
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(prepareSentMessageCode) }}></code>
</pre>
</Box>
</FieldRow>
</Field>
)}
{processSentMessage && (
<Field>
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Messages_Sent_From_Process_Script')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<pre>
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(processSentMessageCode) }}></code>
</pre>
</Box>
</FieldRow>
</Field>
)}
{url && (
<Field>
<FieldLabel>{t('URL')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<code>{url}</code>
</Box>
</FieldRow>
</Field>
)}
{httpCallData && (
<Field>
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Data_Passed_To_URL')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<pre>
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(httpCallDataCode) }}></code>
</pre>
</Box>
</FieldRow>
</Field>
)}
{httpError && (
<Field>
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Http_Response_Error')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<pre>
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(httpErrorCode) }}></code>
</pre>
</Box>
</FieldRow>
</Field>
)}
{httpResult && (
<Field>
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Http_Response')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<pre>
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(httpResultCode) }}></code>
</pre>
</Box>
</FieldRow>
</Field>
)}
{errorStack && (
<Field>
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Error_Stacktrace')}</FieldLabel>
<FieldRow>
<Box withRichContent width='full'>
<pre>
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(errorStackCode) }}></code>
</pre>
</Box>
</FieldRow>
</Field>
)}
</FieldGroup>
</AccordionItem>
);
};
export default HistoryItem;

View File

@@ -0,0 +1,133 @@
import { Button, ButtonGroup, Pagination } from '@rocket.chat/fuselage';
import { CustomScrollbars, usePagination, Page, PageHeader, PageContent } from '@rocket.chat/ui-client';
import { useToastMessageDispatch, useRouteParameter, useTranslation, useEndpoint, useRouter } from '@rocket.chat/ui-contexts';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { ComponentProps } from 'react';
import { useMemo, useState, useEffect } from 'react';
import HistoryContent from './HistoryContent';
import { sdk } from '../../../../../lib/SDKClient';
const OutgoingWebhookHistoryPage = (props: ComponentProps<typeof Page>) => {
const dispatchToastMessage = useToastMessageDispatch();
const t = useTranslation();
const router = useRouter();
const { itemsPerPage, setItemsPerPage, current, setCurrent, itemsPerPageLabel, showingResultsLabel } = usePagination();
const [mounted, setMounted] = useState(false);
const [total, setTotal] = useState(0);
const clearIntegrationHistory = useEndpoint('POST', '/v1/integrations.clearHistory');
const id = useRouteParameter('id') as string;
const query = useMemo(
() => ({
id,
count: itemsPerPage,
offset: current,
}),
[id, itemsPerPage, current],
);
const fetchHistory = useEndpoint('GET', '/v1/integrations.history');
const queryKey = useMemo(() => ['integrations/history', id, itemsPerPage, current], [id, itemsPerPage, current]);
const queryClient = useQueryClient();
type HistoryData = Awaited<ReturnType<typeof fetchHistory>>;
const { data, isPending, refetch } = useQuery({
queryKey,
queryFn: async () => {
const result = fetchHistory(query);
setMounted(true);
return result;
},
gcTime: 99999,
staleTime: 99999,
});
const handleClearHistory = async (): Promise<void> => {
try {
await clearIntegrationHistory({ integrationId: id });
dispatchToastMessage({ type: 'success', message: t('Integration_History_Cleared') });
refetch();
setMounted(false);
} catch (e) {
dispatchToastMessage({ type: 'error', message: e });
}
};
useEffect(() => {
if (mounted) {
return sdk.stream('integrationHistory', [id], (integration) => {
if (integration.type === 'inserted') {
setTotal((total) => total + 1);
queryClient.setQueryData<HistoryData>(queryKey, (oldData): HistoryData | undefined => {
if (!oldData || !integration.data) {
return;
}
return {
...oldData,
history: [integration.data as unknown as HistoryData['history'][number]].concat(oldData.history),
total: oldData.total + 1,
};
});
}
if (integration.type === 'updated') {
queryClient.setQueryData<HistoryData>(queryKey, (oldData): HistoryData | undefined => {
if (!oldData) {
return;
}
const index = oldData.history.findIndex(({ _id }) => _id === id);
if (index === -1) {
return;
}
Object.assign(oldData.history[index], integration.diff);
return { ...oldData };
});
return;
}
if (integration.type === 'removed') {
refetch();
}
}).stop;
}
}, [id, mounted, queryClient, queryKey, refetch]);
return (
<Page flexDirection='column' {...props}>
<PageHeader
title={t('Integration_Outgoing_WebHook_History')}
onClickBack={() => router.navigate(`/admin/integrations/edit/outgoing/${id}`)}
>
<ButtonGroup>
<Button icon='trash' danger onClick={handleClearHistory} disabled={total === 0}>
{t('clear_history')}
</Button>
</ButtonGroup>
</PageHeader>
<PageContent>
<CustomScrollbars>
<HistoryContent key='historyContent' data={data?.history || []} isLoading={isPending} />
</CustomScrollbars>
<Pagination
current={current}
itemsPerPage={itemsPerPage}
itemsPerPageLabel={itemsPerPageLabel}
showingResultsLabel={showingResultsLabel}
count={data?.total || 0}
onSetItemsPerPage={setItemsPerPage}
onSetCurrent={setCurrent}
/>
</PageContent>
</Page>
);
};
export default OutgoingWebhookHistoryPage;