Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.orisoft.app.unifymobile.Service;
- /**
- * Created by Developer on 20/01/2017.
- */
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.text.TextUtils;
- import androidx.appcompat.app.AlertDialog;
- import androidx.localbroadcastmanager.content.LocalBroadcastManager;
- import com.orisoft.app.unifymobile.AppSingleton;
- import com.orisoft.app.unifymobile.Constant;
- import com.orisoft.app.unifymobile.Model.JoinRoomResp;
- import com.orisoft.app.unifymobile.Model.Message;
- import com.orisoft.app.unifymobile.Model.SendMessageResp;
- import com.orisoft.app.unifymobile.Model.SignOnResp;
- import java.util.concurrent.ExecutionException;
- import microsoft.aspnet.signalr.client.Action;
- import microsoft.aspnet.signalr.client.ConnectionState;
- import microsoft.aspnet.signalr.client.LogLevel;
- import microsoft.aspnet.signalr.client.Logger;
- import microsoft.aspnet.signalr.client.Platform;
- import microsoft.aspnet.signalr.client.SignalRFuture;
- import microsoft.aspnet.signalr.client.StateChangedCallback;
- import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
- import microsoft.aspnet.signalr.client.hubs.HubConnection;
- import microsoft.aspnet.signalr.client.hubs.HubProxy;
- import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
- import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;
- import timber.log.Timber;
- public class SignalRHubConnection {
- // HubConnection
- public HubConnection mHubConnection;
- public HubProxy mHubProxy;
- public String mConnectionID;
- private SignalRFuture<Void> signalRFuture;
- private Logger logger;
- private Context context;
- private ServerSentEventsTransport clientTransport;
- public SignalRHubConnection(Context context) {
- this.context = context;
- }
- public void startSignalR() {
- if(!TextUtils.isEmpty(AppSingleton.Companion.getInstance().getAccessToken()) && null == mHubConnection){
- final String serverUrl = Constant.Companion.getSignalRURL();
- String accessToken = AppSingleton.Companion.getInstance().getAccessToken().replace(" ","=");
- final String modifyToken = accessToken.replace("bearer","Bearer");
- try {
- Platform.loadPlatformComponent(new AndroidPlatformComponent());
- logger = new Logger() {
- @Override
- public void log(String message, LogLevel level) {
- Timber.tag("HubConnection").d(message);
- }
- };
- mHubConnection = new HubConnection(serverUrl, modifyToken, false, logger);
- mHubProxy = mHubConnection.createHubProxy("ChatHub");
- if(null == clientTransport)
- clientTransport = new ServerSentEventsTransport(logger);
- signalRFuture = mHubConnection.start(clientTransport);
- signalRFuture.get();
- //set connection id
- mConnectionID = mHubConnection.getConnectionId();
- mHubConnection.stateChanged(new StateChangedCallback() {
- @Override
- public void stateChanged(ConnectionState oldState, ConnectionState newState) {
- Timber.tag("SignalR").d("Connection State : " + oldState.toString() + " ==> " + newState.toString());
- if (newState == ConnectionState.Connected) {
- invokeRegister();
- }
- if(newState == ConnectionState.Disconnected){
- connect();
- }
- }
- });
- } catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
- }
- // Tasks.executeInBackground(context, new BackgroundWork<HubConnection>() {
- // @Override
- // public HubConnection doInBackground() {
- //
- //
- // return mHubConnection;
- // }
- // }, new Completion<HubConnection>() {
- // @Override
- // public void onSuccess(Context context, HubConnection con) {
- // if(null != con) {
- // mHubConnection = con;
- //
- //// mHubConnection.received(new MessageReceivedHandler() {
- //// @Override
- //// public void onMessageReceived(JsonElement json) {
- //// Timber.tag("SignalROnReceived").d("RAW received message :" + json.toString());
- //// }
- //// });
- ////
- //// if(null != mHubProxy){
- //// mHubProxy.on("onReceiveMessage", new SubscriptionHandler1<Object>() {
- //// @Override
- //// public void run(final Object msg) {
- //// try {
- //// JSONObject responseObject = new JSONObject(msg.toString());
- //// Timber.tag("OnReceiveMessage").d(responseObject.toString());
- //// } catch (Exception e) {
- //// e.printStackTrace();
- //// }
- //// }
- //// }, Object.class);
- //// }
- // }
- // }
- // @Override
- // public void onError(Context context, Exception e) {
- //
- // }
- // });
- }
- else{
- Timber.tag("SignalR").d("is running");
- }
- }
- public void invokeRegister() {
- if (null != mHubProxy) {
- mHubProxy.invoke(SignOnResp.class, "SignOn").done(new Action<SignOnResp>() {
- @Override
- public void run(SignOnResp obj) throws Exception {
- broadcastStatus(context);
- }
- });
- }
- }
- public void disconnect() {
- if (null != mHubConnection) {
- mHubConnection.disconnect();
- mHubConnection = null;
- }
- }
- public void connect() {
- if (null != mHubConnection) {
- logger = new Logger() {
- @Override
- public void log(String message, LogLevel level) {
- Timber.tag("SignalR").d(message);
- }
- };
- if (!TextUtils.isEmpty(AppSingleton.Companion.getInstance().getAccessToken())) {
- try {
- if(null == clientTransport)
- clientTransport = new ServerSentEventsTransport(logger);
- signalRFuture = mHubConnection.start(clientTransport);
- signalRFuture.get();
- } catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
- }
- //set connection id
- mConnectionID = mHubConnection.getConnectionId();
- }
- }
- }
- public void joinRoom(int employeeId, Action<JoinRoomResp> action) {
- SignalRFuture<JoinRoomResp> doneCallback = mHubProxy.invoke(JoinRoomResp.class, "JoinRoom", employeeId);
- doneCallback.done(action);
- }
- public void sendMessage(int employeeId, String message, Action<SendMessageResp> action){
- Timber.tag("SendMsg").d(employeeId+","+message);
- if (ConnectionState.Disconnected == mHubConnection.getState()) {
- if(null == logger){
- logger = new Logger() {
- @Override
- public void log(String message, LogLevel level) {
- Timber.tag("SignalR").d(message);
- }
- };
- }
- if(null == clientTransport)
- clientTransport = new ServerSentEventsTransport(logger);
- mHubConnection.start(clientTransport).done(new Action<Void>() {
- @Override
- public void run(Void obj) throws Exception {
- SignalRFuture<SendMessageResp> sendMsgCallback = mHubProxy.invoke(SendMessageResp.class, "SendMessageTo", employeeId, message.trim());
- sendMsgCallback.done(action);
- }
- });
- }
- else if (ConnectionState.Connected == mHubConnection.getState()) {
- SignalRFuture<SendMessageResp> sendMsgCallback = mHubProxy.invoke(SendMessageResp.class, "SendMessageTo", employeeId, message.trim());
- sendMsgCallback.done(action);
- }
- else {
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setMessage("We are experiencing difficulty communicating with the server. Please try again.");
- builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- builder.show();
- }
- }
- public void markMessageAsRead(int roomId, String message){
- SignalRFuture<SendMessageResp> markMessageCallback = mHubProxy.invoke(SendMessageResp.class, "MarkMessagesAsRead", roomId, message);
- markMessageCallback.done(new Action<SendMessageResp>() {
- @Override
- public void run(SendMessageResp s) throws Exception {
- Timber.tag("MarkMessage").d(s.toString());
- }
- });
- }
- public void leaveRoom(String roomName){
- if(null != mHubProxy){
- SignalRFuture<SignOnResp> markMessageCallback = mHubProxy.invoke(SignOnResp.class, "LeaveRoom", roomName);
- markMessageCallback.done(new Action<SignOnResp>() {
- @Override
- public void run(SignOnResp s) throws Exception {
- Timber.tag("LeaveRoom").d(s.toString());
- }
- });
- }
- }
- public void listenToMessage(SubscriptionHandler1<Message> handler){
- if(null != mHubProxy){
- mHubProxy.on("addChatMessage", handler, Message.class);
- }
- }
- public void listenToUnread(SubscriptionHandler1<SignOnResp> handler){
- if(null != mHubProxy){
- mHubProxy.on("unreadForEmployee", handler, SignOnResp.class);
- }
- }
- // public static void sendMessage(Context context, final String userId, final String companyId, final String message, final String jobId, final String roomId ) {
- // if (MainApplication.getInstance().getUser() != null) {
- // User user = MainApplication.getInstance().getUser();
- //
- // if (ConnectionState.Disconnected == mHubConnection.getState())
- // {
- // logger = new Logger() {
- // @Override
- // public void log(String message, LogLevel level) {
- // Log.i("SignalR : " ,message);
- // }
- // };
- //
- // ClientTransport clientTransport = new ServerSentEventsTransport(logger);
- //
- // mHubConnection.start(clientTransport)
- // .done(new Action<Void>() {
- // @Override
- // public void run(Void obj) throws Exception {
- // mHubProxy.invoke("SendPrivateMessage", userId, companyId, message, jobId, roomId);
- // }
- // });
- // }
- // else if (ConnectionState.Connected == mHubConnection.getState())
- // {
- // mHubProxy.invoke("SendPrivateMessage", userId, companyId, message, jobId, roomId);
- // }
- // else
- // {
- // AlertDialog.Builder builder = new AlertDialog.Builder(context);
- // builder.setMessage("We are experiencing difficulty communicating with the server. Please try again.");
- // builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
- // @Override
- // public void onClick(DialogInterface dialog, int which) {
- // dialog.dismiss();
- // }
- // });
- // builder.show();
- // }
- // }
- // }
- private void broadcastStatus(Context context){
- Intent in = new Intent("SignalRService");
- LocalBroadcastManager.getInstance(context).sendBroadcast(in);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement