Commit 6a851e31 authored by Yusuke Iwaki's avatar Yusuke Iwaki

move syncPushToken from ServerConfig to GcmPushRegistration model.

parent cc02f115
...@@ -66,9 +66,6 @@ ...@@ -66,9 +66,6 @@
<action android:name="com.google.android.gms.iid.InstanceID" /> <action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter> </intent-filter>
</service> </service>
<service
android:name=".push.gcm.GcmRegistrationIntentService"
android:exported="false" />
</application> </application>
</manifest> </manifest>
package chat.rocket.android.helper;
import io.realm.Realm;
import io.realm.RealmResults;
import java.util.List;
import chat.rocket.android.model.ddp.PublicSetting;
import chat.rocket.android.model.ddp.PublicSettingsConstants;
/**
* utility class for getting value comprehensibly from public settings list.
*/
public class GcmPushSettingHelper {
public static RealmResults<PublicSetting> queryForGcmPushEnabled(Realm realm) {
return realm.where(PublicSetting.class)
.equalTo(PublicSetting.ID, PublicSettingsConstants.Push.ENABLE)
.or()
.equalTo(PublicSetting.ID, PublicSettingsConstants.Push.GCM_PROJECT_NUMBER)
.findAll();
}
public static boolean isGcmPushEnabled(List<PublicSetting> results) {
return isPushEnabled(results) && hasValidGcmConfig(results);
}
private static boolean isPushEnabled(List<PublicSetting> results) {
for (PublicSetting setting : results) {
if (PublicSettingsConstants.Push.ENABLE.equals(setting.getId())) {
return "true".equals(setting.getValue());
}
}
return false;
}
private static boolean hasValidGcmConfig(List<PublicSetting> results) {
for (PublicSetting setting : results) {
if (PublicSettingsConstants.Push.GCM_PROJECT_NUMBER.equals(setting.getId())) {
return !TextUtils.isEmpty(setting.getValue());
}
}
return false;
}
}
...@@ -20,7 +20,6 @@ public class ServerConfig extends RealmObject { ...@@ -20,7 +20,6 @@ public class ServerConfig extends RealmObject {
public static final String STATE = "state"; public static final String STATE = "state";
public static final String SESSION = "session"; public static final String SESSION = "session";
public static final String ERROR = "error"; 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;
...@@ -32,7 +31,6 @@ public class ServerConfig extends RealmObject { ...@@ -32,7 +31,6 @@ 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.
...@@ -102,12 +100,4 @@ public class ServerConfig extends RealmObject { ...@@ -102,12 +100,4 @@ 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;
}
} }
package chat.rocket.android.model.internal;
import io.realm.Realm;
import io.realm.RealmObject;
import io.realm.RealmQuery;
import io.realm.annotations.PrimaryKey;
import org.json.JSONException;
import org.json.JSONObject;
import chat.rocket.android.model.SyncState;
/**
* just stores gcm registration status.
*/
public class GcmPushRegistration extends RealmObject {
private static final String ID = "dummyId";
public static final String SYNC_STATE = "syncState";
public static final String GCM_PUSH_ENABLED = "gcmPushEnabled";
private static final int DEFAULT_ID = 0;
@PrimaryKey private int dummyId;
private int syncState;
private boolean gcmPushEnabled;
public boolean isGcmPushEnabled() {
return gcmPushEnabled;
}
public void setGcmPushEnabled(boolean gcmPushEnabled) {
this.gcmPushEnabled = gcmPushEnabled;
}
public int getSyncState() {
return syncState;
}
public void setSyncState(int syncState) {
this.syncState = syncState;
}
public static GcmPushRegistration updateGcmPushEnabled(Realm realm, boolean gcmPushEnabled)
throws JSONException {
return realm.createOrUpdateObjectFromJson(GcmPushRegistration.class, new JSONObject()
.put(ID, DEFAULT_ID)
.put(SYNC_STATE, SyncState.NOT_SYNCED)
.put(GCM_PUSH_ENABLED, gcmPushEnabled));
}
public static RealmQuery<GcmPushRegistration> queryDefault(Realm realm) {
return realm.where(GcmPushRegistration.class).equalTo(ID, DEFAULT_ID);
}
}
...@@ -2,13 +2,11 @@ package chat.rocket.android.push.gcm; ...@@ -2,13 +2,11 @@ package chat.rocket.android.push.gcm;
import com.google.android.gms.iid.InstanceIDListenerService; import com.google.android.gms.iid.InstanceIDListenerService;
import android.content.Intent;
import java.util.List; import java.util.List;
import chat.rocket.android.helper.TextUtils; import chat.rocket.android.helper.GcmPushSettingHelper;
import chat.rocket.android.model.ServerConfig; import chat.rocket.android.model.ServerConfig;
import chat.rocket.android.model.ddp.PublicSetting; import chat.rocket.android.model.ddp.PublicSetting;
import chat.rocket.android.model.ddp.PublicSettingsConstants; import chat.rocket.android.model.internal.GcmPushRegistration;
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;
...@@ -16,43 +14,31 @@ public class GcmInstanceIDListenerService extends InstanceIDListenerService { ...@@ -16,43 +14,31 @@ public class GcmInstanceIDListenerService extends InstanceIDListenerService {
@Override @Override
public void onTokenRefresh() { public void onTokenRefresh() {
syncGcmPushAvailability(); List<ServerConfig> serverConfigs = RealmStore.getDefault()
.executeTransactionForReadResults(realm ->
if (!shouldRefreshToken()) { realm.where(ServerConfig.class)
return; .isNotNull(ServerConfig.ID)
.isNotNull(ServerConfig.HOSTNAME)
.findAll());
for (ServerConfig serverConfig : serverConfigs) {
RealmHelper realmHelper = RealmStore.get(serverConfig.getServerConfigId());
if (realmHelper != null) {
updateGcmToken(realmHelper);
}
} }
Intent intent = new Intent(this, GcmRegistrationIntentService.class);
startService(intent);
} }
private void syncGcmPushAvailability() { private void updateGcmToken(RealmHelper realmHelper) {
final RealmHelper realmHelper = RealmStore.getDefault(); final List<PublicSetting> results = realmHelper.executeTransactionForReadResults(
List<ServerConfig> serverConfigs = realmHelper.executeTransactionForReadResults( GcmPushSettingHelper::queryForGcmPushEnabled);
realm -> realm.where(ServerConfig.class).findAll()); final boolean gcmPushEnabled = GcmPushSettingHelper.isGcmPushEnabled(results);
for (final ServerConfig serverConfig : serverConfigs) {
final RealmHelper serverRealmHelper = RealmStore.get(serverConfig.getServerConfigId());
if (serverRealmHelper == null) {
continue;
}
boolean isPushEnabled = PublicSetting
.getBoolean(serverRealmHelper, PublicSettingsConstants.Push.ENABLE, false);
String senderId = PublicSetting
.getString(serverRealmHelper, PublicSettingsConstants.Push.GCM_PROJECT_NUMBER, "").trim();
boolean gcmPushAvailable = isPushEnabled && !TextUtils.isEmpty(senderId); GcmPushRegistration gcmPushRegistration = realmHelper.executeTransactionForRead(realm ->
GcmPushRegistration.queryDefault(realm).findFirst());
if (serverConfig.shouldSyncPushToken() != gcmPushAvailable) { if (gcmPushRegistration == null || gcmPushEnabled != gcmPushRegistration.isGcmPushEnabled()) {
serverConfig.setSyncPushToken(gcmPushAvailable); realmHelper.executeTransaction(realm ->
realmHelper.executeTransaction(realm -> realm.copyToRealmOrUpdate(serverConfig)); GcmPushRegistration.updateGcmPushEnabled(realm, gcmPushEnabled));
}
} }
} }
private boolean shouldRefreshToken() {
return RealmStore.getDefault().isObjectExists(realm ->
realm.where(ServerConfig.class).equalTo(ServerConfig.SYNC_PUSH_TOKEN, true));
}
} }
\ No newline at end of file
package chat.rocket.android.push.gcm;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import android.app.IntentService;
import android.content.Intent;
import java.io.IOException;
import java.util.List;
import chat.rocket.android.RocketChatCache;
import chat.rocket.android.api.RaixPushHelper;
import chat.rocket.android.model.ServerConfig;
import chat.rocket.android.model.ddp.PublicSetting;
import chat.rocket.android.model.ddp.PublicSettingsConstants;
import chat.rocket.android.model.ddp.User;
import chat.rocket.android.realm_helper.RealmHelper;
import chat.rocket.android.realm_helper.RealmStore;
public class GcmRegistrationIntentService extends IntentService {
public GcmRegistrationIntentService() {
super("GcmRegistrationIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
final List<ServerConfig> serverConfigs = RealmStore.getDefault()
.executeTransactionForReadResults(realm ->
realm.where(ServerConfig.class).equalTo(ServerConfig.SYNC_PUSH_TOKEN, true).findAll());
for (ServerConfig serverConfig : serverConfigs) {
registerGcmTokenForServer(serverConfig);
}
}
private void registerGcmTokenForServer(final ServerConfig serverConfig) {
final RealmHelper realmHelper = RealmStore.get(serverConfig.getServerConfigId());
if (realmHelper == null) {
return;
}
final String senderId = PublicSetting
.getString(realmHelper, PublicSettingsConstants.Push.GCM_PROJECT_NUMBER, "").trim();
if ("".equals(senderId)) {
markRefreshAsDone(serverConfig);
return;
}
try {
final String gcmToken = getGcmToken(senderId);
final User currentUser = realmHelper.executeTransactionForRead(realm ->
User.queryCurrentUser(realm).findFirst());
final String pushId = RocketChatCache.getOrCreatePushId(this);
final String userId = currentUser != null ? currentUser.getId() : null;
new RaixPushHelper(getBaseContext(), serverConfig.getServerConfigId())
.pushUpdate(pushId, gcmToken, userId)
.onSuccess(task -> {
markRefreshAsDone(serverConfig);
return task;
});
} catch (Exception e) {
}
}
private String getGcmToken(String senderId) throws IOException {
return InstanceID.getInstance(this)
.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
}
private void markRefreshAsDone(ServerConfig serverConfig) {
serverConfig.setSyncPushToken(false);
RealmStore.getDefault().executeTransaction(realm -> realm.copyToRealm(serverConfig));
}
}
\ No newline at end of file
...@@ -26,6 +26,7 @@ import chat.rocket.android.service.ddp.base.UserDataSubscriber; ...@@ -26,6 +26,7 @@ import chat.rocket.android.service.ddp.base.UserDataSubscriber;
import chat.rocket.android.service.observer.CurrentUserObserver; import chat.rocket.android.service.observer.CurrentUserObserver;
import chat.rocket.android.service.observer.FileUploadingToS3Observer; import chat.rocket.android.service.observer.FileUploadingToS3Observer;
import chat.rocket.android.service.observer.FileUploadingWithUfsObserver; import chat.rocket.android.service.observer.FileUploadingWithUfsObserver;
import chat.rocket.android.service.observer.GcmPushRegistrationObserver;
import chat.rocket.android.service.observer.GetUsersOfRoomsProcedureObserver; import chat.rocket.android.service.observer.GetUsersOfRoomsProcedureObserver;
import chat.rocket.android.service.observer.LoadMessageProcedureObserver; import chat.rocket.android.service.observer.LoadMessageProcedureObserver;
import chat.rocket.android.service.observer.MethodCallObserver; import chat.rocket.android.service.observer.MethodCallObserver;
...@@ -55,7 +56,8 @@ public class RocketChatWebSocketThread extends HandlerThread { ...@@ -55,7 +56,8 @@ public class RocketChatWebSocketThread extends HandlerThread {
ReactiveNotificationManager.class, ReactiveNotificationManager.class,
FileUploadingToS3Observer.class, FileUploadingToS3Observer.class,
FileUploadingWithUfsObserver.class, FileUploadingWithUfsObserver.class,
PushSettingsObserver.class PushSettingsObserver.class,
GcmPushRegistrationObserver.class
}; };
private final Context appContext; private final Context appContext;
private final String serverConfigId; private final String serverConfigId;
......
package chat.rocket.android.service.observer;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import android.content.Context;
import io.realm.Realm;
import io.realm.RealmResults;
import java.io.IOException;
import java.util.List;
import bolts.Task;
import chat.rocket.android.RocketChatCache;
import chat.rocket.android.api.DDPClientWrapper;
import chat.rocket.android.api.RaixPushHelper;
import chat.rocket.android.helper.LogcatIfError;
import chat.rocket.android.model.SyncState;
import chat.rocket.android.model.ddp.PublicSetting;
import chat.rocket.android.model.ddp.PublicSettingsConstants;
import chat.rocket.android.model.ddp.User;
import chat.rocket.android.model.internal.GcmPushRegistration;
import chat.rocket.android.realm_helper.RealmHelper;
/**
* call raix:push-update if needed.
*/
public class GcmPushRegistrationObserver extends AbstractModelObserver<GcmPushRegistration> {
public GcmPushRegistrationObserver(Context context, String hostname,
RealmHelper realmHelper,
DDPClientWrapper ddpClient) {
super(context, hostname, realmHelper, ddpClient);
}
@Override
public RealmResults<GcmPushRegistration> queryItems(Realm realm) {
return GcmPushRegistration.queryDefault(realm)
.equalTo(GcmPushRegistration.SYNC_STATE, SyncState.NOT_SYNCED)
.equalTo(GcmPushRegistration.GCM_PUSH_ENABLED, true)
.findAll();
}
@Override
public void onUpdateResults(List<GcmPushRegistration> results) {
if (results.isEmpty()) {
return;
}
realmHelper.executeTransaction(realm -> {
GcmPushRegistration.queryDefault(realm).findFirst().setSyncState(SyncState.SYNCING);
return null;
}).onSuccessTask(_task -> registerGcmTokenForServer()
).onSuccessTask(_task ->
realmHelper.executeTransaction(realm -> {
GcmPushRegistration.queryDefault(realm).findFirst().setSyncState(SyncState.SYNCED);
return null;
})
).continueWith(task -> {
if (task.isFaulted()) {
realmHelper.executeTransaction(realm -> {
GcmPushRegistration.queryDefault(realm).findFirst().setSyncState(SyncState.FAILED);
return null;
}).continueWith(new LogcatIfError());
}
return null;
});
}
private Task<Void> registerGcmTokenForServer() throws IOException {
final String senderId = PublicSetting
.getString(realmHelper, PublicSettingsConstants.Push.GCM_PROJECT_NUMBER, "").trim();
final String gcmToken = getGcmToken(senderId);
final User currentUser = realmHelper.executeTransactionForRead(realm ->
User.queryCurrentUser(realm).findFirst());
final String userId = currentUser != null ? currentUser.getId() : null;
final String pushId = RocketChatCache.getOrCreatePushId(context);
return new RaixPushHelper(realmHelper, ddpClient)
.pushUpdate(pushId, gcmToken, userId);
}
private String getGcmToken(String senderId) throws IOException {
return InstanceID.getInstance(context)
.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
}
}
package chat.rocket.android.service.observer; package chat.rocket.android.service.observer;
import android.content.Context; import android.content.Context;
import android.content.Intent;
import io.realm.Realm; import io.realm.Realm;
import io.realm.RealmResults; import io.realm.RealmResults;
import java.util.List; import java.util.List;
import chat.rocket.android.api.DDPClientWrapper; import chat.rocket.android.api.DDPClientWrapper;
import chat.rocket.android.helper.LogcatIfError; import chat.rocket.android.helper.GcmPushSettingHelper;
import chat.rocket.android.helper.ServerPolicyHelper;
import chat.rocket.android.helper.TextUtils;
import chat.rocket.android.model.ServerConfig;
import chat.rocket.android.model.ddp.PublicSetting; import chat.rocket.android.model.ddp.PublicSetting;
import chat.rocket.android.model.ddp.PublicSettingsConstants; import chat.rocket.android.model.internal.GcmPushRegistration;
import chat.rocket.android.push.gcm.GcmRegistrationIntentService;
import chat.rocket.android.realm_helper.RealmHelper; import chat.rocket.android.realm_helper.RealmHelper;
import chat.rocket.android.realm_helper.RealmStore;
public class PushSettingsObserver extends AbstractModelObserver<PublicSetting> { public class PushSettingsObserver extends AbstractModelObserver<PublicSetting> {
...@@ -24,60 +18,21 @@ public class PushSettingsObserver extends AbstractModelObserver<PublicSetting> { ...@@ -24,60 +18,21 @@ public class PushSettingsObserver extends AbstractModelObserver<PublicSetting> {
super(context, hostname, realmHelper, ddpClient); super(context, hostname, realmHelper, ddpClient);
} }
@Override
public void onUpdateResults(List<PublicSetting> results) {
final ServerConfig serverConfig = RealmStore.getDefault().executeTransactionForRead(realm ->
realm.where(ServerConfig.class)
.equalTo(ServerConfig.HOSTNAME, ServerPolicyHelper.enforceHostname(hostname))
.findFirst());
boolean gcmPushAvailable = isGcmPushEnabled(results);
if (serverConfig.shouldSyncPushToken() != gcmPushAvailable) {
serverConfig.setSyncPushToken(gcmPushAvailable);
RealmStore.getDefault()
.executeTransaction(realm -> realm.copyToRealmOrUpdate(serverConfig))
.continueWith(task -> {
if (serverConfig.shouldSyncPushToken()) {
Intent intent = new Intent(
context.getApplicationContext(), GcmRegistrationIntentService.class);
context.getApplicationContext().startService(intent);
}
return task;
})
.continueWith(new LogcatIfError());
}
}
@Override @Override
public RealmResults<PublicSetting> queryItems(Realm realm) { public RealmResults<PublicSetting> queryItems(Realm realm) {
return realm.where(PublicSetting.class) return GcmPushSettingHelper.queryForGcmPushEnabled(realm);
.equalTo(PublicSetting.ID, PublicSettingsConstants.Push.ENABLE)
.or()
.equalTo(PublicSetting.ID, PublicSettingsConstants.Push.GCM_PROJECT_NUMBER)
.findAll();
} }
private boolean isGcmPushEnabled(List<PublicSetting> results) { @Override
return isPushEnabled(results) && hasValidGcmConfig(results); public void onUpdateResults(List<PublicSetting> results) {
} boolean gcmPushEnabled = GcmPushSettingHelper.isGcmPushEnabled(results);
private boolean isPushEnabled(List<PublicSetting> results) { GcmPushRegistration gcmPushRegistration = realmHelper.executeTransactionForRead(realm ->
for (PublicSetting setting : results) { GcmPushRegistration.queryDefault(realm).findFirst());
if (PublicSettingsConstants.Push.ENABLE.equals(setting.getId())) {
return "true".equals(setting.getValue());
}
}
return false;
}
private boolean hasValidGcmConfig(List<PublicSetting> results) { if (gcmPushRegistration == null || gcmPushEnabled != gcmPushRegistration.isGcmPushEnabled()) {
for (PublicSetting setting : results) { realmHelper.executeTransaction(realm ->
if (PublicSettingsConstants.Push.GCM_PROJECT_NUMBER.equals(setting.getId())) { GcmPushRegistration.updateGcmPushEnabled(realm, gcmPushEnabled));
return !TextUtils.isEmpty(setting.getValue());
}
} }
return false;
} }
} }
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