This source file includes following definitions.
- onHandleIntent
- invalidate
- invalidateUnknownVersion
- invalidateAll
- informRegistrationFailure
- informRegistrationStatus
- informError
- ready
- reissueRegistrations
- requestAuthToken
- writeState
- readState
- ensureClientStartState
- ensureAccount
- startClient
- stopClient
- setAccount
- readSyncRegistrationsFromPrefs
- readNonSyncRegistrationsFromPrefs
- readRegistrationsFromPrefs
- joinRegistrations
- setRegisteredTypes
- computeRegistrationOps
- requestSync
- requestSyncFromContentResolver
- shouldClientBeRunning
- isSyncEnabled
- isChromeInForeground
- getIsClientStartedForTest
- getClientIdForTest
- getOAuth2ScopeWithType
- setClientId
- setIsClientStarted
package org.chromium.sync.notifier;
import android.accounts.Account;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.google.common.annotations.VisibleForTesting;
import com.google.ipc.invalidation.external.client.InvalidationListener.RegistrationState;
import com.google.ipc.invalidation.external.client.contrib.AndroidListener;
import com.google.ipc.invalidation.external.client.types.ErrorInfo;
import com.google.ipc.invalidation.external.client.types.Invalidation;
import com.google.ipc.invalidation.external.client.types.ObjectId;
import com.google.protos.ipc.invalidation.Types.ClientType;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.CollectionUtil;
import org.chromium.sync.internal_api.pub.base.ModelType;
import org.chromium.sync.notifier.InvalidationPreferences.EditContext;
import org.chromium.sync.signin.AccountManagerHelper;
import org.chromium.sync.signin.ChromeSigninController;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.annotation.Nullable;
public class InvalidationService extends AndroidListener {
@VisibleForTesting
static final int CLIENT_TYPE = ClientType.Type.CHROME_SYNC_ANDROID_VALUE;
private static final String TAG = "InvalidationService";
private static final Random RANDOM = new Random();
private static boolean sIsClientStarted;
@Nullable private static byte[] sClientId;
@Override
public void onHandleIntent(Intent intent) {
Account account = intent.hasExtra(InvalidationIntentProtocol.EXTRA_ACCOUNT) ?
(Account) intent.getParcelableExtra(InvalidationIntentProtocol.EXTRA_ACCOUNT)
: null;
ensureAccount(account);
ensureClientStartState();
if (InvalidationIntentProtocol.isStop(intent) && sIsClientStarted) {
stopClient();
} else if (InvalidationIntentProtocol.isRegisteredTypesChange(intent)) {
List<String> regTypes = intent.getStringArrayListExtra(
InvalidationIntentProtocol.EXTRA_REGISTERED_TYPES);
setRegisteredTypes(regTypes != null ? new HashSet<String>(regTypes) : null,
InvalidationIntentProtocol.getRegisteredObjectIds(intent));
} else {
super.onHandleIntent(intent);
}
}
@Override
public void invalidate(Invalidation invalidation, byte[] ackHandle) {
byte[] payload = invalidation.getPayload();
String payloadStr = (payload == null) ? null : new String(payload);
requestSync(invalidation.getObjectId(), invalidation.getVersion(), payloadStr);
acknowledge(ackHandle);
}
@Override
public void invalidateUnknownVersion(ObjectId objectId, byte[] ackHandle) {
requestSync(objectId, null, null);
acknowledge(ackHandle);
}
@Override
public void invalidateAll(byte[] ackHandle) {
requestSync(null, null, null);
acknowledge(ackHandle);
}
@Override
public void informRegistrationFailure(
byte[] clientId, ObjectId objectId, boolean isTransient, String errorMessage) {
Log.w(TAG, "Registration failure on " + objectId + " ; transient = " + isTransient
+ ": " + errorMessage);
if (isTransient) {
List<ObjectId> objectIdAsList = CollectionUtil.newArrayList(objectId);
if (readRegistrationsFromPrefs().contains(objectId)) {
register(clientId, objectIdAsList);
} else {
unregister(clientId, objectIdAsList);
}
}
}
@Override
public void informRegistrationStatus(
byte[] clientId, ObjectId objectId, RegistrationState regState) {
Log.d(TAG, "Registration status for " + objectId + ": " + regState);
List<ObjectId> objectIdAsList = CollectionUtil.newArrayList(objectId);
boolean registrationisDesired = readRegistrationsFromPrefs().contains(objectId);
if (regState == RegistrationState.REGISTERED) {
if (!registrationisDesired) {
Log.i(TAG, "Unregistering for object we're no longer interested in");
unregister(clientId, objectIdAsList);
}
} else {
if (registrationisDesired) {
Log.i(TAG, "Registering for an object");
register(clientId, objectIdAsList);
}
}
}
@Override
public void informError(ErrorInfo errorInfo) {
Log.w(TAG, "Invalidation client error:" + errorInfo);
if (!errorInfo.isTransient() && sIsClientStarted) {
stopClient();
}
}
@Override
public void ready(byte[] clientId) {
setClientId(clientId);
reissueRegistrations(clientId);
}
@Override
public void reissueRegistrations(byte[] clientId) {
Set<ObjectId> desiredRegistrations = readRegistrationsFromPrefs();
if (!desiredRegistrations.isEmpty()) {
register(clientId, desiredRegistrations);
}
}
@Override
public void requestAuthToken(final PendingIntent pendingIntent,
@Nullable String invalidAuthToken) {
@Nullable Account account = ChromeSigninController.get(this).getSignedInUser();
if (account == null) {
Log.w(TAG, "No signed-in user; cannot send message to data center");
return;
}
AccountManagerHelper.get(this).getNewAuthTokenFromForeground(
account, invalidAuthToken, getOAuth2ScopeWithType(),
new AccountManagerHelper.GetAuthTokenCallback() {
@Override
public void tokenAvailable(String token) {
if (token != null) {
setAuthToken(InvalidationService.this.getApplicationContext(),
pendingIntent, token, getOAuth2ScopeWithType());
}
}
});
}
@Override
public void writeState(byte[] data) {
InvalidationPreferences invPreferences = new InvalidationPreferences(this);
EditContext editContext = invPreferences.edit();
invPreferences.setInternalNotificationClientState(editContext, data);
invPreferences.commit(editContext);
}
@Override
@Nullable public byte[] readState() {
return new InvalidationPreferences(this).getInternalNotificationClientState();
}
private void ensureClientStartState() {
final boolean shouldClientBeRunning = shouldClientBeRunning();
if (!shouldClientBeRunning && sIsClientStarted) {
stopClient();
} else if (shouldClientBeRunning && !sIsClientStarted) {
startClient();
}
}
private void ensureAccount(@Nullable Account intendedAccount) {
if (intendedAccount == null) {
return;
}
InvalidationPreferences invPrefs = new InvalidationPreferences(this);
if (!intendedAccount.equals(invPrefs.getSavedSyncedAccount())) {
if (sIsClientStarted) {
stopClient();
}
setAccount(intendedAccount);
}
}
private void startClient() {
byte[] clientName = InvalidationClientNameProvider.get().getInvalidatorClientName();
Intent startIntent = AndroidListener.createStartIntent(this, CLIENT_TYPE, clientName);
startService(startIntent);
setIsClientStarted(true);
}
private void stopClient() {
startService(AndroidListener.createStopIntent(this));
setIsClientStarted(false);
setClientId(null);
}
private void setAccount(Account owningAccount) {
InvalidationPreferences invPrefs = new InvalidationPreferences(this);
EditContext editContext = invPrefs.edit();
invPrefs.setAccount(editContext, owningAccount);
invPrefs.commit(editContext);
}
private Set<ObjectId> readSyncRegistrationsFromPrefs() {
Set<String> savedTypes = new InvalidationPreferences(this).getSavedSyncedTypes();
if (savedTypes == null) return Collections.emptySet();
else return ModelType.syncTypesToObjectIds(savedTypes);
}
private Set<ObjectId> readNonSyncRegistrationsFromPrefs() {
Set<ObjectId> objectIds = new InvalidationPreferences(this).getSavedObjectIds();
if (objectIds == null) return Collections.emptySet();
else return objectIds;
}
@VisibleForTesting
Set<ObjectId> readRegistrationsFromPrefs() {
return joinRegistrations(readSyncRegistrationsFromPrefs(),
readNonSyncRegistrationsFromPrefs());
}
private static Set<ObjectId> joinRegistrations(Set<ObjectId> syncRegistrations,
Set<ObjectId> nonSyncRegistrations) {
if (nonSyncRegistrations.isEmpty()) {
return syncRegistrations;
}
if (syncRegistrations.isEmpty()) {
return nonSyncRegistrations;
}
Set<ObjectId> registrations = new HashSet<ObjectId>(
syncRegistrations.size() + nonSyncRegistrations.size());
registrations.addAll(syncRegistrations);
registrations.addAll(nonSyncRegistrations);
return registrations;
}
private void setRegisteredTypes(Set<String> syncTypes, Set<ObjectId> objectIds) {
Set<ObjectId> existingSyncRegistrations = (sClientId == null) ?
null : readSyncRegistrationsFromPrefs();
Set<ObjectId> existingNonSyncRegistrations = (sClientId == null) ?
null : readNonSyncRegistrationsFromPrefs();
InvalidationPreferences prefs = new InvalidationPreferences(this);
EditContext editContext = prefs.edit();
if (syncTypes != null) {
prefs.setSyncTypes(editContext, syncTypes);
}
if (objectIds != null) {
prefs.setObjectIds(editContext, objectIds);
}
prefs.commit(editContext);
if (sClientId == null) {
return;
}
Set<ObjectId> desiredSyncRegistrations = syncTypes != null ?
ModelType.syncTypesToObjectIds(syncTypes) : existingSyncRegistrations;
Set<ObjectId> desiredNonSyncRegistrations = objectIds != null ?
objectIds : existingNonSyncRegistrations;
Set<ObjectId> desiredRegistrations = joinRegistrations(desiredNonSyncRegistrations,
desiredSyncRegistrations);
Set<ObjectId> existingRegistrations = joinRegistrations(existingNonSyncRegistrations,
existingSyncRegistrations);
Set<ObjectId> unregistrations = new HashSet<ObjectId>();
Set<ObjectId> registrations = new HashSet<ObjectId>();
computeRegistrationOps(existingRegistrations, desiredRegistrations,
registrations, unregistrations);
unregister(sClientId, unregistrations);
register(sClientId, registrations);
}
@VisibleForTesting
static void computeRegistrationOps(Set<ObjectId> existingRegs, Set<ObjectId> desiredRegs,
Set<ObjectId> regAccumulator, Set<ObjectId> unregAccumulator) {
regAccumulator.addAll(desiredRegs);
regAccumulator.removeAll(existingRegs);
unregAccumulator.addAll(existingRegs);
unregAccumulator.removeAll(desiredRegs);
}
private void requestSync(@Nullable ObjectId objectId, @Nullable Long version,
@Nullable String payload) {
Bundle bundle = new Bundle();
if (objectId == null && version == null && payload == null) {
} else {
if (objectId != null) {
bundle.putInt("objectSource", objectId.getSource());
bundle.putString("objectId", new String(objectId.getName()));
}
bundle.putLong("version", (version == null) ? 0 : version);
bundle.putString("payload", (payload == null) ? "" : payload);
}
Account account = ChromeSigninController.get(this).getSignedInUser();
String contractAuthority = SyncStatusHelper.get(this).getContractAuthority();
requestSyncFromContentResolver(bundle, account, contractAuthority);
}
@VisibleForTesting
void requestSyncFromContentResolver(
Bundle bundle, Account account, String contractAuthority) {
Log.d(TAG, "Request sync: " + account + " / " + contractAuthority + " / "
+ bundle.keySet());
ContentResolver.requestSync(account, contractAuthority, bundle);
}
@VisibleForTesting
boolean shouldClientBeRunning() {
return isSyncEnabled() && isChromeInForeground();
}
@VisibleForTesting
boolean isSyncEnabled() {
return SyncStatusHelper.get(getApplicationContext()).isSyncEnabled();
}
@VisibleForTesting
boolean isChromeInForeground() {
return ApplicationStatus.hasVisibleActivities();
}
@VisibleForTesting
static boolean getIsClientStartedForTest() {
return sIsClientStarted;
}
@VisibleForTesting
@Nullable static byte[] getClientIdForTest() {
return sClientId;
}
private static String getOAuth2ScopeWithType() {
return "oauth2:" + SyncStatusHelper.CHROME_SYNC_OAUTH2_SCOPE;
}
private static void setClientId(byte[] clientId) {
sClientId = clientId;
}
private static void setIsClientStarted(boolean isStarted) {
sIsClientStarted = isStarted;
}
}