blob: 487f6ced42a974d67e4502c12a886cac5b47555a [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080017package android.content;
18
Dianne Hackborn231cc602009-04-27 17:10:36 -070019import com.android.internal.os.AtomicFile;
20import com.android.internal.util.ArrayUtils;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080021import com.android.internal.util.FastXmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022
Dianne Hackborn231cc602009-04-27 17:10:36 -070023import org.xmlpull.v1.XmlPullParser;
24import org.xmlpull.v1.XmlPullParserException;
25import org.xmlpull.v1.XmlSerializer;
26
Fred Quintanad9d2f112009-04-23 13:36:27 -070027import android.accounts.Account;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070030import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.os.Bundle;
33import android.os.Environment;
34import android.os.Handler;
35import android.os.Message;
36import android.os.Parcel;
37import android.os.RemoteCallbackList;
38import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.util.Log;
Dianne Hackborn231cc602009-04-27 17:10:36 -070040import android.util.SparseArray;
41import android.util.Xml;
Fred Quintana307da1a2010-01-21 14:24:20 -080042import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
Dianne Hackborn231cc602009-04-27 17:10:36 -070044import java.io.File;
45import java.io.FileInputStream;
46import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070048import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070050import java.util.Iterator;
51import java.util.TimeZone;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080052import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053
54/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070055 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070057 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 * @hide
59 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070060public class SyncStorageEngine extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061 private static final String TAG = "SyncManager";
Dianne Hackborn231cc602009-04-27 17:10:36 -070062 private static final boolean DEBUG_FILE = false;
Costin Manolache360e4542009-09-04 13:36:04 -070063
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080064 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
65
Dianne Hackborn231cc602009-04-27 17:10:36 -070066 // @VisibleForTesting
67 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
Dianne Hackborn231cc602009-04-27 17:10:36 -070069 /** Enum value for a sync start event. */
70 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
Dianne Hackborn231cc602009-04-27 17:10:36 -070072 /** Enum value for a sync stop event. */
73 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074
Dianne Hackborn231cc602009-04-27 17:10:36 -070075 // TODO: i18n -- grab these out of resources.
76 /** String names for the sync event types. */
77 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
Dianne Hackborn231cc602009-04-27 17:10:36 -070079 /** Enum value for a server-initiated sync. */
80 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
Dianne Hackborn231cc602009-04-27 17:10:36 -070082 /** Enum value for a local-initiated sync. */
83 public static final int SOURCE_LOCAL = 1;
84 /**
85 * Enum value for a poll-based sync (e.g., upon connection to
86 * network)
87 */
88 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
Dianne Hackborn231cc602009-04-27 17:10:36 -070090 /** Enum value for a user-initiated sync. */
91 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080093 /** Enum value for a periodic sync. */
94 public static final int SOURCE_PERIODIC = 4;
95
Fred Quintana307da1a2010-01-21 14:24:20 -080096 public static final long NOT_IN_BACKOFF_MODE = -1;
97
Fred Quintanaac9385e2009-06-22 18:00:59 -070098 private static final Intent SYNC_CONNECTION_SETTING_CHANGED_INTENT =
99 new Intent("com.android.sync.SYNC_CONN_STATUS_CHANGED");
100
Dianne Hackborn231cc602009-04-27 17:10:36 -0700101 // TODO: i18n -- grab these out of resources.
102 /** String names for the sync source types. */
103 public static final String[] SOURCES = { "SERVER",
104 "LOCAL",
105 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800106 "USER",
107 "PERIODIC" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Dianne Hackborn231cc602009-04-27 17:10:36 -0700109 // The MESG column will contain one of these or one of the Error types.
110 public static final String MESG_SUCCESS = "success";
111 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700113 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700114
Dianne Hackborn231cc602009-04-27 17:10:36 -0700115 private static final int MSG_WRITE_STATUS = 1;
116 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700117
Dianne Hackborn231cc602009-04-27 17:10:36 -0700118 private static final int MSG_WRITE_STATISTICS = 2;
119 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700120
121 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700122
Fred Quintanac2e46912010-03-15 16:10:44 -0700123 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700124 private static final int ACCOUNTS_VERSION = 2;
125
126 private static HashMap<String, String> sAuthorityRenames;
127
128 static {
129 sAuthorityRenames = new HashMap<String, String>();
130 sAuthorityRenames.put("contacts", "com.android.contacts");
131 sAuthorityRenames.put("calendar", "com.android.calendar");
132 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700133
Dianne Hackborn231cc602009-04-27 17:10:36 -0700134 public static class PendingOperation {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700135 final Account account;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700136 final int syncSource;
137 final String authority;
138 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800139 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700140
Dianne Hackborn231cc602009-04-27 17:10:36 -0700141 int authorityId;
142 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700143
Dianne Hackborn7a135592009-05-06 00:28:37 -0700144 PendingOperation(Account account, int source,
Fred Quintana307da1a2010-01-21 14:24:20 -0800145 String authority, Bundle extras, boolean expedited) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700146 this.account = account;
147 this.syncSource = source;
148 this.authority = authority;
149 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800150 this.expedited = expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700151 this.authorityId = -1;
152 }
153
154 PendingOperation(PendingOperation other) {
155 this.account = other.account;
156 this.syncSource = other.syncSource;
157 this.authority = other.authority;
158 this.extras = other.extras;
159 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800160 this.expedited = other.expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 }
Costin Manolache360e4542009-09-04 13:36:04 -0700163
Dianne Hackborn231cc602009-04-27 17:10:36 -0700164 static class AccountInfo {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700165 final Account account;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700166 final HashMap<String, AuthorityInfo> authorities =
167 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700168
Dianne Hackborn7a135592009-05-06 00:28:37 -0700169 AccountInfo(Account account) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700170 this.account = account;
171 }
172 }
Costin Manolache360e4542009-09-04 13:36:04 -0700173
Dianne Hackborn231cc602009-04-27 17:10:36 -0700174 public static class AuthorityInfo {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700175 final Account account;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700176 final String authority;
177 final int ident;
178 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700179 int syncable;
Fred Quintana307da1a2010-01-21 14:24:20 -0800180 long backoffTime;
181 long backoffDelay;
182 long delayUntil;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800183 final ArrayList<Pair<Bundle, Long>> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700184
Dianne Hackborn7a135592009-05-06 00:28:37 -0700185 AuthorityInfo(Account account, String authority, int ident) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700186 this.account = account;
187 this.authority = authority;
188 this.ident = ident;
Joe Onorato8294fad2009-07-15 16:08:44 -0700189 enabled = SYNC_ENABLED_DEFAULT;
Fred Quintana4a6679b2009-08-17 13:05:39 -0700190 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800191 backoffTime = -1; // if < 0 then we aren't in backoff mode
192 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800193 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
194 periodicSyncs.add(Pair.create(new Bundle(), DEFAULT_POLL_FREQUENCY_SECONDS));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700195 }
196 }
Costin Manolache360e4542009-09-04 13:36:04 -0700197
Dianne Hackborn231cc602009-04-27 17:10:36 -0700198 public static class SyncHistoryItem {
199 int authorityId;
200 int historyId;
201 long eventTime;
202 long elapsedTime;
203 int source;
204 int event;
205 long upstreamActivity;
206 long downstreamActivity;
207 String mesg;
208 }
Costin Manolache360e4542009-09-04 13:36:04 -0700209
Dianne Hackborn231cc602009-04-27 17:10:36 -0700210 public static class DayStats {
211 public final int day;
212 public int successCount;
213 public long successTime;
214 public int failureCount;
215 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700216
Dianne Hackborn231cc602009-04-27 17:10:36 -0700217 public DayStats(int day) {
218 this.day = day;
219 }
220 }
Costin Manolache360e4542009-09-04 13:36:04 -0700221
Dianne Hackborn231cc602009-04-27 17:10:36 -0700222 // Primary list of all syncable authorities. Also our global lock.
223 private final SparseArray<AuthorityInfo> mAuthorities =
224 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700225
Dianne Hackborn7a135592009-05-06 00:28:37 -0700226 private final HashMap<Account, AccountInfo> mAccounts =
227 new HashMap<Account, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
Dianne Hackborn231cc602009-04-27 17:10:36 -0700229 private final ArrayList<PendingOperation> mPendingOperations =
230 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700231
Fred Quintana918339a2010-10-05 14:00:39 -0700232 private final ArrayList<SyncInfo> mCurrentSyncs = new ArrayList<SyncInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700233
Dianne Hackborn231cc602009-04-27 17:10:36 -0700234 private final SparseArray<SyncStatusInfo> mSyncStatus =
235 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700236
Dianne Hackborn231cc602009-04-27 17:10:36 -0700237 private final ArrayList<SyncHistoryItem> mSyncHistory =
238 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700239
Dianne Hackborn231cc602009-04-27 17:10:36 -0700240 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
241 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700242
Fred Quintana77c560f2010-03-29 22:20:26 -0700243 private int mNextAuthorityId = 0;
244
Dianne Hackborn231cc602009-04-27 17:10:36 -0700245 // We keep 4 weeks of stats.
246 private final DayStats[] mDayStats = new DayStats[7*4];
247 private final Calendar mCal;
248 private int mYear;
249 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700250
Dianne Hackborn231cc602009-04-27 17:10:36 -0700251 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800252
Dianne Hackborn231cc602009-04-27 17:10:36 -0700253 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700254
Dianne Hackborn231cc602009-04-27 17:10:36 -0700255 /**
256 * This file contains the core engine state: all accounts and the
257 * settings for them. It must never be lost, and should be changed
258 * infrequently, so it is stored as an XML file.
259 */
260 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700261
Dianne Hackborn231cc602009-04-27 17:10:36 -0700262 /**
263 * This file contains the current sync status. We would like to retain
264 * it across boots, but its loss is not the end of the world, so we store
265 * this information as binary data.
266 */
267 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700268
Dianne Hackborn231cc602009-04-27 17:10:36 -0700269 /**
270 * This file contains sync statistics. This is purely debugging information
271 * so is written infrequently and can be thrown away at any time.
272 */
273 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700274
Dianne Hackborn231cc602009-04-27 17:10:36 -0700275 /**
276 * This file contains the pending sync operations. It is a binary file,
277 * which must be updated every time an operation is added or removed,
278 * so we have special handling of it.
279 */
280 private final AtomicFile mPendingFile;
281 private static final int PENDING_FINISH_TO_WRITE = 4;
282 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700283
Dianne Hackborn231cc602009-04-27 17:10:36 -0700284 private int mNextHistoryId = 0;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700285 private boolean mMasterSyncAutomatically = true;
Costin Manolache360e4542009-09-04 13:36:04 -0700286
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800287 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700290
Dianne Hackborn231cc602009-04-27 17:10:36 -0700291 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700292
Dianne Hackborn231cc602009-04-27 17:10:36 -0700293 File systemDir = new File(dataDir, "system");
294 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800295 syncDir.mkdirs();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700296 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
297 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
298 mPendingFile = new AtomicFile(new File(syncDir, "pending.bin"));
299 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700300
Dianne Hackborn231cc602009-04-27 17:10:36 -0700301 readAccountInfoLocked();
302 readStatusLocked();
303 readPendingOperationsLocked();
304 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700305 readAndDeleteLegacyAccountInfoLocked();
306 writeAccountInfoLocked();
307 writeStatusLocked();
308 writePendingOperationsLocked();
309 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 }
311
312 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800313 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 }
315
316 public static void init(Context context) {
317 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800318 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800320 // This call will return the correct directory whether Encrypted File Systems is
321 // enabled or not.
322 File dataDir = Environment.getSecureDataDirectory();
323 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 }
325
326 public static SyncStorageEngine getSingleton() {
327 if (sSyncStorageEngine == null) {
328 throw new IllegalStateException("not initialized");
329 }
330 return sSyncStorageEngine;
331 }
332
Dianne Hackborn231cc602009-04-27 17:10:36 -0700333 @Override public void handleMessage(Message msg) {
334 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700335 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700336 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700337 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700338 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700339 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700340 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 }
342 }
343 }
Costin Manolache360e4542009-09-04 13:36:04 -0700344
Dianne Hackborn231cc602009-04-27 17:10:36 -0700345 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
346 synchronized (mAuthorities) {
347 mChangeListeners.register(callback, mask);
348 }
349 }
Costin Manolache360e4542009-09-04 13:36:04 -0700350
Dianne Hackborn231cc602009-04-27 17:10:36 -0700351 public void removeStatusChangeListener(ISyncStatusObserver callback) {
352 synchronized (mAuthorities) {
353 mChangeListeners.unregister(callback);
354 }
355 }
Costin Manolache360e4542009-09-04 13:36:04 -0700356
Dianne Hackborn231cc602009-04-27 17:10:36 -0700357 private void reportChange(int which) {
358 ArrayList<ISyncStatusObserver> reports = null;
359 synchronized (mAuthorities) {
360 int i = mChangeListeners.beginBroadcast();
361 while (i > 0) {
362 i--;
363 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
364 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 continue;
366 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700367 if (reports == null) {
368 reports = new ArrayList<ISyncStatusObserver>(i);
369 }
370 reports.add(mChangeListeners.getBroadcastItem(i));
371 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700372 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700373 }
Costin Manolache360e4542009-09-04 13:36:04 -0700374
Fred Quintana77c560f2010-03-29 22:20:26 -0700375 if (Log.isLoggable(TAG, Log.VERBOSE)) {
376 Log.v(TAG, "reportChange " + which + " to: " + reports);
377 }
Costin Manolache360e4542009-09-04 13:36:04 -0700378
Dianne Hackborn231cc602009-04-27 17:10:36 -0700379 if (reports != null) {
380 int i = reports.size();
381 while (i > 0) {
382 i--;
383 try {
384 reports.get(i).onStatusChanged(which);
385 } catch (RemoteException e) {
386 // The remote callback list will take care of this for us.
387 }
388 }
389 }
390 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700391
Fred Quintanaac9385e2009-06-22 18:00:59 -0700392 public boolean getSyncAutomatically(Account account, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700393 synchronized (mAuthorities) {
394 if (account != null) {
395 AuthorityInfo authority = getAuthorityLocked(account, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700396 "getSyncAutomatically");
397 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700398 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700399
Dianne Hackborn231cc602009-04-27 17:10:36 -0700400 int i = mAuthorities.size();
401 while (i > 0) {
402 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700403 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700404 if (authority.authority.equals(providerName)
405 && authority.enabled) {
406 return true;
407 }
408 }
409 return false;
410 }
411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412
Fred Quintanaac9385e2009-06-22 18:00:59 -0700413 public void setSyncAutomatically(Account account, String providerName, boolean sync) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700414 Log.d(TAG, "setSyncAutomatically: " + account + ", provider " + providerName
415 + " -> " + sync);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700416 synchronized (mAuthorities) {
Joe Onorato8294fad2009-07-15 16:08:44 -0700417 AuthorityInfo authority = getOrCreateAuthorityLocked(account, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700418 if (authority.enabled == sync) {
419 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
420 return;
421 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700422 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700423 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700425
Fred Quintana77c560f2010-03-29 22:20:26 -0700426 if (sync) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800427 ContentResolver.requestSync(account, providerName, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700428 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700429 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 }
431
Fred Quintana5e787c42009-08-16 23:13:53 -0700432 public int getIsSyncable(Account account, String providerName) {
433 synchronized (mAuthorities) {
434 if (account != null) {
435 AuthorityInfo authority = getAuthorityLocked(account, providerName,
436 "getIsSyncable");
437 if (authority == null) {
438 return -1;
439 }
440 return authority.syncable;
441 }
442
443 int i = mAuthorities.size();
444 while (i > 0) {
445 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700446 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700447 if (authority.authority.equals(providerName)) {
448 return authority.syncable;
449 }
450 }
451 return -1;
452 }
453 }
454
455 public void setIsSyncable(Account account, String providerName, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700456 if (syncable > 1) {
457 syncable = 1;
458 } else if (syncable < -1) {
459 syncable = -1;
460 }
461 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName + " -> " + syncable);
Fred Quintana5e787c42009-08-16 23:13:53 -0700462 synchronized (mAuthorities) {
463 AuthorityInfo authority = getOrCreateAuthorityLocked(account, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700464 if (authority.syncable == syncable) {
465 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
466 return;
467 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700468 authority.syncable = syncable;
469 writeAccountInfoLocked();
470 }
471
Fred Quintana77c560f2010-03-29 22:20:26 -0700472 if (syncable > 0) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800473 ContentResolver.requestSync(account, providerName, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700474 }
475 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
476 }
477
Fred Quintana307da1a2010-01-21 14:24:20 -0800478 public Pair<Long, Long> getBackoff(Account account, String providerName) {
479 synchronized (mAuthorities) {
480 AuthorityInfo authority = getAuthorityLocked(account, providerName, "getBackoff");
481 if (authority == null || authority.backoffTime < 0) {
482 return null;
483 }
484 return Pair.create(authority.backoffTime, authority.backoffDelay);
485 }
486 }
487
488 public void setBackoff(Account account, String providerName,
489 long nextSyncTime, long nextDelay) {
490 if (Log.isLoggable(TAG, Log.VERBOSE)) {
491 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
492 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
493 }
494 boolean changed = false;
495 synchronized (mAuthorities) {
496 if (account == null || providerName == null) {
497 for (AccountInfo accountInfo : mAccounts.values()) {
498 if (account != null && !account.equals(accountInfo.account)) continue;
499 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
500 if (providerName != null && !providerName.equals(authorityInfo.authority)) {
501 continue;
502 }
503 if (authorityInfo.backoffTime != nextSyncTime
504 || authorityInfo.backoffDelay != nextDelay) {
505 authorityInfo.backoffTime = nextSyncTime;
506 authorityInfo.backoffDelay = nextDelay;
507 changed = true;
508 }
509 }
510 }
511 } else {
512 AuthorityInfo authority =
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800513 getOrCreateAuthorityLocked(account, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800514 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
515 return;
516 }
517 authority.backoffTime = nextSyncTime;
518 authority.backoffDelay = nextDelay;
519 changed = true;
520 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800521 }
522
523 if (changed) {
524 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
525 }
526 }
527
528 public void setDelayUntilTime(Account account, String providerName, long delayUntil) {
529 if (Log.isLoggable(TAG, Log.VERBOSE)) {
530 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
531 + " -> delayUntil " + delayUntil);
532 }
533 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800534 AuthorityInfo authority = getOrCreateAuthorityLocked(
535 account, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800536 if (authority.delayUntil == delayUntil) {
537 return;
538 }
539 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800540 }
541
542 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
543 }
544
545 public long getDelayUntilTime(Account account, String providerName) {
546 synchronized (mAuthorities) {
547 AuthorityInfo authority = getAuthorityLocked(account, providerName, "getDelayUntil");
548 if (authority == null) {
549 return 0;
550 }
551 return authority.delayUntil;
552 }
553 }
554
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800555 private void updateOrRemovePeriodicSync(Account account, String providerName, Bundle extras,
556 long period, boolean add) {
557 if (period <= 0) {
558 period = 0;
559 }
560 if (extras == null) {
561 extras = new Bundle();
562 }
563 if (Log.isLoggable(TAG, Log.VERBOSE)) {
564 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", provider " + providerName
565 + " -> period " + period + ", extras " + extras);
566 }
567 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700568 try {
569 AuthorityInfo authority =
570 getOrCreateAuthorityLocked(account, providerName, -1, false);
571 if (add) {
572 // add this periodic sync if one with the same extras doesn't already
573 // exist in the periodicSyncs array
574 boolean alreadyPresent = false;
575 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
576 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
577 final Bundle existingExtras = syncInfo.first;
578 if (equals(existingExtras, extras)) {
579 if (syncInfo.second == period) {
580 return;
581 }
582 authority.periodicSyncs.set(i, Pair.create(extras, period));
583 alreadyPresent = true;
584 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800585 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700586 }
587 // if we added an entry to the periodicSyncs array also add an entry to
588 // the periodic syncs status to correspond to it
589 if (!alreadyPresent) {
590 authority.periodicSyncs.add(Pair.create(extras, period));
591 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
592 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
593 }
594 } else {
595 // remove any periodic syncs that match the authority and extras
596 SyncStatusInfo status = mSyncStatus.get(authority.ident);
597 boolean changed = false;
598 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
599 int i = 0;
600 while (iterator.hasNext()) {
601 Pair<Bundle, Long> syncInfo = iterator.next();
602 if (equals(syncInfo.first, extras)) {
603 iterator.remove();
604 changed = true;
605 // if we removed an entry from the periodicSyncs array also
606 // remove the corresponding entry from the status
607 if (status != null) {
608 status.removePeriodicSyncTime(i);
609 }
610 } else {
611 i++;
612 }
613 }
614 if (!changed) {
615 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800616 }
617 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700618 } finally {
619 writeAccountInfoLocked();
620 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800621 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800622 }
623
624 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
625 }
626
627 public void addPeriodicSync(Account account, String providerName, Bundle extras,
628 long pollFrequency) {
629 updateOrRemovePeriodicSync(account, providerName, extras, pollFrequency, true /* add */);
630 }
631
632 public void removePeriodicSync(Account account, String providerName, Bundle extras) {
633 updateOrRemovePeriodicSync(account, providerName, extras, 0 /* period, ignored */,
634 false /* remove */);
635 }
636
637 public List<PeriodicSync> getPeriodicSyncs(Account account, String providerName) {
638 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
639 synchronized (mAuthorities) {
640 AuthorityInfo authority = getAuthorityLocked(account, providerName, "getPeriodicSyncs");
641 if (authority != null) {
642 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
643 syncs.add(new PeriodicSync(account, providerName, item.first, item.second));
644 }
645 }
646 }
647 return syncs;
648 }
649
Fred Quintanaac9385e2009-06-22 18:00:59 -0700650 public void setMasterSyncAutomatically(boolean flag) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700651 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700652 if (mMasterSyncAutomatically == flag) {
653 return;
654 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700655 mMasterSyncAutomatically = flag;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700656 writeAccountInfoLocked();
657 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700658 if (flag) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800659 ContentResolver.requestSync(null, null, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700660 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700661 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
662 mContext.sendBroadcast(SYNC_CONNECTION_SETTING_CHANGED_INTENT);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664
Fred Quintanaac9385e2009-06-22 18:00:59 -0700665 public boolean getMasterSyncAutomatically() {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700666 synchronized (mAuthorities) {
Fred Quintanaac9385e2009-06-22 18:00:59 -0700667 return mMasterSyncAutomatically;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700668 }
669 }
Costin Manolache360e4542009-09-04 13:36:04 -0700670
Fred Quintana1bbcd102010-02-10 10:04:33 -0800671 public AuthorityInfo getOrCreateAuthority(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700672 synchronized (mAuthorities) {
Fred Quintana1bbcd102010-02-10 10:04:33 -0800673 return getOrCreateAuthorityLocked(account, authority,
674 -1 /* assign a new identifier if creating a new authority */,
675 true /* write to storage if this results in a change */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700676 }
677 }
Costin Manolache360e4542009-09-04 13:36:04 -0700678
Fred Quintana7620f1a2010-03-16 15:58:44 -0700679 public void removeAuthority(Account account, String authority) {
680 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700681 removeAuthorityLocked(account, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700682 }
683 }
684
Dianne Hackborn231cc602009-04-27 17:10:36 -0700685 public AuthorityInfo getAuthority(int authorityId) {
686 synchronized (mAuthorities) {
687 return mAuthorities.get(authorityId);
688 }
689 }
Costin Manolache360e4542009-09-04 13:36:04 -0700690
Dianne Hackborn231cc602009-04-27 17:10:36 -0700691 /**
692 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700693 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700694 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700695 public boolean isSyncActive(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700696 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -0700697 for (SyncInfo syncInfo : mCurrentSyncs) {
698 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700699 if (ainfo != null && ainfo.account.equals(account)
700 && ainfo.authority.equals(authority)) {
701 return true;
702 }
703 }
704 }
Costin Manolache360e4542009-09-04 13:36:04 -0700705
Dianne Hackborn231cc602009-04-27 17:10:36 -0700706 return false;
707 }
Costin Manolache360e4542009-09-04 13:36:04 -0700708
Dianne Hackborn231cc602009-04-27 17:10:36 -0700709 public PendingOperation insertIntoPending(PendingOperation op) {
710 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700711 if (Log.isLoggable(TAG, Log.VERBOSE)) {
712 Log.v(TAG, "insertIntoPending: account=" + op.account
Dianne Hackborn231cc602009-04-27 17:10:36 -0700713 + " auth=" + op.authority
714 + " src=" + op.syncSource
715 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700716 }
Costin Manolache360e4542009-09-04 13:36:04 -0700717
Dianne Hackborn231cc602009-04-27 17:10:36 -0700718 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account,
719 op.authority,
720 -1 /* desired identifier */,
721 true /* write accounts to storage */);
722 if (authority == null) {
723 return null;
724 }
Costin Manolache360e4542009-09-04 13:36:04 -0700725
Dianne Hackborn231cc602009-04-27 17:10:36 -0700726 op = new PendingOperation(op);
727 op.authorityId = authority.ident;
728 mPendingOperations.add(op);
729 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700730
Dianne Hackborn231cc602009-04-27 17:10:36 -0700731 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
732 status.pending = true;
733 }
Costin Manolache360e4542009-09-04 13:36:04 -0700734
Fred Quintanaac9385e2009-06-22 18:00:59 -0700735 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700736 return op;
737 }
738
739 public boolean deleteFromPending(PendingOperation op) {
740 boolean res = false;
741 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700742 if (Log.isLoggable(TAG, Log.VERBOSE)) {
743 Log.v(TAG, "deleteFromPending: account=" + op.account
Dianne Hackborn231cc602009-04-27 17:10:36 -0700744 + " auth=" + op.authority
745 + " src=" + op.syncSource
746 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700747 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700748 if (mPendingOperations.remove(op)) {
749 if (mPendingOperations.size() == 0
750 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
751 writePendingOperationsLocked();
752 mNumPendingFinished = 0;
753 } else {
754 mNumPendingFinished++;
755 }
Costin Manolache360e4542009-09-04 13:36:04 -0700756
Dianne Hackborn231cc602009-04-27 17:10:36 -0700757 AuthorityInfo authority = getAuthorityLocked(op.account, op.authority,
758 "deleteFromPending");
759 if (authority != null) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700760 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "removing - " + authority);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700761 final int N = mPendingOperations.size();
762 boolean morePending = false;
763 for (int i=0; i<N; i++) {
764 PendingOperation cur = mPendingOperations.get(i);
765 if (cur.account.equals(op.account)
766 && cur.authority.equals(op.authority)) {
767 morePending = true;
768 break;
769 }
770 }
Costin Manolache360e4542009-09-04 13:36:04 -0700771
Dianne Hackborn231cc602009-04-27 17:10:36 -0700772 if (!morePending) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700773 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700774 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
775 status.pending = false;
776 }
777 }
Costin Manolache360e4542009-09-04 13:36:04 -0700778
Dianne Hackborn231cc602009-04-27 17:10:36 -0700779 res = true;
780 }
781 }
Costin Manolache360e4542009-09-04 13:36:04 -0700782
Fred Quintanaac9385e2009-06-22 18:00:59 -0700783 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700784 return res;
785 }
786
787 public int clearPending() {
788 int num;
789 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700790 if (Log.isLoggable(TAG, Log.VERBOSE)) {
791 Log.v(TAG, "clearPending");
792 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700793 num = mPendingOperations.size();
794 mPendingOperations.clear();
795 final int N = mSyncStatus.size();
796 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -0700797 mSyncStatus.valueAt(i).pending = false;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700798 }
799 writePendingOperationsLocked();
800 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700801 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700802 return num;
803 }
804
805 /**
806 * Return a copy of the current array of pending operations. The
807 * PendingOperation objects are the real objects stored inside, so that
808 * they can be used with deleteFromPending().
809 */
810 public ArrayList<PendingOperation> getPendingOperations() {
811 synchronized (mAuthorities) {
812 return new ArrayList<PendingOperation>(mPendingOperations);
813 }
814 }
Costin Manolache360e4542009-09-04 13:36:04 -0700815
Dianne Hackborn231cc602009-04-27 17:10:36 -0700816 /**
817 * Return the number of currently pending operations.
818 */
819 public int getPendingOperationCount() {
820 synchronized (mAuthorities) {
821 return mPendingOperations.size();
822 }
823 }
Costin Manolache360e4542009-09-04 13:36:04 -0700824
Dianne Hackborn231cc602009-04-27 17:10:36 -0700825 /**
826 * Called when the set of account has changed, given the new array of
827 * active accounts.
828 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700829 public void doDatabaseCleanup(Account[] accounts) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700830 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700831 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.w(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700832 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
833 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
834 while (accIt.hasNext()) {
835 AccountInfo acc = accIt.next();
836 if (!ArrayUtils.contains(accounts, acc.account)) {
837 // This account no longer exists...
Fred Quintana77c560f2010-03-29 22:20:26 -0700838 if (Log.isLoggable(TAG, Log.VERBOSE)) {
839 Log.w(TAG, "Account removed: " + acc.account);
840 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700841 for (AuthorityInfo auth : acc.authorities.values()) {
842 removing.put(auth.ident, auth);
843 }
844 accIt.remove();
845 }
846 }
Costin Manolache360e4542009-09-04 13:36:04 -0700847
Dianne Hackborn231cc602009-04-27 17:10:36 -0700848 // Clean out all data structures.
849 int i = removing.size();
850 if (i > 0) {
851 while (i > 0) {
852 i--;
853 int ident = removing.keyAt(i);
854 mAuthorities.remove(ident);
855 int j = mSyncStatus.size();
856 while (j > 0) {
857 j--;
858 if (mSyncStatus.keyAt(j) == ident) {
859 mSyncStatus.remove(mSyncStatus.keyAt(j));
860 }
861 }
862 j = mSyncHistory.size();
863 while (j > 0) {
864 j--;
865 if (mSyncHistory.get(j).authorityId == ident) {
866 mSyncHistory.remove(j);
867 }
868 }
869 }
870 writeAccountInfoLocked();
871 writeStatusLocked();
872 writePendingOperationsLocked();
873 writeStatisticsLocked();
874 }
875 }
876 }
877
878 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700879 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
880 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700881 */
Fred Quintana918339a2010-10-05 14:00:39 -0700882 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
883 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700884 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -0700885 if (Log.isLoggable(TAG, Log.VERBOSE)) {
886 Log.v(TAG, "setActiveSync: account="
887 + activeSyncContext.mSyncOperation.account
888 + " auth=" + activeSyncContext.mSyncOperation.authority
889 + " src=" + activeSyncContext.mSyncOperation.syncSource
890 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700891 }
Fred Quintana918339a2010-10-05 14:00:39 -0700892 AuthorityInfo authority = getOrCreateAuthorityLocked(
893 activeSyncContext.mSyncOperation.account,
894 activeSyncContext.mSyncOperation.authority,
895 -1 /* assign a new identifier if creating a new authority */,
896 true /* write to storage if this results in a change */);
897 syncInfo = new SyncInfo(authority.ident,
898 authority.account, authority.authority,
899 activeSyncContext.mStartTime);
900 mCurrentSyncs.add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700901 }
Costin Manolache360e4542009-09-04 13:36:04 -0700902
Fred Quintana918339a2010-10-05 14:00:39 -0700903 reportActiveChange();
904 return syncInfo;
905 }
906
907 /**
908 * Called to indicate that a previously active sync is no longer active.
909 */
910 public void removeActiveSync(SyncInfo syncInfo) {
911 synchronized (mAuthorities) {
912 if (Log.isLoggable(TAG, Log.VERBOSE)) {
913 Log.v(TAG, "removeActiveSync: account="
914 + syncInfo.account + " auth=" + syncInfo.authority);
915 }
916 mCurrentSyncs.remove(syncInfo);
917 }
918
919 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700920 }
921
922 /**
923 * To allow others to send active change reports, to poke clients.
924 */
925 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -0700926 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700927 }
Costin Manolache360e4542009-09-04 13:36:04 -0700928
Dianne Hackborn231cc602009-04-27 17:10:36 -0700929 /**
930 * Note that sync has started for the given account and authority.
931 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700932 public long insertStartSyncEvent(Account accountName, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700933 long now, int source) {
934 long id;
935 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700936 if (Log.isLoggable(TAG, Log.VERBOSE)) {
937 Log.v(TAG, "insertStartSyncEvent: account=" + accountName
Dianne Hackborn231cc602009-04-27 17:10:36 -0700938 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -0700939 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700940 AuthorityInfo authority = getAuthorityLocked(accountName, authorityName,
941 "insertStartSyncEvent");
942 if (authority == null) {
943 return -1;
944 }
945 SyncHistoryItem item = new SyncHistoryItem();
946 item.authorityId = authority.ident;
947 item.historyId = mNextHistoryId++;
948 if (mNextHistoryId < 0) mNextHistoryId = 0;
949 item.eventTime = now;
950 item.source = source;
951 item.event = EVENT_START;
952 mSyncHistory.add(0, item);
953 while (mSyncHistory.size() > MAX_HISTORY) {
954 mSyncHistory.remove(mSyncHistory.size()-1);
955 }
956 id = item.historyId;
Fred Quintana77c560f2010-03-29 22:20:26 -0700957 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700958 }
Costin Manolache360e4542009-09-04 13:36:04 -0700959
Fred Quintanaac9385e2009-06-22 18:00:59 -0700960 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700961 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
963
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800964 public static boolean equals(Bundle b1, Bundle b2) {
965 if (b1.size() != b2.size()) {
966 return false;
967 }
968 if (b1.isEmpty()) {
969 return true;
970 }
971 for (String key : b1.keySet()) {
972 if (!b2.containsKey(key)) {
973 return false;
974 }
975 if (!b1.get(key).equals(b2.get(key))) {
976 return false;
977 }
978 }
979 return true;
980 }
981
Fred Quintana77c560f2010-03-29 22:20:26 -0700982 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700984 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700985 if (Log.isLoggable(TAG, Log.VERBOSE)) {
986 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
987 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700988 SyncHistoryItem item = null;
989 int i = mSyncHistory.size();
990 while (i > 0) {
991 i--;
992 item = mSyncHistory.get(i);
993 if (item.historyId == historyId) {
994 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700996 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 }
Costin Manolache360e4542009-09-04 13:36:04 -0700998
Dianne Hackborn231cc602009-04-27 17:10:36 -0700999 if (item == null) {
1000 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1001 return;
1002 }
Costin Manolache360e4542009-09-04 13:36:04 -07001003
Dianne Hackborn231cc602009-04-27 17:10:36 -07001004 item.elapsedTime = elapsedTime;
1005 item.event = EVENT_STOP;
1006 item.mesg = resultMessage;
1007 item.downstreamActivity = downstreamActivity;
1008 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001009
Dianne Hackborn231cc602009-04-27 17:10:36 -07001010 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001011
Dianne Hackborn231cc602009-04-27 17:10:36 -07001012 status.numSyncs++;
1013 status.totalElapsedTime += elapsedTime;
1014 switch (item.source) {
1015 case SOURCE_LOCAL:
1016 status.numSourceLocal++;
1017 break;
1018 case SOURCE_POLL:
1019 status.numSourcePoll++;
1020 break;
1021 case SOURCE_USER:
1022 status.numSourceUser++;
1023 break;
1024 case SOURCE_SERVER:
1025 status.numSourceServer++;
1026 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001027 case SOURCE_PERIODIC:
1028 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001029 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001030 }
Costin Manolache360e4542009-09-04 13:36:04 -07001031
Dianne Hackborn231cc602009-04-27 17:10:36 -07001032 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001033 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001034 if (mDayStats[0] == null) {
1035 mDayStats[0] = new DayStats(day);
1036 } else if (day != mDayStats[0].day) {
1037 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1038 mDayStats[0] = new DayStats(day);
1039 writeStatisticsNow = true;
1040 } else if (mDayStats[0] == null) {
1041 }
1042 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001043
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 final long lastSyncTime = (item.eventTime + elapsedTime);
1045 boolean writeStatusNow = false;
1046 if (MESG_SUCCESS.equals(resultMessage)) {
1047 // - if successful, update the successful columns
1048 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1049 writeStatusNow = true;
1050 }
1051 status.lastSuccessTime = lastSyncTime;
1052 status.lastSuccessSource = item.source;
1053 status.lastFailureTime = 0;
1054 status.lastFailureSource = -1;
1055 status.lastFailureMesg = null;
1056 status.initialFailureTime = 0;
1057 ds.successCount++;
1058 ds.successTime += elapsedTime;
1059 } else if (!MESG_CANCELED.equals(resultMessage)) {
1060 if (status.lastFailureTime == 0) {
1061 writeStatusNow = true;
1062 }
1063 status.lastFailureTime = lastSyncTime;
1064 status.lastFailureSource = item.source;
1065 status.lastFailureMesg = resultMessage;
1066 if (status.initialFailureTime == 0) {
1067 status.initialFailureTime = lastSyncTime;
1068 }
1069 ds.failureCount++;
1070 ds.failureTime += elapsedTime;
1071 }
Costin Manolache360e4542009-09-04 13:36:04 -07001072
Dianne Hackborn231cc602009-04-27 17:10:36 -07001073 if (writeStatusNow) {
1074 writeStatusLocked();
1075 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1076 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1077 WRITE_STATUS_DELAY);
1078 }
1079 if (writeStatisticsNow) {
1080 writeStatisticsLocked();
1081 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1082 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1083 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001084 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001085 }
Costin Manolache360e4542009-09-04 13:36:04 -07001086
Fred Quintanaac9385e2009-06-22 18:00:59 -07001087 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001088 }
1089
1090 /**
1091 * Return the currently active sync information, or null if there is no
1092 * active sync. Note that the returned object is the real, live active
1093 * sync object, so be careful what you do with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001094 * <p>
1095 * Since multiple concurrent syncs are now supported you should use
1096 * {@link #getCurrentSyncs()} to get the accurate list of current syncs.
1097 * This method returns the first item from the list of current syncs
1098 * or null if there are none.
1099 * @deprecated use {@link #getCurrentSyncs()}
Dianne Hackborn231cc602009-04-27 17:10:36 -07001100 */
Fred Quintanad5e4fdc2010-03-30 15:16:21 -07001101 public SyncInfo getCurrentSync() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001102 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -07001103 return !mCurrentSyncs.isEmpty() ? mCurrentSyncs.get(0) : null;
1104 }
1105 }
1106
1107 /**
1108 * Return a list of the currently active syncs. Note that the returned items are the
1109 * real, live active sync objects, so be careful what you do with it.
1110 */
1111 public List<SyncInfo> getCurrentSyncs() {
1112 synchronized (mAuthorities) {
1113 return new ArrayList<SyncInfo>(mCurrentSyncs);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001114 }
1115 }
Costin Manolache360e4542009-09-04 13:36:04 -07001116
Dianne Hackborn231cc602009-04-27 17:10:36 -07001117 /**
1118 * Return an array of the current sync status for all authorities. Note
1119 * that the objects inside the array are the real, live status objects,
1120 * so be careful what you do with them.
1121 */
1122 public ArrayList<SyncStatusInfo> getSyncStatus() {
1123 synchronized (mAuthorities) {
1124 final int N = mSyncStatus.size();
1125 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1126 for (int i=0; i<N; i++) {
1127 ops.add(mSyncStatus.valueAt(i));
1128 }
1129 return ops;
1130 }
1131 }
Costin Manolache360e4542009-09-04 13:36:04 -07001132
Dianne Hackborn231cc602009-04-27 17:10:36 -07001133 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001134 * Return an array of the current authorities. Note
1135 * that the objects inside the array are the real, live objects,
1136 * so be careful what you do with them.
1137 */
1138 public ArrayList<AuthorityInfo> getAuthorities() {
1139 synchronized (mAuthorities) {
1140 final int N = mAuthorities.size();
1141 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1142 for (int i=0; i<N; i++) {
1143 infos.add(mAuthorities.valueAt(i));
1144 }
1145 return infos;
1146 }
1147 }
1148
1149 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001150 * Returns the status that matches the authority and account.
1151 *
1152 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001153 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001154 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001155 */
Costin Manolacheb7520982009-09-02 18:03:05 -07001156 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, String authority) {
1157 if (account == null || authority == null) {
1158 throw new IllegalArgumentException();
1159 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001160 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001161 final int N = mSyncStatus.size();
1162 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001163 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001164 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001165
1166 if (ainfo != null && ainfo.authority.equals(authority) &&
1167 account.equals(ainfo.account)) {
1168 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001169 }
1170 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001171 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001172 }
1173 }
Costin Manolache360e4542009-09-04 13:36:04 -07001174
Dianne Hackborn231cc602009-04-27 17:10:36 -07001175 /**
1176 * Return true if the pending status is true of any matching authorities.
1177 */
Fred Quintanaac9385e2009-06-22 18:00:59 -07001178 public boolean isSyncPending(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001179 synchronized (mAuthorities) {
1180 final int N = mSyncStatus.size();
1181 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001182 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001183 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1184 if (ainfo == null) {
1185 continue;
1186 }
1187 if (account != null && !ainfo.account.equals(account)) {
1188 continue;
1189 }
1190 if (ainfo.authority.equals(authority) && cur.pending) {
1191 return true;
1192 }
1193 }
1194 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
1196 }
1197
1198 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001199 * Return an array of the current sync status for all authorities. Note
1200 * that the objects inside the array are the real, live status objects,
1201 * so be careful what you do with them.
1202 */
1203 public ArrayList<SyncHistoryItem> getSyncHistory() {
1204 synchronized (mAuthorities) {
1205 final int N = mSyncHistory.size();
1206 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1207 for (int i=0; i<N; i++) {
1208 items.add(mSyncHistory.get(i));
1209 }
1210 return items;
1211 }
1212 }
Costin Manolache360e4542009-09-04 13:36:04 -07001213
Dianne Hackborn231cc602009-04-27 17:10:36 -07001214 /**
1215 * Return an array of the current per-day statistics. Note
1216 * that the objects inside the array are the real, live status objects,
1217 * so be careful what you do with them.
1218 */
1219 public DayStats[] getDayStatistics() {
1220 synchronized (mAuthorities) {
1221 DayStats[] ds = new DayStats[mDayStats.length];
1222 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1223 return ds;
1224 }
1225 }
Costin Manolache360e4542009-09-04 13:36:04 -07001226
Dianne Hackborn231cc602009-04-27 17:10:36 -07001227 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 * If sync is failing for any of the provider/accounts then determine the time at which it
1229 * started failing and return the earliest time over all the provider/accounts. If none are
1230 * failing then return 0.
1231 */
1232 public long getInitialSyncFailureTime() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001233 synchronized (mAuthorities) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001234 if (!mMasterSyncAutomatically) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001235 return 0;
1236 }
Costin Manolache360e4542009-09-04 13:36:04 -07001237
Dianne Hackborn231cc602009-04-27 17:10:36 -07001238 long oldest = 0;
1239 int i = mSyncStatus.size();
1240 while (i > 0) {
1241 i--;
1242 SyncStatusInfo stats = mSyncStatus.valueAt(i);
1243 AuthorityInfo authority = mAuthorities.get(stats.authorityId);
1244 if (authority != null && authority.enabled) {
1245 if (oldest == 0 || stats.initialFailureTime < oldest) {
1246 oldest = stats.initialFailureTime;
1247 }
1248 }
1249 }
Costin Manolache360e4542009-09-04 13:36:04 -07001250
Dianne Hackborn231cc602009-04-27 17:10:36 -07001251 return oldest;
1252 }
1253 }
Costin Manolache360e4542009-09-04 13:36:04 -07001254
Dianne Hackborn55280a92009-05-07 15:53:46 -07001255 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001256 mCal.setTimeInMillis(System.currentTimeMillis());
1257 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1258 if (mYear != mCal.get(Calendar.YEAR)) {
1259 mYear = mCal.get(Calendar.YEAR);
1260 mCal.clear();
1261 mCal.set(Calendar.YEAR, mYear);
1262 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1263 }
1264 return dayOfYear + mYearInDays;
1265 }
Costin Manolache360e4542009-09-04 13:36:04 -07001266
Dianne Hackborn231cc602009-04-27 17:10:36 -07001267 /**
1268 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001269 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001270 * @param accountName The name of the account for the authority.
1271 * @param authorityName The name of the authority itself.
1272 * @param tag If non-null, this will be used in a log message if the
1273 * requested authority does not exist.
1274 */
Dianne Hackborn7a135592009-05-06 00:28:37 -07001275 private AuthorityInfo getAuthorityLocked(Account accountName, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001276 String tag) {
1277 AccountInfo account = mAccounts.get(accountName);
1278 if (account == null) {
1279 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001280 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1281 Log.v(TAG, tag + ": unknown account " + accountName);
1282 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001283 }
1284 return null;
1285 }
1286 AuthorityInfo authority = account.authorities.get(authorityName);
1287 if (authority == null) {
1288 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001289 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1290 Log.v(TAG, tag + ": unknown authority " + authorityName);
1291 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001292 }
1293 return null;
1294 }
Costin Manolache360e4542009-09-04 13:36:04 -07001295
Dianne Hackborn231cc602009-04-27 17:10:36 -07001296 return authority;
1297 }
Costin Manolache360e4542009-09-04 13:36:04 -07001298
Dianne Hackborn7a135592009-05-06 00:28:37 -07001299 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001300 String authorityName, int ident, boolean doWrite) {
1301 AccountInfo account = mAccounts.get(accountName);
1302 if (account == null) {
1303 account = new AccountInfo(accountName);
1304 mAccounts.put(accountName, account);
1305 }
1306 AuthorityInfo authority = account.authorities.get(authorityName);
1307 if (authority == null) {
1308 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001309 ident = mNextAuthorityId;
1310 mNextAuthorityId++;
1311 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001312 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001313 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1314 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Fred Quintanab763ab22009-08-18 18:07:30 -07001315 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001316 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001317 authority = new AuthorityInfo(accountName, authorityName, ident);
1318 account.authorities.put(authorityName, authority);
1319 mAuthorities.put(ident, authority);
1320 if (doWrite) {
1321 writeAccountInfoLocked();
1322 }
1323 }
Costin Manolache360e4542009-09-04 13:36:04 -07001324
Dianne Hackborn231cc602009-04-27 17:10:36 -07001325 return authority;
1326 }
Costin Manolache360e4542009-09-04 13:36:04 -07001327
Fred Quintana77c560f2010-03-29 22:20:26 -07001328 private void removeAuthorityLocked(Account account, String authorityName, boolean doWrite) {
Fred Quintana7620f1a2010-03-16 15:58:44 -07001329 AccountInfo accountInfo = mAccounts.get(account);
1330 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001331 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1332 if (authorityInfo != null) {
1333 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001334 if (doWrite) {
1335 writeAccountInfoLocked();
1336 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001337 }
1338 }
1339 }
1340
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001341 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1342 synchronized (mAuthorities) {
1343 return getOrCreateSyncStatusLocked(authority.ident);
1344 }
1345 }
1346
Dianne Hackborn231cc602009-04-27 17:10:36 -07001347 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1348 SyncStatusInfo status = mSyncStatus.get(authorityId);
1349 if (status == null) {
1350 status = new SyncStatusInfo(authorityId);
1351 mSyncStatus.put(authorityId, status);
1352 }
1353 return status;
1354 }
Costin Manolache360e4542009-09-04 13:36:04 -07001355
Dianne Hackborn55280a92009-05-07 15:53:46 -07001356 public void writeAllState() {
1357 synchronized (mAuthorities) {
1358 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001359
Dianne Hackborn55280a92009-05-07 15:53:46 -07001360 if (mNumPendingFinished > 0) {
1361 // Only write these if they are out of date.
1362 writePendingOperationsLocked();
1363 }
Costin Manolache360e4542009-09-04 13:36:04 -07001364
Dianne Hackborn55280a92009-05-07 15:53:46 -07001365 // Just always write these... they are likely out of date.
1366 writeStatusLocked();
1367 writeStatisticsLocked();
1368 }
1369 }
Costin Manolache360e4542009-09-04 13:36:04 -07001370
Dianne Hackborn231cc602009-04-27 17:10:36 -07001371 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001372 * public for testing
1373 */
1374 public void clearAndReadState() {
1375 synchronized (mAuthorities) {
1376 mAuthorities.clear();
1377 mAccounts.clear();
1378 mPendingOperations.clear();
1379 mSyncStatus.clear();
1380 mSyncHistory.clear();
1381
1382 readAccountInfoLocked();
1383 readStatusLocked();
1384 readPendingOperationsLocked();
1385 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001386 readAndDeleteLegacyAccountInfoLocked();
1387 writeAccountInfoLocked();
1388 writeStatusLocked();
1389 writePendingOperationsLocked();
1390 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001391 }
1392 }
1393
1394 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001395 * Read all account information back in to the initial engine state.
1396 */
1397 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001398 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001399 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001401 fis = mAccountInfoFile.openRead();
1402 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1403 XmlPullParser parser = Xml.newPullParser();
1404 parser.setInput(fis, null);
1405 int eventType = parser.getEventType();
1406 while (eventType != XmlPullParser.START_TAG) {
1407 eventType = parser.next();
1408 }
1409 String tagName = parser.getName();
1410 if ("accounts".equals(tagName)) {
1411 String listen = parser.getAttributeValue(
1412 null, "listen-for-tickles");
Fred Quintanac2e46912010-03-15 16:10:44 -07001413 String versionString = parser.getAttributeValue(null, "version");
1414 int version;
1415 try {
1416 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1417 } catch (NumberFormatException e) {
1418 version = 0;
1419 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001420 String nextIdString = parser.getAttributeValue(null, "nextAuthorityId");
1421 try {
1422 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1423 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1424 } catch (NumberFormatException e) {
1425 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001426 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001427 mMasterSyncAutomatically = listen == null || Boolean.parseBoolean(listen);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001428 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001429 AuthorityInfo authority = null;
1430 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001431 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001432 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001433 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001434 if (parser.getDepth() == 2) {
1435 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001436 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001437 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001438 if (authority.ident > highestAuthorityId) {
1439 highestAuthorityId = authority.ident;
1440 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001441 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001442 } else if (parser.getDepth() == 3) {
1443 if ("periodicSync".equals(tagName) && authority != null) {
1444 periodicSync = parsePeriodicSync(parser, authority);
1445 }
1446 } else if (parser.getDepth() == 4 && periodicSync != null) {
1447 if ("extra".equals(tagName)) {
1448 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001449 }
1450 }
1451 }
1452 eventType = parser.next();
1453 } while (eventType != XmlPullParser.END_DOCUMENT);
1454 }
1455 } catch (XmlPullParserException e) {
1456 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001457 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001458 } catch (java.io.IOException e) {
1459 if (fis == null) Log.i(TAG, "No initial accounts");
1460 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001461 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001462 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001463 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001464 if (fis != null) {
1465 try {
1466 fis.close();
1467 } catch (java.io.IOException e1) {
1468 }
1469 }
1470 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001471
Fred Quintana77c560f2010-03-29 22:20:26 -07001472 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001473 }
Costin Manolache360e4542009-09-04 13:36:04 -07001474
Fred Quintanafb084402010-03-23 17:57:03 -07001475 /**
1476 * some authority names have changed. copy over their settings and delete the old ones
1477 * @return true if a change was made
1478 */
1479 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1480 boolean writeNeeded = false;
1481
1482 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1483 final int N = mAuthorities.size();
1484 for (int i=0; i<N; i++) {
1485 AuthorityInfo authority = mAuthorities.valueAt(i);
1486 // skip this authority if it isn't one of the renamed ones
1487 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1488 if (newAuthorityName == null) {
1489 continue;
1490 }
1491
1492 // remember this authority so we can remove it later. we can't remove it
1493 // now without messing up this loop iteration
1494 authoritiesToRemove.add(authority);
1495
1496 // this authority isn't enabled, no need to copy it to the new authority name since
1497 // the default is "disabled"
1498 if (!authority.enabled) {
1499 continue;
1500 }
1501
1502 // if we already have a record of this new authority then don't copy over the settings
1503 if (getAuthorityLocked(authority.account, newAuthorityName, "cleanup") != null) {
1504 continue;
1505 }
1506
1507 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
1508 newAuthorityName, -1 /* ident */, false /* doWrite */);
1509 newAuthority.enabled = true;
1510 writeNeeded = true;
1511 }
1512
1513 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001514 removeAuthorityLocked(authorityInfo.account, authorityInfo.authority,
1515 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001516 writeNeeded = true;
1517 }
1518
1519 return writeNeeded;
1520 }
1521
Fred Quintanac2e46912010-03-15 16:10:44 -07001522 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001523 AuthorityInfo authority = null;
1524 int id = -1;
1525 try {
1526 id = Integer.parseInt(parser.getAttributeValue(
1527 null, "id"));
1528 } catch (NumberFormatException e) {
1529 Log.e(TAG, "error parsing the id of the authority", e);
1530 } catch (NullPointerException e) {
1531 Log.e(TAG, "the id of the authority is null", e);
1532 }
1533 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001534 String authorityName = parser.getAttributeValue(null, "authority");
1535 String enabled = parser.getAttributeValue(null, "enabled");
1536 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001537 String accountName = parser.getAttributeValue(null, "account");
1538 String accountType = parser.getAttributeValue(null, "type");
1539 if (accountType == null) {
1540 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001541 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001542 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001543 authority = mAuthorities.get(id);
1544 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1545 + accountName + " auth=" + authorityName
1546 + " enabled=" + enabled
1547 + " syncable=" + syncable);
1548 if (authority == null) {
1549 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1550 authority = getOrCreateAuthorityLocked(
1551 new Account(accountName, accountType), authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001552 // If the version is 0 then we are upgrading from a file format that did not
1553 // know about periodic syncs. In that case don't clear the list since we
1554 // want the default, which is a daily periodioc sync.
1555 // Otherwise clear out this default list since we will populate it later with
1556 // the periodic sync descriptions that are read from the configuration file.
1557 if (version > 0) {
1558 authority.periodicSyncs.clear();
1559 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001560 }
1561 if (authority != null) {
1562 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1563 if ("unknown".equals(syncable)) {
1564 authority.syncable = -1;
1565 } else {
1566 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001567 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001568 }
1569 } else {
1570 Log.w(TAG, "Failure adding authority: account="
1571 + accountName + " auth=" + authorityName
1572 + " enabled=" + enabled
1573 + " syncable=" + syncable);
1574 }
1575 }
1576
1577 return authority;
1578 }
1579
1580 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1581 Bundle extras = new Bundle();
1582 String periodValue = parser.getAttributeValue(null, "period");
1583 final long period;
1584 try {
1585 period = Long.parseLong(periodValue);
1586 } catch (NumberFormatException e) {
1587 Log.e(TAG, "error parsing the period of a periodic sync", e);
1588 return null;
1589 } catch (NullPointerException e) {
1590 Log.e(TAG, "the period of a periodic sync is null", e);
1591 return null;
1592 }
1593 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1594 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001595
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001596 return periodicSync;
1597 }
1598
1599 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1600 final Bundle extras = periodicSync.first;
1601 String name = parser.getAttributeValue(null, "name");
1602 String type = parser.getAttributeValue(null, "type");
1603 String value1 = parser.getAttributeValue(null, "value1");
1604 String value2 = parser.getAttributeValue(null, "value2");
1605
1606 try {
1607 if ("long".equals(type)) {
1608 extras.putLong(name, Long.parseLong(value1));
1609 } else if ("integer".equals(type)) {
1610 extras.putInt(name, Integer.parseInt(value1));
1611 } else if ("double".equals(type)) {
1612 extras.putDouble(name, Double.parseDouble(value1));
1613 } else if ("float".equals(type)) {
1614 extras.putFloat(name, Float.parseFloat(value1));
1615 } else if ("boolean".equals(type)) {
1616 extras.putBoolean(name, Boolean.parseBoolean(value1));
1617 } else if ("string".equals(type)) {
1618 extras.putString(name, value1);
1619 } else if ("account".equals(type)) {
1620 extras.putParcelable(name, new Account(value1, value2));
1621 }
1622 } catch (NumberFormatException e) {
1623 Log.e(TAG, "error parsing bundle value", e);
1624 } catch (NullPointerException e) {
1625 Log.e(TAG, "error parsing bundle value", e);
1626 }
1627 }
1628
Dianne Hackborn231cc602009-04-27 17:10:36 -07001629 /**
1630 * Write all account information to the account file.
1631 */
1632 private void writeAccountInfoLocked() {
1633 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1634 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001635
Dianne Hackborn231cc602009-04-27 17:10:36 -07001636 try {
1637 fos = mAccountInfoFile.startWrite();
1638 XmlSerializer out = new FastXmlSerializer();
1639 out.setOutput(fos, "utf-8");
1640 out.startDocument(null, true);
1641 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001642
Dianne Hackborn231cc602009-04-27 17:10:36 -07001643 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001644 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Fred Quintana77c560f2010-03-29 22:20:26 -07001645 out.attribute(null, "nextAuthorityId", Integer.toString(mNextAuthorityId));
Fred Quintanaac9385e2009-06-22 18:00:59 -07001646 if (!mMasterSyncAutomatically) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001647 out.attribute(null, "listen-for-tickles", "false");
1648 }
Costin Manolache360e4542009-09-04 13:36:04 -07001649
Dianne Hackborn231cc602009-04-27 17:10:36 -07001650 final int N = mAuthorities.size();
1651 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001652 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001653 out.startTag(null, "authority");
1654 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001655 out.attribute(null, "account", authority.account.name);
1656 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001657 out.attribute(null, "authority", authority.authority);
Fred Quintanafb084402010-03-23 17:57:03 -07001658 out.attribute(null, "enabled", Boolean.toString(authority.enabled));
Fred Quintana5e787c42009-08-16 23:13:53 -07001659 if (authority.syncable < 0) {
1660 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001661 } else {
1662 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001663 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001664 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1665 out.startTag(null, "periodicSync");
1666 out.attribute(null, "period", Long.toString(periodicSync.second));
1667 final Bundle extras = periodicSync.first;
1668 for (String key : extras.keySet()) {
1669 out.startTag(null, "extra");
1670 out.attribute(null, "name", key);
1671 final Object value = extras.get(key);
1672 if (value instanceof Long) {
1673 out.attribute(null, "type", "long");
1674 out.attribute(null, "value1", value.toString());
1675 } else if (value instanceof Integer) {
1676 out.attribute(null, "type", "integer");
1677 out.attribute(null, "value1", value.toString());
1678 } else if (value instanceof Boolean) {
1679 out.attribute(null, "type", "boolean");
1680 out.attribute(null, "value1", value.toString());
1681 } else if (value instanceof Float) {
1682 out.attribute(null, "type", "float");
1683 out.attribute(null, "value1", value.toString());
1684 } else if (value instanceof Double) {
1685 out.attribute(null, "type", "double");
1686 out.attribute(null, "value1", value.toString());
1687 } else if (value instanceof String) {
1688 out.attribute(null, "type", "string");
1689 out.attribute(null, "value1", value.toString());
1690 } else if (value instanceof Account) {
1691 out.attribute(null, "type", "account");
1692 out.attribute(null, "value1", ((Account)value).name);
1693 out.attribute(null, "value2", ((Account)value).type);
1694 }
1695 out.endTag(null, "extra");
1696 }
1697 out.endTag(null, "periodicSync");
1698 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001699 out.endTag(null, "authority");
1700 }
Costin Manolache360e4542009-09-04 13:36:04 -07001701
Dianne Hackborn231cc602009-04-27 17:10:36 -07001702 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001703
Dianne Hackborn231cc602009-04-27 17:10:36 -07001704 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001705
Dianne Hackborn231cc602009-04-27 17:10:36 -07001706 mAccountInfoFile.finishWrite(fos);
1707 } catch (java.io.IOException e1) {
1708 Log.w(TAG, "Error writing accounts", e1);
1709 if (fos != null) {
1710 mAccountInfoFile.failWrite(fos);
1711 }
1712 }
1713 }
Costin Manolache360e4542009-09-04 13:36:04 -07001714
Dianne Hackborn231cc602009-04-27 17:10:36 -07001715 static int getIntColumn(Cursor c, String name) {
1716 return c.getInt(c.getColumnIndex(name));
1717 }
Costin Manolache360e4542009-09-04 13:36:04 -07001718
Dianne Hackborn231cc602009-04-27 17:10:36 -07001719 static long getLongColumn(Cursor c, String name) {
1720 return c.getLong(c.getColumnIndex(name));
1721 }
Costin Manolache360e4542009-09-04 13:36:04 -07001722
Dianne Hackborn231cc602009-04-27 17:10:36 -07001723 /**
1724 * Load sync engine state from the old syncmanager database, and then
1725 * erase it. Note that we don't deal with pending operations, active
1726 * sync, or history.
1727 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001728 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001729 // Look for old database to initialize from.
1730 File file = mContext.getDatabasePath("syncmanager.db");
1731 if (!file.exists()) {
1732 return;
1733 }
1734 String path = file.getPath();
1735 SQLiteDatabase db = null;
1736 try {
1737 db = SQLiteDatabase.openDatabase(path, null,
1738 SQLiteDatabase.OPEN_READONLY);
1739 } catch (SQLiteException e) {
1740 }
Costin Manolache360e4542009-09-04 13:36:04 -07001741
Dianne Hackborn231cc602009-04-27 17:10:36 -07001742 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001743 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001744
Dianne Hackborn231cc602009-04-27 17:10:36 -07001745 // Copy in all of the status information, as well as accounts.
1746 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1747 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1748 qb.setTables("stats, status");
1749 HashMap<String,String> map = new HashMap<String,String>();
1750 map.put("_id", "status._id as _id");
1751 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001752 if (hasType) {
1753 map.put("account_type", "stats.account_type as account_type");
1754 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001755 map.put("authority", "stats.authority as authority");
1756 map.put("totalElapsedTime", "totalElapsedTime");
1757 map.put("numSyncs", "numSyncs");
1758 map.put("numSourceLocal", "numSourceLocal");
1759 map.put("numSourcePoll", "numSourcePoll");
1760 map.put("numSourceServer", "numSourceServer");
1761 map.put("numSourceUser", "numSourceUser");
1762 map.put("lastSuccessSource", "lastSuccessSource");
1763 map.put("lastSuccessTime", "lastSuccessTime");
1764 map.put("lastFailureSource", "lastFailureSource");
1765 map.put("lastFailureTime", "lastFailureTime");
1766 map.put("lastFailureMesg", "lastFailureMesg");
1767 map.put("pending", "pending");
1768 qb.setProjectionMap(map);
1769 qb.appendWhere("stats._id = status.stats_id");
1770 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001772 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001773 String accountType = hasType
1774 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001775 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001776 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001778 String authorityName = c.getString(c.getColumnIndex("authority"));
1779 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Dianne Hackborn7a135592009-05-06 00:28:37 -07001780 new Account(accountName, accountType),
1781 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001782 if (authority != null) {
1783 int i = mSyncStatus.size();
1784 boolean found = false;
1785 SyncStatusInfo st = null;
1786 while (i > 0) {
1787 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001788 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001789 if (st.authorityId == authority.ident) {
1790 found = true;
1791 break;
1792 }
1793 }
1794 if (!found) {
1795 st = new SyncStatusInfo(authority.ident);
1796 mSyncStatus.put(authority.ident, st);
1797 }
1798 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1799 st.numSyncs = getIntColumn(c, "numSyncs");
1800 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1801 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1802 st.numSourceServer = getIntColumn(c, "numSourceServer");
1803 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001804 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001805 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1806 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1807 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1808 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1809 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1810 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 }
Costin Manolache360e4542009-09-04 13:36:04 -07001813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001815
Dianne Hackborn231cc602009-04-27 17:10:36 -07001816 // Retrieve the settings.
1817 qb = new SQLiteQueryBuilder();
1818 qb.setTables("settings");
1819 c = qb.query(db, null, null, null, null, null, null);
1820 while (c.moveToNext()) {
1821 String name = c.getString(c.getColumnIndex("name"));
1822 String value = c.getString(c.getColumnIndex("value"));
1823 if (name == null) continue;
1824 if (name.equals("listen_for_tickles")) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001825 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001826 } else if (name.startsWith("sync_provider_")) {
1827 String provider = name.substring("sync_provider_".length(),
1828 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001829 int i = mAuthorities.size();
1830 while (i > 0) {
1831 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001832 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001833 if (authority.authority.equals(provider)) {
1834 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001835 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001836 }
1837 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 }
Costin Manolache360e4542009-09-04 13:36:04 -07001840
Dianne Hackborn231cc602009-04-27 17:10:36 -07001841 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001842
Dianne Hackborn231cc602009-04-27 17:10:36 -07001843 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001844
Dianne Hackborn231cc602009-04-27 17:10:36 -07001845 (new File(path)).delete();
1846 }
1847 }
Costin Manolache360e4542009-09-04 13:36:04 -07001848
Dianne Hackborn231cc602009-04-27 17:10:36 -07001849 public static final int STATUS_FILE_END = 0;
1850 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001851
Dianne Hackborn231cc602009-04-27 17:10:36 -07001852 /**
1853 * Read all sync status back in to the initial engine state.
1854 */
1855 private void readStatusLocked() {
1856 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1857 try {
1858 byte[] data = mStatusFile.readFully();
1859 Parcel in = Parcel.obtain();
1860 in.unmarshall(data, 0, data.length);
1861 in.setDataPosition(0);
1862 int token;
1863 while ((token=in.readInt()) != STATUS_FILE_END) {
1864 if (token == STATUS_FILE_ITEM) {
1865 SyncStatusInfo status = new SyncStatusInfo(in);
1866 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1867 status.pending = false;
1868 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
1869 + status.authorityId);
1870 mSyncStatus.put(status.authorityId, status);
1871 }
1872 } else {
1873 // Ooops.
1874 Log.w(TAG, "Unknown status token: " + token);
1875 break;
1876 }
1877 }
1878 } catch (java.io.IOException e) {
1879 Log.i(TAG, "No initial status");
1880 }
1881 }
Costin Manolache360e4542009-09-04 13:36:04 -07001882
Dianne Hackborn231cc602009-04-27 17:10:36 -07001883 /**
1884 * Write all sync status to the sync status file.
1885 */
1886 private void writeStatusLocked() {
1887 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07001888
Dianne Hackborn231cc602009-04-27 17:10:36 -07001889 // The file is being written, so we don't need to have a scheduled
1890 // write until the next change.
1891 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07001892
Dianne Hackborn231cc602009-04-27 17:10:36 -07001893 FileOutputStream fos = null;
1894 try {
1895 fos = mStatusFile.startWrite();
1896 Parcel out = Parcel.obtain();
1897 final int N = mSyncStatus.size();
1898 for (int i=0; i<N; i++) {
1899 SyncStatusInfo status = mSyncStatus.valueAt(i);
1900 out.writeInt(STATUS_FILE_ITEM);
1901 status.writeToParcel(out, 0);
1902 }
1903 out.writeInt(STATUS_FILE_END);
1904 fos.write(out.marshall());
1905 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07001906
Dianne Hackborn231cc602009-04-27 17:10:36 -07001907 mStatusFile.finishWrite(fos);
1908 } catch (java.io.IOException e1) {
1909 Log.w(TAG, "Error writing status", e1);
1910 if (fos != null) {
1911 mStatusFile.failWrite(fos);
1912 }
1913 }
1914 }
Costin Manolache360e4542009-09-04 13:36:04 -07001915
Fred Quintana307da1a2010-01-21 14:24:20 -08001916 public static final int PENDING_OPERATION_VERSION = 2;
Costin Manolache360e4542009-09-04 13:36:04 -07001917
Dianne Hackborn231cc602009-04-27 17:10:36 -07001918 /**
1919 * Read all pending operations back in to the initial engine state.
1920 */
1921 private void readPendingOperationsLocked() {
1922 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
1923 try {
1924 byte[] data = mPendingFile.readFully();
1925 Parcel in = Parcel.obtain();
1926 in.unmarshall(data, 0, data.length);
1927 in.setDataPosition(0);
1928 final int SIZE = in.dataSize();
1929 while (in.dataPosition() < SIZE) {
1930 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08001931 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001932 Log.w(TAG, "Unknown pending operation version "
1933 + version + "; dropping all ops");
1934 break;
1935 }
1936 int authorityId = in.readInt();
1937 int syncSource = in.readInt();
1938 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08001939 boolean expedited;
1940 if (version == PENDING_OPERATION_VERSION) {
1941 expedited = in.readInt() != 0;
1942 } else {
1943 expedited = false;
1944 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001945 AuthorityInfo authority = mAuthorities.get(authorityId);
1946 if (authority != null) {
1947 Bundle extras = null;
1948 if (flatExtras != null) {
1949 extras = unflattenBundle(flatExtras);
1950 }
1951 PendingOperation op = new PendingOperation(
1952 authority.account, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08001953 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001954 op.authorityId = authorityId;
1955 op.flatExtras = flatExtras;
1956 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
1957 + " auth=" + op.authority
1958 + " src=" + op.syncSource
Fred Quintana307da1a2010-01-21 14:24:20 -08001959 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07001960 + " extras=" + op.extras);
1961 mPendingOperations.add(op);
1962 }
1963 }
1964 } catch (java.io.IOException e) {
1965 Log.i(TAG, "No initial pending operations");
1966 }
1967 }
Costin Manolache360e4542009-09-04 13:36:04 -07001968
Dianne Hackborn231cc602009-04-27 17:10:36 -07001969 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
1970 out.writeInt(PENDING_OPERATION_VERSION);
1971 out.writeInt(op.authorityId);
1972 out.writeInt(op.syncSource);
1973 if (op.flatExtras == null && op.extras != null) {
1974 op.flatExtras = flattenBundle(op.extras);
1975 }
1976 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08001977 out.writeInt(op.expedited ? 1 : 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001978 }
Costin Manolache360e4542009-09-04 13:36:04 -07001979
Dianne Hackborn231cc602009-04-27 17:10:36 -07001980 /**
1981 * Write all currently pending ops to the pending ops file.
1982 */
1983 private void writePendingOperationsLocked() {
1984 final int N = mPendingOperations.size();
1985 FileOutputStream fos = null;
1986 try {
1987 if (N == 0) {
1988 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
1989 mPendingFile.truncate();
1990 return;
1991 }
Costin Manolache360e4542009-09-04 13:36:04 -07001992
Dianne Hackborn231cc602009-04-27 17:10:36 -07001993 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
1994 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07001995
Dianne Hackborn231cc602009-04-27 17:10:36 -07001996 Parcel out = Parcel.obtain();
1997 for (int i=0; i<N; i++) {
1998 PendingOperation op = mPendingOperations.get(i);
1999 writePendingOperationLocked(op, out);
2000 }
2001 fos.write(out.marshall());
2002 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002003
Dianne Hackborn231cc602009-04-27 17:10:36 -07002004 mPendingFile.finishWrite(fos);
2005 } catch (java.io.IOException e1) {
2006 Log.w(TAG, "Error writing pending operations", e1);
2007 if (fos != null) {
2008 mPendingFile.failWrite(fos);
2009 }
2010 }
2011 }
Costin Manolache360e4542009-09-04 13:36:04 -07002012
Dianne Hackborn231cc602009-04-27 17:10:36 -07002013 /**
2014 * Append the given operation to the pending ops file; if unable to,
2015 * write all pending ops.
2016 */
2017 private void appendPendingOperationLocked(PendingOperation op) {
2018 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2019 FileOutputStream fos = null;
2020 try {
2021 fos = mPendingFile.openAppend();
2022 } catch (java.io.IOException e) {
2023 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2024 writePendingOperationsLocked();
2025 return;
2026 }
Costin Manolache360e4542009-09-04 13:36:04 -07002027
Dianne Hackborn231cc602009-04-27 17:10:36 -07002028 try {
2029 Parcel out = Parcel.obtain();
2030 writePendingOperationLocked(op, out);
2031 fos.write(out.marshall());
2032 out.recycle();
2033 } catch (java.io.IOException e1) {
2034 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002036 try {
2037 fos.close();
2038 } catch (java.io.IOException e2) {
2039 }
2040 }
2041 }
Costin Manolache360e4542009-09-04 13:36:04 -07002042
Dianne Hackborn231cc602009-04-27 17:10:36 -07002043 static private byte[] flattenBundle(Bundle bundle) {
2044 byte[] flatData = null;
2045 Parcel parcel = Parcel.obtain();
2046 try {
2047 bundle.writeToParcel(parcel, 0);
2048 flatData = parcel.marshall();
2049 } finally {
2050 parcel.recycle();
2051 }
2052 return flatData;
2053 }
Costin Manolache360e4542009-09-04 13:36:04 -07002054
Dianne Hackborn231cc602009-04-27 17:10:36 -07002055 static private Bundle unflattenBundle(byte[] flatData) {
2056 Bundle bundle;
2057 Parcel parcel = Parcel.obtain();
2058 try {
2059 parcel.unmarshall(flatData, 0, flatData.length);
2060 parcel.setDataPosition(0);
2061 bundle = parcel.readBundle();
2062 } catch (RuntimeException e) {
2063 // A RuntimeException is thrown if we were unable to parse the parcel.
2064 // Create an empty parcel in this case.
2065 bundle = new Bundle();
2066 } finally {
2067 parcel.recycle();
2068 }
2069 return bundle;
2070 }
Costin Manolache360e4542009-09-04 13:36:04 -07002071
Dianne Hackborn231cc602009-04-27 17:10:36 -07002072 public static final int STATISTICS_FILE_END = 0;
2073 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2074 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002075
Dianne Hackborn231cc602009-04-27 17:10:36 -07002076 /**
2077 * Read all sync statistics back in to the initial engine state.
2078 */
2079 private void readStatisticsLocked() {
2080 try {
2081 byte[] data = mStatisticsFile.readFully();
2082 Parcel in = Parcel.obtain();
2083 in.unmarshall(data, 0, data.length);
2084 in.setDataPosition(0);
2085 int token;
2086 int index = 0;
2087 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2088 if (token == STATISTICS_FILE_ITEM
2089 || token == STATISTICS_FILE_ITEM_OLD) {
2090 int day = in.readInt();
2091 if (token == STATISTICS_FILE_ITEM_OLD) {
2092 day = day - 2009 + 14245; // Magic!
2093 }
2094 DayStats ds = new DayStats(day);
2095 ds.successCount = in.readInt();
2096 ds.successTime = in.readLong();
2097 ds.failureCount = in.readInt();
2098 ds.failureTime = in.readLong();
2099 if (index < mDayStats.length) {
2100 mDayStats[index] = ds;
2101 index++;
2102 }
2103 } else {
2104 // Ooops.
2105 Log.w(TAG, "Unknown stats token: " + token);
2106 break;
2107 }
2108 }
2109 } catch (java.io.IOException e) {
2110 Log.i(TAG, "No initial statistics");
2111 }
2112 }
Costin Manolache360e4542009-09-04 13:36:04 -07002113
Dianne Hackborn231cc602009-04-27 17:10:36 -07002114 /**
2115 * Write all sync statistics to the sync status file.
2116 */
2117 private void writeStatisticsLocked() {
2118 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002119
Dianne Hackborn231cc602009-04-27 17:10:36 -07002120 // The file is being written, so we don't need to have a scheduled
2121 // write until the next change.
2122 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002123
Dianne Hackborn231cc602009-04-27 17:10:36 -07002124 FileOutputStream fos = null;
2125 try {
2126 fos = mStatisticsFile.startWrite();
2127 Parcel out = Parcel.obtain();
2128 final int N = mDayStats.length;
2129 for (int i=0; i<N; i++) {
2130 DayStats ds = mDayStats[i];
2131 if (ds == null) {
2132 break;
2133 }
2134 out.writeInt(STATISTICS_FILE_ITEM);
2135 out.writeInt(ds.day);
2136 out.writeInt(ds.successCount);
2137 out.writeLong(ds.successTime);
2138 out.writeInt(ds.failureCount);
2139 out.writeLong(ds.failureTime);
2140 }
2141 out.writeInt(STATISTICS_FILE_END);
2142 fos.write(out.marshall());
2143 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002144
Dianne Hackborn231cc602009-04-27 17:10:36 -07002145 mStatisticsFile.finishWrite(fos);
2146 } catch (java.io.IOException e1) {
2147 Log.w(TAG, "Error writing stats", e1);
2148 if (fos != null) {
2149 mStatisticsFile.failWrite(fos);
2150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 }
2152 }
2153}