Untitled

mail@pastecode.io avatar
unknown
plain_text
15 days ago
4.6 kB
2
Indexable
Never
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, TextInput, Button, ScrollView, TouchableOpacity, Platform, Alert } from 'react-native';
import NetInfo from "@react-native-community/netinfo";
import DocumentPicker from 'react-native-document-picker';
import WebSocket from 'react-native-websocket';

const App = () => {
    const [message, setMessage] = useState('');
    const [attachment, setAttachment] = useState(null);
    const [messages, setMessages] = useState([]);
    const [connected, setConnected] = useState(false);
    const websocketRef = useRef(null);
    const token = 'NjhRN045Q043TzZlMEduelZzR3cyZFdvbkNRMUtScnFJYkRGb1RoZzR2QUV3OHBGdUVBSUFxSzFPaTRqQU5TN2lQbVo5U2RqWE9lRkpLdThhS3gxYlE9PQ==';
    const targetCustomerId = '';
    const groupId = '1';
    const reconnectInterval = 5000;

    useEffect(() => {
        const connectWebSocket = () => {
            websocketRef.current = new WebSocket('wss://app.haroct.com.my/ws?token=' + token + '&targetCustomerId=' + targetCustomerId + '&groupId=' + groupId);

            websocketRef.current.onopen = () => {
                console.log("Connection established!");
                setConnected(true);
            };

            websocketRef.current.onerror = (e) => {
                console.error("WebSocket error observed:", e);
                setConnected(false);
            };

            websocketRef.current.onclose = (e) => {
                if (!e.wasClean) {
                    console.error('Connection closed unexpectedly');
                    setTimeout(connectWebSocket, reconnectInterval);
                }
                setConnected(false);
            };

            websocketRef.current.onmessage = (e) => {
                const data = JSON.parse(e.data);
                if (data.history) {
                    setMessages(data.history);
                } else {
                    setMessages(prevMessages => [...prevMessages, data]);
                }
            };
        };

        connectWebSocket();
        return () => {
            if (websocketRef.current) {
                websocketRef.current.close();
            }
        };
    }, []);

    const sendMessage = () => {
        if (!message.trim() && !attachment) return;

        const payload = {
            targetCustomerId: targetCustomerId,
            groupId: groupId,
            message: message.trim() ? message : null,
            attachment: null,
            fileName: null
        };

        if (attachment) {
            payload.fileName = attachment.name;
            payload.attachment = attachment.uri;
            setAttachment(null);
        }

        setMessage('');
        websocketRef.current.send(JSON.stringify(payload));
    };

    const pickAttachment = async () => {
        try {
            const result = await DocumentPicker.pick({
                type: [DocumentPicker.types.allFiles],
            });
            setAttachment(result);
        } catch (err) {
            if (DocumentPicker.isCancel(err)) {
                // User cancelled the picker
            } else {
                throw err;
            }
        }
    };

    const displayMessage = (data) => {
        if (data.error) {
            Alert.alert("Error", data.error);
            return;
        }

        return (
            <View key={data.id} style={{ padding: 10, backgroundColor: data.isMe ? '#d9f9b1' : '#ffffff', marginVertical: 5 }}>
                <Text><strong>{data.sender}:</strong> {data.message}</Text>
                {data.attachment && <Text><a href={data.attachment} target="_blank"><i class="fa fa-paperclip"></i> {data.fileName}</a></Text>}
                <Text style={{ color: 'gray', textAlign: 'right' }}>{data.created}</Text>
            </View>
        );
    };

    return (
        <View style={{ flex: 1, padding: 20 }}>
            <ScrollView style={{ flex: 1 }} contentContainerStyle={{ paddingVertical: 20 }}>
                {messages.map(displayMessage)}
            </ScrollView>
            <TextInput
                style={{ height: 40, borderColor: 'gray', borderWidth: 1, marginBottom: 10 }}
                placeholder="Type a message"
                value={message}
                onChangeText={setMessage}
            />
            <Button title="Pick Attachment" onPress={pickAttachment} />
            {attachment && <Text>Attachment: {attachment.name}</Text>}
            <Button title="Send" onPress={sendMessage} disabled={!connected} />
        </View>
    );
};

export default App;
Leave a Comment