Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
16 kB
4
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 StorageProvider from '../../../../framework/src/StorageProvider'
import { GiftedChat } from 'react-native-gifted-chat';
// Customizable Area Start
// import { GiftedChat } from "react-native-gifted-chat";
import { Keyboard, Platform } from "react-native";
import ImagePicker from "react-native-image-crop-picker";

import { CommonContext } from '../../../../components/src/CommonContextProvider'
import {
  ActionCable,
  Cable,
} from '@kesha-antonov/react-native-action-cable'

import {  getStorageData, } from "../../../../framework/src/Utilities";
import moment from "moment";


// Customizable Area End

export const configJSON = require("../../config.json");

export interface Props {
  navigation: any;
  id: string;
  // Customizable Area Start
  // Customizable Area End
}

interface S {
  // Customizable Area Start
  conversation_sid:any
    cableCon: any;
      messages: any;
      profilePhoto: any;
      name: string;
      userId:any;
      receiver_image:string;
      likeArray:any;
      user_name:string;
      actionCable1:any;
      handleName:string;
  

  // Customizable Area End
}
let isFound = false;
interface SS {
  id: any;
}

export default class ChatDetailsController extends BlockComponent<
  Props,
  S,
  SS
> {

  // Customizable Area Start
  actionCable: any;
  getChatDetailsApiId: any;
  
  static contextType = CommonContext;

  // Customizable Area End

  constructor(props: Props) {
    super(props);
    this.receive = this.receive.bind(this);

    // Customizable Area Start
    this.subScribedMessages = [
      // Customizable Area Start
      getName(MessageEnum.NavigationPayLoadMessage),
      getName(MessageEnum.RestAPIResponceMessage),
      // Customizable Area End
    ];

    this.state = {
      conversation_sid: '',
      cableCon: [],
      likeArray:[459,461],
      user_name:'',
      actionCable1:[],
      handleName:'',
       messages:
       [
          //  {
          //    _id: 1,
          //    text: 'Hello developer',
          //    iscustom: false,
          //    location: {
          //      latitude: 37.78825,
          //      longitude: -122.4324,
          //    },
          //    createdAt: new Date(),
          //    user: {
          //      _id: 659,
          //      name: 'React Native',
          //      avatar: 'https://placeimg.com/140/140/any',
          //    },
          //  },
          //  {
          //    _id: 1,
          //    text: 'Hello swapnil',
          //    iscustom: true,
          //    location: {
          //      latitude: 37.78825,
          //      longitude: -122.4324,
          //    },
          //    createdAt: new Date(),
          //    user: {
          //      _id: 1,
          //      name: 'React Native',
          //      avatar: 'https://placeimg.com/140/140/any',
          //    },
          //  },
         ],
     
       profilePhoto:'',
       name:'',
       userId:'',
       receiver_image:'',
       



    };
    // Customizable Area End
    runEngine.attachBuildingBlock(this as IBlock, this.subScribedMessages);

    // Customizable Area Start
    // Customizable Area End

  }


  
  async receive(from: string, message: Message) {

    // Customizable Area Start

    // Navigation passed Data
    if (
      getName(MessageEnum.RestAPIResponceMessage) === message.id &&
      this.getChatDetailsApiId != null &&
      this.getChatDetailsApiId === message.getData(getName(MessageEnum.RestAPIResponceDataMessage))
    ) {

      let responseJson = message.getData(
        getName(MessageEnum.RestAPIResponceSuccessMessage)
      );
      // console.log("nwenfiewnf", responseJson?.data?.attributes) 
      if (responseJson !== undefined && responseJson?.errors === undefined) {

        this.setState({messages:responseJson?.data?.attributes?.messages.reverse()})
     


      } else {
        let errorReponse = message.getData(
          getName(MessageEnum.RestAPIResponceErrorMessage)
        );
        console.log("Error response", errorReponse)
        console.log(responseJson)
      }

    }
    
    
    // Customizable Area End

  }

  async componentDidMount(): Promise<void> {
    this.getparama()
    this._checkActionCableConnect()
    this.fetchAllMessage()
  

  }

  async componentWillUnmount(): Promise<void> {
    this._disConnectChat()
  }


getparama = async()=>{
const userId = await StorageProvider.get('USER_ID')
let params = await this.props.navigation.state.params
this.setState({conversation_sid:params?.item?.conversation_sid, profilePhoto:params?.item?.receiver_image, name:params?.item?.name})
this.setState({ userId:Number(userId) })
this.setState({user_name:params?.item?.user_name})
this.setState({handleName:params?.item?.user_name})


// console.log(params?.item?.user_name, "paramsparamsparamsparamsparams ")
  }



  _checkActionCableConnect = async()=>{

    const token = await StorageProvider.get('USER_TOKEN')
    const link = 'vibesocialmusic-82830-ruby.b82830.dev.us-east-1.aws.svc.builder.cafe'  
    // const token = 'eyJhbGciOiJIUzUxMiJ9.eyJpZCI6MSwiZXhwIjoxNjg2NDc4NzEwLCJ0b2tlbl90eXBlIjoibG9naW4ifQ.jNvUSwPYo0nR0TOu0XDTq6QnF9GiMPFQQ6fbfCyxSuGwoBDD2vZP5UpBz80Wjifm-vIPrM6xkJELeOxyDnT_dw'
    // const link = '17a5-20-207-125-94.in.ngrok.io'

    let conversation_sid = await this.props.navigation.state.params?.item?.conversation_sid
    // let conversation_sid = 8
    console.log('Checking', token)
    this.actionCable = ActionCable.createConsumer(`wss://${link}/cable?token=${token}`)
    const cable = new Cable({
      channel: `MessagesChannel`,
      
    })
    this.setState({ cableCon: cable });
    this.setState({actionCable1:this.actionCable})
 
    const channel = cable.setChannel(
      `MessagesChannel`,
      // channel name to which we will pass data from Rails app with `stream_from`
      this.actionCable.subscriptions.create({
        channel: `MessagesChannel`, // from Rails app app/channels/chat_channel.rb
        // chat_id:8
        chat_id:conversation_sid
    
      })
    );

    channel
      .on("received", (e: any) => 
      {
        this._onRecieved(e)
      }
      )
      .on("connected", (e: any) => console.log(e, "MessagesChannel from server is connected"))
      .on("rejected", (e: any) => console.log(e, "rejected"))
      .on("disconnected", (e) => {
        console.log("disconnect", e);
        this.actionCable.disconnect();
      });
  }


  // fetchDetails = async () => {
  //   const userId = await StorageProvider.get('USER_ID')
  //   this.setState({ userId })
  //   const name = await this.props.navigation.state.params.
  //   this.setState({ headerName: name })
  //   console.log(name, "params.name")
  // }

  fetchAllMessage = async () => {
    const token = await StorageProvider.get('USER_TOKEN')
    const reciverID = await this.props.navigation.state?.params?.item?.conversation_sid

    const header = {
      'Content-Type': 'application/json',
      token
    }
    const requestMessage = new Message(
      getName(MessageEnum.RestAPIRequestMessage),
    )
    this.getChatDetailsApiId = requestMessage.messageId
    requestMessage.addData(
      getName(MessageEnum.RestAPIResponceEndPointMessage),
      // configJSON.getPostListApiEndPoint,
      `bx_block_chat/chats/${reciverID}`
    )
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestHeaderMessage),
      JSON.stringify(header),
    )
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestMethodMessage),
      'GET',
    )

    runEngine.sendMessage(requestMessage.id, requestMessage)
    return true
  }


  // Customizable Area Start

  async componentWillMount() {
    // this._cableCable();
  }
   

  _disConnectChat = () => {
    this.state.actionCable1.disconnect();
    console.log("_disConnectChat_disConnectChat_disConnectChat");
  };



  // Customizable Area End


  updateMessage = async () => {
    const message = await this.state.conversationFromSid.getMessages()


    const parseMessage = await this.parseMessages(message.items)
    this.setState({ messages: parseMessage })


  }
  

  _sendMessage = async(newMessages:any) => {
    console.log("sendMessage from chat", newMessages)
    this.setState({messages: GiftedChat.append(this.state.messages, newMessages)})
    this.state.cableCon.channel(`MessagesChannel`).perform('speak', { text: newMessages[0].text,_id: this.state.userId,createdAt: new Date(), })
    // this.state.cableCon.channel('MessagesChannel').perform('appear')
  }

  updateLastMsg = async (e: any) => {
    // var arr = [...this.state.messages]
    var arr = [...this.state.messages, {
      "_id": "426", "createdAt": "2022-09-12T08:36:14.947Z", "text": "swapnil", 
      "user": { "_id": "426", "name": "426" }
    }]
  }
  _onSend = (newMessages = []) => {
    console.log(newMessages,"new messagesssses")
    this.setState({messages: GiftedChat.append(this.state.messages, newMessages)})
  };

  _onRecieved = (e:any)=>{
    console.log(e,"Recieved")

    if (e?.message?.user_id != this.state.userId) {
      let messsage = {_id: Math.random(),
      createdAt: new Date(), text: e?.message?.message, user: 
      {_id: 1, fullname: e?.message?.name,avatar:this.state.profilePhoto}}
     let arr = [messsage,...this.state.messages,];
     this.setState({messages: arr});
    }
}
_handleLike = (e:number) => {
      console.log(e)
      let array = this.state.likeArray
      if(array.includes(e)){
        array.splice(array.indexOf(e),1)
      this.setState({likeArray:array})
      }else {
        array.push(e)
      this.setState({likeArray:array})
      }
      console.log(this.state.likeArray)
}
}








// scarp


// import RNFS from 'react-native-fs'
// import RNFetchBlob from "rn-fetch-blob";
// import SoundPlayer from "react-native-sound-player";
// import { Alert, BackHandler } from 'react-native'
// import { spotifyLogout } from '../../../../framework/src/Helpers'
// import { AppState } from 'react-native'


// keyBoardVisible: boolean;
  // keyBoardHeight: any;
  // isEliteUser: boolean;
  // isTherapist: boolean;
  // didMountCalled: boolean;

  // token: any;

  // channel: any;
  // chatData: any;
  // galleryModalVisible: boolean;
  // isModalVisible: boolean;
  // modalType: string;
  // search: string;
  // chatEnable: boolean;
  // chatLoading: boolean;
  // textMessage: string;
  // inputComment: string
  // profileData: any;
  // roomName: string;
  // searchProductList: any;
  // selectedProductList: any;
  // searchBlogList: any;
  // selectedBlogList: any;
  // searchVideoList: any;
  // selectedVideoList: any;
  // menuEnabled: boolean;
  // identity: any;
  // receiverIdentity: any;
  // receiverImage: any;
  // sending: boolean;
  // imageObj: any;
  // receiverId: number;
  // nextPageInfo: string;
  // isProductsLoading: boolean;
  // isInitialLoading: boolean;
  // headerName: string
  // conversationsReady: boolean;
  // conversations: any;
  // selectedConversationSid: any;
  // selectedConversation: any;
  // isNotification: boolean;
  // lastMessages: any;
  // inputMessgae: any;
  // userId: string;
  // conversationFromSid: any;
  // conversation_sid: any;
  // isLoading: boolean;
  // showCreatepost: boolean;
  // sliderValue: number;
  // progress: number;
  // isPlayingContext: boolean;
  // hardwareBackAlert: boolean;
  // contextData: boolean;
  // isPlayFinished: boolean;
  // isHomeFocusState: boolean,
  // block: boolean,
  // block_confirmed: boolean,
  // report: boolean,
  // report_reason: boolean,
  // delete: boolean,
  // getReportList: any;
  // public_mssg_request: boolean;
  // following_mssg_request: boolean;
  // verified_mssg_request: boolean;
  // pushNotification : boolean;
  // showreceipt : boolean;
  // platform: string;

  // refreshChatDetailsApiId: any;
  // postSendMessageApiId: any;
  // postSendImageMessageApiId: any;
  // getTutorialVideoApiId: any;
  // getBlogArticalsApiId: any;
  // getBlogListApiId: any;
  // corinaBlogId: any;
  // chatClient: any;
  // chatChannel: any;
  // conversationClientNew: any;
  // conversationChannelNew: any;
  // selectedProductListId: any = [];
  // chatRefreshInterval: any;
  // selectedProductListMsg: any = [];
  // selectedBlogListId: any = [];
  // selectedBlogListMsg: any = [];
  // selectedVideoListId: any = [];
  // selectedVideoListMsg: any = [];
  // searchProductApiId: any;
  // deleteChatApiID: any;
  // conversationsClient: any;
  // fetchTokenApi: any;
  // BackHandler: any;
  // backHandler: any;
  // timeOfSeek: any;
  // _onFinishedPlayingSubscription: any;
  // focusListener: any;
  // getReportListApiCallId: any;
  // updateChatApiID:any;



      // keyBoardVisible: false,
      // keyBoardHeight: Platform.OS === "ios" ? 0 : 100,
      // isEliteUser: false,
      // isTherapist: false,
      // didMountCalled: false,
      // profileData: null,
      // messages: [
      //   // {
      //   //   _id: 1,
      //   //   text: 'Hello developer',
      //   //   iscustom: false,
      //   //   location: {
      //   //     latitude: 37.78825,
      //   //     longitude: -122.4324,
      //   //   },
      //   //   createdAt: new Date(),
      //   //   user: {
      //   //     _id: 2,
      //   //     name: 'React Native',
      //   //     avatar: 'https://placeimg.com/140/140/any',
      //   //   },
      //   // },
      //   // {
      //   //   _id: 1,
      //   //   text: 'Hello swapnil',
      //   //   iscustom: true,
      //   //   location: {
      //   //     latitude: 37.78825,
      //   //     longitude: -122.4324,
      //   //   },
      //   //   createdAt: new Date(),
      //   //   user: {
      //   //     _id: 1,
      //   //     name: 'React Native',
      //   //     avatar: 'https://placeimg.com/140/140/any',
      //   //   },
      //   // },
      // ],
      // token: null,
   
      // channel: null,
      // chatEnable: false,
      // chatLoading: false,
      // chatData: null,
      // galleryModalVisible: false,
      // isModalVisible: false,
      // modalType: "",
      // roomName: "",
      // search: "",
      // searchProductList: [],
      // selectedProductList: [],
      // searchBlogList: null,
      // selectedBlogList: [],
      // searchVideoList: null,
      // selectedVideoList: [],
      // textMessage: "",
      // inputComment: "",
      // menuEnabled: false,
      // identity: "",
      // receiverIdentity: "",
      // receiverImage: null,
      // sending: false,
      // imageObj: null,
      // receiverId: 0,
      // nextPageInfo: "",
      // isProductsLoading: false,
      // isInitialLoading: true,
      // headerName: '',
      // conversationsReady: false,
      // conversations: [],
      // selectedConversationSid: null,
      // selectedConversation: null,
      // isNotification: true,
      // lastMessages: [],
      // inputMessgae: [],
      // userId: '',
      // conversationFromSid: [],
   
      // isLoading: true,
      // showCreatepost: false,
      // sliderValue: 0,
      // progress: 0,
      // isPlayingContext: false,
      // hardwareBackAlert: false,
      // contextData: true,
      // isPlayFinished: false,
      // isHomeFocusState: true,
      // block: false,
      // block_confirmed: false,
      // report: false,
      // report_reason: false,
      // delete: false,
      // getReportList: [],
      // public_mssg_request: false,
      // following_mssg_request : false,
      // verified_mssg_request : false,
      // pushNotification : false,
      // showreceipt : false,
      // platform: ''