Untitled
unknown
plain_text
a year ago
7.8 kB
10
Indexable
// Customizable Area Start
import { IBlock } from '../../../framework/src/IBlock';
import { Message } from '../../../framework/src/Message';
import { BlockComponent } from '../../../framework/src/BlockComponent';
import MessageEnum, {
getName,
} from '../../../framework/src/Messages/MessageEnum';
import { runEngine } from '../../../framework/src/RunEngine';
import { GiftedChat } from 'react-native-gifted-chat';
import {
getStorageData,
removeStorageData,
} from '../../../framework/src/Utilities';
let BEUrl = require('../../../framework/src/config.js');
import createRequestMessage from '../../utilities/src/create-request-message';
// Customizable Area Start
interface MessageArray {
id: number;
message: string;
isUser: boolean;
}
interface RespData {
warning: string;
id: string;
object: string;
created: number;
model: string;
choices: [
{
text: ' Hello there! How can I help you?';
index: 0;
logprobs: null;
finish_reason: 'stop';
}
];
usage: { prompt_tokens: 7; completion_tokens: 9; total_tokens: 16 };
}
interface IMessage {
_id: string | number;
text: string;
createdAt: Date | number;
user: User;
image?: string;
video?: string;
audio?: string;
system?: boolean;
sent?: boolean;
received?: boolean;
pending?: boolean;
quickReplies?: QuickReplies;
}
interface User {
_id: string | number;
name: string;
avatar: string;
}
interface QuickReplies {
type: 'radio' | 'checkbox';
values: Reply[];
keepIt?: boolean;
}
interface Reply {
title: string;
value: string;
messageId?: any;
}
// Customizable Area End
export const configJSON = require('./config');
export interface Props {
navigation: any;
id: string;
// Customizable Area Start
// Customizable Area End
}
interface S {
txtInputValue: string;
txtSavedValue: string;
enableField: boolean;
// Customizable Area Start
messages: Array<MessageArray>;
input: string;
isLoading: boolean;
data: string;
ws: any;
actionCable: WebSocket;
token: any;
// Customizable Area End
}
interface SS {
id: any;
// Customizable Area Start
// Customizable Area End
}
export default class ChatgptController extends BlockComponent<Props, S, SS> {
// Customizable Area Start
openApiID: string = '';
unsubscribe: any;
getDataCallId: any;
closeWebSocketConnection: {
addListener: (func: Function) => void;
remove: () => void;
} = { remove: () => {}, addListener: () => {} };
// Customizable Area End
constructor(props: Props) {
super(props);
this.receive = this.receive.bind(this);
this.subScribedMessages = [
getName(MessageEnum.AccoutLoginSuccess),
// Customizable Area Start
getName(MessageEnum.RestAPIResponceMessage),
getName(MessageEnum.RestAPIRequestMessage),
getName(MessageEnum.RestAPIResponceEndPointMessage),
getName(MessageEnum.RestAPIRequestBodyMessage),
getName(MessageEnum.RestAPIRequestHeaderMessage),
getName(MessageEnum.RestAPIRequestMethodMessage),
// Customizable Area End
];
this.state = {
txtInputValue: '',
txtSavedValue: 'A',
enableField: false,
// Customizable Area Start
messages: [],
input: '',
isLoading: false,
data: '',
token: '',
ws: null,
actionCable: {
binaryType: 'arraybuffer',
bufferedAmount: 0,
extensions: '',
onclose: null,
onerror: null,
onmessage: null,
onopen: null,
protocol: '',
readyState: 0,
url: '',
close: (code?: number | undefined, reason?: string | undefined) => {},
send: (data: string | ArrayBufferView | Blob | ArrayBufferLike) => {},
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3,
addEventListener: function <K extends keyof WebSocketEventMap>(
type: K,
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => {},
options?: boolean | AddEventListenerOptions | undefined
): void {},
removeEventListener: function <K extends keyof WebSocketEventMap>(
type: K,
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => {},
options?: boolean | EventListenerOptions | undefined
): void {},
dispatchEvent: function (event: Event): boolean {
return true;
},
},
// Customizable Area End
};
runEngine.attachBuildingBlock(this as IBlock, this.subScribedMessages);
// Customizable Area Start
// Customizable Area End
}
async receive(from: string, message: Message) {
runEngine.debugLog('Message Recived', message);
// Customizable Area Start
// Customizable Area End
}
// Customizable Area Start
onSend = (messages: any) => {
const requestMessage = new Message(
getName(MessageEnum.RestAPIRequestMessage)
);
this.getDataCallId = requestMessage.messageId;
const endPoint = configJSON.exampleAPiEndPoint;
const formData = new FormData();
formData.append('question[body]', messages.text);
createRequestMessage({
requestMessage: requestMessage,
endPoint: endPoint,
method: configJSON.exampleAPiMethod,
token: this.state.token,
body: formData,
});
this.setState((prevState) => ({
messages: GiftedChat.append(prevState.messages, messages),
}));
};
async componentDidMount(): Promise<void> {
// Create a WebSocket connection
this.getUserToken();
this.unsubscribe = this.props.navigation.addListener(
'didFocus',
async () => {
this.getUserToken();
}
);
this.closeWebSocketConnection = this.props.navigation.addListener(
'didBlur',
() => {
this.state.actionCable.close();
}
);
}
getUserToken = async () => {
let value = await getStorageData('usertoken');
const authToken = JSON.parse(value);
this.setState({ token: authToken });
if (!value) {
this.showAlert('Session expired', 'Please Login again');
} else {
this.notificationsConnectActionCable();
}
};
notificationsConnectActionCable = () => {
const link = BEUrl.baseURL.substring(8);
const actionCable = new WebSocket(
`wss://${link}/cable?token=${this.state.token}`
);
actionCable.onopen = () => {
actionCable.send(
JSON.stringify({
command: 'subscribe',
identifier: `{\"channel\":\"ChatGptChannel\"}`,
})
);
};
actionCable.onmessage = (message) => {
let finalData = JSON.parse(message?.data);
if (
finalData?.message?.record?.data?.attributes?.answer?.data?.attributes
?.body
) {
this.setState((prevState) => ({
messages: GiftedChat.append(prevState.messages, [
{
_id: 'be36c1b7-f811-44e3-b4df-09328de4e5d5',
createdAt: Date.now(),
text: finalData?.message?.record?.data?.attributes?.answer?.data
?.attributes?.body,
user: { _id: 2, name: 'Ava', avatar: '' },
},
]),
}));
// this.setState((prevState) => ({
// messages: GiftedChat.append(
// prevState.messages,
// finalData?.message?.record?.data?.attributes?.answer?.data
// ?.attributes?.body
// ),
// }));
}
};
actionCable.onerror = () => {
actionCable.close();
};
this.setState({ actionCable: actionCable });
};
async componentWillUnmount() {
this.unsubscribe.remove();
this.closeWebSocketConnection.remove();
}
// Customizable Area End
}
// Customizable Area End
Editor is loading...
Leave a Comment