Advertisement
vergepuppeter

SignalR

Nov 23rd, 2020
724
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.73 KB | None | 0 0
  1. package com.orisoft.app.unifymobile.Service;
  2.  
  3. /**
  4.  * Created by Developer on 20/01/2017.
  5.  */
  6.  
  7. import android.content.Context;
  8. import android.content.DialogInterface;
  9. import android.content.Intent;
  10. import android.text.TextUtils;
  11. import androidx.appcompat.app.AlertDialog;
  12. import androidx.localbroadcastmanager.content.LocalBroadcastManager;
  13. import com.orisoft.app.unifymobile.AppSingleton;
  14. import com.orisoft.app.unifymobile.Constant;
  15. import com.orisoft.app.unifymobile.Model.JoinRoomResp;
  16. import com.orisoft.app.unifymobile.Model.Message;
  17. import com.orisoft.app.unifymobile.Model.SendMessageResp;
  18. import com.orisoft.app.unifymobile.Model.SignOnResp;
  19. import java.util.concurrent.ExecutionException;
  20. import microsoft.aspnet.signalr.client.Action;
  21. import microsoft.aspnet.signalr.client.ConnectionState;
  22. import microsoft.aspnet.signalr.client.LogLevel;
  23. import microsoft.aspnet.signalr.client.Logger;
  24. import microsoft.aspnet.signalr.client.Platform;
  25. import microsoft.aspnet.signalr.client.SignalRFuture;
  26. import microsoft.aspnet.signalr.client.StateChangedCallback;
  27. import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
  28. import microsoft.aspnet.signalr.client.hubs.HubConnection;
  29. import microsoft.aspnet.signalr.client.hubs.HubProxy;
  30. import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
  31. import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;
  32. import timber.log.Timber;
  33.  
  34. public class SignalRHubConnection {
  35.     // HubConnection
  36.     public HubConnection mHubConnection;
  37.     public HubProxy mHubProxy;
  38.     public String mConnectionID;
  39.     private SignalRFuture<Void> signalRFuture;
  40.     private Logger logger;
  41.     private Context context;
  42.     private ServerSentEventsTransport clientTransport;
  43.  
  44.     public SignalRHubConnection(Context context) {
  45.         this.context = context;
  46.     }
  47.  
  48.     public void startSignalR() {
  49.         if(!TextUtils.isEmpty(AppSingleton.Companion.getInstance().getAccessToken()) && null == mHubConnection){
  50.  
  51.             final String serverUrl = Constant.Companion.getSignalRURL();
  52.             String accessToken = AppSingleton.Companion.getInstance().getAccessToken().replace(" ","=");
  53.             final String modifyToken = accessToken.replace("bearer","Bearer");
  54.  
  55.             try {
  56.                 Platform.loadPlatformComponent(new AndroidPlatformComponent());
  57.  
  58.                 logger = new Logger() {
  59.                     @Override
  60.                     public void log(String message, LogLevel level) {
  61.                         Timber.tag("HubConnection").d(message);
  62.                     }
  63.                 };
  64.  
  65.                 mHubConnection = new HubConnection(serverUrl, modifyToken, false, logger);
  66.                 mHubProxy = mHubConnection.createHubProxy("ChatHub");
  67.  
  68.                 if(null == clientTransport)
  69.                     clientTransport = new ServerSentEventsTransport(logger);
  70.  
  71.                 signalRFuture = mHubConnection.start(clientTransport);
  72.                 signalRFuture.get();
  73.                 //set connection id
  74.                 mConnectionID = mHubConnection.getConnectionId();
  75.  
  76.                 mHubConnection.stateChanged(new StateChangedCallback() {
  77.                     @Override
  78.                     public void stateChanged(ConnectionState oldState, ConnectionState newState) {
  79.                         Timber.tag("SignalR").d("Connection State : " + oldState.toString() + " ==> " + newState.toString());
  80.                         if (newState == ConnectionState.Connected) {
  81.                             invokeRegister();
  82.                         }
  83.  
  84.                         if(newState == ConnectionState.Disconnected){
  85.                             connect();
  86.                         }
  87.                     }
  88.                 });
  89.  
  90.  
  91.             } catch (InterruptedException | ExecutionException e) {
  92.                 e.printStackTrace();
  93.  
  94.             }
  95.  
  96. //            Tasks.executeInBackground(context, new BackgroundWork<HubConnection>() {
  97. //                @Override
  98. //                public HubConnection doInBackground() {
  99. //
  100. //
  101. //                    return mHubConnection;
  102. //                }
  103. //            }, new Completion<HubConnection>() {
  104. //                @Override
  105. //                public void onSuccess(Context context, HubConnection con) {
  106. //                    if(null != con) {
  107. //                        mHubConnection = con;
  108. //
  109. ////                        mHubConnection.received(new MessageReceivedHandler() {
  110. ////                            @Override
  111. ////                            public void onMessageReceived(JsonElement json) {
  112. ////                                Timber.tag("SignalROnReceived").d("RAW received message :" + json.toString());
  113. ////                            }
  114. ////                        });
  115. ////
  116. ////                        if(null != mHubProxy){
  117. ////                            mHubProxy.on("onReceiveMessage", new SubscriptionHandler1<Object>() {
  118. ////                                @Override
  119. ////                                public void run(final Object msg) {
  120. ////                                    try {
  121. ////                                        JSONObject responseObject = new JSONObject(msg.toString());
  122. ////                                        Timber.tag("OnReceiveMessage").d(responseObject.toString());
  123. ////                                    } catch (Exception e) {
  124. ////                                        e.printStackTrace();
  125. ////                                    }
  126. ////                                }
  127. ////                            }, Object.class);
  128. ////                        }
  129. //                    }
  130. //                }
  131. //                @Override
  132. //                public void onError(Context context, Exception e) {
  133. //
  134. //                }
  135. //            });
  136.         }
  137.         else{
  138.             Timber.tag("SignalR").d("is running");
  139.         }
  140.     }
  141.  
  142.     public void invokeRegister() {
  143.         if (null != mHubProxy) {
  144.             mHubProxy.invoke(SignOnResp.class, "SignOn").done(new Action<SignOnResp>() {
  145.                 @Override
  146.                 public void run(SignOnResp obj) throws Exception {
  147.                     broadcastStatus(context);
  148.                 }
  149.             });
  150.         }
  151.     }
  152.  
  153.     public void disconnect() {
  154.         if (null != mHubConnection) {
  155.             mHubConnection.disconnect();
  156.             mHubConnection = null;
  157.         }
  158.     }
  159.  
  160.     public void connect() {
  161.         if (null != mHubConnection) {
  162.             logger = new Logger() {
  163.                 @Override
  164.                 public void log(String message, LogLevel level) {
  165.                     Timber.tag("SignalR").d(message);
  166.                 }
  167.             };
  168.  
  169.             if (!TextUtils.isEmpty(AppSingleton.Companion.getInstance().getAccessToken())) {
  170.                 try {
  171.                     if(null == clientTransport)
  172.                         clientTransport = new ServerSentEventsTransport(logger);
  173.  
  174.                     signalRFuture = mHubConnection.start(clientTransport);
  175.                     signalRFuture.get();
  176.                 } catch (InterruptedException | ExecutionException e) {
  177.                     e.printStackTrace();
  178.                 }
  179.                 //set connection id
  180.                 mConnectionID = mHubConnection.getConnectionId();
  181.             }
  182.         }
  183.  
  184.     }
  185.  
  186.     public void joinRoom(int employeeId, Action<JoinRoomResp> action) {
  187.         SignalRFuture<JoinRoomResp> doneCallback = mHubProxy.invoke(JoinRoomResp.class, "JoinRoom", employeeId);
  188.         doneCallback.done(action);
  189.     }
  190.  
  191.     public void sendMessage(int employeeId, String message, Action<SendMessageResp> action){
  192.  
  193.         Timber.tag("SendMsg").d(employeeId+","+message);
  194.         if (ConnectionState.Disconnected == mHubConnection.getState()) {
  195.             if(null == logger){
  196.                 logger = new Logger() {
  197.                     @Override
  198.                     public void log(String message, LogLevel level) {
  199.                         Timber.tag("SignalR").d(message);
  200.                     }
  201.                 };
  202.             }
  203.  
  204.             if(null == clientTransport)
  205.                 clientTransport = new ServerSentEventsTransport(logger);
  206.  
  207.             mHubConnection.start(clientTransport).done(new Action<Void>() {
  208.                 @Override
  209.                 public void run(Void obj) throws Exception {
  210.                     SignalRFuture<SendMessageResp> sendMsgCallback = mHubProxy.invoke(SendMessageResp.class, "SendMessageTo", employeeId, message.trim());
  211.                     sendMsgCallback.done(action);
  212.                 }
  213.             });
  214.         }
  215.         else if (ConnectionState.Connected == mHubConnection.getState()) {
  216.             SignalRFuture<SendMessageResp> sendMsgCallback = mHubProxy.invoke(SendMessageResp.class, "SendMessageTo", employeeId, message.trim());
  217.             sendMsgCallback.done(action);
  218.         }
  219.         else {
  220.             AlertDialog.Builder builder = new AlertDialog.Builder(context);
  221.             builder.setMessage("We are experiencing difficulty communicating with the server. Please try again.");
  222.             builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
  223.                 @Override
  224.                 public void onClick(DialogInterface dialog, int which) {
  225.                     dialog.dismiss();
  226.                 }
  227.             });
  228.             builder.show();
  229.         }
  230.     }
  231.  
  232.     public void markMessageAsRead(int roomId, String message){
  233.         SignalRFuture<SendMessageResp> markMessageCallback = mHubProxy.invoke(SendMessageResp.class, "MarkMessagesAsRead", roomId, message);
  234.         markMessageCallback.done(new Action<SendMessageResp>() {
  235.             @Override
  236.             public void run(SendMessageResp s) throws Exception {
  237.                 Timber.tag("MarkMessage").d(s.toString());
  238.             }
  239.         });
  240.     }
  241.  
  242.     public void leaveRoom(String roomName){
  243.         if(null != mHubProxy){
  244.             SignalRFuture<SignOnResp> markMessageCallback = mHubProxy.invoke(SignOnResp.class, "LeaveRoom", roomName);
  245.             markMessageCallback.done(new Action<SignOnResp>() {
  246.                 @Override
  247.                 public void run(SignOnResp s) throws Exception {
  248.                     Timber.tag("LeaveRoom").d(s.toString());
  249.                 }
  250.             });
  251.         }
  252.     }
  253.  
  254.     public void listenToMessage(SubscriptionHandler1<Message> handler){
  255.         if(null != mHubProxy){
  256.             mHubProxy.on("addChatMessage", handler, Message.class);
  257.         }
  258.     }
  259.  
  260.     public void listenToUnread(SubscriptionHandler1<SignOnResp> handler){
  261.         if(null != mHubProxy){
  262.             mHubProxy.on("unreadForEmployee", handler, SignOnResp.class);
  263.         }
  264.     }
  265.  
  266. //    public static void sendMessage(Context context, final String userId, final String companyId, final String message, final String jobId, final String roomId ) {
  267. //        if (MainApplication.getInstance().getUser() != null) {
  268. //            User user = MainApplication.getInstance().getUser();
  269. //
  270. //            if (ConnectionState.Disconnected == mHubConnection.getState())
  271. //            {
  272. //               logger = new Logger() {
  273. //                    @Override
  274. //                    public void log(String message, LogLevel level) {
  275. //                        Log.i("SignalR : " ,message);
  276. //                    }
  277. //                };
  278. //
  279. //                ClientTransport clientTransport = new ServerSentEventsTransport(logger);
  280. //
  281. //                mHubConnection.start(clientTransport)
  282. //                        .done(new Action<Void>() {
  283. //                            @Override
  284. //                            public void run(Void obj) throws Exception {
  285. //                                mHubProxy.invoke("SendPrivateMessage", userId, companyId, message, jobId, roomId);
  286. //                            }
  287. //                        });
  288. //            }
  289. //            else if (ConnectionState.Connected == mHubConnection.getState())
  290. //            {
  291. //                mHubProxy.invoke("SendPrivateMessage", userId, companyId, message, jobId, roomId);
  292. //            }
  293. //            else
  294. //            {
  295. //                AlertDialog.Builder builder = new AlertDialog.Builder(context);
  296. //                builder.setMessage("We are experiencing difficulty communicating with the server. Please try again.");
  297. //                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
  298. //                    @Override
  299. //                    public void onClick(DialogInterface dialog, int which) {
  300. //                        dialog.dismiss();
  301. //                    }
  302. //                });
  303. //                builder.show();
  304. //            }
  305. //        }
  306. //    }
  307.  
  308.     private void broadcastStatus(Context context){
  309.         Intent in = new Intent("SignalRService");
  310.         LocalBroadcastManager.getInstance(context).sendBroadcast(in);
  311.     }
  312.  
  313. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement