mobile/android/base/sync/syncadapter/SyncAdapter.java

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 2 * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 4
michael@0 5 package org.mozilla.gecko.sync.syncadapter;
michael@0 6
michael@0 7 import java.io.IOException;
michael@0 8 import java.net.URI;
michael@0 9 import java.security.NoSuchAlgorithmException;
michael@0 10 import java.util.Collection;
michael@0 11 import java.util.concurrent.atomic.AtomicBoolean;
michael@0 12
michael@0 13 import org.json.simple.parser.ParseException;
michael@0 14 import org.mozilla.gecko.background.common.GlobalConstants;
michael@0 15 import org.mozilla.gecko.background.common.log.Logger;
michael@0 16 import org.mozilla.gecko.db.BrowserContract;
michael@0 17 import org.mozilla.gecko.sync.AlreadySyncingException;
michael@0 18 import org.mozilla.gecko.sync.BackoffHandler;
michael@0 19 import org.mozilla.gecko.sync.CredentialException;
michael@0 20 import org.mozilla.gecko.sync.GlobalSession;
michael@0 21 import org.mozilla.gecko.sync.NonObjectJSONException;
michael@0 22 import org.mozilla.gecko.sync.PrefsBackoffHandler;
michael@0 23 import org.mozilla.gecko.sync.SharedPreferencesClientsDataDelegate;
michael@0 24 import org.mozilla.gecko.sync.SharedPreferencesNodeAssignmentCallback;
michael@0 25 import org.mozilla.gecko.sync.Sync11Configuration;
michael@0 26 import org.mozilla.gecko.sync.SyncConfiguration;
michael@0 27 import org.mozilla.gecko.sync.SyncConfigurationException;
michael@0 28 import org.mozilla.gecko.sync.SyncConstants;
michael@0 29 import org.mozilla.gecko.sync.SyncException;
michael@0 30 import org.mozilla.gecko.sync.ThreadPool;
michael@0 31 import org.mozilla.gecko.sync.Utils;
michael@0 32 import org.mozilla.gecko.sync.config.AccountPickler;
michael@0 33 import org.mozilla.gecko.sync.crypto.CryptoException;
michael@0 34 import org.mozilla.gecko.sync.crypto.KeyBundle;
michael@0 35 import org.mozilla.gecko.sync.delegates.BaseGlobalSessionCallback;
michael@0 36 import org.mozilla.gecko.sync.delegates.ClientsDataDelegate;
michael@0 37 import org.mozilla.gecko.sync.net.AuthHeaderProvider;
michael@0 38 import org.mozilla.gecko.sync.net.BasicAuthHeaderProvider;
michael@0 39 import org.mozilla.gecko.sync.net.ConnectionMonitorThread;
michael@0 40 import org.mozilla.gecko.sync.setup.Constants;
michael@0 41 import org.mozilla.gecko.sync.setup.SyncAccounts;
michael@0 42 import org.mozilla.gecko.sync.setup.SyncAccounts.SyncAccountParameters;
michael@0 43 import org.mozilla.gecko.sync.stage.GlobalSyncStage.Stage;
michael@0 44
michael@0 45 import android.accounts.Account;
michael@0 46 import android.accounts.AccountManager;
michael@0 47 import android.accounts.AuthenticatorException;
michael@0 48 import android.accounts.OperationCanceledException;
michael@0 49 import android.content.AbstractThreadedSyncAdapter;
michael@0 50 import android.content.ContentProviderClient;
michael@0 51 import android.content.ContentResolver;
michael@0 52 import android.content.Context;
michael@0 53 import android.content.SharedPreferences;
michael@0 54 import android.content.SyncResult;
michael@0 55 import android.database.sqlite.SQLiteConstraintException;
michael@0 56 import android.database.sqlite.SQLiteException;
michael@0 57 import android.os.Bundle;
michael@0 58
michael@0 59 public class SyncAdapter extends AbstractThreadedSyncAdapter implements BaseGlobalSessionCallback {
michael@0 60 private static final String LOG_TAG = "SyncAdapter";
michael@0 61
michael@0 62 private static final int BACKOFF_PAD_SECONDS = 5;
michael@0 63 public static final int MULTI_DEVICE_INTERVAL_MILLISECONDS = 5 * 60 * 1000; // 5 minutes.
michael@0 64 public static final int SINGLE_DEVICE_INTERVAL_MILLISECONDS = 24 * 60 * 60 * 1000; // 24 hours.
michael@0 65
michael@0 66 private final Context mContext;
michael@0 67
michael@0 68 protected long syncStartTimestamp;
michael@0 69
michael@0 70 protected volatile BackoffHandler backoffHandler;
michael@0 71
michael@0 72 public SyncAdapter(Context context, boolean autoInitialize) {
michael@0 73 super(context, autoInitialize);
michael@0 74 mContext = context;
michael@0 75 }
michael@0 76
michael@0 77 /**
michael@0 78 * Handle an exception: update stats, log errors, etc.
michael@0 79 * Wakes up sleeping threads by calling notifyMonitor().
michael@0 80 *
michael@0 81 * @param globalSession
michael@0 82 * current global session, or null.
michael@0 83 * @param e
michael@0 84 * Exception to handle.
michael@0 85 */
michael@0 86 protected void processException(final GlobalSession globalSession, final Exception e) {
michael@0 87 try {
michael@0 88 if (e instanceof SQLiteConstraintException) {
michael@0 89 Logger.error(LOG_TAG, "Constraint exception. Aborting sync.", e);
michael@0 90 syncResult.stats.numParseExceptions++; // This is as good as we can do.
michael@0 91 return;
michael@0 92 }
michael@0 93 if (e instanceof SQLiteException) {
michael@0 94 Logger.error(LOG_TAG, "Couldn't open database (locked?). Aborting sync.", e);
michael@0 95 syncResult.stats.numIoExceptions++;
michael@0 96 return;
michael@0 97 }
michael@0 98 if (e instanceof OperationCanceledException) {
michael@0 99 Logger.error(LOG_TAG, "Operation canceled. Aborting sync.", e);
michael@0 100 return;
michael@0 101 }
michael@0 102 if (e instanceof AuthenticatorException) {
michael@0 103 syncResult.stats.numParseExceptions++;
michael@0 104 Logger.error(LOG_TAG, "AuthenticatorException. Aborting sync.", e);
michael@0 105 return;
michael@0 106 }
michael@0 107 if (e instanceof IOException) {
michael@0 108 syncResult.stats.numIoExceptions++;
michael@0 109 Logger.error(LOG_TAG, "IOException. Aborting sync.", e);
michael@0 110 e.printStackTrace();
michael@0 111 return;
michael@0 112 }
michael@0 113
michael@0 114 // Blanket stats updating for SyncException subclasses.
michael@0 115 if (e instanceof SyncException) {
michael@0 116 ((SyncException) e).updateStats(globalSession, syncResult);
michael@0 117 } else {
michael@0 118 // Generic exception.
michael@0 119 syncResult.stats.numIoExceptions++;
michael@0 120 }
michael@0 121
michael@0 122 if (e instanceof CredentialException.MissingAllCredentialsException) {
michael@0 123 // This is bad: either we couldn't fetch credentials, or the credentials
michael@0 124 // were totally blank. Most likely the user has two copies of Firefox
michael@0 125 // installed, and something is misbehaving.
michael@0 126 // Either way, disable this account.
michael@0 127 if (localAccount == null) {
michael@0 128 // Should not happen, but be safe.
michael@0 129 Logger.error(LOG_TAG, "No credentials attached to account. Aborting sync.");
michael@0 130 return;
michael@0 131 }
michael@0 132
michael@0 133 Logger.error(LOG_TAG, "No credentials attached to account " + localAccount.name + ". Aborting sync.");
michael@0 134 try {
michael@0 135 SyncAccounts.setSyncAutomatically(localAccount, false);
michael@0 136 } catch (Exception ex) {
michael@0 137 Logger.error(LOG_TAG, "Unable to disable account " + localAccount.name + ".", ex);
michael@0 138 }
michael@0 139 return;
michael@0 140 }
michael@0 141
michael@0 142 if (e instanceof CredentialException.MissingCredentialException) {
michael@0 143 Logger.error(LOG_TAG, "Credentials attached to account, but missing " +
michael@0 144 ((CredentialException.MissingCredentialException) e).missingCredential + ". Aborting sync.");
michael@0 145 return;
michael@0 146 }
michael@0 147
michael@0 148 if (e instanceof CredentialException) {
michael@0 149 Logger.error(LOG_TAG, "Credentials attached to account were bad.");
michael@0 150 return;
michael@0 151 }
michael@0 152
michael@0 153 // Bug 755638 - Uncaught SecurityException when attempting to sync multiple Fennecs
michael@0 154 // to the same Sync account.
michael@0 155 // Uncheck Sync checkbox because we cannot sync this instance.
michael@0 156 if (e instanceof SecurityException) {
michael@0 157 Logger.error(LOG_TAG, "SecurityException, multiple Fennecs. Disabling this instance.", e);
michael@0 158 SyncAccounts.backgroundSetSyncAutomatically(localAccount, false);
michael@0 159 return;
michael@0 160 }
michael@0 161 // Generic exception.
michael@0 162 Logger.error(LOG_TAG, "Unknown exception. Aborting sync.", e);
michael@0 163 } finally {
michael@0 164 notifyMonitor();
michael@0 165 }
michael@0 166 }
michael@0 167
michael@0 168 @Override
michael@0 169 public void onSyncCanceled() {
michael@0 170 super.onSyncCanceled();
michael@0 171 // TODO: cancel the sync!
michael@0 172 // From the docs: "This will be invoked on a separate thread than the sync
michael@0 173 // thread and so you must consider the multi-threaded implications of the
michael@0 174 // work that you do in this method."
michael@0 175 }
michael@0 176
michael@0 177 public Object syncMonitor = new Object();
michael@0 178 private SyncResult syncResult;
michael@0 179
michael@0 180 protected Account localAccount;
michael@0 181 protected boolean thisSyncIsForced = false;
michael@0 182 protected SharedPreferences accountSharedPreferences;
michael@0 183 protected SharedPreferencesClientsDataDelegate clientsDataDelegate;
michael@0 184 protected SharedPreferencesNodeAssignmentCallback nodeAssignmentDelegate;
michael@0 185
michael@0 186 /**
michael@0 187 * Request that no sync start right away. A new sync won't start until
michael@0 188 * at least <code>backoff</code> milliseconds from now.
michael@0 189 *
michael@0 190 * Don't call this unless you are inside `run`.
michael@0 191 *
michael@0 192 * @param backoff time to wait in milliseconds.
michael@0 193 */
michael@0 194 @Override
michael@0 195 public void requestBackoff(final long backoff) {
michael@0 196 if (this.backoffHandler == null) {
michael@0 197 throw new IllegalStateException("No backoff handler: requesting backoff outside run()?");
michael@0 198 }
michael@0 199 if (backoff > 0) {
michael@0 200 // Fuzz the backoff time (up to 25% more) to prevent client lock-stepping; agrees with desktop.
michael@0 201 final long fuzzedBackoff = backoff + Math.round((double) backoff * 0.25d * Math.random());
michael@0 202 this.backoffHandler.extendEarliestNextRequest(System.currentTimeMillis() + fuzzedBackoff);
michael@0 203 }
michael@0 204 }
michael@0 205
michael@0 206 @Override
michael@0 207 public boolean shouldBackOffStorage() {
michael@0 208 if (thisSyncIsForced) {
michael@0 209 /*
michael@0 210 * If the user asks us to sync, we should sync regardless. This path is
michael@0 211 * hit if the user force syncs and we restart a session after a
michael@0 212 * freshStart.
michael@0 213 */
michael@0 214 return false;
michael@0 215 }
michael@0 216
michael@0 217 if (nodeAssignmentDelegate.wantNodeAssignment()) {
michael@0 218 /*
michael@0 219 * We recently had a 401 and we aborted the last sync. We should kick off
michael@0 220 * another sync to fetch a new node/weave cluster URL, since ours is
michael@0 221 * stale. If we have a user authentication error, the next sync will
michael@0 222 * determine that and will stop requesting node assignment, so this will
michael@0 223 * only force one abnormally scheduled sync.
michael@0 224 */
michael@0 225 return false;
michael@0 226 }
michael@0 227
michael@0 228 if (this.backoffHandler == null) {
michael@0 229 throw new IllegalStateException("No backoff handler: checking backoff outside run()?");
michael@0 230 }
michael@0 231 return this.backoffHandler.delayMilliseconds() > 0;
michael@0 232 }
michael@0 233
michael@0 234 /**
michael@0 235 * Asynchronously request an immediate sync, optionally syncing only the given
michael@0 236 * named stages.
michael@0 237 * <p>
michael@0 238 * Returns immediately.
michael@0 239 *
michael@0 240 * @param account
michael@0 241 * the Android <code>Account</code> instance to sync.
michael@0 242 * @param stageNames
michael@0 243 * stage names to sync, or <code>null</code> to sync all known stages.
michael@0 244 */
michael@0 245 public static void requestImmediateSync(final Account account, final String[] stageNames) {
michael@0 246 requestImmediateSync(account, stageNames, null);
michael@0 247 }
michael@0 248
michael@0 249 /**
michael@0 250 * Asynchronously request an immediate sync, optionally syncing only the given
michael@0 251 * named stages.
michael@0 252 * <p>
michael@0 253 * Returns immediately.
michael@0 254 *
michael@0 255 * @param account
michael@0 256 * the Android <code>Account</code> instance to sync.
michael@0 257 * @param stageNames
michael@0 258 * stage names to sync, or <code>null</code> to sync all known stages.
michael@0 259 * @param moreExtras
michael@0 260 * bundle of extras to give to the sync, or <code>null</code>
michael@0 261 */
michael@0 262 public static void requestImmediateSync(final Account account, final String[] stageNames, Bundle moreExtras) {
michael@0 263 if (account == null) {
michael@0 264 Logger.warn(LOG_TAG, "Not requesting immediate sync because Android Account is null.");
michael@0 265 return;
michael@0 266 }
michael@0 267
michael@0 268 final Bundle extras = new Bundle();
michael@0 269 Utils.putStageNamesToSync(extras, stageNames, null);
michael@0 270 extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
michael@0 271
michael@0 272 if (moreExtras != null) {
michael@0 273 extras.putAll(moreExtras);
michael@0 274 }
michael@0 275
michael@0 276 ContentResolver.requestSync(account, BrowserContract.AUTHORITY, extras);
michael@0 277 }
michael@0 278
michael@0 279 @Override
michael@0 280 public void onPerformSync(final Account account,
michael@0 281 final Bundle extras,
michael@0 282 final String authority,
michael@0 283 final ContentProviderClient provider,
michael@0 284 final SyncResult syncResult) {
michael@0 285 syncStartTimestamp = System.currentTimeMillis();
michael@0 286
michael@0 287 Logger.setThreadLogTag(SyncConstants.GLOBAL_LOG_TAG);
michael@0 288 Logger.resetLogging();
michael@0 289 Utils.reseedSharedRandom(); // Make sure we don't work with the same random seed for too long.
michael@0 290
michael@0 291 // Set these so that we don't need to thread them through assorted calls and callbacks.
michael@0 292 this.syncResult = syncResult;
michael@0 293 this.localAccount = account;
michael@0 294
michael@0 295 SyncAccountParameters params;
michael@0 296 try {
michael@0 297 params = SyncAccounts.blockingFromAndroidAccountV0(mContext, AccountManager.get(mContext), this.localAccount);
michael@0 298 } catch (Exception e) {
michael@0 299 // Updates syncResult and (harmlessly) calls notifyMonitor().
michael@0 300 processException(null, e);
michael@0 301 return;
michael@0 302 }
michael@0 303
michael@0 304 // params and the following fields are non-null at this point.
michael@0 305 final String username = params.username; // Encoded with Utils.usernameFromAccount.
michael@0 306 final String password = params.password;
michael@0 307 final String serverURL = params.serverURL;
michael@0 308 final String syncKey = params.syncKey;
michael@0 309
michael@0 310 final AtomicBoolean setNextSync = new AtomicBoolean(true);
michael@0 311 final SyncAdapter self = this;
michael@0 312 final Runnable runnable = new Runnable() {
michael@0 313 @Override
michael@0 314 public void run() {
michael@0 315 Logger.trace(LOG_TAG, "AccountManagerCallback invoked.");
michael@0 316 // TODO: N.B.: Future must not be used on the main thread.
michael@0 317 try {
michael@0 318 if (Logger.LOG_PERSONAL_INFORMATION) {
michael@0 319 Logger.pii(LOG_TAG, "Syncing account named " + account.name +
michael@0 320 " for authority " + authority + ".");
michael@0 321 } else {
michael@0 322 // Replace "foo@bar.com" with "XXX@XXX.XXX".
michael@0 323 Logger.info(LOG_TAG, "Syncing account named like " + Utils.obfuscateEmail(account.name) +
michael@0 324 " for authority " + authority + ".");
michael@0 325 }
michael@0 326
michael@0 327 // We dump this information right away to help with debugging.
michael@0 328 Logger.debug(LOG_TAG, "Username: " + username);
michael@0 329 Logger.debug(LOG_TAG, "Server: " + serverURL);
michael@0 330 if (Logger.LOG_PERSONAL_INFORMATION) {
michael@0 331 Logger.debug(LOG_TAG, "Password: " + password);
michael@0 332 Logger.debug(LOG_TAG, "Sync key: " + syncKey);
michael@0 333 } else {
michael@0 334 Logger.debug(LOG_TAG, "Password? " + (password != null));
michael@0 335 Logger.debug(LOG_TAG, "Sync key? " + (syncKey != null));
michael@0 336 }
michael@0 337
michael@0 338 // Support multiple accounts by mapping each server/account pair to a branch of the
michael@0 339 // shared preferences space.
michael@0 340 final String product = GlobalConstants.BROWSER_INTENT_PACKAGE;
michael@0 341 final String profile = Constants.DEFAULT_PROFILE;
michael@0 342 final long version = SyncConfiguration.CURRENT_PREFS_VERSION;
michael@0 343 self.accountSharedPreferences = Utils.getSharedPreferences(mContext, product, username, serverURL, profile, version);
michael@0 344 self.clientsDataDelegate = new SharedPreferencesClientsDataDelegate(accountSharedPreferences);
michael@0 345 self.backoffHandler = new PrefsBackoffHandler(accountSharedPreferences, SyncConstants.BACKOFF_PREF_SUFFIX_11);
michael@0 346 final String nodeWeaveURL = Utils.nodeWeaveURL(serverURL, username);
michael@0 347 self.nodeAssignmentDelegate = new SharedPreferencesNodeAssignmentCallback(accountSharedPreferences, nodeWeaveURL);
michael@0 348
michael@0 349 Logger.info(LOG_TAG,
michael@0 350 "Client is named '" + clientsDataDelegate.getClientName() + "'" +
michael@0 351 ", has client guid " + clientsDataDelegate.getAccountGUID() +
michael@0 352 ", and has " + clientsDataDelegate.getClientsCount() + " clients.");
michael@0 353
michael@0 354 final boolean thisSyncIsForced = (extras != null) && (extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false));
michael@0 355 final long delayMillis = backoffHandler.delayMilliseconds();
michael@0 356 boolean shouldSync = thisSyncIsForced || (delayMillis <= 0L);
michael@0 357 if (!shouldSync) {
michael@0 358 long remainingSeconds = delayMillis / 1000;
michael@0 359 syncResult.delayUntil = remainingSeconds + BACKOFF_PAD_SECONDS;
michael@0 360 setNextSync.set(false);
michael@0 361 self.notifyMonitor();
michael@0 362 return;
michael@0 363 }
michael@0 364
michael@0 365 final String prefsPath = Utils.getPrefsPath(product, username, serverURL, profile, version);
michael@0 366 self.performSync(account, extras, authority, provider, syncResult,
michael@0 367 username, password, prefsPath, serverURL, syncKey);
michael@0 368 } catch (Exception e) {
michael@0 369 self.processException(null, e);
michael@0 370 return;
michael@0 371 }
michael@0 372 }
michael@0 373 };
michael@0 374
michael@0 375 synchronized (syncMonitor) {
michael@0 376 // Perform the work in a new thread from within this synchronized block,
michael@0 377 // which allows us to be waiting on the monitor before the callback can
michael@0 378 // notify us in a failure case. Oh, concurrent programming.
michael@0 379 new Thread(runnable).start();
michael@0 380
michael@0 381 // Start our stale connection monitor thread.
michael@0 382 ConnectionMonitorThread stale = new ConnectionMonitorThread();
michael@0 383 stale.start();
michael@0 384
michael@0 385 Logger.trace(LOG_TAG, "Waiting on sync monitor.");
michael@0 386 try {
michael@0 387 syncMonitor.wait();
michael@0 388
michael@0 389 if (setNextSync.get()) {
michael@0 390 long interval = getSyncInterval(clientsDataDelegate);
michael@0 391 long next = System.currentTimeMillis() + interval;
michael@0 392
michael@0 393 if (thisSyncIsForced) {
michael@0 394 Logger.info(LOG_TAG, "Setting minimum next sync time to " + next + " (" + interval + "ms from now).");
michael@0 395 self.backoffHandler.setEarliestNextRequest(next);
michael@0 396 } else {
michael@0 397 Logger.info(LOG_TAG, "Extending minimum next sync time to " + next + " (" + interval + "ms from now).");
michael@0 398 self.backoffHandler.extendEarliestNextRequest(next);
michael@0 399 }
michael@0 400 }
michael@0 401 Logger.info(LOG_TAG, "Sync took " + Utils.formatDuration(syncStartTimestamp, System.currentTimeMillis()) + ".");
michael@0 402 } catch (InterruptedException e) {
michael@0 403 Logger.warn(LOG_TAG, "Waiting on sync monitor interrupted.", e);
michael@0 404 } finally {
michael@0 405 // And we're done with HTTP stuff.
michael@0 406 stale.shutdown();
michael@0 407 }
michael@0 408 }
michael@0 409 }
michael@0 410
michael@0 411 public int getSyncInterval(ClientsDataDelegate clientsDataDelegate) {
michael@0 412 // Must have been a problem that means we can't access the Account.
michael@0 413 if (this.localAccount == null) {
michael@0 414 return SINGLE_DEVICE_INTERVAL_MILLISECONDS;
michael@0 415 }
michael@0 416
michael@0 417 int clientsCount = clientsDataDelegate.getClientsCount();
michael@0 418 if (clientsCount <= 1) {
michael@0 419 return SINGLE_DEVICE_INTERVAL_MILLISECONDS;
michael@0 420 }
michael@0 421
michael@0 422 return MULTI_DEVICE_INTERVAL_MILLISECONDS;
michael@0 423 }
michael@0 424
michael@0 425 /**
michael@0 426 * Now that we have a sync key and password, go ahead and do the work.
michael@0 427 * @throws NoSuchAlgorithmException
michael@0 428 * @throws IllegalArgumentException
michael@0 429 * @throws SyncConfigurationException
michael@0 430 * @throws AlreadySyncingException
michael@0 431 * @throws NonObjectJSONException
michael@0 432 * @throws ParseException
michael@0 433 * @throws IOException
michael@0 434 * @throws CryptoException
michael@0 435 */
michael@0 436 protected void performSync(final Account account,
michael@0 437 final Bundle extras,
michael@0 438 final String authority,
michael@0 439 final ContentProviderClient provider,
michael@0 440 final SyncResult syncResult,
michael@0 441 final String username,
michael@0 442 final String password,
michael@0 443 final String prefsPath,
michael@0 444 final String serverURL,
michael@0 445 final String syncKey)
michael@0 446 throws NoSuchAlgorithmException,
michael@0 447 SyncConfigurationException,
michael@0 448 IllegalArgumentException,
michael@0 449 AlreadySyncingException,
michael@0 450 IOException, ParseException,
michael@0 451 NonObjectJSONException, CryptoException {
michael@0 452 Logger.trace(LOG_TAG, "Performing sync.");
michael@0 453
michael@0 454 /**
michael@0 455 * Bug 769745: pickle Sync account parameters to JSON file. Un-pickle in
michael@0 456 * <code>SyncAccounts.syncAccountsExist</code>.
michael@0 457 */
michael@0 458 try {
michael@0 459 // Constructor can throw on nulls, which should not happen -- but let's be safe.
michael@0 460 final SyncAccountParameters params = new SyncAccountParameters(mContext, null,
michael@0 461 account.name, // Un-encoded, like "test@mozilla.com".
michael@0 462 syncKey,
michael@0 463 password,
michael@0 464 serverURL,
michael@0 465 null, // We'll re-fetch cluster URL; not great, but not harmful.
michael@0 466 clientsDataDelegate.getClientName(),
michael@0 467 clientsDataDelegate.getAccountGUID());
michael@0 468
michael@0 469 // Bug 772971: pickle Sync account parameters on background thread to
michael@0 470 // avoid strict mode warnings.
michael@0 471 ThreadPool.run(new Runnable() {
michael@0 472 @Override
michael@0 473 public void run() {
michael@0 474 final boolean syncAutomatically = ContentResolver.getSyncAutomatically(account, authority);
michael@0 475 try {
michael@0 476 AccountPickler.pickle(mContext, Constants.ACCOUNT_PICKLE_FILENAME, params, syncAutomatically);
michael@0 477 } catch (Exception e) {
michael@0 478 // Should never happen, but we really don't want to die in a background thread.
michael@0 479 Logger.warn(LOG_TAG, "Got exception pickling current account details; ignoring.", e);
michael@0 480 }
michael@0 481 }
michael@0 482 });
michael@0 483 } catch (IllegalArgumentException e) {
michael@0 484 // Do nothing.
michael@0 485 }
michael@0 486
michael@0 487 if (username == null) {
michael@0 488 throw new IllegalArgumentException("username must not be null.");
michael@0 489 }
michael@0 490
michael@0 491 if (syncKey == null) {
michael@0 492 throw new SyncConfigurationException();
michael@0 493 }
michael@0 494
michael@0 495 final KeyBundle keyBundle = new KeyBundle(username, syncKey);
michael@0 496
michael@0 497 if (keyBundle == null ||
michael@0 498 keyBundle.getEncryptionKey() == null ||
michael@0 499 keyBundle.getHMACKey() == null) {
michael@0 500 throw new SyncConfigurationException();
michael@0 501 }
michael@0 502
michael@0 503 final AuthHeaderProvider authHeaderProvider = new BasicAuthHeaderProvider(username, password);
michael@0 504 final SharedPreferences prefs = getContext().getSharedPreferences(prefsPath, Utils.SHARED_PREFERENCES_MODE);
michael@0 505 final SyncConfiguration config = new Sync11Configuration(username, authHeaderProvider, prefs, keyBundle);
michael@0 506
michael@0 507 Collection<String> knownStageNames = SyncConfiguration.validEngineNames();
michael@0 508 config.stagesToSync = Utils.getStagesToSyncFromBundle(knownStageNames, extras);
michael@0 509
michael@0 510 GlobalSession globalSession = new GlobalSession(config, this, this.mContext, clientsDataDelegate, nodeAssignmentDelegate);
michael@0 511 globalSession.start();
michael@0 512 }
michael@0 513
michael@0 514 private void notifyMonitor() {
michael@0 515 synchronized (syncMonitor) {
michael@0 516 Logger.trace(LOG_TAG, "Notifying sync monitor.");
michael@0 517 syncMonitor.notifyAll();
michael@0 518 }
michael@0 519 }
michael@0 520
michael@0 521 // Implementing GlobalSession callbacks.
michael@0 522 @Override
michael@0 523 public void handleError(GlobalSession globalSession, Exception ex) {
michael@0 524 Logger.info(LOG_TAG, "GlobalSession indicated error.");
michael@0 525 this.processException(globalSession, ex);
michael@0 526 }
michael@0 527
michael@0 528 @Override
michael@0 529 public void handleAborted(GlobalSession globalSession, String reason) {
michael@0 530 Logger.warn(LOG_TAG, "Sync aborted: " + reason);
michael@0 531 notifyMonitor();
michael@0 532 }
michael@0 533
michael@0 534 @Override
michael@0 535 public void handleSuccess(GlobalSession globalSession) {
michael@0 536 Logger.info(LOG_TAG, "GlobalSession indicated success.");
michael@0 537 globalSession.config.persistToPrefs();
michael@0 538 notifyMonitor();
michael@0 539 }
michael@0 540
michael@0 541 @Override
michael@0 542 public void handleStageCompleted(Stage currentState,
michael@0 543 GlobalSession globalSession) {
michael@0 544 Logger.trace(LOG_TAG, "Stage completed: " + currentState);
michael@0 545 }
michael@0 546
michael@0 547 @Override
michael@0 548 public void informUnauthorizedResponse(GlobalSession session, URI oldClusterURL) {
michael@0 549 nodeAssignmentDelegate.setClusterURLIsStale(true);
michael@0 550 }
michael@0 551
michael@0 552 @Override
michael@0 553 public void informUpgradeRequiredResponse(final GlobalSession session) {
michael@0 554 final AccountManager manager = AccountManager.get(mContext);
michael@0 555 final Account toDisable = localAccount;
michael@0 556 if (toDisable == null || manager == null) {
michael@0 557 Logger.warn(LOG_TAG, "Attempting to disable account, but null found.");
michael@0 558 return;
michael@0 559 }
michael@0 560 // Sync needs to be upgraded. Don't automatically sync anymore.
michael@0 561 ThreadPool.run(new Runnable() {
michael@0 562 @Override
michael@0 563 public void run() {
michael@0 564 manager.setUserData(toDisable, Constants.DATA_ENABLE_ON_UPGRADE, "1");
michael@0 565 SyncAccounts.setSyncAutomatically(toDisable, false);
michael@0 566 }
michael@0 567 });
michael@0 568 }
michael@0 569 }

mercurial