move initial chats from bot to chatbox

This commit is contained in:
Sharon Kennedy 2020-02-24 14:16:43 -05:00
parent dcd4e4a9ba
commit fec0c1eb14
4 changed files with 117 additions and 56 deletions

View File

@ -209,14 +209,10 @@
} }
.message { .message {
.sender { margin-top: 0.5rem;
font-weight: bold; margin-bottom: 0.5rem;
color: $theme-color;
}
.text { .text {
margin-top: 0.5rem;
margin-bottom: 0.5rem;
width: fit-content; width: fit-content;
} }

View File

@ -4,16 +4,16 @@
color: $dark-theme-color; color: $dark-theme-color;
} }
.widget-header-minimize, .widget-header-close {
background: $dark-background-color;
color: $light-text-color;
border: 1px solid $white;
}
#ocrcc-chatbox { #ocrcc-chatbox {
.btn-icon { .btn-icon {
color: $light-text-color; color: $light-text-color;
} }
.widget-header-minimize, .widget-header-close {
background: $dark-background-color;
color: $light-text-color;
border: 1px solid $white;
}
.message-window { .message-window {
background-color: $dark-background-color; background-color: $dark-background-color;

View File

@ -24,30 +24,52 @@ const DEFAULT_ROOM_NAME = "Support Chat"
const BOT_USERNAME = "@help-bot:rhok.space" const BOT_USERNAME = "@help-bot:rhok.space"
const ENCRYPTION_CONFIG = { "algorithm": "m.megolm.v1.aes-sha2" }; const ENCRYPTION_CONFIG = { "algorithm": "m.megolm.v1.aes-sha2" };
const ENCRYPTION_NOTICE = "Messages in this chat are secured with end-to-end encryption." const ENCRYPTION_NOTICE = "Messages in this chat are secured with end-to-end encryption."
const DEFAULT_THEME = { const INTRO_MESSAGE = "This chat application does not collect any of your personal data or any data from your use of this service."
themeColor: "#008080", // teal const AGREEMENT_MESSAGE = "Do you want to continue? Type yes or no."
lightColor: "#FFF8F0", const CONFIRMATION_MESSAGE = "Starting the chat - a facilitator will be with you soon."
darkColor: "#22333B", const EXIT_MESSAGE = "The chat was not started."
errorColor: "#FFFACD", const FACILITATOR_ROOM_ID = '!pYVVPyFKacZeKZbWyz:rhok.space'
font: "'Assistant', 'Helvetica', sans-serif", const TERMS_URL="https://tosdr.org/"
placement: "right"
};
const initialState = { const initialState = {
opened: false, opened: false,
showDock: true, showDock: true,
client: null, client: null,
ready: false, ready: true,
accessToken: null, accessToken: null,
userId: null, userId: null,
messages: [], messages: [
{
id: 'intro-msg-id',
type: 'm.room.message',
sender: BOT_USERNAME,
content: { body: INTRO_MESSAGE },
},
{
id: 'terms-msg-id',
type: 'm.room.message',
sender: BOT_USERNAME,
content: {
body: `Please read the full terms and conditions at ${TERMS_URL}.`,
formatted_body: `Please read the full <a href="${TERMS_URL}">terms and conditions</a>.`
}
},
{
id: 'agreement-msg-id',
type: 'm.room.message',
sender: BOT_USERNAME,
content: { body: AGREEMENT_MESSAGE },
},
],
inputValue: "", inputValue: "",
errors: [], errors: [],
roomId: null, roomId: null,
typingStatus: null, typingStatus: null,
awaitingAgreement: true,
awaitingFacilitator: false,
} }
class ChatBox extends React.Component { class ChatBox extends React.Component {
constructor(props) { constructor(props) {
super(props) super(props)
@ -75,22 +97,29 @@ class ChatBox extends React.Component {
}); });
} }
handleExitChat = () => { handleWidgetEnter = () => {
this.leaveRoom() this.chatboxInput.current.focus()
.then(() => {
this.setState(initialState)
})
.catch(err => console.log("Error leaving room", err))
} }
leaveRoom = () => { handleExitChat = () => {
if (this.state.roomId) { if (this.state.client) {
return this.state.client.leave(this.state.roomId) this.leaveRoom()
.then(() => {
this.setState(initialState)
})
.catch(err => console.log("Error leaving room", err))
} else {
this.setState(initialState)
} }
} }
initializeClient = () => { leaveRoom = () => {
return this.state.client.leave(this.state.roomId)
}
initializeChat = () => {
// empty registration request to get session // empty registration request to get session
this.setState({ ready: false })
let client = matrix.createClient(this.props.matrixServerUrl) let client = matrix.createClient(this.props.matrixServerUrl)
return client.registerRequest({}) return client.registerRequest({})
.then(data => { .then(data => {
@ -140,7 +169,7 @@ class ChatBox extends React.Component {
console.log("Registration error", err) console.log("Registration error", err)
}) })
.then(() => client.initCrypto()) .then(() => client.initCrypto())
.finally(() => client.startClient()) .then(() => client.startClient())
.then(() => { .then(() => {
this.setState({ this.setState({
client: client client: client
@ -151,9 +180,7 @@ class ChatBox extends React.Component {
verifyAllRoomDevices = async function(roomId) { verifyAllRoomDevices = async function(roomId) {
let room = this.state.client.getRoom(roomId); let room = this.state.client.getRoom(roomId);
console.log('room', room)
let members = (await room.getEncryptionTargetMembers()).map(x => x["userId"]) let members = (await room.getEncryptionTargetMembers()).map(x => x["userId"])
console.log('members', members)
let memberkeys = await this.state.client.downloadKeys(members); let memberkeys = await this.state.client.downloadKeys(members);
for (const userId in memberkeys) { for (const userId in memberkeys) {
for (const deviceId in memberkeys[userId]) { for (const deviceId in memberkeys[userId]) {
@ -169,7 +196,7 @@ class ChatBox extends React.Component {
const chatTime = currentDate.toLocaleTimeString() const chatTime = currentDate.toLocaleTimeString()
return this.state.client.createRoom({ return this.state.client.createRoom({
room_alias_name: `private-support-chat-${uuid()}`, room_alias_name: `private-support-chat-${uuid()}`,
invite: [BOT_USERNAME], // TODO: create bot user to add invite: [BOT_USERNAME],
visibility: 'private', visibility: 'private',
name: `${chatDate} - ${this.props.roomName} - started at ${chatTime}`, name: `${chatDate} - ${this.props.roomName} - started at ${chatTime}`,
initial_state: [ initial_state: [
@ -178,14 +205,13 @@ class ChatBox extends React.Component {
state_key: '', state_key: '',
content: ENCRYPTION_CONFIG, content: ENCRYPTION_CONFIG,
}, },
] ]
}) })
.then(data => { .then(data => {
this.verifyAllRoomDevices(data.room_id) this.verifyAllRoomDevices(data.room_id)
this.state.client.setPowerLevel(data.room_id, BOT_USERNAME, 100) this.state.client.setPowerLevel(data.room_id, BOT_USERNAME, 100)
.then(() => console.log("Set bot power level to 100")) .then(() => console.log("Set bot power level to 100"))
.catch(err => console.log("Error setting bot power level", err)) .catch(err => console.log("Error setting bot power level", err))
this.setState({ this.setState({
roomId: data.room_id roomId: data.room_id
}) })
@ -198,9 +224,7 @@ class ChatBox extends React.Component {
sendMessage = () => { sendMessage = () => {
this.state.client.sendTextMessage(this.state.roomId, this.state.inputValue) this.state.client.sendTextMessage(this.state.roomId, this.state.inputValue)
.then((res) => { .then((res) => {
this.setState({ this.setState({ inputValue: "" })
inputValue: "",
})
this.chatboxInput.current.focus() this.chatboxInput.current.focus()
}) })
.catch((err) => { .catch((err) => {
@ -262,7 +286,7 @@ class ChatBox extends React.Component {
roomId: room.room_id, roomId: room.room_id,
content: { body: ENCRYPTION_NOTICE }, content: { body: ENCRYPTION_NOTICE },
} }
msgList.unshift(encryptionMsg) msgList.push(encryptionMsg)
this.setState({ messages: msgList }) this.setState({ messages: msgList })
} }
@ -282,14 +306,17 @@ class ChatBox extends React.Component {
this.setState({ typingStatus: null }) this.setState({ typingStatus: null })
} }
}); });
} }
if (!prevState.ready && this.state.ready) { if (!prevState.ready && this.state.ready) {
this.chatboxInput.current.focus() this.chatboxInput.current.focus()
} }
if (this.state.client === null && !prevState.opened && this.state.opened) { console.log('OPENED STATE', this.state.opened)
this.initializeClient()
if (!prevState.opened && this.state.opened) {
this.chatboxInput.current.focus()
} }
} }
@ -310,11 +337,46 @@ class ChatBox extends React.Component {
e.preventDefault() e.preventDefault()
if (!Boolean(this.state.inputValue)) return null; if (!Boolean(this.state.inputValue)) return null;
if (!this.state.roomId) { if (this.state.awaitingAgreement && !this.state.client) {
return this.createRoom().then(this.sendMessage) if (this.state.inputValue.toLowerCase() === 'yes') {
const fakeUserMsg = {
id: 'fake-msg-id',
type: 'm.room.message',
sender: 'from-me',
content: { body: this.state.inputValue },
}
const messages = [...this.state.messages]
messages.push(fakeUserMsg)
this.setState({ inputValue: "", messages })
return this.initializeChat()
} else {
const fakeUserMsg = {
id: 'fake-msg-id',
type: 'm.room.message',
sender: 'from-me',
content: { body: this.state.inputValue },
}
const exitMsg = {
id: 'exit-msg-id',
type: 'm.room.message',
sender: BOT_USERNAME,
content: { body: EXIT_MESSAGE },
}
const messages = [...this.state.messages]
messages.push(fakeUserMsg)
messages.push(exitMsg)
this.setState({ inputValue: "", messages })
}
}
if (this.state.client && this.state.roomId) {
return this.sendMessage()
} }
this.sendMessage()
} }
render() { render() {
@ -323,8 +385,9 @@ class ChatBox extends React.Component {
return ( return (
<div className="docked-widget" role="complementary"> <div className="docked-widget" role="complementary">
<Transition in={opened} timeout={250} onExited={this.handleWidgetExit}> <Transition in={opened} timeout={250} onExited={this.handleWidgetExit} onEntered={this.handleWidgetEnter}>
{(status) => ( {(status) => {
return (
<div className={`widget widget-${status}`} aria-hidden={!opened}> <div className={`widget widget-${status}`} aria-hidden={!opened}>
<div id="ocrcc-chatbox" aria-haspopup="dialog"> <div id="ocrcc-chatbox" aria-haspopup="dialog">
<Header handleToggleOpen={this.handleToggleOpen} opened={opened} handleExitChat={this.handleExitChat} /> <Header handleToggleOpen={this.handleToggleOpen} opened={opened} handleExitChat={this.handleExitChat} />
@ -332,19 +395,20 @@ class ChatBox extends React.Component {
<div className="message-window"> <div className="message-window">
<div className="messages"> <div className="messages">
{ {
ready ?
messages.map((message, index) => { messages.map((message, index) => {
return( return(
<Message key={message.id} message={message} userId={userId} botId={BOT_USERNAME} /> <Message key={message.id} message={message} userId={userId} botId={BOT_USERNAME} />
) )
}) : })
<div className="loader">loading...</div>
} }
{ typingStatus && { typingStatus &&
<div className="notices"> <div className="notices">
<div role="status">{typingStatus}</div> <div role="status">{typingStatus}</div>
</div> </div>
} }
{
!ready && <div className="loader">loading...</div>
}
</div> </div>
</div> </div>
<div className="input-window"> <div className="input-window">
@ -363,7 +427,8 @@ class ChatBox extends React.Component {
</div> </div>
</div> </div>
</div> </div>
)} )}
}
</Transition> </Transition>
{showDock && !roomId && <Dock handleToggleOpen={this.handleToggleOpen} />} {showDock && !roomId && <Dock handleToggleOpen={this.handleToggleOpen} />}
{showDock && roomId && <Header handleToggleOpen={this.handleToggleOpen} opened={opened} handleExitChat={this.handleExitChat} />} {showDock && roomId && <Header handleToggleOpen={this.handleToggleOpen} opened={opened} handleExitChat={this.handleExitChat} />}
@ -375,7 +440,6 @@ class ChatBox extends React.Component {
ChatBox.propTypes = { ChatBox.propTypes = {
matrixServerUrl: PropTypes.string.isRequired, matrixServerUrl: PropTypes.string.isRequired,
roomName: PropTypes.string.isRequired, roomName: PropTypes.string.isRequired,
theme: PropTypes.object,
termsUrl: PropTypes.string, termsUrl: PropTypes.string,
privacyStatement: PropTypes.string, privacyStatement: PropTypes.string,
} }
@ -383,7 +447,6 @@ ChatBox.propTypes = {
ChatBox.defaultProps = { ChatBox.defaultProps = {
matrixServerUrl: DEFAULT_MATRIX_SERVER, matrixServerUrl: DEFAULT_MATRIX_SERVER,
roomName: DEFAULT_ROOM_NAME, roomName: DEFAULT_ROOM_NAME,
theme: DEFAULT_THEME,
} }
export default ChatBox; export default ChatBox;

View File

@ -5,6 +5,8 @@ const Message = ({ message, userId, botId }) => {
const senderClass = () => { const senderClass = () => {
switch (message.sender) { switch (message.sender) {
case 'from-me':
return 'from-me'
case userId: case userId:
return 'from-me' return 'from-me'
case botId: case botId: