blob: ef1db356fa26d61db5d01066eb90a4acb1833626 [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
Fred Quintanad9d2f112009-04-23 13:36:27 -070023import android.accounts.Account;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070026import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070028import android.os.Bundle;
29import android.os.Environment;
30import android.os.Handler;
31import android.os.Message;
32import android.os.Parcel;
33import android.os.RemoteCallbackList;
34import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.util.Log;
Jason parks1125d782011-01-12 09:47:26 -060036import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070037import android.util.SparseArray;
38import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039
Dianne Hackborn231cc602009-04-27 17:10:36 -070040import java.io.File;
41import java.io.FileInputStream;
42import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070044import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070046import java.util.Iterator;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080047import java.util.List;
Jason parks1125d782011-01-12 09:47:26 -060048import java.util.TimeZone;
49
50import org.xmlpull.v1.XmlPullParser;
51import org.xmlpull.v1.XmlPullParserException;
52import org.xmlpull.v1.XmlSerializer;
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
Dianne Hackborn043fcd92010-10-06 14:27:34 -070098 public static final Intent SYNC_CONNECTION_SETTING_CHANGED_INTENT =
Fred Quintanaac9385e2009-06-22 18:00:59 -070099 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.
Jason parks1125d782011-01-12 09:47:26 -0600322 File dataDir = Environment.getDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800323 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) {
Wink Savillea4288072010-10-12 12:36:38 -0700414 Log.d(TAG, "setSyncAutomatically: " + /*account +*/ ", provider " + providerName
Fred Quintana77c560f2010-03-29 22:20:26 -0700415 + " -> " + 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
Alon Albert744e310f2010-12-14 11:37:20 -0800528 public void clearAllBackoffs() {
529 boolean changed = false;
530 synchronized (mAuthorities) {
531 for (AccountInfo accountInfo : mAccounts.values()) {
532 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
533 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
534 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
535 if (Log.isLoggable(TAG, Log.VERBOSE)) {
536 Log.v(TAG, "clearAllBackoffs:"
537 + " authority:" + authorityInfo.authority
538 + " account:" + accountInfo.account.name
539 + " backoffTime was: " + authorityInfo.backoffTime
540 + " backoffDelay was: " + authorityInfo.backoffDelay);
541 }
542 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
543 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
544 changed = true;
545 }
546 }
547 }
548 }
549
550 if (changed) {
551 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
552 }
553 }
554
Fred Quintana307da1a2010-01-21 14:24:20 -0800555 public void setDelayUntilTime(Account account, String providerName, long delayUntil) {
556 if (Log.isLoggable(TAG, Log.VERBOSE)) {
557 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
558 + " -> delayUntil " + delayUntil);
559 }
560 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800561 AuthorityInfo authority = getOrCreateAuthorityLocked(
562 account, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800563 if (authority.delayUntil == delayUntil) {
564 return;
565 }
566 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800567 }
568
569 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
570 }
571
572 public long getDelayUntilTime(Account account, String providerName) {
573 synchronized (mAuthorities) {
574 AuthorityInfo authority = getAuthorityLocked(account, providerName, "getDelayUntil");
575 if (authority == null) {
576 return 0;
577 }
578 return authority.delayUntil;
579 }
580 }
581
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800582 private void updateOrRemovePeriodicSync(Account account, String providerName, Bundle extras,
583 long period, boolean add) {
584 if (period <= 0) {
585 period = 0;
586 }
587 if (extras == null) {
588 extras = new Bundle();
589 }
590 if (Log.isLoggable(TAG, Log.VERBOSE)) {
591 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", provider " + providerName
592 + " -> period " + period + ", extras " + extras);
593 }
594 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700595 try {
596 AuthorityInfo authority =
597 getOrCreateAuthorityLocked(account, providerName, -1, false);
598 if (add) {
599 // add this periodic sync if one with the same extras doesn't already
600 // exist in the periodicSyncs array
601 boolean alreadyPresent = false;
602 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
603 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
604 final Bundle existingExtras = syncInfo.first;
605 if (equals(existingExtras, extras)) {
606 if (syncInfo.second == period) {
607 return;
608 }
609 authority.periodicSyncs.set(i, Pair.create(extras, period));
610 alreadyPresent = true;
611 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800612 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700613 }
614 // if we added an entry to the periodicSyncs array also add an entry to
615 // the periodic syncs status to correspond to it
616 if (!alreadyPresent) {
617 authority.periodicSyncs.add(Pair.create(extras, period));
618 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
619 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
620 }
621 } else {
622 // remove any periodic syncs that match the authority and extras
623 SyncStatusInfo status = mSyncStatus.get(authority.ident);
624 boolean changed = false;
625 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
626 int i = 0;
627 while (iterator.hasNext()) {
628 Pair<Bundle, Long> syncInfo = iterator.next();
629 if (equals(syncInfo.first, extras)) {
630 iterator.remove();
631 changed = true;
632 // if we removed an entry from the periodicSyncs array also
633 // remove the corresponding entry from the status
634 if (status != null) {
635 status.removePeriodicSyncTime(i);
636 }
637 } else {
638 i++;
639 }
640 }
641 if (!changed) {
642 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800643 }
644 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700645 } finally {
646 writeAccountInfoLocked();
647 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800648 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800649 }
650
651 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
652 }
653
654 public void addPeriodicSync(Account account, String providerName, Bundle extras,
655 long pollFrequency) {
656 updateOrRemovePeriodicSync(account, providerName, extras, pollFrequency, true /* add */);
657 }
658
659 public void removePeriodicSync(Account account, String providerName, Bundle extras) {
660 updateOrRemovePeriodicSync(account, providerName, extras, 0 /* period, ignored */,
661 false /* remove */);
662 }
663
664 public List<PeriodicSync> getPeriodicSyncs(Account account, String providerName) {
665 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
666 synchronized (mAuthorities) {
667 AuthorityInfo authority = getAuthorityLocked(account, providerName, "getPeriodicSyncs");
668 if (authority != null) {
669 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
670 syncs.add(new PeriodicSync(account, providerName, item.first, item.second));
671 }
672 }
673 }
674 return syncs;
675 }
676
Fred Quintanaac9385e2009-06-22 18:00:59 -0700677 public void setMasterSyncAutomatically(boolean flag) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700678 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700679 if (mMasterSyncAutomatically == flag) {
680 return;
681 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700682 mMasterSyncAutomatically = flag;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700683 writeAccountInfoLocked();
684 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700685 if (flag) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800686 ContentResolver.requestSync(null, null, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700687 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700688 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
689 mContext.sendBroadcast(SYNC_CONNECTION_SETTING_CHANGED_INTENT);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691
Fred Quintanaac9385e2009-06-22 18:00:59 -0700692 public boolean getMasterSyncAutomatically() {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700693 synchronized (mAuthorities) {
Fred Quintanaac9385e2009-06-22 18:00:59 -0700694 return mMasterSyncAutomatically;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700695 }
696 }
Costin Manolache360e4542009-09-04 13:36:04 -0700697
Fred Quintana1bbcd102010-02-10 10:04:33 -0800698 public AuthorityInfo getOrCreateAuthority(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700699 synchronized (mAuthorities) {
Fred Quintana1bbcd102010-02-10 10:04:33 -0800700 return getOrCreateAuthorityLocked(account, authority,
701 -1 /* assign a new identifier if creating a new authority */,
702 true /* write to storage if this results in a change */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700703 }
704 }
Costin Manolache360e4542009-09-04 13:36:04 -0700705
Fred Quintana7620f1a2010-03-16 15:58:44 -0700706 public void removeAuthority(Account account, String authority) {
707 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700708 removeAuthorityLocked(account, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700709 }
710 }
711
Dianne Hackborn231cc602009-04-27 17:10:36 -0700712 public AuthorityInfo getAuthority(int authorityId) {
713 synchronized (mAuthorities) {
714 return mAuthorities.get(authorityId);
715 }
716 }
Costin Manolache360e4542009-09-04 13:36:04 -0700717
Dianne Hackborn231cc602009-04-27 17:10:36 -0700718 /**
719 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700720 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700721 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700722 public boolean isSyncActive(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700723 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -0700724 for (SyncInfo syncInfo : mCurrentSyncs) {
725 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700726 if (ainfo != null && ainfo.account.equals(account)
727 && ainfo.authority.equals(authority)) {
728 return true;
729 }
730 }
731 }
Costin Manolache360e4542009-09-04 13:36:04 -0700732
Dianne Hackborn231cc602009-04-27 17:10:36 -0700733 return false;
734 }
Costin Manolache360e4542009-09-04 13:36:04 -0700735
Dianne Hackborn231cc602009-04-27 17:10:36 -0700736 public PendingOperation insertIntoPending(PendingOperation op) {
737 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700738 if (Log.isLoggable(TAG, Log.VERBOSE)) {
739 Log.v(TAG, "insertIntoPending: account=" + op.account
Dianne Hackborn231cc602009-04-27 17:10:36 -0700740 + " auth=" + op.authority
741 + " src=" + op.syncSource
742 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700743 }
Costin Manolache360e4542009-09-04 13:36:04 -0700744
Dianne Hackborn231cc602009-04-27 17:10:36 -0700745 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account,
746 op.authority,
747 -1 /* desired identifier */,
748 true /* write accounts to storage */);
749 if (authority == null) {
750 return null;
751 }
Costin Manolache360e4542009-09-04 13:36:04 -0700752
Dianne Hackborn231cc602009-04-27 17:10:36 -0700753 op = new PendingOperation(op);
754 op.authorityId = authority.ident;
755 mPendingOperations.add(op);
756 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700757
Dianne Hackborn231cc602009-04-27 17:10:36 -0700758 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
759 status.pending = true;
760 }
Costin Manolache360e4542009-09-04 13:36:04 -0700761
Fred Quintanaac9385e2009-06-22 18:00:59 -0700762 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700763 return op;
764 }
765
766 public boolean deleteFromPending(PendingOperation op) {
767 boolean res = false;
768 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700769 if (Log.isLoggable(TAG, Log.VERBOSE)) {
770 Log.v(TAG, "deleteFromPending: account=" + op.account
Dianne Hackborn231cc602009-04-27 17:10:36 -0700771 + " auth=" + op.authority
772 + " src=" + op.syncSource
773 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700774 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700775 if (mPendingOperations.remove(op)) {
776 if (mPendingOperations.size() == 0
777 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
778 writePendingOperationsLocked();
779 mNumPendingFinished = 0;
780 } else {
781 mNumPendingFinished++;
782 }
Costin Manolache360e4542009-09-04 13:36:04 -0700783
Dianne Hackborn231cc602009-04-27 17:10:36 -0700784 AuthorityInfo authority = getAuthorityLocked(op.account, op.authority,
785 "deleteFromPending");
786 if (authority != null) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700787 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "removing - " + authority);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700788 final int N = mPendingOperations.size();
789 boolean morePending = false;
790 for (int i=0; i<N; i++) {
791 PendingOperation cur = mPendingOperations.get(i);
792 if (cur.account.equals(op.account)
793 && cur.authority.equals(op.authority)) {
794 morePending = true;
795 break;
796 }
797 }
Costin Manolache360e4542009-09-04 13:36:04 -0700798
Dianne Hackborn231cc602009-04-27 17:10:36 -0700799 if (!morePending) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700800 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700801 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
802 status.pending = false;
803 }
804 }
Costin Manolache360e4542009-09-04 13:36:04 -0700805
Dianne Hackborn231cc602009-04-27 17:10:36 -0700806 res = true;
807 }
808 }
Costin Manolache360e4542009-09-04 13:36:04 -0700809
Fred Quintanaac9385e2009-06-22 18:00:59 -0700810 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700811 return res;
812 }
813
814 public int clearPending() {
815 int num;
816 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700817 if (Log.isLoggable(TAG, Log.VERBOSE)) {
818 Log.v(TAG, "clearPending");
819 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700820 num = mPendingOperations.size();
821 mPendingOperations.clear();
822 final int N = mSyncStatus.size();
823 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -0700824 mSyncStatus.valueAt(i).pending = false;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700825 }
826 writePendingOperationsLocked();
827 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700828 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700829 return num;
830 }
831
832 /**
833 * Return a copy of the current array of pending operations. The
834 * PendingOperation objects are the real objects stored inside, so that
835 * they can be used with deleteFromPending().
836 */
837 public ArrayList<PendingOperation> getPendingOperations() {
838 synchronized (mAuthorities) {
839 return new ArrayList<PendingOperation>(mPendingOperations);
840 }
841 }
Costin Manolache360e4542009-09-04 13:36:04 -0700842
Dianne Hackborn231cc602009-04-27 17:10:36 -0700843 /**
844 * Return the number of currently pending operations.
845 */
846 public int getPendingOperationCount() {
847 synchronized (mAuthorities) {
848 return mPendingOperations.size();
849 }
850 }
Costin Manolache360e4542009-09-04 13:36:04 -0700851
Dianne Hackborn231cc602009-04-27 17:10:36 -0700852 /**
853 * Called when the set of account has changed, given the new array of
854 * active accounts.
855 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700856 public void doDatabaseCleanup(Account[] accounts) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700857 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700858 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.w(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700859 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
860 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
861 while (accIt.hasNext()) {
862 AccountInfo acc = accIt.next();
863 if (!ArrayUtils.contains(accounts, acc.account)) {
864 // This account no longer exists...
Fred Quintana77c560f2010-03-29 22:20:26 -0700865 if (Log.isLoggable(TAG, Log.VERBOSE)) {
866 Log.w(TAG, "Account removed: " + acc.account);
867 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700868 for (AuthorityInfo auth : acc.authorities.values()) {
869 removing.put(auth.ident, auth);
870 }
871 accIt.remove();
872 }
873 }
Costin Manolache360e4542009-09-04 13:36:04 -0700874
Dianne Hackborn231cc602009-04-27 17:10:36 -0700875 // Clean out all data structures.
876 int i = removing.size();
877 if (i > 0) {
878 while (i > 0) {
879 i--;
880 int ident = removing.keyAt(i);
881 mAuthorities.remove(ident);
882 int j = mSyncStatus.size();
883 while (j > 0) {
884 j--;
885 if (mSyncStatus.keyAt(j) == ident) {
886 mSyncStatus.remove(mSyncStatus.keyAt(j));
887 }
888 }
889 j = mSyncHistory.size();
890 while (j > 0) {
891 j--;
892 if (mSyncHistory.get(j).authorityId == ident) {
893 mSyncHistory.remove(j);
894 }
895 }
896 }
897 writeAccountInfoLocked();
898 writeStatusLocked();
899 writePendingOperationsLocked();
900 writeStatisticsLocked();
901 }
902 }
903 }
904
905 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700906 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
907 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700908 */
Fred Quintana918339a2010-10-05 14:00:39 -0700909 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
910 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700911 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -0700912 if (Log.isLoggable(TAG, Log.VERBOSE)) {
913 Log.v(TAG, "setActiveSync: account="
914 + activeSyncContext.mSyncOperation.account
915 + " auth=" + activeSyncContext.mSyncOperation.authority
916 + " src=" + activeSyncContext.mSyncOperation.syncSource
917 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700918 }
Fred Quintana918339a2010-10-05 14:00:39 -0700919 AuthorityInfo authority = getOrCreateAuthorityLocked(
920 activeSyncContext.mSyncOperation.account,
921 activeSyncContext.mSyncOperation.authority,
922 -1 /* assign a new identifier if creating a new authority */,
923 true /* write to storage if this results in a change */);
924 syncInfo = new SyncInfo(authority.ident,
925 authority.account, authority.authority,
926 activeSyncContext.mStartTime);
927 mCurrentSyncs.add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700928 }
Costin Manolache360e4542009-09-04 13:36:04 -0700929
Fred Quintana918339a2010-10-05 14:00:39 -0700930 reportActiveChange();
931 return syncInfo;
932 }
933
934 /**
935 * Called to indicate that a previously active sync is no longer active.
936 */
937 public void removeActiveSync(SyncInfo syncInfo) {
938 synchronized (mAuthorities) {
939 if (Log.isLoggable(TAG, Log.VERBOSE)) {
940 Log.v(TAG, "removeActiveSync: account="
941 + syncInfo.account + " auth=" + syncInfo.authority);
942 }
943 mCurrentSyncs.remove(syncInfo);
944 }
945
946 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700947 }
948
949 /**
950 * To allow others to send active change reports, to poke clients.
951 */
952 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -0700953 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700954 }
Costin Manolache360e4542009-09-04 13:36:04 -0700955
Dianne Hackborn231cc602009-04-27 17:10:36 -0700956 /**
957 * Note that sync has started for the given account and authority.
958 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700959 public long insertStartSyncEvent(Account accountName, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700960 long now, int source) {
961 long id;
962 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700963 if (Log.isLoggable(TAG, Log.VERBOSE)) {
964 Log.v(TAG, "insertStartSyncEvent: account=" + accountName
Dianne Hackborn231cc602009-04-27 17:10:36 -0700965 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -0700966 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700967 AuthorityInfo authority = getAuthorityLocked(accountName, authorityName,
968 "insertStartSyncEvent");
969 if (authority == null) {
970 return -1;
971 }
972 SyncHistoryItem item = new SyncHistoryItem();
973 item.authorityId = authority.ident;
974 item.historyId = mNextHistoryId++;
975 if (mNextHistoryId < 0) mNextHistoryId = 0;
976 item.eventTime = now;
977 item.source = source;
978 item.event = EVENT_START;
979 mSyncHistory.add(0, item);
980 while (mSyncHistory.size() > MAX_HISTORY) {
981 mSyncHistory.remove(mSyncHistory.size()-1);
982 }
983 id = item.historyId;
Fred Quintana77c560f2010-03-29 22:20:26 -0700984 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700985 }
Costin Manolache360e4542009-09-04 13:36:04 -0700986
Fred Quintanaac9385e2009-06-22 18:00:59 -0700987 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700988 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
990
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800991 public static boolean equals(Bundle b1, Bundle b2) {
992 if (b1.size() != b2.size()) {
993 return false;
994 }
995 if (b1.isEmpty()) {
996 return true;
997 }
998 for (String key : b1.keySet()) {
999 if (!b2.containsKey(key)) {
1000 return false;
1001 }
1002 if (!b1.get(key).equals(b2.get(key))) {
1003 return false;
1004 }
1005 }
1006 return true;
1007 }
1008
Fred Quintana77c560f2010-03-29 22:20:26 -07001009 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001011 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001012 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1013 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1014 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001015 SyncHistoryItem item = null;
1016 int i = mSyncHistory.size();
1017 while (i > 0) {
1018 i--;
1019 item = mSyncHistory.get(i);
1020 if (item.historyId == historyId) {
1021 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001023 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
Costin Manolache360e4542009-09-04 13:36:04 -07001025
Dianne Hackborn231cc602009-04-27 17:10:36 -07001026 if (item == null) {
1027 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1028 return;
1029 }
Costin Manolache360e4542009-09-04 13:36:04 -07001030
Dianne Hackborn231cc602009-04-27 17:10:36 -07001031 item.elapsedTime = elapsedTime;
1032 item.event = EVENT_STOP;
1033 item.mesg = resultMessage;
1034 item.downstreamActivity = downstreamActivity;
1035 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001036
Dianne Hackborn231cc602009-04-27 17:10:36 -07001037 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001038
Dianne Hackborn231cc602009-04-27 17:10:36 -07001039 status.numSyncs++;
1040 status.totalElapsedTime += elapsedTime;
1041 switch (item.source) {
1042 case SOURCE_LOCAL:
1043 status.numSourceLocal++;
1044 break;
1045 case SOURCE_POLL:
1046 status.numSourcePoll++;
1047 break;
1048 case SOURCE_USER:
1049 status.numSourceUser++;
1050 break;
1051 case SOURCE_SERVER:
1052 status.numSourceServer++;
1053 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001054 case SOURCE_PERIODIC:
1055 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001056 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001057 }
Costin Manolache360e4542009-09-04 13:36:04 -07001058
Dianne Hackborn231cc602009-04-27 17:10:36 -07001059 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001060 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001061 if (mDayStats[0] == null) {
1062 mDayStats[0] = new DayStats(day);
1063 } else if (day != mDayStats[0].day) {
1064 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1065 mDayStats[0] = new DayStats(day);
1066 writeStatisticsNow = true;
1067 } else if (mDayStats[0] == null) {
1068 }
1069 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001070
Dianne Hackborn231cc602009-04-27 17:10:36 -07001071 final long lastSyncTime = (item.eventTime + elapsedTime);
1072 boolean writeStatusNow = false;
1073 if (MESG_SUCCESS.equals(resultMessage)) {
1074 // - if successful, update the successful columns
1075 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1076 writeStatusNow = true;
1077 }
1078 status.lastSuccessTime = lastSyncTime;
1079 status.lastSuccessSource = item.source;
1080 status.lastFailureTime = 0;
1081 status.lastFailureSource = -1;
1082 status.lastFailureMesg = null;
1083 status.initialFailureTime = 0;
1084 ds.successCount++;
1085 ds.successTime += elapsedTime;
1086 } else if (!MESG_CANCELED.equals(resultMessage)) {
1087 if (status.lastFailureTime == 0) {
1088 writeStatusNow = true;
1089 }
1090 status.lastFailureTime = lastSyncTime;
1091 status.lastFailureSource = item.source;
1092 status.lastFailureMesg = resultMessage;
1093 if (status.initialFailureTime == 0) {
1094 status.initialFailureTime = lastSyncTime;
1095 }
1096 ds.failureCount++;
1097 ds.failureTime += elapsedTime;
1098 }
Costin Manolache360e4542009-09-04 13:36:04 -07001099
Dianne Hackborn231cc602009-04-27 17:10:36 -07001100 if (writeStatusNow) {
1101 writeStatusLocked();
1102 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1103 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1104 WRITE_STATUS_DELAY);
1105 }
1106 if (writeStatisticsNow) {
1107 writeStatisticsLocked();
1108 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1109 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1110 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001111 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001112 }
Costin Manolache360e4542009-09-04 13:36:04 -07001113
Fred Quintanaac9385e2009-06-22 18:00:59 -07001114 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001115 }
1116
1117 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001118 * Return a list of the currently active syncs. Note that the returned items are the
1119 * real, live active sync objects, so be careful what you do with it.
1120 */
1121 public List<SyncInfo> getCurrentSyncs() {
1122 synchronized (mAuthorities) {
1123 return new ArrayList<SyncInfo>(mCurrentSyncs);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001124 }
1125 }
Costin Manolache360e4542009-09-04 13:36:04 -07001126
Dianne Hackborn231cc602009-04-27 17:10:36 -07001127 /**
1128 * Return an array of the current sync status for all authorities. Note
1129 * that the objects inside the array are the real, live status objects,
1130 * so be careful what you do with them.
1131 */
1132 public ArrayList<SyncStatusInfo> getSyncStatus() {
1133 synchronized (mAuthorities) {
1134 final int N = mSyncStatus.size();
1135 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1136 for (int i=0; i<N; i++) {
1137 ops.add(mSyncStatus.valueAt(i));
1138 }
1139 return ops;
1140 }
1141 }
Costin Manolache360e4542009-09-04 13:36:04 -07001142
Dianne Hackborn231cc602009-04-27 17:10:36 -07001143 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001144 * Return an array of the current authorities. Note
1145 * that the objects inside the array are the real, live objects,
1146 * so be careful what you do with them.
1147 */
1148 public ArrayList<AuthorityInfo> getAuthorities() {
1149 synchronized (mAuthorities) {
1150 final int N = mAuthorities.size();
1151 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1152 for (int i=0; i<N; i++) {
1153 infos.add(mAuthorities.valueAt(i));
1154 }
1155 return infos;
1156 }
1157 }
1158
1159 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001160 * Returns the status that matches the authority and account.
1161 *
1162 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001163 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001164 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001165 */
Costin Manolacheb7520982009-09-02 18:03:05 -07001166 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, String authority) {
1167 if (account == null || authority == null) {
1168 throw new IllegalArgumentException();
1169 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001170 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001171 final int N = mSyncStatus.size();
1172 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001173 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001174 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001175
1176 if (ainfo != null && ainfo.authority.equals(authority) &&
1177 account.equals(ainfo.account)) {
1178 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001179 }
1180 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001181 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001182 }
1183 }
Costin Manolache360e4542009-09-04 13:36:04 -07001184
Dianne Hackborn231cc602009-04-27 17:10:36 -07001185 /**
1186 * Return true if the pending status is true of any matching authorities.
1187 */
Fred Quintanaac9385e2009-06-22 18:00:59 -07001188 public boolean isSyncPending(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001189 synchronized (mAuthorities) {
1190 final int N = mSyncStatus.size();
1191 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001192 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001193 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1194 if (ainfo == null) {
1195 continue;
1196 }
1197 if (account != null && !ainfo.account.equals(account)) {
1198 continue;
1199 }
1200 if (ainfo.authority.equals(authority) && cur.pending) {
1201 return true;
1202 }
1203 }
1204 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 }
1206 }
1207
1208 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001209 * Return an array of the current sync status for all authorities. Note
1210 * that the objects inside the array are the real, live status objects,
1211 * so be careful what you do with them.
1212 */
1213 public ArrayList<SyncHistoryItem> getSyncHistory() {
1214 synchronized (mAuthorities) {
1215 final int N = mSyncHistory.size();
1216 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1217 for (int i=0; i<N; i++) {
1218 items.add(mSyncHistory.get(i));
1219 }
1220 return items;
1221 }
1222 }
Costin Manolache360e4542009-09-04 13:36:04 -07001223
Dianne Hackborn231cc602009-04-27 17:10:36 -07001224 /**
1225 * Return an array of the current per-day statistics. Note
1226 * that the objects inside the array are the real, live status objects,
1227 * so be careful what you do with them.
1228 */
1229 public DayStats[] getDayStatistics() {
1230 synchronized (mAuthorities) {
1231 DayStats[] ds = new DayStats[mDayStats.length];
1232 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1233 return ds;
1234 }
1235 }
Costin Manolache360e4542009-09-04 13:36:04 -07001236
Dianne Hackborn231cc602009-04-27 17:10:36 -07001237 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 * If sync is failing for any of the provider/accounts then determine the time at which it
1239 * started failing and return the earliest time over all the provider/accounts. If none are
1240 * failing then return 0.
1241 */
1242 public long getInitialSyncFailureTime() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001243 synchronized (mAuthorities) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001244 if (!mMasterSyncAutomatically) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001245 return 0;
1246 }
Costin Manolache360e4542009-09-04 13:36:04 -07001247
Dianne Hackborn231cc602009-04-27 17:10:36 -07001248 long oldest = 0;
1249 int i = mSyncStatus.size();
1250 while (i > 0) {
1251 i--;
1252 SyncStatusInfo stats = mSyncStatus.valueAt(i);
1253 AuthorityInfo authority = mAuthorities.get(stats.authorityId);
1254 if (authority != null && authority.enabled) {
1255 if (oldest == 0 || stats.initialFailureTime < oldest) {
1256 oldest = stats.initialFailureTime;
1257 }
1258 }
1259 }
Costin Manolache360e4542009-09-04 13:36:04 -07001260
Dianne Hackborn231cc602009-04-27 17:10:36 -07001261 return oldest;
1262 }
1263 }
Costin Manolache360e4542009-09-04 13:36:04 -07001264
Dianne Hackborn55280a92009-05-07 15:53:46 -07001265 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001266 mCal.setTimeInMillis(System.currentTimeMillis());
1267 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1268 if (mYear != mCal.get(Calendar.YEAR)) {
1269 mYear = mCal.get(Calendar.YEAR);
1270 mCal.clear();
1271 mCal.set(Calendar.YEAR, mYear);
1272 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1273 }
1274 return dayOfYear + mYearInDays;
1275 }
Costin Manolache360e4542009-09-04 13:36:04 -07001276
Dianne Hackborn231cc602009-04-27 17:10:36 -07001277 /**
1278 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001279 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001280 * @param accountName The name of the account for the authority.
1281 * @param authorityName The name of the authority itself.
1282 * @param tag If non-null, this will be used in a log message if the
1283 * requested authority does not exist.
1284 */
Dianne Hackborn7a135592009-05-06 00:28:37 -07001285 private AuthorityInfo getAuthorityLocked(Account accountName, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001286 String tag) {
1287 AccountInfo account = mAccounts.get(accountName);
1288 if (account == null) {
1289 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001290 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1291 Log.v(TAG, tag + ": unknown account " + accountName);
1292 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001293 }
1294 return null;
1295 }
1296 AuthorityInfo authority = account.authorities.get(authorityName);
1297 if (authority == null) {
1298 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001299 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1300 Log.v(TAG, tag + ": unknown authority " + authorityName);
1301 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001302 }
1303 return null;
1304 }
Costin Manolache360e4542009-09-04 13:36:04 -07001305
Dianne Hackborn231cc602009-04-27 17:10:36 -07001306 return authority;
1307 }
Costin Manolache360e4542009-09-04 13:36:04 -07001308
Dianne Hackborn7a135592009-05-06 00:28:37 -07001309 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001310 String authorityName, int ident, boolean doWrite) {
1311 AccountInfo account = mAccounts.get(accountName);
1312 if (account == null) {
1313 account = new AccountInfo(accountName);
1314 mAccounts.put(accountName, account);
1315 }
1316 AuthorityInfo authority = account.authorities.get(authorityName);
1317 if (authority == null) {
1318 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001319 ident = mNextAuthorityId;
1320 mNextAuthorityId++;
1321 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001322 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001323 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1324 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Fred Quintanab763ab22009-08-18 18:07:30 -07001325 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001326 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001327 authority = new AuthorityInfo(accountName, authorityName, ident);
1328 account.authorities.put(authorityName, authority);
1329 mAuthorities.put(ident, authority);
1330 if (doWrite) {
1331 writeAccountInfoLocked();
1332 }
1333 }
Costin Manolache360e4542009-09-04 13:36:04 -07001334
Dianne Hackborn231cc602009-04-27 17:10:36 -07001335 return authority;
1336 }
Costin Manolache360e4542009-09-04 13:36:04 -07001337
Fred Quintana77c560f2010-03-29 22:20:26 -07001338 private void removeAuthorityLocked(Account account, String authorityName, boolean doWrite) {
Fred Quintana7620f1a2010-03-16 15:58:44 -07001339 AccountInfo accountInfo = mAccounts.get(account);
1340 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001341 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1342 if (authorityInfo != null) {
1343 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001344 if (doWrite) {
1345 writeAccountInfoLocked();
1346 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001347 }
1348 }
1349 }
1350
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001351 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1352 synchronized (mAuthorities) {
1353 return getOrCreateSyncStatusLocked(authority.ident);
1354 }
1355 }
1356
Dianne Hackborn231cc602009-04-27 17:10:36 -07001357 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1358 SyncStatusInfo status = mSyncStatus.get(authorityId);
1359 if (status == null) {
1360 status = new SyncStatusInfo(authorityId);
1361 mSyncStatus.put(authorityId, status);
1362 }
1363 return status;
1364 }
Costin Manolache360e4542009-09-04 13:36:04 -07001365
Dianne Hackborn55280a92009-05-07 15:53:46 -07001366 public void writeAllState() {
1367 synchronized (mAuthorities) {
1368 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001369
Dianne Hackborn55280a92009-05-07 15:53:46 -07001370 if (mNumPendingFinished > 0) {
1371 // Only write these if they are out of date.
1372 writePendingOperationsLocked();
1373 }
Costin Manolache360e4542009-09-04 13:36:04 -07001374
Dianne Hackborn55280a92009-05-07 15:53:46 -07001375 // Just always write these... they are likely out of date.
1376 writeStatusLocked();
1377 writeStatisticsLocked();
1378 }
1379 }
Costin Manolache360e4542009-09-04 13:36:04 -07001380
Dianne Hackborn231cc602009-04-27 17:10:36 -07001381 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001382 * public for testing
1383 */
1384 public void clearAndReadState() {
1385 synchronized (mAuthorities) {
1386 mAuthorities.clear();
1387 mAccounts.clear();
1388 mPendingOperations.clear();
1389 mSyncStatus.clear();
1390 mSyncHistory.clear();
1391
1392 readAccountInfoLocked();
1393 readStatusLocked();
1394 readPendingOperationsLocked();
1395 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001396 readAndDeleteLegacyAccountInfoLocked();
1397 writeAccountInfoLocked();
1398 writeStatusLocked();
1399 writePendingOperationsLocked();
1400 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001401 }
1402 }
1403
1404 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001405 * Read all account information back in to the initial engine state.
1406 */
1407 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001408 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001409 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001411 fis = mAccountInfoFile.openRead();
1412 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1413 XmlPullParser parser = Xml.newPullParser();
1414 parser.setInput(fis, null);
1415 int eventType = parser.getEventType();
1416 while (eventType != XmlPullParser.START_TAG) {
1417 eventType = parser.next();
1418 }
1419 String tagName = parser.getName();
1420 if ("accounts".equals(tagName)) {
1421 String listen = parser.getAttributeValue(
1422 null, "listen-for-tickles");
Fred Quintanac2e46912010-03-15 16:10:44 -07001423 String versionString = parser.getAttributeValue(null, "version");
1424 int version;
1425 try {
1426 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1427 } catch (NumberFormatException e) {
1428 version = 0;
1429 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001430 String nextIdString = parser.getAttributeValue(null, "nextAuthorityId");
1431 try {
1432 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1433 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1434 } catch (NumberFormatException e) {
1435 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001436 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001437 mMasterSyncAutomatically = listen == null || Boolean.parseBoolean(listen);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001438 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001439 AuthorityInfo authority = null;
1440 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001441 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001442 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001443 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001444 if (parser.getDepth() == 2) {
1445 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001446 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001447 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001448 if (authority.ident > highestAuthorityId) {
1449 highestAuthorityId = authority.ident;
1450 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001451 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001452 } else if (parser.getDepth() == 3) {
1453 if ("periodicSync".equals(tagName) && authority != null) {
1454 periodicSync = parsePeriodicSync(parser, authority);
1455 }
1456 } else if (parser.getDepth() == 4 && periodicSync != null) {
1457 if ("extra".equals(tagName)) {
1458 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001459 }
1460 }
1461 }
1462 eventType = parser.next();
1463 } while (eventType != XmlPullParser.END_DOCUMENT);
1464 }
1465 } catch (XmlPullParserException e) {
1466 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001467 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001468 } catch (java.io.IOException e) {
1469 if (fis == null) Log.i(TAG, "No initial accounts");
1470 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001471 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001472 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001473 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001474 if (fis != null) {
1475 try {
1476 fis.close();
1477 } catch (java.io.IOException e1) {
1478 }
1479 }
1480 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001481
Fred Quintana77c560f2010-03-29 22:20:26 -07001482 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001483 }
Costin Manolache360e4542009-09-04 13:36:04 -07001484
Fred Quintanafb084402010-03-23 17:57:03 -07001485 /**
1486 * some authority names have changed. copy over their settings and delete the old ones
1487 * @return true if a change was made
1488 */
1489 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1490 boolean writeNeeded = false;
1491
1492 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1493 final int N = mAuthorities.size();
1494 for (int i=0; i<N; i++) {
1495 AuthorityInfo authority = mAuthorities.valueAt(i);
1496 // skip this authority if it isn't one of the renamed ones
1497 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1498 if (newAuthorityName == null) {
1499 continue;
1500 }
1501
1502 // remember this authority so we can remove it later. we can't remove it
1503 // now without messing up this loop iteration
1504 authoritiesToRemove.add(authority);
1505
1506 // this authority isn't enabled, no need to copy it to the new authority name since
1507 // the default is "disabled"
1508 if (!authority.enabled) {
1509 continue;
1510 }
1511
1512 // if we already have a record of this new authority then don't copy over the settings
1513 if (getAuthorityLocked(authority.account, newAuthorityName, "cleanup") != null) {
1514 continue;
1515 }
1516
1517 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
1518 newAuthorityName, -1 /* ident */, false /* doWrite */);
1519 newAuthority.enabled = true;
1520 writeNeeded = true;
1521 }
1522
1523 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001524 removeAuthorityLocked(authorityInfo.account, authorityInfo.authority,
1525 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001526 writeNeeded = true;
1527 }
1528
1529 return writeNeeded;
1530 }
1531
Fred Quintanac2e46912010-03-15 16:10:44 -07001532 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001533 AuthorityInfo authority = null;
1534 int id = -1;
1535 try {
1536 id = Integer.parseInt(parser.getAttributeValue(
1537 null, "id"));
1538 } catch (NumberFormatException e) {
1539 Log.e(TAG, "error parsing the id of the authority", e);
1540 } catch (NullPointerException e) {
1541 Log.e(TAG, "the id of the authority is null", e);
1542 }
1543 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001544 String authorityName = parser.getAttributeValue(null, "authority");
1545 String enabled = parser.getAttributeValue(null, "enabled");
1546 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001547 String accountName = parser.getAttributeValue(null, "account");
1548 String accountType = parser.getAttributeValue(null, "type");
1549 if (accountType == null) {
1550 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001551 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001552 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001553 authority = mAuthorities.get(id);
1554 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1555 + accountName + " auth=" + authorityName
1556 + " enabled=" + enabled
1557 + " syncable=" + syncable);
1558 if (authority == null) {
1559 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1560 authority = getOrCreateAuthorityLocked(
1561 new Account(accountName, accountType), authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001562 // If the version is 0 then we are upgrading from a file format that did not
1563 // know about periodic syncs. In that case don't clear the list since we
1564 // want the default, which is a daily periodioc sync.
1565 // Otherwise clear out this default list since we will populate it later with
1566 // the periodic sync descriptions that are read from the configuration file.
1567 if (version > 0) {
1568 authority.periodicSyncs.clear();
1569 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001570 }
1571 if (authority != null) {
1572 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1573 if ("unknown".equals(syncable)) {
1574 authority.syncable = -1;
1575 } else {
1576 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001577 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001578 }
1579 } else {
1580 Log.w(TAG, "Failure adding authority: account="
1581 + accountName + " auth=" + authorityName
1582 + " enabled=" + enabled
1583 + " syncable=" + syncable);
1584 }
1585 }
1586
1587 return authority;
1588 }
1589
1590 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1591 Bundle extras = new Bundle();
1592 String periodValue = parser.getAttributeValue(null, "period");
1593 final long period;
1594 try {
1595 period = Long.parseLong(periodValue);
1596 } catch (NumberFormatException e) {
1597 Log.e(TAG, "error parsing the period of a periodic sync", e);
1598 return null;
1599 } catch (NullPointerException e) {
1600 Log.e(TAG, "the period of a periodic sync is null", e);
1601 return null;
1602 }
1603 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1604 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001605
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001606 return periodicSync;
1607 }
1608
1609 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1610 final Bundle extras = periodicSync.first;
1611 String name = parser.getAttributeValue(null, "name");
1612 String type = parser.getAttributeValue(null, "type");
1613 String value1 = parser.getAttributeValue(null, "value1");
1614 String value2 = parser.getAttributeValue(null, "value2");
1615
1616 try {
1617 if ("long".equals(type)) {
1618 extras.putLong(name, Long.parseLong(value1));
1619 } else if ("integer".equals(type)) {
1620 extras.putInt(name, Integer.parseInt(value1));
1621 } else if ("double".equals(type)) {
1622 extras.putDouble(name, Double.parseDouble(value1));
1623 } else if ("float".equals(type)) {
1624 extras.putFloat(name, Float.parseFloat(value1));
1625 } else if ("boolean".equals(type)) {
1626 extras.putBoolean(name, Boolean.parseBoolean(value1));
1627 } else if ("string".equals(type)) {
1628 extras.putString(name, value1);
1629 } else if ("account".equals(type)) {
1630 extras.putParcelable(name, new Account(value1, value2));
1631 }
1632 } catch (NumberFormatException e) {
1633 Log.e(TAG, "error parsing bundle value", e);
1634 } catch (NullPointerException e) {
1635 Log.e(TAG, "error parsing bundle value", e);
1636 }
1637 }
1638
Dianne Hackborn231cc602009-04-27 17:10:36 -07001639 /**
1640 * Write all account information to the account file.
1641 */
1642 private void writeAccountInfoLocked() {
1643 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1644 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001645
Dianne Hackborn231cc602009-04-27 17:10:36 -07001646 try {
1647 fos = mAccountInfoFile.startWrite();
1648 XmlSerializer out = new FastXmlSerializer();
1649 out.setOutput(fos, "utf-8");
1650 out.startDocument(null, true);
1651 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001652
Dianne Hackborn231cc602009-04-27 17:10:36 -07001653 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001654 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Fred Quintana77c560f2010-03-29 22:20:26 -07001655 out.attribute(null, "nextAuthorityId", Integer.toString(mNextAuthorityId));
Fred Quintanaac9385e2009-06-22 18:00:59 -07001656 if (!mMasterSyncAutomatically) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001657 out.attribute(null, "listen-for-tickles", "false");
1658 }
Costin Manolache360e4542009-09-04 13:36:04 -07001659
Dianne Hackborn231cc602009-04-27 17:10:36 -07001660 final int N = mAuthorities.size();
1661 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001662 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001663 out.startTag(null, "authority");
1664 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001665 out.attribute(null, "account", authority.account.name);
1666 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001667 out.attribute(null, "authority", authority.authority);
Fred Quintanafb084402010-03-23 17:57:03 -07001668 out.attribute(null, "enabled", Boolean.toString(authority.enabled));
Fred Quintana5e787c42009-08-16 23:13:53 -07001669 if (authority.syncable < 0) {
1670 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001671 } else {
1672 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001673 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001674 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1675 out.startTag(null, "periodicSync");
1676 out.attribute(null, "period", Long.toString(periodicSync.second));
1677 final Bundle extras = periodicSync.first;
1678 for (String key : extras.keySet()) {
1679 out.startTag(null, "extra");
1680 out.attribute(null, "name", key);
1681 final Object value = extras.get(key);
1682 if (value instanceof Long) {
1683 out.attribute(null, "type", "long");
1684 out.attribute(null, "value1", value.toString());
1685 } else if (value instanceof Integer) {
1686 out.attribute(null, "type", "integer");
1687 out.attribute(null, "value1", value.toString());
1688 } else if (value instanceof Boolean) {
1689 out.attribute(null, "type", "boolean");
1690 out.attribute(null, "value1", value.toString());
1691 } else if (value instanceof Float) {
1692 out.attribute(null, "type", "float");
1693 out.attribute(null, "value1", value.toString());
1694 } else if (value instanceof Double) {
1695 out.attribute(null, "type", "double");
1696 out.attribute(null, "value1", value.toString());
1697 } else if (value instanceof String) {
1698 out.attribute(null, "type", "string");
1699 out.attribute(null, "value1", value.toString());
1700 } else if (value instanceof Account) {
1701 out.attribute(null, "type", "account");
1702 out.attribute(null, "value1", ((Account)value).name);
1703 out.attribute(null, "value2", ((Account)value).type);
1704 }
1705 out.endTag(null, "extra");
1706 }
1707 out.endTag(null, "periodicSync");
1708 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001709 out.endTag(null, "authority");
1710 }
Costin Manolache360e4542009-09-04 13:36:04 -07001711
Dianne Hackborn231cc602009-04-27 17:10:36 -07001712 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001713
Dianne Hackborn231cc602009-04-27 17:10:36 -07001714 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001715
Dianne Hackborn231cc602009-04-27 17:10:36 -07001716 mAccountInfoFile.finishWrite(fos);
1717 } catch (java.io.IOException e1) {
1718 Log.w(TAG, "Error writing accounts", e1);
1719 if (fos != null) {
1720 mAccountInfoFile.failWrite(fos);
1721 }
1722 }
1723 }
Costin Manolache360e4542009-09-04 13:36:04 -07001724
Dianne Hackborn231cc602009-04-27 17:10:36 -07001725 static int getIntColumn(Cursor c, String name) {
1726 return c.getInt(c.getColumnIndex(name));
1727 }
Costin Manolache360e4542009-09-04 13:36:04 -07001728
Dianne Hackborn231cc602009-04-27 17:10:36 -07001729 static long getLongColumn(Cursor c, String name) {
1730 return c.getLong(c.getColumnIndex(name));
1731 }
Costin Manolache360e4542009-09-04 13:36:04 -07001732
Dianne Hackborn231cc602009-04-27 17:10:36 -07001733 /**
1734 * Load sync engine state from the old syncmanager database, and then
1735 * erase it. Note that we don't deal with pending operations, active
1736 * sync, or history.
1737 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001738 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001739 // Look for old database to initialize from.
1740 File file = mContext.getDatabasePath("syncmanager.db");
1741 if (!file.exists()) {
1742 return;
1743 }
1744 String path = file.getPath();
1745 SQLiteDatabase db = null;
1746 try {
1747 db = SQLiteDatabase.openDatabase(path, null,
1748 SQLiteDatabase.OPEN_READONLY);
1749 } catch (SQLiteException e) {
1750 }
Costin Manolache360e4542009-09-04 13:36:04 -07001751
Dianne Hackborn231cc602009-04-27 17:10:36 -07001752 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001753 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001754
Dianne Hackborn231cc602009-04-27 17:10:36 -07001755 // Copy in all of the status information, as well as accounts.
1756 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1757 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1758 qb.setTables("stats, status");
1759 HashMap<String,String> map = new HashMap<String,String>();
1760 map.put("_id", "status._id as _id");
1761 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001762 if (hasType) {
1763 map.put("account_type", "stats.account_type as account_type");
1764 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001765 map.put("authority", "stats.authority as authority");
1766 map.put("totalElapsedTime", "totalElapsedTime");
1767 map.put("numSyncs", "numSyncs");
1768 map.put("numSourceLocal", "numSourceLocal");
1769 map.put("numSourcePoll", "numSourcePoll");
1770 map.put("numSourceServer", "numSourceServer");
1771 map.put("numSourceUser", "numSourceUser");
1772 map.put("lastSuccessSource", "lastSuccessSource");
1773 map.put("lastSuccessTime", "lastSuccessTime");
1774 map.put("lastFailureSource", "lastFailureSource");
1775 map.put("lastFailureTime", "lastFailureTime");
1776 map.put("lastFailureMesg", "lastFailureMesg");
1777 map.put("pending", "pending");
1778 qb.setProjectionMap(map);
1779 qb.appendWhere("stats._id = status.stats_id");
1780 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001782 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001783 String accountType = hasType
1784 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001785 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001786 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001788 String authorityName = c.getString(c.getColumnIndex("authority"));
1789 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Dianne Hackborn7a135592009-05-06 00:28:37 -07001790 new Account(accountName, accountType),
1791 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001792 if (authority != null) {
1793 int i = mSyncStatus.size();
1794 boolean found = false;
1795 SyncStatusInfo st = null;
1796 while (i > 0) {
1797 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001798 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001799 if (st.authorityId == authority.ident) {
1800 found = true;
1801 break;
1802 }
1803 }
1804 if (!found) {
1805 st = new SyncStatusInfo(authority.ident);
1806 mSyncStatus.put(authority.ident, st);
1807 }
1808 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1809 st.numSyncs = getIntColumn(c, "numSyncs");
1810 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1811 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1812 st.numSourceServer = getIntColumn(c, "numSourceServer");
1813 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001814 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001815 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1816 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1817 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1818 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1819 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1820 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
Costin Manolache360e4542009-09-04 13:36:04 -07001823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001825
Dianne Hackborn231cc602009-04-27 17:10:36 -07001826 // Retrieve the settings.
1827 qb = new SQLiteQueryBuilder();
1828 qb.setTables("settings");
1829 c = qb.query(db, null, null, null, null, null, null);
1830 while (c.moveToNext()) {
1831 String name = c.getString(c.getColumnIndex("name"));
1832 String value = c.getString(c.getColumnIndex("value"));
1833 if (name == null) continue;
1834 if (name.equals("listen_for_tickles")) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001835 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001836 } else if (name.startsWith("sync_provider_")) {
1837 String provider = name.substring("sync_provider_".length(),
1838 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001839 int i = mAuthorities.size();
1840 while (i > 0) {
1841 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001842 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001843 if (authority.authority.equals(provider)) {
1844 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001845 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001846 }
1847 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 }
Costin Manolache360e4542009-09-04 13:36:04 -07001850
Dianne Hackborn231cc602009-04-27 17:10:36 -07001851 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001852
Dianne Hackborn231cc602009-04-27 17:10:36 -07001853 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001854
Dianne Hackborn231cc602009-04-27 17:10:36 -07001855 (new File(path)).delete();
1856 }
1857 }
Costin Manolache360e4542009-09-04 13:36:04 -07001858
Dianne Hackborn231cc602009-04-27 17:10:36 -07001859 public static final int STATUS_FILE_END = 0;
1860 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001861
Dianne Hackborn231cc602009-04-27 17:10:36 -07001862 /**
1863 * Read all sync status back in to the initial engine state.
1864 */
1865 private void readStatusLocked() {
1866 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1867 try {
1868 byte[] data = mStatusFile.readFully();
1869 Parcel in = Parcel.obtain();
1870 in.unmarshall(data, 0, data.length);
1871 in.setDataPosition(0);
1872 int token;
1873 while ((token=in.readInt()) != STATUS_FILE_END) {
1874 if (token == STATUS_FILE_ITEM) {
1875 SyncStatusInfo status = new SyncStatusInfo(in);
1876 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1877 status.pending = false;
1878 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
1879 + status.authorityId);
1880 mSyncStatus.put(status.authorityId, status);
1881 }
1882 } else {
1883 // Ooops.
1884 Log.w(TAG, "Unknown status token: " + token);
1885 break;
1886 }
1887 }
1888 } catch (java.io.IOException e) {
1889 Log.i(TAG, "No initial status");
1890 }
1891 }
Costin Manolache360e4542009-09-04 13:36:04 -07001892
Dianne Hackborn231cc602009-04-27 17:10:36 -07001893 /**
1894 * Write all sync status to the sync status file.
1895 */
1896 private void writeStatusLocked() {
1897 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07001898
Dianne Hackborn231cc602009-04-27 17:10:36 -07001899 // The file is being written, so we don't need to have a scheduled
1900 // write until the next change.
1901 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07001902
Dianne Hackborn231cc602009-04-27 17:10:36 -07001903 FileOutputStream fos = null;
1904 try {
1905 fos = mStatusFile.startWrite();
1906 Parcel out = Parcel.obtain();
1907 final int N = mSyncStatus.size();
1908 for (int i=0; i<N; i++) {
1909 SyncStatusInfo status = mSyncStatus.valueAt(i);
1910 out.writeInt(STATUS_FILE_ITEM);
1911 status.writeToParcel(out, 0);
1912 }
1913 out.writeInt(STATUS_FILE_END);
1914 fos.write(out.marshall());
1915 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07001916
Dianne Hackborn231cc602009-04-27 17:10:36 -07001917 mStatusFile.finishWrite(fos);
1918 } catch (java.io.IOException e1) {
1919 Log.w(TAG, "Error writing status", e1);
1920 if (fos != null) {
1921 mStatusFile.failWrite(fos);
1922 }
1923 }
1924 }
Costin Manolache360e4542009-09-04 13:36:04 -07001925
Fred Quintana307da1a2010-01-21 14:24:20 -08001926 public static final int PENDING_OPERATION_VERSION = 2;
Costin Manolache360e4542009-09-04 13:36:04 -07001927
Dianne Hackborn231cc602009-04-27 17:10:36 -07001928 /**
1929 * Read all pending operations back in to the initial engine state.
1930 */
1931 private void readPendingOperationsLocked() {
1932 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
1933 try {
1934 byte[] data = mPendingFile.readFully();
1935 Parcel in = Parcel.obtain();
1936 in.unmarshall(data, 0, data.length);
1937 in.setDataPosition(0);
1938 final int SIZE = in.dataSize();
1939 while (in.dataPosition() < SIZE) {
1940 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08001941 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001942 Log.w(TAG, "Unknown pending operation version "
1943 + version + "; dropping all ops");
1944 break;
1945 }
1946 int authorityId = in.readInt();
1947 int syncSource = in.readInt();
1948 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08001949 boolean expedited;
1950 if (version == PENDING_OPERATION_VERSION) {
1951 expedited = in.readInt() != 0;
1952 } else {
1953 expedited = false;
1954 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001955 AuthorityInfo authority = mAuthorities.get(authorityId);
1956 if (authority != null) {
Fred Quintana5695c7b2010-12-06 15:07:52 -08001957 Bundle extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001958 if (flatExtras != null) {
1959 extras = unflattenBundle(flatExtras);
Fred Quintana5695c7b2010-12-06 15:07:52 -08001960 } else {
1961 // if we are unable to parse the extras for whatever reason convert this
1962 // to a regular sync by creating an empty extras
1963 extras = new Bundle();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001964 }
1965 PendingOperation op = new PendingOperation(
1966 authority.account, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08001967 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001968 op.authorityId = authorityId;
1969 op.flatExtras = flatExtras;
1970 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
1971 + " auth=" + op.authority
1972 + " src=" + op.syncSource
Fred Quintana307da1a2010-01-21 14:24:20 -08001973 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07001974 + " extras=" + op.extras);
1975 mPendingOperations.add(op);
1976 }
1977 }
1978 } catch (java.io.IOException e) {
1979 Log.i(TAG, "No initial pending operations");
1980 }
1981 }
Costin Manolache360e4542009-09-04 13:36:04 -07001982
Dianne Hackborn231cc602009-04-27 17:10:36 -07001983 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
1984 out.writeInt(PENDING_OPERATION_VERSION);
1985 out.writeInt(op.authorityId);
1986 out.writeInt(op.syncSource);
1987 if (op.flatExtras == null && op.extras != null) {
1988 op.flatExtras = flattenBundle(op.extras);
1989 }
1990 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08001991 out.writeInt(op.expedited ? 1 : 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001992 }
Costin Manolache360e4542009-09-04 13:36:04 -07001993
Dianne Hackborn231cc602009-04-27 17:10:36 -07001994 /**
1995 * Write all currently pending ops to the pending ops file.
1996 */
1997 private void writePendingOperationsLocked() {
1998 final int N = mPendingOperations.size();
1999 FileOutputStream fos = null;
2000 try {
2001 if (N == 0) {
2002 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2003 mPendingFile.truncate();
2004 return;
2005 }
Costin Manolache360e4542009-09-04 13:36:04 -07002006
Dianne Hackborn231cc602009-04-27 17:10:36 -07002007 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2008 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07002009
Dianne Hackborn231cc602009-04-27 17:10:36 -07002010 Parcel out = Parcel.obtain();
2011 for (int i=0; i<N; i++) {
2012 PendingOperation op = mPendingOperations.get(i);
2013 writePendingOperationLocked(op, out);
2014 }
2015 fos.write(out.marshall());
2016 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002017
Dianne Hackborn231cc602009-04-27 17:10:36 -07002018 mPendingFile.finishWrite(fos);
2019 } catch (java.io.IOException e1) {
2020 Log.w(TAG, "Error writing pending operations", e1);
2021 if (fos != null) {
2022 mPendingFile.failWrite(fos);
2023 }
2024 }
2025 }
Costin Manolache360e4542009-09-04 13:36:04 -07002026
Dianne Hackborn231cc602009-04-27 17:10:36 -07002027 /**
2028 * Append the given operation to the pending ops file; if unable to,
2029 * write all pending ops.
2030 */
2031 private void appendPendingOperationLocked(PendingOperation op) {
2032 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2033 FileOutputStream fos = null;
2034 try {
2035 fos = mPendingFile.openAppend();
2036 } catch (java.io.IOException e) {
2037 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2038 writePendingOperationsLocked();
2039 return;
2040 }
Costin Manolache360e4542009-09-04 13:36:04 -07002041
Dianne Hackborn231cc602009-04-27 17:10:36 -07002042 try {
2043 Parcel out = Parcel.obtain();
2044 writePendingOperationLocked(op, out);
2045 fos.write(out.marshall());
2046 out.recycle();
2047 } catch (java.io.IOException e1) {
2048 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002050 try {
2051 fos.close();
2052 } catch (java.io.IOException e2) {
2053 }
2054 }
2055 }
Costin Manolache360e4542009-09-04 13:36:04 -07002056
Dianne Hackborn231cc602009-04-27 17:10:36 -07002057 static private byte[] flattenBundle(Bundle bundle) {
2058 byte[] flatData = null;
2059 Parcel parcel = Parcel.obtain();
2060 try {
2061 bundle.writeToParcel(parcel, 0);
2062 flatData = parcel.marshall();
2063 } finally {
2064 parcel.recycle();
2065 }
2066 return flatData;
2067 }
Costin Manolache360e4542009-09-04 13:36:04 -07002068
Dianne Hackborn231cc602009-04-27 17:10:36 -07002069 static private Bundle unflattenBundle(byte[] flatData) {
2070 Bundle bundle;
2071 Parcel parcel = Parcel.obtain();
2072 try {
2073 parcel.unmarshall(flatData, 0, flatData.length);
2074 parcel.setDataPosition(0);
2075 bundle = parcel.readBundle();
2076 } catch (RuntimeException e) {
2077 // A RuntimeException is thrown if we were unable to parse the parcel.
2078 // Create an empty parcel in this case.
2079 bundle = new Bundle();
2080 } finally {
2081 parcel.recycle();
2082 }
2083 return bundle;
2084 }
Costin Manolache360e4542009-09-04 13:36:04 -07002085
Dianne Hackborn231cc602009-04-27 17:10:36 -07002086 public static final int STATISTICS_FILE_END = 0;
2087 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2088 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002089
Dianne Hackborn231cc602009-04-27 17:10:36 -07002090 /**
2091 * Read all sync statistics back in to the initial engine state.
2092 */
2093 private void readStatisticsLocked() {
2094 try {
2095 byte[] data = mStatisticsFile.readFully();
2096 Parcel in = Parcel.obtain();
2097 in.unmarshall(data, 0, data.length);
2098 in.setDataPosition(0);
2099 int token;
2100 int index = 0;
2101 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2102 if (token == STATISTICS_FILE_ITEM
2103 || token == STATISTICS_FILE_ITEM_OLD) {
2104 int day = in.readInt();
2105 if (token == STATISTICS_FILE_ITEM_OLD) {
2106 day = day - 2009 + 14245; // Magic!
2107 }
2108 DayStats ds = new DayStats(day);
2109 ds.successCount = in.readInt();
2110 ds.successTime = in.readLong();
2111 ds.failureCount = in.readInt();
2112 ds.failureTime = in.readLong();
2113 if (index < mDayStats.length) {
2114 mDayStats[index] = ds;
2115 index++;
2116 }
2117 } else {
2118 // Ooops.
2119 Log.w(TAG, "Unknown stats token: " + token);
2120 break;
2121 }
2122 }
2123 } catch (java.io.IOException e) {
2124 Log.i(TAG, "No initial statistics");
2125 }
2126 }
Costin Manolache360e4542009-09-04 13:36:04 -07002127
Dianne Hackborn231cc602009-04-27 17:10:36 -07002128 /**
2129 * Write all sync statistics to the sync status file.
2130 */
2131 private void writeStatisticsLocked() {
2132 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002133
Dianne Hackborn231cc602009-04-27 17:10:36 -07002134 // The file is being written, so we don't need to have a scheduled
2135 // write until the next change.
2136 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002137
Dianne Hackborn231cc602009-04-27 17:10:36 -07002138 FileOutputStream fos = null;
2139 try {
2140 fos = mStatisticsFile.startWrite();
2141 Parcel out = Parcel.obtain();
2142 final int N = mDayStats.length;
2143 for (int i=0; i<N; i++) {
2144 DayStats ds = mDayStats[i];
2145 if (ds == null) {
2146 break;
2147 }
2148 out.writeInt(STATISTICS_FILE_ITEM);
2149 out.writeInt(ds.day);
2150 out.writeInt(ds.successCount);
2151 out.writeLong(ds.successTime);
2152 out.writeInt(ds.failureCount);
2153 out.writeLong(ds.failureTime);
2154 }
2155 out.writeInt(STATISTICS_FILE_END);
2156 fos.write(out.marshall());
2157 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002158
Dianne Hackborn231cc602009-04-27 17:10:36 -07002159 mStatisticsFile.finishWrite(fos);
2160 } catch (java.io.IOException e1) {
2161 Log.w(TAG, "Error writing stats", e1);
2162 if (fos != null) {
2163 mStatisticsFile.failWrite(fos);
2164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 }
2166 }
2167}