Commit 65d5c3a7 authored by Leonardo Aramaki's avatar Leonardo Aramaki

Fix some issues when logging-in after previous backpress fix

parent cf18e7f8
package chat.rocket.android.helper
import android.content.Context
import chat.rocket.android.RocketChatCache
import chat.rocket.android.api.rest.CookieInterceptor
import chat.rocket.android.api.rest.DefaultCookieProvider
import com.facebook.stetho.okhttp3.StethoInterceptor
......@@ -24,17 +23,18 @@ object OkHttpHelper {
return httpClientForUploadFile ?: throw AssertionError("httpClientForUploadFile set to null by another thread")
}
fun getClientForDownloadFile(context: Context): OkHttpClient {
if(httpClientForDownloadFile == null) {
fun getClientForDownloadFile(): OkHttpClient {
if (httpClientForDownloadFile == null) {
httpClientForDownloadFile = OkHttpClient.Builder()
.addNetworkInterceptor(StethoInterceptor())
.followRedirects(true)
.followSslRedirects(true)
.addInterceptor(CookieInterceptor(DefaultCookieProvider(RocketChatCache(context))))
.addInterceptor(CookieInterceptor(DefaultCookieProvider()))
.build()
}
return httpClientForDownloadFile ?: throw AssertionError("httpClientForDownloadFile set to null by another thread")
}
/**
* Returns the OkHttpClient instance for WebSocket connection.
* @return The OkHttpClient WebSocket connection instance.
......
......@@ -35,6 +35,7 @@ public class RocketChatApplication extends MultiDexApplication {
@Override
public void onCreate() {
super.onCreate();
RocketChatCache.INSTANCE.initialize(this);
JobManager.create(this).addJobCreator(new RocketChatJobCreator());
DDPClient.initialize(OkHttpHelper.INSTANCE.getClientForWebSocket());
Fabric.with(this, new Crashlytics());
......@@ -46,7 +47,7 @@ public class RocketChatApplication extends MultiDexApplication {
RealmStore.put(serverInfo.getHostname());
}
RocketChatWidgets.initialize(this, OkHttpHelper.INSTANCE.getClientForDownloadFile(this));
RocketChatWidgets.initialize(this, OkHttpHelper.INSTANCE.getClientForDownloadFile());
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
......
This diff is collapsed.
......@@ -16,77 +16,85 @@ import chat.rocket.persistence.realm.repositories.RealmSessionRepository;
* Activity for Login, Sign-up, and Retry connecting...
*/
public class LoginActivity extends AbstractFragmentActivity implements LoginContract.View {
public static final String KEY_HOSTNAME = "hostname";
public static final String KEY_HOSTNAME = "hostname";
private LoginContract.Presenter presenter;
private LoginContract.Presenter presenter;
@Override
protected int getLayoutContainerForFragment() {
return R.id.content;
}
@Override
protected int getLayoutContainerForFragment() {
return R.id.content;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String hostname = null;
Intent intent = getIntent();
if (intent != null && intent.getExtras() != null) {
hostname = intent.getStringExtra(KEY_HOSTNAME);
}
presenter = new LoginPresenter(
hostname,
new SessionInteractor(new RealmSessionRepository(hostname)),
ConnectivityManager.getInstance(getApplicationContext())
);
}
@Override
protected void onResume() {
super.onResume();
presenter.bindView(this);
}
@Override
protected void onDestroy() {
presenter.release();
super.onDestroy();
}
private void showFragment(Fragment fragment, String hostname) {
setContentView(R.layout.simple_screen);
injectHostnameArgTo(fragment, hostname);
super.showFragment(fragment);
}
private void injectHostnameArgTo(Fragment fragment, String hostname) {
Bundle args = fragment.getArguments();
if (args == null) {
args = new Bundle();
}
args.putString(LoginActivity.KEY_HOSTNAME, hostname);
fragment.setArguments(args);
}
@Override
protected void onBackPressedNotHandled() {
moveTaskToBack(true);
}
@Override
public void showLogin(String hostname) {
showFragment(new LoginFragment(), hostname);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void showRetryLogin(String hostname) {
showFragment(new RetryLoginFragment(), hostname);
}
String hostname = null;
Intent intent = getIntent();
if (intent != null && intent.getExtras() != null) {
hostname = intent.getStringExtra(KEY_HOSTNAME);
@Override
public void closeView() {
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
presenter = new LoginPresenter(
hostname,
new SessionInteractor(new RealmSessionRepository(hostname)),
ConnectivityManager.getInstance(getApplicationContext())
);
}
@Override
protected void onResume() {
super.onResume();
presenter.bindView(this);
}
@Override
protected void onDestroy() {
presenter.release();
super.onDestroy();
}
private void showFragment(Fragment fragment, String hostname) {
setContentView(R.layout.simple_screen);
injectHostnameArgTo(fragment, hostname);
super.showFragment(fragment);
}
private void injectHostnameArgTo(Fragment fragment, String hostname) {
Bundle args = fragment.getArguments();
if (args == null) {
args = new Bundle();
@Override
protected boolean onBackPress() {
LoginFragment loginFragment = (LoginFragment) getSupportFragmentManager()
.findFragmentById(getLayoutContainerForFragment());
loginFragment.goBack();
return true;
}
args.putString(LoginActivity.KEY_HOSTNAME, hostname);
fragment.setArguments(args);
}
@Override
protected void onBackPressedNotHandled() {
moveTaskToBack(true);
}
@Override
public void showLogin(String hostname) {
showFragment(new LoginFragment(), hostname);
}
@Override
public void showRetryLogin(String hostname) {
showFragment(new RetryLoginFragment(), hostname);
}
@Override
public void closeView() {
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
......@@ -81,7 +81,7 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
ConnectivityManagerApi connectivityManager = ConnectivityManager.getInstance(getApplicationContext());
if (hostname == null || presenter == null) {
String previousHostname = hostname;
hostname = new RocketChatCache(getApplicationContext()).getSelectedServerHostname();
hostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
if (hostname == null) {
showAddServerScreen();
} else {
......@@ -95,7 +95,7 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
connectivityManager.keepAliveServer();
presenter.bindView(this);
presenter.loadSignedInServers(hostname);
roomId = new RocketChatCache(getApplicationContext()).getSelectedRoomId();
roomId = RocketChatCache.INSTANCE.getSelectedRoomId();
}
}
......@@ -186,15 +186,12 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
PublicSettingRepository publicSettingRepository = new RealmPublicSettingRepository(hostname);
RocketChatCache rocketChatCache = new RocketChatCache(this);
presenter = new MainPresenter(
roomInteractor,
createRoomInteractor,
sessionInteractor,
new MethodCallHelper(this, hostname),
ConnectivityManager.getInstance(getApplicationContext()),
rocketChatCache,
publicSettingRepository
);
......@@ -203,12 +200,12 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
presenter.bindView(this);
presenter.loadSignedInServers(hostname);
roomId = rocketChatCache.getSelectedRoomId();
roomId = RocketChatCache.INSTANCE.getSelectedRoomId();
}
private void updateSidebarMainFragment() {
closeSidebarIfNeeded();
String selectedServerHostname = new RocketChatCache(this).getSelectedServerHostname();
String selectedServerHostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
Fragment sidebarFragment = findFragmentByTag(selectedServerHostname);
if (sidebarFragment == null) {
sidebarFragment = SidebarMainFragment.create(selectedServerHostname);
......@@ -399,15 +396,14 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
private void changeServerIfNeeded(String serverHostname) {
if (!hostname.equalsIgnoreCase(serverHostname)) {
RocketChatCache rocketChatCache = new RocketChatCache(getApplicationContext());
rocketChatCache.setSelectedServerHostname(serverHostname);
RocketChatCache.INSTANCE.setSelectedServerHostname(serverHostname);
}
}
@DebugLog
public void onLogout() {
presenter.prepareToLogout();
if (new RocketChatCache(getApplicationContext()).getSelectedServerHostname() == null) {
if (RocketChatCache.INSTANCE.getSelectedServerHostname() == null) {
finish();
LaunchUtil.showMainActivity(this);
} else {
......
......@@ -41,7 +41,6 @@ public class MainPresenter extends BasePresenter<MainContract.View>
private final SessionInteractor sessionInteractor;
private final MethodCallHelper methodCallHelper;
private final ConnectivityManagerApi connectivityManagerApi;
private final RocketChatCache rocketChatCache;
private final PublicSettingRepository publicSettingRepository;
public MainPresenter(RoomInteractor roomInteractor,
......@@ -49,13 +48,12 @@ public class MainPresenter extends BasePresenter<MainContract.View>
SessionInteractor sessionInteractor,
MethodCallHelper methodCallHelper,
ConnectivityManagerApi connectivityManagerApi,
RocketChatCache rocketChatCache, PublicSettingRepository publicSettingRepository) {
PublicSettingRepository publicSettingRepository) {
this.roomInteractor = roomInteractor;
this.canCreateRoomInteractor = canCreateRoomInteractor;
this.sessionInteractor = sessionInteractor;
this.methodCallHelper = methodCallHelper;
this.connectivityManagerApi = connectivityManagerApi;
this.rocketChatCache = rocketChatCache;
this.publicSettingRepository = publicSettingRepository;
}
......@@ -101,7 +99,7 @@ public class MainPresenter extends BasePresenter<MainContract.View>
@Override
public void release() {
if (rocketChatCache.getSessionToken() != null) {
if (RocketChatCache.INSTANCE.getSessionToken() != null) {
setUserAway();
}
......@@ -158,13 +156,13 @@ public class MainPresenter extends BasePresenter<MainContract.View>
String logoUrl = (jsonObject.has("url")) ?
jsonObject.optString("url") : jsonObject.optString("defaultUrl");
String siteName = serverInfoPair.second;
rocketChatCache.addHostname(hostname.toLowerCase(), logoUrl, siteName);
return rocketChatCache.getServerList();
RocketChatCache.INSTANCE.addHostname(hostname.toLowerCase(), logoUrl, siteName);
return RocketChatCache.INSTANCE.getServerList();
}
private void openRoom() {
String hostname = rocketChatCache.getSelectedServerHostname();
String roomId = rocketChatCache.getSelectedRoomId();
String hostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
String roomId = RocketChatCache.INSTANCE.getSelectedRoomId();
if (roomId == null || roomId.length() == 0) {
view.showHome();
......@@ -214,7 +212,7 @@ public class MainPresenter extends BasePresenter<MainContract.View>
}
// TODO: Should we remove below and above calls to view?
// view.showConnectionOk();
rocketChatCache.setSessionToken(session.getToken());
RocketChatCache.INSTANCE.setSessionToken(session.getToken());
},
Logger.INSTANCE::report
);
......
......@@ -12,7 +12,6 @@ import java.util.UUID;
import bolts.Continuation;
import bolts.Task;
import chat.rocket.android.RocketChatApplication;
import chat.rocket.android.RocketChatCache;
import chat.rocket.android.helper.CheckSum;
import chat.rocket.android.helper.TextUtils;
......@@ -304,9 +303,7 @@ public class MethodCallHelper {
realm.createOrUpdateAllFromJson(
RealmRoom.class, result);
Context appContext = RocketChatApplication.getInstance();
RocketChatCache cache = new RocketChatCache(appContext);
JSONObject openedRooms = cache.getOpenedRooms();
JSONObject openedRooms = RocketChatCache.INSTANCE.getOpenedRooms();
RealmQuery<RealmRoom> query = realm.where(RealmRoom.class);
Iterator<String> keys = openedRooms.keys();
......@@ -314,7 +311,7 @@ public class MethodCallHelper {
String rid = keys.next();
RealmRoom realmRoom = query.equalTo(RealmRoom.ID, rid).findFirst();
if (realmRoom == null) {
cache.removeOpenedRoom(rid);
RocketChatCache.INSTANCE.removeOpenedRoom(rid);
} else {
loadMissedMessages(rid, realmRoom.getLastSeen())
.continueWithTask(task1 -> {
......@@ -511,9 +508,8 @@ public class MethodCallHelper {
HttpUrl httpSiteUrl = HttpUrl.parse(siteUrl);
if (httpSiteUrl != null) {
String host = httpSiteUrl.host();
RocketChatCache rocketChatCache = new RocketChatCache(context);
rocketChatCache.addSiteUrl(host, currentHostname);
rocketChatCache.addSiteName(currentHostname, siteName);
RocketChatCache.INSTANCE.addSiteUrl(host, currentHostname);
RocketChatCache.INSTANCE.addSiteName(currentHostname, siteName);
}
}
......
......@@ -8,42 +8,37 @@ import chat.rocket.persistence.realm.models.internal.RealmSession;
public class DefaultCookieProvider implements CookieProvider {
private RocketChatCache rocketChatCache;
public DefaultCookieProvider(RocketChatCache rocketChatCache) {
this.rocketChatCache = rocketChatCache;
}
@Override
public String getHostname() {
return getHostnameFromCache();
}
@Override
public String getCookie() {
final String hostname = getHostnameFromCache();
if (hostname == null) {
return "";
}
final RealmHelper realmHelper = RealmStore.get(getHostnameFromCache());
if (realmHelper == null) {
return "";
@Override
public String getHostname() {
return getHostnameFromCache();
}
final RealmUser user = realmHelper.executeTransactionForRead(realm ->
RealmUser.queryCurrentUser(realm).findFirst());
final RealmSession session = realmHelper.executeTransactionForRead(realm ->
RealmSession.queryDefaultSession(realm).findFirst());
@Override
public String getCookie() {
final String hostname = getHostnameFromCache();
if (hostname == null) {
return "";
}
if (user == null || session == null) {
return "";
}
final RealmHelper realmHelper = RealmStore.get(getHostnameFromCache());
if (realmHelper == null) {
return "";
}
final RealmUser user = realmHelper.executeTransactionForRead(realm ->
RealmUser.queryCurrentUser(realm).findFirst());
final RealmSession session = realmHelper.executeTransactionForRead(realm ->
RealmSession.queryDefaultSession(realm).findFirst());
return "rc_uid=" + user.getId() + ";rc_token=" + session.getToken();
}
if (user == null || session == null) {
return "";
}
private String getHostnameFromCache() {
return rocketChatCache.getSelectedServerHostname();
}
return "rc_uid=" + user.getId() + ";rc_token=" + session.getToken();
}
private String getHostnameFromCache() {
return RocketChatCache.INSTANCE.getSelectedServerHostname();
}
}
......@@ -32,7 +32,7 @@ public class InputHostnameFragment extends AbstractFragment implements InputHost
super.onCreate(savedInstanceState);
Context appContext = getContext().getApplicationContext();
presenter = new InputHostnamePresenter(new RocketChatCache(appContext), ConnectivityManager.getInstance(appContext));
presenter = new InputHostnamePresenter(ConnectivityManager.getInstance(appContext));
}
@Override
......
......@@ -14,11 +14,9 @@ import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
public class InputHostnamePresenter extends BasePresenter<InputHostnameContract.View> implements InputHostnameContract.Presenter {
private final RocketChatCache rocketChatCache;
private final ConnectivityManagerApi connectivityManager;
public InputHostnamePresenter(RocketChatCache rocketChatCache, ConnectivityManagerApi connectivityManager) {
this.rocketChatCache = rocketChatCache;
public InputHostnamePresenter(ConnectivityManagerApi connectivityManager) {
this.connectivityManager = connectivityManager;
}
......@@ -54,7 +52,7 @@ public class InputHostnamePresenter extends BasePresenter<InputHostnameContract.
}
private void onServerValid(String hostname, boolean usesSecureConnection) {
rocketChatCache.setSelectedServerHostname(hostname);
RocketChatCache.INSTANCE.setSelectedServerHostname(hostname);
String server = hostname.replace("/", ".");
connectivityManager.addOrUpdateServer(server, server, !usesSecureConnection);
......
......@@ -170,7 +170,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
@Override
public void loadMissedMessages() {
RocketChatApplication appContext = RocketChatApplication.getInstance();
JSONObject openedRooms = new RocketChatCache(appContext).getOpenedRooms();
JSONObject openedRooms = RocketChatCache.INSTANCE.getOpenedRooms();
if (openedRooms.has(roomId)) {
try {
JSONObject room = openedRooms.getJSONObject(roomId);
......@@ -369,8 +369,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
.filter(Optional::isPresent)
.map(Optional::get)
.map(room -> {
new RocketChatCache(RocketChatApplication.getInstance())
.addOpenedRoom(room.getRoomId(), room.getLastSeen());
RocketChatCache.INSTANCE.addOpenedRoom(room.getRoomId(), room.getLastSeen());
return room;
})
.flatMap(messageInteractor::getAllFrom)
......
......@@ -7,21 +7,25 @@ import chat.rocket.core.models.LoginServiceConfiguration;
public interface LoginContract {
interface View extends BaseContract.View {
interface View extends BaseContract.View {
void showLoader();
void showLoader();
void hideLoader();
void hideLoader();
void showError(String message);
void showError(String message);
void showLoginServices(List<LoginServiceConfiguration> loginServiceList);
void showLoginServices(List<LoginServiceConfiguration> loginServiceList);
void showTwoStepAuth();
}
void showTwoStepAuth();
interface Presenter extends BaseContract.Presenter<View> {
void goBack();
}
void login(String username, String password);
}
interface Presenter extends BaseContract.Presenter<View> {
void login(String username, String password);
void goBack();
}
}
......@@ -50,9 +50,9 @@ class LoginFragment : AbstractServerConfigFragment(), LoginContract.View {
txtPasswd = rootView.findViewById(R.id.editor_passwd)
waitingView = rootView.findViewById(R.id.waiting)
btnEmail.setOnClickListener { view -> presenter.login(txtUsername.text.toString(), txtPasswd.text.toString()) }
btnEmail.setOnClickListener { _ -> presenter.login(txtUsername.text.toString(), txtPasswd.text.toString()) }
btnUserRegistration.setOnClickListener { view ->
btnUserRegistration.setOnClickListener { _ ->
UserRegistrationDialogFragment.create(hostname, txtUsername.text.toString(), txtPasswd.text.toString())
.show(fragmentManager!!, "UserRegistrationDialogFragment")
}
......@@ -84,7 +84,7 @@ class LoginFragment : AbstractServerConfigFragment(), LoginContract.View {
for (info in OAuthProviderInfo.LIST) {
if (supportedMap[info.serviceName] == false && info.serviceName == authProvider.service) {
supportedMap.put(info.serviceName, true)
viewMap[info.serviceName]?.setOnClickListener { view ->
viewMap[info.serviceName]?.setOnClickListener { _ ->
var fragment: Fragment? = null
try {
fragment = info.fragmentClass.newInstance()
......@@ -126,4 +126,8 @@ class LoginFragment : AbstractServerConfigFragment(), LoginContract.View {
presenter.release()
super.onPause()
}
override fun goBack() {
presenter.goBack()
}
}
......@@ -30,17 +30,14 @@ class LoginPresenter(private val loginServiceConfigurationRepository: LoginServi
getLoginServices()
}
override fun release() {
override fun goBack() {
val context = RocketChatApplication.getInstance()
val rocketChatCache = RocketChatCache(context)
val hostname = rocketChatCache.selectedServerHostname
val hostname = RocketChatCache.getSelectedServerHostname()
hostname?.let {
ConnectivityManager.getInstance(context).removeServer(hostname)
rocketChatCache.clearSelectedHostnameReferences()
RocketChatCache.clearSelectedHostnameReferences()
}
super.release()
LaunchUtil.showMainActivity(context)
}
......
......@@ -94,13 +94,11 @@ public class SidebarMainFragment extends AbstractFragment implements SidebarMain
new SessionInteractor(new RealmSessionRepository(hostname))
);
RocketChatCache rocketChatCache = new RocketChatCache(getContext().getApplicationContext());
presenter = new SidebarMainPresenter(
hostname,
new RoomInteractor(new RealmRoomRepository(hostname)),
userRepository,
rocketChatCache,
absoluteUrlHelper,
new MethodCallHelper(getContext(), hostname),
new RealmSpotlightRepository(hostname)
......
......@@ -38,7 +38,6 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
private final String hostname;
private final RoomInteractor roomInteractor;
private final UserRepository userRepository;
private final RocketChatCache rocketChatCache;
private final AbsoluteUrlHelper absoluteUrlHelper;
private final MethodCallHelper methodCallHelper;
private SpotlightRepository realmSpotlightRepository;
......@@ -47,14 +46,12 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
public SidebarMainPresenter(String hostname,
RoomInteractor roomInteractor,
UserRepository userRepository,
RocketChatCache rocketChatCache,
AbsoluteUrlHelper absoluteUrlHelper,
MethodCallHelper methodCallHelper,
RealmSpotlightRepository realmSpotlightRepository) {
this.hostname = hostname;
this.roomInteractor = roomInteractor;
this.userRepository = userRepository;
this.rocketChatCache = rocketChatCache;
this.absoluteUrlHelper = absoluteUrlHelper;
this.methodCallHelper = methodCallHelper;
this.realmSpotlightRepository = realmSpotlightRepository;
......@@ -87,7 +84,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
@Override
public void onRoomSelected(RoomSidebar roomSidebar) {
rocketChatCache.setSelectedRoomId(roomSidebar.getRoomId());
RocketChatCache.INSTANCE.setSelectedRoomId(roomSidebar.getRoomId());
}
@Override
......@@ -103,7 +100,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
methodCallHelper.createDirectMessage(username)
.continueWithTask(task -> {
if (task.isCompleted()) {
rocketChatCache.setSelectedRoomId(task.getResult());
RocketChatCache.INSTANCE.setSelectedRoomId(task.getResult());
}
return null;
});
......@@ -111,7 +108,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
methodCallHelper.joinRoom(spotlight.getId())
.continueWithTask(task -> {
if (task.isCompleted()) {
rocketChatCache.setSelectedRoomId(spotlight.getId());
RocketChatCache.INSTANCE.setSelectedRoomId(spotlight.getId());
}
return null;
});
......@@ -157,12 +154,12 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
}
clearSubscriptions();
String currentHostname = rocketChatCache.getSelectedServerHostname();
String currentHostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
RealmHelper realmHelper = RealmStore.getOrCreate(currentHostname);
return realmHelper.executeTransaction(realm -> {
rocketChatCache.removeHostname(currentHostname);
rocketChatCache.removeSelectedRoomId(currentHostname);
rocketChatCache.setSelectedServerHostname(rocketChatCache.getFirstLoggedHostnameIfAny());
RocketChatCache.INSTANCE.removeHostname(currentHostname);
RocketChatCache.INSTANCE.removeSelectedRoomId(currentHostname);
RocketChatCache.INSTANCE.setSelectedServerHostname(RocketChatCache.INSTANCE.getFirstLoggedHostnameIfAny());
realm.executeTransactionAsync(Realm::deleteAll);
view.onPreparedToLogOut();
ConnectivityManager.getInstance(RocketChatApplication.getInstance())
......
......@@ -48,9 +48,7 @@ public class MessagePopup {
}
private void showAvailableActionsOnly(Context context) {
RocketChatCache cache = new RocketChatCache(context.getApplicationContext());
String hostname = cache.getSelectedServerHostname();
String hostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
EditMessageInteractor editMessageInteractor = getEditMessageInteractor(hostname);
......@@ -167,7 +165,7 @@ public class MessagePopup {
}
public MessagePopup setDeleteAction(ActionListener actionListener) {
DELETE_ACTION_INFO.actionListener= actionListener;
DELETE_ACTION_INFO.actionListener = actionListener;
return singleton;
}
......
package chat.rocket.android.push
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
......@@ -137,6 +138,7 @@ object PushManager {
return group
}
@SuppressLint("NewApi")
internal fun showNotification(context: Context, lastPushMessage: PushMessage) {
if (lastPushMessage.host == null || lastPushMessage.message == null || lastPushMessage.title == null) {
return
......@@ -202,7 +204,7 @@ object PushManager {
.setDeleteIntent(deleteIntent)
.setMessageNotification()
val subText = RocketChatCache(context).getHostSiteName(host)
val subText = RocketChatCache.getHostSiteName(host)
if (subText.isNotEmpty()) {
builder.setSubText(subText)
}
......@@ -257,6 +259,7 @@ object PushManager {
}
}
@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.N)
internal fun createGroupNotificationForNougatAndAbove(context: Context, lastPushMessage: PushMessage): Notification? {
with(lastPushMessage) {
......@@ -289,7 +292,7 @@ object PushManager {
manager.createNotificationChannel(groupChannel)
}
val subText = RocketChatCache(context).getHostSiteName(host)
val subText = RocketChatCache.getHostSiteName(host)
if (subText.isNotEmpty()) {
builder.setSubText(subText)
}
......@@ -344,7 +347,7 @@ object PushManager {
.setContentIntent(contentIntent)
.setMessageNotification()
val subText = RocketChatCache(context).getHostSiteName(host)
val subText = RocketChatCache.getHostSiteName(host)
if (subText.isNotEmpty()) {
builder.setSubText(subText)
}
......@@ -370,6 +373,7 @@ object PushManager {
}
}
@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.N)
internal fun createSingleNotificationForNougatAndAbove(context: Context, lastPushMessage: PushMessage): Notification? {
val manager: NotificationManager =
......@@ -404,7 +408,7 @@ object PushManager {
manager.createNotificationChannel(channel)
}
val subText = RocketChatCache(context).getHostSiteName(host)
val subText = RocketChatCache.getHostSiteName(host)
if (subText.isNotEmpty()) {
builder.setSubText(subText)
}
......@@ -647,7 +651,7 @@ object PushManager {
}
val httpUrl = HttpUrl.parse(pushMessage.host)
httpUrl?.let {
val siteUrl = RocketChatCache(context).getSiteUrlFor(httpUrl.host())
val siteUrl = RocketChatCache.getSiteUrlFor(httpUrl.host())
if (siteUrl != null) {
sendMessage(siteUrl, message, pushMessage.rid)
}
......
......@@ -2,7 +2,6 @@ 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
import com.evernote.android.job.JobManager
import com.evernote.android.job.JobRequest
......@@ -11,7 +10,6 @@ import java.util.concurrent.TimeUnit
class KeepAliveJob : Job() {
private val connectivityManager: ConnectivityManagerApi
private val rocketChatCache: RocketChatCache
companion object {
val TAG = "chat.rocket.android.service.KeepAliveJob"
......@@ -38,7 +36,6 @@ class KeepAliveJob : Job() {
init {
val context = RocketChatApplication.getInstance()
connectivityManager = ConnectivityManager.getInstance(context)
rocketChatCache = RocketChatCache(context)
}
override fun onRunJob(params: Params): Result {
......
......@@ -74,7 +74,7 @@ import io.reactivex.subjects.BehaviorSubject;
@DebugLog
@Override
public void ensureConnections() {
String hostname = new RocketChatCache(appContext).getSelectedServerHostname();
String hostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
if (hostname == null) {
return;
}
......
......@@ -106,21 +106,24 @@ public class RocketChatService extends Service implements ConnectivityServiceInt
}
if (currentWebSocketThread != null) {
return currentWebSocketThread.terminate(isDisconnected)
.doAfterTerminate(() -> currentWebSocketThread = null)
.flatMap(terminated ->
RocketChatWebSocketThread.getStarted(getApplicationContext(), hostname)
.doOnSuccess(thread -> {
currentWebSocketThread = thread;
webSocketThreadLock.release();
})
.doOnError(throwable -> {
currentWebSocketThread = null;
RCLog.e(throwable);
Logger.INSTANCE.report(throwable);
webSocketThreadLock.release();
})
);
if (isDisconnected) {
return currentWebSocketThread.terminate(true)
.doAfterTerminate(() -> currentWebSocketThread = null)
.flatMap(terminated ->
RocketChatWebSocketThread.getStarted(getApplicationContext(), hostname)
.doOnSuccess(thread -> {
currentWebSocketThread = thread;
webSocketThreadLock.release();
})
.doOnError(throwable -> {
currentWebSocketThread = null;
RCLog.e(throwable);
Logger.INSTANCE.report(throwable);
webSocketThreadLock.release();
})
);
}
return Single.just(currentWebSocketThread);
}
return RocketChatWebSocketThread.getStarted(getApplicationContext(), hostname)
......
......@@ -13,13 +13,11 @@ import chat.rocket.persistence.realm.models.ddp.RealmRoom;
import io.reactivex.disposables.CompositeDisposable;
public abstract class AbstractRocketChatCacheObserver implements Registrable {
private final Context context;
private final RealmHelper realmHelper;
private String roomId;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
protected AbstractRocketChatCacheObserver(Context context, RealmHelper realmHelper) {
this.context = context;
protected AbstractRocketChatCacheObserver(RealmHelper realmHelper) {
this.realmHelper = realmHelper;
}
......@@ -47,7 +45,7 @@ public abstract class AbstractRocketChatCacheObserver implements Registrable {
@Override
public final void register() {
compositeDisposable.add(
new RocketChatCache(context)
RocketChatCache.INSTANCE
.getSelectedRoomIdPublisher()
.filter(Optional::isPresent)
.map(Optional::get)
......
......@@ -13,60 +13,58 @@ import chat.rocket.persistence.realm.RealmHelper;
* wrapper for managing stream-notify-message depending on RocketChatCache.
*/
public class StreamRoomMessageManager implements Registrable {
private final Context context;
private final String hostname;
private final RealmHelper realmHelper;
private final AbstractRocketChatCacheObserver cacheObserver;
private final Handler handler;
private final RocketChatCache rocketChatCache;
private StreamRoomMessage streamRoomMessage;
private final Context context;
private final String hostname;
private final RealmHelper realmHelper;
private final AbstractRocketChatCacheObserver cacheObserver;
private final Handler handler;
private StreamRoomMessage streamRoomMessage;
public StreamRoomMessageManager(Context context, String hostname,
RealmHelper realmHelper) {
this.context = context;
this.hostname = hostname;
this.realmHelper = realmHelper;
this.rocketChatCache = new RocketChatCache(context);
public StreamRoomMessageManager(Context context, String hostname,
RealmHelper realmHelper) {
this.context = context;
this.hostname = hostname;
this.realmHelper = realmHelper;
cacheObserver = new AbstractRocketChatCacheObserver(context, realmHelper) {
@Override
protected void onRoomIdUpdated(String roomId) {
unregisterStreamNotifyMessageIfNeeded();
registerStreamNotifyMessage(roomId);
}
};
handler = new Handler(Looper.myLooper());
}
cacheObserver = new AbstractRocketChatCacheObserver(realmHelper) {
@Override
protected void onRoomIdUpdated(String roomId) {
unregisterStreamNotifyMessageIfNeeded();
registerStreamNotifyMessage(roomId);
}
};
handler = new Handler(Looper.myLooper());
}
private void registerStreamNotifyMessage(String roomId) {
handler.post(() -> {
streamRoomMessage = new StreamRoomMessage(context, hostname, realmHelper, roomId);
streamRoomMessage.register();
});
}
private void registerStreamNotifyMessage(String roomId) {
handler.post(() -> {
streamRoomMessage = new StreamRoomMessage(context, hostname, realmHelper, roomId);
streamRoomMessage.register();
});
}
private void unregisterStreamNotifyMessageIfNeeded() {
handler.post(() -> {
if (streamRoomMessage != null) {
streamRoomMessage.unregister();
streamRoomMessage = null;
}
});
}
private void unregisterStreamNotifyMessageIfNeeded() {
handler.post(() -> {
if (streamRoomMessage != null) {
streamRoomMessage.unregister();
streamRoomMessage = null;
}
});
}
@Override
public void register() {
cacheObserver.register();
String selectedRoomId = rocketChatCache.getSelectedRoomId();
if (selectedRoomId == null) {
return;
@Override
public void register() {
cacheObserver.register();
String selectedRoomId = RocketChatCache.INSTANCE.getSelectedRoomId();
if (selectedRoomId == null) {
return;
}
registerStreamNotifyMessage(selectedRoomId);
}
registerStreamNotifyMessage(selectedRoomId);
}
@Override
public void unregister() {
unregisterStreamNotifyMessageIfNeeded();
cacheObserver.unregister();
}
@Override
public void unregister() {
unregisterStreamNotifyMessageIfNeeded();
cacheObserver.unregister();
}
}
......@@ -68,7 +68,7 @@ public class GcmPushRegistrationObserver extends AbstractModelObserver<GcmPushRe
final RealmUser currentUser = realmHelper.executeTransactionForRead(realm ->
RealmUser.queryCurrentUser(realm).findFirst());
final String userId = currentUser != null ? currentUser.getId() : null;
final String pushId = new RocketChatCache(context).getOrCreatePushId();
final String pushId = RocketChatCache.INSTANCE.getOrCreatePushId();
return new RaixPushHelper(realmHelper)
.pushUpdate(pushId, gcmToken, userId);
......
......@@ -74,7 +74,7 @@ public class SessionObserver extends AbstractModelObserver<RealmSession> {
// update push info
pushHelper
.pushSetUser(new RocketChatCache(context).getOrCreatePushId())
.pushSetUser(RocketChatCache.INSTANCE.getOrCreatePushId())
.continueWith(new LogIfError());
ConnectivityManager.getInstance(context).notifySessionEstablished(hostname);
......
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