blob: 10e7bff785d4dd10db56717d2bb13137756541de [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080017package android.content;
18
Dianne Hackborn231cc602009-04-27 17:10:36 -070019import com.android.internal.util.ArrayUtils;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080020import com.android.internal.util.FastXmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021
Jason parksa3cdaa52011-01-13 14:15:43 -060022import org.xmlpull.v1.XmlPullParser;
23import org.xmlpull.v1.XmlPullParserException;
24import org.xmlpull.v1.XmlSerializer;
25
Fred Quintanad9d2f112009-04-23 13:36:27 -070026import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070027import android.accounts.AccountAndUser;
Yameng Huang2b5d0ea2011-01-11 14:00:19 +080028import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070031import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070033import android.os.Bundle;
34import android.os.Environment;
35import android.os.Handler;
36import android.os.Message;
37import android.os.Parcel;
38import android.os.RemoteCallbackList;
39import android.os.RemoteException;
Dianne Hackborn39606a02012-07-31 17:54:35 -070040import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.util.Log;
Dianne Hackborn231cc602009-04-27 17:10:36 -070042import android.util.SparseArray;
43import android.util.Xml;
Jason parksa3cdaa52011-01-13 14:15:43 -060044import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045
Dianne Hackborn231cc602009-04-27 17:10:36 -070046import java.io.File;
47import java.io.FileInputStream;
48import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070050import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070052import java.util.Iterator;
Ashish Sharma69d95de2012-04-11 17:27:24 -070053import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060054import java.util.TimeZone;
Jason parksa3cdaa52011-01-13 14:15:43 -060055import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
57/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070058 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070060 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061 * @hide
62 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070063public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 private static final String TAG = "SyncManager";
Dianne Hackborn231cc602009-04-27 17:10:36 -070066 private static final boolean DEBUG_FILE = false;
Costin Manolache360e4542009-09-04 13:36:04 -070067
Amith Yamasani04e0d262012-02-14 11:50:53 -080068 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
69 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070070 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080071 private static final String XML_ATTR_ENABLED = "enabled";
72 private static final String XML_ATTR_USER = "user";
73 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
74
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080075 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
76
Dianne Hackborn231cc602009-04-27 17:10:36 -070077 // @VisibleForTesting
78 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
Dianne Hackborn231cc602009-04-27 17:10:36 -070080 /** Enum value for a sync start event. */
81 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
Dianne Hackborn231cc602009-04-27 17:10:36 -070083 /** Enum value for a sync stop event. */
84 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
Dianne Hackborn231cc602009-04-27 17:10:36 -070086 // TODO: i18n -- grab these out of resources.
87 /** String names for the sync event types. */
88 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
Dianne Hackborn231cc602009-04-27 17:10:36 -070090 /** Enum value for a server-initiated sync. */
91 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Dianne Hackborn231cc602009-04-27 17:10:36 -070093 /** Enum value for a local-initiated sync. */
94 public static final int SOURCE_LOCAL = 1;
95 /**
96 * Enum value for a poll-based sync (e.g., upon connection to
97 * network)
98 */
99 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Dianne Hackborn231cc602009-04-27 17:10:36 -0700101 /** Enum value for a user-initiated sync. */
102 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800104 /** Enum value for a periodic sync. */
105 public static final int SOURCE_PERIODIC = 4;
106
Fred Quintana307da1a2010-01-21 14:24:20 -0800107 public static final long NOT_IN_BACKOFF_MODE = -1;
108
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700109 public static final Intent SYNC_CONNECTION_SETTING_CHANGED_INTENT =
Fred Quintanaac9385e2009-06-22 18:00:59 -0700110 new Intent("com.android.sync.SYNC_CONN_STATUS_CHANGED");
111
Dianne Hackborn231cc602009-04-27 17:10:36 -0700112 // TODO: i18n -- grab these out of resources.
113 /** String names for the sync source types. */
114 public static final String[] SOURCES = { "SERVER",
115 "LOCAL",
116 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800117 "USER",
118 "PERIODIC" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Dianne Hackborn231cc602009-04-27 17:10:36 -0700120 // The MESG column will contain one of these or one of the Error types.
121 public static final String MESG_SUCCESS = "success";
122 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700124 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700125
Dianne Hackborn231cc602009-04-27 17:10:36 -0700126 private static final int MSG_WRITE_STATUS = 1;
127 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700128
Dianne Hackborn231cc602009-04-27 17:10:36 -0700129 private static final int MSG_WRITE_STATISTICS = 2;
130 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700131
132 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700133
Fred Quintanac2e46912010-03-15 16:10:44 -0700134 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700135 private static final int ACCOUNTS_VERSION = 2;
136
137 private static HashMap<String, String> sAuthorityRenames;
138
139 static {
140 sAuthorityRenames = new HashMap<String, String>();
141 sAuthorityRenames.put("contacts", "com.android.contacts");
142 sAuthorityRenames.put("calendar", "com.android.calendar");
143 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700144
Dianne Hackborn231cc602009-04-27 17:10:36 -0700145 public static class PendingOperation {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700146 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800147 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700148 final int syncSource;
149 final String authority;
150 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800151 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700152
Dianne Hackborn231cc602009-04-27 17:10:36 -0700153 int authorityId;
154 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700155
Amith Yamasani04e0d262012-02-14 11:50:53 -0800156 PendingOperation(Account account, int userId, int source,
Fred Quintana307da1a2010-01-21 14:24:20 -0800157 String authority, Bundle extras, boolean expedited) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700158 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800159 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700160 this.syncSource = source;
161 this.authority = authority;
162 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800163 this.expedited = expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700164 this.authorityId = -1;
165 }
166
167 PendingOperation(PendingOperation other) {
168 this.account = other.account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800169 this.userId = other.userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700170 this.syncSource = other.syncSource;
171 this.authority = other.authority;
172 this.extras = other.extras;
173 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800174 this.expedited = other.expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 }
Costin Manolache360e4542009-09-04 13:36:04 -0700177
Dianne Hackborn231cc602009-04-27 17:10:36 -0700178 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800179 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700180 final HashMap<String, AuthorityInfo> authorities =
181 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700182
Amith Yamasani04e0d262012-02-14 11:50:53 -0800183 AccountInfo(AccountAndUser accountAndUser) {
184 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700185 }
186 }
Costin Manolache360e4542009-09-04 13:36:04 -0700187
Dianne Hackborn231cc602009-04-27 17:10:36 -0700188 public static class AuthorityInfo {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700189 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800190 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700191 final String authority;
192 final int ident;
193 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700194 int syncable;
Fred Quintana307da1a2010-01-21 14:24:20 -0800195 long backoffTime;
196 long backoffDelay;
197 long delayUntil;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800198 final ArrayList<Pair<Bundle, Long>> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700199
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700200 /**
201 * Copy constructor for making deep-ish copies. Only the bundles stored
202 * in periodic syncs can make unexpected changes.
203 *
204 * @param toCopy AuthorityInfo to be copied.
205 */
206 AuthorityInfo(AuthorityInfo toCopy) {
207 account = toCopy.account;
208 userId = toCopy.userId;
209 authority = toCopy.authority;
210 ident = toCopy.ident;
211 enabled = toCopy.enabled;
212 syncable = toCopy.syncable;
213 backoffTime = toCopy.backoffTime;
214 backoffDelay = toCopy.backoffDelay;
215 delayUntil = toCopy.delayUntil;
216 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
217 for (Pair<Bundle, Long> sync : toCopy.periodicSyncs) {
218 // Still not a perfect copy, because we are just copying the mappings.
219 periodicSyncs.add(Pair.create(new Bundle(sync.first), sync.second));
220 }
221 }
222
Amith Yamasani04e0d262012-02-14 11:50:53 -0800223 AuthorityInfo(Account account, int userId, String authority, int ident) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700224 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800225 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700226 this.authority = authority;
227 this.ident = ident;
Joe Onorato8294fad2009-07-15 16:08:44 -0700228 enabled = SYNC_ENABLED_DEFAULT;
Fred Quintana4a6679b2009-08-17 13:05:39 -0700229 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800230 backoffTime = -1; // if < 0 then we aren't in backoff mode
231 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800232 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
233 periodicSyncs.add(Pair.create(new Bundle(), DEFAULT_POLL_FREQUENCY_SECONDS));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700234 }
235 }
Costin Manolache360e4542009-09-04 13:36:04 -0700236
Dianne Hackborn231cc602009-04-27 17:10:36 -0700237 public static class SyncHistoryItem {
238 int authorityId;
239 int historyId;
240 long eventTime;
241 long elapsedTime;
242 int source;
243 int event;
244 long upstreamActivity;
245 long downstreamActivity;
246 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700247 boolean initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700248 }
Costin Manolache360e4542009-09-04 13:36:04 -0700249
Dianne Hackborn231cc602009-04-27 17:10:36 -0700250 public static class DayStats {
251 public final int day;
252 public int successCount;
253 public long successTime;
254 public int failureCount;
255 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700256
Dianne Hackborn231cc602009-04-27 17:10:36 -0700257 public DayStats(int day) {
258 this.day = day;
259 }
260 }
Costin Manolache360e4542009-09-04 13:36:04 -0700261
Amith Yamasani04e0d262012-02-14 11:50:53 -0800262 interface OnSyncRequestListener {
263 /**
264 * Called when a sync is needed on an account(s) due to some change in state.
265 * @param account
266 * @param userId
267 * @param authority
268 * @param extras
269 */
270 public void onSyncRequest(Account account, int userId, String authority, Bundle extras);
271 }
272
Dianne Hackborn231cc602009-04-27 17:10:36 -0700273 // Primary list of all syncable authorities. Also our global lock.
274 private final SparseArray<AuthorityInfo> mAuthorities =
275 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700276
Amith Yamasani04e0d262012-02-14 11:50:53 -0800277 private final HashMap<AccountAndUser, AccountInfo> mAccounts
278 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279
Dianne Hackborn231cc602009-04-27 17:10:36 -0700280 private final ArrayList<PendingOperation> mPendingOperations =
281 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700282
Amith Yamasani04e0d262012-02-14 11:50:53 -0800283 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
284 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700285
Dianne Hackborn231cc602009-04-27 17:10:36 -0700286 private final SparseArray<SyncStatusInfo> mSyncStatus =
287 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700288
Dianne Hackborn231cc602009-04-27 17:10:36 -0700289 private final ArrayList<SyncHistoryItem> mSyncHistory =
290 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700291
Dianne Hackborn231cc602009-04-27 17:10:36 -0700292 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
293 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700294
Fred Quintana77c560f2010-03-29 22:20:26 -0700295 private int mNextAuthorityId = 0;
296
Dianne Hackborn231cc602009-04-27 17:10:36 -0700297 // We keep 4 weeks of stats.
298 private final DayStats[] mDayStats = new DayStats[7*4];
299 private final Calendar mCal;
300 private int mYear;
301 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700302
Dianne Hackborn231cc602009-04-27 17:10:36 -0700303 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800304
Dianne Hackborn231cc602009-04-27 17:10:36 -0700305 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700306
Ashish Sharma69d95de2012-04-11 17:27:24 -0700307 private int mSyncRandomOffset;
308
Dianne Hackborn231cc602009-04-27 17:10:36 -0700309 /**
310 * This file contains the core engine state: all accounts and the
311 * settings for them. It must never be lost, and should be changed
312 * infrequently, so it is stored as an XML file.
313 */
314 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700315
Dianne Hackborn231cc602009-04-27 17:10:36 -0700316 /**
317 * This file contains the current sync status. We would like to retain
318 * it across boots, but its loss is not the end of the world, so we store
319 * this information as binary data.
320 */
321 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700322
Dianne Hackborn231cc602009-04-27 17:10:36 -0700323 /**
324 * This file contains sync statistics. This is purely debugging information
325 * so is written infrequently and can be thrown away at any time.
326 */
327 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700328
Dianne Hackborn231cc602009-04-27 17:10:36 -0700329 /**
330 * This file contains the pending sync operations. It is a binary file,
331 * which must be updated every time an operation is added or removed,
332 * so we have special handling of it.
333 */
334 private final AtomicFile mPendingFile;
335 private static final int PENDING_FINISH_TO_WRITE = 4;
336 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700337
Dianne Hackborn231cc602009-04-27 17:10:36 -0700338 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800339 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800340 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800341
342 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700343
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800344 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700347
Dianne Hackborn231cc602009-04-27 17:10:36 -0700348 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700349
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800350 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
351 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
352
Dianne Hackborn231cc602009-04-27 17:10:36 -0700353 File systemDir = new File(dataDir, "system");
354 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800355 syncDir.mkdirs();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700356 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
357 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
358 mPendingFile = new AtomicFile(new File(syncDir, "pending.bin"));
359 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700360
Dianne Hackborn231cc602009-04-27 17:10:36 -0700361 readAccountInfoLocked();
362 readStatusLocked();
363 readPendingOperationsLocked();
364 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700365 readAndDeleteLegacyAccountInfoLocked();
366 writeAccountInfoLocked();
367 writeStatusLocked();
368 writePendingOperationsLocked();
369 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 }
371
372 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800373 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 }
375
376 public static void init(Context context) {
377 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800378 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800380 // This call will return the correct directory whether Encrypted File Systems is
381 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600382 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800383 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 }
385
386 public static SyncStorageEngine getSingleton() {
387 if (sSyncStorageEngine == null) {
388 throw new IllegalStateException("not initialized");
389 }
390 return sSyncStorageEngine;
391 }
392
Amith Yamasani04e0d262012-02-14 11:50:53 -0800393 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
394 if (mSyncRequestListener == null) {
395 mSyncRequestListener = listener;
396 }
397 }
398
Dianne Hackborn231cc602009-04-27 17:10:36 -0700399 @Override public void handleMessage(Message msg) {
400 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700401 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700402 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700403 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700404 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700405 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700406 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 }
408 }
409 }
Costin Manolache360e4542009-09-04 13:36:04 -0700410
Ashish Sharma69d95de2012-04-11 17:27:24 -0700411 public int getSyncRandomOffset() {
412 return mSyncRandomOffset;
413 }
414
Dianne Hackborn231cc602009-04-27 17:10:36 -0700415 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
416 synchronized (mAuthorities) {
417 mChangeListeners.register(callback, mask);
418 }
419 }
Costin Manolache360e4542009-09-04 13:36:04 -0700420
Dianne Hackborn231cc602009-04-27 17:10:36 -0700421 public void removeStatusChangeListener(ISyncStatusObserver callback) {
422 synchronized (mAuthorities) {
423 mChangeListeners.unregister(callback);
424 }
425 }
Costin Manolache360e4542009-09-04 13:36:04 -0700426
Dianne Hackborn231cc602009-04-27 17:10:36 -0700427 private void reportChange(int which) {
428 ArrayList<ISyncStatusObserver> reports = null;
429 synchronized (mAuthorities) {
430 int i = mChangeListeners.beginBroadcast();
431 while (i > 0) {
432 i--;
433 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
434 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 continue;
436 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700437 if (reports == null) {
438 reports = new ArrayList<ISyncStatusObserver>(i);
439 }
440 reports.add(mChangeListeners.getBroadcastItem(i));
441 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700442 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700443 }
Costin Manolache360e4542009-09-04 13:36:04 -0700444
Fred Quintana77c560f2010-03-29 22:20:26 -0700445 if (Log.isLoggable(TAG, Log.VERBOSE)) {
446 Log.v(TAG, "reportChange " + which + " to: " + reports);
447 }
Costin Manolache360e4542009-09-04 13:36:04 -0700448
Dianne Hackborn231cc602009-04-27 17:10:36 -0700449 if (reports != null) {
450 int i = reports.size();
451 while (i > 0) {
452 i--;
453 try {
454 reports.get(i).onStatusChanged(which);
455 } catch (RemoteException e) {
456 // The remote callback list will take care of this for us.
457 }
458 }
459 }
460 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700461
Amith Yamasani04e0d262012-02-14 11:50:53 -0800462 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700463 synchronized (mAuthorities) {
464 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800465 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700466 "getSyncAutomatically");
467 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700468 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700469
Dianne Hackborn231cc602009-04-27 17:10:36 -0700470 int i = mAuthorities.size();
471 while (i > 0) {
472 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700473 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700474 if (authority.authority.equals(providerName)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800475 && authority.userId == userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700476 && authority.enabled) {
477 return true;
478 }
479 }
480 return false;
481 }
482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483
Amith Yamasani04e0d262012-02-14 11:50:53 -0800484 public void setSyncAutomatically(Account account, int userId, String providerName,
485 boolean sync) {
486 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
487 + ", user " + userId + " -> " + sync);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700488 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800489 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
490 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700491 if (authority.enabled == sync) {
492 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
493 return;
494 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700495 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700496 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700498
Fred Quintana77c560f2010-03-29 22:20:26 -0700499 if (sync) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800500 requestSync(account, userId, providerName, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700501 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700502 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 }
504
Amith Yamasani04e0d262012-02-14 11:50:53 -0800505 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700506 synchronized (mAuthorities) {
507 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800508 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintana5e787c42009-08-16 23:13:53 -0700509 "getIsSyncable");
510 if (authority == null) {
511 return -1;
512 }
513 return authority.syncable;
514 }
515
516 int i = mAuthorities.size();
517 while (i > 0) {
518 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700519 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700520 if (authority.authority.equals(providerName)) {
521 return authority.syncable;
522 }
523 }
524 return -1;
525 }
526 }
527
Amith Yamasani04e0d262012-02-14 11:50:53 -0800528 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700529 if (syncable > 1) {
530 syncable = 1;
531 } else if (syncable < -1) {
532 syncable = -1;
533 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800534 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName
535 + ", user " + userId + " -> " + syncable);
Fred Quintana5e787c42009-08-16 23:13:53 -0700536 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800537 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
538 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700539 if (authority.syncable == syncable) {
540 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
541 return;
542 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700543 authority.syncable = syncable;
544 writeAccountInfoLocked();
545 }
546
Fred Quintana77c560f2010-03-29 22:20:26 -0700547 if (syncable > 0) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800548 requestSync(account, userId, providerName, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700549 }
550 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
551 }
552
Amith Yamasani04e0d262012-02-14 11:50:53 -0800553 public Pair<Long, Long> getBackoff(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800554 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800555 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
556 "getBackoff");
Fred Quintana307da1a2010-01-21 14:24:20 -0800557 if (authority == null || authority.backoffTime < 0) {
558 return null;
559 }
560 return Pair.create(authority.backoffTime, authority.backoffDelay);
561 }
562 }
563
Amith Yamasani04e0d262012-02-14 11:50:53 -0800564 public void setBackoff(Account account, int userId, String providerName,
Fred Quintana307da1a2010-01-21 14:24:20 -0800565 long nextSyncTime, long nextDelay) {
566 if (Log.isLoggable(TAG, Log.VERBOSE)) {
567 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800568 + ", user " + userId
Fred Quintana307da1a2010-01-21 14:24:20 -0800569 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
570 }
571 boolean changed = false;
572 synchronized (mAuthorities) {
573 if (account == null || providerName == null) {
574 for (AccountInfo accountInfo : mAccounts.values()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800575 if (account != null && !account.equals(accountInfo.accountAndUser.account)
576 && userId != accountInfo.accountAndUser.userId) {
577 continue;
578 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800579 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
580 if (providerName != null && !providerName.equals(authorityInfo.authority)) {
581 continue;
582 }
583 if (authorityInfo.backoffTime != nextSyncTime
584 || authorityInfo.backoffDelay != nextDelay) {
585 authorityInfo.backoffTime = nextSyncTime;
586 authorityInfo.backoffDelay = nextDelay;
587 changed = true;
588 }
589 }
590 }
591 } else {
592 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800593 getOrCreateAuthorityLocked(account, userId, providerName, -1 /* ident */,
594 true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800595 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
596 return;
597 }
598 authority.backoffTime = nextSyncTime;
599 authority.backoffDelay = nextDelay;
600 changed = true;
601 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800602 }
603
604 if (changed) {
605 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
606 }
607 }
608
Alon Alberted1d2532011-02-15 14:02:14 -0800609 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800610 boolean changed = false;
611 synchronized (mAuthorities) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700612 synchronized (syncQueue) {
613 for (AccountInfo accountInfo : mAccounts.values()) {
614 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
615 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
616 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
617 if (Log.isLoggable(TAG, Log.VERBOSE)) {
618 Log.v(TAG, "clearAllBackoffs:"
619 + " authority:" + authorityInfo.authority
620 + " account:" + accountInfo.accountAndUser.account.name
621 + " user:" + accountInfo.accountAndUser.userId
622 + " backoffTime was: " + authorityInfo.backoffTime
623 + " backoffDelay was: " + authorityInfo.backoffDelay);
624 }
625 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
626 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
627 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
628 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
629 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800630 }
Alon Albert744e310f2010-12-14 11:37:20 -0800631 }
632 }
633 }
634 }
635
636 if (changed) {
637 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
638 }
639 }
640
Amith Yamasani04e0d262012-02-14 11:50:53 -0800641 public void setDelayUntilTime(Account account, int userId, String providerName,
642 long delayUntil) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800643 if (Log.isLoggable(TAG, Log.VERBOSE)) {
644 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800645 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800646 }
647 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800648 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800649 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800650 if (authority.delayUntil == delayUntil) {
651 return;
652 }
653 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800654 }
655
656 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
657 }
658
Amith Yamasani04e0d262012-02-14 11:50:53 -0800659 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800660 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800661 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
662 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800663 if (authority == null) {
664 return 0;
665 }
666 return authority.delayUntil;
667 }
668 }
669
Amith Yamasani04e0d262012-02-14 11:50:53 -0800670 private void updateOrRemovePeriodicSync(Account account, int userId, String providerName,
671 Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800672 long period, boolean add) {
673 if (period <= 0) {
674 period = 0;
675 }
676 if (extras == null) {
677 extras = new Bundle();
678 }
679 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800680 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", user " + userId
681 + ", provider " + providerName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800682 + " -> period " + period + ", extras " + extras);
683 }
684 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700685 try {
686 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800687 getOrCreateAuthorityLocked(account, userId, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700688 if (add) {
689 // add this periodic sync if one with the same extras doesn't already
690 // exist in the periodicSyncs array
691 boolean alreadyPresent = false;
692 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
693 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
694 final Bundle existingExtras = syncInfo.first;
695 if (equals(existingExtras, extras)) {
696 if (syncInfo.second == period) {
697 return;
698 }
699 authority.periodicSyncs.set(i, Pair.create(extras, period));
700 alreadyPresent = true;
701 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800702 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700703 }
704 // if we added an entry to the periodicSyncs array also add an entry to
705 // the periodic syncs status to correspond to it
706 if (!alreadyPresent) {
707 authority.periodicSyncs.add(Pair.create(extras, period));
708 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
709 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
710 }
711 } else {
712 // remove any periodic syncs that match the authority and extras
713 SyncStatusInfo status = mSyncStatus.get(authority.ident);
714 boolean changed = false;
715 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
716 int i = 0;
717 while (iterator.hasNext()) {
718 Pair<Bundle, Long> syncInfo = iterator.next();
719 if (equals(syncInfo.first, extras)) {
720 iterator.remove();
721 changed = true;
722 // if we removed an entry from the periodicSyncs array also
723 // remove the corresponding entry from the status
724 if (status != null) {
725 status.removePeriodicSyncTime(i);
726 }
727 } else {
728 i++;
729 }
730 }
731 if (!changed) {
732 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800733 }
734 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700735 } finally {
736 writeAccountInfoLocked();
737 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800738 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800739 }
740
741 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
742 }
743
Amith Yamasani04e0d262012-02-14 11:50:53 -0800744 public void addPeriodicSync(Account account, int userId, String providerName, Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800745 long pollFrequency) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800746 updateOrRemovePeriodicSync(account, userId, providerName, extras, pollFrequency,
747 true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800748 }
749
Amith Yamasani04e0d262012-02-14 11:50:53 -0800750 public void removePeriodicSync(Account account, int userId, String providerName,
751 Bundle extras) {
752 updateOrRemovePeriodicSync(account, userId, providerName, extras, 0 /* period, ignored */,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800753 false /* remove */);
754 }
755
Amith Yamasani04e0d262012-02-14 11:50:53 -0800756 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800757 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
758 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800759 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
760 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800761 if (authority != null) {
762 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800763 syncs.add(new PeriodicSync(account, providerName, item.first,
764 item.second));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800765 }
766 }
767 }
768 return syncs;
769 }
770
Amith Yamasani04e0d262012-02-14 11:50:53 -0800771 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700772 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800773 Boolean auto = mMasterSyncAutomatically.get(userId);
774 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700775 return;
776 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800777 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700778 writeAccountInfoLocked();
779 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700780 if (flag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800781 requestSync(null, userId, null, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700782 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700783 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
784 mContext.sendBroadcast(SYNC_CONNECTION_SETTING_CHANGED_INTENT);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786
Amith Yamasani04e0d262012-02-14 11:50:53 -0800787 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700788 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800789 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800790 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700791 }
792 }
Costin Manolache360e4542009-09-04 13:36:04 -0700793
Amith Yamasani04e0d262012-02-14 11:50:53 -0800794 public AuthorityInfo getOrCreateAuthority(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700795 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800796 return getOrCreateAuthorityLocked(account, userId, authority,
Fred Quintana1bbcd102010-02-10 10:04:33 -0800797 -1 /* assign a new identifier if creating a new authority */,
798 true /* write to storage if this results in a change */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700799 }
800 }
Costin Manolache360e4542009-09-04 13:36:04 -0700801
Amith Yamasani04e0d262012-02-14 11:50:53 -0800802 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700803 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800804 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700805 }
806 }
807
Dianne Hackborn231cc602009-04-27 17:10:36 -0700808 public AuthorityInfo getAuthority(int authorityId) {
809 synchronized (mAuthorities) {
810 return mAuthorities.get(authorityId);
811 }
812 }
Costin Manolache360e4542009-09-04 13:36:04 -0700813
Dianne Hackborn231cc602009-04-27 17:10:36 -0700814 /**
815 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700816 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700817 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800818 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700819 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800820 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700821 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700822 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800823 && ainfo.authority.equals(authority)
824 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700825 return true;
826 }
827 }
828 }
Costin Manolache360e4542009-09-04 13:36:04 -0700829
Dianne Hackborn231cc602009-04-27 17:10:36 -0700830 return false;
831 }
Costin Manolache360e4542009-09-04 13:36:04 -0700832
Dianne Hackborn231cc602009-04-27 17:10:36 -0700833 public PendingOperation insertIntoPending(PendingOperation op) {
834 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700835 if (Log.isLoggable(TAG, Log.VERBOSE)) {
836 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800837 + " user=" + op.userId
838 + " auth=" + op.authority
839 + " src=" + op.syncSource
840 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700841 }
Costin Manolache360e4542009-09-04 13:36:04 -0700842
Amith Yamasani04e0d262012-02-14 11:50:53 -0800843 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700844 op.authority,
845 -1 /* desired identifier */,
846 true /* write accounts to storage */);
847 if (authority == null) {
848 return null;
849 }
Costin Manolache360e4542009-09-04 13:36:04 -0700850
Dianne Hackborn231cc602009-04-27 17:10:36 -0700851 op = new PendingOperation(op);
852 op.authorityId = authority.ident;
853 mPendingOperations.add(op);
854 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700855
Dianne Hackborn231cc602009-04-27 17:10:36 -0700856 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
857 status.pending = true;
858 }
Costin Manolache360e4542009-09-04 13:36:04 -0700859
Fred Quintanaac9385e2009-06-22 18:00:59 -0700860 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700861 return op;
862 }
863
864 public boolean deleteFromPending(PendingOperation op) {
865 boolean res = false;
866 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700867 if (Log.isLoggable(TAG, Log.VERBOSE)) {
868 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800869 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700870 + " auth=" + op.authority
871 + " src=" + op.syncSource
872 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700873 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700874 if (mPendingOperations.remove(op)) {
875 if (mPendingOperations.size() == 0
876 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
877 writePendingOperationsLocked();
878 mNumPendingFinished = 0;
879 } else {
880 mNumPendingFinished++;
881 }
Costin Manolache360e4542009-09-04 13:36:04 -0700882
Amith Yamasani04e0d262012-02-14 11:50:53 -0800883 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700884 "deleteFromPending");
885 if (authority != null) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700886 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "removing - " + authority);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700887 final int N = mPendingOperations.size();
888 boolean morePending = false;
889 for (int i=0; i<N; i++) {
890 PendingOperation cur = mPendingOperations.get(i);
891 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800892 && cur.authority.equals(op.authority)
893 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700894 morePending = true;
895 break;
896 }
897 }
Costin Manolache360e4542009-09-04 13:36:04 -0700898
Dianne Hackborn231cc602009-04-27 17:10:36 -0700899 if (!morePending) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700900 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700901 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
902 status.pending = false;
903 }
904 }
Costin Manolache360e4542009-09-04 13:36:04 -0700905
Dianne Hackborn231cc602009-04-27 17:10:36 -0700906 res = true;
907 }
908 }
Costin Manolache360e4542009-09-04 13:36:04 -0700909
Fred Quintanaac9385e2009-06-22 18:00:59 -0700910 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700911 return res;
912 }
913
Dianne Hackborn231cc602009-04-27 17:10:36 -0700914 /**
915 * Return a copy of the current array of pending operations. The
916 * PendingOperation objects are the real objects stored inside, so that
917 * they can be used with deleteFromPending().
918 */
919 public ArrayList<PendingOperation> getPendingOperations() {
920 synchronized (mAuthorities) {
921 return new ArrayList<PendingOperation>(mPendingOperations);
922 }
923 }
Costin Manolache360e4542009-09-04 13:36:04 -0700924
Dianne Hackborn231cc602009-04-27 17:10:36 -0700925 /**
926 * Return the number of currently pending operations.
927 */
928 public int getPendingOperationCount() {
929 synchronized (mAuthorities) {
930 return mPendingOperations.size();
931 }
932 }
Costin Manolache360e4542009-09-04 13:36:04 -0700933
Dianne Hackborn231cc602009-04-27 17:10:36 -0700934 /**
935 * Called when the set of account has changed, given the new array of
936 * active accounts.
937 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800938 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700939 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700940 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.w(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700941 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
942 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
943 while (accIt.hasNext()) {
944 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800945 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
946 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700947 // This account no longer exists...
Fred Quintana77c560f2010-03-29 22:20:26 -0700948 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800949 Log.w(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700950 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700951 for (AuthorityInfo auth : acc.authorities.values()) {
952 removing.put(auth.ident, auth);
953 }
954 accIt.remove();
955 }
956 }
Costin Manolache360e4542009-09-04 13:36:04 -0700957
Dianne Hackborn231cc602009-04-27 17:10:36 -0700958 // Clean out all data structures.
959 int i = removing.size();
960 if (i > 0) {
961 while (i > 0) {
962 i--;
963 int ident = removing.keyAt(i);
964 mAuthorities.remove(ident);
965 int j = mSyncStatus.size();
966 while (j > 0) {
967 j--;
968 if (mSyncStatus.keyAt(j) == ident) {
969 mSyncStatus.remove(mSyncStatus.keyAt(j));
970 }
971 }
972 j = mSyncHistory.size();
973 while (j > 0) {
974 j--;
975 if (mSyncHistory.get(j).authorityId == ident) {
976 mSyncHistory.remove(j);
977 }
978 }
979 }
980 writeAccountInfoLocked();
981 writeStatusLocked();
982 writePendingOperationsLocked();
983 writeStatisticsLocked();
984 }
985 }
986 }
987
988 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700989 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
990 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700991 */
Fred Quintana918339a2010-10-05 14:00:39 -0700992 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
993 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700994 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -0700995 if (Log.isLoggable(TAG, Log.VERBOSE)) {
996 Log.v(TAG, "setActiveSync: account="
997 + activeSyncContext.mSyncOperation.account
998 + " auth=" + activeSyncContext.mSyncOperation.authority
999 + " src=" + activeSyncContext.mSyncOperation.syncSource
1000 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001001 }
Fred Quintana918339a2010-10-05 14:00:39 -07001002 AuthorityInfo authority = getOrCreateAuthorityLocked(
1003 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001004 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -07001005 activeSyncContext.mSyncOperation.authority,
1006 -1 /* assign a new identifier if creating a new authority */,
1007 true /* write to storage if this results in a change */);
1008 syncInfo = new SyncInfo(authority.ident,
1009 authority.account, authority.authority,
1010 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001011 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001012 }
Costin Manolache360e4542009-09-04 13:36:04 -07001013
Fred Quintana918339a2010-10-05 14:00:39 -07001014 reportActiveChange();
1015 return syncInfo;
1016 }
1017
1018 /**
1019 * Called to indicate that a previously active sync is no longer active.
1020 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001021 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001022 synchronized (mAuthorities) {
1023 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001024 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1025 + " user=" + userId
1026 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001027 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001028 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001029 }
1030
1031 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001032 }
1033
1034 /**
1035 * To allow others to send active change reports, to poke clients.
1036 */
1037 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001038 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001039 }
Costin Manolache360e4542009-09-04 13:36:04 -07001040
Dianne Hackborn231cc602009-04-27 17:10:36 -07001041 /**
1042 * Note that sync has started for the given account and authority.
1043 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001044 public long insertStartSyncEvent(Account accountName, int userId, String authorityName,
Fred Quintanadc475562012-05-04 15:51:54 -07001045 long now, int source, boolean initialization) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001046 long id;
1047 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001048 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001049 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001050 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001051 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001052 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001053 "insertStartSyncEvent");
1054 if (authority == null) {
1055 return -1;
1056 }
1057 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001058 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001059 item.authorityId = authority.ident;
1060 item.historyId = mNextHistoryId++;
1061 if (mNextHistoryId < 0) mNextHistoryId = 0;
1062 item.eventTime = now;
1063 item.source = source;
1064 item.event = EVENT_START;
1065 mSyncHistory.add(0, item);
1066 while (mSyncHistory.size() > MAX_HISTORY) {
1067 mSyncHistory.remove(mSyncHistory.size()-1);
1068 }
1069 id = item.historyId;
Fred Quintana77c560f2010-03-29 22:20:26 -07001070 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001071 }
Costin Manolache360e4542009-09-04 13:36:04 -07001072
Fred Quintanaac9385e2009-06-22 18:00:59 -07001073 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001074 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001077 public static boolean equals(Bundle b1, Bundle b2) {
1078 if (b1.size() != b2.size()) {
1079 return false;
1080 }
1081 if (b1.isEmpty()) {
1082 return true;
1083 }
1084 for (String key : b1.keySet()) {
1085 if (!b2.containsKey(key)) {
1086 return false;
1087 }
1088 if (!b1.get(key).equals(b2.get(key))) {
1089 return false;
1090 }
1091 }
1092 return true;
1093 }
1094
Fred Quintana77c560f2010-03-29 22:20:26 -07001095 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001097 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001098 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1099 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1100 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001101 SyncHistoryItem item = null;
1102 int i = mSyncHistory.size();
1103 while (i > 0) {
1104 i--;
1105 item = mSyncHistory.get(i);
1106 if (item.historyId == historyId) {
1107 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001109 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 }
Costin Manolache360e4542009-09-04 13:36:04 -07001111
Dianne Hackborn231cc602009-04-27 17:10:36 -07001112 if (item == null) {
1113 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1114 return;
1115 }
Costin Manolache360e4542009-09-04 13:36:04 -07001116
Dianne Hackborn231cc602009-04-27 17:10:36 -07001117 item.elapsedTime = elapsedTime;
1118 item.event = EVENT_STOP;
1119 item.mesg = resultMessage;
1120 item.downstreamActivity = downstreamActivity;
1121 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001122
Dianne Hackborn231cc602009-04-27 17:10:36 -07001123 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001124
Dianne Hackborn231cc602009-04-27 17:10:36 -07001125 status.numSyncs++;
1126 status.totalElapsedTime += elapsedTime;
1127 switch (item.source) {
1128 case SOURCE_LOCAL:
1129 status.numSourceLocal++;
1130 break;
1131 case SOURCE_POLL:
1132 status.numSourcePoll++;
1133 break;
1134 case SOURCE_USER:
1135 status.numSourceUser++;
1136 break;
1137 case SOURCE_SERVER:
1138 status.numSourceServer++;
1139 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001140 case SOURCE_PERIODIC:
1141 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001142 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001143 }
Costin Manolache360e4542009-09-04 13:36:04 -07001144
Dianne Hackborn231cc602009-04-27 17:10:36 -07001145 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001146 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001147 if (mDayStats[0] == null) {
1148 mDayStats[0] = new DayStats(day);
1149 } else if (day != mDayStats[0].day) {
1150 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1151 mDayStats[0] = new DayStats(day);
1152 writeStatisticsNow = true;
1153 } else if (mDayStats[0] == null) {
1154 }
1155 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001156
Dianne Hackborn231cc602009-04-27 17:10:36 -07001157 final long lastSyncTime = (item.eventTime + elapsedTime);
1158 boolean writeStatusNow = false;
1159 if (MESG_SUCCESS.equals(resultMessage)) {
1160 // - if successful, update the successful columns
1161 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1162 writeStatusNow = true;
1163 }
1164 status.lastSuccessTime = lastSyncTime;
1165 status.lastSuccessSource = item.source;
1166 status.lastFailureTime = 0;
1167 status.lastFailureSource = -1;
1168 status.lastFailureMesg = null;
1169 status.initialFailureTime = 0;
1170 ds.successCount++;
1171 ds.successTime += elapsedTime;
1172 } else if (!MESG_CANCELED.equals(resultMessage)) {
1173 if (status.lastFailureTime == 0) {
1174 writeStatusNow = true;
1175 }
1176 status.lastFailureTime = lastSyncTime;
1177 status.lastFailureSource = item.source;
1178 status.lastFailureMesg = resultMessage;
1179 if (status.initialFailureTime == 0) {
1180 status.initialFailureTime = lastSyncTime;
1181 }
1182 ds.failureCount++;
1183 ds.failureTime += elapsedTime;
1184 }
Costin Manolache360e4542009-09-04 13:36:04 -07001185
Dianne Hackborn231cc602009-04-27 17:10:36 -07001186 if (writeStatusNow) {
1187 writeStatusLocked();
1188 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1189 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1190 WRITE_STATUS_DELAY);
1191 }
1192 if (writeStatisticsNow) {
1193 writeStatisticsLocked();
1194 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1195 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1196 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001197 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001198 }
Costin Manolache360e4542009-09-04 13:36:04 -07001199
Fred Quintanaac9385e2009-06-22 18:00:59 -07001200 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001201 }
1202
1203 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001204 * Return a list of the currently active syncs. Note that the returned items are the
1205 * real, live active sync objects, so be careful what you do with it.
1206 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001207 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001208 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001209 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1210 if (syncs == null) {
1211 syncs = new ArrayList<SyncInfo>();
1212 mCurrentSyncs.put(userId, syncs);
1213 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001214 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001215 }
1216 }
Costin Manolache360e4542009-09-04 13:36:04 -07001217
Dianne Hackborn231cc602009-04-27 17:10:36 -07001218 /**
1219 * Return an array of the current sync status for all authorities. Note
1220 * that the objects inside the array are the real, live status objects,
1221 * so be careful what you do with them.
1222 */
1223 public ArrayList<SyncStatusInfo> getSyncStatus() {
1224 synchronized (mAuthorities) {
1225 final int N = mSyncStatus.size();
1226 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1227 for (int i=0; i<N; i++) {
1228 ops.add(mSyncStatus.valueAt(i));
1229 }
1230 return ops;
1231 }
1232 }
Costin Manolache360e4542009-09-04 13:36:04 -07001233
Dianne Hackborn231cc602009-04-27 17:10:36 -07001234 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001235 * Return an array of the current authorities. Note
1236 * that the objects inside the array are the real, live objects,
1237 * so be careful what you do with them.
1238 */
1239 public ArrayList<AuthorityInfo> getAuthorities() {
1240 synchronized (mAuthorities) {
1241 final int N = mAuthorities.size();
1242 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1243 for (int i=0; i<N; i++) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -07001244 // Make deep copy because AuthorityInfo syncs are liable to change.
1245 infos.add(new AuthorityInfo(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001246 }
1247 return infos;
1248 }
1249 }
1250
1251 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001252 * Returns the status that matches the authority and account.
1253 *
1254 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001255 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001256 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001257 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001258 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1259 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001260 if (account == null || authority == null) {
1261 throw new IllegalArgumentException();
1262 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001263 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001264 final int N = mSyncStatus.size();
1265 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001266 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001267 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001268
Amith Yamasani04e0d262012-02-14 11:50:53 -08001269 if (ainfo != null && ainfo.authority.equals(authority)
1270 && ainfo.userId == userId
1271 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001272 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001273 }
1274 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001275 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001276 }
1277 }
Costin Manolache360e4542009-09-04 13:36:04 -07001278
Dianne Hackborn231cc602009-04-27 17:10:36 -07001279 /**
1280 * Return true if the pending status is true of any matching authorities.
1281 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001282 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001283 synchronized (mAuthorities) {
1284 final int N = mSyncStatus.size();
1285 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001286 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001287 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1288 if (ainfo == null) {
1289 continue;
1290 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001291 if (userId != ainfo.userId) {
1292 continue;
1293 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001294 if (account != null && !ainfo.account.equals(account)) {
1295 continue;
1296 }
1297 if (ainfo.authority.equals(authority) && cur.pending) {
1298 return true;
1299 }
1300 }
1301 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 }
1303 }
1304
1305 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001306 * Return an array of the current sync status for all authorities. Note
1307 * that the objects inside the array are the real, live status objects,
1308 * so be careful what you do with them.
1309 */
1310 public ArrayList<SyncHistoryItem> getSyncHistory() {
1311 synchronized (mAuthorities) {
1312 final int N = mSyncHistory.size();
1313 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1314 for (int i=0; i<N; i++) {
1315 items.add(mSyncHistory.get(i));
1316 }
1317 return items;
1318 }
1319 }
Costin Manolache360e4542009-09-04 13:36:04 -07001320
Dianne Hackborn231cc602009-04-27 17:10:36 -07001321 /**
1322 * Return an array of the current per-day statistics. Note
1323 * that the objects inside the array are the real, live status objects,
1324 * so be careful what you do with them.
1325 */
1326 public DayStats[] getDayStatistics() {
1327 synchronized (mAuthorities) {
1328 DayStats[] ds = new DayStats[mDayStats.length];
1329 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1330 return ds;
1331 }
1332 }
Costin Manolache360e4542009-09-04 13:36:04 -07001333
Dianne Hackborn55280a92009-05-07 15:53:46 -07001334 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001335 mCal.setTimeInMillis(System.currentTimeMillis());
1336 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1337 if (mYear != mCal.get(Calendar.YEAR)) {
1338 mYear = mCal.get(Calendar.YEAR);
1339 mCal.clear();
1340 mCal.set(Calendar.YEAR, mYear);
1341 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1342 }
1343 return dayOfYear + mYearInDays;
1344 }
Costin Manolache360e4542009-09-04 13:36:04 -07001345
Dianne Hackborn231cc602009-04-27 17:10:36 -07001346 /**
1347 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001348 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001349 * @param accountName The name of the account for the authority.
1350 * @param authorityName The name of the authority itself.
1351 * @param tag If non-null, this will be used in a log message if the
1352 * requested authority does not exist.
1353 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001354 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001355 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001356 AccountAndUser au = new AccountAndUser(accountName, userId);
1357 AccountInfo accountInfo = mAccounts.get(au);
1358 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001359 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001360 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001361 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001362 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001363 }
1364 return null;
1365 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001366 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001367 if (authority == null) {
1368 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001369 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1370 Log.v(TAG, tag + ": unknown authority " + authorityName);
1371 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001372 }
1373 return null;
1374 }
Costin Manolache360e4542009-09-04 13:36:04 -07001375
Dianne Hackborn231cc602009-04-27 17:10:36 -07001376 return authority;
1377 }
Costin Manolache360e4542009-09-04 13:36:04 -07001378
Amith Yamasani04e0d262012-02-14 11:50:53 -08001379 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001380 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001381 AccountAndUser au = new AccountAndUser(accountName, userId);
1382 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001383 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001384 account = new AccountInfo(au);
1385 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001386 }
1387 AuthorityInfo authority = account.authorities.get(authorityName);
1388 if (authority == null) {
1389 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001390 ident = mNextAuthorityId;
1391 mNextAuthorityId++;
1392 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001393 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001394 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1395 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001396 + ", user " + userId
1397 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001398 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001399 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001400 account.authorities.put(authorityName, authority);
1401 mAuthorities.put(ident, authority);
1402 if (doWrite) {
1403 writeAccountInfoLocked();
1404 }
1405 }
Costin Manolache360e4542009-09-04 13:36:04 -07001406
Dianne Hackborn231cc602009-04-27 17:10:36 -07001407 return authority;
1408 }
Costin Manolache360e4542009-09-04 13:36:04 -07001409
Amith Yamasani04e0d262012-02-14 11:50:53 -08001410 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1411 boolean doWrite) {
1412 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001413 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001414 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1415 if (authorityInfo != null) {
1416 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001417 if (doWrite) {
1418 writeAccountInfoLocked();
1419 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001420 }
1421 }
1422 }
1423
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001424 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1425 synchronized (mAuthorities) {
1426 return getOrCreateSyncStatusLocked(authority.ident);
1427 }
1428 }
1429
Dianne Hackborn231cc602009-04-27 17:10:36 -07001430 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1431 SyncStatusInfo status = mSyncStatus.get(authorityId);
1432 if (status == null) {
1433 status = new SyncStatusInfo(authorityId);
1434 mSyncStatus.put(authorityId, status);
1435 }
1436 return status;
1437 }
Costin Manolache360e4542009-09-04 13:36:04 -07001438
Dianne Hackborn55280a92009-05-07 15:53:46 -07001439 public void writeAllState() {
1440 synchronized (mAuthorities) {
1441 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001442
Dianne Hackborn55280a92009-05-07 15:53:46 -07001443 if (mNumPendingFinished > 0) {
1444 // Only write these if they are out of date.
1445 writePendingOperationsLocked();
1446 }
Costin Manolache360e4542009-09-04 13:36:04 -07001447
Dianne Hackborn55280a92009-05-07 15:53:46 -07001448 // Just always write these... they are likely out of date.
1449 writeStatusLocked();
1450 writeStatisticsLocked();
1451 }
1452 }
Costin Manolache360e4542009-09-04 13:36:04 -07001453
Dianne Hackborn231cc602009-04-27 17:10:36 -07001454 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001455 * public for testing
1456 */
1457 public void clearAndReadState() {
1458 synchronized (mAuthorities) {
1459 mAuthorities.clear();
1460 mAccounts.clear();
1461 mPendingOperations.clear();
1462 mSyncStatus.clear();
1463 mSyncHistory.clear();
1464
1465 readAccountInfoLocked();
1466 readStatusLocked();
1467 readPendingOperationsLocked();
1468 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001469 readAndDeleteLegacyAccountInfoLocked();
1470 writeAccountInfoLocked();
1471 writeStatusLocked();
1472 writePendingOperationsLocked();
1473 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001474 }
1475 }
1476
1477 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001478 * Read all account information back in to the initial engine state.
1479 */
1480 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001481 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001482 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001484 fis = mAccountInfoFile.openRead();
1485 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1486 XmlPullParser parser = Xml.newPullParser();
1487 parser.setInput(fis, null);
1488 int eventType = parser.getEventType();
1489 while (eventType != XmlPullParser.START_TAG) {
1490 eventType = parser.next();
1491 }
1492 String tagName = parser.getName();
1493 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001494 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001495 String versionString = parser.getAttributeValue(null, "version");
1496 int version;
1497 try {
1498 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1499 } catch (NumberFormatException e) {
1500 version = 0;
1501 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001502 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001503 try {
1504 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1505 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1506 } catch (NumberFormatException e) {
1507 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001508 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001509 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1510 try {
1511 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1512 } catch (NumberFormatException e) {
1513 mSyncRandomOffset = 0;
1514 }
1515 if (mSyncRandomOffset == 0) {
1516 Random random = new Random(System.currentTimeMillis());
1517 mSyncRandomOffset = random.nextInt(86400);
1518 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001519 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001520 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001521 AuthorityInfo authority = null;
1522 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001523 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001524 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001525 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001526 if (parser.getDepth() == 2) {
1527 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001528 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001529 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001530 if (authority.ident > highestAuthorityId) {
1531 highestAuthorityId = authority.ident;
1532 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001533 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1534 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001535 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001536 } else if (parser.getDepth() == 3) {
1537 if ("periodicSync".equals(tagName) && authority != null) {
1538 periodicSync = parsePeriodicSync(parser, authority);
1539 }
1540 } else if (parser.getDepth() == 4 && periodicSync != null) {
1541 if ("extra".equals(tagName)) {
1542 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001543 }
1544 }
1545 }
1546 eventType = parser.next();
1547 } while (eventType != XmlPullParser.END_DOCUMENT);
1548 }
1549 } catch (XmlPullParserException e) {
1550 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001551 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001552 } catch (java.io.IOException e) {
1553 if (fis == null) Log.i(TAG, "No initial accounts");
1554 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001555 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001556 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001557 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001558 if (fis != null) {
1559 try {
1560 fis.close();
1561 } catch (java.io.IOException e1) {
1562 }
1563 }
1564 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001565
Fred Quintana77c560f2010-03-29 22:20:26 -07001566 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001567 }
Costin Manolache360e4542009-09-04 13:36:04 -07001568
Fred Quintanafb084402010-03-23 17:57:03 -07001569 /**
1570 * some authority names have changed. copy over their settings and delete the old ones
1571 * @return true if a change was made
1572 */
1573 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1574 boolean writeNeeded = false;
1575
1576 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1577 final int N = mAuthorities.size();
1578 for (int i=0; i<N; i++) {
1579 AuthorityInfo authority = mAuthorities.valueAt(i);
1580 // skip this authority if it isn't one of the renamed ones
1581 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1582 if (newAuthorityName == null) {
1583 continue;
1584 }
1585
1586 // remember this authority so we can remove it later. we can't remove it
1587 // now without messing up this loop iteration
1588 authoritiesToRemove.add(authority);
1589
1590 // this authority isn't enabled, no need to copy it to the new authority name since
1591 // the default is "disabled"
1592 if (!authority.enabled) {
1593 continue;
1594 }
1595
1596 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001597 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1598 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001599 continue;
1600 }
1601
1602 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001603 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001604 newAuthority.enabled = true;
1605 writeNeeded = true;
1606 }
1607
1608 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001609 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1610 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001611 writeNeeded = true;
1612 }
1613
1614 return writeNeeded;
1615 }
1616
Amith Yamasani04e0d262012-02-14 11:50:53 -08001617 private void parseListenForTickles(XmlPullParser parser) {
1618 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1619 int userId = 0;
1620 try {
1621 userId = Integer.parseInt(user);
1622 } catch (NumberFormatException e) {
1623 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1624 } catch (NullPointerException e) {
1625 Log.e(TAG, "the user in listen-for-tickles is null", e);
1626 }
1627 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1628 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1629 mMasterSyncAutomatically.put(userId, listen);
1630 }
1631
Fred Quintanac2e46912010-03-15 16:10:44 -07001632 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001633 AuthorityInfo authority = null;
1634 int id = -1;
1635 try {
1636 id = Integer.parseInt(parser.getAttributeValue(
1637 null, "id"));
1638 } catch (NumberFormatException e) {
1639 Log.e(TAG, "error parsing the id of the authority", e);
1640 } catch (NullPointerException e) {
1641 Log.e(TAG, "the id of the authority is null", e);
1642 }
1643 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001644 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001645 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001646 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001647 String accountName = parser.getAttributeValue(null, "account");
1648 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001649 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1650 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001651 if (accountType == null) {
1652 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001653 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001654 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001655 authority = mAuthorities.get(id);
1656 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1657 + accountName + " auth=" + authorityName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001658 + " user=" + userId
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001659 + " enabled=" + enabled
1660 + " syncable=" + syncable);
1661 if (authority == null) {
1662 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1663 authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001664 new Account(accountName, accountType), userId, authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001665 // If the version is 0 then we are upgrading from a file format that did not
1666 // know about periodic syncs. In that case don't clear the list since we
1667 // want the default, which is a daily periodioc sync.
1668 // Otherwise clear out this default list since we will populate it later with
1669 // the periodic sync descriptions that are read from the configuration file.
1670 if (version > 0) {
1671 authority.periodicSyncs.clear();
1672 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001673 }
1674 if (authority != null) {
1675 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1676 if ("unknown".equals(syncable)) {
1677 authority.syncable = -1;
1678 } else {
1679 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001680 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001681 }
1682 } else {
1683 Log.w(TAG, "Failure adding authority: account="
1684 + accountName + " auth=" + authorityName
1685 + " enabled=" + enabled
1686 + " syncable=" + syncable);
1687 }
1688 }
1689
1690 return authority;
1691 }
1692
1693 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1694 Bundle extras = new Bundle();
1695 String periodValue = parser.getAttributeValue(null, "period");
1696 final long period;
1697 try {
1698 period = Long.parseLong(periodValue);
1699 } catch (NumberFormatException e) {
1700 Log.e(TAG, "error parsing the period of a periodic sync", e);
1701 return null;
1702 } catch (NullPointerException e) {
1703 Log.e(TAG, "the period of a periodic sync is null", e);
1704 return null;
1705 }
1706 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1707 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001708
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001709 return periodicSync;
1710 }
1711
1712 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1713 final Bundle extras = periodicSync.first;
1714 String name = parser.getAttributeValue(null, "name");
1715 String type = parser.getAttributeValue(null, "type");
1716 String value1 = parser.getAttributeValue(null, "value1");
1717 String value2 = parser.getAttributeValue(null, "value2");
1718
1719 try {
1720 if ("long".equals(type)) {
1721 extras.putLong(name, Long.parseLong(value1));
1722 } else if ("integer".equals(type)) {
1723 extras.putInt(name, Integer.parseInt(value1));
1724 } else if ("double".equals(type)) {
1725 extras.putDouble(name, Double.parseDouble(value1));
1726 } else if ("float".equals(type)) {
1727 extras.putFloat(name, Float.parseFloat(value1));
1728 } else if ("boolean".equals(type)) {
1729 extras.putBoolean(name, Boolean.parseBoolean(value1));
1730 } else if ("string".equals(type)) {
1731 extras.putString(name, value1);
1732 } else if ("account".equals(type)) {
1733 extras.putParcelable(name, new Account(value1, value2));
1734 }
1735 } catch (NumberFormatException e) {
1736 Log.e(TAG, "error parsing bundle value", e);
1737 } catch (NullPointerException e) {
1738 Log.e(TAG, "error parsing bundle value", e);
1739 }
1740 }
1741
Dianne Hackborn231cc602009-04-27 17:10:36 -07001742 /**
1743 * Write all account information to the account file.
1744 */
1745 private void writeAccountInfoLocked() {
1746 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1747 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001748
Dianne Hackborn231cc602009-04-27 17:10:36 -07001749 try {
1750 fos = mAccountInfoFile.startWrite();
1751 XmlSerializer out = new FastXmlSerializer();
1752 out.setOutput(fos, "utf-8");
1753 out.startDocument(null, true);
1754 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001755
Dianne Hackborn231cc602009-04-27 17:10:36 -07001756 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001757 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001758 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001759 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001760
1761 // Write the Sync Automatically flags for each user
1762 final int M = mMasterSyncAutomatically.size();
1763 for (int m = 0; m < M; m++) {
1764 int userId = mMasterSyncAutomatically.keyAt(m);
1765 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1766 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1767 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1768 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1769 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001770 }
Costin Manolache360e4542009-09-04 13:36:04 -07001771
Dianne Hackborn231cc602009-04-27 17:10:36 -07001772 final int N = mAuthorities.size();
1773 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001774 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001775 out.startTag(null, "authority");
1776 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001777 out.attribute(null, "account", authority.account.name);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001778 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001779 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001780 out.attribute(null, "authority", authority.authority);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001781 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Fred Quintana5e787c42009-08-16 23:13:53 -07001782 if (authority.syncable < 0) {
1783 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001784 } else {
1785 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001786 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001787 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1788 out.startTag(null, "periodicSync");
1789 out.attribute(null, "period", Long.toString(periodicSync.second));
1790 final Bundle extras = periodicSync.first;
1791 for (String key : extras.keySet()) {
1792 out.startTag(null, "extra");
1793 out.attribute(null, "name", key);
1794 final Object value = extras.get(key);
1795 if (value instanceof Long) {
1796 out.attribute(null, "type", "long");
1797 out.attribute(null, "value1", value.toString());
1798 } else if (value instanceof Integer) {
1799 out.attribute(null, "type", "integer");
1800 out.attribute(null, "value1", value.toString());
1801 } else if (value instanceof Boolean) {
1802 out.attribute(null, "type", "boolean");
1803 out.attribute(null, "value1", value.toString());
1804 } else if (value instanceof Float) {
1805 out.attribute(null, "type", "float");
1806 out.attribute(null, "value1", value.toString());
1807 } else if (value instanceof Double) {
1808 out.attribute(null, "type", "double");
1809 out.attribute(null, "value1", value.toString());
1810 } else if (value instanceof String) {
1811 out.attribute(null, "type", "string");
1812 out.attribute(null, "value1", value.toString());
1813 } else if (value instanceof Account) {
1814 out.attribute(null, "type", "account");
1815 out.attribute(null, "value1", ((Account)value).name);
1816 out.attribute(null, "value2", ((Account)value).type);
1817 }
1818 out.endTag(null, "extra");
1819 }
1820 out.endTag(null, "periodicSync");
1821 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001822 out.endTag(null, "authority");
1823 }
Costin Manolache360e4542009-09-04 13:36:04 -07001824
Dianne Hackborn231cc602009-04-27 17:10:36 -07001825 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001826
Dianne Hackborn231cc602009-04-27 17:10:36 -07001827 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001828
Dianne Hackborn231cc602009-04-27 17:10:36 -07001829 mAccountInfoFile.finishWrite(fos);
1830 } catch (java.io.IOException e1) {
1831 Log.w(TAG, "Error writing accounts", e1);
1832 if (fos != null) {
1833 mAccountInfoFile.failWrite(fos);
1834 }
1835 }
1836 }
Costin Manolache360e4542009-09-04 13:36:04 -07001837
Dianne Hackborn231cc602009-04-27 17:10:36 -07001838 static int getIntColumn(Cursor c, String name) {
1839 return c.getInt(c.getColumnIndex(name));
1840 }
Costin Manolache360e4542009-09-04 13:36:04 -07001841
Dianne Hackborn231cc602009-04-27 17:10:36 -07001842 static long getLongColumn(Cursor c, String name) {
1843 return c.getLong(c.getColumnIndex(name));
1844 }
Costin Manolache360e4542009-09-04 13:36:04 -07001845
Dianne Hackborn231cc602009-04-27 17:10:36 -07001846 /**
1847 * Load sync engine state from the old syncmanager database, and then
1848 * erase it. Note that we don't deal with pending operations, active
1849 * sync, or history.
1850 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001851 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001852 // Look for old database to initialize from.
1853 File file = mContext.getDatabasePath("syncmanager.db");
1854 if (!file.exists()) {
1855 return;
1856 }
1857 String path = file.getPath();
1858 SQLiteDatabase db = null;
1859 try {
1860 db = SQLiteDatabase.openDatabase(path, null,
1861 SQLiteDatabase.OPEN_READONLY);
1862 } catch (SQLiteException e) {
1863 }
Costin Manolache360e4542009-09-04 13:36:04 -07001864
Dianne Hackborn231cc602009-04-27 17:10:36 -07001865 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001866 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001867
Dianne Hackborn231cc602009-04-27 17:10:36 -07001868 // Copy in all of the status information, as well as accounts.
1869 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1870 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1871 qb.setTables("stats, status");
1872 HashMap<String,String> map = new HashMap<String,String>();
1873 map.put("_id", "status._id as _id");
1874 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001875 if (hasType) {
1876 map.put("account_type", "stats.account_type as account_type");
1877 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001878 map.put("authority", "stats.authority as authority");
1879 map.put("totalElapsedTime", "totalElapsedTime");
1880 map.put("numSyncs", "numSyncs");
1881 map.put("numSourceLocal", "numSourceLocal");
1882 map.put("numSourcePoll", "numSourcePoll");
1883 map.put("numSourceServer", "numSourceServer");
1884 map.put("numSourceUser", "numSourceUser");
1885 map.put("lastSuccessSource", "lastSuccessSource");
1886 map.put("lastSuccessTime", "lastSuccessTime");
1887 map.put("lastFailureSource", "lastFailureSource");
1888 map.put("lastFailureTime", "lastFailureTime");
1889 map.put("lastFailureMesg", "lastFailureMesg");
1890 map.put("pending", "pending");
1891 qb.setProjectionMap(map);
1892 qb.appendWhere("stats._id = status.stats_id");
1893 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001895 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001896 String accountType = hasType
1897 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001898 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001899 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001901 String authorityName = c.getString(c.getColumnIndex("authority"));
1902 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001903 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07001904 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001905 if (authority != null) {
1906 int i = mSyncStatus.size();
1907 boolean found = false;
1908 SyncStatusInfo st = null;
1909 while (i > 0) {
1910 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001911 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001912 if (st.authorityId == authority.ident) {
1913 found = true;
1914 break;
1915 }
1916 }
1917 if (!found) {
1918 st = new SyncStatusInfo(authority.ident);
1919 mSyncStatus.put(authority.ident, st);
1920 }
1921 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1922 st.numSyncs = getIntColumn(c, "numSyncs");
1923 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1924 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1925 st.numSourceServer = getIntColumn(c, "numSourceServer");
1926 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001927 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001928 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1929 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1930 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1931 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1932 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1933 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
Costin Manolache360e4542009-09-04 13:36:04 -07001936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001938
Dianne Hackborn231cc602009-04-27 17:10:36 -07001939 // Retrieve the settings.
1940 qb = new SQLiteQueryBuilder();
1941 qb.setTables("settings");
1942 c = qb.query(db, null, null, null, null, null, null);
1943 while (c.moveToNext()) {
1944 String name = c.getString(c.getColumnIndex("name"));
1945 String value = c.getString(c.getColumnIndex("value"));
1946 if (name == null) continue;
1947 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001948 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001949 } else if (name.startsWith("sync_provider_")) {
1950 String provider = name.substring("sync_provider_".length(),
1951 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001952 int i = mAuthorities.size();
1953 while (i > 0) {
1954 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001955 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001956 if (authority.authority.equals(provider)) {
1957 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001958 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001959 }
1960 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 }
Costin Manolache360e4542009-09-04 13:36:04 -07001963
Dianne Hackborn231cc602009-04-27 17:10:36 -07001964 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001965
Dianne Hackborn231cc602009-04-27 17:10:36 -07001966 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001967
Dianne Hackborn231cc602009-04-27 17:10:36 -07001968 (new File(path)).delete();
1969 }
1970 }
Costin Manolache360e4542009-09-04 13:36:04 -07001971
Dianne Hackborn231cc602009-04-27 17:10:36 -07001972 public static final int STATUS_FILE_END = 0;
1973 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001974
Dianne Hackborn231cc602009-04-27 17:10:36 -07001975 /**
1976 * Read all sync status back in to the initial engine state.
1977 */
1978 private void readStatusLocked() {
1979 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1980 try {
1981 byte[] data = mStatusFile.readFully();
1982 Parcel in = Parcel.obtain();
1983 in.unmarshall(data, 0, data.length);
1984 in.setDataPosition(0);
1985 int token;
1986 while ((token=in.readInt()) != STATUS_FILE_END) {
1987 if (token == STATUS_FILE_ITEM) {
1988 SyncStatusInfo status = new SyncStatusInfo(in);
1989 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1990 status.pending = false;
1991 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
1992 + status.authorityId);
1993 mSyncStatus.put(status.authorityId, status);
1994 }
1995 } else {
1996 // Ooops.
1997 Log.w(TAG, "Unknown status token: " + token);
1998 break;
1999 }
2000 }
2001 } catch (java.io.IOException e) {
2002 Log.i(TAG, "No initial status");
2003 }
2004 }
Costin Manolache360e4542009-09-04 13:36:04 -07002005
Dianne Hackborn231cc602009-04-27 17:10:36 -07002006 /**
2007 * Write all sync status to the sync status file.
2008 */
2009 private void writeStatusLocked() {
2010 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002011
Dianne Hackborn231cc602009-04-27 17:10:36 -07002012 // The file is being written, so we don't need to have a scheduled
2013 // write until the next change.
2014 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002015
Dianne Hackborn231cc602009-04-27 17:10:36 -07002016 FileOutputStream fos = null;
2017 try {
2018 fos = mStatusFile.startWrite();
2019 Parcel out = Parcel.obtain();
2020 final int N = mSyncStatus.size();
2021 for (int i=0; i<N; i++) {
2022 SyncStatusInfo status = mSyncStatus.valueAt(i);
2023 out.writeInt(STATUS_FILE_ITEM);
2024 status.writeToParcel(out, 0);
2025 }
2026 out.writeInt(STATUS_FILE_END);
2027 fos.write(out.marshall());
2028 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002029
Dianne Hackborn231cc602009-04-27 17:10:36 -07002030 mStatusFile.finishWrite(fos);
2031 } catch (java.io.IOException e1) {
2032 Log.w(TAG, "Error writing status", e1);
2033 if (fos != null) {
2034 mStatusFile.failWrite(fos);
2035 }
2036 }
2037 }
Costin Manolache360e4542009-09-04 13:36:04 -07002038
Fred Quintana307da1a2010-01-21 14:24:20 -08002039 public static final int PENDING_OPERATION_VERSION = 2;
Costin Manolache360e4542009-09-04 13:36:04 -07002040
Dianne Hackborn231cc602009-04-27 17:10:36 -07002041 /**
2042 * Read all pending operations back in to the initial engine state.
2043 */
2044 private void readPendingOperationsLocked() {
2045 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
2046 try {
2047 byte[] data = mPendingFile.readFully();
2048 Parcel in = Parcel.obtain();
2049 in.unmarshall(data, 0, data.length);
2050 in.setDataPosition(0);
2051 final int SIZE = in.dataSize();
2052 while (in.dataPosition() < SIZE) {
2053 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08002054 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002055 Log.w(TAG, "Unknown pending operation version "
2056 + version + "; dropping all ops");
2057 break;
2058 }
2059 int authorityId = in.readInt();
2060 int syncSource = in.readInt();
2061 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08002062 boolean expedited;
2063 if (version == PENDING_OPERATION_VERSION) {
2064 expedited = in.readInt() != 0;
2065 } else {
2066 expedited = false;
2067 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002068 AuthorityInfo authority = mAuthorities.get(authorityId);
2069 if (authority != null) {
Fred Quintana5695c7b2010-12-06 15:07:52 -08002070 Bundle extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002071 if (flatExtras != null) {
2072 extras = unflattenBundle(flatExtras);
Fred Quintana5695c7b2010-12-06 15:07:52 -08002073 } else {
2074 // if we are unable to parse the extras for whatever reason convert this
2075 // to a regular sync by creating an empty extras
2076 extras = new Bundle();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002077 }
2078 PendingOperation op = new PendingOperation(
Amith Yamasani04e0d262012-02-14 11:50:53 -08002079 authority.account, authority.userId, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08002080 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002081 op.authorityId = authorityId;
2082 op.flatExtras = flatExtras;
2083 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
2084 + " auth=" + op.authority
2085 + " src=" + op.syncSource
Fred Quintana307da1a2010-01-21 14:24:20 -08002086 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07002087 + " extras=" + op.extras);
2088 mPendingOperations.add(op);
2089 }
2090 }
2091 } catch (java.io.IOException e) {
2092 Log.i(TAG, "No initial pending operations");
2093 }
2094 }
Costin Manolache360e4542009-09-04 13:36:04 -07002095
Dianne Hackborn231cc602009-04-27 17:10:36 -07002096 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
2097 out.writeInt(PENDING_OPERATION_VERSION);
2098 out.writeInt(op.authorityId);
2099 out.writeInt(op.syncSource);
2100 if (op.flatExtras == null && op.extras != null) {
2101 op.flatExtras = flattenBundle(op.extras);
2102 }
2103 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08002104 out.writeInt(op.expedited ? 1 : 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002105 }
Costin Manolache360e4542009-09-04 13:36:04 -07002106
Dianne Hackborn231cc602009-04-27 17:10:36 -07002107 /**
2108 * Write all currently pending ops to the pending ops file.
2109 */
2110 private void writePendingOperationsLocked() {
2111 final int N = mPendingOperations.size();
2112 FileOutputStream fos = null;
2113 try {
2114 if (N == 0) {
2115 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2116 mPendingFile.truncate();
2117 return;
2118 }
Costin Manolache360e4542009-09-04 13:36:04 -07002119
Dianne Hackborn231cc602009-04-27 17:10:36 -07002120 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2121 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07002122
Dianne Hackborn231cc602009-04-27 17:10:36 -07002123 Parcel out = Parcel.obtain();
2124 for (int i=0; i<N; i++) {
2125 PendingOperation op = mPendingOperations.get(i);
2126 writePendingOperationLocked(op, out);
2127 }
2128 fos.write(out.marshall());
2129 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002130
Dianne Hackborn231cc602009-04-27 17:10:36 -07002131 mPendingFile.finishWrite(fos);
2132 } catch (java.io.IOException e1) {
2133 Log.w(TAG, "Error writing pending operations", e1);
2134 if (fos != null) {
2135 mPendingFile.failWrite(fos);
2136 }
2137 }
2138 }
Costin Manolache360e4542009-09-04 13:36:04 -07002139
Dianne Hackborn231cc602009-04-27 17:10:36 -07002140 /**
2141 * Append the given operation to the pending ops file; if unable to,
2142 * write all pending ops.
2143 */
2144 private void appendPendingOperationLocked(PendingOperation op) {
2145 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2146 FileOutputStream fos = null;
2147 try {
2148 fos = mPendingFile.openAppend();
2149 } catch (java.io.IOException e) {
2150 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2151 writePendingOperationsLocked();
2152 return;
2153 }
Costin Manolache360e4542009-09-04 13:36:04 -07002154
Dianne Hackborn231cc602009-04-27 17:10:36 -07002155 try {
2156 Parcel out = Parcel.obtain();
2157 writePendingOperationLocked(op, out);
2158 fos.write(out.marshall());
2159 out.recycle();
2160 } catch (java.io.IOException e1) {
2161 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002163 try {
2164 fos.close();
2165 } catch (java.io.IOException e2) {
2166 }
2167 }
2168 }
Costin Manolache360e4542009-09-04 13:36:04 -07002169
Dianne Hackborn231cc602009-04-27 17:10:36 -07002170 static private byte[] flattenBundle(Bundle bundle) {
2171 byte[] flatData = null;
2172 Parcel parcel = Parcel.obtain();
2173 try {
2174 bundle.writeToParcel(parcel, 0);
2175 flatData = parcel.marshall();
2176 } finally {
2177 parcel.recycle();
2178 }
2179 return flatData;
2180 }
Costin Manolache360e4542009-09-04 13:36:04 -07002181
Dianne Hackborn231cc602009-04-27 17:10:36 -07002182 static private Bundle unflattenBundle(byte[] flatData) {
2183 Bundle bundle;
2184 Parcel parcel = Parcel.obtain();
2185 try {
2186 parcel.unmarshall(flatData, 0, flatData.length);
2187 parcel.setDataPosition(0);
2188 bundle = parcel.readBundle();
2189 } catch (RuntimeException e) {
2190 // A RuntimeException is thrown if we were unable to parse the parcel.
2191 // Create an empty parcel in this case.
2192 bundle = new Bundle();
2193 } finally {
2194 parcel.recycle();
2195 }
2196 return bundle;
2197 }
Costin Manolache360e4542009-09-04 13:36:04 -07002198
Amith Yamasani04e0d262012-02-14 11:50:53 -08002199 private void requestSync(Account account, int userId, String authority, Bundle extras) {
2200 // If this is happening in the system process, then call the syncrequest listener
2201 // to make a request back to the SyncManager directly.
2202 // If this is probably a test instance, then call back through the ContentResolver
2203 // which will know which userId to apply based on the Binder id.
2204 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2205 && mSyncRequestListener != null) {
2206 mSyncRequestListener.onSyncRequest(account, userId, authority, extras);
2207 } else {
2208 ContentResolver.requestSync(account, authority, extras);
2209 }
2210 }
2211
Dianne Hackborn231cc602009-04-27 17:10:36 -07002212 public static final int STATISTICS_FILE_END = 0;
2213 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2214 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002215
Dianne Hackborn231cc602009-04-27 17:10:36 -07002216 /**
2217 * Read all sync statistics back in to the initial engine state.
2218 */
2219 private void readStatisticsLocked() {
2220 try {
2221 byte[] data = mStatisticsFile.readFully();
2222 Parcel in = Parcel.obtain();
2223 in.unmarshall(data, 0, data.length);
2224 in.setDataPosition(0);
2225 int token;
2226 int index = 0;
2227 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2228 if (token == STATISTICS_FILE_ITEM
2229 || token == STATISTICS_FILE_ITEM_OLD) {
2230 int day = in.readInt();
2231 if (token == STATISTICS_FILE_ITEM_OLD) {
2232 day = day - 2009 + 14245; // Magic!
2233 }
2234 DayStats ds = new DayStats(day);
2235 ds.successCount = in.readInt();
2236 ds.successTime = in.readLong();
2237 ds.failureCount = in.readInt();
2238 ds.failureTime = in.readLong();
2239 if (index < mDayStats.length) {
2240 mDayStats[index] = ds;
2241 index++;
2242 }
2243 } else {
2244 // Ooops.
2245 Log.w(TAG, "Unknown stats token: " + token);
2246 break;
2247 }
2248 }
2249 } catch (java.io.IOException e) {
2250 Log.i(TAG, "No initial statistics");
2251 }
2252 }
Costin Manolache360e4542009-09-04 13:36:04 -07002253
Dianne Hackborn231cc602009-04-27 17:10:36 -07002254 /**
2255 * Write all sync statistics to the sync status file.
2256 */
2257 private void writeStatisticsLocked() {
2258 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002259
Dianne Hackborn231cc602009-04-27 17:10:36 -07002260 // The file is being written, so we don't need to have a scheduled
2261 // write until the next change.
2262 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002263
Dianne Hackborn231cc602009-04-27 17:10:36 -07002264 FileOutputStream fos = null;
2265 try {
2266 fos = mStatisticsFile.startWrite();
2267 Parcel out = Parcel.obtain();
2268 final int N = mDayStats.length;
2269 for (int i=0; i<N; i++) {
2270 DayStats ds = mDayStats[i];
2271 if (ds == null) {
2272 break;
2273 }
2274 out.writeInt(STATISTICS_FILE_ITEM);
2275 out.writeInt(ds.day);
2276 out.writeInt(ds.successCount);
2277 out.writeLong(ds.successTime);
2278 out.writeInt(ds.failureCount);
2279 out.writeLong(ds.failureTime);
2280 }
2281 out.writeInt(STATISTICS_FILE_END);
2282 fos.write(out.marshall());
2283 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002284
Dianne Hackborn231cc602009-04-27 17:10:36 -07002285 mStatisticsFile.finishWrite(fos);
2286 } catch (java.io.IOException e1) {
2287 Log.w(TAG, "Error writing stats", e1);
2288 if (fos != null) {
2289 mStatisticsFile.failWrite(fos);
2290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 }
2292 }
2293}