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 package chat.rocket.android.helper
import android.content.Context import android.content.Context
import chat.rocket.android.RocketChatCache
import chat.rocket.android.api.rest.CookieInterceptor import chat.rocket.android.api.rest.CookieInterceptor
import chat.rocket.android.api.rest.DefaultCookieProvider import chat.rocket.android.api.rest.DefaultCookieProvider
import com.facebook.stetho.okhttp3.StethoInterceptor import com.facebook.stetho.okhttp3.StethoInterceptor
...@@ -24,17 +23,18 @@ object OkHttpHelper { ...@@ -24,17 +23,18 @@ object OkHttpHelper {
return httpClientForUploadFile ?: throw AssertionError("httpClientForUploadFile set to null by another thread") return httpClientForUploadFile ?: throw AssertionError("httpClientForUploadFile set to null by another thread")
} }
fun getClientForDownloadFile(context: Context): OkHttpClient { fun getClientForDownloadFile(): OkHttpClient {
if(httpClientForDownloadFile == null) { if (httpClientForDownloadFile == null) {
httpClientForDownloadFile = OkHttpClient.Builder() httpClientForDownloadFile = OkHttpClient.Builder()
.addNetworkInterceptor(StethoInterceptor()) .addNetworkInterceptor(StethoInterceptor())
.followRedirects(true) .followRedirects(true)
.followSslRedirects(true) .followSslRedirects(true)
.addInterceptor(CookieInterceptor(DefaultCookieProvider(RocketChatCache(context)))) .addInterceptor(CookieInterceptor(DefaultCookieProvider()))
.build() .build()
} }
return httpClientForDownloadFile ?: throw AssertionError("httpClientForDownloadFile set to null by another thread") return httpClientForDownloadFile ?: throw AssertionError("httpClientForDownloadFile set to null by another thread")
} }
/** /**
* Returns the OkHttpClient instance for WebSocket connection. * Returns the OkHttpClient instance for WebSocket connection.
* @return The OkHttpClient WebSocket connection instance. * @return The OkHttpClient WebSocket connection instance.
......
...@@ -35,6 +35,7 @@ public class RocketChatApplication extends MultiDexApplication { ...@@ -35,6 +35,7 @@ public class RocketChatApplication extends MultiDexApplication {
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
RocketChatCache.INSTANCE.initialize(this);
JobManager.create(this).addJobCreator(new RocketChatJobCreator()); JobManager.create(this).addJobCreator(new RocketChatJobCreator());
DDPClient.initialize(OkHttpHelper.INSTANCE.getClientForWebSocket()); DDPClient.initialize(OkHttpHelper.INSTANCE.getClientForWebSocket());
Fabric.with(this, new Crashlytics()); Fabric.with(this, new Crashlytics());
...@@ -46,7 +47,7 @@ public class RocketChatApplication extends MultiDexApplication { ...@@ -46,7 +47,7 @@ public class RocketChatApplication extends MultiDexApplication {
RealmStore.put(serverInfo.getHostname()); 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) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
......
package chat.rocket.android;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.hadisatrio.optional.Optional;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import chat.rocket.android.helper.Logger;
import chat.rocket.android.log.RCLog;
import chat.rocket.core.utils.Pair;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import okhttp3.HttpUrl;
/**
* sharedpreference-based cache.
*/
public class RocketChatCache {
private static final String KEY_SELECTED_SERVER_HOSTNAME = "KEY_SELECTED_SERVER_HOSTNAME";
private static final String KEY_SELECTED_SITE_URL = "KEY_SELECTED_SITE_URL";
private static final String KEY_SELECTED_SITE_NAME = "KEY_SELECTED_SITE_NAME";
private static final String KEY_SELECTED_ROOM_ID = "KEY_SELECTED_ROOM_ID";
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;
public RocketChatCache(Context context) {
this.context = context.getApplicationContext();
}
public void addOpenedRoom(@NotNull String roomId, long lastSeen) {
JSONObject openedRooms = getOpenedRooms();
try {
JSONObject room = new JSONObject().put("rid", roomId).put("ls", lastSeen);
openedRooms.put(roomId, room);
} catch (JSONException e) {
RCLog.e(e);
}
setString(KEY_OPENED_ROOMS, openedRooms.toString());
}
public void removeOpenedRoom(@NotNull String roomId) {
JSONObject openedRooms = getOpenedRooms();
if (openedRooms.has(roomId)) {
openedRooms.remove(roomId);
}
}
@NotNull
public JSONObject getOpenedRooms() {
String openedRooms = getString(KEY_OPENED_ROOMS, "");
if (openedRooms.isEmpty()) {
return new JSONObject();
}
try {
return new JSONObject(openedRooms);
} catch (JSONException e) {
RCLog.e(e);
}
return new JSONObject();
}
public String getSelectedServerHostname() {
return getString(KEY_SELECTED_SERVER_HOSTNAME, null);
}
public void setSelectedServerHostname(String hostname) {
String newHostname = null;
if (hostname != null) {
newHostname = hostname.toLowerCase();
}
setString(KEY_SELECTED_SERVER_HOSTNAME, newHostname);
}
public void addSiteName(@NotNull String currentHostname, @NotNull String siteName) {
try {
String hostSiteNamesJson = getSiteName();
JSONObject jsonObject = (hostSiteNamesJson == null) ?
new JSONObject() : new JSONObject(hostSiteNamesJson);
jsonObject.put(currentHostname, siteName);
setString(KEY_SELECTED_SITE_NAME, jsonObject.toString());
} catch (JSONException e) {
RCLog.e(e);
}
}
public void removeSiteName(@NotNull String hostname) {
try {
String siteNameJson = getSiteName();
JSONObject jsonObject = (siteNameJson == null) ?
new JSONObject() : new JSONObject(siteNameJson);
if (jsonObject.has(hostname)) {
jsonObject.remove(hostname);
}
setString(KEY_SELECTED_SITE_NAME, jsonObject.toString());
} catch (JSONException e) {
RCLog.e(e);
}
}
@NotNull
public String getHostSiteName(@NotNull String host) {
if (host.startsWith("http")) {
HttpUrl url = HttpUrl.parse(host);
if (url != null) {
host = url.host();
}
}
try {
String hostSiteNamesJson = getSiteName();
JSONObject jsonObject = (hostSiteNamesJson == null) ?
new JSONObject() : new JSONObject(hostSiteNamesJson);
host = getSiteUrlFor(host);
return jsonObject.optString(host);
} catch (JSONException e) {
RCLog.e(e);
}
return "";
}
@Nullable
private String getSiteName() {
return getString(KEY_SELECTED_SITE_NAME, null);
}
public void addSiteUrl(@Nullable String hostnameAlias, @NotNull String currentHostname) {
String alias = null;
if (hostnameAlias != null) {
alias = hostnameAlias.toLowerCase();
}
try {
String selectedHostnameAliasJson = getSiteUrlForAllServers();
JSONObject jsonObject = selectedHostnameAliasJson == null ?
new JSONObject() : new JSONObject(selectedHostnameAliasJson);
jsonObject.put(alias, currentHostname);
setString(KEY_SELECTED_SITE_URL, jsonObject.toString());
} catch (JSONException e) {
RCLog.e(e);
}
}
private void removeSiteUrl(@NotNull String hostname) {
try {
String siteUrlForAllServersJson = getSiteUrlForAllServers();
JSONObject jsonObject = siteUrlForAllServersJson == null ?
new JSONObject() : new JSONObject(siteUrlForAllServersJson);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String alias = keys.next();
if (hostname.equals(jsonObject.getString(alias))) {
jsonObject.remove(alias);
break;
}
}
setString(KEY_SELECTED_SITE_URL, jsonObject.toString());
} catch (JSONException e) {
RCLog.e(e);
}
}
@Nullable
public String getSiteUrlFor(String hostname) {
try {
String selectedServerHostname = getSelectedServerHostname();
if (getSiteUrlForAllServers() == null || getSiteUrlForAllServers().isEmpty()) {
return null;
}
return new JSONObject(getSiteUrlForAllServers())
.optString(hostname, selectedServerHostname);
} catch (JSONException e) {
RCLog.e(e);
}
return null;
}
@Nullable
private String getSiteUrlForAllServers() {
return getString(KEY_SELECTED_SITE_URL, null);
}
public void addHostname(@NotNull String hostname, @Nullable String hostnameAvatarUri, String siteName) {
String hostnameList = getString(KEY_HOSTNAME_LIST, null);
try {
JSONObject json;
if (hostnameList == null) {
json = new JSONObject();
} else {
json = new JSONObject(hostnameList);
}
JSONObject serverInfoJson = new JSONObject();
serverInfoJson.put("avatar", hostnameAvatarUri);
serverInfoJson.put("sitename", siteName);
// Replace server avatar uri if exists.
json.put(hostname, hostnameAvatarUri == null ? JSONObject.NULL : serverInfoJson);
setString(KEY_HOSTNAME_LIST, json.toString());
} catch (JSONException e) {
RCLog.e(e);
}
}
public List<Pair<String, Pair<String, String>>> getServerList() {
String json = getString(KEY_HOSTNAME_LIST, null);
if (json == null) {
return Collections.emptyList();
}
try {
JSONObject jsonObj = new JSONObject(json);
List<Pair<String, Pair<String, String>>> serverList = new ArrayList<>();
for (Iterator<String> iter = jsonObj.keys(); iter.hasNext(); ) {
String hostname = iter.next();
JSONObject serverInfoJson = jsonObj.getJSONObject(hostname);
serverList.add(new Pair<>(hostname, new Pair<>(
"http://" + hostname + "/" + serverInfoJson.getString("avatar"),
serverInfoJson.getString("sitename"))));
}
return serverList;
} catch (JSONException e) {
RCLog.e(e);
}
return Collections.emptyList();
}
public void removeHostname(String hostname) {
String json = getString(KEY_HOSTNAME_LIST, null);
if (TextUtils.isEmpty(json)) {
return;
}
try {
JSONObject jsonObj = new JSONObject(json);
jsonObj.remove(hostname);
String result = jsonObj.length() == 0 ? null : jsonObj.toString();
setString(KEY_HOSTNAME_LIST, result);
} catch (JSONException e) {
RCLog.e(e);
}
}
@Nullable
public String getFirstLoggedHostnameIfAny() {
String json = getString(KEY_HOSTNAME_LIST, null);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj.length() > 0 && jsonObj.keys().hasNext()) {
// Returns the first hostname on the list.
return jsonObj.keys().next();
}
} catch (JSONException e) {
RCLog.e(e);
}
}
return null;
}
public String getSelectedRoomId() {
try {
JSONObject jsonObject = getSelectedRoomIdJsonObject();
return jsonObject.optString(getSelectedServerHostname(), null);
} catch (JSONException e) {
RCLog.e(e);
Logger.INSTANCE.report(e);
}
return null;
}
public void setSelectedRoomId(String roomId) {
try {
JSONObject jsonObject = getSelectedRoomIdJsonObject();
jsonObject.put(getSelectedServerHostname(), roomId);
setString(KEY_SELECTED_ROOM_ID, jsonObject.toString());
} catch (JSONException e) {
RCLog.e(e);
Logger.INSTANCE.report(e);
}
}
@NonNull
private JSONObject getSelectedRoomIdJsonObject() throws JSONException {
String json = getString(KEY_SELECTED_ROOM_ID, null);
if (json == null) {
return new JSONObject();
}
return new JSONObject(json);
}
public String getOrCreatePushId() {
SharedPreferences preferences = getSharedPreferences();
if (!preferences.contains(KEY_PUSH_ID)) {
// generates one and save
String newId = UUID.randomUUID().toString().replace("-", "");
preferences.edit()
.putString(KEY_PUSH_ID, newId)
.apply();
return newId;
}
return preferences.getString(KEY_PUSH_ID, null);
}
public Flowable<Optional<String>> getSelectedServerHostnamePublisher() {
return getValuePublisher(KEY_SELECTED_SERVER_HOSTNAME);
}
public Flowable<Optional<String>> getSelectedRoomIdPublisher() {
return getValuePublisher(KEY_SELECTED_ROOM_ID)
.filter(Optional::isPresent)
.map(Optional::get)
.map(roomValue -> Optional.ofNullable(new JSONObject(roomValue).optString(getSelectedServerHostname(), null)));
}
private SharedPreferences getSharedPreferences() {
return context.getSharedPreferences("cache", Context.MODE_PRIVATE);
}
private SharedPreferences.Editor getEditor() {
return getSharedPreferences().edit();
}
public 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<Optional<String>> getValuePublisher(final String key) {
return Flowable.create(emitter -> {
SharedPreferences.OnSharedPreferenceChangeListener
listener = (sharedPreferences, changedKey) -> {
if (key.equals(changedKey) && !emitter.isCancelled()) {
String value = getString(key, null);
emitter.onNext(Optional.ofNullable(value));
}
};
emitter.setCancellable(() -> getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(listener));
getSharedPreferences().registerOnSharedPreferenceChangeListener(listener);
}, BackpressureStrategy.LATEST);
}
public void removeSelectedRoomId(String currentHostname) {
try {
JSONObject selectedRoomIdJsonObject = getSelectedRoomIdJsonObject();
selectedRoomIdJsonObject.remove(currentHostname);
String result = selectedRoomIdJsonObject.length() == 0 ?
null : selectedRoomIdJsonObject.toString();
setString(KEY_SELECTED_ROOM_ID, result);
} catch (JSONException 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;
}
/**
* Wipe all given hostname entries and references from cache.
*/
public void clearSelectedHostnameReferences() {
String hostname = getSelectedServerHostname();
if (hostname != null) {
removeSiteName(hostname);
removeHostname(hostname);
removeSiteUrl(hostname);
setSelectedServerHostname(null);
}
}
}
package chat.rocket.android
import android.content.Context
import android.content.SharedPreferences
import android.text.TextUtils
import chat.rocket.android.helper.Logger
import chat.rocket.android.log.RCLog
import chat.rocket.core.utils.Pair
import com.hadisatrio.optional.Optional
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import okhttp3.HttpUrl
import org.json.JSONException
import org.json.JSONObject
import java.util.*
object RocketChatCache {
private val KEY_SELECTED_SERVER_HOSTNAME = "KEY_SELECTED_SERVER_HOSTNAME"
private val KEY_SELECTED_SITE_URL = "KEY_SELECTED_SITE_URL"
private val KEY_SELECTED_SITE_NAME = "KEY_SELECTED_SITE_NAME"
private val KEY_SELECTED_ROOM_ID = "KEY_SELECTED_ROOM_ID"
private val KEY_PUSH_ID = "KEY_PUSH_ID"
private val KEY_HOSTNAME_LIST = "KEY_HOSTNAME_LIST"
private val KEY_OPENED_ROOMS = "KEY_OPENED_ROOMS"
private val KEY_SESSION_TOKEN = "KEY_SESSION_TOKEN"
private lateinit var sharedPreferences: SharedPreferences
fun initialize(context: Context) {
sharedPreferences = context.getSharedPreferences("cache", Context.MODE_PRIVATE)
}
fun addOpenedRoom(roomId: String, lastSeen: Long) {
val openedRooms = getOpenedRooms()
try {
val room = JSONObject().put("rid", roomId).put("ls", lastSeen)
openedRooms.put(roomId, room)
} catch (e: JSONException) {
RCLog.e(e)
}
setString(KEY_OPENED_ROOMS, openedRooms.toString())
}
fun removeOpenedRoom(roomId: String) {
val openedRooms = getOpenedRooms()
if (openedRooms.has(roomId)) {
openedRooms.remove(roomId)
}
}
fun getOpenedRooms(): JSONObject {
val openedRooms = getString(KEY_OPENED_ROOMS, "")
openedRooms?.let {
if (openedRooms.isEmpty()) {
return JSONObject()
}
try {
return JSONObject(openedRooms)
} catch (e: JSONException) {
RCLog.e(e)
}
}
return JSONObject()
}
fun getSelectedServerHostname(): String? {
return getString(KEY_SELECTED_SERVER_HOSTNAME, null)
}
fun setSelectedRoomId(roomId: String) {
try {
val jsonObject = getSelectedRoomIdJsonObject()
jsonObject.put(getSelectedServerHostname(), roomId)
setString(KEY_SELECTED_ROOM_ID, jsonObject.toString())
} catch (e: JSONException) {
RCLog.e(e)
Logger.report(e)
}
}
@Throws(JSONException::class)
private fun getSelectedRoomIdJsonObject(): JSONObject {
val json = getString(KEY_SELECTED_ROOM_ID, null) ?: return JSONObject()
return JSONObject(json)
}
fun getOrCreatePushId(): String? {
val preferences = sharedPreferences
if (!preferences.contains(KEY_PUSH_ID)) {
// generates one and save
val newId = UUID.randomUUID().toString().replace("-", "")
preferences.edit()
.putString(KEY_PUSH_ID, newId)
.apply()
return newId
}
return preferences.getString(KEY_PUSH_ID, null)
}
fun addSiteName(currentHostname: String, siteName: String) {
try {
val hostSiteNamesJson = getSiteName()
val jsonObject = if (hostSiteNamesJson == null)
JSONObject()
else
JSONObject(hostSiteNamesJson)
jsonObject.put(currentHostname, siteName)
setString(KEY_SELECTED_SITE_NAME, jsonObject.toString())
} catch (e: JSONException) {
RCLog.e(e)
}
}
fun getHostSiteName(hostname: String): String {
var host = hostname
if (hostname.startsWith("http")) {
val url = HttpUrl.parse(hostname)
if (url != null) {
host = url.host()
}
}
try {
val hostSiteNamesJson = getSiteName()
val jsonObject = if (hostSiteNamesJson == null)
JSONObject()
else
JSONObject(hostSiteNamesJson)
val siteUrlFor = getSiteUrlFor(host)
return if (siteUrlFor == null) "" else jsonObject.optString(host)
} catch (e: JSONException) {
RCLog.e(e)
}
return ""
}
fun removeSiteName(hostname: String) {
try {
val siteNameJson = getSiteName()
val jsonObject = if (siteNameJson == null)
JSONObject()
else
JSONObject(siteNameJson)
if (jsonObject.has(hostname)) {
jsonObject.remove(hostname)
}
setString(KEY_SELECTED_SITE_NAME, jsonObject.toString())
} catch (e: JSONException) {
RCLog.e(e)
}
}
fun addSiteUrl(hostnameAlias: String?, currentHostname: String) {
var alias: String? = null
if (hostnameAlias != null) {
alias = hostnameAlias.toLowerCase()
}
try {
val selectedHostnameAliasJson = getSiteUrlForAllServers()
val jsonObject = if (selectedHostnameAliasJson == null)
JSONObject()
else
JSONObject(selectedHostnameAliasJson)
jsonObject.put(alias, currentHostname)
setString(KEY_SELECTED_SITE_URL, jsonObject.toString())
} catch (e: JSONException) {
RCLog.e(e)
}
}
fun getSiteUrlFor(hostname: String): String? {
try {
val selectedServerHostname = getSelectedServerHostname()
return if (getSiteUrlForAllServers() == null) null else JSONObject(getSiteUrlForAllServers())
.optString(hostname, selectedServerHostname)
} catch (e: JSONException) {
RCLog.e(e)
}
return null
}
fun addHostname(hostname: String, hostnameAvatarUri: String?, siteName: String) {
val hostnameList = getString(KEY_HOSTNAME_LIST, null)
try {
val json: JSONObject
if (hostnameList == null) {
json = JSONObject()
} else {
json = JSONObject(hostnameList)
}
val serverInfoJson = JSONObject()
serverInfoJson.put("avatar", hostnameAvatarUri)
serverInfoJson.put("sitename", siteName)
// Replace server avatar uri if exists.
json.put(hostname, if (hostnameAvatarUri == null) JSONObject.NULL else serverInfoJson)
setString(KEY_HOSTNAME_LIST, json.toString())
} catch (e: JSONException) {
RCLog.e(e)
}
}
fun getServerList(): List<Pair<String, Pair<String, String>>> {
val json = getString(KEY_HOSTNAME_LIST, null) ?: return emptyList()
try {
val jsonObj = JSONObject(json)
val serverList = ArrayList<Pair<String, Pair<String, String>>>()
val iter = jsonObj.keys()
while (iter.hasNext()) {
val hostname = iter.next()
val serverInfoJson = jsonObj.getJSONObject(hostname)
serverList.add(Pair(hostname, Pair(
"http://" + hostname + "/" + serverInfoJson.getString("avatar"),
serverInfoJson.getString("sitename"))))
}
return serverList
} catch (e: JSONException) {
RCLog.e(e)
}
return emptyList()
}
/**
* Wipe all given hostname entries and references from cache.
*/
fun clearSelectedHostnameReferences() {
val hostname = getSelectedServerHostname()
if (hostname != null) {
removeSiteName(hostname)
removeHostname(hostname)
removeSiteUrl(hostname)
setSelectedServerHostname(null)
}
}
fun removeHostname(hostname: String) {
val json = getString(KEY_HOSTNAME_LIST, null)
if (TextUtils.isEmpty(json)) {
return
}
try {
val jsonObj = JSONObject(json)
jsonObj.remove(hostname)
val result = if (jsonObj.length() == 0) null else jsonObj.toString()
setString(KEY_HOSTNAME_LIST, result)
} catch (e: JSONException) {
RCLog.e(e)
}
}
fun setSelectedServerHostname(hostname: String?) {
var newHostname: String? = null
if (hostname != null) {
newHostname = hostname.toLowerCase()
}
setString(KEY_SELECTED_SERVER_HOSTNAME, newHostname)
}
fun getSelectedRoomId(): String? {
try {
val jsonObject = getSelectedRoomIdJsonObject()
return jsonObject.optString(getSelectedServerHostname(), null)
} catch (e: JSONException) {
RCLog.e(e)
Logger.report(e)
}
return null
}
fun removeSelectedRoomId(currentHostname: String) {
try {
val selectedRoomIdJsonObject = getSelectedRoomIdJsonObject()
selectedRoomIdJsonObject.remove(currentHostname)
val result = if (selectedRoomIdJsonObject.length() == 0) null else selectedRoomIdJsonObject.toString()
setString(KEY_SELECTED_ROOM_ID, result)
} catch (e: JSONException) {
Logger.report(e)
RCLog.e(e)
}
}
fun getFirstLoggedHostnameIfAny(): String? {
val json = getString(KEY_HOSTNAME_LIST, null)
if (json != null) {
try {
val jsonObj = JSONObject(json)
if (jsonObj.length() > 0 && jsonObj.keys().hasNext()) {
// Returns the first hostname on the list.
return jsonObj.keys().next()
}
} catch (e: JSONException) {
RCLog.e(e)
}
}
return null
}
fun setSessionToken(sessionToken: String) {
val selectedServerHostname = getSelectedServerHostname() ?:
throw IllegalStateException("Trying to set sessionToken to null hostname")
val sessions = getSessionToken()
try {
val jsonObject = if (sessions == null) JSONObject() else JSONObject(sessions)
jsonObject.put(selectedServerHostname, sessionToken)
setString(KEY_SESSION_TOKEN, jsonObject.toString())
} catch (e: JSONException) {
RCLog.e(e)
}
}
fun getSessionToken(): String? {
val selectedServerHostname = getSelectedServerHostname()
val sessions = getString(KEY_SESSION_TOKEN, null)
if (sessions == null || selectedServerHostname == null) {
return null
}
try {
val jsonObject = JSONObject(sessions)
if (jsonObject.has(selectedServerHostname)) {
return jsonObject.optString(selectedServerHostname, null)
}
} catch (e: JSONException) {
RCLog.e(e)
}
return null
}
private fun removeSiteUrl(hostname: String) {
try {
val siteUrlForAllServersJson = getSiteUrlForAllServers()
val jsonObject = if (siteUrlForAllServersJson == null)
JSONObject()
else
JSONObject(siteUrlForAllServersJson)
val keys = jsonObject.keys()
while (keys.hasNext()) {
val alias = keys.next()
if (hostname == jsonObject.getString(alias)) {
jsonObject.remove(alias)
break
}
}
setString(KEY_SELECTED_SITE_URL, jsonObject.toString())
} catch (e: JSONException) {
RCLog.e(e)
}
}
private fun getString(key: String, defaultValue: String?): String? {
return sharedPreferences.getString(key, defaultValue)
}
private fun getSiteUrlForAllServers(): String? {
return getString(KEY_SELECTED_SITE_URL, null)
}
private fun setString(key: String, value: String?) {
getEditor().putString(key, value).apply()
}
private fun getSiteName(): String? {
return getString(KEY_SELECTED_SITE_NAME, null)
}
private fun getEditor(): SharedPreferences.Editor {
return sharedPreferences.edit()
}
fun getSelectedServerHostnamePublisher(): Flowable<Optional<String>> {
return getValuePublisher(KEY_SELECTED_SERVER_HOSTNAME)
}
fun getSelectedRoomIdPublisher(): Flowable<Optional<String>> {
return getValuePublisher(KEY_SELECTED_ROOM_ID)
.filter { it.isPresent() }
.map { it.get() }
.map { roomValue -> Optional.ofNullable(JSONObject(roomValue).optString(getSelectedServerHostname(), null)) }
}
private fun getValuePublisher(key: String): Flowable<Optional<String>> {
return Flowable.create({ emitter ->
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, changedKey ->
if (key == changedKey && !emitter.isCancelled) {
val value = getString(key, null)
emitter.onNext(Optional.ofNullable(value))
}
}
emitter.setCancellable {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener)
}
sharedPreferences.registerOnSharedPreferenceChangeListener(listener)
}, BackpressureStrategy.LATEST)
}
}
\ No newline at end of file
...@@ -24,10 +24,11 @@ import io.reactivex.schedulers.Schedulers; ...@@ -24,10 +24,11 @@ import io.reactivex.schedulers.Schedulers;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
abstract class AbstractAuthedActivity extends AbstractFragmentActivity { abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
@State protected String hostname; @State
@State protected String roomId; protected String hostname;
@State
protected String roomId;
private RocketChatCache rocketChatCache;
private CompositeDisposable compositeDisposable = new CompositeDisposable(); private CompositeDisposable compositeDisposable = new CompositeDisposable();
private boolean isNotification; private boolean isNotification;
...@@ -36,13 +37,11 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -36,13 +37,11 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
rocketChatCache = new RocketChatCache(this);
if (savedInstanceState == null) { if (savedInstanceState == null) {
handleIntent(getIntent()); handleIntent(getIntent());
} }
updateHostnameIfNeeded(rocketChatCache.getSelectedServerHostname()); updateHostnameIfNeeded(RocketChatCache.INSTANCE.getSelectedServerHostname());
} }
@Override @Override
...@@ -61,16 +60,16 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -61,16 +60,16 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
HttpUrl url = HttpUrl.parse(hostname); HttpUrl url = HttpUrl.parse(hostname);
if (url != null) { if (url != null) {
String hostnameFromPush = url.host(); String hostnameFromPush = url.host();
String loginHostname = rocketChatCache.getSiteUrlFor(hostnameFromPush); String loginHostname = RocketChatCache.INSTANCE.getSiteUrlFor(hostnameFromPush);
rocketChatCache.setSelectedServerHostname(loginHostname); RocketChatCache.INSTANCE.setSelectedServerHostname(loginHostname);
if (intent.hasExtra(PushManager.EXTRA_ROOM_ID)) { if (intent.hasExtra(PushManager.EXTRA_ROOM_ID)) {
rocketChatCache.setSelectedRoomId(intent.getStringExtra(PushManager.EXTRA_ROOM_ID)); RocketChatCache.INSTANCE.setSelectedRoomId(intent.getStringExtra(PushManager.EXTRA_ROOM_ID));
} }
} }
PushManager.INSTANCE.clearNotificationsByHost(hostname); PushManager.INSTANCE.clearNotificationsByHost(hostname);
} else { } else {
updateHostnameIfNeeded(rocketChatCache.getSelectedServerHostname()); updateHostnameIfNeeded(RocketChatCache.INSTANCE.getSelectedServerHostname());
} }
if (intent.hasExtra(PushManager.EXTRA_NOT_ID) && intent.hasExtra(PushManager.EXTRA_HOSTNAME)) { if (intent.hasExtra(PushManager.EXTRA_NOT_ID) && intent.hasExtra(PushManager.EXTRA_HOSTNAME)) {
...@@ -80,7 +79,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -80,7 +79,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
HttpUrl url = HttpUrl.parse(hostname); HttpUrl url = HttpUrl.parse(hostname);
if (url != null) { if (url != null) {
String hostnameFromPush = url.host(); String hostnameFromPush = url.host();
String loginHostname = rocketChatCache.getSiteUrlFor(hostnameFromPush); String loginHostname = RocketChatCache.INSTANCE.getSiteUrlFor(hostnameFromPush);
PushManager.INSTANCE.clearNotificationsByHostAndNotificationId(loginHostname, notificationId); PushManager.INSTANCE.clearNotificationsByHostAndNotificationId(loginHostname, notificationId);
} else { } else {
PushManager.INSTANCE.clearNotificationsByNotificationId(notificationId); PushManager.INSTANCE.clearNotificationsByNotificationId(notificationId);
...@@ -93,14 +92,14 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -93,14 +92,14 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
if (hostname == null) { if (hostname == null) {
if (newHostname != null && assertServerRealmStoreExists(newHostname)) { if (newHostname != null && assertServerRealmStoreExists(newHostname)) {
updateHostname(newHostname); updateHostname(newHostname);
updateRoomIdIfNeeded(rocketChatCache.getSelectedRoomId()); updateRoomIdIfNeeded(RocketChatCache.INSTANCE.getSelectedRoomId());
} else { } else {
recoverFromHostnameError(); recoverFromHostnameError();
} }
} else { } else {
if (hostname.equals(newHostname)) { if (hostname.equals(newHostname)) {
updateHostname(newHostname); updateHostname(newHostname);
updateRoomIdIfNeeded(rocketChatCache.getSelectedRoomId()); updateRoomIdIfNeeded(RocketChatCache.INSTANCE.getSelectedRoomId());
return; return;
} }
...@@ -135,8 +134,8 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -135,8 +134,8 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
// just connect to the first available // just connect to the first available
final ServerInfo serverInfo = serverInfoList.get(0); final ServerInfo serverInfo = serverInfoList.get(0);
rocketChatCache.setSelectedServerHostname(serverInfo.getHostname()); RocketChatCache.INSTANCE.setSelectedServerHostname(serverInfo.getHostname());
rocketChatCache.setSelectedRoomId(null); RocketChatCache.INSTANCE.setSelectedRoomId(null);
} }
private void updateRoomIdIfNeeded(String newRoomId) { private void updateRoomIdIfNeeded(String newRoomId) {
...@@ -159,7 +158,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -159,7 +158,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
RealmRoom room = RealmStore.get(hostname).executeTransactionForRead(realm -> RealmRoom room = RealmStore.get(hostname).executeTransactionForRead(realm ->
realm.where(RealmRoom.class).equalTo(RealmRoom.ROOM_ID, roomId).findFirst()); realm.where(RealmRoom.class).equalTo(RealmRoom.ROOM_ID, roomId).findFirst());
if (room == null) { if (room == null) {
rocketChatCache.setSelectedRoomId(null); RocketChatCache.INSTANCE.setSelectedRoomId(null);
return false; return false;
} }
return true; return true;
...@@ -184,8 +183,8 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -184,8 +183,8 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
ConnectivityManager.getInstance(getApplicationContext()).keepAliveServer(); ConnectivityManager.getInstance(getApplicationContext()).keepAliveServer();
if (isNotification) { if (isNotification) {
updateHostnameIfNeeded(rocketChatCache.getSelectedServerHostname()); updateHostnameIfNeeded(RocketChatCache.INSTANCE.getSelectedServerHostname());
updateRoomIdIfNeeded(rocketChatCache.getSelectedRoomId()); updateRoomIdIfNeeded(RocketChatCache.INSTANCE.getSelectedRoomId());
isNotification = false; isNotification = false;
} }
} }
...@@ -204,7 +203,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -204,7 +203,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
private void subscribeToConfigChanges() { private void subscribeToConfigChanges() {
compositeDisposable.add( compositeDisposable.add(
rocketChatCache.getSelectedServerHostnamePublisher() RocketChatCache.INSTANCE.getSelectedServerHostnamePublisher()
.map(Optional::get) .map(Optional::get)
.distinctUntilChanged() .distinctUntilChanged()
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
...@@ -216,7 +215,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -216,7 +215,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
); );
compositeDisposable.add( compositeDisposable.add(
rocketChatCache.getSelectedRoomIdPublisher() RocketChatCache.INSTANCE.getSelectedRoomIdPublisher()
.filter(Optional::isPresent) .filter(Optional::isPresent)
.map(Optional::get) .map(Optional::get)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
......
...@@ -89,4 +89,12 @@ public class LoginActivity extends AbstractFragmentActivity implements LoginCont ...@@ -89,4 +89,12 @@ public class LoginActivity extends AbstractFragmentActivity implements LoginCont
finish(); finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
} }
@Override
protected boolean onBackPress() {
LoginFragment loginFragment = (LoginFragment) getSupportFragmentManager()
.findFragmentById(getLayoutContainerForFragment());
loginFragment.goBack();
return true;
}
} }
...@@ -81,7 +81,7 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract ...@@ -81,7 +81,7 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
ConnectivityManagerApi connectivityManager = ConnectivityManager.getInstance(getApplicationContext()); ConnectivityManagerApi connectivityManager = ConnectivityManager.getInstance(getApplicationContext());
if (hostname == null || presenter == null) { if (hostname == null || presenter == null) {
String previousHostname = hostname; String previousHostname = hostname;
hostname = new RocketChatCache(getApplicationContext()).getSelectedServerHostname(); hostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
if (hostname == null) { if (hostname == null) {
showAddServerScreen(); showAddServerScreen();
} else { } else {
...@@ -95,7 +95,7 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract ...@@ -95,7 +95,7 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
connectivityManager.keepAliveServer(); connectivityManager.keepAliveServer();
presenter.bindView(this); presenter.bindView(this);
presenter.loadSignedInServers(hostname); presenter.loadSignedInServers(hostname);
roomId = new RocketChatCache(getApplicationContext()).getSelectedRoomId(); roomId = RocketChatCache.INSTANCE.getSelectedRoomId();
} }
} }
...@@ -186,15 +186,12 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract ...@@ -186,15 +186,12 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
PublicSettingRepository publicSettingRepository = new RealmPublicSettingRepository(hostname); PublicSettingRepository publicSettingRepository = new RealmPublicSettingRepository(hostname);
RocketChatCache rocketChatCache = new RocketChatCache(this);
presenter = new MainPresenter( presenter = new MainPresenter(
roomInteractor, roomInteractor,
createRoomInteractor, createRoomInteractor,
sessionInteractor, sessionInteractor,
new MethodCallHelper(this, hostname), new MethodCallHelper(this, hostname),
ConnectivityManager.getInstance(getApplicationContext()), ConnectivityManager.getInstance(getApplicationContext()),
rocketChatCache,
publicSettingRepository publicSettingRepository
); );
...@@ -203,12 +200,12 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract ...@@ -203,12 +200,12 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
presenter.bindView(this); presenter.bindView(this);
presenter.loadSignedInServers(hostname); presenter.loadSignedInServers(hostname);
roomId = rocketChatCache.getSelectedRoomId(); roomId = RocketChatCache.INSTANCE.getSelectedRoomId();
} }
private void updateSidebarMainFragment() { private void updateSidebarMainFragment() {
closeSidebarIfNeeded(); closeSidebarIfNeeded();
String selectedServerHostname = new RocketChatCache(this).getSelectedServerHostname(); String selectedServerHostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
Fragment sidebarFragment = findFragmentByTag(selectedServerHostname); Fragment sidebarFragment = findFragmentByTag(selectedServerHostname);
if (sidebarFragment == null) { if (sidebarFragment == null) {
sidebarFragment = SidebarMainFragment.create(selectedServerHostname); sidebarFragment = SidebarMainFragment.create(selectedServerHostname);
...@@ -399,15 +396,14 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract ...@@ -399,15 +396,14 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
private void changeServerIfNeeded(String serverHostname) { private void changeServerIfNeeded(String serverHostname) {
if (!hostname.equalsIgnoreCase(serverHostname)) { if (!hostname.equalsIgnoreCase(serverHostname)) {
RocketChatCache rocketChatCache = new RocketChatCache(getApplicationContext()); RocketChatCache.INSTANCE.setSelectedServerHostname(serverHostname);
rocketChatCache.setSelectedServerHostname(serverHostname);
} }
} }
@DebugLog @DebugLog
public void onLogout() { public void onLogout() {
presenter.prepareToLogout(); presenter.prepareToLogout();
if (new RocketChatCache(getApplicationContext()).getSelectedServerHostname() == null) { if (RocketChatCache.INSTANCE.getSelectedServerHostname() == null) {
finish(); finish();
LaunchUtil.showMainActivity(this); LaunchUtil.showMainActivity(this);
} else { } else {
......
...@@ -41,7 +41,6 @@ public class MainPresenter extends BasePresenter<MainContract.View> ...@@ -41,7 +41,6 @@ public class MainPresenter extends BasePresenter<MainContract.View>
private final SessionInteractor sessionInteractor; private final SessionInteractor sessionInteractor;
private final MethodCallHelper methodCallHelper; private final MethodCallHelper methodCallHelper;
private final ConnectivityManagerApi connectivityManagerApi; private final ConnectivityManagerApi connectivityManagerApi;
private final RocketChatCache rocketChatCache;
private final PublicSettingRepository publicSettingRepository; private final PublicSettingRepository publicSettingRepository;
public MainPresenter(RoomInteractor roomInteractor, public MainPresenter(RoomInteractor roomInteractor,
...@@ -49,13 +48,12 @@ public class MainPresenter extends BasePresenter<MainContract.View> ...@@ -49,13 +48,12 @@ public class MainPresenter extends BasePresenter<MainContract.View>
SessionInteractor sessionInteractor, SessionInteractor sessionInteractor,
MethodCallHelper methodCallHelper, MethodCallHelper methodCallHelper,
ConnectivityManagerApi connectivityManagerApi, ConnectivityManagerApi connectivityManagerApi,
RocketChatCache rocketChatCache, PublicSettingRepository publicSettingRepository) { PublicSettingRepository publicSettingRepository) {
this.roomInteractor = roomInteractor; this.roomInteractor = roomInteractor;
this.canCreateRoomInteractor = canCreateRoomInteractor; this.canCreateRoomInteractor = canCreateRoomInteractor;
this.sessionInteractor = sessionInteractor; this.sessionInteractor = sessionInteractor;
this.methodCallHelper = methodCallHelper; this.methodCallHelper = methodCallHelper;
this.connectivityManagerApi = connectivityManagerApi; this.connectivityManagerApi = connectivityManagerApi;
this.rocketChatCache = rocketChatCache;
this.publicSettingRepository = publicSettingRepository; this.publicSettingRepository = publicSettingRepository;
} }
...@@ -101,7 +99,7 @@ public class MainPresenter extends BasePresenter<MainContract.View> ...@@ -101,7 +99,7 @@ public class MainPresenter extends BasePresenter<MainContract.View>
@Override @Override
public void release() { public void release() {
if (rocketChatCache.getSessionToken() != null) { if (RocketChatCache.INSTANCE.getSessionToken() != null) {
setUserAway(); setUserAway();
} }
...@@ -158,13 +156,13 @@ public class MainPresenter extends BasePresenter<MainContract.View> ...@@ -158,13 +156,13 @@ public class MainPresenter extends BasePresenter<MainContract.View>
String logoUrl = (jsonObject.has("url")) ? String logoUrl = (jsonObject.has("url")) ?
jsonObject.optString("url") : jsonObject.optString("defaultUrl"); jsonObject.optString("url") : jsonObject.optString("defaultUrl");
String siteName = serverInfoPair.second; String siteName = serverInfoPair.second;
rocketChatCache.addHostname(hostname.toLowerCase(), logoUrl, siteName); RocketChatCache.INSTANCE.addHostname(hostname.toLowerCase(), logoUrl, siteName);
return rocketChatCache.getServerList(); return RocketChatCache.INSTANCE.getServerList();
} }
private void openRoom() { private void openRoom() {
String hostname = rocketChatCache.getSelectedServerHostname(); String hostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
String roomId = rocketChatCache.getSelectedRoomId(); String roomId = RocketChatCache.INSTANCE.getSelectedRoomId();
if (roomId == null || roomId.length() == 0) { if (roomId == null || roomId.length() == 0) {
view.showHome(); view.showHome();
...@@ -214,7 +212,7 @@ public class MainPresenter extends BasePresenter<MainContract.View> ...@@ -214,7 +212,7 @@ public class MainPresenter extends BasePresenter<MainContract.View>
} }
// TODO: Should we remove below and above calls to view? // TODO: Should we remove below and above calls to view?
// view.showConnectionOk(); // view.showConnectionOk();
rocketChatCache.setSessionToken(session.getToken()); RocketChatCache.INSTANCE.setSessionToken(session.getToken());
}, },
Logger.INSTANCE::report Logger.INSTANCE::report
); );
......
...@@ -12,7 +12,6 @@ import java.util.UUID; ...@@ -12,7 +12,6 @@ import java.util.UUID;
import bolts.Continuation; import bolts.Continuation;
import bolts.Task; import bolts.Task;
import chat.rocket.android.RocketChatApplication;
import chat.rocket.android.RocketChatCache; import chat.rocket.android.RocketChatCache;
import chat.rocket.android.helper.CheckSum; import chat.rocket.android.helper.CheckSum;
import chat.rocket.android.helper.TextUtils; import chat.rocket.android.helper.TextUtils;
...@@ -304,9 +303,7 @@ public class MethodCallHelper { ...@@ -304,9 +303,7 @@ public class MethodCallHelper {
realm.createOrUpdateAllFromJson( realm.createOrUpdateAllFromJson(
RealmRoom.class, result); RealmRoom.class, result);
Context appContext = RocketChatApplication.getInstance(); JSONObject openedRooms = RocketChatCache.INSTANCE.getOpenedRooms();
RocketChatCache cache = new RocketChatCache(appContext);
JSONObject openedRooms = cache.getOpenedRooms();
RealmQuery<RealmRoom> query = realm.where(RealmRoom.class); RealmQuery<RealmRoom> query = realm.where(RealmRoom.class);
Iterator<String> keys = openedRooms.keys(); Iterator<String> keys = openedRooms.keys();
...@@ -314,7 +311,7 @@ public class MethodCallHelper { ...@@ -314,7 +311,7 @@ public class MethodCallHelper {
String rid = keys.next(); String rid = keys.next();
RealmRoom realmRoom = query.equalTo(RealmRoom.ID, rid).findFirst(); RealmRoom realmRoom = query.equalTo(RealmRoom.ID, rid).findFirst();
if (realmRoom == null) { if (realmRoom == null) {
cache.removeOpenedRoom(rid); RocketChatCache.INSTANCE.removeOpenedRoom(rid);
} else { } else {
loadMissedMessages(rid, realmRoom.getLastSeen()) loadMissedMessages(rid, realmRoom.getLastSeen())
.continueWithTask(task1 -> { .continueWithTask(task1 -> {
...@@ -511,9 +508,8 @@ public class MethodCallHelper { ...@@ -511,9 +508,8 @@ public class MethodCallHelper {
HttpUrl httpSiteUrl = HttpUrl.parse(siteUrl); HttpUrl httpSiteUrl = HttpUrl.parse(siteUrl);
if (httpSiteUrl != null) { if (httpSiteUrl != null) {
String host = httpSiteUrl.host(); String host = httpSiteUrl.host();
RocketChatCache rocketChatCache = new RocketChatCache(context); RocketChatCache.INSTANCE.addSiteUrl(host, currentHostname);
rocketChatCache.addSiteUrl(host, currentHostname); RocketChatCache.INSTANCE.addSiteName(currentHostname, siteName);
rocketChatCache.addSiteName(currentHostname, siteName);
} }
} }
......
...@@ -8,11 +8,6 @@ import chat.rocket.persistence.realm.models.internal.RealmSession; ...@@ -8,11 +8,6 @@ import chat.rocket.persistence.realm.models.internal.RealmSession;
public class DefaultCookieProvider implements CookieProvider { public class DefaultCookieProvider implements CookieProvider {
private RocketChatCache rocketChatCache;
public DefaultCookieProvider(RocketChatCache rocketChatCache) {
this.rocketChatCache = rocketChatCache;
}
@Override @Override
public String getHostname() { public String getHostname() {
...@@ -44,6 +39,6 @@ public class DefaultCookieProvider implements CookieProvider { ...@@ -44,6 +39,6 @@ public class DefaultCookieProvider implements CookieProvider {
} }
private String getHostnameFromCache() { private String getHostnameFromCache() {
return rocketChatCache.getSelectedServerHostname(); return RocketChatCache.INSTANCE.getSelectedServerHostname();
} }
} }
...@@ -32,7 +32,7 @@ public class InputHostnameFragment extends AbstractFragment implements InputHost ...@@ -32,7 +32,7 @@ public class InputHostnameFragment extends AbstractFragment implements InputHost
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
Context appContext = getContext().getApplicationContext(); Context appContext = getContext().getApplicationContext();
presenter = new InputHostnamePresenter(new RocketChatCache(appContext), ConnectivityManager.getInstance(appContext)); presenter = new InputHostnamePresenter(ConnectivityManager.getInstance(appContext));
} }
@Override @Override
......
...@@ -14,11 +14,9 @@ import io.reactivex.android.schedulers.AndroidSchedulers; ...@@ -14,11 +14,9 @@ import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposable;
public class InputHostnamePresenter extends BasePresenter<InputHostnameContract.View> implements InputHostnameContract.Presenter { public class InputHostnamePresenter extends BasePresenter<InputHostnameContract.View> implements InputHostnameContract.Presenter {
private final RocketChatCache rocketChatCache;
private final ConnectivityManagerApi connectivityManager; private final ConnectivityManagerApi connectivityManager;
public InputHostnamePresenter(RocketChatCache rocketChatCache, ConnectivityManagerApi connectivityManager) { public InputHostnamePresenter(ConnectivityManagerApi connectivityManager) {
this.rocketChatCache = rocketChatCache;
this.connectivityManager = connectivityManager; this.connectivityManager = connectivityManager;
} }
...@@ -54,7 +52,7 @@ public class InputHostnamePresenter extends BasePresenter<InputHostnameContract. ...@@ -54,7 +52,7 @@ public class InputHostnamePresenter extends BasePresenter<InputHostnameContract.
} }
private void onServerValid(String hostname, boolean usesSecureConnection) { private void onServerValid(String hostname, boolean usesSecureConnection) {
rocketChatCache.setSelectedServerHostname(hostname); RocketChatCache.INSTANCE.setSelectedServerHostname(hostname);
String server = hostname.replace("/", "."); String server = hostname.replace("/", ".");
connectivityManager.addOrUpdateServer(server, server, !usesSecureConnection); connectivityManager.addOrUpdateServer(server, server, !usesSecureConnection);
......
...@@ -170,7 +170,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View> ...@@ -170,7 +170,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
@Override @Override
public void loadMissedMessages() { public void loadMissedMessages() {
RocketChatApplication appContext = RocketChatApplication.getInstance(); RocketChatApplication appContext = RocketChatApplication.getInstance();
JSONObject openedRooms = new RocketChatCache(appContext).getOpenedRooms(); JSONObject openedRooms = RocketChatCache.INSTANCE.getOpenedRooms();
if (openedRooms.has(roomId)) { if (openedRooms.has(roomId)) {
try { try {
JSONObject room = openedRooms.getJSONObject(roomId); JSONObject room = openedRooms.getJSONObject(roomId);
...@@ -369,8 +369,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View> ...@@ -369,8 +369,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
.filter(Optional::isPresent) .filter(Optional::isPresent)
.map(Optional::get) .map(Optional::get)
.map(room -> { .map(room -> {
new RocketChatCache(RocketChatApplication.getInstance()) RocketChatCache.INSTANCE.addOpenedRoom(room.getRoomId(), room.getLastSeen());
.addOpenedRoom(room.getRoomId(), room.getLastSeen());
return room; return room;
}) })
.flatMap(messageInteractor::getAllFrom) .flatMap(messageInteractor::getAllFrom)
......
...@@ -91,9 +91,7 @@ public class MessageOptionsDialogFragment extends BottomSheetDialogFragment { ...@@ -91,9 +91,7 @@ public class MessageOptionsDialogFragment extends BottomSheetDialogFragment {
} }
private void setUpDialog(final BottomSheetDialog bottomSheetDialog, String messageId) { private void setUpDialog(final BottomSheetDialog bottomSheetDialog, String messageId) {
RocketChatCache cache = new RocketChatCache(bottomSheetDialog.getContext()); String hostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
String hostname = cache.getSelectedServerHostname();
EditMessageInteractor editMessageInteractor = getEditMessageInteractor(hostname); EditMessageInteractor editMessageInteractor = getEditMessageInteractor(hostname);
......
...@@ -18,10 +18,14 @@ public interface LoginContract { ...@@ -18,10 +18,14 @@ public interface LoginContract {
void showLoginServices(List<LoginServiceConfiguration> loginServiceList); void showLoginServices(List<LoginServiceConfiguration> loginServiceList);
void showTwoStepAuth(); void showTwoStepAuth();
void goBack();
} }
interface Presenter extends BaseContract.Presenter<View> { interface Presenter extends BaseContract.Presenter<View> {
void login(String username, String password); void login(String username, String password);
void goBack();
} }
} }
...@@ -50,9 +50,9 @@ class LoginFragment : AbstractServerConfigFragment(), LoginContract.View { ...@@ -50,9 +50,9 @@ class LoginFragment : AbstractServerConfigFragment(), LoginContract.View {
txtPasswd = rootView.findViewById(R.id.editor_passwd) txtPasswd = rootView.findViewById(R.id.editor_passwd)
waitingView = rootView.findViewById(R.id.waiting) 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()) UserRegistrationDialogFragment.create(hostname, txtUsername.text.toString(), txtPasswd.text.toString())
.show(fragmentManager!!, "UserRegistrationDialogFragment") .show(fragmentManager!!, "UserRegistrationDialogFragment")
} }
...@@ -84,7 +84,7 @@ class LoginFragment : AbstractServerConfigFragment(), LoginContract.View { ...@@ -84,7 +84,7 @@ class LoginFragment : AbstractServerConfigFragment(), LoginContract.View {
for (info in OAuthProviderInfo.LIST) { for (info in OAuthProviderInfo.LIST) {
if (supportedMap[info.serviceName] == false && info.serviceName == authProvider.service) { if (supportedMap[info.serviceName] == false && info.serviceName == authProvider.service) {
supportedMap.put(info.serviceName, true) supportedMap.put(info.serviceName, true)
viewMap[info.serviceName]?.setOnClickListener { view -> viewMap[info.serviceName]?.setOnClickListener { _ ->
var fragment: Fragment? = null var fragment: Fragment? = null
try { try {
fragment = info.fragmentClass.newInstance() fragment = info.fragmentClass.newInstance()
...@@ -126,4 +126,8 @@ class LoginFragment : AbstractServerConfigFragment(), LoginContract.View { ...@@ -126,4 +126,8 @@ class LoginFragment : AbstractServerConfigFragment(), LoginContract.View {
presenter.release() presenter.release()
super.onPause() super.onPause()
} }
override fun goBack() {
presenter.goBack()
}
} }
...@@ -30,17 +30,14 @@ class LoginPresenter(private val loginServiceConfigurationRepository: LoginServi ...@@ -30,17 +30,14 @@ class LoginPresenter(private val loginServiceConfigurationRepository: LoginServi
getLoginServices() getLoginServices()
} }
override fun release() { override fun goBack() {
val context = RocketChatApplication.getInstance() val context = RocketChatApplication.getInstance()
val rocketChatCache = RocketChatCache(context) val hostname = RocketChatCache.getSelectedServerHostname()
val hostname = rocketChatCache.selectedServerHostname
hostname?.let { hostname?.let {
ConnectivityManager.getInstance(context).removeServer(hostname) ConnectivityManager.getInstance(context).removeServer(hostname)
rocketChatCache.clearSelectedHostnameReferences() RocketChatCache.clearSelectedHostnameReferences()
} }
super.release()
LaunchUtil.showMainActivity(context) LaunchUtil.showMainActivity(context)
} }
......
...@@ -94,13 +94,11 @@ public class SidebarMainFragment extends AbstractFragment implements SidebarMain ...@@ -94,13 +94,11 @@ public class SidebarMainFragment extends AbstractFragment implements SidebarMain
new SessionInteractor(new RealmSessionRepository(hostname)) new SessionInteractor(new RealmSessionRepository(hostname))
); );
RocketChatCache rocketChatCache = new RocketChatCache(getContext().getApplicationContext());
presenter = new SidebarMainPresenter( presenter = new SidebarMainPresenter(
hostname, hostname,
new RoomInteractor(new RealmRoomRepository(hostname)), new RoomInteractor(new RealmRoomRepository(hostname)),
userRepository, userRepository,
rocketChatCache,
absoluteUrlHelper, absoluteUrlHelper,
new MethodCallHelper(getContext(), hostname), new MethodCallHelper(getContext(), hostname),
new RealmSpotlightRepository(hostname) new RealmSpotlightRepository(hostname)
......
...@@ -38,7 +38,6 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View ...@@ -38,7 +38,6 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
private final String hostname; private final String hostname;
private final RoomInteractor roomInteractor; private final RoomInteractor roomInteractor;
private final UserRepository userRepository; private final UserRepository userRepository;
private final RocketChatCache rocketChatCache;
private final AbsoluteUrlHelper absoluteUrlHelper; private final AbsoluteUrlHelper absoluteUrlHelper;
private final MethodCallHelper methodCallHelper; private final MethodCallHelper methodCallHelper;
private SpotlightRepository realmSpotlightRepository; private SpotlightRepository realmSpotlightRepository;
...@@ -47,14 +46,12 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View ...@@ -47,14 +46,12 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
public SidebarMainPresenter(String hostname, public SidebarMainPresenter(String hostname,
RoomInteractor roomInteractor, RoomInteractor roomInteractor,
UserRepository userRepository, UserRepository userRepository,
RocketChatCache rocketChatCache,
AbsoluteUrlHelper absoluteUrlHelper, AbsoluteUrlHelper absoluteUrlHelper,
MethodCallHelper methodCallHelper, MethodCallHelper methodCallHelper,
RealmSpotlightRepository realmSpotlightRepository) { RealmSpotlightRepository realmSpotlightRepository) {
this.hostname = hostname; this.hostname = hostname;
this.roomInteractor = roomInteractor; this.roomInteractor = roomInteractor;
this.userRepository = userRepository; this.userRepository = userRepository;
this.rocketChatCache = rocketChatCache;
this.absoluteUrlHelper = absoluteUrlHelper; this.absoluteUrlHelper = absoluteUrlHelper;
this.methodCallHelper = methodCallHelper; this.methodCallHelper = methodCallHelper;
this.realmSpotlightRepository = realmSpotlightRepository; this.realmSpotlightRepository = realmSpotlightRepository;
...@@ -87,7 +84,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View ...@@ -87,7 +84,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
@Override @Override
public void onRoomSelected(RoomSidebar roomSidebar) { public void onRoomSelected(RoomSidebar roomSidebar) {
rocketChatCache.setSelectedRoomId(roomSidebar.getRoomId()); RocketChatCache.INSTANCE.setSelectedRoomId(roomSidebar.getRoomId());
} }
@Override @Override
...@@ -103,7 +100,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View ...@@ -103,7 +100,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
methodCallHelper.createDirectMessage(username) methodCallHelper.createDirectMessage(username)
.continueWithTask(task -> { .continueWithTask(task -> {
if (task.isCompleted()) { if (task.isCompleted()) {
rocketChatCache.setSelectedRoomId(task.getResult()); RocketChatCache.INSTANCE.setSelectedRoomId(task.getResult());
} }
return null; return null;
}); });
...@@ -111,7 +108,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View ...@@ -111,7 +108,7 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
methodCallHelper.joinRoom(spotlight.getId()) methodCallHelper.joinRoom(spotlight.getId())
.continueWithTask(task -> { .continueWithTask(task -> {
if (task.isCompleted()) { if (task.isCompleted()) {
rocketChatCache.setSelectedRoomId(spotlight.getId()); RocketChatCache.INSTANCE.setSelectedRoomId(spotlight.getId());
} }
return null; return null;
}); });
...@@ -157,12 +154,12 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View ...@@ -157,12 +154,12 @@ public class SidebarMainPresenter extends BasePresenter<SidebarMainContract.View
} }
clearSubscriptions(); clearSubscriptions();
String currentHostname = rocketChatCache.getSelectedServerHostname(); String currentHostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
RealmHelper realmHelper = RealmStore.getOrCreate(currentHostname); RealmHelper realmHelper = RealmStore.getOrCreate(currentHostname);
return realmHelper.executeTransaction(realm -> { return realmHelper.executeTransaction(realm -> {
rocketChatCache.removeHostname(currentHostname); RocketChatCache.INSTANCE.removeHostname(currentHostname);
rocketChatCache.removeSelectedRoomId(currentHostname); RocketChatCache.INSTANCE.removeSelectedRoomId(currentHostname);
rocketChatCache.setSelectedServerHostname(rocketChatCache.getFirstLoggedHostnameIfAny()); RocketChatCache.INSTANCE.setSelectedServerHostname(RocketChatCache.INSTANCE.getFirstLoggedHostnameIfAny());
realm.executeTransactionAsync(Realm::deleteAll); realm.executeTransactionAsync(Realm::deleteAll);
view.onPreparedToLogOut(); view.onPreparedToLogOut();
ConnectivityManager.getInstance(RocketChatApplication.getInstance()) ConnectivityManager.getInstance(RocketChatApplication.getInstance())
......
...@@ -48,9 +48,7 @@ public class MessagePopup { ...@@ -48,9 +48,7 @@ public class MessagePopup {
} }
private void showAvailableActionsOnly(Context context) { private void showAvailableActionsOnly(Context context) {
RocketChatCache cache = new RocketChatCache(context.getApplicationContext()); String hostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
String hostname = cache.getSelectedServerHostname();
EditMessageInteractor editMessageInteractor = getEditMessageInteractor(hostname); EditMessageInteractor editMessageInteractor = getEditMessageInteractor(hostname);
...@@ -167,7 +165,7 @@ public class MessagePopup { ...@@ -167,7 +165,7 @@ public class MessagePopup {
} }
public MessagePopup setDeleteAction(ActionListener actionListener) { public MessagePopup setDeleteAction(ActionListener actionListener) {
DELETE_ACTION_INFO.actionListener= actionListener; DELETE_ACTION_INFO.actionListener = actionListener;
return singleton; return singleton;
} }
......
package chat.rocket.android.push package chat.rocket.android.push
import android.annotation.SuppressLint
import android.app.Notification import android.app.Notification
import android.app.NotificationChannel import android.app.NotificationChannel
import android.app.NotificationManager import android.app.NotificationManager
...@@ -137,6 +138,7 @@ object PushManager { ...@@ -137,6 +138,7 @@ object PushManager {
return group return group
} }
@SuppressLint("NewApi")
internal fun showNotification(context: Context, lastPushMessage: PushMessage) { internal fun showNotification(context: Context, lastPushMessage: PushMessage) {
if (lastPushMessage.host == null || lastPushMessage.message == null || lastPushMessage.title == null) { if (lastPushMessage.host == null || lastPushMessage.message == null || lastPushMessage.title == null) {
return return
...@@ -202,7 +204,7 @@ object PushManager { ...@@ -202,7 +204,7 @@ object PushManager {
.setDeleteIntent(deleteIntent) .setDeleteIntent(deleteIntent)
.setMessageNotification() .setMessageNotification()
val subText = RocketChatCache(context).getHostSiteName(host) val subText = RocketChatCache.getHostSiteName(host)
if (subText.isNotEmpty()) { if (subText.isNotEmpty()) {
builder.setSubText(subText) builder.setSubText(subText)
} }
...@@ -257,6 +259,7 @@ object PushManager { ...@@ -257,6 +259,7 @@ object PushManager {
} }
} }
@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.N) @RequiresApi(Build.VERSION_CODES.N)
internal fun createGroupNotificationForNougatAndAbove(context: Context, lastPushMessage: PushMessage): Notification? { internal fun createGroupNotificationForNougatAndAbove(context: Context, lastPushMessage: PushMessage): Notification? {
with(lastPushMessage) { with(lastPushMessage) {
...@@ -289,7 +292,7 @@ object PushManager { ...@@ -289,7 +292,7 @@ object PushManager {
manager.createNotificationChannel(groupChannel) manager.createNotificationChannel(groupChannel)
} }
val subText = RocketChatCache(context).getHostSiteName(host) val subText = RocketChatCache.getHostSiteName(host)
if (subText.isNotEmpty()) { if (subText.isNotEmpty()) {
builder.setSubText(subText) builder.setSubText(subText)
} }
...@@ -344,7 +347,7 @@ object PushManager { ...@@ -344,7 +347,7 @@ object PushManager {
.setContentIntent(contentIntent) .setContentIntent(contentIntent)
.setMessageNotification() .setMessageNotification()
val subText = RocketChatCache(context).getHostSiteName(host) val subText = RocketChatCache.getHostSiteName(host)
if (subText.isNotEmpty()) { if (subText.isNotEmpty()) {
builder.setSubText(subText) builder.setSubText(subText)
} }
...@@ -370,6 +373,7 @@ object PushManager { ...@@ -370,6 +373,7 @@ object PushManager {
} }
} }
@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.N) @RequiresApi(Build.VERSION_CODES.N)
internal fun createSingleNotificationForNougatAndAbove(context: Context, lastPushMessage: PushMessage): Notification? { internal fun createSingleNotificationForNougatAndAbove(context: Context, lastPushMessage: PushMessage): Notification? {
val manager: NotificationManager = val manager: NotificationManager =
...@@ -404,7 +408,7 @@ object PushManager { ...@@ -404,7 +408,7 @@ object PushManager {
manager.createNotificationChannel(channel) manager.createNotificationChannel(channel)
} }
val subText = RocketChatCache(context).getHostSiteName(host) val subText = RocketChatCache.getHostSiteName(host)
if (subText.isNotEmpty()) { if (subText.isNotEmpty()) {
builder.setSubText(subText) builder.setSubText(subText)
} }
...@@ -647,7 +651,7 @@ object PushManager { ...@@ -647,7 +651,7 @@ object PushManager {
} }
val httpUrl = HttpUrl.parse(pushMessage.host) val httpUrl = HttpUrl.parse(pushMessage.host)
httpUrl?.let { httpUrl?.let {
val siteUrl = RocketChatCache(context).getSiteUrlFor(httpUrl.host()) val siteUrl = RocketChatCache.getSiteUrlFor(httpUrl.host())
if (siteUrl != null) { if (siteUrl != null) {
sendMessage(siteUrl, message, pushMessage.rid) sendMessage(siteUrl, message, pushMessage.rid)
} }
......
...@@ -2,7 +2,6 @@ package chat.rocket.android.service ...@@ -2,7 +2,6 @@ package chat.rocket.android.service
import chat.rocket.android.ConnectionStatusManager import chat.rocket.android.ConnectionStatusManager
import chat.rocket.android.RocketChatApplication import chat.rocket.android.RocketChatApplication
import chat.rocket.android.RocketChatCache
import com.evernote.android.job.Job import com.evernote.android.job.Job
import com.evernote.android.job.JobManager import com.evernote.android.job.JobManager
import com.evernote.android.job.JobRequest import com.evernote.android.job.JobRequest
...@@ -11,7 +10,6 @@ import java.util.concurrent.TimeUnit ...@@ -11,7 +10,6 @@ import java.util.concurrent.TimeUnit
class KeepAliveJob : Job() { class KeepAliveJob : Job() {
private val connectivityManager: ConnectivityManagerApi private val connectivityManager: ConnectivityManagerApi
private val rocketChatCache: RocketChatCache
companion object { companion object {
val TAG = "chat.rocket.android.service.KeepAliveJob" val TAG = "chat.rocket.android.service.KeepAliveJob"
...@@ -38,7 +36,6 @@ class KeepAliveJob : Job() { ...@@ -38,7 +36,6 @@ class KeepAliveJob : Job() {
init { init {
val context = RocketChatApplication.getInstance() val context = RocketChatApplication.getInstance()
connectivityManager = ConnectivityManager.getInstance(context) connectivityManager = ConnectivityManager.getInstance(context)
rocketChatCache = RocketChatCache(context)
} }
override fun onRunJob(params: Params): Result { override fun onRunJob(params: Params): Result {
......
...@@ -74,7 +74,7 @@ import io.reactivex.subjects.BehaviorSubject; ...@@ -74,7 +74,7 @@ import io.reactivex.subjects.BehaviorSubject;
@DebugLog @DebugLog
@Override @Override
public void ensureConnections() { public void ensureConnections() {
String hostname = new RocketChatCache(appContext).getSelectedServerHostname(); String hostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
if (hostname == null) { if (hostname == null) {
return; return;
} }
......
...@@ -106,7 +106,8 @@ public class RocketChatService extends Service implements ConnectivityServiceInt ...@@ -106,7 +106,8 @@ public class RocketChatService extends Service implements ConnectivityServiceInt
} }
if (currentWebSocketThread != null) { if (currentWebSocketThread != null) {
return currentWebSocketThread.terminate(isDisconnected) if (isDisconnected) {
return currentWebSocketThread.terminate(true)
.doAfterTerminate(() -> currentWebSocketThread = null) .doAfterTerminate(() -> currentWebSocketThread = null)
.flatMap(terminated -> .flatMap(terminated ->
RocketChatWebSocketThread.getStarted(getApplicationContext(), hostname) RocketChatWebSocketThread.getStarted(getApplicationContext(), hostname)
...@@ -122,6 +123,8 @@ public class RocketChatService extends Service implements ConnectivityServiceInt ...@@ -122,6 +123,8 @@ public class RocketChatService extends Service implements ConnectivityServiceInt
}) })
); );
} }
return Single.just(currentWebSocketThread);
}
return RocketChatWebSocketThread.getStarted(getApplicationContext(), hostname) return RocketChatWebSocketThread.getStarted(getApplicationContext(), hostname)
.doOnSuccess(thread -> { .doOnSuccess(thread -> {
......
...@@ -13,13 +13,11 @@ import chat.rocket.persistence.realm.models.ddp.RealmRoom; ...@@ -13,13 +13,11 @@ import chat.rocket.persistence.realm.models.ddp.RealmRoom;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
public abstract class AbstractRocketChatCacheObserver implements Registrable { public abstract class AbstractRocketChatCacheObserver implements Registrable {
private final Context context;
private final RealmHelper realmHelper; private final RealmHelper realmHelper;
private String roomId; private String roomId;
private CompositeDisposable compositeDisposable = new CompositeDisposable(); private CompositeDisposable compositeDisposable = new CompositeDisposable();
protected AbstractRocketChatCacheObserver(Context context, RealmHelper realmHelper) { protected AbstractRocketChatCacheObserver(RealmHelper realmHelper) {
this.context = context;
this.realmHelper = realmHelper; this.realmHelper = realmHelper;
} }
...@@ -47,7 +45,7 @@ public abstract class AbstractRocketChatCacheObserver implements Registrable { ...@@ -47,7 +45,7 @@ public abstract class AbstractRocketChatCacheObserver implements Registrable {
@Override @Override
public final void register() { public final void register() {
compositeDisposable.add( compositeDisposable.add(
new RocketChatCache(context) RocketChatCache.INSTANCE
.getSelectedRoomIdPublisher() .getSelectedRoomIdPublisher()
.filter(Optional::isPresent) .filter(Optional::isPresent)
.map(Optional::get) .map(Optional::get)
......
...@@ -18,7 +18,6 @@ public class StreamRoomMessageManager implements Registrable { ...@@ -18,7 +18,6 @@ public class StreamRoomMessageManager implements Registrable {
private final RealmHelper realmHelper; private final RealmHelper realmHelper;
private final AbstractRocketChatCacheObserver cacheObserver; private final AbstractRocketChatCacheObserver cacheObserver;
private final Handler handler; private final Handler handler;
private final RocketChatCache rocketChatCache;
private StreamRoomMessage streamRoomMessage; private StreamRoomMessage streamRoomMessage;
public StreamRoomMessageManager(Context context, String hostname, public StreamRoomMessageManager(Context context, String hostname,
...@@ -26,9 +25,8 @@ public class StreamRoomMessageManager implements Registrable { ...@@ -26,9 +25,8 @@ public class StreamRoomMessageManager implements Registrable {
this.context = context; this.context = context;
this.hostname = hostname; this.hostname = hostname;
this.realmHelper = realmHelper; this.realmHelper = realmHelper;
this.rocketChatCache = new RocketChatCache(context);
cacheObserver = new AbstractRocketChatCacheObserver(context, realmHelper) { cacheObserver = new AbstractRocketChatCacheObserver(realmHelper) {
@Override @Override
protected void onRoomIdUpdated(String roomId) { protected void onRoomIdUpdated(String roomId) {
unregisterStreamNotifyMessageIfNeeded(); unregisterStreamNotifyMessageIfNeeded();
...@@ -57,7 +55,7 @@ public class StreamRoomMessageManager implements Registrable { ...@@ -57,7 +55,7 @@ public class StreamRoomMessageManager implements Registrable {
@Override @Override
public void register() { public void register() {
cacheObserver.register(); cacheObserver.register();
String selectedRoomId = rocketChatCache.getSelectedRoomId(); String selectedRoomId = RocketChatCache.INSTANCE.getSelectedRoomId();
if (selectedRoomId == null) { if (selectedRoomId == null) {
return; return;
} }
......
...@@ -68,7 +68,7 @@ public class GcmPushRegistrationObserver extends AbstractModelObserver<GcmPushRe ...@@ -68,7 +68,7 @@ public class GcmPushRegistrationObserver extends AbstractModelObserver<GcmPushRe
final RealmUser currentUser = realmHelper.executeTransactionForRead(realm -> final RealmUser currentUser = realmHelper.executeTransactionForRead(realm ->
RealmUser.queryCurrentUser(realm).findFirst()); RealmUser.queryCurrentUser(realm).findFirst());
final String userId = currentUser != null ? currentUser.getId() : null; 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) return new RaixPushHelper(realmHelper)
.pushUpdate(pushId, gcmToken, userId); .pushUpdate(pushId, gcmToken, userId);
......
...@@ -74,7 +74,7 @@ public class SessionObserver extends AbstractModelObserver<RealmSession> { ...@@ -74,7 +74,7 @@ public class SessionObserver extends AbstractModelObserver<RealmSession> {
// update push info // update push info
pushHelper pushHelper
.pushSetUser(new RocketChatCache(context).getOrCreatePushId()) .pushSetUser(RocketChatCache.INSTANCE.getOrCreatePushId())
.continueWith(new LogIfError()); .continueWith(new LogIfError());
ConnectivityManager.getInstance(context).notifySessionEstablished(hostname); 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