Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
13 kB
1
Indexable
Never
// 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";
import SoundPlayer from 'react-native-sound-player';


// 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;
      progress: any;
      indexId:number
      songDetails:any;
      imputMessage:string;
      msgID:number;
      avatarTitle:any;
      username:any;

  // 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;
  likeButtonApiCall: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 = {
      avatarTitle:'',
      username:'',
      msgID:0,
      conversation_sid: '',
      cableCon: null,
      likeArray:[459,461],
      user_name:'',
      actionCable1:[],
      imputMessage:'',
      handleName:'',
      progress: 0,
      indexId:0,
      songDetails:[],
       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?.id) 
       
      if (responseJson !== undefined && responseJson?.errors === undefined) {

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


      } 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()
    this.handleProfile()
  

  }

  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 link = '04a9-20-207-125-94.in.ngrok.io'

    let conversation_sid = await this.props.navigation.state.params?.item?.conversation_sid
   
    console.log('conversation_sid', conversation_sid)
    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 = 'eyJhbGciOiJIUzUxMiJ9.eyJpZCI6MywiZXhwIjoxNjg2ODMwNDI2LCJ0b2tlbl90eXBlIjoibG9naW4ifQ.zLUq3X_wJpqQu_w_YDd57uFGjz4iF233I0N3XnOuMIgTguD12Y_LG9Q7QPcNHGkNdeTy__B12JBGM4ii6JkrBQ'
    // const reciverID = 14
    // const token = 'eyJhbGciOiJIUzUxMiJ9.eyJpZCI6NywiZXhwIjoxNjg2OTAwMjUzLCJ0b2tlbl90eXBlIjoibG9naW4ifQ.tTIGn8DFr4BsSqcNvEP7p9h-w47EhgW-SMyB6rJM9HSbIX0VfcCEL0Zjx4KV3vioX3WscWYnaITkjogvfRYIVw'
    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._disConnectChat()
    // this._cableCable();
  }
   

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

  
  

  _sendMessage = async(newMessages:any) => {
    console.log("sendMessage from _sendMessage_sendMessage_sendMessage_sendMessage", newMessages[0]._id)
    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('messages_onRecieved_onRecieved_onRecieved,',e)

    if (e?.message?.user_id != this.state.userId) {
      if (e?.like_message?.is_favourite) {
        console.log('leiked')
      } else {
            let messsage = {_id: e?.message?.message_id,
      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});
      }
    //   let messsage = {_id: e?.message?.message_id,
    //   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});
    } else if (e?.message?.is_favourite) {
      console.log('liked')
    } else {
      console.log('else')
    }
}
_handleLike = (e:number) => {
  console.log('e',e)
  this.state.cableCon.channel(`MessagesChannel`).perform('speak', { message_id:e,is_favorite:true })
      // 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)
}

_countCharacterLimit = (e) => {
  if (e.length > 10) {
    console.log('character limit')
    
  } 
}


_playSong = (e:any) => {

  this.setState({songDetails:{
    songName: 'test',
    artistName: 'artist',
    songImageUrl: 'image',
    songMediaUrl: e,
    bandName: 'band',
    liked: 'liked',
    spotify_post_id:'223' 
  }})
  
  if (this.context.contextId !== this.state.indexId) {

    this.context.playData(false)
    this.context.contextIdData(this.state.indexId)
    this.context.songData(this.state.songDetails)
    SoundPlayer.playUrl(e)


  } else {
    if (this.context.contextId === this.state.indexId) {
      if (this.context.isplay) {


        this.context.playData(false)
        this.context.contextIdData(this.state.indexId)
        this.context.songData(this.state.songDetails)
        SoundPlayer.playUrl(e)
      } else {

        this.context.playData(true)
        this.context.contextIdData(this.state.indexId)
        this.context.songData(this.state.songDetails)
        SoundPlayer.pause()
      }
    }
    else {
      this.context.playData(true)
      this.context.contextIdData(this.state.indexId)
      this.context.songData(this.state.songDetails)
      SoundPlayer.pause()
    }

  }
}

idGenerator = (e:any) => {
  console.log('idGenerator', e)
}




handleProfile = () => {
 console.log("Image vala bug ",this.props.navigation.state.params);
 
    // this.props.navigation.navigate('CustomisableUserProfiles3', {
    //   anotherProfileId: item?.attributes?.account?.data?.id ? item?.attributes?.account?.data?.id : '',
    //   anotherProfileEmail: item?.attributes?.account?.data?.attributes?.email ? item?.attributes?.account?.data?.attributes?.email : '',
    // })
  
}

onLikePress = () => {
  console.log('onLikePress')
}

_rightBubbleFunction = async(e:any) => {
  console.log(e?._id,"e?._id")
  let newState = this.state.messages.map(obj => {
    // 👇️ if id equals 2, update country property
    if (obj._id === e?._id + 1) {
      return {...obj, is_favourite:true};
    }

    // 👇️ otherwise return the object as is
    return obj;
  });

 this.setState({messages:newState})

}



}