Commit 7abf6706 authored by Tiago Cunha's avatar Tiago Cunha

Refactor RocketChatCache

parent 3e1bb00a
......@@ -3,30 +3,43 @@ package chat.rocket.android;
import android.content.Context;
import android.content.SharedPreferences;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import java.util.UUID;
/**
* sharedpreference-based cache.
*/
public class RocketChatCache {
public static final String KEY_SELECTED_SERVER_HOSTNAME = "selectedServerHostname";
public static final String KEY_SELECTED_ROOM_ID = "selectedRoomId";
private static final String KEY_SELECTED_SERVER_HOSTNAME = "selectedServerHostname";
private static final String KEY_SELECTED_ROOM_ID = "selectedRoomId";
private static final String KEY_PUSH_ID = "pushId";
/**
* get SharedPreference instance for RocketChat application cache.
*/
public static SharedPreferences get(Context context) {
return context.getSharedPreferences("cache", Context.MODE_PRIVATE);
private Context context;
public RocketChatCache(Context context) {
this.context = context.getApplicationContext();
}
public String getSelectedServerHostname() {
return getString(KEY_SELECTED_SERVER_HOSTNAME, null);
}
public void setSelectedServerHostname(String hostname) {
setString(KEY_SELECTED_SERVER_HOSTNAME, hostname);
}
public String getSelectedRoomId() {
return getString(KEY_SELECTED_ROOM_ID, null);
}
public static String getSelectedServerHostname(Context context) {
return get(context).getString(KEY_SELECTED_SERVER_HOSTNAME, null);
public void setSelectedRoomId(String roomId) {
setString(KEY_SELECTED_ROOM_ID, roomId);
}
public static String getOrCreatePushId(Context context) {
SharedPreferences preferences = get(context);
public String getOrCreatePushId() {
SharedPreferences preferences = getSharedPreferences();
if (!preferences.contains(KEY_PUSH_ID)) {
// generates one and save
String newId = UUID.randomUUID().toString().replace("-", "");
......@@ -37,4 +50,44 @@ public class RocketChatCache {
}
return preferences.getString(KEY_PUSH_ID, null);
}
public Flowable<String> getSelectedServerHostnamePublisher() {
return getValuePublisher(KEY_SELECTED_SERVER_HOSTNAME);
}
public Flowable<String> getSelectedRoomIdPublisher() {
return getValuePublisher(KEY_SELECTED_ROOM_ID);
}
private SharedPreferences getSharedPreferences() {
return context.getSharedPreferences("cache", Context.MODE_PRIVATE);
}
private SharedPreferences.Editor getEditor() {
return getSharedPreferences().edit();
}
private String getString(String key, String defaultValue) {
return getSharedPreferences().getString(key, defaultValue);
}
private void setString(String key, String value) {
getEditor().putString(key, value).apply();
}
private Flowable<String> getValuePublisher(final String key) {
return Flowable.create(emitter -> {
SharedPreferences.OnSharedPreferenceChangeListener
listener = (sharedPreferences, changedKey) -> {
if (key.equals(changedKey) && !emitter.isCancelled()) {
emitter.onNext(getString(key, null));
}
};
emitter.setCancellable(() -> getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(listener));
getSharedPreferences().registerOnSharedPreferenceChangeListener(listener);
}, BackpressureStrategy.LATEST);
}
}
package chat.rocket.android.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import java.util.List;
import chat.rocket.android.LaunchUtil;
import chat.rocket.android.RocketChatCache;
......@@ -19,18 +22,16 @@ import icepick.State;
abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
@State protected String hostname;
@State protected String roomId;
SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener =
(sharedPreferences, key) -> {
if (RocketChatCache.KEY_SELECTED_SERVER_HOSTNAME.equals(key)) {
updateHostnameIfNeeded(sharedPreferences);
} else if (RocketChatCache.KEY_SELECTED_ROOM_ID.equals(key)) {
updateRoomIdIfNeeded(sharedPreferences);
}
};
private RocketChatCache rocketChatCache;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rocketChatCache = new RocketChatCache(this);
if (savedInstanceState == null) {
handleIntent(getIntent());
}
......@@ -48,15 +49,11 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
}
if (intent.hasExtra(PushConstants.HOSTNAME)) {
SharedPreferences.Editor editor = RocketChatCache.get(this).edit();
editor.putString(RocketChatCache.KEY_SELECTED_SERVER_HOSTNAME,
intent.getStringExtra(PushConstants.HOSTNAME));
rocketChatCache.setSelectedServerHostname(intent.getStringExtra(PushConstants.HOSTNAME));
if (intent.hasExtra(PushConstants.ROOM_ID)) {
editor.putString(RocketChatCache.KEY_SELECTED_ROOM_ID,
intent.getStringExtra(PushConstants.ROOM_ID));
rocketChatCache.setSelectedRoomId(intent.getStringExtra(PushConstants.ROOM_ID));
}
editor.apply();
}
if (intent.hasExtra(PushConstants.NOT_ID)) {
......@@ -65,13 +62,12 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
}
}
private void updateHostnameIfNeeded(SharedPreferences prefs) {
String newHostname = prefs.getString(RocketChatCache.KEY_SELECTED_SERVER_HOSTNAME, null);
private void updateHostnameIfNeeded(String newHostname) {
if (hostname == null) {
if (newHostname != null && assertServerRealmStoreExists(newHostname)) {
updateHostname(newHostname);
} else {
recoverFromHostnameError(prefs);
recoverFromHostnameError();
}
} else {
if (hostname.equals(newHostname)) {
......@@ -82,7 +78,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
if (assertServerRealmStoreExists(newHostname)) {
updateHostname(newHostname);
} else {
recoverFromHostnameError(prefs);
recoverFromHostnameError();
}
}
}
......@@ -96,7 +92,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
onHostnameUpdated();
}
private void recoverFromHostnameError(SharedPreferences prefs) {
private void recoverFromHostnameError() {
final List<ServerInfo> serverInfoList =
ConnectivityManager.getInstance(getApplicationContext()).getServerList();
if (serverInfoList == null || serverInfoList.size() == 0) {
......@@ -106,26 +102,24 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
// just connect to the first available
final ServerInfo serverInfo = serverInfoList.get(0);
prefs.edit()
.putString(RocketChatCache.KEY_SELECTED_SERVER_HOSTNAME, serverInfo.getHostname())
.remove(RocketChatCache.KEY_SELECTED_ROOM_ID)
.apply();
rocketChatCache.setSelectedServerHostname(serverInfo.getHostname());
rocketChatCache.setSelectedRoomId(null);
}
private void updateRoomIdIfNeeded(SharedPreferences prefs) {
String newRoomId = prefs.getString(RocketChatCache.KEY_SELECTED_ROOM_ID, null);
private void updateRoomIdIfNeeded(String newRoomId) {
if (roomId == null) {
if (newRoomId != null && assertRoomSubscriptionExists(newRoomId, prefs)) {
if (newRoomId != null && assertRoomSubscriptionExists(newRoomId)) {
updateRoomId(newRoomId);
}
} else {
if (!roomId.equals(newRoomId) && assertRoomSubscriptionExists(newRoomId, prefs)) {
if (!roomId.equals(newRoomId) && assertRoomSubscriptionExists(newRoomId)) {
updateRoomId(newRoomId);
}
}
}
private boolean assertRoomSubscriptionExists(String roomId, SharedPreferences prefs) {
private boolean assertRoomSubscriptionExists(String roomId) {
if (!assertServerRealmStoreExists(hostname)) {
return false;
}
......@@ -133,9 +127,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
RealmRoom room = RealmStore.get(hostname).executeTransactionForRead(realm ->
realm.where(RealmRoom.class).equalTo(RealmRoom.ROOM_ID, roomId).findFirst());
if (room == null) {
prefs.edit()
.remove(RocketChatCache.KEY_SELECTED_ROOM_ID)
.apply();
rocketChatCache.setSelectedRoomId(null);
return false;
}
return true;
......@@ -157,16 +149,15 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
super.onResume();
ConnectivityManager.getInstance(getApplicationContext()).keepAliveServer();
SharedPreferences prefs = RocketChatCache.get(this);
updateHostnameIfNeeded(prefs);
updateRoomIdIfNeeded(prefs);
prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
updateHostnameIfNeeded(rocketChatCache.getSelectedServerHostname());
updateRoomIdIfNeeded(rocketChatCache.getSelectedRoomId());
subscribeToConfigChanges();
}
@Override
protected void onPause() {
SharedPreferences prefs = RocketChatCache.get(this);
prefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
compositeDisposable.clear();
super.onPause();
}
......@@ -175,4 +166,22 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void subscribeToConfigChanges() {
compositeDisposable.add(
rocketChatCache.getSelectedServerHostnamePublisher()
.distinctUntilChanged()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::updateHostnameIfNeeded)
);
compositeDisposable.add(
rocketChatCache.getSelectedRoomIdPublisher()
.distinctUntilChanged()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::updateRoomIdIfNeeded)
);
}
}
package chat.rocket.android.api.rest;
import android.content.Context;
import chat.rocket.android.RocketChatCache;
import chat.rocket.persistence.realm.models.ddp.RealmUser;
import chat.rocket.persistence.realm.models.internal.RealmSession;
......@@ -10,10 +8,10 @@ import chat.rocket.persistence.realm.RealmStore;
public class DefaultCookieProvider implements CookieProvider {
private final Context applicationContext;
private RocketChatCache rocketChatCache;
public DefaultCookieProvider(Context context) {
applicationContext = context.getApplicationContext();
public DefaultCookieProvider(RocketChatCache rocketChatCache) {
this.rocketChatCache = rocketChatCache;
}
@Override
......@@ -46,6 +44,6 @@ public class DefaultCookieProvider implements CookieProvider {
}
private String getHostnameFromCache() {
return RocketChatCache.getSelectedServerHostname(applicationContext);
return rocketChatCache.getSelectedServerHostname();
}
}
......@@ -32,7 +32,7 @@ public class InputHostnameFragment extends AbstractFragment implements InputHost
final Context appContext = getContext().getApplicationContext();
presenter = new InputHostnamePresenter(
RocketChatCache.get(appContext),
new RocketChatCache(appContext),
ConnectivityManager.getInstance(appContext));
}
......
package chat.rocket.android.fragment.add_server;
import android.content.SharedPreferences;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
......@@ -18,10 +16,10 @@ import chat.rocket.android.shared.BasePresenter;
public class InputHostnamePresenter extends BasePresenter<InputHostnameContract.View>
implements InputHostnameContract.Presenter {
private final SharedPreferences rocketChatCache;
private final RocketChatCache rocketChatCache;
private final ConnectivityManagerApi connectivityManager;
public InputHostnamePresenter(SharedPreferences rocketChatCache,
public InputHostnamePresenter(RocketChatCache rocketChatCache,
ConnectivityManagerApi connectivityManager) {
this.rocketChatCache = rocketChatCache;
this.connectivityManager = connectivityManager;
......@@ -63,9 +61,7 @@ public class InputHostnamePresenter extends BasePresenter<InputHostnameContract.
}
private void onServerValid(final String hostname, boolean usesSecureConnection) {
rocketChatCache.edit()
.putString(RocketChatCache.KEY_SELECTED_SERVER_HOSTNAME, hostname)
.apply();
rocketChatCache.setSelectedServerHostname(hostname);
connectivityManager.addOrUpdateServer(hostname, hostname, !usesSecureConnection);
connectivityManager.keepAliveServer();
......
......@@ -47,6 +47,8 @@ public class SidebarMainFragment extends AbstractFragment implements SidebarMain
private String hostname;
private RocketChatCache rocketChatCache;
public SidebarMainFragment() {
}
......@@ -70,6 +72,8 @@ public class SidebarMainFragment extends AbstractFragment implements SidebarMain
Bundle args = getArguments();
hostname = args == null ? null : args.getString(HOSTNAME);
rocketChatCache = new RocketChatCache(getContext());
presenter = new SidebarMainPresenter(
hostname,
new RoomInteractor(new RealmRoomRepository(hostname)),
......@@ -103,9 +107,7 @@ public class SidebarMainFragment extends AbstractFragment implements SidebarMain
setupVersionInfo();
adapter = new RoomListAdapter();
adapter.setOnItemClickListener(room -> RocketChatCache.get(getContext()).edit()
.putString(RocketChatCache.KEY_SELECTED_ROOM_ID, room.getRoomId())
.apply());
adapter.setOnItemClickListener(room -> rocketChatCache.setSelectedRoomId(room.getRoomId()));
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.room_list_container);
recyclerView.setLayoutManager(
......
......@@ -4,6 +4,7 @@ import android.content.Context;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import java.util.concurrent.TimeUnit;
import chat.rocket.android.RocketChatCache;
import chat.rocket.android.api.rest.CookieInterceptor;
import chat.rocket.android.api.rest.DefaultCookieProvider;
import okhttp3.OkHttpClient;
......@@ -20,7 +21,8 @@ public class OkHttpHelper {
if (httpClientForDownloadFile == null) {
httpClientForDownloadFile = new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.addInterceptor(new CookieInterceptor(new DefaultCookieProvider(context)))
.addInterceptor(
new CookieInterceptor(new DefaultCookieProvider(new RocketChatCache(context))))
.build();
}
return httpClientForDownloadFile;
......
package chat.rocket.android.service.internal;
import android.content.Context;
import android.content.SharedPreferences;
import io.reactivex.disposables.CompositeDisposable;
import chat.rocket.android.RocketChatCache;
import chat.rocket.android.helper.TextUtils;
......@@ -13,20 +14,14 @@ public abstract class AbstractRocketChatCacheObserver implements Registrable {
private final Context context;
private final RealmHelper realmHelper;
private String roomId;
private SharedPreferences.OnSharedPreferenceChangeListener listener =
(prefs, key) -> {
if (RocketChatCache.KEY_SELECTED_ROOM_ID.equals(key)) {
updateRoomIdWith(prefs);
}
};
private CompositeDisposable compositeDisposable = new CompositeDisposable();
protected AbstractRocketChatCacheObserver(Context context, RealmHelper realmHelper) {
this.context = context;
this.realmHelper = realmHelper;
}
private void updateRoomIdWith(SharedPreferences prefs) {
String roomId = prefs.getString(RocketChatCache.KEY_SELECTED_ROOM_ID, null);
private void updateRoomIdWith(String roomId) {
if (!TextUtils.isEmpty(roomId)) {
RealmRoom room = realmHelper.executeTransactionForRead(realm ->
realm.where(RealmRoom.class).equalTo("rid", roomId).findFirst());
......@@ -49,13 +44,15 @@ public abstract class AbstractRocketChatCacheObserver implements Registrable {
@Override
public final void register() {
SharedPreferences prefs = RocketChatCache.get(context);
prefs.registerOnSharedPreferenceChangeListener(listener);
updateRoomIdWith(prefs);
compositeDisposable.add(
new RocketChatCache(context)
.getSelectedRoomIdPublisher()
.subscribe(this::updateRoomIdWith)
);
}
@Override
public final void unregister() {
RocketChatCache.get(context).unregisterOnSharedPreferenceChangeListener(listener);
compositeDisposable.clear();
}
}
......@@ -26,8 +26,8 @@ import chat.rocket.android.service.DDPClientRef;
*/
public class GcmPushRegistrationObserver extends AbstractModelObserver<GcmPushRegistration> {
public GcmPushRegistrationObserver(Context context, String hostname,
RealmHelper realmHelper,
DDPClientRef ddpClientRef) {
RealmHelper realmHelper,
DDPClientRef ddpClientRef) {
super(context, hostname, realmHelper, ddpClientRef);
}
......@@ -50,10 +50,10 @@ public class GcmPushRegistrationObserver extends AbstractModelObserver<GcmPushRe
return null;
}).onSuccessTask(_task -> registerGcmTokenForServer()
).onSuccessTask(_task ->
realmHelper.executeTransaction(realm -> {
GcmPushRegistration.queryDefault(realm).findFirst().setSyncState(SyncState.SYNCED);
return null;
})
realmHelper.executeTransaction(realm -> {
GcmPushRegistration.queryDefault(realm).findFirst().setSyncState(SyncState.SYNCED);
return null;
})
).continueWith(task -> {
if (task.isFaulted()) {
realmHelper.executeTransaction(realm -> {
......@@ -73,7 +73,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 = RocketChatCache.getOrCreatePushId(context);
final String pushId = new RocketChatCache(context).getOrCreatePushId();
return new RaixPushHelper(realmHelper, ddpClientRef)
.pushUpdate(pushId, gcmToken, userId);
......
......@@ -33,7 +33,8 @@ public class SessionObserver extends AbstractModelObserver<RealmSession> {
super(context, hostname, realmHelper, ddpClientRef);
count = 0;
streamNotifyMessage = new StreamRoomMessageManager(context, hostname, realmHelper, ddpClientRef);
streamNotifyMessage =
new StreamRoomMessageManager(context, hostname, realmHelper, ddpClientRef);
pushHelper = new RaixPushHelper(realmHelper, ddpClientRef);
}
......@@ -72,7 +73,7 @@ public class SessionObserver extends AbstractModelObserver<RealmSession> {
// update push info
pushHelper
.pushSetUser(RocketChatCache.getOrCreatePushId(context))
.pushSetUser(new RocketChatCache(context).getOrCreatePushId())
.continueWith(new LogIfError());
}
......
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