Commit 6ccb8ad4 authored by Tiago Cunha's avatar Tiago Cunha

From string to constants

parent 7db4b7cf
...@@ -24,7 +24,7 @@ public class RocketChatApplication extends MultiDexApplication { ...@@ -24,7 +24,7 @@ public class RocketChatApplication extends MultiDexApplication {
new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build()); new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build());
List<ServerConfig> configs = RealmStore.getDefault().executeTransactionForReadResults(realm -> List<ServerConfig> configs = RealmStore.getDefault().executeTransactionForReadResults(realm ->
realm.where(ServerConfig.class).isNotNull("session").findAll()); realm.where(ServerConfig.class).isNotNull(ServerConfig.SESSION).findAll());
for (ServerConfig config : configs) { for (ServerConfig config : configs) {
RealmStore.put(config.getServerConfigId()); RealmStore.put(config.getServerConfigId());
} }
......
...@@ -3,6 +3,8 @@ package chat.rocket.android; ...@@ -3,6 +3,8 @@ package chat.rocket.android;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import java.util.UUID;
/** /**
* sharedpreference-based cache. * sharedpreference-based cache.
*/ */
...@@ -10,10 +12,25 @@ public class RocketChatCache { ...@@ -10,10 +12,25 @@ public class RocketChatCache {
public static final String KEY_SELECTED_SERVER_CONFIG_ID = "selectedServerConfigId"; public static final String KEY_SELECTED_SERVER_CONFIG_ID = "selectedServerConfigId";
public static final String KEY_SELECTED_ROOM_ID = "selectedRoomId"; public static final String KEY_SELECTED_ROOM_ID = "selectedRoomId";
private static final String PUSH_ID = "pushId";
/** /**
* get SharedPreference instance for RocketChat application cache. * get SharedPreference instance for RocketChat application cache.
*/ */
public static SharedPreferences get(Context context) { public static SharedPreferences get(Context context) {
return context.getSharedPreferences("cache", Context.MODE_PRIVATE); return context.getSharedPreferences("cache", Context.MODE_PRIVATE);
} }
public static String getPushId(Context context) {
SharedPreferences preferences = get(context);
String id = null;
if (!preferences.contains(PUSH_ID)) {
// generates one and save
id = UUID.randomUUID().toString();
SharedPreferences.Editor editor = preferences.edit();
editor.putString(PUSH_ID, id);
editor.apply();
}
return preferences.getString(PUSH_ID, id);
}
} }
...@@ -28,7 +28,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -28,7 +28,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
private RealmListObserver<ServerConfig> unconfiguredServersObserver = private RealmListObserver<ServerConfig> unconfiguredServersObserver =
RealmStore.getDefault() RealmStore.getDefault()
.createListObserver(realm -> .createListObserver(realm ->
realm.where(ServerConfig.class).isNotNull("session").findAll()) realm.where(ServerConfig.class).isNotNull(ServerConfig.SESSION).findAll())
.setOnUpdateListener(results -> { .setOnUpdateListener(results -> {
if (results.isEmpty()) { if (results.isEmpty()) {
LaunchUtil.showAddServerActivity(this); LaunchUtil.showAddServerActivity(this);
...@@ -41,10 +41,10 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -41,10 +41,10 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
if (savedInstanceState == null) { if (savedInstanceState == null) {
Intent intent = getIntent(); Intent intent = getIntent();
if (intent != null) { if (intent != null) {
if (intent.hasExtra("serverConfigId")) { if (intent.hasExtra(ServerConfig.ID)) {
SharedPreferences.Editor editor = RocketChatCache.get(this).edit(); SharedPreferences.Editor editor = RocketChatCache.get(this).edit();
editor.putString(RocketChatCache.KEY_SELECTED_SERVER_CONFIG_ID, editor.putString(RocketChatCache.KEY_SELECTED_SERVER_CONFIG_ID,
intent.getStringExtra("serverConfigId")); intent.getStringExtra(ServerConfig.ID));
if (intent.hasExtra("roomId")) { if (intent.hasExtra("roomId")) {
editor.putString(RocketChatCache.KEY_SELECTED_ROOM_ID, intent.getStringExtra("roomId")); editor.putString(RocketChatCache.KEY_SELECTED_ROOM_ID, intent.getStringExtra("roomId"));
...@@ -104,7 +104,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity { ...@@ -104,7 +104,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
} }
RoomSubscription room = RealmStore.get(serverConfigId).executeTransactionForRead(realm -> RoomSubscription room = RealmStore.get(serverConfigId).executeTransactionForRead(realm ->
realm.where(RoomSubscription.class).equalTo("rid", roomId).findFirst()); realm.where(RoomSubscription.class).equalTo(RoomSubscription.ROOM_ID, roomId).findFirst());
if (room == null) { if (room == null) {
prefs.edit() prefs.edit()
.remove(RocketChatCache.KEY_SELECTED_ROOM_ID) .remove(RocketChatCache.KEY_SELECTED_ROOM_ID)
......
...@@ -19,7 +19,8 @@ public class AddServerActivity extends AbstractFragmentActivity { ...@@ -19,7 +19,8 @@ public class AddServerActivity extends AbstractFragmentActivity {
private String serverConfigId; private String serverConfigId;
private RealmListObserver<ServerConfig> configuredServersObserver = RealmStore.getDefault() private RealmListObserver<ServerConfig> configuredServersObserver = RealmStore.getDefault()
.createListObserver(realm -> realm.where(ServerConfig.class).isNotNull("session").findAll()) .createListObserver(
realm -> realm.where(ServerConfig.class).isNotNull(ServerConfig.SESSION).findAll())
.setOnUpdateListener(results -> { .setOnUpdateListener(results -> {
if (!results.isEmpty()) { if (!results.isEmpty()) {
RocketChatCache.get(this).edit() RocketChatCache.get(this).edit()
...@@ -32,7 +33,7 @@ public class AddServerActivity extends AbstractFragmentActivity { ...@@ -32,7 +33,7 @@ public class AddServerActivity extends AbstractFragmentActivity {
private RealmObjectObserver<ServerConfig> targetServerConfigObserver = RealmStore.getDefault() private RealmObjectObserver<ServerConfig> targetServerConfigObserver = RealmStore.getDefault()
.createObjectObserver(realm -> .createObjectObserver(realm ->
realm.where(ServerConfig.class).equalTo("serverConfigId", serverConfigId)) realm.where(ServerConfig.class).equalTo(ServerConfig.ID, serverConfigId))
.setOnUpdateListener(config -> { .setOnUpdateListener(config -> {
if (config == null || config.getState() == ServerConfig.STATE_CONNECTION_ERROR) { if (config == null || config.getState() == ServerConfig.STATE_CONNECTION_ERROR) {
showFragment(new InputHostnameFragment()); showFragment(new InputHostnameFragment());
...@@ -52,7 +53,7 @@ public class AddServerActivity extends AbstractFragmentActivity { ...@@ -52,7 +53,7 @@ public class AddServerActivity extends AbstractFragmentActivity {
private void setupServerConfigId() { private void setupServerConfigId() {
ServerConfig config = RealmStore.getDefault().executeTransactionForRead(realm -> ServerConfig config = RealmStore.getDefault().executeTransactionForRead(realm ->
realm.where(ServerConfig.class).isNull("hostname").findFirst()); realm.where(ServerConfig.class).isNull(ServerConfig.HOSTNAME).findFirst());
if (config != null) { if (config != null) {
serverConfigId = config.getServerConfigId(); serverConfigId = config.getServerConfigId();
return; return;
...@@ -60,7 +61,7 @@ public class AddServerActivity extends AbstractFragmentActivity { ...@@ -60,7 +61,7 @@ public class AddServerActivity extends AbstractFragmentActivity {
config = RealmStore.getDefault().executeTransactionForRead(realm -> config = RealmStore.getDefault().executeTransactionForRead(realm ->
realm.where(ServerConfig.class) realm.where(ServerConfig.class)
.equalTo("state", ServerConfig.STATE_CONNECTION_ERROR).findFirst()); .equalTo(ServerConfig.STATE, ServerConfig.STATE_CONNECTION_ERROR).findFirst());
if (config != null) { if (config != null) {
serverConfigId = config.getServerConfigId(); serverConfigId = config.getServerConfigId();
return; return;
...@@ -105,7 +106,7 @@ public class AddServerActivity extends AbstractFragmentActivity { ...@@ -105,7 +106,7 @@ public class AddServerActivity extends AbstractFragmentActivity {
if (args == null) { if (args == null) {
args = new Bundle(); args = new Bundle();
} }
args.putString("serverConfigId", serverConfigId); args.putString(ServerConfig.ID, serverConfigId);
fragment.setArguments(args); fragment.setArguments(args);
} }
......
...@@ -143,9 +143,9 @@ public class MainActivity extends AbstractAuthedActivity { ...@@ -143,9 +143,9 @@ public class MainActivity extends AbstractAuthedActivity {
sessionObserver = realmHelper sessionObserver = realmHelper
.createObjectObserver(realm -> .createObjectObserver(realm ->
Session.queryDefaultSession(realm) Session.queryDefaultSession(realm)
.isNotNull("token") .isNotNull(Session.TOKEN)
.equalTo("tokenVerified", true) .equalTo(Session.TOKEN_VERIFIED, true)
.isNull("error")) .isNull(Session.ERROR))
.setOnUpdateListener(session -> { .setOnUpdateListener(session -> {
if (session == null && isForeground) { if (session == null && isForeground) {
LaunchUtil.showServerConfigActivity(this, serverConfigId); LaunchUtil.showServerConfigActivity(this, serverConfigId);
......
...@@ -41,7 +41,7 @@ public class ServerConfigActivity extends AbstractFragmentActivity { ...@@ -41,7 +41,7 @@ public class ServerConfigActivity extends AbstractFragmentActivity {
return; return;
} }
serverConfigId = intent.getStringExtra("serverConfigId"); serverConfigId = intent.getStringExtra(ServerConfig.ID);
if (TextUtils.isEmpty(serverConfigId)) { if (TextUtils.isEmpty(serverConfigId)) {
finish(); finish();
return; return;
...@@ -50,8 +50,8 @@ public class ServerConfigActivity extends AbstractFragmentActivity { ...@@ -50,8 +50,8 @@ public class ServerConfigActivity extends AbstractFragmentActivity {
serverConfigErrorObserver = RealmStore.getDefault() serverConfigErrorObserver = RealmStore.getDefault()
.createObjectObserver(realm -> .createObjectObserver(realm ->
realm.where(ServerConfig.class) realm.where(ServerConfig.class)
.equalTo("serverConfigId", serverConfigId) .equalTo(ServerConfig.ID, serverConfigId)
.equalTo("state", ServerConfig.STATE_CONNECTION_ERROR)) .equalTo(ServerConfig.STATE, ServerConfig.STATE_CONNECTION_ERROR))
.setOnUpdateListener(this::onRenderServerConfigError); .setOnUpdateListener(this::onRenderServerConfigError);
sessionObserver = RealmStore.get(serverConfigId) sessionObserver = RealmStore.get(serverConfigId)
...@@ -128,7 +128,7 @@ public class ServerConfigActivity extends AbstractFragmentActivity { ...@@ -128,7 +128,7 @@ public class ServerConfigActivity extends AbstractFragmentActivity {
if (args == null) { if (args == null) {
args = new Bundle(); args = new Bundle();
} }
args.putString("serverConfigId", serverConfigId); args.putString(ServerConfig.ID, serverConfigId);
fragment.setArguments(args); fragment.setArguments(args);
} }
......
package chat.rocket.android.api; package chat.rocket.android.api;
import android.content.Context; import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Patterns; import android.util.Patterns;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
...@@ -17,6 +19,7 @@ import chat.rocket.android.model.ddp.PublicSetting; ...@@ -17,6 +19,7 @@ import chat.rocket.android.model.ddp.PublicSetting;
import chat.rocket.android.model.ddp.RoomSubscription; import chat.rocket.android.model.ddp.RoomSubscription;
import chat.rocket.android.model.internal.MethodCall; import chat.rocket.android.model.internal.MethodCall;
import chat.rocket.android.model.internal.Session; import chat.rocket.android.model.internal.Session;
import chat.rocket.android.model.params.PushUpdate;
import chat.rocket.android.realm_helper.RealmHelper; import chat.rocket.android.realm_helper.RealmHelper;
import chat.rocket.android.realm_helper.RealmStore; import chat.rocket.android.realm_helper.RealmStore;
import chat.rocket.android_ddp.DDPClientCallback; import chat.rocket.android_ddp.DDPClientCallback;
...@@ -24,6 +27,7 @@ import hugo.weaving.DebugLog; ...@@ -24,6 +27,7 @@ import hugo.weaving.DebugLog;
/** /**
* Utility class for creating/handling MethodCall or RPC. * Utility class for creating/handling MethodCall or RPC.
*
* TODO: separate method into several manager classes (SubscriptionManager, MessageManager, ...). * TODO: separate method into several manager classes (SubscriptionManager, MessageManager, ...).
*/ */
public class MethodCallHelper { public class MethodCallHelper {
...@@ -37,9 +41,8 @@ public class MethodCallHelper { ...@@ -37,9 +41,8 @@ public class MethodCallHelper {
protected final RealmHelper realmHelper; protected final RealmHelper realmHelper;
protected final DDPClientWrapper ddpClient; protected final DDPClientWrapper ddpClient;
@Deprecated
/** /**
* Deprecated. use MethodCall(Context, String) instead. * initialize with ServerConfigId.
*/ */
public MethodCallHelper(String serverConfigId) { public MethodCallHelper(String serverConfigId) {
this(null, serverConfigId); this(null, serverConfigId);
...@@ -304,6 +307,19 @@ public class MethodCallHelper { ...@@ -304,6 +307,19 @@ public class MethodCallHelper {
.onSuccessTask(task -> Task.forResult(null)); .onSuccessTask(task -> Task.forResult(null));
} }
public Task<Void> pushUpdate(@NonNull String pushId, @NonNull String token,
@Nullable String userId) {
return call("raix:push-update", TIMEOUT_MS, () -> {
JSONObject param = new PushUpdate(pushId, token, userId).toJson();
return new JSONArray().put(param);
}).onSuccessTask(task -> Task.forResult(null));
}
public Task<Void> pushSetUser(String pushId) {
return call("raix:push-setuser", TIMEOUT_MS, () -> new JSONArray().put(pushId))
.onSuccessTask(task -> Task.forResult(null));
}
/** /**
* send message. * send message.
*/ */
......
...@@ -104,20 +104,21 @@ public class RoomFragment extends AbstractChatRoomFragment ...@@ -104,20 +104,21 @@ public class RoomFragment extends AbstractChatRoomFragment
roomId = args.getString("roomId"); roomId = args.getString("roomId");
hostname = RealmStore.getDefault().executeTransactionForRead(realm -> hostname = RealmStore.getDefault().executeTransactionForRead(realm ->
realm.where(ServerConfig.class) realm.where(ServerConfig.class)
.equalTo("serverConfigId", serverConfigId) .equalTo(ServerConfig.ID, serverConfigId)
.isNotNull("hostname") .isNotNull(ServerConfig.HOSTNAME)
.findFirst()).getHostname(); .findFirst()).getHostname();
userId = realmHelper.executeTransactionForRead(realm -> userId = realmHelper.executeTransactionForRead(realm ->
User.queryCurrentUser(realm).findFirst()).getId(); User.queryCurrentUser(realm).findFirst()).getId();
token = realmHelper.executeTransactionForRead(realm -> token = realmHelper.executeTransactionForRead(realm ->
Session.queryDefaultSession(realm).findFirst()).getToken(); Session.queryDefaultSession(realm).findFirst()).getToken();
roomObserver = realmHelper roomObserver = realmHelper
.createObjectObserver(realm -> realm.where(RoomSubscription.class).equalTo("rid", roomId)) .createObjectObserver(
realm -> realm.where(RoomSubscription.class).equalTo(RoomSubscription.ROOM_ID, roomId))
.setOnUpdateListener(this::onRenderRoom); .setOnUpdateListener(this::onRenderRoom);
procedureObserver = realmHelper procedureObserver = realmHelper
.createObjectObserver(realm -> .createObjectObserver(realm ->
realm.where(LoadMessageProcedure.class).equalTo("roomId", roomId)) realm.where(LoadMessageProcedure.class).equalTo(LoadMessageProcedure.ID, roomId))
.setOnUpdateListener(this::onUpdateLoadMessageProcedure); .setOnUpdateListener(this::onUpdateLoadMessageProcedure);
if (savedInstanceState == null) { if (savedInstanceState == null) {
initialRequest(); initialRequest();
...@@ -134,8 +135,8 @@ public class RoomFragment extends AbstractChatRoomFragment ...@@ -134,8 +135,8 @@ public class RoomFragment extends AbstractChatRoomFragment
RecyclerView listView = (RecyclerView) rootView.findViewById(R.id.recyclerview); RecyclerView listView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
MessageListAdapter adapter = (MessageListAdapter) realmHelper.createListAdapter(getContext(), MessageListAdapter adapter = (MessageListAdapter) realmHelper.createListAdapter(getContext(),
realm -> realm.where(Message.class) realm -> realm.where(Message.class)
.equalTo("rid", roomId) .equalTo(Message.ROOM_ID, roomId)
.findAllSorted("ts", Sort.DESCENDING), .findAllSorted(Message.TIMESTAMP, Sort.DESCENDING),
context -> new MessageListAdapter(context, hostname, userId, token) context -> new MessageListAdapter(context, hostname, userId, token)
); );
listView.setAdapter(adapter); listView.setAdapter(adapter);
...@@ -167,15 +168,15 @@ public class RoomFragment extends AbstractChatRoomFragment ...@@ -167,15 +168,15 @@ public class RoomFragment extends AbstractChatRoomFragment
.setPositiveButton(R.string.resend, (dialog, which) -> { .setPositiveButton(R.string.resend, (dialog, which) -> {
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(Message.class, new JSONObject() realm.createOrUpdateObjectFromJson(Message.class, new JSONObject()
.put("_id", messageId) .put(Message.ID, messageId)
.put("syncstate", SyncState.NOT_SYNCED)) .put(Message.SYNC_STATE, SyncState.NOT_SYNCED))
).continueWith(new LogcatIfError()); ).continueWith(new LogcatIfError());
}) })
.setNegativeButton(android.R.string.cancel, null) .setNegativeButton(android.R.string.cancel, null)
.setNeutralButton(R.string.discard, (dialog, which) -> { .setNeutralButton(R.string.discard, (dialog, which) -> {
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.where(Message.class) realm.where(Message.class)
.equalTo("_id", messageId).findAll().deleteAllFromRealm() .equalTo(Message.ID, messageId).findAll().deleteAllFromRealm()
).continueWith(new LogcatIfError()); ).continueWith(new LogcatIfError());
}) })
.show(); .show();
...@@ -225,11 +226,11 @@ public class RoomFragment extends AbstractChatRoomFragment ...@@ -225,11 +226,11 @@ public class RoomFragment extends AbstractChatRoomFragment
messageFormManager.setSendMessageCallback(messageText -> messageFormManager.setSendMessageCallback(messageText ->
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(Message.class, new JSONObject() realm.createOrUpdateObjectFromJson(Message.class, new JSONObject()
.put("_id", UUID.randomUUID().toString()) .put(Message.ID, UUID.randomUUID().toString())
.put("syncstate", SyncState.NOT_SYNCED) .put(Message.SYNC_STATE, SyncState.NOT_SYNCED)
.put("ts", System.currentTimeMillis()) .put(Message.TIMESTAMP, System.currentTimeMillis())
.put("rid", roomId) .put(Message.ROOM_ID, roomId)
.put("msg", messageText)))); .put(Message.MESSAGE, messageText))));
messageFormManager.registerExtraActionItem(new ImageUploadActionItem()); messageFormManager.registerExtraActionItem(new ImageUploadActionItem());
messageFormManager.registerExtraActionItem(new AudioUploadActionItem()); messageFormManager.registerExtraActionItem(new AudioUploadActionItem());
messageFormManager.registerExtraActionItem(new VideoUploadActionItem()); messageFormManager.registerExtraActionItem(new VideoUploadActionItem());
...@@ -298,10 +299,10 @@ public class RoomFragment extends AbstractChatRoomFragment ...@@ -298,10 +299,10 @@ public class RoomFragment extends AbstractChatRoomFragment
private void initialRequest() { private void initialRequest() {
realmHelper.executeTransaction(realm -> { realmHelper.executeTransaction(realm -> {
realm.createOrUpdateObjectFromJson(LoadMessageProcedure.class, new JSONObject() realm.createOrUpdateObjectFromJson(LoadMessageProcedure.class, new JSONObject()
.put("roomId", roomId) .put(LoadMessageProcedure.ID, roomId)
.put("syncstate", SyncState.NOT_SYNCED) .put(LoadMessageProcedure.SYNC_STATE, SyncState.NOT_SYNCED)
.put("count", 100) .put(LoadMessageProcedure.COUNT, 100)
.put("reset", true)); .put(LoadMessageProcedure.RESET, true));
return null; return null;
}).onSuccessTask(task -> { }).onSuccessTask(task -> {
RocketChatService.keepAlive(getContext()); RocketChatService.keepAlive(getContext());
...@@ -312,13 +313,13 @@ public class RoomFragment extends AbstractChatRoomFragment ...@@ -312,13 +313,13 @@ public class RoomFragment extends AbstractChatRoomFragment
private void loadMoreRequest() { private void loadMoreRequest() {
realmHelper.executeTransaction(realm -> { realmHelper.executeTransaction(realm -> {
LoadMessageProcedure procedure = realm.where(LoadMessageProcedure.class) LoadMessageProcedure procedure = realm.where(LoadMessageProcedure.class)
.equalTo("roomId", roomId) .equalTo(LoadMessageProcedure.ID, roomId)
.beginGroup() .beginGroup()
.equalTo("syncstate", SyncState.SYNCED) .equalTo(LoadMessageProcedure.SYNC_STATE, SyncState.SYNCED)
.or() .or()
.equalTo("syncstate", SyncState.FAILED) .equalTo(LoadMessageProcedure.SYNC_STATE, SyncState.FAILED)
.endGroup() .endGroup()
.equalTo("hasNext", true) .equalTo(LoadMessageProcedure.HAS_NEXT, true)
.findFirst(); .findFirst();
if (procedure != null) { if (procedure != null) {
procedure.setSyncState(SyncState.NOT_SYNCED); procedure.setSyncState(SyncState.NOT_SYNCED);
...@@ -332,7 +333,7 @@ public class RoomFragment extends AbstractChatRoomFragment ...@@ -332,7 +333,7 @@ public class RoomFragment extends AbstractChatRoomFragment
private void markAsReadIfNeeded() { private void markAsReadIfNeeded() {
RoomSubscription room = realmHelper.executeTransactionForRead(realm -> RoomSubscription room = realmHelper.executeTransactionForRead(realm ->
realm.where(RoomSubscription.class).equalTo("rid", roomId).findFirst()); realm.where(RoomSubscription.class).equalTo(RoomSubscription.ROOM_ID, roomId).findFirst());
if (room != null && room.isAlert()) { if (room != null && room.isAlert()) {
new MethodCallHelper(getContext(), serverConfigId).readMessages(roomId) new MethodCallHelper(getContext(), serverConfigId).readMessages(roomId)
.continueWith(new LogcatIfError()); .continueWith(new LogcatIfError());
......
...@@ -57,11 +57,11 @@ public abstract class AbstractOAuthFragment extends AbstractWebViewFragment { ...@@ -57,11 +57,11 @@ public abstract class AbstractOAuthFragment extends AbstractWebViewFragment {
serverConfigId = args.getString("serverConfigId"); serverConfigId = args.getString("serverConfigId");
ServerConfig serverConfig = RealmStore.getDefault().executeTransactionForRead(realm -> ServerConfig serverConfig = RealmStore.getDefault().executeTransactionForRead(realm ->
realm.where(ServerConfig.class).equalTo("serverConfigId", serverConfigId).findFirst()); realm.where(ServerConfig.class).equalTo(ServerConfig.ID, serverConfigId).findFirst());
MeteorLoginServiceConfiguration oauthConfig = MeteorLoginServiceConfiguration oauthConfig =
RealmStore.get(serverConfigId).executeTransactionForRead(realm -> RealmStore.get(serverConfigId).executeTransactionForRead(realm ->
realm.where(MeteorLoginServiceConfiguration.class) realm.where(MeteorLoginServiceConfiguration.class)
.equalTo("service", getOAuthServiceName()) .equalTo(MeteorLoginServiceConfiguration.SERVICE, getOAuthServiceName())
.findFirst()); .findFirst());
if (serverConfig == null || oauthConfig == null) { if (serverConfig == null || oauthConfig == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
......
...@@ -21,7 +21,7 @@ import chat.rocket.android.realm_helper.RealmStore; ...@@ -21,7 +21,7 @@ import chat.rocket.android.realm_helper.RealmStore;
public class InputHostnameFragment extends AbstractServerConfigFragment { public class InputHostnameFragment extends AbstractServerConfigFragment {
RealmObjectObserver<ServerConfig> serverConfigObserver = RealmStore.getDefault() RealmObjectObserver<ServerConfig> serverConfigObserver = RealmStore.getDefault()
.createObjectObserver(realm -> .createObjectObserver(realm ->
realm.where(ServerConfig.class).equalTo("serverConfigId", serverConfigId)) realm.where(ServerConfig.class).equalTo(ServerConfig.ID, serverConfigId))
.setOnUpdateListener(this::onRenderServerConfig); .setOnUpdateListener(this::onRenderServerConfig);
public InputHostnameFragment() { public InputHostnameFragment() {
...@@ -82,11 +82,12 @@ public class InputHostnameFragment extends AbstractServerConfigFragment { ...@@ -82,11 +82,12 @@ public class InputHostnameFragment extends AbstractServerConfigFragment {
RealmStore.getDefault().executeTransaction( RealmStore.getDefault().executeTransaction(
realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class, realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class,
new JSONObject().put("serverConfigId", serverConfigId) new JSONObject().put(ServerConfig.ID, serverConfigId)
.put("hostname", hostname) .put(ServerConfig.HOSTNAME, hostname)
.put("error", JSONObject.NULL) .put(ServerConfig.ERROR, JSONObject.NULL)
.put("session", JSONObject.NULL) .put(ServerConfig.SESSION, JSONObject.NULL)
.put("state", ServerConfig.STATE_READY))).continueWith(new LogcatIfError()); .put(ServerConfig.STATE, ServerConfig.STATE_READY)))
.continueWith(new LogcatIfError());
} }
private void showError(String errString) { private void showError(String errString) {
......
...@@ -28,7 +28,7 @@ public class RetryConnectFragment extends AbstractServerConfigFragment { ...@@ -28,7 +28,7 @@ public class RetryConnectFragment extends AbstractServerConfigFragment {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
serverConfigObserver = RealmStore.getDefault() serverConfigObserver = RealmStore.getDefault()
.createObjectObserver(realm -> .createObjectObserver(realm ->
realm.where(ServerConfig.class).equalTo("serverConfigId", serverConfigId)) realm.where(ServerConfig.class).equalTo(ServerConfig.ID, serverConfigId))
.setOnUpdateListener(this::onRenderServerConfig); .setOnUpdateListener(this::onRenderServerConfig);
} }
...@@ -41,7 +41,7 @@ public class RetryConnectFragment extends AbstractServerConfigFragment { ...@@ -41,7 +41,7 @@ public class RetryConnectFragment extends AbstractServerConfigFragment {
RealmStore.getDefault() RealmStore.getDefault()
.executeTransaction(realm -> { .executeTransaction(realm -> {
ServerConfig config = realm.where(ServerConfig.class) ServerConfig config = realm.where(ServerConfig.class)
.equalTo("serverConfigId", serverConfigId).findFirst(); .equalTo(ServerConfig.ID, serverConfigId).findFirst();
if (config != null && config.getState() == ServerConfig.STATE_CONNECTION_ERROR) { if (config != null && config.getState() == ServerConfig.STATE_CONNECTION_ERROR) {
config.setState(ServerConfig.STATE_READY); config.setState(ServerConfig.STATE_READY);
} }
......
...@@ -62,7 +62,7 @@ public class SidebarMainFragment extends AbstractFragment { ...@@ -62,7 +62,7 @@ public class SidebarMainFragment extends AbstractFragment {
serverConfigId = args == null ? null : args.getString("serverConfigId"); serverConfigId = args == null ? null : args.getString("serverConfigId");
if (!TextUtils.isEmpty(serverConfigId)) { if (!TextUtils.isEmpty(serverConfigId)) {
ServerConfig config = RealmStore.getDefault().executeTransactionForRead(realm -> ServerConfig config = RealmStore.getDefault().executeTransactionForRead(realm ->
realm.where(ServerConfig.class).equalTo("serverConfigId", serverConfigId).findFirst()); realm.where(ServerConfig.class).equalTo(ServerConfig.ID, serverConfigId).findFirst());
if (config != null) { if (config != null) {
hostname = config.getHostname(); hostname = config.getHostname();
} }
...@@ -71,7 +71,7 @@ public class SidebarMainFragment extends AbstractFragment { ...@@ -71,7 +71,7 @@ public class SidebarMainFragment extends AbstractFragment {
if (realmHelper != null) { if (realmHelper != null) {
roomsObserver = realmHelper roomsObserver = realmHelper
.createListObserver( .createListObserver(
realm -> realm.where(RoomSubscription.class).equalTo("open", true).findAll()) realm -> realm.where(RoomSubscription.class).equalTo(RoomSubscription.OPEN, true).findAll())
.setOnUpdateListener(list -> roomListManager.setRooms(list)); .setOnUpdateListener(list -> roomListManager.setRooms(list));
currentUserObserver = realmHelper currentUserObserver = realmHelper
......
...@@ -34,8 +34,8 @@ public class AddDirectMessageDialogFragment extends AbstractAddRoomDialogFragmen ...@@ -34,8 +34,8 @@ public class AddDirectMessageDialogFragment extends AbstractAddRoomDialogFragmen
RealmAutoCompleteAdapter<User> adapter = realmHelper.createAutoCompleteAdapter(getContext(), RealmAutoCompleteAdapter<User> adapter = realmHelper.createAutoCompleteAdapter(getContext(),
(realm, text) -> realm.where(User.class) (realm, text) -> realm.where(User.class)
.contains("username", text, Case.INSENSITIVE) .contains(User.USERNAME, text, Case.INSENSITIVE)
.findAllSorted("username"), .findAllSorted(User.USERNAME),
context -> new SuggestUserAdapter(context, hostname)); context -> new SuggestUserAdapter(context, hostname));
autoCompleteTextView.setAdapter(adapter); autoCompleteTextView.setAdapter(adapter);
......
...@@ -12,7 +12,7 @@ public class CheckSum { ...@@ -12,7 +12,7 @@ public class CheckSum {
* SHA-256. * SHA-256.
*/ */
public static String sha256(String orig) { public static String sha256(String orig) {
MessageDigest messageDigest = null; MessageDigest messageDigest;
try { try {
messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException exception) { } catch (NoSuchAlgorithmException exception) {
......
...@@ -33,8 +33,7 @@ public class FileUploadHelper { ...@@ -33,8 +33,7 @@ public class FileUploadHelper {
} }
/** /**
* requestUploading file. * requestUploading file. returns id for observing progress.
* returns id for observing progress.
*/ */
public public
@Nullable @Nullable
...@@ -64,15 +63,16 @@ public class FileUploadHelper { ...@@ -64,15 +63,16 @@ public class FileUploadHelper {
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject() realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject()
.put("uplId", uplId) .put(FileUploading.ID, uplId)
.put("syncstate", SyncState.NOT_SYNCED) .put(FileUploading.SYNC_STATE, SyncState.NOT_SYNCED)
.put("storageType", TextUtils.isEmpty(storageType) ? JSONObject.NULL : storageType) .put(FileUploading.STORAGE_TYPE,
.put("uri", uri.toString()) TextUtils.isEmpty(storageType) ? JSONObject.NULL : storageType)
.put("filename", filename) .put(FileUploading.URI, uri.toString())
.put("filesize", filesize) .put(FileUploading.FILENAME, filename)
.put("mimeType", mimeType) .put(FileUploading.FILE_SIZE, filesize)
.put("roomId", roomId) .put(FileUploading.MIME_TYPE, mimeType)
.put("error", JSONObject.NULL) .put(FileUploading.ROOM_ID, roomId)
.put(FileUploading.ERROR, JSONObject.NULL)
) )
).continueWith(new LogcatIfError()); ).continueWith(new LogcatIfError());
return uplId; return uplId;
......
...@@ -48,7 +48,7 @@ public class RoomUserAdapter extends RecyclerView.Adapter<RoomUserViewHolder> { ...@@ -48,7 +48,7 @@ public class RoomUserAdapter extends RecyclerView.Adapter<RoomUserViewHolder> {
} }
User user = realmHelper.executeTransactionForRead(realm -> User user = realmHelper.executeTransactionForRead(realm ->
realm.where(User.class).equalTo("username", username).findFirst()); realm.where(User.class).equalTo(User.USERNAME, username).findFirst());
if (user == null) { if (user == null) {
user = new User(); user = new User();
user.setUsername(username); user.setUsername(username);
......
...@@ -13,6 +13,14 @@ import hugo.weaving.DebugLog; ...@@ -13,6 +13,14 @@ import hugo.weaving.DebugLog;
* Server configuration. * Server configuration.
*/ */
public class ServerConfig extends RealmObject { public class ServerConfig extends RealmObject {
public static final String ID = "serverConfigId";
public static final String HOSTNAME = "hostname";
public static final String STATE = "state";
public static final String SESSION = "session";
public static final String ERROR = "error";
public static final String SYNC_PUSH_TOKEN = "syncPushToken";
public static final int STATE_READY = 0; public static final int STATE_READY = 0;
public static final int STATE_CONNECTING = 1; public static final int STATE_CONNECTING = 1;
public static final int STATE_CONNECTED = 2; public static final int STATE_CONNECTED = 2;
...@@ -23,6 +31,7 @@ public class ServerConfig extends RealmObject { ...@@ -23,6 +31,7 @@ public class ServerConfig extends RealmObject {
private int state; private int state;
private String session; private String session;
private String error; private String error;
private boolean syncPushToken;
/** /**
* Log the server connection is lost due to some exception. * Log the server connection is lost due to some exception.
...@@ -31,9 +40,9 @@ public class ServerConfig extends RealmObject { ...@@ -31,9 +40,9 @@ public class ServerConfig extends RealmObject {
public static void logConnectionError(String serverConfigId, Exception exception) { public static void logConnectionError(String serverConfigId, Exception exception) {
RealmStore.getDefault().executeTransaction( RealmStore.getDefault().executeTransaction(
realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class, new JSONObject() realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class, new JSONObject()
.put("serverConfigId", serverConfigId) .put(ID, serverConfigId)
.put("state", STATE_CONNECTION_ERROR) .put(STATE, STATE_CONNECTION_ERROR)
.put("error", exception.getMessage()))) .put(ERROR, exception.getMessage())))
.continueWith(new LogcatIfError()); .continueWith(new LogcatIfError());
} }
...@@ -43,11 +52,11 @@ public class ServerConfig extends RealmObject { ...@@ -43,11 +52,11 @@ public class ServerConfig extends RealmObject {
public static Task<Void> updateState(final String serverConfigId, int state) { public static Task<Void> updateState(final String serverConfigId, int state) {
return RealmStore.getDefault().executeTransaction(realm -> { return RealmStore.getDefault().executeTransaction(realm -> {
ServerConfig config = ServerConfig config =
realm.where(ServerConfig.class).equalTo("serverConfigId", serverConfigId).findFirst(); realm.where(ServerConfig.class).equalTo(ID, serverConfigId).findFirst();
if (config == null || config.getState() != state) { if (config == null || config.getState() != state) {
realm.createOrUpdateObjectFromJson(ServerConfig.class, new JSONObject() realm.createOrUpdateObjectFromJson(ServerConfig.class, new JSONObject()
.put("serverConfigId", serverConfigId) .put(ID, serverConfigId)
.put("state", state)); .put(STATE, state));
} }
return null; return null;
}); });
...@@ -92,4 +101,12 @@ public class ServerConfig extends RealmObject { ...@@ -92,4 +101,12 @@ public class ServerConfig extends RealmObject {
public void setError(String error) { public void setError(String error) {
this.error = error; this.error = error;
} }
public boolean shouldSyncPushToken() {
return syncPushToken;
}
public void setSyncPushToken(boolean syncPushToken) {
this.syncPushToken = syncPushToken;
}
} }
...@@ -5,6 +5,7 @@ import io.realm.annotations.PrimaryKey; ...@@ -5,6 +5,7 @@ import io.realm.annotations.PrimaryKey;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import chat.rocket.android.model.JsonConstants;
import chat.rocket.android.model.SyncState; import chat.rocket.android.model.SyncState;
/** /**
...@@ -15,6 +16,17 @@ import chat.rocket.android.model.SyncState; ...@@ -15,6 +16,17 @@ import chat.rocket.android.model.SyncState;
public class Message extends RealmObject { public class Message extends RealmObject {
//ref: Rocket.Chat:packages/rocketchat-lib/lib/MessageTypes.coffee //ref: Rocket.Chat:packages/rocketchat-lib/lib/MessageTypes.coffee
public static final String ID = "_id";
public static final String TYPE = "t";
public static final String ROOM_ID = "rid";
public static final String SYNC_STATE = "syncstate";
public static final String TIMESTAMP = "ts";
public static final String MESSAGE = "msg";
public static final String USER = "u";
public static final String GROUPABLE = "groupable";
public static final String ATTACHMENTS = "attachments";
public static final String URLS = "urls";
@PrimaryKey private String _id; @PrimaryKey private String _id;
private String t; //type: private String t; //type:
private String rid; //roomId. private String rid; //roomId.
...@@ -27,12 +39,12 @@ public class Message extends RealmObject { ...@@ -27,12 +39,12 @@ public class Message extends RealmObject {
private String urls; //JSONArray. private String urls; //JSONArray.
public static JSONObject customizeJson(JSONObject messageJson) throws JSONException { public static JSONObject customizeJson(JSONObject messageJson) throws JSONException {
long ts = messageJson.getJSONObject("ts").getLong("$date"); long ts = messageJson.getJSONObject(TIMESTAMP).getLong(JsonConstants.DATE);
messageJson.remove("ts"); messageJson.remove(TIMESTAMP);
messageJson.put("ts", ts).put("syncstate", SyncState.SYNCED); messageJson.put(TIMESTAMP, ts).put(SYNC_STATE, SyncState.SYNCED);
if (messageJson.isNull("groupable")) { if (messageJson.isNull(GROUPABLE)) {
messageJson.put("groupable", true); messageJson.put(GROUPABLE, true);
} }
return messageJson; return messageJson;
......
...@@ -10,6 +10,13 @@ import io.realm.annotations.PrimaryKey; ...@@ -10,6 +10,13 @@ import io.realm.annotations.PrimaryKey;
"PMD.MethodNamingConventions", "PMD.VariableNamingConventions"}) "PMD.MethodNamingConventions", "PMD.VariableNamingConventions"})
public class MeteorLoginServiceConfiguration public class MeteorLoginServiceConfiguration
extends RealmObject { extends RealmObject {
public static final String ID = "_id";
public static final String SERVICE = "service";
public static final String CONSUMER_KEY = "consumerKey";
public static final String APP_ID = "appId";
public static final String CLIENT_ID = "clientId";
@PrimaryKey private String _id; @PrimaryKey private String _id;
private String service; private String service;
private String consumerKey; //for Twitter private String consumerKey; //for Twitter
......
...@@ -6,6 +6,7 @@ import io.realm.annotations.PrimaryKey; ...@@ -6,6 +6,7 @@ import io.realm.annotations.PrimaryKey;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import chat.rocket.android.model.JsonConstants;
import chat.rocket.android.realm_helper.RealmHelper; import chat.rocket.android.realm_helper.RealmHelper;
/** /**
...@@ -14,6 +15,14 @@ import chat.rocket.android.realm_helper.RealmHelper; ...@@ -14,6 +15,14 @@ import chat.rocket.android.realm_helper.RealmHelper;
@SuppressWarnings({"PMD.ShortClassName", "PMD.ShortVariable", @SuppressWarnings({"PMD.ShortClassName", "PMD.ShortVariable",
"PMD.MethodNamingConventions", "PMD.VariableNamingConventions"}) "PMD.MethodNamingConventions", "PMD.VariableNamingConventions"})
public class PublicSetting extends RealmObject { public class PublicSetting extends RealmObject {
public static final String ID = "_id";
public static final String GROUP = "group";
public static final String TYPE = "type";
public static final String VALUE = "value";
public static final String UPDATED_AT = "_updatedAt";
public static final String META = "meta";
@PrimaryKey private String _id; @PrimaryKey private String _id;
private String group; private String group;
private String type; private String type;
...@@ -22,25 +31,24 @@ public class PublicSetting extends RealmObject { ...@@ -22,25 +31,24 @@ public class PublicSetting extends RealmObject {
private String meta; //JSON private String meta; //JSON
public static JSONObject customizeJson(JSONObject settingJson) throws JSONException { public static JSONObject customizeJson(JSONObject settingJson) throws JSONException {
if (!settingJson.isNull("_updatedAt")) { if (!settingJson.isNull(UPDATED_AT)) {
long updatedAt = settingJson.getJSONObject("_updatedAt").getLong("$date"); long updatedAt = settingJson.getJSONObject(UPDATED_AT)
settingJson.remove("_updatedAt"); .getLong(JsonConstants.DATE);
settingJson.put("_updatedAt", updatedAt); settingJson.remove(UPDATED_AT);
settingJson.put(UPDATED_AT, updatedAt);
} }
return settingJson; return settingJson;
} }
private static
@Nullable @Nullable
PublicSetting get(RealmHelper realmHelper, String _id) { private static PublicSetting get(RealmHelper realmHelper, String _id) {
return realmHelper.executeTransactionForRead(realm -> return realmHelper.executeTransactionForRead(realm ->
realm.where(PublicSetting.class).equalTo("_id", _id).findFirst()); realm.where(PublicSetting.class).equalTo(ID, _id).findFirst());
} }
public static
@Nullable @Nullable
String getString(RealmHelper realmHelper, public static String getString(RealmHelper realmHelper,
String _id, String defaultValue) { String _id, String defaultValue) {
PublicSetting setting = get(realmHelper, _id); PublicSetting setting = get(realmHelper, _id);
if (setting != null) { if (setting != null) {
...@@ -49,9 +57,7 @@ public class PublicSetting extends RealmObject { ...@@ -49,9 +57,7 @@ public class PublicSetting extends RealmObject {
return defaultValue; return defaultValue;
} }
public static public static boolean getBoolean(RealmHelper realmHelper,
@Nullable
boolean getBoolean(RealmHelper realmHelper,
String _id, boolean defaultValue) { String _id, boolean defaultValue) {
PublicSetting setting = get(realmHelper, _id); PublicSetting setting = get(realmHelper, _id);
if (setting != null) { if (setting != null) {
......
...@@ -5,12 +5,25 @@ import io.realm.annotations.PrimaryKey; ...@@ -5,12 +5,25 @@ import io.realm.annotations.PrimaryKey;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import chat.rocket.android.model.JsonConstants;
/** /**
* Chat Room(Subscription). * Chat Room(Subscription).
*/ */
@SuppressWarnings({"PMD.ShortClassName", "PMD.ShortVariable", @SuppressWarnings({"PMD.ShortClassName", "PMD.ShortVariable",
"PMD.MethodNamingConventions", "PMD.VariableNamingConventions"}) "PMD.MethodNamingConventions", "PMD.VariableNamingConventions"})
public class RoomSubscription extends RealmObject { public class RoomSubscription extends RealmObject {
public static final String ID = "_id";
public static final String ROOM_ID = "rid";
public static final String NAME = "name";
public static final String TYPE = "t";
public static final String OPEN = "open";
public static final String ALERT = "alert";
public static final String UNREAD = "unread";
public static final String UPDATED_AT = "_updatedAt";
public static final String LAST_SEEN = "ls";
public static final String TYPE_CHANNEL = "c"; public static final String TYPE_CHANNEL = "c";
public static final String TYPE_PRIVATE = "p"; public static final String TYPE_PRIVATE = "p";
public static final String TYPE_DIRECT_MESSAGE = "d"; public static final String TYPE_DIRECT_MESSAGE = "d";
...@@ -27,16 +40,16 @@ public class RoomSubscription extends RealmObject { ...@@ -27,16 +40,16 @@ public class RoomSubscription extends RealmObject {
private long ls; //last seen. private long ls; //last seen.
public static JSONObject customizeJson(JSONObject roomSubscriptionJson) throws JSONException { public static JSONObject customizeJson(JSONObject roomSubscriptionJson) throws JSONException {
if (!roomSubscriptionJson.isNull("ls")) { if (!roomSubscriptionJson.isNull(LAST_SEEN)) {
long ls = roomSubscriptionJson.getJSONObject("ls").getLong("$date"); long ls = roomSubscriptionJson.getJSONObject(LAST_SEEN).getLong(JsonConstants.DATE);
roomSubscriptionJson.remove("ls"); roomSubscriptionJson.remove(LAST_SEEN);
roomSubscriptionJson.put("ls", ls); roomSubscriptionJson.put(LAST_SEEN, ls);
} }
if (!roomSubscriptionJson.isNull("_updatedAt")) { if (!roomSubscriptionJson.isNull(UPDATED_AT)) {
long updatedAt = roomSubscriptionJson.getJSONObject("_updatedAt").getLong("$date"); long updatedAt = roomSubscriptionJson.getJSONObject(UPDATED_AT).getLong(JsonConstants.DATE);
roomSubscriptionJson.remove("_updatedAt"); roomSubscriptionJson.remove(UPDATED_AT);
roomSubscriptionJson.put("_updatedAt", updatedAt); roomSubscriptionJson.put(UPDATED_AT, updatedAt);
} }
return roomSubscriptionJson; return roomSubscriptionJson;
......
...@@ -12,6 +12,14 @@ import io.realm.annotations.PrimaryKey; ...@@ -12,6 +12,14 @@ import io.realm.annotations.PrimaryKey;
@SuppressWarnings({"PMD.ShortClassName", "PMD.ShortVariable", @SuppressWarnings({"PMD.ShortClassName", "PMD.ShortVariable",
"PMD.MethodNamingConventions", "PMD.VariableNamingConventions"}) "PMD.MethodNamingConventions", "PMD.VariableNamingConventions"})
public class User extends RealmObject { public class User extends RealmObject {
public static final String ID = "_id";
public static final String USERNAME = "username";
public static final String STATUS = "status";
public static final String UTC_OFFSET = "utcOffset";
public static final String EMAILS = "emails";
public static final String SETTINGS = "settings";
public static final String STATUS_ONLINE = "online"; public static final String STATUS_ONLINE = "online";
public static final String STATUS_BUSY = "busy"; public static final String STATUS_BUSY = "busy";
public static final String STATUS_AWAY = "away"; public static final String STATUS_AWAY = "away";
...@@ -25,7 +33,7 @@ public class User extends RealmObject { ...@@ -25,7 +33,7 @@ public class User extends RealmObject {
private Settings settings; private Settings settings;
public static RealmQuery<User> queryCurrentUser(Realm realm) { public static RealmQuery<User> queryCurrentUser(Realm realm) {
return realm.where(User.class).isNotEmpty("emails"); return realm.where(User.class).isNotEmpty(EMAILS);
} }
public String getId() { public String getId() {
......
...@@ -7,6 +7,18 @@ import io.realm.annotations.PrimaryKey; ...@@ -7,6 +7,18 @@ import io.realm.annotations.PrimaryKey;
* holding statuses for uploading file. * holding statuses for uploading file.
*/ */
public class FileUploading extends RealmObject { public class FileUploading extends RealmObject {
public static final String ID = "uplId";
public static final String SYNC_STATE = "syncstate";
public static final String STORAGE_TYPE = "storageType";
public static final String URI = "uri";
public static final String FILENAME = "filename";
public static final String FILE_SIZE = "filesize";
public static final String MIME_TYPE = "mimeType";
public static final String ROOM_ID = "roomId";
public static final String UPLOADED_SIZE = "uploadedSize";
public static final String ERROR = "error";
public static final String STORAGE_TYPE_S3 = "AmazonS3"; public static final String STORAGE_TYPE_S3 = "AmazonS3";
public static final String STORAGE_TYPE_GRID_FS = "GridFS"; public static final String STORAGE_TYPE_GRID_FS = "GridFS";
public static final String STORAGE_TYPE_FILE_SYSTEM = "FileSystem"; public static final String STORAGE_TYPE_FILE_SYSTEM = "FileSystem";
......
...@@ -7,6 +7,13 @@ import io.realm.annotations.PrimaryKey; ...@@ -7,6 +7,13 @@ import io.realm.annotations.PrimaryKey;
* Get users in a Room. * Get users in a Room.
*/ */
public class GetUsersOfRoomsProcedure extends RealmObject { public class GetUsersOfRoomsProcedure extends RealmObject {
public static final String ID = "roomId";
public static final String SYNC_STATE = "syncstate";
public static final String SHOW_ALL = "showAll";
public static final String TOTAL = "total";
public static final String RECORDS = "records";
@PrimaryKey private String roomId; @PrimaryKey private String roomId;
private int syncstate; private int syncstate;
private boolean showAll; private boolean showAll;
......
...@@ -7,9 +7,16 @@ import io.realm.annotations.PrimaryKey; ...@@ -7,9 +7,16 @@ import io.realm.annotations.PrimaryKey;
* Load messages in the room. * Load messages in the room.
*/ */
public class LoadMessageProcedure extends RealmObject { public class LoadMessageProcedure extends RealmObject {
public static final String ID = "roomId";
public static final String SYNC_STATE = "syncstate";
public static final String RESET = "reset";
public static final String TIMESTAMP = "timestamp";
public static final String COUNT = "count";
public static final String HAS_NEXT = "hasNext";
@PrimaryKey private String roomId; @PrimaryKey private String roomId;
private int syncstate; private int syncstate;
private boolean reset; private boolean reset;
private long timestamp; private long timestamp;
private int count; private int count;
......
...@@ -20,6 +20,13 @@ import chat.rocket.android.service.RocketChatService; ...@@ -20,6 +20,13 @@ import chat.rocket.android.service.RocketChatService;
public class MethodCall extends RealmObject { public class MethodCall extends RealmObject {
public static final String ID = "methodCallId";
public static final String SYNC_STATE = "syncstate";
public static final String NAME = "name";
public static final String PARAMS_JSON = "paramsJson";
public static final String RESULT_JSON = "resultJson";
public static final String TIMEOUT = "timeout";
private static final HashMap<String, RealmObjectObserver<MethodCall>> REF_MAP = new HashMap<>(); private static final HashMap<String, RealmObjectObserver<MethodCall>> REF_MAP = new HashMap<>();
@PrimaryKey private String methodCallId; @PrimaryKey private String methodCallId;
private int syncstate; private int syncstate;
...@@ -38,10 +45,10 @@ public class MethodCall extends RealmObject { ...@@ -38,10 +45,10 @@ public class MethodCall extends RealmObject {
TaskCompletionSource<String> task = new TaskCompletionSource<>(); TaskCompletionSource<String> task = new TaskCompletionSource<>();
realmHelper.executeTransaction(realm -> { realmHelper.executeTransaction(realm -> {
MethodCall call = realm.createObjectFromJson(MethodCall.class, new JSONObject() MethodCall call = realm.createObjectFromJson(MethodCall.class, new JSONObject()
.put("methodCallId", newId) .put(ID, newId)
.put("syncstate", SyncState.NOT_SYNCED) .put(SYNC_STATE, SyncState.NOT_SYNCED)
.put("timeout", timeout) .put(TIMEOUT, timeout)
.put("name", name)); .put(NAME, name));
call.setParamsJson(paramsJson); call.setParamsJson(paramsJson);
return null; return null;
}).continueWith(_task -> { }).continueWith(_task -> {
...@@ -50,7 +57,7 @@ public class MethodCall extends RealmObject { ...@@ -50,7 +57,7 @@ public class MethodCall extends RealmObject {
} else { } else {
final RealmObjectObserver<MethodCall> observer = final RealmObjectObserver<MethodCall> observer =
realmHelper.createObjectObserver(realm -> realmHelper.createObjectObserver(realm ->
realm.where(MethodCall.class).equalTo("methodCallId", newId)); realm.where(MethodCall.class).equalTo(ID, newId));
observer.setOnUpdateListener(methodCall -> { observer.setOnUpdateListener(methodCall -> {
if (methodCall == null) { if (methodCall == null) {
observer.unsub(); observer.unsub();
...@@ -95,7 +102,7 @@ public class MethodCall extends RealmObject { ...@@ -95,7 +102,7 @@ public class MethodCall extends RealmObject {
public static final Task<Void> remove(RealmHelper realmHelper, String methodCallId) { public static final Task<Void> remove(RealmHelper realmHelper, String methodCallId) {
return realmHelper.executeTransaction(realm -> return realmHelper.executeTransaction(realm ->
realm.where(MethodCall.class) realm.where(MethodCall.class)
.equalTo("methodCallId", methodCallId) .equalTo(ID, methodCallId)
.findAll() .findAll()
.deleteAllFromRealm()); .deleteAllFromRealm());
} }
......
...@@ -7,6 +7,15 @@ import io.realm.annotations.PrimaryKey; ...@@ -7,6 +7,15 @@ import io.realm.annotations.PrimaryKey;
* ViewData model for notification. * ViewData model for notification.
*/ */
public class NotificationItem extends RealmObject { public class NotificationItem extends RealmObject {
public static final String ID = "roomId";
public static final String TITLE = "title";
public static final String DESCRIPTION = "description";
public static final String UNREAD_COUNT = "unreadCount";
public static final String SENDER_NAME = "senderName";
public static final String CONTENT_UPDATED_AT = "contentUpdatedAt";
public static final String LAST_SEEN_AT = "lastSeenAt";
@PrimaryKey private String roomId; @PrimaryKey private String roomId;
private String title; private String title;
private String description; private String description;
......
...@@ -15,23 +15,31 @@ import hugo.weaving.DebugLog; ...@@ -15,23 +15,31 @@ import hugo.weaving.DebugLog;
* Login session info. * Login session info.
*/ */
public class Session extends RealmObject { public class Session extends RealmObject {
public static final String ID = "sessionId";
public static final String TOKEN = "token";
public static final String TOKEN_VERIFIED = "tokenVerified";
public static final String ERROR = "error";
public static final int DEFAULT_ID = 0; public static final int DEFAULT_ID = 0;
public static final String AUTH_ERROR_CODE = "[403]";
@PrimaryKey private int sessionId; //only 0 is used! @PrimaryKey private int sessionId; //only 0 is used!
private String token; private String token;
private boolean tokenVerified; private boolean tokenVerified;
private String error; private String error;
public static RealmQuery<Session> queryDefaultSession(Realm realm) { public static RealmQuery<Session> queryDefaultSession(Realm realm) {
return realm.where(Session.class).equalTo("sessionId", Session.DEFAULT_ID); return realm.where(Session.class).equalTo(ID, Session.DEFAULT_ID);
} }
/** /**
* Log the server connection is lost due to soem exception. * Log the server connection is lost due to some exception.
*/ */
@DebugLog @DebugLog
public static void logError(RealmHelper realmHelper, Exception exception) { public static void logError(RealmHelper realmHelper, Exception exception) {
String errString = exception.getMessage(); String errString = exception.getMessage();
if (!TextUtils.isEmpty(errString) && errString.contains("[403]")) { if (!TextUtils.isEmpty(errString) && errString.contains(AUTH_ERROR_CODE)) {
realmHelper.executeTransaction(realm -> { realmHelper.executeTransaction(realm -> {
realm.delete(Session.class); realm.delete(Session.class);
return null; return null;
...@@ -39,9 +47,9 @@ public class Session extends RealmObject { ...@@ -39,9 +47,9 @@ public class Session extends RealmObject {
} else { } else {
realmHelper.executeTransaction( realmHelper.executeTransaction(
realm -> realm.createOrUpdateObjectFromJson(Session.class, new JSONObject() realm -> realm.createOrUpdateObjectFromJson(Session.class, new JSONObject()
.put("sessionId", Session.DEFAULT_ID) .put(ID, Session.DEFAULT_ID)
.put("tokenVerified", false) .put(TOKEN_VERIFIED, false)
.put("error", errString))) .put(ERROR, errString)))
.continueWith(new LogcatIfError()); .continueWith(new LogcatIfError());
} }
} }
......
...@@ -39,8 +39,8 @@ public class RocketChatService extends Service { ...@@ -39,8 +39,8 @@ public class RocketChatService extends Service {
realmHelper = RealmStore.getDefault(); realmHelper = RealmStore.getDefault();
connectionRequiredServerConfigObserver = realmHelper connectionRequiredServerConfigObserver = realmHelper
.createListObserver(realm -> realm.where(ServerConfig.class) .createListObserver(realm -> realm.where(ServerConfig.class)
.isNotNull("hostname") .isNotNull(ServerConfig.HOSTNAME)
.equalTo("state", ServerConfig.STATE_READY) .equalTo(ServerConfig.STATE, ServerConfig.STATE_READY)
.findAll()) .findAll())
.setOnUpdateListener(this::connectToServerWithServerConfig); .setOnUpdateListener(this::connectToServerWithServerConfig);
...@@ -50,7 +50,7 @@ public class RocketChatService extends Service { ...@@ -50,7 +50,7 @@ public class RocketChatService extends Service {
private void refreshServerConfigState() { private void refreshServerConfigState() {
realmHelper.executeTransaction(realm -> { realmHelper.executeTransaction(realm -> {
RealmResults<ServerConfig> configs = realm.where(ServerConfig.class) RealmResults<ServerConfig> configs = realm.where(ServerConfig.class)
.notEqualTo("state", ServerConfig.STATE_READY) .notEqualTo(ServerConfig.STATE, ServerConfig.STATE_READY)
.findAll(); .findAll();
for (ServerConfig config : configs) { for (ServerConfig config : configs) {
config.setState(ServerConfig.STATE_READY); config.setState(ServerConfig.STATE_READY);
...@@ -64,7 +64,7 @@ public class RocketChatService extends Service { ...@@ -64,7 +64,7 @@ public class RocketChatService extends Service {
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
List<ServerConfig> configs = realmHelper.executeTransactionForReadResults(realm -> List<ServerConfig> configs = realmHelper.executeTransactionForReadResults(realm ->
realm.where(ServerConfig.class) realm.where(ServerConfig.class)
.equalTo("state", ServerConfig.STATE_CONNECTED) .equalTo(ServerConfig.STATE, ServerConfig.STATE_CONNECTED)
.findAll()); .findAll());
for (ServerConfig config : configs) { for (ServerConfig config : configs) {
String serverConfigId = config.getServerConfigId(); String serverConfigId = config.getServerConfigId();
...@@ -80,11 +80,11 @@ public class RocketChatService extends Service { ...@@ -80,11 +80,11 @@ public class RocketChatService extends Service {
RealmResults<ServerConfig> targetConfigs = realm RealmResults<ServerConfig> targetConfigs = realm
.where(ServerConfig.class) .where(ServerConfig.class)
.beginGroup() .beginGroup()
.equalTo("state", ServerConfig.STATE_CONNECTION_ERROR) .equalTo(ServerConfig.STATE, ServerConfig.STATE_CONNECTION_ERROR)
.or() .or()
.isNotNull("error") .isNotNull(ServerConfig.ERROR)
.endGroup() .endGroup()
.isNotNull("session") .isNotNull(ServerConfig.SESSION)
.findAll(); .findAll();
for (ServerConfig config : targetConfigs) { for (ServerConfig config : targetConfigs) {
config.setState(ServerConfig.STATE_READY); config.setState(ServerConfig.STATE_READY);
......
...@@ -144,7 +144,7 @@ public class RocketChatWebSocketThread extends HandlerThread { ...@@ -144,7 +144,7 @@ public class RocketChatWebSocketThread extends HandlerThread {
if (ddpClient == null || !ddpClient.isConnected()) { if (ddpClient == null || !ddpClient.isConnected()) {
defaultRealm.executeTransaction(realm -> { defaultRealm.executeTransaction(realm -> {
ServerConfig config = realm.where(ServerConfig.class) ServerConfig config = realm.where(ServerConfig.class)
.equalTo("serverConfigId", serverConfigId) .equalTo(ServerConfig.ID, serverConfigId)
.findFirst(); .findFirst();
if (config != null && config.getState() == ServerConfig.STATE_CONNECTED) { if (config != null && config.getState() == ServerConfig.STATE_CONNECTED) {
config.setState(ServerConfig.STATE_READY); config.setState(ServerConfig.STATE_READY);
...@@ -164,7 +164,7 @@ public class RocketChatWebSocketThread extends HandlerThread { ...@@ -164,7 +164,7 @@ public class RocketChatWebSocketThread extends HandlerThread {
@DebugLog @DebugLog
private Task<Void> connect() { private Task<Void> connect() {
final ServerConfig config = defaultRealm.executeTransactionForRead(realm -> final ServerConfig config = defaultRealm.executeTransactionForRead(realm ->
realm.where(ServerConfig.class).equalTo("serverConfigId", serverConfigId).findFirst()); realm.where(ServerConfig.class).equalTo(ServerConfig.ID, serverConfigId).findFirst());
prepareWebSocket(config.getHostname()); prepareWebSocket(config.getHostname());
return ddpClient.connect(config.getSession()).onSuccessTask(task -> { return ddpClient.connect(config.getSession()).onSuccessTask(task -> {
...@@ -232,7 +232,7 @@ public class RocketChatWebSocketThread extends HandlerThread { ...@@ -232,7 +232,7 @@ public class RocketChatWebSocketThread extends HandlerThread {
listenersRegistered = true; listenersRegistered = true;
final ServerConfig config = defaultRealm.executeTransactionForRead(realm -> final ServerConfig config = defaultRealm.executeTransactionForRead(realm ->
realm.where(ServerConfig.class).equalTo("serverConfigId", serverConfigId).findFirst()); realm.where(ServerConfig.class).equalTo(ServerConfig.ID, serverConfigId).findFirst());
final String hostname = config.getHostname(); final String hostname = config.getHostname();
for (Class clazz : REGISTERABLE_CLASSES) { for (Class clazz : REGISTERABLE_CLASSES) {
......
...@@ -31,7 +31,7 @@ public class NotificationDismissalCallbackService extends IntentService { ...@@ -31,7 +31,7 @@ public class NotificationDismissalCallbackService extends IntentService {
realmHelper.executeTransaction(realm -> { realmHelper.executeTransaction(realm -> {
NotificationItem item = NotificationItem item =
realm.where(NotificationItem.class).equalTo("roomId", roomId).findFirst(); realm.where(NotificationItem.class).equalTo(NotificationItem.ID, roomId).findFirst();
if (item != null) { if (item != null) {
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
if (item.getLastSeenAt() <= currentTime) { if (item.getLastSeenAt() <= currentTime) {
......
...@@ -42,8 +42,8 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi ...@@ -42,8 +42,8 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi
realmHelper.executeTransaction(realm -> { realmHelper.executeTransaction(realm -> {
// resume pending operations. // resume pending operations.
RealmResults<FileUploading> pendingUploadRequests = realm.where(FileUploading.class) RealmResults<FileUploading> pendingUploadRequests = realm.where(FileUploading.class)
.equalTo("syncstate", SyncState.SYNCING) .equalTo(FileUploading.SYNC_STATE, SyncState.SYNCING)
.equalTo("storageType", FileUploading.STORAGE_TYPE_S3) .equalTo(FileUploading.STORAGE_TYPE, FileUploading.STORAGE_TYPE_S3)
.findAll(); .findAll();
for (FileUploading req : pendingUploadRequests) { for (FileUploading req : pendingUploadRequests) {
req.setSyncState(SyncState.NOT_SYNCED); req.setSyncState(SyncState.NOT_SYNCED);
...@@ -52,11 +52,11 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi ...@@ -52,11 +52,11 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi
// clean up records. // clean up records.
realm.where(FileUploading.class) realm.where(FileUploading.class)
.beginGroup() .beginGroup()
.equalTo("syncstate", SyncState.SYNCED) .equalTo(FileUploading.SYNC_STATE, SyncState.SYNCED)
.or() .or()
.equalTo("syncstate", SyncState.FAILED) .equalTo(FileUploading.SYNC_STATE, SyncState.FAILED)
.endGroup() .endGroup()
.equalTo("storageType", FileUploading.STORAGE_TYPE_S3) .equalTo(FileUploading.STORAGE_TYPE, FileUploading.STORAGE_TYPE_S3)
.findAll().deleteAllFromRealm(); .findAll().deleteAllFromRealm();
return null; return null;
}).continueWith(new LogcatIfError()); }).continueWith(new LogcatIfError());
...@@ -65,8 +65,8 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi ...@@ -65,8 +65,8 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi
@Override @Override
public RealmResults<FileUploading> queryItems(Realm realm) { public RealmResults<FileUploading> queryItems(Realm realm) {
return realm.where(FileUploading.class) return realm.where(FileUploading.class)
.equalTo("syncstate", SyncState.NOT_SYNCED) .equalTo(FileUploading.SYNC_STATE, SyncState.NOT_SYNCED)
.equalTo("storageType", FileUploading.STORAGE_TYPE_S3) .equalTo(FileUploading.STORAGE_TYPE, FileUploading.STORAGE_TYPE_S3)
.findAll(); .findAll();
} }
...@@ -77,7 +77,8 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi ...@@ -77,7 +77,8 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi
} }
List<FileUploading> uploadingList = realmHelper.executeTransactionForReadResults(realm -> List<FileUploading> uploadingList = realmHelper.executeTransactionForReadResults(realm ->
realm.where(FileUploading.class).equalTo("syncstate", SyncState.SYNCING).findAll()); realm.where(FileUploading.class).equalTo(FileUploading.SYNC_STATE, SyncState.SYNCING)
.findAll());
if (uploadingList.size() >= 3) { if (uploadingList.size() >= 3) {
// do not upload more than 3 files simultaneously // do not upload more than 3 files simultaneously
return; return;
...@@ -93,8 +94,8 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi ...@@ -93,8 +94,8 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject() realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject()
.put("uplId", uplId) .put(FileUploading.ID, uplId)
.put("syncstate", SyncState.SYNCING) .put(FileUploading.SYNC_STATE, SyncState.SYNCING)
) )
).onSuccessTask(_task -> methodCall.uploadRequest(filename, filesize, mimeType, roomId) ).onSuccessTask(_task -> methodCall.uploadRequest(filename, filesize, mimeType, roomId)
).onSuccessTask(task -> { ).onSuccessTask(task -> {
...@@ -134,8 +135,8 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi ...@@ -134,8 +135,8 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi
numBytes += readBytes; numBytes += readBytes;
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject() realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject()
.put("uplId", uplId) .put(FileUploading.ID, uplId)
.put("uploadedSize", numBytes))) .put(FileUploading.UPLOADED_SIZE, numBytes)))
.continueWith(new LogcatIfError()); .continueWith(new LogcatIfError());
} }
} }
...@@ -164,18 +165,18 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi ...@@ -164,18 +165,18 @@ public class FileUploadingToS3Observer extends AbstractModelObserver<FileUploadi
); );
}).onSuccessTask(task -> realmHelper.executeTransaction(realm -> }).onSuccessTask(task -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject() realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject()
.put("uplId", uplId) .put(FileUploading.ID, uplId)
.put("syncstate", SyncState.SYNCED) .put(FileUploading.SYNC_STATE, SyncState.SYNCED)
.put("error", JSONObject.NULL) .put(FileUploading.ERROR, JSONObject.NULL)
) )
)).continueWithTask(task -> { )).continueWithTask(task -> {
if (task.isFaulted()) { if (task.isFaulted()) {
RCLog.w(task.getError()); RCLog.w(task.getError());
return realmHelper.executeTransaction(realm -> return realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject() realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject()
.put("uplId", uplId) .put(FileUploading.ID, uplId)
.put("syncstate", SyncState.FAILED) .put(FileUploading.SYNC_STATE, SyncState.FAILED)
.put("error", task.getError().getMessage()) .put(FileUploading.ERROR, task.getError().getMessage())
)); ));
} else { } else {
return Task.forResult(null); return Task.forResult(null);
......
...@@ -38,11 +38,11 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo ...@@ -38,11 +38,11 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo
realmHelper.executeTransaction(realm -> { realmHelper.executeTransaction(realm -> {
// resume pending operations. // resume pending operations.
RealmResults<FileUploading> pendingUploadRequests = realm.where(FileUploading.class) RealmResults<FileUploading> pendingUploadRequests = realm.where(FileUploading.class)
.equalTo("syncstate", SyncState.SYNCING) .equalTo(FileUploading.SYNC_STATE, SyncState.SYNCING)
.beginGroup() .beginGroup()
.equalTo("storageType", FileUploading.STORAGE_TYPE_GRID_FS) .equalTo(FileUploading.STORAGE_TYPE, FileUploading.STORAGE_TYPE_GRID_FS)
.or() .or()
.equalTo("storageType", FileUploading.STORAGE_TYPE_FILE_SYSTEM) .equalTo(FileUploading.STORAGE_TYPE, FileUploading.STORAGE_TYPE_FILE_SYSTEM)
.endGroup() .endGroup()
.findAll(); .findAll();
for (FileUploading req : pendingUploadRequests) { for (FileUploading req : pendingUploadRequests) {
...@@ -52,14 +52,14 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo ...@@ -52,14 +52,14 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo
// clean up records. // clean up records.
realm.where(FileUploading.class) realm.where(FileUploading.class)
.beginGroup() .beginGroup()
.equalTo("syncstate", SyncState.SYNCED) .equalTo(FileUploading.SYNC_STATE, SyncState.SYNCED)
.or() .or()
.equalTo("syncstate", SyncState.FAILED) .equalTo(FileUploading.SYNC_STATE, SyncState.FAILED)
.endGroup() .endGroup()
.beginGroup() .beginGroup()
.equalTo("storageType", FileUploading.STORAGE_TYPE_GRID_FS) .equalTo(FileUploading.STORAGE_TYPE, FileUploading.STORAGE_TYPE_GRID_FS)
.or() .or()
.equalTo("storageType", FileUploading.STORAGE_TYPE_FILE_SYSTEM) .equalTo(FileUploading.STORAGE_TYPE, FileUploading.STORAGE_TYPE_FILE_SYSTEM)
.endGroup() .endGroup()
.findAll().deleteAllFromRealm(); .findAll().deleteAllFromRealm();
return null; return null;
...@@ -69,11 +69,11 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo ...@@ -69,11 +69,11 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo
@Override @Override
public RealmResults<FileUploading> queryItems(Realm realm) { public RealmResults<FileUploading> queryItems(Realm realm) {
return realm.where(FileUploading.class) return realm.where(FileUploading.class)
.equalTo("syncstate", SyncState.NOT_SYNCED) .equalTo(FileUploading.SYNC_STATE, SyncState.NOT_SYNCED)
.beginGroup() .beginGroup()
.equalTo("storageType", FileUploading.STORAGE_TYPE_GRID_FS) .equalTo(FileUploading.STORAGE_TYPE, FileUploading.STORAGE_TYPE_GRID_FS)
.or() .or()
.equalTo("storageType", FileUploading.STORAGE_TYPE_FILE_SYSTEM) .equalTo(FileUploading.STORAGE_TYPE, FileUploading.STORAGE_TYPE_FILE_SYSTEM)
.endGroup() .endGroup()
.findAll(); .findAll();
} }
...@@ -85,7 +85,8 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo ...@@ -85,7 +85,8 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo
} }
List<FileUploading> uploadingList = realmHelper.executeTransactionForReadResults(realm -> List<FileUploading> uploadingList = realmHelper.executeTransactionForReadResults(realm ->
realm.where(FileUploading.class).equalTo("syncstate", SyncState.SYNCING).findAll()); realm.where(FileUploading.class).equalTo(FileUploading.SYNC_STATE, SyncState.SYNCING)
.findAll());
if (uploadingList.size() >= 1) { if (uploadingList.size() >= 1) {
// do not upload multiple files simultaneously // do not upload multiple files simultaneously
return; return;
...@@ -115,8 +116,8 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo ...@@ -115,8 +116,8 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject() realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject()
.put("uplId", uplId) .put(FileUploading.ID, uplId)
.put("syncstate", SyncState.SYNCING) .put(FileUploading.SYNC_STATE, SyncState.SYNCING)
) )
).onSuccessTask(_task -> methodCall.ufsCreate(filename, filesize, mimeType, store, roomId) ).onSuccessTask(_task -> methodCall.ufsCreate(filename, filesize, mimeType, store, roomId)
).onSuccessTask(task -> { ).onSuccessTask(task -> {
...@@ -145,8 +146,8 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo ...@@ -145,8 +146,8 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo
Response response = OkHttpHelper.getClientForUploadFile().newCall(request).execute(); Response response = OkHttpHelper.getClientForUploadFile().newCall(request).execute();
if (response.isSuccessful()) { if (response.isSuccessful()) {
final JSONObject obj = new JSONObject() final JSONObject obj = new JSONObject()
.put("uplId", uplId) .put(FileUploading.ID, uplId)
.put("uploadedSize", offset); .put(FileUploading.UPLOADED_SIZE, offset);
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(FileUploading.class, obj)); realm.createOrUpdateObjectFromJson(FileUploading.class, obj));
} else { } else {
...@@ -159,18 +160,18 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo ...@@ -159,18 +160,18 @@ public class FileUploadingWithUfsObserver extends AbstractModelObserver<FileUplo
}).onSuccessTask(task -> methodCall.sendFileMessage(roomId, null, task.getResult()) }).onSuccessTask(task -> methodCall.sendFileMessage(roomId, null, task.getResult())
).onSuccessTask(task -> realmHelper.executeTransaction(realm -> ).onSuccessTask(task -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject() realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject()
.put("uplId", uplId) .put(FileUploading.ID, uplId)
.put("syncstate", SyncState.SYNCED) .put(FileUploading.SYNC_STATE, SyncState.SYNCED)
.put("error", JSONObject.NULL) .put(FileUploading.ERROR, JSONObject.NULL)
) )
)).continueWithTask(task -> { )).continueWithTask(task -> {
if (task.isFaulted()) { if (task.isFaulted()) {
RCLog.w(task.getError()); RCLog.w(task.getError());
return realmHelper.executeTransaction(realm -> return realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject() realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject()
.put("uplId", uplId) .put(FileUploading.ID, uplId)
.put("syncstate", SyncState.FAILED) .put(FileUploading.SYNC_STATE, SyncState.FAILED)
.put("error", task.getError().getMessage()) .put(FileUploading.ERROR, task.getError().getMessage())
)); ));
} else { } else {
return Task.forResult(null); return Task.forResult(null);
......
...@@ -31,7 +31,7 @@ public class GetUsersOfRoomsProcedureObserver ...@@ -31,7 +31,7 @@ public class GetUsersOfRoomsProcedureObserver
@Override @Override
public RealmResults<GetUsersOfRoomsProcedure> queryItems(Realm realm) { public RealmResults<GetUsersOfRoomsProcedure> queryItems(Realm realm) {
return realm.where(GetUsersOfRoomsProcedure.class) return realm.where(GetUsersOfRoomsProcedure.class)
.equalTo("syncstate", SyncState.NOT_SYNCED) .equalTo(GetUsersOfRoomsProcedure.SYNC_STATE, SyncState.NOT_SYNCED)
.findAll(); .findAll();
} }
...@@ -47,8 +47,8 @@ public class GetUsersOfRoomsProcedureObserver ...@@ -47,8 +47,8 @@ public class GetUsersOfRoomsProcedureObserver
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(GetUsersOfRoomsProcedure.class, new JSONObject() realm.createOrUpdateObjectFromJson(GetUsersOfRoomsProcedure.class, new JSONObject()
.put("roomId", roomId) .put(GetUsersOfRoomsProcedure.ID, roomId)
.put("syncstate", SyncState.SYNCING)) .put(GetUsersOfRoomsProcedure.SYNC_STATE, SyncState.SYNCING))
).onSuccessTask(task -> ).onSuccessTask(task ->
methodCall.getUsersOfRoom(roomId, showAll) methodCall.getUsersOfRoom(roomId, showAll)
.onSuccessTask(_task -> { .onSuccessTask(_task -> {
...@@ -64,8 +64,8 @@ public class GetUsersOfRoomsProcedureObserver ...@@ -64,8 +64,8 @@ public class GetUsersOfRoomsProcedureObserver
RCLog.w(task.getError()); RCLog.w(task.getError());
return realmHelper.executeTransaction(realm -> return realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(GetUsersOfRoomsProcedure.class, new JSONObject() realm.createOrUpdateObjectFromJson(GetUsersOfRoomsProcedure.class, new JSONObject()
.put("roomId", roomId) .put(GetUsersOfRoomsProcedure.ID, roomId)
.put("syncstate", SyncState.FAILED))); .put(GetUsersOfRoomsProcedure.SYNC_STATE, SyncState.FAILED)));
} else { } else {
return Task.forResult(null); return Task.forResult(null);
} }
......
...@@ -32,7 +32,7 @@ public class LoadMessageProcedureObserver extends AbstractModelObserver<LoadMess ...@@ -32,7 +32,7 @@ public class LoadMessageProcedureObserver extends AbstractModelObserver<LoadMess
@Override @Override
public RealmResults<LoadMessageProcedure> queryItems(Realm realm) { public RealmResults<LoadMessageProcedure> queryItems(Realm realm) {
return realm.where(LoadMessageProcedure.class) return realm.where(LoadMessageProcedure.class)
.equalTo("syncstate", SyncState.NOT_SYNCED) .equalTo(LoadMessageProcedure.SYNC_STATE, SyncState.NOT_SYNCED)
.findAll(); .findAll();
} }
...@@ -51,33 +51,33 @@ public class LoadMessageProcedureObserver extends AbstractModelObserver<LoadMess ...@@ -51,33 +51,33 @@ public class LoadMessageProcedureObserver extends AbstractModelObserver<LoadMess
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(LoadMessageProcedure.class, new JSONObject() realm.createOrUpdateObjectFromJson(LoadMessageProcedure.class, new JSONObject()
.put("roomId", roomId) .put(LoadMessageProcedure.ID, roomId)
.put("syncstate", SyncState.SYNCING)) .put(LoadMessageProcedure.SYNC_STATE, SyncState.SYNCING))
).onSuccessTask(task -> ).onSuccessTask(task ->
methodCall.loadHistory(roomId, isReset ? 0 : timestamp, count, lastSeen) methodCall.loadHistory(roomId, isReset ? 0 : timestamp, count, lastSeen)
.onSuccessTask(_task -> { .onSuccessTask(_task -> {
Message lastMessage = realmHelper.executeTransactionForRead(realm -> Message lastMessage = realmHelper.executeTransactionForRead(realm ->
realm.where(Message.class) realm.where(Message.class)
.equalTo("rid", roomId) .equalTo(Message.ROOM_ID, roomId)
.equalTo("syncstate", SyncState.SYNCED) .equalTo(Message.SYNC_STATE, SyncState.SYNCED)
.findAllSorted("ts", Sort.ASCENDING).first(null)); .findAllSorted(Message.TIMESTAMP, Sort.ASCENDING).first(null));
long lastTs = lastMessage != null ? lastMessage.getTimestamp() : 0; long lastTs = lastMessage != null ? lastMessage.getTimestamp() : 0;
int messageCount = _task.getResult().length(); int messageCount = _task.getResult().length();
return realmHelper.executeTransaction(realm -> return realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(LoadMessageProcedure.class, new JSONObject() realm.createOrUpdateObjectFromJson(LoadMessageProcedure.class, new JSONObject()
.put("roomId", roomId) .put(LoadMessageProcedure.ID, roomId)
.put("syncstate", SyncState.SYNCED) .put(LoadMessageProcedure.SYNC_STATE, SyncState.SYNCED)
.put("timestamp", lastTs) .put(LoadMessageProcedure.TIMESTAMP, lastTs)
.put("reset", false) .put(LoadMessageProcedure.RESET, false)
.put("hasNext", messageCount == count))); .put(LoadMessageProcedure.HAS_NEXT, messageCount == count)));
}) })
).continueWithTask(task -> { ).continueWithTask(task -> {
if (task.isFaulted()) { if (task.isFaulted()) {
RCLog.w(task.getError()); RCLog.w(task.getError());
return realmHelper.executeTransaction(realm -> return realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(LoadMessageProcedure.class, new JSONObject() realm.createOrUpdateObjectFromJson(LoadMessageProcedure.class, new JSONObject()
.put("roomId", roomId) .put(LoadMessageProcedure.ID, roomId)
.put("syncstate", SyncState.FAILED))); .put(LoadMessageProcedure.SYNC_STATE, SyncState.FAILED)));
} else { } else {
return Task.forResult(null); return Task.forResult(null);
} }
......
...@@ -30,7 +30,7 @@ public class MethodCallObserver extends AbstractModelObserver<MethodCall> { ...@@ -30,7 +30,7 @@ public class MethodCallObserver extends AbstractModelObserver<MethodCall> {
realmHelper.executeTransaction(realm -> { realmHelper.executeTransaction(realm -> {
// resume pending operations. // resume pending operations.
RealmResults<MethodCall> pendingMethodCalls = realm.where(MethodCall.class) RealmResults<MethodCall> pendingMethodCalls = realm.where(MethodCall.class)
.equalTo("syncstate", SyncState.SYNCING) .equalTo(MethodCall.SYNC_STATE, SyncState.SYNCING)
.findAll(); .findAll();
for (MethodCall call : pendingMethodCalls) { for (MethodCall call : pendingMethodCalls) {
call.setSyncState(SyncState.NOT_SYNCED); call.setSyncState(SyncState.NOT_SYNCED);
...@@ -39,9 +39,9 @@ public class MethodCallObserver extends AbstractModelObserver<MethodCall> { ...@@ -39,9 +39,9 @@ public class MethodCallObserver extends AbstractModelObserver<MethodCall> {
// clean up records. // clean up records.
realm.where(MethodCall.class) realm.where(MethodCall.class)
.beginGroup() .beginGroup()
.equalTo("syncstate", SyncState.SYNCED) .equalTo(MethodCall.SYNC_STATE, SyncState.SYNCED)
.or() .or()
.equalTo("syncstate", SyncState.FAILED) .equalTo(MethodCall.SYNC_STATE, SyncState.FAILED)
.endGroup() .endGroup()
.findAll().deleteAllFromRealm(); .findAll().deleteAllFromRealm();
return null; return null;
...@@ -51,8 +51,8 @@ public class MethodCallObserver extends AbstractModelObserver<MethodCall> { ...@@ -51,8 +51,8 @@ public class MethodCallObserver extends AbstractModelObserver<MethodCall> {
@Override @Override
public RealmResults<MethodCall> queryItems(Realm realm) { public RealmResults<MethodCall> queryItems(Realm realm) {
return realm.where(MethodCall.class) return realm.where(MethodCall.class)
.isNotNull("name") .isNotNull(MethodCall.NAME)
.equalTo("syncstate", SyncState.NOT_SYNCED) .equalTo(MethodCall.SYNC_STATE, SyncState.NOT_SYNCED)
.findAll(); .findAll();
} }
...@@ -94,16 +94,16 @@ public class MethodCallObserver extends AbstractModelObserver<MethodCall> { ...@@ -94,16 +94,16 @@ public class MethodCallObserver extends AbstractModelObserver<MethodCall> {
final long timeout = call.getTimeout(); final long timeout = call.getTimeout();
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(MethodCall.class, new JSONObject() realm.createOrUpdateObjectFromJson(MethodCall.class, new JSONObject()
.put("methodCallId", methodCallId) .put(MethodCall.ID, methodCallId)
.put("syncstate", SyncState.SYNCING)) .put(MethodCall.SYNC_STATE, SyncState.SYNCING))
).onSuccessTask(task -> ).onSuccessTask(task ->
ddpClient.rpc(methodCallId, methodName, params, timeout) ddpClient.rpc(methodCallId, methodName, params, timeout)
.onSuccessTask(_task -> realmHelper.executeTransaction(realm -> { .onSuccessTask(_task -> realmHelper.executeTransaction(realm -> {
String json = _task.getResult().result; String json = _task.getResult().result;
return realm.createOrUpdateObjectFromJson(MethodCall.class, new JSONObject() return realm.createOrUpdateObjectFromJson(MethodCall.class, new JSONObject()
.put("methodCallId", methodCallId) .put(MethodCall.ID, methodCallId)
.put("syncstate", SyncState.SYNCED) .put(MethodCall.SYNC_STATE, SyncState.SYNCED)
.put("resultJson", json)); .put(MethodCall.RESULT_JSON, json));
})) }))
).continueWithTask(task -> { ).continueWithTask(task -> {
if (task.isFaulted()) { if (task.isFaulted()) {
...@@ -113,9 +113,9 @@ public class MethodCallObserver extends AbstractModelObserver<MethodCall> { ...@@ -113,9 +113,9 @@ public class MethodCallObserver extends AbstractModelObserver<MethodCall> {
? ((DDPClientCallback.RPC.Error) exception).error.toString() ? ((DDPClientCallback.RPC.Error) exception).error.toString()
: exception.getMessage(); : exception.getMessage();
realm.createOrUpdateObjectFromJson(MethodCall.class, new JSONObject() realm.createOrUpdateObjectFromJson(MethodCall.class, new JSONObject()
.put("methodCallId", methodCallId) .put(MethodCall.ID, methodCallId)
.put("syncstate", SyncState.FAILED) .put(MethodCall.SYNC_STATE, SyncState.FAILED)
.put("resultJson", errMessage)); .put(MethodCall.RESULT_JSON, errMessage));
return null; return null;
}); });
} }
......
...@@ -29,7 +29,7 @@ public class NewMessageObserver extends AbstractModelObserver<Message> { ...@@ -29,7 +29,7 @@ public class NewMessageObserver extends AbstractModelObserver<Message> {
realmHelper.executeTransaction(realm -> { realmHelper.executeTransaction(realm -> {
// resume pending operations. // resume pending operations.
RealmResults<Message> pendingMethodCalls = realm.where(Message.class) RealmResults<Message> pendingMethodCalls = realm.where(Message.class)
.equalTo("syncstate", SyncState.SYNCING) .equalTo(Message.SYNC_STATE, SyncState.SYNCING)
.findAll(); .findAll();
for (Message message : pendingMethodCalls) { for (Message message : pendingMethodCalls) {
message.setSyncState(SyncState.NOT_SYNCED); message.setSyncState(SyncState.NOT_SYNCED);
...@@ -42,8 +42,8 @@ public class NewMessageObserver extends AbstractModelObserver<Message> { ...@@ -42,8 +42,8 @@ public class NewMessageObserver extends AbstractModelObserver<Message> {
@Override @Override
public RealmResults<Message> queryItems(Realm realm) { public RealmResults<Message> queryItems(Realm realm) {
return realm.where(Message.class) return realm.where(Message.class)
.equalTo("syncstate", SyncState.NOT_SYNCED) .equalTo(Message.SYNC_STATE, SyncState.NOT_SYNCED)
.isNotNull("rid") .isNotNull(Message.ROOM_ID)
.findAll(); .findAll();
} }
...@@ -60,8 +60,8 @@ public class NewMessageObserver extends AbstractModelObserver<Message> { ...@@ -60,8 +60,8 @@ public class NewMessageObserver extends AbstractModelObserver<Message> {
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(Message.class, new JSONObject() realm.createOrUpdateObjectFromJson(Message.class, new JSONObject()
.put("_id", messageId) .put(Message.ID, messageId)
.put("syncstate", SyncState.SYNCING) .put(Message.SYNC_STATE, SyncState.SYNCING)
) )
).onSuccessTask(task -> ).onSuccessTask(task ->
methodCall.sendMessage(messageId, roomId, msg).onSuccessTask(_task -> { methodCall.sendMessage(messageId, roomId, msg).onSuccessTask(_task -> {
...@@ -75,8 +75,8 @@ public class NewMessageObserver extends AbstractModelObserver<Message> { ...@@ -75,8 +75,8 @@ public class NewMessageObserver extends AbstractModelObserver<Message> {
RCLog.w(task.getError()); RCLog.w(task.getError());
realmHelper.executeTransaction(realm -> realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(Message.class, new JSONObject() realm.createOrUpdateObjectFromJson(Message.class, new JSONObject()
.put("_id", messageId) .put(Message.ID, messageId)
.put("syncstate", SyncState.FAILED))); .put(Message.SYNC_STATE, SyncState.FAILED)));
} }
return null; return null;
}); });
......
...@@ -91,7 +91,7 @@ public class NotificationItemObserver extends AbstractModelObserver<Notification ...@@ -91,7 +91,7 @@ public class NotificationItemObserver extends AbstractModelObserver<Notification
Intent intent = new Intent(context, MainActivity.class); Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_CLEAR_TOP);
ServerConfig config = RealmStore.getDefault().executeTransactionForRead(realm -> ServerConfig config = RealmStore.getDefault().executeTransactionForRead(realm ->
realm.where(ServerConfig.class).equalTo("hostname", hostname).findFirst()); realm.where(ServerConfig.class).equalTo(ServerConfig.HOSTNAME, hostname).findFirst());
if (config != null) { if (config != null) {
intent.putExtra("serverConfigId", config.getServerConfigId()); intent.putExtra("serverConfigId", config.getServerConfigId());
intent.putExtra("roomId", roomId); intent.putExtra("roomId", roomId);
...@@ -105,7 +105,7 @@ public class NotificationItemObserver extends AbstractModelObserver<Notification ...@@ -105,7 +105,7 @@ public class NotificationItemObserver extends AbstractModelObserver<Notification
private PendingIntent getDeleteIntent(String roomId) { private PendingIntent getDeleteIntent(String roomId) {
Intent intent = new Intent(context, NotificationDismissalCallbackService.class); Intent intent = new Intent(context, NotificationDismissalCallbackService.class);
ServerConfig config = RealmStore.getDefault().executeTransactionForRead(realm -> ServerConfig config = RealmStore.getDefault().executeTransactionForRead(realm ->
realm.where(ServerConfig.class).equalTo("hostname", hostname).findFirst()); realm.where(ServerConfig.class).equalTo(ServerConfig.HOSTNAME, hostname).findFirst());
if (config != null) { if (config != null) {
intent.putExtra("serverConfigId", config.getServerConfigId()); intent.putExtra("serverConfigId", config.getServerConfigId());
intent.putExtra("roomId", roomId); intent.putExtra("roomId", roomId);
......
...@@ -27,7 +27,7 @@ public class ReactiveNotificationManager extends AbstractModelObserver<RoomSubsc ...@@ -27,7 +27,7 @@ public class ReactiveNotificationManager extends AbstractModelObserver<RoomSubsc
@Override @Override
public RealmResults<RoomSubscription> queryItems(Realm realm) { public RealmResults<RoomSubscription> queryItems(Realm realm) {
return realm.where(RoomSubscription.class) return realm.where(RoomSubscription.class)
.equalTo("open", true) .equalTo(RoomSubscription.OPEN, true)
.findAll(); .findAll();
} }
...@@ -37,9 +37,10 @@ public class ReactiveNotificationManager extends AbstractModelObserver<RoomSubsc ...@@ -37,9 +37,10 @@ public class ReactiveNotificationManager extends AbstractModelObserver<RoomSubsc
for (RoomSubscription roomSubscription : roomSubscriptions) { for (RoomSubscription roomSubscription : roomSubscriptions) {
final String roomId = roomSubscription.getRoomId(); final String roomId = roomSubscription.getRoomId();
NotificationItem item = realmHelper.executeTransactionForRead(realm -> NotificationItem item = realmHelper.executeTransactionForRead(realm ->
realm.where(NotificationItem.class).equalTo("roomId", roomId).findFirst()); realm.where(NotificationItem.class).equalTo(NotificationItem.ID, roomId).findFirst());
long lastSeenAt = Math.max(item != null ? item.getLastSeenAt() : 0, roomSubscription.getLastSeen()); long lastSeenAt = Math
.max(item != null ? item.getLastSeenAt() : 0, roomSubscription.getLastSeen());
try { try {
JSONObject notification = new JSONObject() JSONObject notification = new JSONObject()
.put("roomId", roomSubscription.getRoomId()) .put("roomId", roomSubscription.getRoomId())
......
...@@ -38,9 +38,9 @@ public class SessionObserver extends AbstractModelObserver<Session> { ...@@ -38,9 +38,9 @@ public class SessionObserver extends AbstractModelObserver<Session> {
@Override @Override
public RealmResults<Session> queryItems(Realm realm) { public RealmResults<Session> queryItems(Realm realm) {
return realm.where(Session.class) return realm.where(Session.class)
.isNotNull("token") .isNotNull(Session.TOKEN)
.equalTo("tokenVerified", true) .equalTo(Session.TOKEN_VERIFIED, true)
.isNull("error") .isNull(Session.ERROR)
.findAll(); .findAll();
} }
......
...@@ -24,9 +24,9 @@ public class TokenLoginObserver extends AbstractModelObserver<Session> { ...@@ -24,9 +24,9 @@ public class TokenLoginObserver extends AbstractModelObserver<Session> {
@Override @Override
public RealmResults<Session> queryItems(Realm realm) { public RealmResults<Session> queryItems(Realm realm) {
return realm.where(Session.class) return realm.where(Session.class)
.isNotNull("token") .isNotNull(Session.TOKEN)
.equalTo("tokenVerified", false) .equalTo(Session.TOKEN_VERIFIED, false)
.isNull("error") .isNull(Session.ERROR)
.findAll(); .findAll();
} }
......
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