blob: 7a9fc65e4099e86b7b9b4e94d4471e199db0baac [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
Jason parksa3cdaa52011-01-13 14:15:43 -060023import org.xmlpull.v1.XmlPullParser;
24import org.xmlpull.v1.XmlPullParserException;
25import org.xmlpull.v1.XmlSerializer;
26
Fred Quintanad9d2f112009-04-23 13:36:27 -070027import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070028import android.accounts.AccountAndUser;
Yameng Huang2b5d0ea2011-01-11 14:00:19 +080029import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070034import android.os.Bundle;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.Message;
38import android.os.Parcel;
39import android.os.RemoteCallbackList;
40import android.os.RemoteException;
Ashish Sharma69d95de2012-04-11 17:27:24 -070041import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.util.Log;
Dianne Hackborn231cc602009-04-27 17:10:36 -070043import android.util.SparseArray;
44import android.util.Xml;
Jason parksa3cdaa52011-01-13 14:15:43 -060045import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046
Dianne Hackborn231cc602009-04-27 17:10:36 -070047import java.io.File;
48import java.io.FileInputStream;
49import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070051import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070053import java.util.Iterator;
Ashish Sharma69d95de2012-04-11 17:27:24 -070054import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060055import java.util.TimeZone;
Jason parksa3cdaa52011-01-13 14:15:43 -060056import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057
58/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070059 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070061 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 * @hide
63 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070064public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 private static final String TAG = "SyncManager";
Dianne Hackborn231cc602009-04-27 17:10:36 -070067 private static final boolean DEBUG_FILE = false;
Costin Manolache360e4542009-09-04 13:36:04 -070068
Amith Yamasani04e0d262012-02-14 11:50:53 -080069 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
70 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070071 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080072 private static final String XML_ATTR_ENABLED = "enabled";
73 private static final String XML_ATTR_USER = "user";
74 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
75
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080076 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
77
Dianne Hackborn231cc602009-04-27 17:10:36 -070078 // @VisibleForTesting
79 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080
Dianne Hackborn231cc602009-04-27 17:10:36 -070081 /** Enum value for a sync start event. */
82 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
Dianne Hackborn231cc602009-04-27 17:10:36 -070084 /** Enum value for a sync stop event. */
85 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
Dianne Hackborn231cc602009-04-27 17:10:36 -070087 // TODO: i18n -- grab these out of resources.
88 /** String names for the sync event types. */
89 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
Dianne Hackborn231cc602009-04-27 17:10:36 -070091 /** Enum value for a server-initiated sync. */
92 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Dianne Hackborn231cc602009-04-27 17:10:36 -070094 /** Enum value for a local-initiated sync. */
95 public static final int SOURCE_LOCAL = 1;
96 /**
97 * Enum value for a poll-based sync (e.g., upon connection to
98 * network)
99 */
100 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
Dianne Hackborn231cc602009-04-27 17:10:36 -0700102 /** Enum value for a user-initiated sync. */
103 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800105 /** Enum value for a periodic sync. */
106 public static final int SOURCE_PERIODIC = 4;
107
Fred Quintana307da1a2010-01-21 14:24:20 -0800108 public static final long NOT_IN_BACKOFF_MODE = -1;
109
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700110 public static final Intent SYNC_CONNECTION_SETTING_CHANGED_INTENT =
Fred Quintanaac9385e2009-06-22 18:00:59 -0700111 new Intent("com.android.sync.SYNC_CONN_STATUS_CHANGED");
112
Dianne Hackborn231cc602009-04-27 17:10:36 -0700113 // TODO: i18n -- grab these out of resources.
114 /** String names for the sync source types. */
115 public static final String[] SOURCES = { "SERVER",
116 "LOCAL",
117 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800118 "USER",
119 "PERIODIC" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
Dianne Hackborn231cc602009-04-27 17:10:36 -0700121 // The MESG column will contain one of these or one of the Error types.
122 public static final String MESG_SUCCESS = "success";
123 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700125 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700126
Dianne Hackborn231cc602009-04-27 17:10:36 -0700127 private static final int MSG_WRITE_STATUS = 1;
128 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700129
Dianne Hackborn231cc602009-04-27 17:10:36 -0700130 private static final int MSG_WRITE_STATISTICS = 2;
131 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700132
133 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700134
Fred Quintanac2e46912010-03-15 16:10:44 -0700135 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700136 private static final int ACCOUNTS_VERSION = 2;
137
138 private static HashMap<String, String> sAuthorityRenames;
139
140 static {
141 sAuthorityRenames = new HashMap<String, String>();
142 sAuthorityRenames.put("contacts", "com.android.contacts");
143 sAuthorityRenames.put("calendar", "com.android.calendar");
144 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700145
Dianne Hackborn231cc602009-04-27 17:10:36 -0700146 public static class PendingOperation {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700147 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800148 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700149 final int syncSource;
150 final String authority;
151 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800152 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700153
Dianne Hackborn231cc602009-04-27 17:10:36 -0700154 int authorityId;
155 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700156
Amith Yamasani04e0d262012-02-14 11:50:53 -0800157 PendingOperation(Account account, int userId, int source,
Fred Quintana307da1a2010-01-21 14:24:20 -0800158 String authority, Bundle extras, boolean expedited) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700159 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800160 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700161 this.syncSource = source;
162 this.authority = authority;
163 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800164 this.expedited = expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700165 this.authorityId = -1;
166 }
167
168 PendingOperation(PendingOperation other) {
169 this.account = other.account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800170 this.userId = other.userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700171 this.syncSource = other.syncSource;
172 this.authority = other.authority;
173 this.extras = other.extras;
174 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800175 this.expedited = other.expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 }
Costin Manolache360e4542009-09-04 13:36:04 -0700178
Dianne Hackborn231cc602009-04-27 17:10:36 -0700179 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800180 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700181 final HashMap<String, AuthorityInfo> authorities =
182 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700183
Amith Yamasani04e0d262012-02-14 11:50:53 -0800184 AccountInfo(AccountAndUser accountAndUser) {
185 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700186 }
187 }
Costin Manolache360e4542009-09-04 13:36:04 -0700188
Dianne Hackborn231cc602009-04-27 17:10:36 -0700189 public static class AuthorityInfo {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700190 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800191 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700192 final String authority;
193 final int ident;
194 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700195 int syncable;
Fred Quintana307da1a2010-01-21 14:24:20 -0800196 long backoffTime;
197 long backoffDelay;
198 long delayUntil;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800199 final ArrayList<Pair<Bundle, Long>> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700200
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700201 /**
202 * Copy constructor for making deep-ish copies. Only the bundles stored
203 * in periodic syncs can make unexpected changes.
204 *
205 * @param toCopy AuthorityInfo to be copied.
206 */
207 AuthorityInfo(AuthorityInfo toCopy) {
208 account = toCopy.account;
209 userId = toCopy.userId;
210 authority = toCopy.authority;
211 ident = toCopy.ident;
212 enabled = toCopy.enabled;
213 syncable = toCopy.syncable;
214 backoffTime = toCopy.backoffTime;
215 backoffDelay = toCopy.backoffDelay;
216 delayUntil = toCopy.delayUntil;
217 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
218 for (Pair<Bundle, Long> sync : toCopy.periodicSyncs) {
219 // Still not a perfect copy, because we are just copying the mappings.
220 periodicSyncs.add(Pair.create(new Bundle(sync.first), sync.second));
221 }
222 }
223
Amith Yamasani04e0d262012-02-14 11:50:53 -0800224 AuthorityInfo(Account account, int userId, String authority, int ident) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700225 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800226 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700227 this.authority = authority;
228 this.ident = ident;
Joe Onorato8294fad2009-07-15 16:08:44 -0700229 enabled = SYNC_ENABLED_DEFAULT;
Fred Quintana4a6679b2009-08-17 13:05:39 -0700230 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800231 backoffTime = -1; // if < 0 then we aren't in backoff mode
232 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800233 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
234 periodicSyncs.add(Pair.create(new Bundle(), DEFAULT_POLL_FREQUENCY_SECONDS));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700235 }
236 }
Costin Manolache360e4542009-09-04 13:36:04 -0700237
Dianne Hackborn231cc602009-04-27 17:10:36 -0700238 public static class SyncHistoryItem {
239 int authorityId;
240 int historyId;
241 long eventTime;
242 long elapsedTime;
243 int source;
244 int event;
245 long upstreamActivity;
246 long downstreamActivity;
247 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700248 boolean initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700249 }
Costin Manolache360e4542009-09-04 13:36:04 -0700250
Dianne Hackborn231cc602009-04-27 17:10:36 -0700251 public static class DayStats {
252 public final int day;
253 public int successCount;
254 public long successTime;
255 public int failureCount;
256 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700257
Dianne Hackborn231cc602009-04-27 17:10:36 -0700258 public DayStats(int day) {
259 this.day = day;
260 }
261 }
Costin Manolache360e4542009-09-04 13:36:04 -0700262
Amith Yamasani04e0d262012-02-14 11:50:53 -0800263 interface OnSyncRequestListener {
264 /**
265 * Called when a sync is needed on an account(s) due to some change in state.
266 * @param account
267 * @param userId
268 * @param authority
269 * @param extras
270 */
271 public void onSyncRequest(Account account, int userId, String authority, Bundle extras);
272 }
273
Dianne Hackborn231cc602009-04-27 17:10:36 -0700274 // Primary list of all syncable authorities. Also our global lock.
275 private final SparseArray<AuthorityInfo> mAuthorities =
276 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700277
Amith Yamasani04e0d262012-02-14 11:50:53 -0800278 private final HashMap<AccountAndUser, AccountInfo> mAccounts
279 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280
Dianne Hackborn231cc602009-04-27 17:10:36 -0700281 private final ArrayList<PendingOperation> mPendingOperations =
282 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700283
Amith Yamasani04e0d262012-02-14 11:50:53 -0800284 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
285 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700286
Dianne Hackborn231cc602009-04-27 17:10:36 -0700287 private final SparseArray<SyncStatusInfo> mSyncStatus =
288 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700289
Dianne Hackborn231cc602009-04-27 17:10:36 -0700290 private final ArrayList<SyncHistoryItem> mSyncHistory =
291 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700292
Dianne Hackborn231cc602009-04-27 17:10:36 -0700293 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
294 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700295
Fred Quintana77c560f2010-03-29 22:20:26 -0700296 private int mNextAuthorityId = 0;
297
Dianne Hackborn231cc602009-04-27 17:10:36 -0700298 // We keep 4 weeks of stats.
299 private final DayStats[] mDayStats = new DayStats[7*4];
300 private final Calendar mCal;
301 private int mYear;
302 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700303
Dianne Hackborn231cc602009-04-27 17:10:36 -0700304 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800305
Dianne Hackborn231cc602009-04-27 17:10:36 -0700306 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700307
Ashish Sharma69d95de2012-04-11 17:27:24 -0700308 private int mSyncRandomOffset;
309
Dianne Hackborn231cc602009-04-27 17:10:36 -0700310 /**
311 * This file contains the core engine state: all accounts and the
312 * settings for them. It must never be lost, and should be changed
313 * infrequently, so it is stored as an XML file.
314 */
315 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700316
Dianne Hackborn231cc602009-04-27 17:10:36 -0700317 /**
318 * This file contains the current sync status. We would like to retain
319 * it across boots, but its loss is not the end of the world, so we store
320 * this information as binary data.
321 */
322 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700323
Dianne Hackborn231cc602009-04-27 17:10:36 -0700324 /**
325 * This file contains sync statistics. This is purely debugging information
326 * so is written infrequently and can be thrown away at any time.
327 */
328 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700329
Dianne Hackborn231cc602009-04-27 17:10:36 -0700330 /**
331 * This file contains the pending sync operations. It is a binary file,
332 * which must be updated every time an operation is added or removed,
333 * so we have special handling of it.
334 */
335 private final AtomicFile mPendingFile;
336 private static final int PENDING_FINISH_TO_WRITE = 4;
337 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700338
Dianne Hackborn231cc602009-04-27 17:10:36 -0700339 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800340 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800341 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800342
343 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700344
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800345 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700348
Dianne Hackborn231cc602009-04-27 17:10:36 -0700349 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700350
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800351 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
352 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
353
Dianne Hackborn231cc602009-04-27 17:10:36 -0700354 File systemDir = new File(dataDir, "system");
355 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800356 syncDir.mkdirs();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700357 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
358 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
359 mPendingFile = new AtomicFile(new File(syncDir, "pending.bin"));
360 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700361
Dianne Hackborn231cc602009-04-27 17:10:36 -0700362 readAccountInfoLocked();
363 readStatusLocked();
364 readPendingOperationsLocked();
365 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700366 readAndDeleteLegacyAccountInfoLocked();
367 writeAccountInfoLocked();
368 writeStatusLocked();
369 writePendingOperationsLocked();
370 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 }
372
373 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800374 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 }
376
377 public static void init(Context context) {
378 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800379 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800381 // This call will return the correct directory whether Encrypted File Systems is
382 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600383 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800384 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 }
386
387 public static SyncStorageEngine getSingleton() {
388 if (sSyncStorageEngine == null) {
389 throw new IllegalStateException("not initialized");
390 }
391 return sSyncStorageEngine;
392 }
393
Amith Yamasani04e0d262012-02-14 11:50:53 -0800394 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
395 if (mSyncRequestListener == null) {
396 mSyncRequestListener = listener;
397 }
398 }
399
Dianne Hackborn231cc602009-04-27 17:10:36 -0700400 @Override public void handleMessage(Message msg) {
401 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700402 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700403 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700404 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700405 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700406 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700407 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 }
409 }
410 }
Costin Manolache360e4542009-09-04 13:36:04 -0700411
Ashish Sharma69d95de2012-04-11 17:27:24 -0700412 public int getSyncRandomOffset() {
413 return mSyncRandomOffset;
414 }
415
Dianne Hackborn231cc602009-04-27 17:10:36 -0700416 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
417 synchronized (mAuthorities) {
418 mChangeListeners.register(callback, mask);
419 }
420 }
Costin Manolache360e4542009-09-04 13:36:04 -0700421
Dianne Hackborn231cc602009-04-27 17:10:36 -0700422 public void removeStatusChangeListener(ISyncStatusObserver callback) {
423 synchronized (mAuthorities) {
424 mChangeListeners.unregister(callback);
425 }
426 }
Costin Manolache360e4542009-09-04 13:36:04 -0700427
Dianne Hackborn231cc602009-04-27 17:10:36 -0700428 private void reportChange(int which) {
429 ArrayList<ISyncStatusObserver> reports = null;
430 synchronized (mAuthorities) {
431 int i = mChangeListeners.beginBroadcast();
432 while (i > 0) {
433 i--;
434 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
435 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 continue;
437 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700438 if (reports == null) {
439 reports = new ArrayList<ISyncStatusObserver>(i);
440 }
441 reports.add(mChangeListeners.getBroadcastItem(i));
442 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700443 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700444 }
Costin Manolache360e4542009-09-04 13:36:04 -0700445
Fred Quintana77c560f2010-03-29 22:20:26 -0700446 if (Log.isLoggable(TAG, Log.VERBOSE)) {
447 Log.v(TAG, "reportChange " + which + " to: " + reports);
448 }
Costin Manolache360e4542009-09-04 13:36:04 -0700449
Dianne Hackborn231cc602009-04-27 17:10:36 -0700450 if (reports != null) {
451 int i = reports.size();
452 while (i > 0) {
453 i--;
454 try {
455 reports.get(i).onStatusChanged(which);
456 } catch (RemoteException e) {
457 // The remote callback list will take care of this for us.
458 }
459 }
460 }
461 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700462
Amith Yamasani04e0d262012-02-14 11:50:53 -0800463 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700464 synchronized (mAuthorities) {
465 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800466 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700467 "getSyncAutomatically");
468 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700469 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700470
Dianne Hackborn231cc602009-04-27 17:10:36 -0700471 int i = mAuthorities.size();
472 while (i > 0) {
473 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700474 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700475 if (authority.authority.equals(providerName)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800476 && authority.userId == userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700477 && authority.enabled) {
478 return true;
479 }
480 }
481 return false;
482 }
483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484
Amith Yamasani04e0d262012-02-14 11:50:53 -0800485 public void setSyncAutomatically(Account account, int userId, String providerName,
486 boolean sync) {
487 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
488 + ", user " + userId + " -> " + sync);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700489 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800490 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
491 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700492 if (authority.enabled == sync) {
493 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
494 return;
495 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700496 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700497 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700499
Fred Quintana77c560f2010-03-29 22:20:26 -0700500 if (sync) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800501 requestSync(account, userId, providerName, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700502 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700503 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 }
505
Amith Yamasani04e0d262012-02-14 11:50:53 -0800506 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700507 synchronized (mAuthorities) {
508 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800509 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintana5e787c42009-08-16 23:13:53 -0700510 "getIsSyncable");
511 if (authority == null) {
512 return -1;
513 }
514 return authority.syncable;
515 }
516
517 int i = mAuthorities.size();
518 while (i > 0) {
519 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700520 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700521 if (authority.authority.equals(providerName)) {
522 return authority.syncable;
523 }
524 }
525 return -1;
526 }
527 }
528
Amith Yamasani04e0d262012-02-14 11:50:53 -0800529 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700530 if (syncable > 1) {
531 syncable = 1;
532 } else if (syncable < -1) {
533 syncable = -1;
534 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800535 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName
536 + ", user " + userId + " -> " + syncable);
Fred Quintana5e787c42009-08-16 23:13:53 -0700537 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800538 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
539 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700540 if (authority.syncable == syncable) {
541 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
542 return;
543 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700544 authority.syncable = syncable;
545 writeAccountInfoLocked();
546 }
547
Fred Quintana77c560f2010-03-29 22:20:26 -0700548 if (syncable > 0) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800549 requestSync(account, userId, providerName, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700550 }
551 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
552 }
553
Amith Yamasani04e0d262012-02-14 11:50:53 -0800554 public Pair<Long, Long> getBackoff(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800555 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800556 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
557 "getBackoff");
Fred Quintana307da1a2010-01-21 14:24:20 -0800558 if (authority == null || authority.backoffTime < 0) {
559 return null;
560 }
561 return Pair.create(authority.backoffTime, authority.backoffDelay);
562 }
563 }
564
Amith Yamasani04e0d262012-02-14 11:50:53 -0800565 public void setBackoff(Account account, int userId, String providerName,
Fred Quintana307da1a2010-01-21 14:24:20 -0800566 long nextSyncTime, long nextDelay) {
567 if (Log.isLoggable(TAG, Log.VERBOSE)) {
568 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800569 + ", user " + userId
Fred Quintana307da1a2010-01-21 14:24:20 -0800570 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
571 }
572 boolean changed = false;
573 synchronized (mAuthorities) {
574 if (account == null || providerName == null) {
575 for (AccountInfo accountInfo : mAccounts.values()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800576 if (account != null && !account.equals(accountInfo.accountAndUser.account)
577 && userId != accountInfo.accountAndUser.userId) {
578 continue;
579 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800580 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
581 if (providerName != null && !providerName.equals(authorityInfo.authority)) {
582 continue;
583 }
584 if (authorityInfo.backoffTime != nextSyncTime
585 || authorityInfo.backoffDelay != nextDelay) {
586 authorityInfo.backoffTime = nextSyncTime;
587 authorityInfo.backoffDelay = nextDelay;
588 changed = true;
589 }
590 }
591 }
592 } else {
593 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800594 getOrCreateAuthorityLocked(account, userId, providerName, -1 /* ident */,
595 true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800596 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
597 return;
598 }
599 authority.backoffTime = nextSyncTime;
600 authority.backoffDelay = nextDelay;
601 changed = true;
602 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800603 }
604
605 if (changed) {
606 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
607 }
608 }
609
Alon Alberted1d2532011-02-15 14:02:14 -0800610 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800611 boolean changed = false;
612 synchronized (mAuthorities) {
613 for (AccountInfo accountInfo : mAccounts.values()) {
614 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
615 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
616 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
617 if (Log.isLoggable(TAG, Log.VERBOSE)) {
618 Log.v(TAG, "clearAllBackoffs:"
619 + " authority:" + authorityInfo.authority
Amith Yamasani04e0d262012-02-14 11:50:53 -0800620 + " account:" + accountInfo.accountAndUser.account.name
621 + " user:" + accountInfo.accountAndUser.userId
Alon Albert744e310f2010-12-14 11:37:20 -0800622 + " backoffTime was: " + authorityInfo.backoffTime
623 + " backoffDelay was: " + authorityInfo.backoffDelay);
624 }
625 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
626 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800627 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
628 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
Alon Albert744e310f2010-12-14 11:37:20 -0800629 changed = true;
630 }
631 }
632 }
633 }
634
635 if (changed) {
636 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
637 }
638 }
639
Amith Yamasani04e0d262012-02-14 11:50:53 -0800640 public void setDelayUntilTime(Account account, int userId, String providerName,
641 long delayUntil) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800642 if (Log.isLoggable(TAG, Log.VERBOSE)) {
643 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800644 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800645 }
646 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800647 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800648 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800649 if (authority.delayUntil == delayUntil) {
650 return;
651 }
652 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800653 }
654
655 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
656 }
657
Amith Yamasani04e0d262012-02-14 11:50:53 -0800658 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800659 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800660 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
661 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800662 if (authority == null) {
663 return 0;
664 }
665 return authority.delayUntil;
666 }
667 }
668
Amith Yamasani04e0d262012-02-14 11:50:53 -0800669 private void updateOrRemovePeriodicSync(Account account, int userId, String providerName,
670 Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800671 long period, boolean add) {
672 if (period <= 0) {
673 period = 0;
674 }
675 if (extras == null) {
676 extras = new Bundle();
677 }
678 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800679 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", user " + userId
680 + ", provider " + providerName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800681 + " -> period " + period + ", extras " + extras);
682 }
683 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700684 try {
685 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800686 getOrCreateAuthorityLocked(account, userId, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700687 if (add) {
688 // add this periodic sync if one with the same extras doesn't already
689 // exist in the periodicSyncs array
690 boolean alreadyPresent = false;
691 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
692 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
693 final Bundle existingExtras = syncInfo.first;
694 if (equals(existingExtras, extras)) {
695 if (syncInfo.second == period) {
696 return;
697 }
698 authority.periodicSyncs.set(i, Pair.create(extras, period));
699 alreadyPresent = true;
700 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800701 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700702 }
703 // if we added an entry to the periodicSyncs array also add an entry to
704 // the periodic syncs status to correspond to it
705 if (!alreadyPresent) {
706 authority.periodicSyncs.add(Pair.create(extras, period));
707 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
708 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
709 }
710 } else {
711 // remove any periodic syncs that match the authority and extras
712 SyncStatusInfo status = mSyncStatus.get(authority.ident);
713 boolean changed = false;
714 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
715 int i = 0;
716 while (iterator.hasNext()) {
717 Pair<Bundle, Long> syncInfo = iterator.next();
718 if (equals(syncInfo.first, extras)) {
719 iterator.remove();
720 changed = true;
721 // if we removed an entry from the periodicSyncs array also
722 // remove the corresponding entry from the status
723 if (status != null) {
724 status.removePeriodicSyncTime(i);
725 }
726 } else {
727 i++;
728 }
729 }
730 if (!changed) {
731 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800732 }
733 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700734 } finally {
735 writeAccountInfoLocked();
736 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800737 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800738 }
739
740 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
741 }
742
Amith Yamasani04e0d262012-02-14 11:50:53 -0800743 public void addPeriodicSync(Account account, int userId, String providerName, Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800744 long pollFrequency) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800745 updateOrRemovePeriodicSync(account, userId, providerName, extras, pollFrequency,
746 true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800747 }
748
Amith Yamasani04e0d262012-02-14 11:50:53 -0800749 public void removePeriodicSync(Account account, int userId, String providerName,
750 Bundle extras) {
751 updateOrRemovePeriodicSync(account, userId, providerName, extras, 0 /* period, ignored */,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800752 false /* remove */);
753 }
754
Amith Yamasani04e0d262012-02-14 11:50:53 -0800755 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800756 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
757 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800758 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
759 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800760 if (authority != null) {
761 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800762 syncs.add(new PeriodicSync(account, providerName, item.first,
763 item.second));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800764 }
765 }
766 }
767 return syncs;
768 }
769
Amith Yamasani04e0d262012-02-14 11:50:53 -0800770 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700771 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800772 Boolean auto = mMasterSyncAutomatically.get(userId);
773 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700774 return;
775 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800776 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700777 writeAccountInfoLocked();
778 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700779 if (flag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800780 requestSync(null, userId, null, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700781 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700782 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
783 mContext.sendBroadcast(SYNC_CONNECTION_SETTING_CHANGED_INTENT);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785
Amith Yamasani04e0d262012-02-14 11:50:53 -0800786 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700787 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800788 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800789 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700790 }
791 }
Costin Manolache360e4542009-09-04 13:36:04 -0700792
Amith Yamasani04e0d262012-02-14 11:50:53 -0800793 public AuthorityInfo getOrCreateAuthority(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700794 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800795 return getOrCreateAuthorityLocked(account, userId, authority,
Fred Quintana1bbcd102010-02-10 10:04:33 -0800796 -1 /* assign a new identifier if creating a new authority */,
797 true /* write to storage if this results in a change */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700798 }
799 }
Costin Manolache360e4542009-09-04 13:36:04 -0700800
Amith Yamasani04e0d262012-02-14 11:50:53 -0800801 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700802 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800803 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700804 }
805 }
806
Dianne Hackborn231cc602009-04-27 17:10:36 -0700807 public AuthorityInfo getAuthority(int authorityId) {
808 synchronized (mAuthorities) {
809 return mAuthorities.get(authorityId);
810 }
811 }
Costin Manolache360e4542009-09-04 13:36:04 -0700812
Dianne Hackborn231cc602009-04-27 17:10:36 -0700813 /**
814 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700815 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700816 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800817 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700818 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800819 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700820 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700821 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800822 && ainfo.authority.equals(authority)
823 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700824 return true;
825 }
826 }
827 }
Costin Manolache360e4542009-09-04 13:36:04 -0700828
Dianne Hackborn231cc602009-04-27 17:10:36 -0700829 return false;
830 }
Costin Manolache360e4542009-09-04 13:36:04 -0700831
Dianne Hackborn231cc602009-04-27 17:10:36 -0700832 public PendingOperation insertIntoPending(PendingOperation op) {
833 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700834 if (Log.isLoggable(TAG, Log.VERBOSE)) {
835 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800836 + " user=" + op.userId
837 + " auth=" + op.authority
838 + " src=" + op.syncSource
839 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700840 }
Costin Manolache360e4542009-09-04 13:36:04 -0700841
Amith Yamasani04e0d262012-02-14 11:50:53 -0800842 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700843 op.authority,
844 -1 /* desired identifier */,
845 true /* write accounts to storage */);
846 if (authority == null) {
847 return null;
848 }
Costin Manolache360e4542009-09-04 13:36:04 -0700849
Dianne Hackborn231cc602009-04-27 17:10:36 -0700850 op = new PendingOperation(op);
851 op.authorityId = authority.ident;
852 mPendingOperations.add(op);
853 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700854
Dianne Hackborn231cc602009-04-27 17:10:36 -0700855 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
856 status.pending = true;
857 }
Costin Manolache360e4542009-09-04 13:36:04 -0700858
Fred Quintanaac9385e2009-06-22 18:00:59 -0700859 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700860 return op;
861 }
862
863 public boolean deleteFromPending(PendingOperation op) {
864 boolean res = false;
865 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700866 if (Log.isLoggable(TAG, Log.VERBOSE)) {
867 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800868 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700869 + " auth=" + op.authority
870 + " src=" + op.syncSource
871 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700872 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700873 if (mPendingOperations.remove(op)) {
874 if (mPendingOperations.size() == 0
875 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
876 writePendingOperationsLocked();
877 mNumPendingFinished = 0;
878 } else {
879 mNumPendingFinished++;
880 }
Costin Manolache360e4542009-09-04 13:36:04 -0700881
Amith Yamasani04e0d262012-02-14 11:50:53 -0800882 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700883 "deleteFromPending");
884 if (authority != null) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700885 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "removing - " + authority);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700886 final int N = mPendingOperations.size();
887 boolean morePending = false;
888 for (int i=0; i<N; i++) {
889 PendingOperation cur = mPendingOperations.get(i);
890 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800891 && cur.authority.equals(op.authority)
892 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700893 morePending = true;
894 break;
895 }
896 }
Costin Manolache360e4542009-09-04 13:36:04 -0700897
Dianne Hackborn231cc602009-04-27 17:10:36 -0700898 if (!morePending) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700899 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700900 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
901 status.pending = false;
902 }
903 }
Costin Manolache360e4542009-09-04 13:36:04 -0700904
Dianne Hackborn231cc602009-04-27 17:10:36 -0700905 res = true;
906 }
907 }
Costin Manolache360e4542009-09-04 13:36:04 -0700908
Fred Quintanaac9385e2009-06-22 18:00:59 -0700909 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700910 return res;
911 }
912
Dianne Hackborn231cc602009-04-27 17:10:36 -0700913 /**
914 * Return a copy of the current array of pending operations. The
915 * PendingOperation objects are the real objects stored inside, so that
916 * they can be used with deleteFromPending().
917 */
918 public ArrayList<PendingOperation> getPendingOperations() {
919 synchronized (mAuthorities) {
920 return new ArrayList<PendingOperation>(mPendingOperations);
921 }
922 }
Costin Manolache360e4542009-09-04 13:36:04 -0700923
Dianne Hackborn231cc602009-04-27 17:10:36 -0700924 /**
925 * Return the number of currently pending operations.
926 */
927 public int getPendingOperationCount() {
928 synchronized (mAuthorities) {
929 return mPendingOperations.size();
930 }
931 }
Costin Manolache360e4542009-09-04 13:36:04 -0700932
Dianne Hackborn231cc602009-04-27 17:10:36 -0700933 /**
934 * Called when the set of account has changed, given the new array of
935 * active accounts.
936 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800937 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700938 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700939 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.w(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700940 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
941 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
942 while (accIt.hasNext()) {
943 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800944 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
945 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700946 // This account no longer exists...
Fred Quintana77c560f2010-03-29 22:20:26 -0700947 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800948 Log.w(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700949 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700950 for (AuthorityInfo auth : acc.authorities.values()) {
951 removing.put(auth.ident, auth);
952 }
953 accIt.remove();
954 }
955 }
Costin Manolache360e4542009-09-04 13:36:04 -0700956
Dianne Hackborn231cc602009-04-27 17:10:36 -0700957 // Clean out all data structures.
958 int i = removing.size();
959 if (i > 0) {
960 while (i > 0) {
961 i--;
962 int ident = removing.keyAt(i);
963 mAuthorities.remove(ident);
964 int j = mSyncStatus.size();
965 while (j > 0) {
966 j--;
967 if (mSyncStatus.keyAt(j) == ident) {
968 mSyncStatus.remove(mSyncStatus.keyAt(j));
969 }
970 }
971 j = mSyncHistory.size();
972 while (j > 0) {
973 j--;
974 if (mSyncHistory.get(j).authorityId == ident) {
975 mSyncHistory.remove(j);
976 }
977 }
978 }
979 writeAccountInfoLocked();
980 writeStatusLocked();
981 writePendingOperationsLocked();
982 writeStatisticsLocked();
983 }
984 }
985 }
986
987 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700988 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
989 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700990 */
Fred Quintana918339a2010-10-05 14:00:39 -0700991 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
992 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700993 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -0700994 if (Log.isLoggable(TAG, Log.VERBOSE)) {
995 Log.v(TAG, "setActiveSync: account="
996 + activeSyncContext.mSyncOperation.account
997 + " auth=" + activeSyncContext.mSyncOperation.authority
998 + " src=" + activeSyncContext.mSyncOperation.syncSource
999 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001000 }
Fred Quintana918339a2010-10-05 14:00:39 -07001001 AuthorityInfo authority = getOrCreateAuthorityLocked(
1002 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001003 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -07001004 activeSyncContext.mSyncOperation.authority,
1005 -1 /* assign a new identifier if creating a new authority */,
1006 true /* write to storage if this results in a change */);
1007 syncInfo = new SyncInfo(authority.ident,
1008 authority.account, authority.authority,
1009 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001010 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001011 }
Costin Manolache360e4542009-09-04 13:36:04 -07001012
Fred Quintana918339a2010-10-05 14:00:39 -07001013 reportActiveChange();
1014 return syncInfo;
1015 }
1016
1017 /**
1018 * Called to indicate that a previously active sync is no longer active.
1019 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001020 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001021 synchronized (mAuthorities) {
1022 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001023 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1024 + " user=" + userId
1025 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001026 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001027 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001028 }
1029
1030 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001031 }
1032
1033 /**
1034 * To allow others to send active change reports, to poke clients.
1035 */
1036 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001037 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001038 }
Costin Manolache360e4542009-09-04 13:36:04 -07001039
Dianne Hackborn231cc602009-04-27 17:10:36 -07001040 /**
1041 * Note that sync has started for the given account and authority.
1042 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001043 public long insertStartSyncEvent(Account accountName, int userId, String authorityName,
Fred Quintanadc475562012-05-04 15:51:54 -07001044 long now, int source, boolean initialization) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001045 long id;
1046 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001047 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001048 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001049 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001050 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001051 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001052 "insertStartSyncEvent");
1053 if (authority == null) {
1054 return -1;
1055 }
1056 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001057 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001058 item.authorityId = authority.ident;
1059 item.historyId = mNextHistoryId++;
1060 if (mNextHistoryId < 0) mNextHistoryId = 0;
1061 item.eventTime = now;
1062 item.source = source;
1063 item.event = EVENT_START;
1064 mSyncHistory.add(0, item);
1065 while (mSyncHistory.size() > MAX_HISTORY) {
1066 mSyncHistory.remove(mSyncHistory.size()-1);
1067 }
1068 id = item.historyId;
Fred Quintana77c560f2010-03-29 22:20:26 -07001069 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001070 }
Costin Manolache360e4542009-09-04 13:36:04 -07001071
Fred Quintanaac9385e2009-06-22 18:00:59 -07001072 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001073 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
1075
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001076 public static boolean equals(Bundle b1, Bundle b2) {
1077 if (b1.size() != b2.size()) {
1078 return false;
1079 }
1080 if (b1.isEmpty()) {
1081 return true;
1082 }
1083 for (String key : b1.keySet()) {
1084 if (!b2.containsKey(key)) {
1085 return false;
1086 }
1087 if (!b1.get(key).equals(b2.get(key))) {
1088 return false;
1089 }
1090 }
1091 return true;
1092 }
1093
Fred Quintana77c560f2010-03-29 22:20:26 -07001094 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001096 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001097 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1098 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1099 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001100 SyncHistoryItem item = null;
1101 int i = mSyncHistory.size();
1102 while (i > 0) {
1103 i--;
1104 item = mSyncHistory.get(i);
1105 if (item.historyId == historyId) {
1106 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001108 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
Costin Manolache360e4542009-09-04 13:36:04 -07001110
Dianne Hackborn231cc602009-04-27 17:10:36 -07001111 if (item == null) {
1112 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1113 return;
1114 }
Costin Manolache360e4542009-09-04 13:36:04 -07001115
Dianne Hackborn231cc602009-04-27 17:10:36 -07001116 item.elapsedTime = elapsedTime;
1117 item.event = EVENT_STOP;
1118 item.mesg = resultMessage;
1119 item.downstreamActivity = downstreamActivity;
1120 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001121
Dianne Hackborn231cc602009-04-27 17:10:36 -07001122 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001123
Dianne Hackborn231cc602009-04-27 17:10:36 -07001124 status.numSyncs++;
1125 status.totalElapsedTime += elapsedTime;
1126 switch (item.source) {
1127 case SOURCE_LOCAL:
1128 status.numSourceLocal++;
1129 break;
1130 case SOURCE_POLL:
1131 status.numSourcePoll++;
1132 break;
1133 case SOURCE_USER:
1134 status.numSourceUser++;
1135 break;
1136 case SOURCE_SERVER:
1137 status.numSourceServer++;
1138 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001139 case SOURCE_PERIODIC:
1140 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001141 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001142 }
Costin Manolache360e4542009-09-04 13:36:04 -07001143
Dianne Hackborn231cc602009-04-27 17:10:36 -07001144 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001145 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001146 if (mDayStats[0] == null) {
1147 mDayStats[0] = new DayStats(day);
1148 } else if (day != mDayStats[0].day) {
1149 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1150 mDayStats[0] = new DayStats(day);
1151 writeStatisticsNow = true;
1152 } else if (mDayStats[0] == null) {
1153 }
1154 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001155
Dianne Hackborn231cc602009-04-27 17:10:36 -07001156 final long lastSyncTime = (item.eventTime + elapsedTime);
1157 boolean writeStatusNow = false;
1158 if (MESG_SUCCESS.equals(resultMessage)) {
1159 // - if successful, update the successful columns
1160 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1161 writeStatusNow = true;
1162 }
1163 status.lastSuccessTime = lastSyncTime;
1164 status.lastSuccessSource = item.source;
1165 status.lastFailureTime = 0;
1166 status.lastFailureSource = -1;
1167 status.lastFailureMesg = null;
1168 status.initialFailureTime = 0;
1169 ds.successCount++;
1170 ds.successTime += elapsedTime;
1171 } else if (!MESG_CANCELED.equals(resultMessage)) {
1172 if (status.lastFailureTime == 0) {
1173 writeStatusNow = true;
1174 }
1175 status.lastFailureTime = lastSyncTime;
1176 status.lastFailureSource = item.source;
1177 status.lastFailureMesg = resultMessage;
1178 if (status.initialFailureTime == 0) {
1179 status.initialFailureTime = lastSyncTime;
1180 }
1181 ds.failureCount++;
1182 ds.failureTime += elapsedTime;
1183 }
Costin Manolache360e4542009-09-04 13:36:04 -07001184
Dianne Hackborn231cc602009-04-27 17:10:36 -07001185 if (writeStatusNow) {
1186 writeStatusLocked();
1187 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1188 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1189 WRITE_STATUS_DELAY);
1190 }
1191 if (writeStatisticsNow) {
1192 writeStatisticsLocked();
1193 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1194 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1195 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001196 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001197 }
Costin Manolache360e4542009-09-04 13:36:04 -07001198
Fred Quintanaac9385e2009-06-22 18:00:59 -07001199 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001200 }
1201
1202 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001203 * Return a list of the currently active syncs. Note that the returned items are the
1204 * real, live active sync objects, so be careful what you do with it.
1205 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001206 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001207 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001208 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1209 if (syncs == null) {
1210 syncs = new ArrayList<SyncInfo>();
1211 mCurrentSyncs.put(userId, syncs);
1212 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001213 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001214 }
1215 }
Costin Manolache360e4542009-09-04 13:36:04 -07001216
Dianne Hackborn231cc602009-04-27 17:10:36 -07001217 /**
1218 * Return an array of the current sync status for all authorities. Note
1219 * that the objects inside the array are the real, live status objects,
1220 * so be careful what you do with them.
1221 */
1222 public ArrayList<SyncStatusInfo> getSyncStatus() {
1223 synchronized (mAuthorities) {
1224 final int N = mSyncStatus.size();
1225 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1226 for (int i=0; i<N; i++) {
1227 ops.add(mSyncStatus.valueAt(i));
1228 }
1229 return ops;
1230 }
1231 }
Costin Manolache360e4542009-09-04 13:36:04 -07001232
Dianne Hackborn231cc602009-04-27 17:10:36 -07001233 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001234 * Return an array of the current authorities. Note
1235 * that the objects inside the array are the real, live objects,
1236 * so be careful what you do with them.
1237 */
1238 public ArrayList<AuthorityInfo> getAuthorities() {
1239 synchronized (mAuthorities) {
1240 final int N = mAuthorities.size();
1241 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1242 for (int i=0; i<N; i++) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -07001243 // Make deep copy because AuthorityInfo syncs are liable to change.
1244 infos.add(new AuthorityInfo(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001245 }
1246 return infos;
1247 }
1248 }
1249
1250 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001251 * Returns the status that matches the authority and account.
1252 *
1253 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001254 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001255 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001256 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001257 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1258 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001259 if (account == null || authority == null) {
1260 throw new IllegalArgumentException();
1261 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001262 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001263 final int N = mSyncStatus.size();
1264 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001265 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001266 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001267
Amith Yamasani04e0d262012-02-14 11:50:53 -08001268 if (ainfo != null && ainfo.authority.equals(authority)
1269 && ainfo.userId == userId
1270 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001271 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001272 }
1273 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001274 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001275 }
1276 }
Costin Manolache360e4542009-09-04 13:36:04 -07001277
Dianne Hackborn231cc602009-04-27 17:10:36 -07001278 /**
1279 * Return true if the pending status is true of any matching authorities.
1280 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001281 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001282 synchronized (mAuthorities) {
1283 final int N = mSyncStatus.size();
1284 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001285 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001286 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1287 if (ainfo == null) {
1288 continue;
1289 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001290 if (userId != ainfo.userId) {
1291 continue;
1292 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001293 if (account != null && !ainfo.account.equals(account)) {
1294 continue;
1295 }
1296 if (ainfo.authority.equals(authority) && cur.pending) {
1297 return true;
1298 }
1299 }
1300 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
1302 }
1303
1304 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001305 * Return an array of the current sync status for all authorities. Note
1306 * that the objects inside the array are the real, live status objects,
1307 * so be careful what you do with them.
1308 */
1309 public ArrayList<SyncHistoryItem> getSyncHistory() {
1310 synchronized (mAuthorities) {
1311 final int N = mSyncHistory.size();
1312 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1313 for (int i=0; i<N; i++) {
1314 items.add(mSyncHistory.get(i));
1315 }
1316 return items;
1317 }
1318 }
Costin Manolache360e4542009-09-04 13:36:04 -07001319
Dianne Hackborn231cc602009-04-27 17:10:36 -07001320 /**
1321 * Return an array of the current per-day statistics. Note
1322 * that the objects inside the array are the real, live status objects,
1323 * so be careful what you do with them.
1324 */
1325 public DayStats[] getDayStatistics() {
1326 synchronized (mAuthorities) {
1327 DayStats[] ds = new DayStats[mDayStats.length];
1328 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1329 return ds;
1330 }
1331 }
Costin Manolache360e4542009-09-04 13:36:04 -07001332
Dianne Hackborn55280a92009-05-07 15:53:46 -07001333 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001334 mCal.setTimeInMillis(System.currentTimeMillis());
1335 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1336 if (mYear != mCal.get(Calendar.YEAR)) {
1337 mYear = mCal.get(Calendar.YEAR);
1338 mCal.clear();
1339 mCal.set(Calendar.YEAR, mYear);
1340 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1341 }
1342 return dayOfYear + mYearInDays;
1343 }
Costin Manolache360e4542009-09-04 13:36:04 -07001344
Dianne Hackborn231cc602009-04-27 17:10:36 -07001345 /**
1346 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001347 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001348 * @param accountName The name of the account for the authority.
1349 * @param authorityName The name of the authority itself.
1350 * @param tag If non-null, this will be used in a log message if the
1351 * requested authority does not exist.
1352 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001353 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001354 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001355 AccountAndUser au = new AccountAndUser(accountName, userId);
1356 AccountInfo accountInfo = mAccounts.get(au);
1357 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001358 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001359 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001360 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001361 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001362 }
1363 return null;
1364 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001365 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001366 if (authority == null) {
1367 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001368 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1369 Log.v(TAG, tag + ": unknown authority " + authorityName);
1370 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001371 }
1372 return null;
1373 }
Costin Manolache360e4542009-09-04 13:36:04 -07001374
Dianne Hackborn231cc602009-04-27 17:10:36 -07001375 return authority;
1376 }
Costin Manolache360e4542009-09-04 13:36:04 -07001377
Amith Yamasani04e0d262012-02-14 11:50:53 -08001378 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001379 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001380 AccountAndUser au = new AccountAndUser(accountName, userId);
1381 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001382 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001383 account = new AccountInfo(au);
1384 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001385 }
1386 AuthorityInfo authority = account.authorities.get(authorityName);
1387 if (authority == null) {
1388 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001389 ident = mNextAuthorityId;
1390 mNextAuthorityId++;
1391 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001392 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001393 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1394 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001395 + ", user " + userId
1396 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001397 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001398 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001399 account.authorities.put(authorityName, authority);
1400 mAuthorities.put(ident, authority);
1401 if (doWrite) {
1402 writeAccountInfoLocked();
1403 }
1404 }
Costin Manolache360e4542009-09-04 13:36:04 -07001405
Dianne Hackborn231cc602009-04-27 17:10:36 -07001406 return authority;
1407 }
Costin Manolache360e4542009-09-04 13:36:04 -07001408
Amith Yamasani04e0d262012-02-14 11:50:53 -08001409 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1410 boolean doWrite) {
1411 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001412 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001413 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1414 if (authorityInfo != null) {
1415 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001416 if (doWrite) {
1417 writeAccountInfoLocked();
1418 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001419 }
1420 }
1421 }
1422
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001423 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1424 synchronized (mAuthorities) {
1425 return getOrCreateSyncStatusLocked(authority.ident);
1426 }
1427 }
1428
Dianne Hackborn231cc602009-04-27 17:10:36 -07001429 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1430 SyncStatusInfo status = mSyncStatus.get(authorityId);
1431 if (status == null) {
1432 status = new SyncStatusInfo(authorityId);
1433 mSyncStatus.put(authorityId, status);
1434 }
1435 return status;
1436 }
Costin Manolache360e4542009-09-04 13:36:04 -07001437
Dianne Hackborn55280a92009-05-07 15:53:46 -07001438 public void writeAllState() {
1439 synchronized (mAuthorities) {
1440 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001441
Dianne Hackborn55280a92009-05-07 15:53:46 -07001442 if (mNumPendingFinished > 0) {
1443 // Only write these if they are out of date.
1444 writePendingOperationsLocked();
1445 }
Costin Manolache360e4542009-09-04 13:36:04 -07001446
Dianne Hackborn55280a92009-05-07 15:53:46 -07001447 // Just always write these... they are likely out of date.
1448 writeStatusLocked();
1449 writeStatisticsLocked();
1450 }
1451 }
Costin Manolache360e4542009-09-04 13:36:04 -07001452
Dianne Hackborn231cc602009-04-27 17:10:36 -07001453 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001454 * public for testing
1455 */
1456 public void clearAndReadState() {
1457 synchronized (mAuthorities) {
1458 mAuthorities.clear();
1459 mAccounts.clear();
1460 mPendingOperations.clear();
1461 mSyncStatus.clear();
1462 mSyncHistory.clear();
1463
1464 readAccountInfoLocked();
1465 readStatusLocked();
1466 readPendingOperationsLocked();
1467 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001468 readAndDeleteLegacyAccountInfoLocked();
1469 writeAccountInfoLocked();
1470 writeStatusLocked();
1471 writePendingOperationsLocked();
1472 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001473 }
1474 }
1475
1476 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001477 * Read all account information back in to the initial engine state.
1478 */
1479 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001480 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001481 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001483 fis = mAccountInfoFile.openRead();
1484 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1485 XmlPullParser parser = Xml.newPullParser();
1486 parser.setInput(fis, null);
1487 int eventType = parser.getEventType();
1488 while (eventType != XmlPullParser.START_TAG) {
1489 eventType = parser.next();
1490 }
1491 String tagName = parser.getName();
1492 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001493 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001494 String versionString = parser.getAttributeValue(null, "version");
1495 int version;
1496 try {
1497 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1498 } catch (NumberFormatException e) {
1499 version = 0;
1500 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001501 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001502 try {
1503 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1504 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1505 } catch (NumberFormatException e) {
1506 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001507 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001508 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1509 try {
1510 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1511 } catch (NumberFormatException e) {
1512 mSyncRandomOffset = 0;
1513 }
1514 if (mSyncRandomOffset == 0) {
1515 Random random = new Random(System.currentTimeMillis());
1516 mSyncRandomOffset = random.nextInt(86400);
1517 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001518 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001519 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001520 AuthorityInfo authority = null;
1521 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001522 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001523 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001524 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001525 if (parser.getDepth() == 2) {
1526 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001527 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001528 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001529 if (authority.ident > highestAuthorityId) {
1530 highestAuthorityId = authority.ident;
1531 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001532 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1533 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001534 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001535 } else if (parser.getDepth() == 3) {
1536 if ("periodicSync".equals(tagName) && authority != null) {
1537 periodicSync = parsePeriodicSync(parser, authority);
1538 }
1539 } else if (parser.getDepth() == 4 && periodicSync != null) {
1540 if ("extra".equals(tagName)) {
1541 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001542 }
1543 }
1544 }
1545 eventType = parser.next();
1546 } while (eventType != XmlPullParser.END_DOCUMENT);
1547 }
1548 } catch (XmlPullParserException e) {
1549 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001550 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001551 } catch (java.io.IOException e) {
1552 if (fis == null) Log.i(TAG, "No initial accounts");
1553 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001554 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001555 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001556 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001557 if (fis != null) {
1558 try {
1559 fis.close();
1560 } catch (java.io.IOException e1) {
1561 }
1562 }
1563 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001564
Fred Quintana77c560f2010-03-29 22:20:26 -07001565 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001566 }
Costin Manolache360e4542009-09-04 13:36:04 -07001567
Fred Quintanafb084402010-03-23 17:57:03 -07001568 /**
1569 * some authority names have changed. copy over their settings and delete the old ones
1570 * @return true if a change was made
1571 */
1572 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1573 boolean writeNeeded = false;
1574
1575 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1576 final int N = mAuthorities.size();
1577 for (int i=0; i<N; i++) {
1578 AuthorityInfo authority = mAuthorities.valueAt(i);
1579 // skip this authority if it isn't one of the renamed ones
1580 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1581 if (newAuthorityName == null) {
1582 continue;
1583 }
1584
1585 // remember this authority so we can remove it later. we can't remove it
1586 // now without messing up this loop iteration
1587 authoritiesToRemove.add(authority);
1588
1589 // this authority isn't enabled, no need to copy it to the new authority name since
1590 // the default is "disabled"
1591 if (!authority.enabled) {
1592 continue;
1593 }
1594
1595 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001596 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1597 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001598 continue;
1599 }
1600
1601 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001602 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001603 newAuthority.enabled = true;
1604 writeNeeded = true;
1605 }
1606
1607 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001608 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1609 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001610 writeNeeded = true;
1611 }
1612
1613 return writeNeeded;
1614 }
1615
Amith Yamasani04e0d262012-02-14 11:50:53 -08001616 private void parseListenForTickles(XmlPullParser parser) {
1617 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1618 int userId = 0;
1619 try {
1620 userId = Integer.parseInt(user);
1621 } catch (NumberFormatException e) {
1622 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1623 } catch (NullPointerException e) {
1624 Log.e(TAG, "the user in listen-for-tickles is null", e);
1625 }
1626 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1627 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1628 mMasterSyncAutomatically.put(userId, listen);
1629 }
1630
Fred Quintanac2e46912010-03-15 16:10:44 -07001631 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001632 AuthorityInfo authority = null;
1633 int id = -1;
1634 try {
1635 id = Integer.parseInt(parser.getAttributeValue(
1636 null, "id"));
1637 } catch (NumberFormatException e) {
1638 Log.e(TAG, "error parsing the id of the authority", e);
1639 } catch (NullPointerException e) {
1640 Log.e(TAG, "the id of the authority is null", e);
1641 }
1642 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001643 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001644 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001645 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001646 String accountName = parser.getAttributeValue(null, "account");
1647 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001648 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1649 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001650 if (accountType == null) {
1651 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001652 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001653 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001654 authority = mAuthorities.get(id);
1655 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1656 + accountName + " auth=" + authorityName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001657 + " user=" + userId
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001658 + " enabled=" + enabled
1659 + " syncable=" + syncable);
1660 if (authority == null) {
1661 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1662 authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001663 new Account(accountName, accountType), userId, authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001664 // If the version is 0 then we are upgrading from a file format that did not
1665 // know about periodic syncs. In that case don't clear the list since we
1666 // want the default, which is a daily periodioc sync.
1667 // Otherwise clear out this default list since we will populate it later with
1668 // the periodic sync descriptions that are read from the configuration file.
1669 if (version > 0) {
1670 authority.periodicSyncs.clear();
1671 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001672 }
1673 if (authority != null) {
1674 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1675 if ("unknown".equals(syncable)) {
1676 authority.syncable = -1;
1677 } else {
1678 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001679 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001680 }
1681 } else {
1682 Log.w(TAG, "Failure adding authority: account="
1683 + accountName + " auth=" + authorityName
1684 + " enabled=" + enabled
1685 + " syncable=" + syncable);
1686 }
1687 }
1688
1689 return authority;
1690 }
1691
1692 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1693 Bundle extras = new Bundle();
1694 String periodValue = parser.getAttributeValue(null, "period");
1695 final long period;
1696 try {
1697 period = Long.parseLong(periodValue);
1698 } catch (NumberFormatException e) {
1699 Log.e(TAG, "error parsing the period of a periodic sync", e);
1700 return null;
1701 } catch (NullPointerException e) {
1702 Log.e(TAG, "the period of a periodic sync is null", e);
1703 return null;
1704 }
1705 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1706 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001707
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001708 return periodicSync;
1709 }
1710
1711 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1712 final Bundle extras = periodicSync.first;
1713 String name = parser.getAttributeValue(null, "name");
1714 String type = parser.getAttributeValue(null, "type");
1715 String value1 = parser.getAttributeValue(null, "value1");
1716 String value2 = parser.getAttributeValue(null, "value2");
1717
1718 try {
1719 if ("long".equals(type)) {
1720 extras.putLong(name, Long.parseLong(value1));
1721 } else if ("integer".equals(type)) {
1722 extras.putInt(name, Integer.parseInt(value1));
1723 } else if ("double".equals(type)) {
1724 extras.putDouble(name, Double.parseDouble(value1));
1725 } else if ("float".equals(type)) {
1726 extras.putFloat(name, Float.parseFloat(value1));
1727 } else if ("boolean".equals(type)) {
1728 extras.putBoolean(name, Boolean.parseBoolean(value1));
1729 } else if ("string".equals(type)) {
1730 extras.putString(name, value1);
1731 } else if ("account".equals(type)) {
1732 extras.putParcelable(name, new Account(value1, value2));
1733 }
1734 } catch (NumberFormatException e) {
1735 Log.e(TAG, "error parsing bundle value", e);
1736 } catch (NullPointerException e) {
1737 Log.e(TAG, "error parsing bundle value", e);
1738 }
1739 }
1740
Dianne Hackborn231cc602009-04-27 17:10:36 -07001741 /**
1742 * Write all account information to the account file.
1743 */
1744 private void writeAccountInfoLocked() {
1745 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1746 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001747
Dianne Hackborn231cc602009-04-27 17:10:36 -07001748 try {
1749 fos = mAccountInfoFile.startWrite();
1750 XmlSerializer out = new FastXmlSerializer();
1751 out.setOutput(fos, "utf-8");
1752 out.startDocument(null, true);
1753 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001754
Dianne Hackborn231cc602009-04-27 17:10:36 -07001755 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001756 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001757 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001758 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001759
1760 // Write the Sync Automatically flags for each user
1761 final int M = mMasterSyncAutomatically.size();
1762 for (int m = 0; m < M; m++) {
1763 int userId = mMasterSyncAutomatically.keyAt(m);
1764 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1765 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1766 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1767 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1768 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001769 }
Costin Manolache360e4542009-09-04 13:36:04 -07001770
Dianne Hackborn231cc602009-04-27 17:10:36 -07001771 final int N = mAuthorities.size();
1772 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001773 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001774 out.startTag(null, "authority");
1775 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001776 out.attribute(null, "account", authority.account.name);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001777 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001778 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001779 out.attribute(null, "authority", authority.authority);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001780 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Fred Quintana5e787c42009-08-16 23:13:53 -07001781 if (authority.syncable < 0) {
1782 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001783 } else {
1784 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001785 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001786 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1787 out.startTag(null, "periodicSync");
1788 out.attribute(null, "period", Long.toString(periodicSync.second));
1789 final Bundle extras = periodicSync.first;
1790 for (String key : extras.keySet()) {
1791 out.startTag(null, "extra");
1792 out.attribute(null, "name", key);
1793 final Object value = extras.get(key);
1794 if (value instanceof Long) {
1795 out.attribute(null, "type", "long");
1796 out.attribute(null, "value1", value.toString());
1797 } else if (value instanceof Integer) {
1798 out.attribute(null, "type", "integer");
1799 out.attribute(null, "value1", value.toString());
1800 } else if (value instanceof Boolean) {
1801 out.attribute(null, "type", "boolean");
1802 out.attribute(null, "value1", value.toString());
1803 } else if (value instanceof Float) {
1804 out.attribute(null, "type", "float");
1805 out.attribute(null, "value1", value.toString());
1806 } else if (value instanceof Double) {
1807 out.attribute(null, "type", "double");
1808 out.attribute(null, "value1", value.toString());
1809 } else if (value instanceof String) {
1810 out.attribute(null, "type", "string");
1811 out.attribute(null, "value1", value.toString());
1812 } else if (value instanceof Account) {
1813 out.attribute(null, "type", "account");
1814 out.attribute(null, "value1", ((Account)value).name);
1815 out.attribute(null, "value2", ((Account)value).type);
1816 }
1817 out.endTag(null, "extra");
1818 }
1819 out.endTag(null, "periodicSync");
1820 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001821 out.endTag(null, "authority");
1822 }
Costin Manolache360e4542009-09-04 13:36:04 -07001823
Dianne Hackborn231cc602009-04-27 17:10:36 -07001824 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001825
Dianne Hackborn231cc602009-04-27 17:10:36 -07001826 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001827
Dianne Hackborn231cc602009-04-27 17:10:36 -07001828 mAccountInfoFile.finishWrite(fos);
1829 } catch (java.io.IOException e1) {
1830 Log.w(TAG, "Error writing accounts", e1);
1831 if (fos != null) {
1832 mAccountInfoFile.failWrite(fos);
1833 }
1834 }
1835 }
Costin Manolache360e4542009-09-04 13:36:04 -07001836
Dianne Hackborn231cc602009-04-27 17:10:36 -07001837 static int getIntColumn(Cursor c, String name) {
1838 return c.getInt(c.getColumnIndex(name));
1839 }
Costin Manolache360e4542009-09-04 13:36:04 -07001840
Dianne Hackborn231cc602009-04-27 17:10:36 -07001841 static long getLongColumn(Cursor c, String name) {
1842 return c.getLong(c.getColumnIndex(name));
1843 }
Costin Manolache360e4542009-09-04 13:36:04 -07001844
Dianne Hackborn231cc602009-04-27 17:10:36 -07001845 /**
1846 * Load sync engine state from the old syncmanager database, and then
1847 * erase it. Note that we don't deal with pending operations, active
1848 * sync, or history.
1849 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001850 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001851 // Look for old database to initialize from.
1852 File file = mContext.getDatabasePath("syncmanager.db");
1853 if (!file.exists()) {
1854 return;
1855 }
1856 String path = file.getPath();
1857 SQLiteDatabase db = null;
1858 try {
1859 db = SQLiteDatabase.openDatabase(path, null,
1860 SQLiteDatabase.OPEN_READONLY);
1861 } catch (SQLiteException e) {
1862 }
Costin Manolache360e4542009-09-04 13:36:04 -07001863
Dianne Hackborn231cc602009-04-27 17:10:36 -07001864 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001865 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001866
Dianne Hackborn231cc602009-04-27 17:10:36 -07001867 // Copy in all of the status information, as well as accounts.
1868 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1869 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1870 qb.setTables("stats, status");
1871 HashMap<String,String> map = new HashMap<String,String>();
1872 map.put("_id", "status._id as _id");
1873 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001874 if (hasType) {
1875 map.put("account_type", "stats.account_type as account_type");
1876 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001877 map.put("authority", "stats.authority as authority");
1878 map.put("totalElapsedTime", "totalElapsedTime");
1879 map.put("numSyncs", "numSyncs");
1880 map.put("numSourceLocal", "numSourceLocal");
1881 map.put("numSourcePoll", "numSourcePoll");
1882 map.put("numSourceServer", "numSourceServer");
1883 map.put("numSourceUser", "numSourceUser");
1884 map.put("lastSuccessSource", "lastSuccessSource");
1885 map.put("lastSuccessTime", "lastSuccessTime");
1886 map.put("lastFailureSource", "lastFailureSource");
1887 map.put("lastFailureTime", "lastFailureTime");
1888 map.put("lastFailureMesg", "lastFailureMesg");
1889 map.put("pending", "pending");
1890 qb.setProjectionMap(map);
1891 qb.appendWhere("stats._id = status.stats_id");
1892 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001894 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001895 String accountType = hasType
1896 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001897 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001898 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001900 String authorityName = c.getString(c.getColumnIndex("authority"));
1901 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001902 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07001903 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001904 if (authority != null) {
1905 int i = mSyncStatus.size();
1906 boolean found = false;
1907 SyncStatusInfo st = null;
1908 while (i > 0) {
1909 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001910 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001911 if (st.authorityId == authority.ident) {
1912 found = true;
1913 break;
1914 }
1915 }
1916 if (!found) {
1917 st = new SyncStatusInfo(authority.ident);
1918 mSyncStatus.put(authority.ident, st);
1919 }
1920 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1921 st.numSyncs = getIntColumn(c, "numSyncs");
1922 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1923 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1924 st.numSourceServer = getIntColumn(c, "numSourceServer");
1925 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001926 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001927 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1928 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1929 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1930 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1931 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1932 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 }
Costin Manolache360e4542009-09-04 13:36:04 -07001935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001937
Dianne Hackborn231cc602009-04-27 17:10:36 -07001938 // Retrieve the settings.
1939 qb = new SQLiteQueryBuilder();
1940 qb.setTables("settings");
1941 c = qb.query(db, null, null, null, null, null, null);
1942 while (c.moveToNext()) {
1943 String name = c.getString(c.getColumnIndex("name"));
1944 String value = c.getString(c.getColumnIndex("value"));
1945 if (name == null) continue;
1946 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001947 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001948 } else if (name.startsWith("sync_provider_")) {
1949 String provider = name.substring("sync_provider_".length(),
1950 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001951 int i = mAuthorities.size();
1952 while (i > 0) {
1953 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001954 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001955 if (authority.authority.equals(provider)) {
1956 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001957 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001958 }
1959 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 }
Costin Manolache360e4542009-09-04 13:36:04 -07001962
Dianne Hackborn231cc602009-04-27 17:10:36 -07001963 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001964
Dianne Hackborn231cc602009-04-27 17:10:36 -07001965 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001966
Dianne Hackborn231cc602009-04-27 17:10:36 -07001967 (new File(path)).delete();
1968 }
1969 }
Costin Manolache360e4542009-09-04 13:36:04 -07001970
Dianne Hackborn231cc602009-04-27 17:10:36 -07001971 public static final int STATUS_FILE_END = 0;
1972 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001973
Dianne Hackborn231cc602009-04-27 17:10:36 -07001974 /**
1975 * Read all sync status back in to the initial engine state.
1976 */
1977 private void readStatusLocked() {
1978 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1979 try {
1980 byte[] data = mStatusFile.readFully();
1981 Parcel in = Parcel.obtain();
1982 in.unmarshall(data, 0, data.length);
1983 in.setDataPosition(0);
1984 int token;
1985 while ((token=in.readInt()) != STATUS_FILE_END) {
1986 if (token == STATUS_FILE_ITEM) {
1987 SyncStatusInfo status = new SyncStatusInfo(in);
1988 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1989 status.pending = false;
1990 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
1991 + status.authorityId);
1992 mSyncStatus.put(status.authorityId, status);
1993 }
1994 } else {
1995 // Ooops.
1996 Log.w(TAG, "Unknown status token: " + token);
1997 break;
1998 }
1999 }
2000 } catch (java.io.IOException e) {
2001 Log.i(TAG, "No initial status");
2002 }
2003 }
Costin Manolache360e4542009-09-04 13:36:04 -07002004
Dianne Hackborn231cc602009-04-27 17:10:36 -07002005 /**
2006 * Write all sync status to the sync status file.
2007 */
2008 private void writeStatusLocked() {
2009 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002010
Dianne Hackborn231cc602009-04-27 17:10:36 -07002011 // The file is being written, so we don't need to have a scheduled
2012 // write until the next change.
2013 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002014
Dianne Hackborn231cc602009-04-27 17:10:36 -07002015 FileOutputStream fos = null;
2016 try {
2017 fos = mStatusFile.startWrite();
2018 Parcel out = Parcel.obtain();
2019 final int N = mSyncStatus.size();
2020 for (int i=0; i<N; i++) {
2021 SyncStatusInfo status = mSyncStatus.valueAt(i);
2022 out.writeInt(STATUS_FILE_ITEM);
2023 status.writeToParcel(out, 0);
2024 }
2025 out.writeInt(STATUS_FILE_END);
2026 fos.write(out.marshall());
2027 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002028
Dianne Hackborn231cc602009-04-27 17:10:36 -07002029 mStatusFile.finishWrite(fos);
2030 } catch (java.io.IOException e1) {
2031 Log.w(TAG, "Error writing status", e1);
2032 if (fos != null) {
2033 mStatusFile.failWrite(fos);
2034 }
2035 }
2036 }
Costin Manolache360e4542009-09-04 13:36:04 -07002037
Fred Quintana307da1a2010-01-21 14:24:20 -08002038 public static final int PENDING_OPERATION_VERSION = 2;
Costin Manolache360e4542009-09-04 13:36:04 -07002039
Dianne Hackborn231cc602009-04-27 17:10:36 -07002040 /**
2041 * Read all pending operations back in to the initial engine state.
2042 */
2043 private void readPendingOperationsLocked() {
2044 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
2045 try {
2046 byte[] data = mPendingFile.readFully();
2047 Parcel in = Parcel.obtain();
2048 in.unmarshall(data, 0, data.length);
2049 in.setDataPosition(0);
2050 final int SIZE = in.dataSize();
2051 while (in.dataPosition() < SIZE) {
2052 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08002053 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002054 Log.w(TAG, "Unknown pending operation version "
2055 + version + "; dropping all ops");
2056 break;
2057 }
2058 int authorityId = in.readInt();
2059 int syncSource = in.readInt();
2060 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08002061 boolean expedited;
2062 if (version == PENDING_OPERATION_VERSION) {
2063 expedited = in.readInt() != 0;
2064 } else {
2065 expedited = false;
2066 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002067 AuthorityInfo authority = mAuthorities.get(authorityId);
2068 if (authority != null) {
Fred Quintana5695c7b2010-12-06 15:07:52 -08002069 Bundle extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002070 if (flatExtras != null) {
2071 extras = unflattenBundle(flatExtras);
Fred Quintana5695c7b2010-12-06 15:07:52 -08002072 } else {
2073 // if we are unable to parse the extras for whatever reason convert this
2074 // to a regular sync by creating an empty extras
2075 extras = new Bundle();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002076 }
2077 PendingOperation op = new PendingOperation(
Amith Yamasani04e0d262012-02-14 11:50:53 -08002078 authority.account, authority.userId, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08002079 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002080 op.authorityId = authorityId;
2081 op.flatExtras = flatExtras;
2082 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
2083 + " auth=" + op.authority
2084 + " src=" + op.syncSource
Fred Quintana307da1a2010-01-21 14:24:20 -08002085 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07002086 + " extras=" + op.extras);
2087 mPendingOperations.add(op);
2088 }
2089 }
2090 } catch (java.io.IOException e) {
2091 Log.i(TAG, "No initial pending operations");
2092 }
2093 }
Costin Manolache360e4542009-09-04 13:36:04 -07002094
Dianne Hackborn231cc602009-04-27 17:10:36 -07002095 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
2096 out.writeInt(PENDING_OPERATION_VERSION);
2097 out.writeInt(op.authorityId);
2098 out.writeInt(op.syncSource);
2099 if (op.flatExtras == null && op.extras != null) {
2100 op.flatExtras = flattenBundle(op.extras);
2101 }
2102 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08002103 out.writeInt(op.expedited ? 1 : 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002104 }
Costin Manolache360e4542009-09-04 13:36:04 -07002105
Dianne Hackborn231cc602009-04-27 17:10:36 -07002106 /**
2107 * Write all currently pending ops to the pending ops file.
2108 */
2109 private void writePendingOperationsLocked() {
2110 final int N = mPendingOperations.size();
2111 FileOutputStream fos = null;
2112 try {
2113 if (N == 0) {
2114 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2115 mPendingFile.truncate();
2116 return;
2117 }
Costin Manolache360e4542009-09-04 13:36:04 -07002118
Dianne Hackborn231cc602009-04-27 17:10:36 -07002119 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2120 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07002121
Dianne Hackborn231cc602009-04-27 17:10:36 -07002122 Parcel out = Parcel.obtain();
2123 for (int i=0; i<N; i++) {
2124 PendingOperation op = mPendingOperations.get(i);
2125 writePendingOperationLocked(op, out);
2126 }
2127 fos.write(out.marshall());
2128 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002129
Dianne Hackborn231cc602009-04-27 17:10:36 -07002130 mPendingFile.finishWrite(fos);
2131 } catch (java.io.IOException e1) {
2132 Log.w(TAG, "Error writing pending operations", e1);
2133 if (fos != null) {
2134 mPendingFile.failWrite(fos);
2135 }
2136 }
2137 }
Costin Manolache360e4542009-09-04 13:36:04 -07002138
Dianne Hackborn231cc602009-04-27 17:10:36 -07002139 /**
2140 * Append the given operation to the pending ops file; if unable to,
2141 * write all pending ops.
2142 */
2143 private void appendPendingOperationLocked(PendingOperation op) {
2144 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2145 FileOutputStream fos = null;
2146 try {
2147 fos = mPendingFile.openAppend();
2148 } catch (java.io.IOException e) {
2149 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2150 writePendingOperationsLocked();
2151 return;
2152 }
Costin Manolache360e4542009-09-04 13:36:04 -07002153
Dianne Hackborn231cc602009-04-27 17:10:36 -07002154 try {
2155 Parcel out = Parcel.obtain();
2156 writePendingOperationLocked(op, out);
2157 fos.write(out.marshall());
2158 out.recycle();
2159 } catch (java.io.IOException e1) {
2160 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002162 try {
2163 fos.close();
2164 } catch (java.io.IOException e2) {
2165 }
2166 }
2167 }
Costin Manolache360e4542009-09-04 13:36:04 -07002168
Dianne Hackborn231cc602009-04-27 17:10:36 -07002169 static private byte[] flattenBundle(Bundle bundle) {
2170 byte[] flatData = null;
2171 Parcel parcel = Parcel.obtain();
2172 try {
2173 bundle.writeToParcel(parcel, 0);
2174 flatData = parcel.marshall();
2175 } finally {
2176 parcel.recycle();
2177 }
2178 return flatData;
2179 }
Costin Manolache360e4542009-09-04 13:36:04 -07002180
Dianne Hackborn231cc602009-04-27 17:10:36 -07002181 static private Bundle unflattenBundle(byte[] flatData) {
2182 Bundle bundle;
2183 Parcel parcel = Parcel.obtain();
2184 try {
2185 parcel.unmarshall(flatData, 0, flatData.length);
2186 parcel.setDataPosition(0);
2187 bundle = parcel.readBundle();
2188 } catch (RuntimeException e) {
2189 // A RuntimeException is thrown if we were unable to parse the parcel.
2190 // Create an empty parcel in this case.
2191 bundle = new Bundle();
2192 } finally {
2193 parcel.recycle();
2194 }
2195 return bundle;
2196 }
Costin Manolache360e4542009-09-04 13:36:04 -07002197
Amith Yamasani04e0d262012-02-14 11:50:53 -08002198 private void requestSync(Account account, int userId, String authority, Bundle extras) {
2199 // If this is happening in the system process, then call the syncrequest listener
2200 // to make a request back to the SyncManager directly.
2201 // If this is probably a test instance, then call back through the ContentResolver
2202 // which will know which userId to apply based on the Binder id.
2203 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2204 && mSyncRequestListener != null) {
2205 mSyncRequestListener.onSyncRequest(account, userId, authority, extras);
2206 } else {
2207 ContentResolver.requestSync(account, authority, extras);
2208 }
2209 }
2210
Dianne Hackborn231cc602009-04-27 17:10:36 -07002211 public static final int STATISTICS_FILE_END = 0;
2212 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2213 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002214
Dianne Hackborn231cc602009-04-27 17:10:36 -07002215 /**
2216 * Read all sync statistics back in to the initial engine state.
2217 */
2218 private void readStatisticsLocked() {
2219 try {
2220 byte[] data = mStatisticsFile.readFully();
2221 Parcel in = Parcel.obtain();
2222 in.unmarshall(data, 0, data.length);
2223 in.setDataPosition(0);
2224 int token;
2225 int index = 0;
2226 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2227 if (token == STATISTICS_FILE_ITEM
2228 || token == STATISTICS_FILE_ITEM_OLD) {
2229 int day = in.readInt();
2230 if (token == STATISTICS_FILE_ITEM_OLD) {
2231 day = day - 2009 + 14245; // Magic!
2232 }
2233 DayStats ds = new DayStats(day);
2234 ds.successCount = in.readInt();
2235 ds.successTime = in.readLong();
2236 ds.failureCount = in.readInt();
2237 ds.failureTime = in.readLong();
2238 if (index < mDayStats.length) {
2239 mDayStats[index] = ds;
2240 index++;
2241 }
2242 } else {
2243 // Ooops.
2244 Log.w(TAG, "Unknown stats token: " + token);
2245 break;
2246 }
2247 }
2248 } catch (java.io.IOException e) {
2249 Log.i(TAG, "No initial statistics");
2250 }
2251 }
Costin Manolache360e4542009-09-04 13:36:04 -07002252
Dianne Hackborn231cc602009-04-27 17:10:36 -07002253 /**
2254 * Write all sync statistics to the sync status file.
2255 */
2256 private void writeStatisticsLocked() {
2257 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002258
Dianne Hackborn231cc602009-04-27 17:10:36 -07002259 // The file is being written, so we don't need to have a scheduled
2260 // write until the next change.
2261 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002262
Dianne Hackborn231cc602009-04-27 17:10:36 -07002263 FileOutputStream fos = null;
2264 try {
2265 fos = mStatisticsFile.startWrite();
2266 Parcel out = Parcel.obtain();
2267 final int N = mDayStats.length;
2268 for (int i=0; i<N; i++) {
2269 DayStats ds = mDayStats[i];
2270 if (ds == null) {
2271 break;
2272 }
2273 out.writeInt(STATISTICS_FILE_ITEM);
2274 out.writeInt(ds.day);
2275 out.writeInt(ds.successCount);
2276 out.writeLong(ds.successTime);
2277 out.writeInt(ds.failureCount);
2278 out.writeLong(ds.failureTime);
2279 }
2280 out.writeInt(STATISTICS_FILE_END);
2281 fos.write(out.marshall());
2282 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002283
Dianne Hackborn231cc602009-04-27 17:10:36 -07002284 mStatisticsFile.finishWrite(fos);
2285 } catch (java.io.IOException e1) {
2286 Log.w(TAG, "Error writing stats", e1);
2287 if (fos != null) {
2288 mStatisticsFile.failWrite(fos);
2289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 }
2291 }
2292}