Files
bot/packages/bot-engine/src/services/inputs.ts

66 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-02-10 10:25:38 +01:00
import {
2022-06-11 07:27:38 +02:00
BubbleBlock,
BubbleBlockType,
2022-02-10 10:25:38 +01:00
Edge,
2022-06-11 07:27:38 +02:00
EmailInputBlock,
InputBlockType,
PhoneNumberInputBlock,
Block,
UrlInputBlock,
2022-02-10 10:25:38 +01:00
Variable,
} from 'models'
import { isPossiblePhoneNumber } from 'react-phone-number-input'
2022-06-11 07:27:38 +02:00
import { isInputBlock } from 'utils'
2022-02-10 10:25:38 +01:00
import { parseVariables } from './variable'
const emailRegex =
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
const urlRegex =
/^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})$/
2022-02-10 10:25:38 +01:00
export const isInputValid = (
inputValue: string,
2022-06-11 07:27:38 +02:00
type: InputBlockType
2022-02-10 10:25:38 +01:00
): boolean => {
switch (type) {
2022-06-11 07:27:38 +02:00
case InputBlockType.EMAIL:
2022-02-10 10:25:38 +01:00
return emailRegex.test(inputValue)
2022-06-11 07:27:38 +02:00
case InputBlockType.PHONE:
2022-02-10 10:25:38 +01:00
return isPossiblePhoneNumber(inputValue)
2022-06-11 07:27:38 +02:00
case InputBlockType.URL:
2022-02-10 10:25:38 +01:00
return urlRegex.test(inputValue)
}
return true
}
2022-06-11 07:27:38 +02:00
export const blockCanBeRetried = (
block: Block
): block is EmailInputBlock | UrlInputBlock | PhoneNumberInputBlock =>
isInputBlock(block) && 'retryMessageContent' in block.options
2022-02-10 10:25:38 +01:00
2022-06-11 07:27:38 +02:00
export const parseRetryBlock = (
block: EmailInputBlock | UrlInputBlock | PhoneNumberInputBlock,
2022-02-10 10:25:38 +01:00
variables: Variable[],
createEdge: (edge: Edge) => void
2022-06-11 07:27:38 +02:00
): BubbleBlock => {
const content = parseVariables(variables)(block.options.retryMessageContent)
const newBlockId = block.id + Math.random() * 1000
2022-02-10 10:25:38 +01:00
const newEdge: Edge = {
id: (Math.random() * 1000).toString(),
2022-06-11 07:27:38 +02:00
from: { blockId: newBlockId, groupId: block.groupId },
to: { groupId: block.groupId, blockId: block.id },
2022-02-10 10:25:38 +01:00
}
createEdge(newEdge)
return {
2022-06-11 07:27:38 +02:00
groupId: block.groupId,
id: newBlockId,
type: BubbleBlockType.TEXT,
2022-02-10 10:25:38 +01:00
content: {
html: `<div>${content}</div>`,
richText: [],
plainText: content,
},
outgoingEdgeId: newEdge.id,
}
}