Commit 346e21c5 authored by Leonardo Aramaki's avatar Leonardo Aramaki

Add HelperExtensions file and convert Logger to Kotlin; consider new

connection state STATE_SESSION_ESTABLISHED when applied
parent f900423f
package chat.rocket.android
import chat.rocket.android.extensions.printStackTraceOnDebug
import chat.rocket.android.service.KeepAliveJob
import unquietcode.tools.esm.EnumStateMachine
import unquietcode.tools.esm.TransitionException
......@@ -20,6 +21,9 @@ object ConnectionStatusManager {
stateMachine.addTransitions(State.ONLINE, State.OFFLINE)
}
@Synchronized
fun transitionCount() = stateMachine.transitionCount()
@Synchronized
fun currentState() = stateMachine.currentState()
......@@ -47,7 +51,7 @@ object ConnectionStatusManager {
callback.onTransitioned(true)
} catch (e: TransitionException) {
if (DEBUG) {
e.printStackTrace()
e.printStackTraceOnDebug()
}
callback.onTransitioned(false)
}
......
......@@ -59,7 +59,7 @@ public class RocketChatApplication extends MultiDexApplication {
if (BuildConfig.DEBUG) {
e.printStackTrace();
}
Logger.report(e);
Logger.INSTANCE.report(e);
});
instance = this;
......
......@@ -2,6 +2,7 @@ package chat.rocket.android;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import com.hadisatrio.optional.Optional;
......@@ -15,7 +16,6 @@ import java.util.List;
import java.util.UUID;
import chat.rocket.android.helper.Logger;
import chat.rocket.android.helper.TextUtils;
import chat.rocket.android.log.RCLog;
import chat.rocket.core.utils.Pair;
import io.reactivex.BackpressureStrategy;
......@@ -35,8 +35,10 @@ public class RocketChatCache {
private static final String KEY_PUSH_ID = "KEY_PUSH_ID";
private static final String KEY_HOSTNAME_LIST = "KEY_HOSTNAME_LIST";
private static final String KEY_OPENED_ROOMS = "KEY_OPENED_ROOMS";
private static final String KEY_SESSION_TOKEN = "KEY_SESSION_TOKEN";
private Context context;
private String session;
public RocketChatCache(Context context) {
this.context = context.getApplicationContext();
......@@ -239,7 +241,7 @@ public class RocketChatCache {
return jsonObject.optString(getSelectedServerHostname(), null);
} catch (JSONException e) {
RCLog.e(e);
Logger.report(e);
Logger.INSTANCE.report(e);
}
return null;
}
......@@ -251,7 +253,7 @@ public class RocketChatCache {
setString(KEY_SELECTED_ROOM_ID, jsonObject.toString());
} catch (JSONException e) {
RCLog.e(e);
Logger.report(e);
Logger.INSTANCE.report(e);
}
}
......@@ -328,8 +330,41 @@ public class RocketChatCache {
null : selectedRoomIdJsonObject.toString();
setString(KEY_SELECTED_ROOM_ID, result);
} catch (JSONException e) {
Logger.report(e);
Logger.INSTANCE.report(e);
RCLog.e(e);
}
}
public void setSessionToken(String sessionToken) {
String selectedServerHostname = getSelectedServerHostname();
if (selectedServerHostname == null) {
throw new IllegalStateException("Trying to set sessionToken to null hostname");
}
String sessions = getSessionToken();
try {
JSONObject jsonObject = (sessions == null) ? new JSONObject() : new JSONObject(sessions);
jsonObject.put(selectedServerHostname, sessionToken);
setString(KEY_SESSION_TOKEN, jsonObject.toString());
} catch (JSONException e) {
RCLog.e(e);
}
}
public String getSessionToken() {
String selectedServerHostname = getSelectedServerHostname();
String sessions = getString(KEY_SESSION_TOKEN, null);
if (sessions == null || selectedServerHostname == null) {
return null;
}
try {
JSONObject jsonObject = new JSONObject(sessions);
if (jsonObject.has(selectedServerHostname)) {
return jsonObject.optString(selectedServerHostname, null);
}
} catch (JSONException e) {
RCLog.e(e);
}
return null;
}
}
......@@ -211,7 +211,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
this::updateHostnameIfNeeded,
Logger::report
Logger.INSTANCE::report
)
);
......@@ -223,7 +223,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
this::updateRoomIdIfNeeded,
Logger::report
Logger.INSTANCE::report
)
);
}
......
......@@ -66,7 +66,7 @@ public class LoginPresenter extends BasePresenter<LoginContract.View>
view.closeView();
}
},
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......
......@@ -97,12 +97,13 @@ public class MainPresenter extends BasePresenter<MainContract.View>
subscribeToNetworkChanges();
subscribeToUnreadCount();
subscribeToSession();
setUserOnline();
}
@Override
public void release() {
setUserAway();
if (rocketChatCache.getSessionToken() != null) {
setUserAway();
}
super.release();
}
......@@ -120,7 +121,7 @@ public class MainPresenter extends BasePresenter<MainContract.View>
view.showHome();
}
},
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -183,7 +184,7 @@ public class MainPresenter extends BasePresenter<MainContract.View>
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
pair -> view.showUnreadCount(pair.first, pair.second),
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -213,8 +214,9 @@ public class MainPresenter extends BasePresenter<MainContract.View>
}
// TODO: Should we remove below and above calls to view?
// view.showConnectionOk();
rocketChatCache.setSessionToken(session.getToken());
},
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -234,6 +236,7 @@ public class MainPresenter extends BasePresenter<MainContract.View>
view.showConnectionError();
}
} else if (connectivity.state == ServerConnectivity.STATE_SESSION_ESTABLISHED) {
setUserOnline();
view.refreshRoom();
view.showConnectionOk();
} else {
......
package chat.rocket.android.extensions
import chat.rocket.android.BuildConfig
fun Throwable.printStackTraceOnDebug() {
if (BuildConfig.DEBUG) {
this.printStackTrace()
}
}
\ No newline at end of file
......@@ -47,7 +47,7 @@ public class InputHostnamePresenter extends BasePresenter<InputHostnameContract.
}
},
throwable -> {
Logger.report(throwable);
Logger.INSTANCE.report(throwable);
view.showConnectionError();
});
addSubscription(subscription);
......
......@@ -540,7 +540,7 @@ public class RoomFragment extends AbstractChatRoomFragment implements
inputContentInfo.releasePermission();
} catch (Exception e) {
RCLog.e(e);
Logger.report(e);
Logger.INSTANCE.report(e);
}
return true;
......
......@@ -87,7 +87,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
connectivityManagerApi.keepAliveServer();
}
},
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -105,7 +105,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
connectivityManagerApi.keepAliveServer();
}
},
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -152,7 +152,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
view.onReply(absoluteUrl, buildReplyOrQuoteMarkdown(baseUrl, message, justQuote), message);
}
},
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -217,7 +217,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
},
throwable -> {
view.enableMessageInput();
Logger.report(throwable);
Logger.INSTANCE.report(throwable);
}
);
......@@ -251,7 +251,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
},
throwable -> {
view.enableMessageInput();
Logger.report(throwable);
Logger.INSTANCE.report(throwable);
}
);
......@@ -277,7 +277,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
count -> view.showUnreadCount(count),
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -295,7 +295,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
.subscribe(
room -> methodCallHelper.readMessages(room.getRoomId())
.continueWith(new LogIfError()),
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -312,7 +312,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
.map(Optional::get)
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::processRoom, Logger::report);
.subscribe(this::processRoom, Logger.INSTANCE::report);
addSubscription(subscription);
}
......@@ -332,7 +332,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
.map(Optional::get)
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(view::showUserStatus, Logger::report);
.subscribe(view::showUserStatus, Logger.INSTANCE::report);
addSubscription(disposable);
}
......@@ -351,7 +351,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
syncState == SyncState.SYNCED || syncState == SyncState.FAILED
);
},
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -378,7 +378,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
view::showMessages,
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -403,7 +403,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
view.manualLoadImages();
}
},
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......@@ -415,7 +415,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
it -> view.setupWith(it.orNull()),
Logger::report
Logger.INSTANCE::report
);
addSubscription(subscription);
......
......@@ -132,7 +132,7 @@ public class MessageOptionsDialogFragment extends BottomSheetDialogFragment {
((TextView) bottomSheetDialog.findViewById(R.id.message_options_info))
.setText(R.string.message_options_no_message_info);
Logger.report(throwable);
Logger.INSTANCE.report(throwable);
}
);
......
......@@ -37,7 +37,7 @@ public class OAuthPresenter extends BasePresenter<OAuthContract.View>
view.close();
}
},
Logger::report
Logger.INSTANCE::report
)
);
}
......
......@@ -53,7 +53,7 @@ public class LoginPresenter extends BasePresenter<LoginContract.View>
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
publicSettingOptional -> doLogin(username, password, publicSettingOptional),
Logger::report
Logger.INSTANCE::report
)
);
}
......@@ -65,7 +65,7 @@ public class LoginPresenter extends BasePresenter<LoginContract.View>
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
loginServiceConfigurations -> view.showLoginServices(loginServiceConfigurations),
Logger::report
Logger.INSTANCE::report
)
);
}
......
......@@ -52,7 +52,7 @@ public class RetryLoginPresenter extends BasePresenter<RetryLoginContract.View>
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
this::onSession,
Logger::report
Logger.INSTANCE::report
)
);
}
......
......@@ -239,7 +239,7 @@ public class SidebarMainFragment extends AbstractFragment implements SidebarMain
.compose(bindToLifecycle())
.subscribe(
this::showUserActionContainer,
Logger::report
Logger.INSTANCE::report
);
}
......
......@@ -80,7 +80,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
)
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(pair -> view.show(pair.first.orNull()), Logger::report);
.subscribe(pair -> view.show(pair.first.orNull()), Logger.INSTANCE::report);
addSubscription(subscription);
}
......@@ -142,7 +142,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
public void onLogout(Continuation<Void, Object> continuation) {
methodCallHelper.logout().continueWith(task -> {
if (task.isFaulted()) {
Logger.report(task.getError());
Logger.INSTANCE.report(task.getError());
return Task.forError(task.getError());
}
return task.onSuccess(continuation);
......@@ -183,7 +183,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
.distinctUntilChanged()
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::processRooms, Logger::report);
.subscribe(this::processRooms, Logger.INSTANCE::report);
addSubscription(subscription);
}
......@@ -227,7 +227,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
.distinctUntilChanged()
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::processUsers, Logger::report);
.subscribe(this::processUsers, Logger.INSTANCE::report);
addSubscription(subscription);
}
......
......@@ -47,7 +47,7 @@ public class AddChannelDialogFragment extends AbstractAddRoomDialogFragment {
.compose(bindToLifecycle())
.subscribe(
buttonAddChannel::setEnabled,
Logger::report
Logger.INSTANCE::report
);
buttonAddChannel.setOnClickListener(view -> createRoom());
......
......@@ -68,7 +68,7 @@ public class AddDirectMessageDialogFragment extends AbstractAddRoomDialogFragmen
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
this::setupView,
Logger::report
Logger.INSTANCE::report
)
);
......@@ -77,7 +77,7 @@ public class AddDirectMessageDialogFragment extends AbstractAddRoomDialogFragmen
.compose(bindToLifecycle())
.subscribe(
buttonAddDirectMessage::setEnabled,
Logger::report
Logger.INSTANCE::report
);
buttonAddDirectMessage.setOnClickListener(view -> createRoom());
......
package chat.rocket.android.helper;
import com.crashlytics.android.Crashlytics;
import com.google.firebase.crash.FirebaseCrash;
public class Logger {
public static void report(Throwable throwable) {
FirebaseCrash.report(throwable);
Crashlytics.logException(throwable);
}
}
package chat.rocket.android.helper
import com.crashlytics.android.Crashlytics
import com.google.firebase.crash.FirebaseCrash
import chat.rocket.android.BuildConfig
object Logger {
fun report(throwable: Throwable) {
if (BuildConfig.DEBUG) {
throwable.printStackTrace()
}
FirebaseCrash.report(throwable)
Crashlytics.logException(throwable)
}
}
......@@ -102,7 +102,7 @@ public class MessagePopup {
.create()
.show();
},
Logger::report
Logger.INSTANCE::report
);
compositeDisposable.add(disposable);
}
......
......@@ -101,7 +101,7 @@ public class RoomListItemViewHolder extends RecyclerView.ViewHolder {
break;
default: {
itemView.showPrivateChannelIcon();
Logger.report(new AssertionError("Room type doesn't satisfies the method documentation. Room type is:" + roomType));
Logger.INSTANCE.report(new AssertionError("Room type doesn't satisfies the method documentation. Room type is:" + roomType));
}
}
}
......
......@@ -22,6 +22,7 @@ import chat.rocket.android.BuildConfig
import chat.rocket.android.R
import chat.rocket.android.RocketChatCache
import chat.rocket.android.activity.MainActivity
import chat.rocket.android.extensions.printStackTraceOnDebug
import chat.rocket.android.helper.Logger
import chat.rocket.core.interactors.MessageInteractor
import chat.rocket.core.models.Room
......@@ -694,7 +695,6 @@ object PushManager {
.subscribe({ _ ->
// Empty
}, { throwable ->
throwable.printStackTrace()
Logger.report(throwable)
})
}
......
......@@ -31,7 +31,5 @@ public interface ConnectivityManagerApi {
void notifySessionEstablished(String hostname);
void notifyRetryingConnection(String hostname);
void notifyConnecting(String hostname);
}
package chat.rocket.android.service
import chat.rocket.android.ConnectionStatusManager
import chat.rocket.android.RocketChatApplication
import chat.rocket.android.RocketChatCache
import com.evernote.android.job.Job
......@@ -41,7 +42,15 @@ class KeepAliveJob : Job() {
}
override fun onRunJob(params: Params): Result {
connectivityManager.keepAliveServer()
if (ConnectionStatusManager.transitionCount() == 0L) {
return Result.SUCCESS
}
when (ConnectionStatusManager.currentState()) {
ConnectionStatusManager.State.CONNECTING, ConnectionStatusManager.State.ONLINE -> {
cancel()
}
else -> connectivityManager.keepAliveServer()
}
return Result.SUCCESS
}
}
\ No newline at end of file
......@@ -136,12 +136,6 @@ import io.reactivex.subjects.BehaviorSubject;
return list;
}
@Override
public void notifyRetryingConnection(String hostname) {
connectivitySubject.onNext(
new ServerConnectivity(hostname, ServerConnectivity.STATE_RETRYING_CONNECTION));
}
@Override
public void notifySessionEstablished(String hostname) {
serverConnectivityList.put(hostname, ServerConnectivity.STATE_SESSION_ESTABLISHED);
......
......@@ -99,7 +99,7 @@ public class RocketChatService extends Service implements ConnectivityServiceInt
return Single.defer(() -> {
webSocketThreadLock.acquire();
int connectivityState = ConnectivityManager.getInstance(getApplicationContext()).getConnectivityState(hostname);
boolean isDisconnected = connectivityState != ServerConnectivity.STATE_CONNECTED;
boolean isDisconnected = connectivityState < ServerConnectivity.STATE_CONNECTED ;
if (currentWebSocketThread != null && existsThreadForHostname(hostname) && !isDisconnected) {
webSocketThreadLock.release();
return Single.just(currentWebSocketThread);
......@@ -117,7 +117,7 @@ public class RocketChatService extends Service implements ConnectivityServiceInt
.doOnError(throwable -> {
currentWebSocketThread = null;
RCLog.e(throwable);
Logger.report(throwable);
Logger.INSTANCE.report(throwable);
webSocketThreadLock.release();
})
);
......@@ -131,7 +131,7 @@ public class RocketChatService extends Service implements ConnectivityServiceInt
.doOnError(throwable -> {
currentWebSocketThread = null;
RCLog.e(throwable);
Logger.report(throwable);
Logger.INSTANCE.report(throwable);
webSocketThreadLock.release();
});
});
......
......@@ -29,7 +29,6 @@ import chat.rocket.android.service.observer.FileUploadingWithUfsObserver;
import chat.rocket.android.service.observer.GcmPushRegistrationObserver;
import chat.rocket.android.service.observer.GetUsersOfRoomsProcedureObserver;
import chat.rocket.android.service.observer.LoadMessageProcedureObserver;
import chat.rocket.android.service.observer.MethodCallObserver;
import chat.rocket.android.service.observer.NewMessageObserver;
import chat.rocket.android.service.observer.PushSettingsObserver;
import chat.rocket.android.service.observer.SessionObserver;
......@@ -167,7 +166,7 @@ public class RocketChatWebSocketThread extends HandlerThread {
@DebugLog
/* package */ Single<Boolean> keepAlive() {
return checkIfConnectionAlive()
.flatMap(alive -> connectWithExponentialBackoff());
.flatMap(alive -> alive ? Single.just(true) : connectWithExponentialBackoff());
}
@DebugLog
......
......@@ -5,51 +5,50 @@ package chat.rocket.android.service;
*/
public class ServerConnectivity {
public static final int STATE_CONNECTED = 1;
public static final int STATE_DISCONNECTED = 2;
/* package */ static final int STATE_CONNECTING = 3;
/* package */ static final int STATE_DISCONNECTING = 4;
public static final int STATE_SESSION_ESTABLISHED = 5;
/* package */ static final int STATE_RETRYING_CONNECTION = 6;
/* package */ static final ServerConnectivity CONNECTED = new ServerConnectivity(null, STATE_CONNECTED);
public final String hostname;
public final int state;
public final int code;
ServerConnectivity(String hostname, int state) {
this.hostname = hostname;
this.state = state;
this.code = -1;
}
ServerConnectivity(String hostname, int state, int code) {
this.hostname = hostname;
this.state = state;
this.code = code;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ServerConnectivity that = (ServerConnectivity) o;
return state == that.state;
}
@Override
public int hashCode() {
return state;
}
/**
* This exception should be thrown when connection is lost during waiting for CONNECTED.
*/
public static final int STATE_DISCONNECTED = 0;
/* package */ static final int STATE_DISCONNECTING = 1;
/* package */ static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
public static final int STATE_SESSION_ESTABLISHED = 4;
/* package */ static final ServerConnectivity CONNECTED = new ServerConnectivity(null, STATE_CONNECTED);
public final String hostname;
public final int state;
public final int code;
ServerConnectivity(String hostname, int state) {
this.hostname = hostname;
this.state = state;
this.code = -1;
}
ServerConnectivity(String hostname, int state, int code) {
this.hostname = hostname;
this.state = state;
this.code = code;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ServerConnectivity that = (ServerConnectivity) o;
return state == that.state;
}
@Override
public int hashCode() {
return state;
}
/**
* This exception should be thrown when connection is lost during waiting for CONNECTED.
*/
/* package */static class DisconnectedException extends Exception {
/* package */DisconnectedException() {
super("Disconnected");
/* package */DisconnectedException() {
super("Disconnected");
}
}
}
}
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment