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);
......
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,207 +24,206 @@ import io.reactivex.schedulers.Schedulers;
import okhttp3.HttpUrl;
abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
@State protected String hostname;
@State protected String roomId;
@State
protected String hostname;
@State
protected String roomId;
private RocketChatCache rocketChatCache;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private boolean isNotification;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private boolean isNotification;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rocketChatCache = new RocketChatCache(this);
if (savedInstanceState == null) {
handleIntent(getIntent());
}
updateHostnameIfNeeded(RocketChatCache.INSTANCE.getSelectedServerHostname());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (intent == null) {
return;
}
if (intent.hasExtra(PushManager.EXTRA_HOSTNAME)) {
String hostname = intent.getStringExtra(PushManager.EXTRA_HOSTNAME);
HttpUrl url = HttpUrl.parse(hostname);
if (url != null) {
String hostnameFromPush = url.host();
String loginHostname = RocketChatCache.INSTANCE.getSiteUrlFor(hostnameFromPush);
RocketChatCache.INSTANCE.setSelectedServerHostname(loginHostname);
if (intent.hasExtra(PushManager.EXTRA_ROOM_ID)) {
RocketChatCache.INSTANCE.setSelectedRoomId(intent.getStringExtra(PushManager.EXTRA_ROOM_ID));
}
}
PushManager.INSTANCE.clearNotificationsByHost(hostname);
} else {
updateHostnameIfNeeded(RocketChatCache.INSTANCE.getSelectedServerHostname());
}
if (intent.hasExtra(PushManager.EXTRA_NOT_ID) && intent.hasExtra(PushManager.EXTRA_HOSTNAME)) {
isNotification = true;
int notificationId = intent.getIntExtra(PushManager.EXTRA_NOT_ID, 0);
String hostname = intent.getStringExtra(PushManager.EXTRA_HOSTNAME);
HttpUrl url = HttpUrl.parse(hostname);
if (url != null) {
String hostnameFromPush = url.host();
String loginHostname = RocketChatCache.INSTANCE.getSiteUrlFor(hostnameFromPush);
PushManager.INSTANCE.clearNotificationsByHostAndNotificationId(loginHostname, notificationId);
} else {
PushManager.INSTANCE.clearNotificationsByNotificationId(notificationId);
}
}
}
private void updateHostnameIfNeeded(String newHostname) {
if (hostname == null) {
if (newHostname != null && assertServerRealmStoreExists(newHostname)) {
updateHostname(newHostname);
updateRoomIdIfNeeded(RocketChatCache.INSTANCE.getSelectedRoomId());
} else {
recoverFromHostnameError();
}
} else {
if (hostname.equals(newHostname)) {
updateHostname(newHostname);
updateRoomIdIfNeeded(RocketChatCache.INSTANCE.getSelectedRoomId());
return;
}
if (assertServerRealmStoreExists(newHostname)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else {
recoverFromHostnameError();
}
}
}
private boolean assertServerRealmStoreExists(String hostname) {
return RealmStore.get(hostname) != null;
}
private void updateHostname(String hostname) {
this.hostname = hostname;
onHostnameUpdated();
}
private void recoverFromHostnameError() {
final List<ServerInfo> serverInfoList =
ConnectivityManager.getInstance(getApplicationContext()).getServerList();
if (serverInfoList == null || serverInfoList.size() == 0) {
LaunchUtil.showAddServerActivity(this);
return;
}
// just connect to the first available
final ServerInfo serverInfo = serverInfoList.get(0);
if (savedInstanceState == null) {
handleIntent(getIntent());
RocketChatCache.INSTANCE.setSelectedServerHostname(serverInfo.getHostname());
RocketChatCache.INSTANCE.setSelectedRoomId(null);
}
updateHostnameIfNeeded(rocketChatCache.getSelectedServerHostname());
}
private void updateRoomIdIfNeeded(String newRoomId) {
if (roomId == null) {
if (newRoomId != null && assertRoomSubscriptionExists(newRoomId)) {
updateRoomId(newRoomId);
}
} else {
if (!roomId.equals(newRoomId) && assertRoomSubscriptionExists(newRoomId)) {
updateRoomId(newRoomId);
}
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
private boolean assertRoomSubscriptionExists(String roomId) {
if (!assertServerRealmStoreExists(hostname)) {
return false;
}
private void handleIntent(Intent intent) {
if (intent == null) {
return;
RealmRoom room = RealmStore.get(hostname).executeTransactionForRead(realm ->
realm.where(RealmRoom.class).equalTo(RealmRoom.ROOM_ID, roomId).findFirst());
if (room == null) {
RocketChatCache.INSTANCE.setSelectedRoomId(null);
return false;
}
return true;
}
if (intent.hasExtra(PushManager.EXTRA_HOSTNAME)) {
String hostname = intent.getStringExtra(PushManager.EXTRA_HOSTNAME);
HttpUrl url = HttpUrl.parse(hostname);
if (url != null) {
String hostnameFromPush = url.host();
String loginHostname = rocketChatCache.getSiteUrlFor(hostnameFromPush);
rocketChatCache.setSelectedServerHostname(loginHostname);
private void updateRoomId(String roomId) {
this.roomId = roomId;
onRoomIdUpdated();
}
protected void onHostnameUpdated() {
}
protected void onRoomIdUpdated() {
}
if (intent.hasExtra(PushManager.EXTRA_ROOM_ID)) {
rocketChatCache.setSelectedRoomId(intent.getStringExtra(PushManager.EXTRA_ROOM_ID));
@Override
protected void onResume() {
super.onResume();
subscribeToConfigChanges();
ConnectivityManager.getInstance(getApplicationContext()).keepAliveServer();
if (isNotification) {
updateHostnameIfNeeded(RocketChatCache.INSTANCE.getSelectedServerHostname());
updateRoomIdIfNeeded(RocketChatCache.INSTANCE.getSelectedRoomId());
isNotification = false;
}
}
PushManager.INSTANCE.clearNotificationsByHost(hostname);
} else {
updateHostnameIfNeeded(rocketChatCache.getSelectedServerHostname());
}
if (intent.hasExtra(PushManager.EXTRA_NOT_ID) && intent.hasExtra(PushManager.EXTRA_HOSTNAME)) {
isNotification = true;
int notificationId = intent.getIntExtra(PushManager.EXTRA_NOT_ID, 0);
String hostname = intent.getStringExtra(PushManager.EXTRA_HOSTNAME);
HttpUrl url = HttpUrl.parse(hostname);
if (url != null) {
String hostnameFromPush = url.host();
String loginHostname = rocketChatCache.getSiteUrlFor(hostnameFromPush);
PushManager.INSTANCE.clearNotificationsByHostAndNotificationId(loginHostname, notificationId);
} else {
PushManager.INSTANCE.clearNotificationsByNotificationId(notificationId);
}
}
}
private void updateHostnameIfNeeded(String newHostname) {
if (hostname == null) {
if (newHostname != null && assertServerRealmStoreExists(newHostname)) {
updateHostname(newHostname);
updateRoomIdIfNeeded(rocketChatCache.getSelectedRoomId());
} else {
recoverFromHostnameError();
}
} else {
if (hostname.equals(newHostname)) {
updateHostname(newHostname);
updateRoomIdIfNeeded(rocketChatCache.getSelectedRoomId());
return;
}
if (assertServerRealmStoreExists(newHostname)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else {
recoverFromHostnameError();
}
}
}
private boolean assertServerRealmStoreExists(String hostname) {
return RealmStore.get(hostname) != null;
}
private void updateHostname(String hostname) {
this.hostname = hostname;
onHostnameUpdated();
}
private void recoverFromHostnameError() {
final List<ServerInfo> serverInfoList =
ConnectivityManager.getInstance(getApplicationContext()).getServerList();
if (serverInfoList == null || serverInfoList.size() == 0) {
LaunchUtil.showAddServerActivity(this);
return;
}
// just connect to the first available
final ServerInfo serverInfo = serverInfoList.get(0);
rocketChatCache.setSelectedServerHostname(serverInfo.getHostname());
rocketChatCache.setSelectedRoomId(null);
}
private void updateRoomIdIfNeeded(String newRoomId) {
if (roomId == null) {
if (newRoomId != null && assertRoomSubscriptionExists(newRoomId)) {
updateRoomId(newRoomId);
}
} else {
if (!roomId.equals(newRoomId) && assertRoomSubscriptionExists(newRoomId)) {
updateRoomId(newRoomId);
}
}
}
private boolean assertRoomSubscriptionExists(String roomId) {
if (!assertServerRealmStoreExists(hostname)) {
return false;
}
RealmRoom room = RealmStore.get(hostname).executeTransactionForRead(realm ->
realm.where(RealmRoom.class).equalTo(RealmRoom.ROOM_ID, roomId).findFirst());
if (room == null) {
rocketChatCache.setSelectedRoomId(null);
return false;
}
return true;
}
private void updateRoomId(String roomId) {
this.roomId = roomId;
onRoomIdUpdated();
}
protected void onHostnameUpdated() {
}
protected void onRoomIdUpdated() {
}
@Override
protected void onResume() {
super.onResume();
subscribeToConfigChanges();
ConnectivityManager.getInstance(getApplicationContext()).keepAliveServer();
if (isNotification) {
updateHostnameIfNeeded(rocketChatCache.getSelectedServerHostname());
updateRoomIdIfNeeded(rocketChatCache.getSelectedRoomId());
isNotification = false;
}
}
@Override
protected void onPause() {
compositeDisposable.clear();
super.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void subscribeToConfigChanges() {
compositeDisposable.add(
rocketChatCache.getSelectedServerHostnamePublisher()
.map(Optional::get)
.distinctUntilChanged()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
this::updateHostnameIfNeeded,
Logger.INSTANCE::report
)
);
compositeDisposable.add(
rocketChatCache.getSelectedRoomIdPublisher()
.filter(Optional::isPresent)
.map(Optional::get)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
this::updateRoomIdIfNeeded,
Logger.INSTANCE::report
)
);
}
}
@Override
protected void onPause() {
compositeDisposable.clear();
super.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void subscribeToConfigChanges() {
compositeDisposable.add(
RocketChatCache.INSTANCE.getSelectedServerHostnamePublisher()
.map(Optional::get)
.distinctUntilChanged()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
this::updateHostnameIfNeeded,
Logger.INSTANCE::report
)
);
compositeDisposable.add(
RocketChatCache.INSTANCE.getSelectedRoomIdPublisher()
.filter(Optional::isPresent)
.map(Optional::get)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
this::updateRoomIdIfNeeded,
Logger.INSTANCE::report
)
);
}
}
......@@ -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)
......
......@@ -36,134 +36,132 @@ import io.reactivex.disposables.Disposable;
public class MessageOptionsDialogFragment extends BottomSheetDialogFragment {
public final static String ARG_MESSAGE_ID = "messageId";
public final static String ARG_MESSAGE_ID = "messageId";
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private OnMessageOptionSelectedListener internalListener = new OnMessageOptionSelectedListener() {
@Override
public void onEdit(Message message) {
if (externalListener != null) {
externalListener.onEdit(message);
}
}
};
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private OnMessageOptionSelectedListener internalListener = new OnMessageOptionSelectedListener() {
@Override
public void onEdit(Message message) {
if (externalListener != null) {
externalListener.onEdit(message);
}
}
};
private OnMessageOptionSelectedListener externalListener = null;
private OnMessageOptionSelectedListener externalListener = null;
public static MessageOptionsDialogFragment create(@NonNull Message message) {
Bundle bundle = new Bundle();
bundle.putString(ARG_MESSAGE_ID, message.getId());
public static MessageOptionsDialogFragment create(@NonNull Message message) {
Bundle bundle = new Bundle();
bundle.putString(ARG_MESSAGE_ID, message.getId());
MessageOptionsDialogFragment messageOptionsDialogFragment = new MessageOptionsDialogFragment();
messageOptionsDialogFragment.setArguments(bundle);
MessageOptionsDialogFragment messageOptionsDialogFragment = new MessageOptionsDialogFragment();
messageOptionsDialogFragment.setArguments(bundle);
return messageOptionsDialogFragment;
}
return messageOptionsDialogFragment;
}
public void setOnMessageOptionSelectedListener(
OnMessageOptionSelectedListener onMessageOptionSelectedListener) {
externalListener = onMessageOptionSelectedListener;
}
public void setOnMessageOptionSelectedListener(
OnMessageOptionSelectedListener onMessageOptionSelectedListener) {
externalListener = onMessageOptionSelectedListener;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getContext());
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getContext());
bottomSheetDialog.setContentView(R.layout.dialog_message_options);
bottomSheetDialog.setContentView(R.layout.dialog_message_options);
TextView info = (TextView) bottomSheetDialog.findViewById(R.id.message_options_info);
TextView info = (TextView) bottomSheetDialog.findViewById(R.id.message_options_info);
Bundle args = getArguments();
if (args == null || !args.containsKey(ARG_MESSAGE_ID)) {
info.setText(R.string.message_options_no_message_info);
} else {
setUpDialog(bottomSheetDialog, args.getString(ARG_MESSAGE_ID));
}
Bundle args = getArguments();
if (args == null || !args.containsKey(ARG_MESSAGE_ID)) {
info.setText(R.string.message_options_no_message_info);
} else {
setUpDialog(bottomSheetDialog, args.getString(ARG_MESSAGE_ID));
return bottomSheetDialog;
}
return bottomSheetDialog;
}
@Override
public void onDismiss(DialogInterface dialog) {
compositeDisposable.clear();
super.onDismiss(dialog);
}
private void setUpDialog(final BottomSheetDialog bottomSheetDialog, String messageId) {
RocketChatCache cache = new RocketChatCache(bottomSheetDialog.getContext());
String hostname = cache.getSelectedServerHostname();
EditMessageInteractor editMessageInteractor = getEditMessageInteractor(hostname);
MessageRepository messageRepository = new RealmMessageRepository(hostname);
Disposable disposable = messageRepository.getById(messageId)
.flatMap(it -> {
if (!it.isPresent()) {
return Single.just(Pair.<Message, Boolean>create(null, false));
}
Message message = it.get();
return Single.zip(
Single.just(message),
editMessageInteractor.isAllowed(message),
Pair::create
);
})
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
pair -> {
if (pair.second) {
bottomSheetDialog.findViewById(R.id.message_options_info)
.setVisibility(View.GONE);
View editView = bottomSheetDialog.findViewById(R.id.message_options_edit_action);
editView.setVisibility(View.VISIBLE);
editView.setOnClickListener(view -> internalListener.onEdit(pair.first));
} else {
((TextView) bottomSheetDialog.findViewById(R.id.message_options_info))
.setText(R.string.message_options_no_permissions_info);
}
},
throwable -> {
((TextView) bottomSheetDialog.findViewById(R.id.message_options_info))
.setText(R.string.message_options_no_message_info);
Logger.INSTANCE.report(throwable);
}
@Override
public void onDismiss(DialogInterface dialog) {
compositeDisposable.clear();
super.onDismiss(dialog);
}
private void setUpDialog(final BottomSheetDialog bottomSheetDialog, String messageId) {
String hostname = RocketChatCache.INSTANCE.getSelectedServerHostname();
EditMessageInteractor editMessageInteractor = getEditMessageInteractor(hostname);
MessageRepository messageRepository = new RealmMessageRepository(hostname);
Disposable disposable = messageRepository.getById(messageId)
.flatMap(it -> {
if (!it.isPresent()) {
return Single.just(Pair.<Message, Boolean>create(null, false));
}
Message message = it.get();
return Single.zip(
Single.just(message),
editMessageInteractor.isAllowed(message),
Pair::create
);
})
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
pair -> {
if (pair.second) {
bottomSheetDialog.findViewById(R.id.message_options_info)
.setVisibility(View.GONE);
View editView = bottomSheetDialog.findViewById(R.id.message_options_edit_action);
editView.setVisibility(View.VISIBLE);
editView.setOnClickListener(view -> internalListener.onEdit(pair.first));
} else {
((TextView) bottomSheetDialog.findViewById(R.id.message_options_info))
.setText(R.string.message_options_no_permissions_info);
}
},
throwable -> {
((TextView) bottomSheetDialog.findViewById(R.id.message_options_info))
.setText(R.string.message_options_no_message_info);
Logger.INSTANCE.report(throwable);
}
);
compositeDisposable.add(disposable);
}
private EditMessageInteractor getEditMessageInteractor(String hostname) {
UserRepository userRepository = new RealmUserRepository(hostname);
RoomRoleRepository roomRoleRepository = new RealmRoomRoleRepository(hostname);
PermissionRepository permissionRepository = new RealmPermissionRepository(hostname);
PermissionInteractor permissionInteractor = new PermissionInteractor(
userRepository,
roomRoleRepository,
permissionRepository
);
compositeDisposable.add(disposable);
}
private EditMessageInteractor getEditMessageInteractor(String hostname) {
UserRepository userRepository = new RealmUserRepository(hostname);
RoomRoleRepository roomRoleRepository = new RealmRoomRoleRepository(hostname);
PermissionRepository permissionRepository = new RealmPermissionRepository(hostname);
PermissionInteractor permissionInteractor = new PermissionInteractor(
userRepository,
roomRoleRepository,
permissionRepository
);
MessageRepository messageRepository = new RealmMessageRepository(hostname);
RoomRepository roomRepository = new RealmRoomRepository(hostname);
PublicSettingRepository publicSettingRepository = new RealmPublicSettingRepository(hostname);
return new EditMessageInteractor(
permissionInteractor,
userRepository,
messageRepository,
roomRepository,
publicSettingRepository
);
}
public interface OnMessageOptionSelectedListener {
void onEdit(Message message);
}
MessageRepository messageRepository = new RealmMessageRepository(hostname);
RoomRepository roomRepository = new RealmRoomRepository(hostname);
PublicSettingRepository publicSettingRepository = new RealmPublicSettingRepository(hostname);
return new EditMessageInteractor(
permissionInteractor,
userRepository,
messageRepository,
roomRepository,
publicSettingRepository
);
}
public interface OnMessageOptionSelectedListener {
void onEdit(Message message);
}
}
......@@ -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