blob: bdc5a3feff34db24d8c726ef99c5fb9968018697 [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
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080019import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn231cc602009-04-27 17:10:36 -070020import 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;
Dianne Hackborn39606a02012-07-31 17:54:35 -070041import android.util.AtomicFile;
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
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080078 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070079 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) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700613 synchronized (syncQueue) {
614 for (AccountInfo accountInfo : mAccounts.values()) {
615 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
616 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
617 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
618 if (Log.isLoggable(TAG, Log.VERBOSE)) {
619 Log.v(TAG, "clearAllBackoffs:"
620 + " authority:" + authorityInfo.authority
621 + " account:" + accountInfo.accountAndUser.account.name
622 + " user:" + accountInfo.accountAndUser.userId
623 + " backoffTime was: " + authorityInfo.backoffTime
624 + " backoffDelay was: " + authorityInfo.backoffDelay);
625 }
626 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
627 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
628 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
629 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
630 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800631 }
Alon Albert744e310f2010-12-14 11:37:20 -0800632 }
633 }
634 }
635 }
636
637 if (changed) {
638 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
639 }
640 }
641
Amith Yamasani04e0d262012-02-14 11:50:53 -0800642 public void setDelayUntilTime(Account account, int userId, String providerName,
643 long delayUntil) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800644 if (Log.isLoggable(TAG, Log.VERBOSE)) {
645 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800646 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800647 }
648 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800649 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800650 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800651 if (authority.delayUntil == delayUntil) {
652 return;
653 }
654 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800655 }
656
657 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
658 }
659
Amith Yamasani04e0d262012-02-14 11:50:53 -0800660 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800661 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800662 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
663 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800664 if (authority == null) {
665 return 0;
666 }
667 return authority.delayUntil;
668 }
669 }
670
Amith Yamasani04e0d262012-02-14 11:50:53 -0800671 private void updateOrRemovePeriodicSync(Account account, int userId, String providerName,
672 Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800673 long period, boolean add) {
674 if (period <= 0) {
675 period = 0;
676 }
677 if (extras == null) {
678 extras = new Bundle();
679 }
680 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800681 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", user " + userId
682 + ", provider " + providerName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800683 + " -> period " + period + ", extras " + extras);
684 }
685 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700686 try {
687 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800688 getOrCreateAuthorityLocked(account, userId, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700689 if (add) {
690 // add this periodic sync if one with the same extras doesn't already
691 // exist in the periodicSyncs array
692 boolean alreadyPresent = false;
693 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
694 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
695 final Bundle existingExtras = syncInfo.first;
696 if (equals(existingExtras, extras)) {
697 if (syncInfo.second == period) {
698 return;
699 }
700 authority.periodicSyncs.set(i, Pair.create(extras, period));
701 alreadyPresent = true;
702 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800703 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700704 }
705 // if we added an entry to the periodicSyncs array also add an entry to
706 // the periodic syncs status to correspond to it
707 if (!alreadyPresent) {
708 authority.periodicSyncs.add(Pair.create(extras, period));
709 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
710 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
711 }
712 } else {
713 // remove any periodic syncs that match the authority and extras
714 SyncStatusInfo status = mSyncStatus.get(authority.ident);
715 boolean changed = false;
716 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
717 int i = 0;
718 while (iterator.hasNext()) {
719 Pair<Bundle, Long> syncInfo = iterator.next();
720 if (equals(syncInfo.first, extras)) {
721 iterator.remove();
722 changed = true;
723 // if we removed an entry from the periodicSyncs array also
724 // remove the corresponding entry from the status
725 if (status != null) {
726 status.removePeriodicSyncTime(i);
727 }
728 } else {
729 i++;
730 }
731 }
732 if (!changed) {
733 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800734 }
735 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700736 } finally {
737 writeAccountInfoLocked();
738 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800739 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800740 }
741
742 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
743 }
744
Amith Yamasani04e0d262012-02-14 11:50:53 -0800745 public void addPeriodicSync(Account account, int userId, String providerName, Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800746 long pollFrequency) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800747 updateOrRemovePeriodicSync(account, userId, providerName, extras, pollFrequency,
748 true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800749 }
750
Amith Yamasani04e0d262012-02-14 11:50:53 -0800751 public void removePeriodicSync(Account account, int userId, String providerName,
752 Bundle extras) {
753 updateOrRemovePeriodicSync(account, userId, providerName, extras, 0 /* period, ignored */,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800754 false /* remove */);
755 }
756
Amith Yamasani04e0d262012-02-14 11:50:53 -0800757 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800758 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
759 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800760 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
761 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800762 if (authority != null) {
763 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800764 syncs.add(new PeriodicSync(account, providerName, item.first,
765 item.second));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800766 }
767 }
768 }
769 return syncs;
770 }
771
Amith Yamasani04e0d262012-02-14 11:50:53 -0800772 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700773 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800774 Boolean auto = mMasterSyncAutomatically.get(userId);
775 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700776 return;
777 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800778 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700779 writeAccountInfoLocked();
780 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700781 if (flag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800782 requestSync(null, userId, null, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700783 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700784 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
785 mContext.sendBroadcast(SYNC_CONNECTION_SETTING_CHANGED_INTENT);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787
Amith Yamasani04e0d262012-02-14 11:50:53 -0800788 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700789 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800790 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800791 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700792 }
793 }
Costin Manolache360e4542009-09-04 13:36:04 -0700794
Amith Yamasani04e0d262012-02-14 11:50:53 -0800795 public AuthorityInfo getOrCreateAuthority(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700796 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800797 return getOrCreateAuthorityLocked(account, userId, authority,
Fred Quintana1bbcd102010-02-10 10:04:33 -0800798 -1 /* assign a new identifier if creating a new authority */,
799 true /* write to storage if this results in a change */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700800 }
801 }
Costin Manolache360e4542009-09-04 13:36:04 -0700802
Amith Yamasani04e0d262012-02-14 11:50:53 -0800803 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700804 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800805 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700806 }
807 }
808
Dianne Hackborn231cc602009-04-27 17:10:36 -0700809 public AuthorityInfo getAuthority(int authorityId) {
810 synchronized (mAuthorities) {
811 return mAuthorities.get(authorityId);
812 }
813 }
Costin Manolache360e4542009-09-04 13:36:04 -0700814
Dianne Hackborn231cc602009-04-27 17:10:36 -0700815 /**
816 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700817 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700818 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800819 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700820 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800821 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700822 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700823 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800824 && ainfo.authority.equals(authority)
825 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700826 return true;
827 }
828 }
829 }
Costin Manolache360e4542009-09-04 13:36:04 -0700830
Dianne Hackborn231cc602009-04-27 17:10:36 -0700831 return false;
832 }
Costin Manolache360e4542009-09-04 13:36:04 -0700833
Dianne Hackborn231cc602009-04-27 17:10:36 -0700834 public PendingOperation insertIntoPending(PendingOperation op) {
835 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700836 if (Log.isLoggable(TAG, Log.VERBOSE)) {
837 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800838 + " user=" + op.userId
839 + " auth=" + op.authority
840 + " src=" + op.syncSource
841 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700842 }
Costin Manolache360e4542009-09-04 13:36:04 -0700843
Amith Yamasani04e0d262012-02-14 11:50:53 -0800844 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700845 op.authority,
846 -1 /* desired identifier */,
847 true /* write accounts to storage */);
848 if (authority == null) {
849 return null;
850 }
Costin Manolache360e4542009-09-04 13:36:04 -0700851
Dianne Hackborn231cc602009-04-27 17:10:36 -0700852 op = new PendingOperation(op);
853 op.authorityId = authority.ident;
854 mPendingOperations.add(op);
855 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700856
Dianne Hackborn231cc602009-04-27 17:10:36 -0700857 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
858 status.pending = true;
859 }
Costin Manolache360e4542009-09-04 13:36:04 -0700860
Fred Quintanaac9385e2009-06-22 18:00:59 -0700861 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700862 return op;
863 }
864
865 public boolean deleteFromPending(PendingOperation op) {
866 boolean res = false;
867 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700868 if (Log.isLoggable(TAG, Log.VERBOSE)) {
869 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800870 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700871 + " auth=" + op.authority
872 + " src=" + op.syncSource
873 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700874 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700875 if (mPendingOperations.remove(op)) {
876 if (mPendingOperations.size() == 0
877 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
878 writePendingOperationsLocked();
879 mNumPendingFinished = 0;
880 } else {
881 mNumPendingFinished++;
882 }
Costin Manolache360e4542009-09-04 13:36:04 -0700883
Amith Yamasani04e0d262012-02-14 11:50:53 -0800884 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700885 "deleteFromPending");
886 if (authority != null) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700887 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "removing - " + authority);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700888 final int N = mPendingOperations.size();
889 boolean morePending = false;
890 for (int i=0; i<N; i++) {
891 PendingOperation cur = mPendingOperations.get(i);
892 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800893 && cur.authority.equals(op.authority)
894 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700895 morePending = true;
896 break;
897 }
898 }
Costin Manolache360e4542009-09-04 13:36:04 -0700899
Dianne Hackborn231cc602009-04-27 17:10:36 -0700900 if (!morePending) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700901 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700902 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
903 status.pending = false;
904 }
905 }
Costin Manolache360e4542009-09-04 13:36:04 -0700906
Dianne Hackborn231cc602009-04-27 17:10:36 -0700907 res = true;
908 }
909 }
Costin Manolache360e4542009-09-04 13:36:04 -0700910
Fred Quintanaac9385e2009-06-22 18:00:59 -0700911 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700912 return res;
913 }
914
Dianne Hackborn231cc602009-04-27 17:10:36 -0700915 /**
916 * Return a copy of the current array of pending operations. The
917 * PendingOperation objects are the real objects stored inside, so that
918 * they can be used with deleteFromPending().
919 */
920 public ArrayList<PendingOperation> getPendingOperations() {
921 synchronized (mAuthorities) {
922 return new ArrayList<PendingOperation>(mPendingOperations);
923 }
924 }
Costin Manolache360e4542009-09-04 13:36:04 -0700925
Dianne Hackborn231cc602009-04-27 17:10:36 -0700926 /**
927 * Return the number of currently pending operations.
928 */
929 public int getPendingOperationCount() {
930 synchronized (mAuthorities) {
931 return mPendingOperations.size();
932 }
933 }
Costin Manolache360e4542009-09-04 13:36:04 -0700934
Dianne Hackborn231cc602009-04-27 17:10:36 -0700935 /**
936 * Called when the set of account has changed, given the new array of
937 * active accounts.
938 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800939 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700940 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700941 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.w(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700942 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
943 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
944 while (accIt.hasNext()) {
945 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800946 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
947 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700948 // This account no longer exists...
Fred Quintana77c560f2010-03-29 22:20:26 -0700949 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800950 Log.w(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700951 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700952 for (AuthorityInfo auth : acc.authorities.values()) {
953 removing.put(auth.ident, auth);
954 }
955 accIt.remove();
956 }
957 }
Costin Manolache360e4542009-09-04 13:36:04 -0700958
Dianne Hackborn231cc602009-04-27 17:10:36 -0700959 // Clean out all data structures.
960 int i = removing.size();
961 if (i > 0) {
962 while (i > 0) {
963 i--;
964 int ident = removing.keyAt(i);
965 mAuthorities.remove(ident);
966 int j = mSyncStatus.size();
967 while (j > 0) {
968 j--;
969 if (mSyncStatus.keyAt(j) == ident) {
970 mSyncStatus.remove(mSyncStatus.keyAt(j));
971 }
972 }
973 j = mSyncHistory.size();
974 while (j > 0) {
975 j--;
976 if (mSyncHistory.get(j).authorityId == ident) {
977 mSyncHistory.remove(j);
978 }
979 }
980 }
981 writeAccountInfoLocked();
982 writeStatusLocked();
983 writePendingOperationsLocked();
984 writeStatisticsLocked();
985 }
986 }
987 }
988
989 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700990 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
991 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700992 */
Fred Quintana918339a2010-10-05 14:00:39 -0700993 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
994 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700995 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -0700996 if (Log.isLoggable(TAG, Log.VERBOSE)) {
997 Log.v(TAG, "setActiveSync: account="
998 + activeSyncContext.mSyncOperation.account
999 + " auth=" + activeSyncContext.mSyncOperation.authority
1000 + " src=" + activeSyncContext.mSyncOperation.syncSource
1001 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001002 }
Fred Quintana918339a2010-10-05 14:00:39 -07001003 AuthorityInfo authority = getOrCreateAuthorityLocked(
1004 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001005 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -07001006 activeSyncContext.mSyncOperation.authority,
1007 -1 /* assign a new identifier if creating a new authority */,
1008 true /* write to storage if this results in a change */);
1009 syncInfo = new SyncInfo(authority.ident,
1010 authority.account, authority.authority,
1011 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001012 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001013 }
Costin Manolache360e4542009-09-04 13:36:04 -07001014
Fred Quintana918339a2010-10-05 14:00:39 -07001015 reportActiveChange();
1016 return syncInfo;
1017 }
1018
1019 /**
1020 * Called to indicate that a previously active sync is no longer active.
1021 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001022 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001023 synchronized (mAuthorities) {
1024 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001025 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1026 + " user=" + userId
1027 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001028 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001029 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001030 }
1031
1032 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001033 }
1034
1035 /**
1036 * To allow others to send active change reports, to poke clients.
1037 */
1038 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001039 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001040 }
Costin Manolache360e4542009-09-04 13:36:04 -07001041
Dianne Hackborn231cc602009-04-27 17:10:36 -07001042 /**
1043 * Note that sync has started for the given account and authority.
1044 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001045 public long insertStartSyncEvent(Account accountName, int userId, String authorityName,
Fred Quintanadc475562012-05-04 15:51:54 -07001046 long now, int source, boolean initialization) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001047 long id;
1048 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001049 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001050 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001051 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001052 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001053 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001054 "insertStartSyncEvent");
1055 if (authority == null) {
1056 return -1;
1057 }
1058 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001059 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001060 item.authorityId = authority.ident;
1061 item.historyId = mNextHistoryId++;
1062 if (mNextHistoryId < 0) mNextHistoryId = 0;
1063 item.eventTime = now;
1064 item.source = source;
1065 item.event = EVENT_START;
1066 mSyncHistory.add(0, item);
1067 while (mSyncHistory.size() > MAX_HISTORY) {
1068 mSyncHistory.remove(mSyncHistory.size()-1);
1069 }
1070 id = item.historyId;
Fred Quintana77c560f2010-03-29 22:20:26 -07001071 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001072 }
Costin Manolache360e4542009-09-04 13:36:04 -07001073
Fred Quintanaac9385e2009-06-22 18:00:59 -07001074 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001075 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
1077
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001078 public static boolean equals(Bundle b1, Bundle b2) {
1079 if (b1.size() != b2.size()) {
1080 return false;
1081 }
1082 if (b1.isEmpty()) {
1083 return true;
1084 }
1085 for (String key : b1.keySet()) {
1086 if (!b2.containsKey(key)) {
1087 return false;
1088 }
1089 if (!b1.get(key).equals(b2.get(key))) {
1090 return false;
1091 }
1092 }
1093 return true;
1094 }
1095
Fred Quintana77c560f2010-03-29 22:20:26 -07001096 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001098 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001099 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1100 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1101 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001102 SyncHistoryItem item = null;
1103 int i = mSyncHistory.size();
1104 while (i > 0) {
1105 i--;
1106 item = mSyncHistory.get(i);
1107 if (item.historyId == historyId) {
1108 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001110 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 }
Costin Manolache360e4542009-09-04 13:36:04 -07001112
Dianne Hackborn231cc602009-04-27 17:10:36 -07001113 if (item == null) {
1114 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1115 return;
1116 }
Costin Manolache360e4542009-09-04 13:36:04 -07001117
Dianne Hackborn231cc602009-04-27 17:10:36 -07001118 item.elapsedTime = elapsedTime;
1119 item.event = EVENT_STOP;
1120 item.mesg = resultMessage;
1121 item.downstreamActivity = downstreamActivity;
1122 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001123
Dianne Hackborn231cc602009-04-27 17:10:36 -07001124 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001125
Dianne Hackborn231cc602009-04-27 17:10:36 -07001126 status.numSyncs++;
1127 status.totalElapsedTime += elapsedTime;
1128 switch (item.source) {
1129 case SOURCE_LOCAL:
1130 status.numSourceLocal++;
1131 break;
1132 case SOURCE_POLL:
1133 status.numSourcePoll++;
1134 break;
1135 case SOURCE_USER:
1136 status.numSourceUser++;
1137 break;
1138 case SOURCE_SERVER:
1139 status.numSourceServer++;
1140 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001141 case SOURCE_PERIODIC:
1142 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001143 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001144 }
Costin Manolache360e4542009-09-04 13:36:04 -07001145
Dianne Hackborn231cc602009-04-27 17:10:36 -07001146 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001147 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001148 if (mDayStats[0] == null) {
1149 mDayStats[0] = new DayStats(day);
1150 } else if (day != mDayStats[0].day) {
1151 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1152 mDayStats[0] = new DayStats(day);
1153 writeStatisticsNow = true;
1154 } else if (mDayStats[0] == null) {
1155 }
1156 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001157
Dianne Hackborn231cc602009-04-27 17:10:36 -07001158 final long lastSyncTime = (item.eventTime + elapsedTime);
1159 boolean writeStatusNow = false;
1160 if (MESG_SUCCESS.equals(resultMessage)) {
1161 // - if successful, update the successful columns
1162 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1163 writeStatusNow = true;
1164 }
1165 status.lastSuccessTime = lastSyncTime;
1166 status.lastSuccessSource = item.source;
1167 status.lastFailureTime = 0;
1168 status.lastFailureSource = -1;
1169 status.lastFailureMesg = null;
1170 status.initialFailureTime = 0;
1171 ds.successCount++;
1172 ds.successTime += elapsedTime;
1173 } else if (!MESG_CANCELED.equals(resultMessage)) {
1174 if (status.lastFailureTime == 0) {
1175 writeStatusNow = true;
1176 }
1177 status.lastFailureTime = lastSyncTime;
1178 status.lastFailureSource = item.source;
1179 status.lastFailureMesg = resultMessage;
1180 if (status.initialFailureTime == 0) {
1181 status.initialFailureTime = lastSyncTime;
1182 }
1183 ds.failureCount++;
1184 ds.failureTime += elapsedTime;
1185 }
Costin Manolache360e4542009-09-04 13:36:04 -07001186
Dianne Hackborn231cc602009-04-27 17:10:36 -07001187 if (writeStatusNow) {
1188 writeStatusLocked();
1189 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1190 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1191 WRITE_STATUS_DELAY);
1192 }
1193 if (writeStatisticsNow) {
1194 writeStatisticsLocked();
1195 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1196 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1197 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001198 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001199 }
Costin Manolache360e4542009-09-04 13:36:04 -07001200
Fred Quintanaac9385e2009-06-22 18:00:59 -07001201 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001202 }
1203
1204 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001205 * Return a list of the currently active syncs. Note that the returned items are the
1206 * real, live active sync objects, so be careful what you do with it.
1207 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001208 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001209 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001210 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1211 if (syncs == null) {
1212 syncs = new ArrayList<SyncInfo>();
1213 mCurrentSyncs.put(userId, syncs);
1214 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001215 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001216 }
1217 }
Costin Manolache360e4542009-09-04 13:36:04 -07001218
Dianne Hackborn231cc602009-04-27 17:10:36 -07001219 /**
1220 * Return an array of the current sync status for all authorities. Note
1221 * that the objects inside the array are the real, live status objects,
1222 * so be careful what you do with them.
1223 */
1224 public ArrayList<SyncStatusInfo> getSyncStatus() {
1225 synchronized (mAuthorities) {
1226 final int N = mSyncStatus.size();
1227 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1228 for (int i=0; i<N; i++) {
1229 ops.add(mSyncStatus.valueAt(i));
1230 }
1231 return ops;
1232 }
1233 }
Costin Manolache360e4542009-09-04 13:36:04 -07001234
Dianne Hackborn231cc602009-04-27 17:10:36 -07001235 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001236 * Return an array of the current authorities. Note
1237 * that the objects inside the array are the real, live objects,
1238 * so be careful what you do with them.
1239 */
1240 public ArrayList<AuthorityInfo> getAuthorities() {
1241 synchronized (mAuthorities) {
1242 final int N = mAuthorities.size();
1243 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1244 for (int i=0; i<N; i++) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -07001245 // Make deep copy because AuthorityInfo syncs are liable to change.
1246 infos.add(new AuthorityInfo(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001247 }
1248 return infos;
1249 }
1250 }
1251
1252 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001253 * Returns the status that matches the authority and account.
1254 *
1255 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001256 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001257 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001258 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001259 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1260 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001261 if (account == null || authority == null) {
1262 throw new IllegalArgumentException();
1263 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001264 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001265 final int N = mSyncStatus.size();
1266 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001267 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001268 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001269
Amith Yamasani04e0d262012-02-14 11:50:53 -08001270 if (ainfo != null && ainfo.authority.equals(authority)
1271 && ainfo.userId == userId
1272 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001273 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001274 }
1275 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001276 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001277 }
1278 }
Costin Manolache360e4542009-09-04 13:36:04 -07001279
Dianne Hackborn231cc602009-04-27 17:10:36 -07001280 /**
1281 * Return true if the pending status is true of any matching authorities.
1282 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001283 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001284 synchronized (mAuthorities) {
1285 final int N = mSyncStatus.size();
1286 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001287 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001288 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1289 if (ainfo == null) {
1290 continue;
1291 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001292 if (userId != ainfo.userId) {
1293 continue;
1294 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001295 if (account != null && !ainfo.account.equals(account)) {
1296 continue;
1297 }
1298 if (ainfo.authority.equals(authority) && cur.pending) {
1299 return true;
1300 }
1301 }
1302 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
1304 }
1305
1306 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001307 * Return an array of the current sync status for all authorities. Note
1308 * that the objects inside the array are the real, live status objects,
1309 * so be careful what you do with them.
1310 */
1311 public ArrayList<SyncHistoryItem> getSyncHistory() {
1312 synchronized (mAuthorities) {
1313 final int N = mSyncHistory.size();
1314 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1315 for (int i=0; i<N; i++) {
1316 items.add(mSyncHistory.get(i));
1317 }
1318 return items;
1319 }
1320 }
Costin Manolache360e4542009-09-04 13:36:04 -07001321
Dianne Hackborn231cc602009-04-27 17:10:36 -07001322 /**
1323 * Return an array of the current per-day statistics. Note
1324 * that the objects inside the array are the real, live status objects,
1325 * so be careful what you do with them.
1326 */
1327 public DayStats[] getDayStatistics() {
1328 synchronized (mAuthorities) {
1329 DayStats[] ds = new DayStats[mDayStats.length];
1330 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1331 return ds;
1332 }
1333 }
Costin Manolache360e4542009-09-04 13:36:04 -07001334
Dianne Hackborn55280a92009-05-07 15:53:46 -07001335 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001336 mCal.setTimeInMillis(System.currentTimeMillis());
1337 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1338 if (mYear != mCal.get(Calendar.YEAR)) {
1339 mYear = mCal.get(Calendar.YEAR);
1340 mCal.clear();
1341 mCal.set(Calendar.YEAR, mYear);
1342 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1343 }
1344 return dayOfYear + mYearInDays;
1345 }
Costin Manolache360e4542009-09-04 13:36:04 -07001346
Dianne Hackborn231cc602009-04-27 17:10:36 -07001347 /**
1348 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001349 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001350 * @param accountName The name of the account for the authority.
1351 * @param authorityName The name of the authority itself.
1352 * @param tag If non-null, this will be used in a log message if the
1353 * requested authority does not exist.
1354 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001355 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001356 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001357 AccountAndUser au = new AccountAndUser(accountName, userId);
1358 AccountInfo accountInfo = mAccounts.get(au);
1359 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001360 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001361 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001362 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001363 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001364 }
1365 return null;
1366 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001367 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001368 if (authority == null) {
1369 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001370 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1371 Log.v(TAG, tag + ": unknown authority " + authorityName);
1372 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001373 }
1374 return null;
1375 }
Costin Manolache360e4542009-09-04 13:36:04 -07001376
Dianne Hackborn231cc602009-04-27 17:10:36 -07001377 return authority;
1378 }
Costin Manolache360e4542009-09-04 13:36:04 -07001379
Amith Yamasani04e0d262012-02-14 11:50:53 -08001380 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001381 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001382 AccountAndUser au = new AccountAndUser(accountName, userId);
1383 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001384 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001385 account = new AccountInfo(au);
1386 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001387 }
1388 AuthorityInfo authority = account.authorities.get(authorityName);
1389 if (authority == null) {
1390 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001391 ident = mNextAuthorityId;
1392 mNextAuthorityId++;
1393 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001394 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001395 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1396 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001397 + ", user " + userId
1398 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001399 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001400 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001401 account.authorities.put(authorityName, authority);
1402 mAuthorities.put(ident, authority);
1403 if (doWrite) {
1404 writeAccountInfoLocked();
1405 }
1406 }
Costin Manolache360e4542009-09-04 13:36:04 -07001407
Dianne Hackborn231cc602009-04-27 17:10:36 -07001408 return authority;
1409 }
Costin Manolache360e4542009-09-04 13:36:04 -07001410
Amith Yamasani04e0d262012-02-14 11:50:53 -08001411 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1412 boolean doWrite) {
1413 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001414 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001415 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1416 if (authorityInfo != null) {
1417 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001418 if (doWrite) {
1419 writeAccountInfoLocked();
1420 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001421 }
1422 }
1423 }
1424
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001425 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1426 synchronized (mAuthorities) {
1427 return getOrCreateSyncStatusLocked(authority.ident);
1428 }
1429 }
1430
Dianne Hackborn231cc602009-04-27 17:10:36 -07001431 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1432 SyncStatusInfo status = mSyncStatus.get(authorityId);
1433 if (status == null) {
1434 status = new SyncStatusInfo(authorityId);
1435 mSyncStatus.put(authorityId, status);
1436 }
1437 return status;
1438 }
Costin Manolache360e4542009-09-04 13:36:04 -07001439
Dianne Hackborn55280a92009-05-07 15:53:46 -07001440 public void writeAllState() {
1441 synchronized (mAuthorities) {
1442 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001443
Dianne Hackborn55280a92009-05-07 15:53:46 -07001444 if (mNumPendingFinished > 0) {
1445 // Only write these if they are out of date.
1446 writePendingOperationsLocked();
1447 }
Costin Manolache360e4542009-09-04 13:36:04 -07001448
Dianne Hackborn55280a92009-05-07 15:53:46 -07001449 // Just always write these... they are likely out of date.
1450 writeStatusLocked();
1451 writeStatisticsLocked();
1452 }
1453 }
Costin Manolache360e4542009-09-04 13:36:04 -07001454
Dianne Hackborn231cc602009-04-27 17:10:36 -07001455 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001456 * public for testing
1457 */
1458 public void clearAndReadState() {
1459 synchronized (mAuthorities) {
1460 mAuthorities.clear();
1461 mAccounts.clear();
1462 mPendingOperations.clear();
1463 mSyncStatus.clear();
1464 mSyncHistory.clear();
1465
1466 readAccountInfoLocked();
1467 readStatusLocked();
1468 readPendingOperationsLocked();
1469 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001470 readAndDeleteLegacyAccountInfoLocked();
1471 writeAccountInfoLocked();
1472 writeStatusLocked();
1473 writePendingOperationsLocked();
1474 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001475 }
1476 }
1477
1478 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001479 * Read all account information back in to the initial engine state.
1480 */
1481 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001482 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001483 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001485 fis = mAccountInfoFile.openRead();
1486 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1487 XmlPullParser parser = Xml.newPullParser();
1488 parser.setInput(fis, null);
1489 int eventType = parser.getEventType();
1490 while (eventType != XmlPullParser.START_TAG) {
1491 eventType = parser.next();
1492 }
1493 String tagName = parser.getName();
1494 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001495 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001496 String versionString = parser.getAttributeValue(null, "version");
1497 int version;
1498 try {
1499 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1500 } catch (NumberFormatException e) {
1501 version = 0;
1502 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001503 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001504 try {
1505 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1506 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1507 } catch (NumberFormatException e) {
1508 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001509 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001510 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1511 try {
1512 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1513 } catch (NumberFormatException e) {
1514 mSyncRandomOffset = 0;
1515 }
1516 if (mSyncRandomOffset == 0) {
1517 Random random = new Random(System.currentTimeMillis());
1518 mSyncRandomOffset = random.nextInt(86400);
1519 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001520 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001521 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001522 AuthorityInfo authority = null;
1523 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001524 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001525 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001526 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001527 if (parser.getDepth() == 2) {
1528 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001529 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001530 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001531 if (authority.ident > highestAuthorityId) {
1532 highestAuthorityId = authority.ident;
1533 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001534 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1535 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001536 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001537 } else if (parser.getDepth() == 3) {
1538 if ("periodicSync".equals(tagName) && authority != null) {
1539 periodicSync = parsePeriodicSync(parser, authority);
1540 }
1541 } else if (parser.getDepth() == 4 && periodicSync != null) {
1542 if ("extra".equals(tagName)) {
1543 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001544 }
1545 }
1546 }
1547 eventType = parser.next();
1548 } while (eventType != XmlPullParser.END_DOCUMENT);
1549 }
1550 } catch (XmlPullParserException e) {
1551 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001552 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001553 } catch (java.io.IOException e) {
1554 if (fis == null) Log.i(TAG, "No initial accounts");
1555 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001556 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001557 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001558 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001559 if (fis != null) {
1560 try {
1561 fis.close();
1562 } catch (java.io.IOException e1) {
1563 }
1564 }
1565 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001566
Fred Quintana77c560f2010-03-29 22:20:26 -07001567 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001568 }
Costin Manolache360e4542009-09-04 13:36:04 -07001569
Fred Quintanafb084402010-03-23 17:57:03 -07001570 /**
1571 * some authority names have changed. copy over their settings and delete the old ones
1572 * @return true if a change was made
1573 */
1574 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1575 boolean writeNeeded = false;
1576
1577 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1578 final int N = mAuthorities.size();
1579 for (int i=0; i<N; i++) {
1580 AuthorityInfo authority = mAuthorities.valueAt(i);
1581 // skip this authority if it isn't one of the renamed ones
1582 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1583 if (newAuthorityName == null) {
1584 continue;
1585 }
1586
1587 // remember this authority so we can remove it later. we can't remove it
1588 // now without messing up this loop iteration
1589 authoritiesToRemove.add(authority);
1590
1591 // this authority isn't enabled, no need to copy it to the new authority name since
1592 // the default is "disabled"
1593 if (!authority.enabled) {
1594 continue;
1595 }
1596
1597 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001598 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1599 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001600 continue;
1601 }
1602
1603 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001604 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001605 newAuthority.enabled = true;
1606 writeNeeded = true;
1607 }
1608
1609 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001610 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1611 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001612 writeNeeded = true;
1613 }
1614
1615 return writeNeeded;
1616 }
1617
Amith Yamasani04e0d262012-02-14 11:50:53 -08001618 private void parseListenForTickles(XmlPullParser parser) {
1619 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1620 int userId = 0;
1621 try {
1622 userId = Integer.parseInt(user);
1623 } catch (NumberFormatException e) {
1624 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1625 } catch (NullPointerException e) {
1626 Log.e(TAG, "the user in listen-for-tickles is null", e);
1627 }
1628 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1629 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1630 mMasterSyncAutomatically.put(userId, listen);
1631 }
1632
Fred Quintanac2e46912010-03-15 16:10:44 -07001633 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001634 AuthorityInfo authority = null;
1635 int id = -1;
1636 try {
1637 id = Integer.parseInt(parser.getAttributeValue(
1638 null, "id"));
1639 } catch (NumberFormatException e) {
1640 Log.e(TAG, "error parsing the id of the authority", e);
1641 } catch (NullPointerException e) {
1642 Log.e(TAG, "the id of the authority is null", e);
1643 }
1644 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001645 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001646 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001647 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001648 String accountName = parser.getAttributeValue(null, "account");
1649 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001650 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1651 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001652 if (accountType == null) {
1653 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001654 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001655 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001656 authority = mAuthorities.get(id);
1657 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1658 + accountName + " auth=" + authorityName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001659 + " user=" + userId
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001660 + " enabled=" + enabled
1661 + " syncable=" + syncable);
1662 if (authority == null) {
1663 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1664 authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001665 new Account(accountName, accountType), userId, authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001666 // If the version is 0 then we are upgrading from a file format that did not
1667 // know about periodic syncs. In that case don't clear the list since we
1668 // want the default, which is a daily periodioc sync.
1669 // Otherwise clear out this default list since we will populate it later with
1670 // the periodic sync descriptions that are read from the configuration file.
1671 if (version > 0) {
1672 authority.periodicSyncs.clear();
1673 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001674 }
1675 if (authority != null) {
1676 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1677 if ("unknown".equals(syncable)) {
1678 authority.syncable = -1;
1679 } else {
1680 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001681 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001682 }
1683 } else {
1684 Log.w(TAG, "Failure adding authority: account="
1685 + accountName + " auth=" + authorityName
1686 + " enabled=" + enabled
1687 + " syncable=" + syncable);
1688 }
1689 }
1690
1691 return authority;
1692 }
1693
1694 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1695 Bundle extras = new Bundle();
1696 String periodValue = parser.getAttributeValue(null, "period");
1697 final long period;
1698 try {
1699 period = Long.parseLong(periodValue);
1700 } catch (NumberFormatException e) {
1701 Log.e(TAG, "error parsing the period of a periodic sync", e);
1702 return null;
1703 } catch (NullPointerException e) {
1704 Log.e(TAG, "the period of a periodic sync is null", e);
1705 return null;
1706 }
1707 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1708 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001709
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001710 return periodicSync;
1711 }
1712
1713 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1714 final Bundle extras = periodicSync.first;
1715 String name = parser.getAttributeValue(null, "name");
1716 String type = parser.getAttributeValue(null, "type");
1717 String value1 = parser.getAttributeValue(null, "value1");
1718 String value2 = parser.getAttributeValue(null, "value2");
1719
1720 try {
1721 if ("long".equals(type)) {
1722 extras.putLong(name, Long.parseLong(value1));
1723 } else if ("integer".equals(type)) {
1724 extras.putInt(name, Integer.parseInt(value1));
1725 } else if ("double".equals(type)) {
1726 extras.putDouble(name, Double.parseDouble(value1));
1727 } else if ("float".equals(type)) {
1728 extras.putFloat(name, Float.parseFloat(value1));
1729 } else if ("boolean".equals(type)) {
1730 extras.putBoolean(name, Boolean.parseBoolean(value1));
1731 } else if ("string".equals(type)) {
1732 extras.putString(name, value1);
1733 } else if ("account".equals(type)) {
1734 extras.putParcelable(name, new Account(value1, value2));
1735 }
1736 } catch (NumberFormatException e) {
1737 Log.e(TAG, "error parsing bundle value", e);
1738 } catch (NullPointerException e) {
1739 Log.e(TAG, "error parsing bundle value", e);
1740 }
1741 }
1742
Dianne Hackborn231cc602009-04-27 17:10:36 -07001743 /**
1744 * Write all account information to the account file.
1745 */
1746 private void writeAccountInfoLocked() {
1747 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1748 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001749
Dianne Hackborn231cc602009-04-27 17:10:36 -07001750 try {
1751 fos = mAccountInfoFile.startWrite();
1752 XmlSerializer out = new FastXmlSerializer();
1753 out.setOutput(fos, "utf-8");
1754 out.startDocument(null, true);
1755 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001756
Dianne Hackborn231cc602009-04-27 17:10:36 -07001757 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001758 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001759 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001760 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001761
1762 // Write the Sync Automatically flags for each user
1763 final int M = mMasterSyncAutomatically.size();
1764 for (int m = 0; m < M; m++) {
1765 int userId = mMasterSyncAutomatically.keyAt(m);
1766 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1767 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1768 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1769 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1770 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001771 }
Costin Manolache360e4542009-09-04 13:36:04 -07001772
Dianne Hackborn231cc602009-04-27 17:10:36 -07001773 final int N = mAuthorities.size();
1774 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001775 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001776 out.startTag(null, "authority");
1777 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001778 out.attribute(null, "account", authority.account.name);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001779 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001780 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001781 out.attribute(null, "authority", authority.authority);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001782 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Fred Quintana5e787c42009-08-16 23:13:53 -07001783 if (authority.syncable < 0) {
1784 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001785 } else {
1786 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001787 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001788 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1789 out.startTag(null, "periodicSync");
1790 out.attribute(null, "period", Long.toString(periodicSync.second));
1791 final Bundle extras = periodicSync.first;
1792 for (String key : extras.keySet()) {
1793 out.startTag(null, "extra");
1794 out.attribute(null, "name", key);
1795 final Object value = extras.get(key);
1796 if (value instanceof Long) {
1797 out.attribute(null, "type", "long");
1798 out.attribute(null, "value1", value.toString());
1799 } else if (value instanceof Integer) {
1800 out.attribute(null, "type", "integer");
1801 out.attribute(null, "value1", value.toString());
1802 } else if (value instanceof Boolean) {
1803 out.attribute(null, "type", "boolean");
1804 out.attribute(null, "value1", value.toString());
1805 } else if (value instanceof Float) {
1806 out.attribute(null, "type", "float");
1807 out.attribute(null, "value1", value.toString());
1808 } else if (value instanceof Double) {
1809 out.attribute(null, "type", "double");
1810 out.attribute(null, "value1", value.toString());
1811 } else if (value instanceof String) {
1812 out.attribute(null, "type", "string");
1813 out.attribute(null, "value1", value.toString());
1814 } else if (value instanceof Account) {
1815 out.attribute(null, "type", "account");
1816 out.attribute(null, "value1", ((Account)value).name);
1817 out.attribute(null, "value2", ((Account)value).type);
1818 }
1819 out.endTag(null, "extra");
1820 }
1821 out.endTag(null, "periodicSync");
1822 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001823 out.endTag(null, "authority");
1824 }
Costin Manolache360e4542009-09-04 13:36:04 -07001825
Dianne Hackborn231cc602009-04-27 17:10:36 -07001826 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001827
Dianne Hackborn231cc602009-04-27 17:10:36 -07001828 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001829
Dianne Hackborn231cc602009-04-27 17:10:36 -07001830 mAccountInfoFile.finishWrite(fos);
1831 } catch (java.io.IOException e1) {
1832 Log.w(TAG, "Error writing accounts", e1);
1833 if (fos != null) {
1834 mAccountInfoFile.failWrite(fos);
1835 }
1836 }
1837 }
Costin Manolache360e4542009-09-04 13:36:04 -07001838
Dianne Hackborn231cc602009-04-27 17:10:36 -07001839 static int getIntColumn(Cursor c, String name) {
1840 return c.getInt(c.getColumnIndex(name));
1841 }
Costin Manolache360e4542009-09-04 13:36:04 -07001842
Dianne Hackborn231cc602009-04-27 17:10:36 -07001843 static long getLongColumn(Cursor c, String name) {
1844 return c.getLong(c.getColumnIndex(name));
1845 }
Costin Manolache360e4542009-09-04 13:36:04 -07001846
Dianne Hackborn231cc602009-04-27 17:10:36 -07001847 /**
1848 * Load sync engine state from the old syncmanager database, and then
1849 * erase it. Note that we don't deal with pending operations, active
1850 * sync, or history.
1851 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001852 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001853 // Look for old database to initialize from.
1854 File file = mContext.getDatabasePath("syncmanager.db");
1855 if (!file.exists()) {
1856 return;
1857 }
1858 String path = file.getPath();
1859 SQLiteDatabase db = null;
1860 try {
1861 db = SQLiteDatabase.openDatabase(path, null,
1862 SQLiteDatabase.OPEN_READONLY);
1863 } catch (SQLiteException e) {
1864 }
Costin Manolache360e4542009-09-04 13:36:04 -07001865
Dianne Hackborn231cc602009-04-27 17:10:36 -07001866 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001867 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001868
Dianne Hackborn231cc602009-04-27 17:10:36 -07001869 // Copy in all of the status information, as well as accounts.
1870 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1871 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1872 qb.setTables("stats, status");
1873 HashMap<String,String> map = new HashMap<String,String>();
1874 map.put("_id", "status._id as _id");
1875 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001876 if (hasType) {
1877 map.put("account_type", "stats.account_type as account_type");
1878 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001879 map.put("authority", "stats.authority as authority");
1880 map.put("totalElapsedTime", "totalElapsedTime");
1881 map.put("numSyncs", "numSyncs");
1882 map.put("numSourceLocal", "numSourceLocal");
1883 map.put("numSourcePoll", "numSourcePoll");
1884 map.put("numSourceServer", "numSourceServer");
1885 map.put("numSourceUser", "numSourceUser");
1886 map.put("lastSuccessSource", "lastSuccessSource");
1887 map.put("lastSuccessTime", "lastSuccessTime");
1888 map.put("lastFailureSource", "lastFailureSource");
1889 map.put("lastFailureTime", "lastFailureTime");
1890 map.put("lastFailureMesg", "lastFailureMesg");
1891 map.put("pending", "pending");
1892 qb.setProjectionMap(map);
1893 qb.appendWhere("stats._id = status.stats_id");
1894 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001896 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001897 String accountType = hasType
1898 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001899 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001900 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001902 String authorityName = c.getString(c.getColumnIndex("authority"));
1903 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001904 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07001905 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001906 if (authority != null) {
1907 int i = mSyncStatus.size();
1908 boolean found = false;
1909 SyncStatusInfo st = null;
1910 while (i > 0) {
1911 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001912 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001913 if (st.authorityId == authority.ident) {
1914 found = true;
1915 break;
1916 }
1917 }
1918 if (!found) {
1919 st = new SyncStatusInfo(authority.ident);
1920 mSyncStatus.put(authority.ident, st);
1921 }
1922 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1923 st.numSyncs = getIntColumn(c, "numSyncs");
1924 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1925 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1926 st.numSourceServer = getIntColumn(c, "numSourceServer");
1927 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001928 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001929 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1930 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1931 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1932 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1933 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1934 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
Costin Manolache360e4542009-09-04 13:36:04 -07001937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001939
Dianne Hackborn231cc602009-04-27 17:10:36 -07001940 // Retrieve the settings.
1941 qb = new SQLiteQueryBuilder();
1942 qb.setTables("settings");
1943 c = qb.query(db, null, null, null, null, null, null);
1944 while (c.moveToNext()) {
1945 String name = c.getString(c.getColumnIndex("name"));
1946 String value = c.getString(c.getColumnIndex("value"));
1947 if (name == null) continue;
1948 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001949 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001950 } else if (name.startsWith("sync_provider_")) {
1951 String provider = name.substring("sync_provider_".length(),
1952 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001953 int i = mAuthorities.size();
1954 while (i > 0) {
1955 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001956 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001957 if (authority.authority.equals(provider)) {
1958 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001959 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001960 }
1961 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 }
Costin Manolache360e4542009-09-04 13:36:04 -07001964
Dianne Hackborn231cc602009-04-27 17:10:36 -07001965 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001966
Dianne Hackborn231cc602009-04-27 17:10:36 -07001967 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001968
Dianne Hackborn231cc602009-04-27 17:10:36 -07001969 (new File(path)).delete();
1970 }
1971 }
Costin Manolache360e4542009-09-04 13:36:04 -07001972
Dianne Hackborn231cc602009-04-27 17:10:36 -07001973 public static final int STATUS_FILE_END = 0;
1974 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001975
Dianne Hackborn231cc602009-04-27 17:10:36 -07001976 /**
1977 * Read all sync status back in to the initial engine state.
1978 */
1979 private void readStatusLocked() {
1980 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1981 try {
1982 byte[] data = mStatusFile.readFully();
1983 Parcel in = Parcel.obtain();
1984 in.unmarshall(data, 0, data.length);
1985 in.setDataPosition(0);
1986 int token;
1987 while ((token=in.readInt()) != STATUS_FILE_END) {
1988 if (token == STATUS_FILE_ITEM) {
1989 SyncStatusInfo status = new SyncStatusInfo(in);
1990 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1991 status.pending = false;
1992 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
1993 + status.authorityId);
1994 mSyncStatus.put(status.authorityId, status);
1995 }
1996 } else {
1997 // Ooops.
1998 Log.w(TAG, "Unknown status token: " + token);
1999 break;
2000 }
2001 }
2002 } catch (java.io.IOException e) {
2003 Log.i(TAG, "No initial status");
2004 }
2005 }
Costin Manolache360e4542009-09-04 13:36:04 -07002006
Dianne Hackborn231cc602009-04-27 17:10:36 -07002007 /**
2008 * Write all sync status to the sync status file.
2009 */
2010 private void writeStatusLocked() {
2011 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002012
Dianne Hackborn231cc602009-04-27 17:10:36 -07002013 // The file is being written, so we don't need to have a scheduled
2014 // write until the next change.
2015 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002016
Dianne Hackborn231cc602009-04-27 17:10:36 -07002017 FileOutputStream fos = null;
2018 try {
2019 fos = mStatusFile.startWrite();
2020 Parcel out = Parcel.obtain();
2021 final int N = mSyncStatus.size();
2022 for (int i=0; i<N; i++) {
2023 SyncStatusInfo status = mSyncStatus.valueAt(i);
2024 out.writeInt(STATUS_FILE_ITEM);
2025 status.writeToParcel(out, 0);
2026 }
2027 out.writeInt(STATUS_FILE_END);
2028 fos.write(out.marshall());
2029 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002030
Dianne Hackborn231cc602009-04-27 17:10:36 -07002031 mStatusFile.finishWrite(fos);
2032 } catch (java.io.IOException e1) {
2033 Log.w(TAG, "Error writing status", e1);
2034 if (fos != null) {
2035 mStatusFile.failWrite(fos);
2036 }
2037 }
2038 }
Costin Manolache360e4542009-09-04 13:36:04 -07002039
Fred Quintana307da1a2010-01-21 14:24:20 -08002040 public static final int PENDING_OPERATION_VERSION = 2;
Costin Manolache360e4542009-09-04 13:36:04 -07002041
Dianne Hackborn231cc602009-04-27 17:10:36 -07002042 /**
2043 * Read all pending operations back in to the initial engine state.
2044 */
2045 private void readPendingOperationsLocked() {
2046 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
2047 try {
2048 byte[] data = mPendingFile.readFully();
2049 Parcel in = Parcel.obtain();
2050 in.unmarshall(data, 0, data.length);
2051 in.setDataPosition(0);
2052 final int SIZE = in.dataSize();
2053 while (in.dataPosition() < SIZE) {
2054 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08002055 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002056 Log.w(TAG, "Unknown pending operation version "
2057 + version + "; dropping all ops");
2058 break;
2059 }
2060 int authorityId = in.readInt();
2061 int syncSource = in.readInt();
2062 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08002063 boolean expedited;
2064 if (version == PENDING_OPERATION_VERSION) {
2065 expedited = in.readInt() != 0;
2066 } else {
2067 expedited = false;
2068 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002069 AuthorityInfo authority = mAuthorities.get(authorityId);
2070 if (authority != null) {
Fred Quintana5695c7b2010-12-06 15:07:52 -08002071 Bundle extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002072 if (flatExtras != null) {
2073 extras = unflattenBundle(flatExtras);
Fred Quintana5695c7b2010-12-06 15:07:52 -08002074 } else {
2075 // if we are unable to parse the extras for whatever reason convert this
2076 // to a regular sync by creating an empty extras
2077 extras = new Bundle();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002078 }
2079 PendingOperation op = new PendingOperation(
Amith Yamasani04e0d262012-02-14 11:50:53 -08002080 authority.account, authority.userId, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08002081 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002082 op.authorityId = authorityId;
2083 op.flatExtras = flatExtras;
2084 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
2085 + " auth=" + op.authority
2086 + " src=" + op.syncSource
Fred Quintana307da1a2010-01-21 14:24:20 -08002087 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07002088 + " extras=" + op.extras);
2089 mPendingOperations.add(op);
2090 }
2091 }
2092 } catch (java.io.IOException e) {
2093 Log.i(TAG, "No initial pending operations");
2094 }
2095 }
Costin Manolache360e4542009-09-04 13:36:04 -07002096
Dianne Hackborn231cc602009-04-27 17:10:36 -07002097 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
2098 out.writeInt(PENDING_OPERATION_VERSION);
2099 out.writeInt(op.authorityId);
2100 out.writeInt(op.syncSource);
2101 if (op.flatExtras == null && op.extras != null) {
2102 op.flatExtras = flattenBundle(op.extras);
2103 }
2104 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08002105 out.writeInt(op.expedited ? 1 : 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002106 }
Costin Manolache360e4542009-09-04 13:36:04 -07002107
Dianne Hackborn231cc602009-04-27 17:10:36 -07002108 /**
2109 * Write all currently pending ops to the pending ops file.
2110 */
2111 private void writePendingOperationsLocked() {
2112 final int N = mPendingOperations.size();
2113 FileOutputStream fos = null;
2114 try {
2115 if (N == 0) {
2116 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2117 mPendingFile.truncate();
2118 return;
2119 }
Costin Manolache360e4542009-09-04 13:36:04 -07002120
Dianne Hackborn231cc602009-04-27 17:10:36 -07002121 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2122 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07002123
Dianne Hackborn231cc602009-04-27 17:10:36 -07002124 Parcel out = Parcel.obtain();
2125 for (int i=0; i<N; i++) {
2126 PendingOperation op = mPendingOperations.get(i);
2127 writePendingOperationLocked(op, out);
2128 }
2129 fos.write(out.marshall());
2130 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002131
Dianne Hackborn231cc602009-04-27 17:10:36 -07002132 mPendingFile.finishWrite(fos);
2133 } catch (java.io.IOException e1) {
2134 Log.w(TAG, "Error writing pending operations", e1);
2135 if (fos != null) {
2136 mPendingFile.failWrite(fos);
2137 }
2138 }
2139 }
Costin Manolache360e4542009-09-04 13:36:04 -07002140
Dianne Hackborn231cc602009-04-27 17:10:36 -07002141 /**
2142 * Append the given operation to the pending ops file; if unable to,
2143 * write all pending ops.
2144 */
2145 private void appendPendingOperationLocked(PendingOperation op) {
2146 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2147 FileOutputStream fos = null;
2148 try {
2149 fos = mPendingFile.openAppend();
2150 } catch (java.io.IOException e) {
2151 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2152 writePendingOperationsLocked();
2153 return;
2154 }
Costin Manolache360e4542009-09-04 13:36:04 -07002155
Dianne Hackborn231cc602009-04-27 17:10:36 -07002156 try {
2157 Parcel out = Parcel.obtain();
2158 writePendingOperationLocked(op, out);
2159 fos.write(out.marshall());
2160 out.recycle();
2161 } catch (java.io.IOException e1) {
2162 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002164 try {
2165 fos.close();
2166 } catch (java.io.IOException e2) {
2167 }
2168 }
2169 }
Costin Manolache360e4542009-09-04 13:36:04 -07002170
Dianne Hackborn231cc602009-04-27 17:10:36 -07002171 static private byte[] flattenBundle(Bundle bundle) {
2172 byte[] flatData = null;
2173 Parcel parcel = Parcel.obtain();
2174 try {
2175 bundle.writeToParcel(parcel, 0);
2176 flatData = parcel.marshall();
2177 } finally {
2178 parcel.recycle();
2179 }
2180 return flatData;
2181 }
Costin Manolache360e4542009-09-04 13:36:04 -07002182
Dianne Hackborn231cc602009-04-27 17:10:36 -07002183 static private Bundle unflattenBundle(byte[] flatData) {
2184 Bundle bundle;
2185 Parcel parcel = Parcel.obtain();
2186 try {
2187 parcel.unmarshall(flatData, 0, flatData.length);
2188 parcel.setDataPosition(0);
2189 bundle = parcel.readBundle();
2190 } catch (RuntimeException e) {
2191 // A RuntimeException is thrown if we were unable to parse the parcel.
2192 // Create an empty parcel in this case.
2193 bundle = new Bundle();
2194 } finally {
2195 parcel.recycle();
2196 }
2197 return bundle;
2198 }
Costin Manolache360e4542009-09-04 13:36:04 -07002199
Amith Yamasani04e0d262012-02-14 11:50:53 -08002200 private void requestSync(Account account, int userId, String authority, Bundle extras) {
2201 // If this is happening in the system process, then call the syncrequest listener
2202 // to make a request back to the SyncManager directly.
2203 // If this is probably a test instance, then call back through the ContentResolver
2204 // which will know which userId to apply based on the Binder id.
2205 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2206 && mSyncRequestListener != null) {
2207 mSyncRequestListener.onSyncRequest(account, userId, authority, extras);
2208 } else {
2209 ContentResolver.requestSync(account, authority, extras);
2210 }
2211 }
2212
Dianne Hackborn231cc602009-04-27 17:10:36 -07002213 public static final int STATISTICS_FILE_END = 0;
2214 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2215 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002216
Dianne Hackborn231cc602009-04-27 17:10:36 -07002217 /**
2218 * Read all sync statistics back in to the initial engine state.
2219 */
2220 private void readStatisticsLocked() {
2221 try {
2222 byte[] data = mStatisticsFile.readFully();
2223 Parcel in = Parcel.obtain();
2224 in.unmarshall(data, 0, data.length);
2225 in.setDataPosition(0);
2226 int token;
2227 int index = 0;
2228 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2229 if (token == STATISTICS_FILE_ITEM
2230 || token == STATISTICS_FILE_ITEM_OLD) {
2231 int day = in.readInt();
2232 if (token == STATISTICS_FILE_ITEM_OLD) {
2233 day = day - 2009 + 14245; // Magic!
2234 }
2235 DayStats ds = new DayStats(day);
2236 ds.successCount = in.readInt();
2237 ds.successTime = in.readLong();
2238 ds.failureCount = in.readInt();
2239 ds.failureTime = in.readLong();
2240 if (index < mDayStats.length) {
2241 mDayStats[index] = ds;
2242 index++;
2243 }
2244 } else {
2245 // Ooops.
2246 Log.w(TAG, "Unknown stats token: " + token);
2247 break;
2248 }
2249 }
2250 } catch (java.io.IOException e) {
2251 Log.i(TAG, "No initial statistics");
2252 }
2253 }
Costin Manolache360e4542009-09-04 13:36:04 -07002254
Dianne Hackborn231cc602009-04-27 17:10:36 -07002255 /**
2256 * Write all sync statistics to the sync status file.
2257 */
2258 private void writeStatisticsLocked() {
2259 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002260
Dianne Hackborn231cc602009-04-27 17:10:36 -07002261 // The file is being written, so we don't need to have a scheduled
2262 // write until the next change.
2263 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002264
Dianne Hackborn231cc602009-04-27 17:10:36 -07002265 FileOutputStream fos = null;
2266 try {
2267 fos = mStatisticsFile.startWrite();
2268 Parcel out = Parcel.obtain();
2269 final int N = mDayStats.length;
2270 for (int i=0; i<N; i++) {
2271 DayStats ds = mDayStats[i];
2272 if (ds == null) {
2273 break;
2274 }
2275 out.writeInt(STATISTICS_FILE_ITEM);
2276 out.writeInt(ds.day);
2277 out.writeInt(ds.successCount);
2278 out.writeLong(ds.successTime);
2279 out.writeInt(ds.failureCount);
2280 out.writeLong(ds.failureTime);
2281 }
2282 out.writeInt(STATISTICS_FILE_END);
2283 fos.write(out.marshall());
2284 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002285
Dianne Hackborn231cc602009-04-27 17:10:36 -07002286 mStatisticsFile.finishWrite(fos);
2287 } catch (java.io.IOException e1) {
2288 Log.w(TAG, "Error writing stats", e1);
2289 if (fos != null) {
2290 mStatisticsFile.failWrite(fos);
2291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 }
2293 }
2294}