Thursday, 28 February 2019

How can I invite a user to a newly created private chat channel using the Twilio?

I have created a private channel, and joined the channel. I like to invite another user to join that channel and chat. To be clear, this should be a chat between two members only.

public class MainActivity extends AppCompatActivity {
        /*
       Change this URL to match the token URL for your Twilio Function
    */
    final static String SERVER_TOKEN_URL = "https://example.com/twilio/token/";

    final static String MY_CHANNEL_NAME = "testchat1234567810";
    final static String TAG = "TwilioChat";

    // Update this identity for each individual user, for instance after they login
    private String mIdentity ;
    private String accessToken;
    private RecyclerView mMessagesRecyclerView;
    private MessagesAdapter mMessagesAdapter;
    private ArrayList<Message> mMessages = new ArrayList<>();

    private EditText mWriteMessageEditText;
    private Button mSendChatMessageButton;

    private ChatClient mChatClient;

    private Channel mGeneralChannel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMessagesRecyclerView = (RecyclerView) findViewById(R.id.messagesRecyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        // for a chat app, show latest at the bottom
        layoutManager.setStackFromEnd(true);
        mMessagesRecyclerView.setLayoutManager(layoutManager);

        mMessagesAdapter = new MessagesAdapter();
        mMessagesRecyclerView.setAdapter(mMessagesAdapter);

        mWriteMessageEditText = (EditText) findViewById(R.id.writeMessageEditText);

        mSendChatMessageButton = (Button) findViewById(R.id.sendChatMessageButton);

        mSendChatMessageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createOrJoinChannel();
                if (mGeneralChannel != null) {

                    String messageBody = mWriteMessageEditText.getText().toString();
                    Message.Options options = Message.options().withBody(messageBody);
                    // mGeneralChannel.getMembers().add();
                    Members members = mGeneralChannel.getMembers();
                    if (members != null) {
                        ArrayList<Member> list = (ArrayList<Member>) members.getMembersList();
                        for (int i = 0; i < list.size(); i++) {
                            Log.i(TAG, "member " + i + list.get(i).getIdentity());
                        }
                    }
                    mGeneralChannel.getMembers().inviteByIdentity("user1@gmail.com", new StatusListener() {
                        @Override
                        public void onSuccess() {
                            Log.d(TAG, "User Invited on send!");

                        }

                        @Override
                        public void onError(ErrorInfo errorInfo) {
                            Log.i(TAG, "chats: inviting user" + errorInfo.getMessage());
                        }
                    });

                    mGeneralChannel.getMembersCount(new CallbackListener<Long>() {
                        @Override
                        public void onSuccess(Long aLong) {
                            Log.e("member count >>", aLong + "");
                        }
                    });
                    mGeneralChannel.getMessages().sendMessage(options, new CallbackListener<Message>() {
                        @Override
                        public void onSuccess(Message message) {
                            MainActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Log.d(TAG, "Message created");
                                    // need to modify user interface elements on the UI thread
                                    mWriteMessageEditText.setText("");
                                }
                            });
                        }
                    });
                }
            }
        });

        retrieveAccessTokenfromServer();



    }



    private void retrieveAccessTokenfromServer() {
        String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
Log.e("deviceid >>",deviceId);
        String tokenURL = SERVER_TOKEN_URL + deviceId;

        Ion.with(this)
                .load(tokenURL)
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {
                        Log.e("result >>", result.toString() + "");
                        if (e == null) {
                            mIdentity = result.get("identity").getAsString();
                            accessToken = result.get("token").getAsString();
                            setTitle(mIdentity);

                            ChatClient.Properties.Builder builder = new ChatClient.Properties.Builder();
                         //   ChatClient.setLogLevel(Log.VERBOSE);
                            ChatClient.Properties props = builder.createProperties();
                            ChatClient.create(MainActivity.this, accessToken, props, mChatClientCallback);

                        } else {
                            Toast.makeText(MainActivity.this,
                                    R.string.error_retrieving_access_token, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                });
    }

    private CallbackListener<ChatClient> mChatClientCallback =
            new CallbackListener<ChatClient>() {
                @Override
                public void onSuccess(ChatClient chatClient) {
                    mChatClient = chatClient;
                    //   createOrJoinChannel();
                    //  loadChannels();
                    Log.d(TAG, "Success creating Twilio Chat Client");
                }

                @Override
                public void onError(ErrorInfo errorInfo) {
                    Log.e(TAG, "Error creating Twilio Chat Client: " + errorInfo.getMessage());
                }


            };



    private void createOrJoinChannel() {
        //Only SID or unique name of channel can be supplied as parameter
        mChatClient.getChannels().getChannel(MY_CHANNEL_NAME, new CallbackListener<Channel>() {

            @Override
            public void onSuccess(Channel channel) {
                if (channel != null) {
                    if (channel.getStatus() == Channel.ChannelStatus.JOINED) {
                        // already in the channel, load the messages
                        mGeneralChannel = channel;
                        mGeneralChannel.addListener(mDefaultChannelListener);
                    } else if (channel.getStatus() == Channel.ChannelStatus.NOT_PARTICIPATING) {
                        // already in the channel, load the messages
                        mGeneralChannel = channel;
                        mGeneralChannel.addListener(mDefaultChannelListener);
                    } else {
                        // join the channel
                        joinChannel(channel);
                    }

                } else {
                    Log.i(TAG, "Error occurred in getting channel");
                }
            }

            @Override
            public void onError(ErrorInfo errorInfo) {
                Log.i(TAG, "Error retrieving channel: " + errorInfo.getMessage());
                createChannel();
            }

        });
    }

    private void joinChannel(final Channel channel) {
        Log.i(TAG, "inside join channel" + channel.getUniqueName());
        Log.i(TAG, "channel status: " + channel.getStatus());

        Members members = channel.getMembers();
        if (members != null) {
            ArrayList<Member> list = (ArrayList<Member>) members.getMembersList();
            for (int i = 0; i < list.size(); i++) {
                Log.i(TAG, "member " + i + list.get(i).getIdentity());
            }
        } else {
            Log.i(TAG, "null object"); //Getting this even when I get
            //"Member already exists" error
        }
        channel.join(new StatusListener() {
            @Override
            public void onSuccess() {
                mGeneralChannel = channel;
                mGeneralChannel.addListener(mDefaultChannelListener);
            }

            @Override
            public void onError(ErrorInfo errorInfo) {
                //Error joining channel: Member already exists
                Log.i(TAG, "Error joining channel: " + errorInfo.getMessage());
            }
        });
    }


    private void createChannel() {
        mChatClient.getChannels().createChannel(MY_CHANNEL_NAME,
                Channel.ChannelType.PUBLIC, new CallbackListener<Channel>() {
                    @Override
                    public void onSuccess(final Channel channel) {
                        if (channel != null) {
                               /* channel.getMembersCount(new CallbackListener<Long>() {
                                    @Override
                                    public void onSuccess(Long aLong) {
                                        Log.e("member count >>",aLong+"");
                                    }
                                });*/
                            channel.getMembers().inviteByIdentity("user1@gmail.com", new StatusListener() {
                                @Override
                                public void onSuccess() {
                                    Log.d(TAG, "User Invited!");
                                }

                                @Override
                                public void onError(ErrorInfo errorInfo) {
                                    Log.i(TAG, "chats: inviting user" + errorInfo.getMessage());
                                }
                            });
                            channel.join(new StatusListener() {
                                @Override
                                public void onSuccess() {

                                }
                            });
                            setUniqueNameAndJoin(channel);
                        }
                    }

                    @Override
                    public void onError(ErrorInfo errorInfo) {
                        Log.i(TAG, "chats: " + "Unique name could not be set: " + errorInfo.getMessage());
                    }
                });
    }

    private void setUniqueNameAndJoin(final Channel channel) {
        channel.setUniqueName(MY_CHANNEL_NAME, new StatusListener() {
            @Override
            public void onSuccess() {
                Log.i(TAG, "channel with unique name created " + channel.getUniqueName());
                joinChannel(channel);
            }

            @Override
            public void onError(ErrorInfo errorInfo) {
                super.onError(errorInfo);
            }
        });
    }

    private ChannelListener mDefaultChannelListener = new ChannelListener() {


        @Override
        public void onMessageAdded(final Message message) {
            Log.d(TAG, "Message added");
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // need to modify user interface elements on the UI thread
                    mMessages.add(message);
                    mMessagesAdapter.notifyDataSetChanged();
                }
            });

        }

        @Override
        public void onMessageUpdated(Message message, Message.UpdateReason updateReason) {
            Log.d(TAG, "Message updated: " + message.getMessageBody());
        }

        @Override
        public void onMessageDeleted(Message message) {
            Log.d(TAG, "Message deleted");
        }

        @Override
        public void onMemberAdded(Member member) {
            Log.d(TAG, "Member added: " + member.getIdentity());
        }

        @Override
        public void onMemberUpdated(Member member, Member.UpdateReason updateReason) {
            Log.d(TAG, "Member updated: " + member.getIdentity());
        }

        @Override
        public void onMemberDeleted(Member member) {
            Log.d(TAG, "Member deleted: " + member.getIdentity());
        }

        @Override
        public void onTypingStarted(Channel channel, Member member) {
            Log.d(TAG, "Started Typing: " + member.getIdentity());
        }

        @Override
        public void onTypingEnded(Channel channel, Member member) {
            Log.d(TAG, "Ended Typing: " + member.getIdentity());
        }

        @Override
        public void onSynchronizationChanged(Channel channel) {

        }
    };


    class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.ViewHolder> {

        class ViewHolder extends RecyclerView.ViewHolder {

            public TextView mMessageTextView;

            public ViewHolder(TextView textView) {
                super(textView);
                mMessageTextView = textView;
            }
        }

        public MessagesAdapter() {

        }

        @Override
        public MessagesAdapter
                .ViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
            TextView messageTextView = (TextView) LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.message_text_view, parent, false);
            return new ViewHolder(messageTextView);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Message message = mMessages.get(position);
            String messageText = String.format("%s: %s", message.getAuthor(), message.getMessageBody());
            holder.mMessageTextView.setText(messageText);

        }

        @Override
        public int getItemCount() {
            return mMessages.size();
        }
    }



}

And also, I need to accept the invite. How it can be done?



from How can I invite a user to a newly created private chat channel using the Twilio?

No comments:

Post a Comment