npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@armiasystems/react-native-armia-chat-sdk

v1.0.9

Published

## Getting started

Downloads

5

Readme

@armiasystems/react-native-armia-chat-sdk

Getting started

NPM

$ npm install @armiasystems/react-native-armia-chat-sdk --save

YARN

$ yarn add @armiasystems/react-native-armia-chat-sdk

Firebase Set up

For Firebase setup you need to follow this instructions

Setup the RealTime Database and Storage in Firebase with edited rules

Install dependencies

@react-native-community/async-storage, @react-native-community/masked-view @react-native-firebase/app, @react-native-firebase/auth, @react-native-firebase/database, @react-native-firebase/firestore, @react-native-firebase/storage, mobx, mobx-react, react-native-animatable, react-native-audio-recorder-player, react-native-device-info, react-native-document-picker, react-native-fast-image, react-native-fetch-blob, react-native-file-provider, react-native-file-viewer, react-native-fs, react-native-gesture-handler, react-native-image-picker, react-native-modal, react-native-permissions react-native-phone-input, react-native-reanimated, react-native-safe-area-context, react-native-screens, react-native-size-matters, react-native-snackbar, react-native-sound, react-native-svg, react-native-vector-icons,

Make sure all dependencies settings/installation are done by refering respective npm package to avoid build errors

Usage

Sign up, login using firebase email authentication


import auth from "@react-native-firebase/auth";
import database from "@react-native-firebase/database";
import {saveKey,saveUserDisplayName,saveEmail} from"@armiasystems/react-native-armia-chat-sdk/src/utils/asyncStorage";

async function register(name, email, password) {
  try {
    let result = await auth().createUserWithEmailAndPassword(email, password);
    if (result) {
      //save result
      //save userKey into async storage 
      saveKey(result.data.key);
      saveUserDisplayName(result.data.name);
      saveEmail(result.data.email);
    } else {
      console.log("error", result);
    }
  } catch (e) {
    console.log(e);
  }
}

async function login(email, password) {
  try {
    let result = await auth().signInWithEmailAndPassword(email, password);
    if (result) {
      //save result
      //save userKey into async storage 
    } else {
      console.log("error", result);
    }
  } catch (e) {
    console.log(e);
  }
}

Sign up, login using firebase phone authentication

For Firebase phone authentication you need to follow this instructions

import React, { useState} from 'react';
import auth from "@react-native-firebase/auth";
import {saveKey,saveUserDisplayName,saveEmail} from"@armiasystems/react-native-armia-chat-sdk/src/utils/asyncStorage";

function PhoneSignIn() {
   // If null, no SMS has been sent
  const [confirm, setConfirm] = useState(null);

  // verification code (OTP - One-Time-Passcode)
  const [code, setCode] = useState('');
  async function register(phoneNumber) {
    try {
      let result = await auth().signInWithPhoneNumber(phoneNumber);
      if (result) {
        //save result
        //save userKey into async storage 
      saveKey(result.data.key);
      saveUserDisplayName(result.data.name);
      saveEmail(result.data.email);
      setConfirm(confirmation);
      } else {
        console.log("error", result);
      }
    } catch (e) {
      console.log(e);
    }
  }
  async function confirmCode() {
    try {
      await confirm.confirm(code);
    } catch (error) {
      console.log('Invalid code.');
    }
  }
}

Logout


import auth from "@react-native-firebase/auth";
import database from "@react-native-firebase/database";
import {removeAllKeys} from"@armiasystems/react-native-armia-chat-sdk/src/utils/asyncStorage";

async function logout() {
  try {
    let keyFromAsync = await loadKey();
    const reference = database().ref(`/online/${keyFromAsync}`);

    reference.set(true).then(() => console.log("Online presence set"));

    // Remove the node whenever the client disconnects
    reference
      .onDisconnect()
      .remove()
      .then(() => console.log("On disconnect function configured."));
    await database()
      .ref("Users")
      .child(keyFromAsync)
      .update({ online: false });
    await database()
      .ref("Users")
      .child(keyFromAsync)
      .update({ lastSeen: Date.now() });

    onSignOut().then(async () => {
      removeAllKeys();
      await auth().signOut();
      dispatch({ type: "SIGN_OUT" });
    });
    //clear values in onSignOut function and switch the stack
  } catch (e) {
    console.error(e);
  }
}

app.js setup


import { Provider } from "mobx-react";
import stores from "@armiasystems/react-native-armia-chat-sdk/src/store";

function App() {
  return (
    <Provider {...stores}>   
       // Add the Navigation Container
    </Provider>
  );
}

export default App;

List all threads [The Conversation List]


//A class component with ConversationList component will give chat list

import ConversationList from '@armiasystems/react-native-armia-chat-sdk/src/chatComponents/conversationList';
import Conversations from '@armiasystems/react-native-armia-chat-sdk/src/store/conversation';
import ConversationItem from '@armiasystems/react-native-armia-chat-sdk/src/chatComponents/conversationItem';
import Snackbar from 'react-native-snackbar';
import moment from 'moment';
    
render(){
  let keyFromAsync = await loadKey();
  return(
  <ConversationList
    primaryColor={'#4090B3'}
    Preview={(data, index) =>
      this.CustomListItemPreview(data, index)
    }
    token={this.state.key}//keyFromAsync saved to state as 'key'
    navigation={this.props.navigation}
    contentContainerStyle={{
      paddingBottom: 80,
      flexGrow: 1,
      paddingTop: 15,
    }}
    goToDetails={() => {}}
    ref={(inst) => (this.listRef = inst)}
    deleteConversations={(item) => {
      this.deleteConversation(item);
    }}
    listEmptyComponent={this.renderListEmpty()}
    customLoader={()=>{
      //Provide any loader component
    }}
  />
  )
}


  CustomListItemPreview = (item, index) => {

    let result = '';
    let you = '';
    if (item.lastType === 'info') {
      let text = item.lastMessage;
      // Save the username to state as 'name'
      if (text.includes(this.state.name)) {
        result = text.replace(this.state.name, 'You');
      } else {
        result = item.lastMessage;
      }
    }
    if (item.lastMsgUser.split('***')[0] === item.userId) {
      you = 'true';
    }
    this.filterUnreadConversationCount(item, this.state.key);
    return (
      <ConversationItem
        isGroup={item.type === 'group'}
        navigation={this.props.navigation}
        imageSrc={item.avatarSource ? item.avatarSource : undefined}
        username={item.name ? item.name : item.email}
        bio=""
        description={

          item.type === 'group'
            ? item.lastType !== 'info'
              ? item.lastMsgUser
                ? item.lastMsgUser.split('***')[0] === item.userId
                  ? 'You' + ': ' + item.lastMessage
                  : item.lastMsgUser.split('***')[1] + ': ' + item.lastMessage
                : item.lastMessage
              : result
            : item.lastMessage
        }
        type={item.lastType}
        time={this.formatedTime(item.lastTime)}
        notification={
          item.userUnreadCount !== 0 &&
            item.userUnreadCount !== undefined &&
            item.userUnreadCount !== null
            ? item.userUnreadCount
            : ''
        }
        isBlocked={false}
        isMuted={false}
        hasStory={false}
        ownKey={this.state.key}//keyFromAsync saved to state as 'key'
        receiverKey={item.userKey}
        chatInfo={item}
        onPress={() => {
          this.onPressListItem(item);
        }}
        onLongPress={() => {
          this.deleteConversation(item);
        }}
        goToProfile={() => {
          this.onPressListItem(item);
        }}
        yourMessage={you}
      />
    );
  };

  deleteConversation = (item) => {
    if (item.type !== 'group') {
      Alert.alert('Remove', 'Do you want to remove the conversation?', [
        {
          text: 'NO',
          onPress: () => console.log('Cancel Pressed'),
        },
        {
          text: 'YES',
          onPress: async () =>
          {
            //keyFromAsync saved to state as 'key'
            Conversations.deleteConversation(this.state.key, item.key)
              .then((result) => {
                if (result) {
                  this.listRef.removeItemFromList(item.key);
                } else {
                  Snackbar.show({
                    text: 'Something went wrong, Please try again later',
                    duration: Snackbar.LENGTH_SHORT,
                  });
                }
              })
              .catch((err) => console.warn('error====>', err));
           },
        },
      ]);
    }
  };

  onPressListItem = (item) => {
        this.props.navigation.navigate('ChatView', {
        conversationKey: item.type === 'group' ? item.conversation_key : item.key,
        currentUserKey: this.state.key,//keyFromAsync saved to state as 'key'
        title: item.name ? item.name : item.email,
        imageURL: item.avatarSource,
        unreadCount: item.unreadCount,
        userkey_unreadCount: item.userkey_unreadCount,
        update: this.update(),
        lastseen: item.lastSeen,
        isOnline: item.online,
        type: item.type,
        receiverKey: item.userKey,
        chatInfo: item,
        isAGroupMember:'',
      });
  };
  renderListEmpty = () => {
    return (
      <View style={styles.emptyListContainer}>
        <Text>No chats yet</Text>
      </View>
    );
  };
   update = async () => {
    this.listRef.refreshList();
  };
  formatedTime = (time) => {
    var formatted = '';
    let timestempFormated;

    let fulltoday = new Date();
    var today =
      fulltoday.getDate() +
      '-' +
      parseInt(fulltoday.getMonth() + 1) +
      '-' +
      fulltoday.getFullYear();
    let yesterday =
      fulltoday.getDate() -
      1 +
      '-' +
      parseInt(fulltoday.getMonth() + 1) +
      '-' +
      fulltoday.getFullYear();
    if (time) {
      var timestemp = new Date(time);

      let hour = timestemp.getHours() % 12 || 12;
      let ampm = timestemp.getHours() < 12 ? ' AM' : ' PM';

      timestempFormated =
        timestemp.getDate() +
        '-' +
        parseInt(timestemp.getMonth() + 1) +
        '-' +
        timestemp.getFullYear();

      if (timestempFormated === today) {
        formatted =
          hour + ':' + ('0' + timestemp.getMinutes()).slice(-2) + ampm;
      } else if (timestempFormated === yesterday) {
        formatted = 'Yesterday';
      } else {

        formatted = moment(timestemp).format('DD/MM/YYYY');

        // formatted =
        //   ('0' + timestemp.getDate()).slice(-2) +
        //   '/' +
        //   ('0' + timestemp.getMonth()).slice(-2) +
        //   '/' +
        //   timestemp.getFullYear();
      }
    }
    return formatted;
  };

   filterUnreadConversationCount = async (data, userkey) => {
    const unreadCountVal = data.userUnreadCount;
    if (unreadCountVal !== 0) {
      if (this.state.contactsListFiltered.includes(data.conversation_key) === false) {
        this.state.contactsListFiltered.push(data.conversation_key);
      }
    }
    const count = this.state.contactsListFiltered.length;
    //  console.log('Count', count);
    if (count !== 0) {
      await database()
        .ref('Users')
        .child(userkey)
        .update({ unreadChatCount: count });
    } else {
      await database()
        .ref('Users')
        .child(userkey)
        .update({ unreadChatCount: 0 });
    }
  };

To use single contact list item


import Contact from "@armiasystems/react-native-armia-chat-sdk/src/components/contact";
import database from '@react-native-firebase/database';

<Contact
  name={item.name}
  item={item}
  avatarUrl={{
    uri: item.avatarSource !== "" ? item.avatarSource : undefined
  }}
  bio={item.bio}
  onPress={() =>
   //check whether the current user is a member of the group & then add isAGroupMember value
    startConversation(item.key).then(val => {
      //Navigate to a screen called "ChatView" that has ChatDetails component(Can be found in SDK) with below props
      //** Make sure the component name should be "ChatView" in navigator stack (Since many internal redirection are done using this route name)
    
      navigation.navigate("ChatView", {
        conversationKey: item.type === 'group' ? item.conversation_key : item.key,
        currentUserKey: key,
        title: item.name ? item.name : item.email,
        imageURL: item.avatarSource,
        unreadCount: item.unreadCount,
        userkey_unreadCount: item.userkey_unreadCount,
        update: this.update(),
        lastseen: item.lastSeen,
        isOnline: item.online,
        type: item.type,
        receiverKey: item.userKey,
        chatInfo: item,
        isAGroupMember:isAGroupMember !== undefined ? isAGroupMember : '',
      });
    })
  }
  reRenderFlatList={(index, unreadvalue) => {}}
/>;

  update = async () => {
    //Add a ref to refresh the list
  };

 startConversation = async (receiver) => {
  const keyFromAsync = await loadKey();
    try {
      let key = null;

      let Users = {};
      Users[keyFromAsync] = true;
      Users[receiver] = true;

      const snapshot = await database()
        .ref('Conversations')
        .orderByChild(keyFromAsync)
        .equalTo(true)
        .once('value');

      snapshot.forEach((item) => {
        item.forEach((subItem) => {
          if (
            subItem.key === receiver &&
            item.child('type').val() !== 'group'
          ) {
            key = item.key;
            return;
          }
        });
      });

      if (key === null || key === undefined) {
        key = await database().ref('Conversations').push(Users).key;
      }

      return Promise.resolve(key);
    } catch (error) {
      return Promise.reject(error);
    }
  };

To use chat details page

import ChatDetails from "@armiasystems/react-native-armia-chat-sdk/src/chatComponents/chatDetails";

 <ChatDetails
  conversationKey={conversationKey}
  currentUserKey={keyFromAsync}
  uri={imgUrl}
  title={title}
  goBack={() => {
    navigation.goBack();
  }}
  navigation={navigation}
  unreadCount={unreadCount}
  lastseen={lastseen}
  isOnline={isOnline}
  type={type}
  userName={userName}
  isAMemberOfGroup={
     //check whether the current user is a member of the group & then check
    isAGroupMember
    ? isAGroupMember
    : 'No'
  }
  goToProfile={() => {
    if (type === 'group') {
      //navigate to group details screen
    }
  }}
  customHeader={(isOnline, lastSeen, type, typingInfo) =>
    //Add a customHeader to chat details screen(You can refer to ChatHeader component in SDK)
  }
  placeHolder={'Type Something…'}
  customSenderMsg={(data) => {
    // Add the message component (You can refer to ChatCard component in SDK with isLeft={false}) 
  }}
  customReceiverMsg={(data) => {
     // Add the message component (You can refer to ChatCard component in SDK with isLeft={true}) 
  }}
  customFooterMainContainerStyle={{
          paddingHorizontal: 10,
          justifyContent: 'space-between',
          alignItems: 'center',
          flexDirection: 'row',
          paddingVertical: 10,
          backgroundColor: 'white',
          borderWidth: 0,
          elevation: 0,
          borderRadius: 0,
          margin: 0,
    //Messagebar container  style
  }}
  customFooterInnerContainerStyle={{
          flexDirection: 'row',
          backgroundColor: 'white',
          flex: 3,
          marginHorizontal: 10,
          paddingVertical: Platform.OS === 'ios' ? 10 : 0,
          borderRadius: 30,
          alignItems: 'center',
          justifyContent: 'space-between',
          elevation: 2,
    //Messagebar inner style
  }}
  textInputStyle={{ 
    fontWeight: '400',
    //Message bar text style
  }}
  sendIconSize={25}
  sendIconColor={'white'
    //Send icon background color
  }
  primaryColor={'#4090B3'}
  senderBg={
    '#4090B3'
    //Sender chat bubble background color
  }
  receiverBg={
     '#F5F5F5'
    //Reciever chat bubble background color
  }
  sendIconContainerStyle={{ 
     backgroundColor: '#4090B3',
    //Send button background color
  }}
  receiverKey={receiverKey}
  mediaPress={(type,url)=>{
    console.log('Type',type);
    console.log('Url',url);
    //case 'image':
         //Add image view screen
    //case 'video':
         //Add video view screen with video player
    // case 'doc':
         //Add FileViewer to open files or documents
  }
      
  }
  isVoiceShareAvailable={true}
  fileSharingEnable={true}
  isTypingIndicatorEnabled={true}
  ref={(inst) => (this.chatListRef = inst)}
  />

ChatHeader


import ChatHeader from '@armiasystems/react-native-armia-chat-sdk/src/components/chatComponents/ChatHeader';
import SDKGroup from '@armiasystems/react-native-armia-chat-sdk/src/store/group';

//Info needed for GroupDetials screen
const [groupDetails, setGroupDetails] = useState([]);
const [admin, setAdmin] = useState('');
 async function loadGroupDetails() {
    let keyFromAsync = await loadKey();
    SDKGroup.loadGroupInfo(
      keyFromAsync,
      props.route.params.conversationKey,
    ).then(result => {
      if (result) {
        setGroupDetails(result);
        if (result.data.adminKey) {
          if (keyFromAsync === result.data.adminKey) {
            setAdmin(true);
          } else {
            setAdmin(false);
          }
        }
      }
    });
  }


<ChatHeader
  type={type}
  onOpenProfile={() => {
     //Can either use SDK friendProfilePage & GroupDetails screen or provide a custom Profile screen
     //**********Usage *********

    if (type === 'group') {

       // 1) Add the  GroupDetail screen to the navigation stack
      import GroupDetails from '@armiasystems/react-native-armia-chat-sdk/src/screens/groupDetails';

      // 2) Add the below navigation step 
      navigation.navigate('GroupDetails', {
              conversationKey: conversationKey, 
              title: 'Group detail',
              addedList: groupDetails?.data.participantList,
              name: groupDetails?.data.groupName,
              profileImage: groupDetails?.data.groupImage,
              groupKey: groupDetails?.data.groupKey,
              createUserId: groupDetails?.data.createUser,
              adminKey: groupDetails?.data.adminKey,
              returnScreen:'Home' 

              // "returnScreen"-> screen which you want to return after certain function like exist/delete group

            });
    } else {

      // 1) Add the  FriendProfilePage screen to the navigation stack
      import FriendsProfilePage from '@armiasystems/react-native-armia-chat-sdk/src/screens/friendsProfilePage';

      // 2) Add the below navigation step
            navigation.navigate('FriendsProfilePage', {
              username: title,
              bio: '',
              imageSrc: imgUrl,
              isBlocked: false,
              isMuted: false,
              ownKey: key,
              receiverKey:receiverKey,
              chatInfo: chatInfo,
            });
    }
  }}
  onPress={() => navigation.goBack()}
  username={title}
  imageSrc={imgUrl}
  receiverKey={receiverKey}
  onlineStatus={
   isOnline ? 'Online' : 'Last seen at ' + this.getLastSeen(lastSeen)
  }
  lastSeen={lastSeen}
  typingInfo={typingInfo}
  />

  getLastSeen = (lastseenVal) => {
    var formatted = 'unknown';
    let lastseen = lastseenVal;
    let dispayTimestempDay = '';
    let timestempday = '';
    if (lastseen) {
      var fulltoday = new Date();
      var today =
        fulltoday.getDate() +
        '-' +
        parseInt(fulltoday.getMonth() + 1) +
        '-' +
        fulltoday.getFullYear();

      fulltoday.setDate(fulltoday.getDate() - 1);
      var yesterday =
        fulltoday.getDate() +
        '-' +
        parseInt(fulltoday.getMonth() + 1) +
        '-' +
        fulltoday.getFullYear();

      var timestemp = new Date(lastseen);
      timestempday =
        timestemp.getDate() +
        '-' +
        parseInt(timestemp.getMonth() + 1) +
        '-' +
        timestemp.getFullYear();
      dispayTimestempDay =
        (timestemp.getDate() < 9
          ? '0' + timestemp.getDate()
          : timestemp.getDate()) +
        '-' +
        (parseInt(timestemp.getMonth() + 1) < 9
          ? '0' + parseInt(timestemp.getMonth() + 1)
          : parseInt(timestemp.getMonth() + 1)) +
        '-' +
        timestemp.getFullYear();

      let hour = timestemp.getHours() % 12 || 12;
      let ampm = timestemp.getHours() < 12 ? ' AM' : ' PM';

      if (timestempday === today) {
        formatted =
          (hour >= 10 ? hour : '0' + hour) +
          ':' +
          ('0' + timestemp.getMinutes()).slice(-2) +
          ampm;
      } else if (timestempday === yesterday) {
        formatted = 'Yesterday';
      } else {
        formatted = dispayTimestempDay;
      }
    }
    return formatted;
  };

ChatCard (Message bubble)


import ChatCard from '@armiasystems/react-native-armia-chat-sdk/src/components/chatComponents/chatCard';

<ChatCard
  time={time}
  isLeft={false} //Sender=false, Reciever=true  
  chat={content}
  type={type}
  name={name}
  isSeen={isSeen}
  isDelivered={isDelivered}
  messageKey={messageKey}
  conversationKey={conversationKey}
  deleteMsg={(messageKey, deleteValue) => {
      if (this.chatListRef) {
        //--------Sender
        //this.chatListRef.removeMessageFromList(messageKey, deleteValue);
        //---------Reciever
        //this.chatListRef.removeMessageFromList(messageKey);
      }
    //Do function to remove message
  }}
  showAvatar={showAvatar}
  messageType={messageType}
  />

Searching users


import database from '@react-native-firebase/database';

const snapshot = await database()
  .ref('Users')
  .once('value');
let contacts = []
snapshot.forEach(item => {
  if (item.val().name) {
    if (
      item
        .val()
        .name.toLowerCase()
        .includes(text.toLowerCase())
    ) {
      const contact = {
        key: item.key,
        lastTime: '',
        lastMessage: ''
        ...item.val(),
      };
      if (item.key !== key) {
        contacts.push(contact);
      }
    }
  }
});

Block & Unblock user


import database from '@react-native-firebase/database';
import {Alert} from 'react-native';

async function fetchBlockUserList (shouldBlock) {
  let keyFromAsync = await loadKey(); //ownKey
  const referencePath = '/blocked/' + keyFromAsync;
  database().ref(referencePath)once('value').then((snapshot) => {
    let blockList = [];
    if (snapshot.val() != null && snapshot.val().length !== 0) {
      blockList = snapshot.val();
    }
    if (shouldBlock) {
      Alert.alert('Block', 'Are you sure you want to block?', [
        {
          text: 'Cancel',
          style: 'cancel',
        },
        { text: 'Block', onPress: () => blockTheUser(blockList) },
      ]);
    } else {
      unblockTheUser(blockList);
    }
  });
}

async function blockTheUser(blockList){
  let keyFromAsync = await loadKey(); //ownKey
  const referencePath = '/blocked/' + keyFromAsync;

  let updatedList = blockList;
  //Push the user key which you want to block to updatedList
  updatedList.push(userkey); 
  database().ref(referencePath).set(updatedList).then(() => {
    // Save the result to state to refer whether the user is blocked or not
  });
};

async function unblockTheUser(blockList){
  let keyFromAsync = await loadKey();//ownKey
  const referencePath = '/blocked/' + keyFromAsync;

  let filtered = blockList.filter((item) => item !== userkey);
  database().ref(referencePath).set(filtered).then(() => {
    // Save the result to state to refer whether the user is blocked or not
  });
};

Creating a group


//Initailly add below screen from the SDK to the stack navigator

//Make sure the stack screen name should be same as import name(eg:GroupDetails)

import GroupDetails from '@armiasystems/react-native-armia-chat-sdk/src/screens/groupDetails';
import CreateGroup from '@armiasystems/react-native-armia-chat-sdk/src/screens/createGroup';
import AddParticipants from '@armiasystems/react-native-armia-chat-sdk/src/screens/addParticipants';


<TouchableOpacity
  onPress={() =>
 
    this.props.navigation.navigate('AddParticipants', {
      title: 'Create Group', 
      returnScreen: 'Home',//Screen which the user will redirected after group creation
      })
  }>
  <Text>Create Group</Text>
</TouchableOpacity>

//The above Touchable opacity onPress will navigate you to AddParticipants screen which is added to your app stack navigator

//Here we will see the list of user where we can select the participant and the press the botton arrow to CreateGroup with name & photo then press forward arrow in the bottom to create group

//Here a return screen  will redirect to specified screen

Image Upload

import storage from "@react-native-firebase/storage";

async function imageUpload() {
  let url = "",
    ref = "";
  let data = {
    groupSource: groupImage,
    groupRef: groupImage
  };
  if (fileName !== "") {
    const rImage = await storage()
      .ref("/groupPics/" + getFileName(fileName))
      .putFile(groupImage);

    url = await storage()
      .ref(rImage.metadata.fullPath)
      .getDownloadURL();

    ref = rImage.metadata.fullPath;

    data = {
      groupSource: url,
      groupRef: ref
    };
  }
  return data;
}

function getFileName(originalName) {
  const re = /(?:\.([^.]+))?$/;
  return "IMG-" + getFormattedTime() + "." + re.exec(originalName)[1];
}

function getFormattedTime() {
  var today = new Date();
  var y = today.getFullYear();
  var m = today.getMonth() + 1;
  var d = today.getDate();
  var h = today.getHours();
  var mi = today.getMinutes();
  var s = today.getSeconds();
  return y + "-" + m + "-" + d + "-" + h + "-" + mi + "-" + s;
}

Mini Profile


import MiniPofile from '@armiasystems/react-native-armia-chat-sdk/src/components/miniProfile';

//This component can be used inside a modal
 <MiniProfile
  isGroup={isGroup}
  username={username}
  imageSrc={imageSrc}
  bio={bio}
  isBlocked={isBlocked}
  isMuted={isMuted}
  ownKey={ownKey}
  receiverKey={receiverKey}
  chatInfo={chatInfo}
  hide={
    //set state to hide the profile (hide the modal)
  }
  navigation={navigation}
  goToProfile={() => {
             //Navigate to profile
  }}
  returnScreen={isGroup&&'Home'} //if the type is a 'group' it should have a return screen route name given
  />

Profile view


getCurrentUser = async () => {
  let key;
  let keyFromAsync = await loadKey();
  let emailFromAsync = await loadEmail();

  this.setState({
    key: keyFromAsync
  });

  if (keyFromAsync) {
    key = keyFromAsync;
  } else {
    const snapshot = await database()
      .ref("Email")
      .once("value");
    if (snapshot.val() !== null) {
      key = snapshot.val()[emailFromAsync];
      if (key === undefined) {
        return;
      }
    }
  }

  const userSnapshot = await database()
    .ref("Users")
    .child(key)
    .once("value");

  const _user = userSnapshot.val();
  if (_user) {
    this.setState({
      userDetails: _user,
      profileImage: _user.avatarSource !== undefined ? _user.avatarSource : "",
      name: _user.name
    });
  }
};

import ProfileHeader from '@armiasystems/react-native-armia-chat-sdk/src/components/profileComponents/ProfileInfo';

 <ProfileInfo
  myProfile
  username={''}
  bio=""
  profilePicture={''}
  onPressNameEdit={() => {}}
  onPressImageEdit={() => {}}
  />

Open Room Chat creation


//Add both the import to Stack navigator as a screen 

import RoomList from '@armiasystems/react-native-armia-chat-sdk/src/screens/roomList';
import RoomChat from '@armiasystems/react-native-armia-chat-sdk/src/screens/roomChat';

//Below onPress in touchableOpacity will navigate to the screen call RoomList

<TouchableOpacity
  onPress={() =>{
 //You can create any number of rooms with different name 

    this.props.navigation.navigate('RoomList', {
      hideOption: false,
      rooms:[
         { id: 'room_1', name: 'Startups' },
         { id: 'room_2', name: 'Sports' },
         { id: 'room_3', name: 'Health and Wellness' },
         { id: 'room_4', name: 'Stock Market' },
         { id: 'room_5', name: 'Travel & Tourism' },
      ],
      imageViewScreen:'', //(Image full view on press in chat)Provide the name of screen where image full view is implemented 
      videoViewScreen:'', //(Video Player screen) Provide the name of the screen where video player is implemented
      });
  }}>
  <Text>Room List</Text>
</TouchableOpacity>

Delete account

import auth from "@react-native-firebase/auth";
import database from "@react-native-firebase/database";
import {removeAllKeys} from"@armiasystems/react-native-armia-chat-sdk/src/utils/asyncStorage";

async function deleteAccount() {
  try {
    let keyFromAsync = await loadKey();
    
    await database()
      .ref("Users")
      .child(keyFromAsync)
      .update({ online: false });
    await database()
      .ref("Users")
      .child(keyFromAsync)
      .update({ lastSeen: Date.now() });
    await database()
      .ref('Users')
      .child(key)
      .update({ deletedAccount: true });
    await auth().currentUser.delete();
    onSignOut().then(async () => {
      removeAllKeys();
      await auth().signOut();
      dispatch({ type: "SIGN_OUT" });
    });
    //clear values in onSignOut function and switch the stack
  } catch (e) {
    console.error(e);
  }
}

Push Notification

For Push notification implementation, you can follow Firebase Cloud Messaging and react-native-push-notification

Check out the sample app https://gitlab.armiasystems.com/mobilelearningprojects/chatwithme.git