Commit ad38ddad authored by murtaza98's avatar murtaza98

code refactor

- create seperate file for logs
- add default message
parent 69d47199
......@@ -7,7 +7,13 @@ export enum AppSetting {
RasaHandoverMessage = 'rasa_handover_message',
RasaCloseChatMessage = 'rasa_close_chat_message',
RasaEnableCallbacks = 'rasa_enable_callbacks',
}
}
export enum DefaultMessage {
DEFAULT_DialogflowServiceUnavailableMessage = 'Sorry, I\'m having trouble answering your question.',
DEFAULT_DialogflowHandoverMessage = 'Transferring to an online agent',
DEFAULT_DialogflowCloseChatMessage = 'Closing the chat, Goodbye',
}
export const settings: Array<ISetting> = [
{
......
import { HttpStatusCode, IHttp, IModify, IPersistence, IRead } from '@rocket.chat/apps-engine/definition/accessors';
import { ApiEndpoint, IApiEndpointInfo, IApiRequest, IApiResponse } from '@rocket.chat/apps-engine/definition/api';
import { Headers } from '../enum/Http';
import { Headers, Response } from '../enum/Http';
import { Logs } from '../enum/Logs';
import { IRasaMessage } from '../enum/Rasa';
import { createHttpResponse } from '../lib/Http';
import { createRasaMessage } from '../lib/Message';
......@@ -15,13 +16,13 @@ export class CallbackInputEndpoint extends ApiEndpoint {
modify: IModify,
http: IHttp,
persis: IPersistence): Promise<IApiResponse> {
this.app.getLogger().info('Endpoint received an request');
this.app.getLogger().info(Logs.ENDPOINT_RECEIVED_REQUEST);
try {
await this.processRequest(read, modify, persis, request.content);
return createHttpResponse(HttpStatusCode.OK, { 'Content-Type': Headers.CONTENT_TYPE_JSON }, { result: 'Success' });
return createHttpResponse(HttpStatusCode.OK, { 'Content-Type': Headers.CONTENT_TYPE_JSON }, { result: Response.SUCCESS });
} catch (error) {
this.app.getLogger().error('Error occurred while processing the request. Details:- ', error);
this.app.getLogger().error(`${ Logs.ENDPOINT_REQUEST_PROCESSING_ERROR } ${error}`);
return createHttpResponse(HttpStatusCode.INTERNAL_SERVER_ERROR, { 'Content-Type': Headers.CONTENT_TYPE_JSON }, { error: error.message });
}
}
......
......@@ -2,7 +2,8 @@ import { HttpStatusCode, IHttp, IModify, IPersistence, IRead } from '@rocket.cha
import { ApiEndpoint, IApiEndpointInfo, IApiRequest, IApiResponse } from '@rocket.chat/apps-engine/definition/api';
import { ILivechatRoom } from '@rocket.chat/apps-engine/definition/livechat';
import { EndpointActionNames, IActionsEndpointContent } from '../enum/Endpoints';
import { Headers } from '../enum/Http';
import { Headers, Response } from '../enum/Http';
import { Logs } from '../enum/Logs';
import { createHttpResponse } from '../lib/Http';
import { closeChat, performHandover } from '../lib/Room';
......@@ -15,13 +16,13 @@ export class IncomingEndpoint extends ApiEndpoint {
modify: IModify,
http: IHttp,
persis: IPersistence): Promise<IApiResponse> {
this.app.getLogger().info('Endpoint recieved an request');
this.app.getLogger().info(Logs.ENDPOINT_RECEIVED_REQUEST);
try {
await this.processRequest(read, modify, persis, request.content);
return createHttpResponse(HttpStatusCode.OK, { 'Content-Type': Headers.CONTENT_TYPE_JSON }, { result: 'Success' });
return createHttpResponse(HttpStatusCode.OK, { 'Content-Type': Headers.CONTENT_TYPE_JSON }, { result: Response.SUCCESS });
} catch (error) {
this.app.getLogger().error('Error occurred while processing the request. Details:- ', error);
this.app.getLogger().error(`${ Logs.ENDPOINT_REQUEST_PROCESSING_ERROR } ${ error }`);
return createHttpResponse(HttpStatusCode.INTERNAL_SERVER_ERROR, { 'Content-Type': Headers.CONTENT_TYPE_JSON }, { error: error.message });
}
}
......@@ -30,7 +31,7 @@ export class IncomingEndpoint extends ApiEndpoint {
const { action, sessionId } = endpointContent;
if (!sessionId) {
throw new Error('Error!! Session Id not present in payload');
throw new Error(Logs.INVALID_SESSION_ID);
}
switch (action) {
case EndpointActionNames.CLOSE_CHAT:
......@@ -39,12 +40,12 @@ export class IncomingEndpoint extends ApiEndpoint {
case EndpointActionNames.HANDOVER:
const { actionData: { targetDepartment = '' } = {} } = endpointContent;
const room = await read.getRoomReader().getById(sessionId) as ILivechatRoom;
if (!room) { throw new Error('Error! Session Id not valid'); }
if (!room) { throw new Error(Logs.INVALID_SESSION_ID); }
const { visitor: { token: visitorToken } } = room;
await performHandover(modify, read, sessionId, visitorToken, targetDepartment);
break;
default:
throw new Error('Error!! Invalid Action type');
throw new Error(Logs.INVALID_ENDPOINT_ACTION);
}
}
}
......@@ -2,3 +2,7 @@ export enum Headers {
CONTENT_TYPE_JSON = 'application/json',
ACCEPT_JSON = 'application/json',
}
export enum Response {
SUCCESS = 'Your request was processed successfully',
}
export enum Logs {
ENDPOINT_RECEIVED_REQUEST = 'Endpoint received a request',
INVALID_SESSION_ID = 'Error! Session Id not valid',
INVALID_ROOM_ID = 'Error! Room Id not valid',
INVALID_REQUEST_CONTENT = 'Error! Request content not valid',
INVALID_BOT_USERNAME_SETTING = 'The Bot User does not exist.',
INVALID_RASA_SERVER_URL_SETTING = 'Error! Rasa server url not valid',
INVALID_VISITOR_TOKEN = 'Error: Visitor Token not valid',
INVALID_DEPARTMENT_NAME = 'Error: Department Name is not valid',
ENDPOINT_REQUEST_PROCESSING_ERROR = 'Error occurred while processing the request. Details:- ',
INVALID_ENDPOINT_ACTION = 'Error!! Invalid Action type',
EMPTY_BOT_USERNAME_SETTING = 'The Bot Username setting is not defined.',
RASA_REST_API_COMMUNICATION_ERROR = 'Error occurred while interacting with Rasa Rest API. Details: ',
INVALID_RESPONSE_FROM_RASA = 'Error!! Invalid Response From RASA',
INVALID_RESPONSE_FROM_RASA_CONTENT_UNDEFINED = 'Error Parsing RASA\'s Response. Content is undefined',
CLOSE_CHAT_REQUEST_FAILED_ERROR = 'Error: Internal Server Error. Could not close the chat',
HANDOVER_REQUEST_FAILED_ERROR = 'Error occurred while processing handover. Details',
}
......@@ -2,7 +2,8 @@ import { IHttp, IModify, IPersistence, IRead } from '@rocket.chat/apps-engine/de
import { IApp } from '@rocket.chat/apps-engine/definition/IApp';
import { ILivechatMessage, ILivechatRoom } from '@rocket.chat/apps-engine/definition/livechat';
import { RoomType } from '@rocket.chat/apps-engine/definition/rooms';
import { AppSetting } from '../config/Settings';
import { AppSetting, DefaultMessage } from '../config/Settings';
import { Logs } from '../enum/Logs';
import { IRasaMessage } from '../enum/Rasa';
import { createMessage, createRasaMessage } from '../lib/Message';
import { sendMessage } from '../lib/Rasa';
......@@ -49,10 +50,12 @@ export class PostMessageSentHandler {
try {
response = await sendMessage(this.read, this.http, rid, text);
} catch (error) {
this.app.getLogger().error(`Error occurred while using Rasa Rest API. Details:- ${error.message}`);
this.app.getLogger().error(`${ Logs.RASA_REST_API_COMMUNICATION_ERROR } ${error.message}`);
const serviceUnavailable: string = await getAppSettingValue(this.read, AppSetting.RasaServiceUnavailableMessage);
await createMessage(rid, this.read, this.modify, { text: serviceUnavailable ? serviceUnavailable : '' });
await createMessage(rid, this.read, this.modify, {
text: serviceUnavailable ? serviceUnavailable : DefaultMessage.DEFAULT_DialogflowServiceUnavailableMessage,
});
return;
}
......
import { IModify, IRead } from '@rocket.chat/apps-engine/definition/accessors';
import { IMessageAction, IMessageAttachment, MessageActionType, MessageProcessingType } from '@rocket.chat/apps-engine/definition/messages';
import { AppSetting } from '../config/Settings';
import { Logs } from '../enum/Logs';
import { IRasaMessage, IRasaQuickReplies, IRasaQuickReply } from '../enum/Rasa';
import { getAppSettingValue } from './Setting';
......@@ -31,19 +32,19 @@ export const createMessage = async (rid: string, read: IRead, modify: IModify,
const botUserName = await getAppSettingValue(read, AppSetting.RasaBotUsername);
if (!botUserName) {
this.app.getLogger().error('The Bot Username setting is not defined.');
this.app.getLogger().error(Logs.EMPTY_BOT_USERNAME_SETTING);
return;
}
const sender = await read.getUserReader().getByUsername(botUserName);
if (!sender) {
this.app.getLogger().error('The Bot User does not exist.');
this.app.getLogger().error(Logs.INVALID_BOT_USERNAME_SETTING);
return;
}
const room = await read.getRoomReader().getById(rid);
if (!room) {
this.app.getLogger().error(`Invalid room id ${rid}`);
this.app.getLogger().error(Logs.INVALID_ROOM_ID);
return;
}
......
import { IHttp, IHttpRequest, IRead } from '@rocket.chat/apps-engine/definition/accessors';
import { AppSetting } from '../config/Settings';
import { Headers } from '../enum/Http';
import { Logs } from '../enum/Logs';
import { IRasaMessage, IRasaQuickReplies, IRasaQuickReply } from '../enum/Rasa';
import { createHttpRequest } from './Http';
import { getAppSettingValue } from './Setting';
export const sendMessage = async (read: IRead, http: IHttp, sender: string, message: string): Promise<Array<IRasaMessage> | null> => {
const rasaServerUrl = await getAppSettingValue(read, AppSetting.RasaServerUrl);
if (!rasaServerUrl) { throw new Error('Error! Rasa server url setting empty'); }
if (!rasaServerUrl) { throw new Error(Logs.INVALID_RASA_SERVER_URL_SETTING); }
const callbackEnabled: boolean = await getAppSettingValue(read, AppSetting.RasaEnableCallbacks);
const httpRequestContent: IHttpRequest = createHttpRequest(
......@@ -17,7 +18,7 @@ export const sendMessage = async (read: IRead, http: IHttp, sender: string, mess
const rasaWebhookUrl = callbackEnabled ? `${rasaServerUrl}/webhooks/callback/webhook` : `${rasaServerUrl}/webhooks/rest/webhook`;
const response = await http.post(rasaWebhookUrl, httpRequestContent);
if (response.statusCode !== 200) { throw Error(`Error occurred while interacting with Rasa Rest API. Details: ${response.content}`); }
if (response.statusCode !== 200) { throw Error(`${ Logs.RASA_REST_API_COMMUNICATION_ERROR } ${ response.content }`); }
if (!callbackEnabled) {
const parsedMessage = parseRasaResponse(response.data);
......@@ -27,7 +28,7 @@ export const sendMessage = async (read: IRead, http: IHttp, sender: string, mess
};
export const parseRasaResponse = (response: any): Array<IRasaMessage> => {
if (!response) { throw new Error('Error Parsing Rasa\'s Response. Data is undefined'); }
if (!response) { throw new Error(Logs.INVALID_RESPONSE_FROM_RASA_CONTENT_UNDEFINED); }
const messages: Array<IRasaMessage> = [];
......
import { IModify, IRead } from '@rocket.chat/apps-engine/definition/accessors';
import { IDepartment, ILivechatRoom, ILivechatTransferData, IVisitor } from '@rocket.chat/apps-engine/definition/livechat';
import { IRoom } from '@rocket.chat/apps-engine/definition/rooms';
import { AppSetting } from '../config/Settings';
import { AppSetting, DefaultMessage } from '../config/Settings';
import { Logs } from '../enum/Logs';
import { createMessage } from './Message';
import { getAppSettingValue } from './Setting';
......@@ -32,24 +33,25 @@ export const updateRoomCustomFields = async (rid: string, data: any, read: IRead
export const closeChat = async (modify: IModify, read: IRead, rid: string) => {
const room: IRoom = (await read.getRoomReader().getById(rid)) as IRoom;
if (!room) { throw new Error('Error: Room Id not valid'); }
if (!room) { throw new Error(Logs.INVALID_ROOM_ID); }
const closeChatMessage = await getAppSettingValue(read, AppSetting.RasaCloseChatMessage);
const result = await modify.getUpdater().getLivechatUpdater().closeRoom(room, closeChatMessage ? closeChatMessage : '');
if (!result) { throw new Error('Error: Internal Server Error. Could not close the chat'); }
const result = await modify.getUpdater().getLivechatUpdater()
.closeRoom(room, closeChatMessage ? closeChatMessage : DefaultMessage.DEFAULT_DialogflowCloseChatMessage);
if (!result) { throw new Error(Logs.CLOSE_CHAT_REQUEST_FAILED_ERROR); }
};
export const performHandover = async (modify: IModify, read: IRead, rid: string, visitorToken: string, targetDepartmentName?: string) => {
const handoverMessage: string = await getAppSettingValue(read, AppSetting.RasaHandoverMessage);
await createMessage(rid, read, modify, { text: handoverMessage ? handoverMessage : '' });
await createMessage(rid, read, modify, { text: handoverMessage ? handoverMessage : DefaultMessage.DEFAULT_DialogflowHandoverMessage });
const room: ILivechatRoom = (await read.getRoomReader().getById(rid)) as ILivechatRoom;
if (!room) { throw new Error('Error: Room Id not valid'); }
if (!room) { throw new Error(Logs.INVALID_ROOM_ID); }
const visitor: IVisitor = (await read.getLivechatReader().getLivechatVisitorByToken(visitorToken)) as IVisitor;
if (!visitor) { throw new Error('Error: Visitor Id not valid'); }
if (!visitor) { throw new Error(Logs.INVALID_VISITOR_TOKEN); }
const livechatTransferData: ILivechatTransferData = {
currentRoom: room,
......@@ -58,17 +60,17 @@ export const performHandover = async (modify: IModify, read: IRead, rid: string,
// Fill livechatTransferData.targetDepartment param if required
if (targetDepartmentName) {
const targetDepartment: IDepartment = (await read.getLivechatReader().getLivechatDepartmentByIdOrName(targetDepartmentName)) as IDepartment;
if (!targetDepartment) { throw new Error('Error: Department Name is not valid'); }
if (!targetDepartment) { throw new Error(Logs.INVALID_DEPARTMENT_NAME); }
livechatTransferData.targetDepartment = targetDepartment.id;
}
const result = await modify.getUpdater().getLivechatUpdater().transferVisitor(visitor, livechatTransferData)
.catch((error) => {
throw new Error('Error occured while processing handover. Details' + error);
throw new Error(`${ Logs.HANDOVER_REQUEST_FAILED_ERROR } ${error}`);
});
if (!result) {
const offlineMessage: string = await getAppSettingValue(read, AppSetting.RasaServiceUnavailableMessage);
await createMessage(rid, read, modify, { text: offlineMessage ? offlineMessage : '' });
await createMessage(rid, read, modify, { text: offlineMessage ? offlineMessage : DefaultMessage.DEFAULT_DialogflowServiceUnavailableMessage });
}
};
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment