blob: 226e107fbd34c8379ea829f25c524bb559f25216 [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080017package android.content;
18
Dianne Hackborn231cc602009-04-27 17:10:36 -070019import com.android.internal.os.AtomicFile;
20import com.android.internal.util.ArrayUtils;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080021import com.android.internal.util.FastXmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022
Jason parksa3cdaa52011-01-13 14:15:43 -060023import org.xmlpull.v1.XmlPullParser;
24import org.xmlpull.v1.XmlPullParserException;
25import org.xmlpull.v1.XmlSerializer;
26
Fred Quintanad9d2f112009-04-23 13:36:27 -070027import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070028import android.accounts.AccountAndUser;
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;
Ashish Sharma69d95de2012-04-11 17:27:24 -070040import android.os.SystemClock;
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>();
340
341 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700342
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800343 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700346
Dianne Hackborn231cc602009-04-27 17:10:36 -0700347 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700348
Dianne Hackborn231cc602009-04-27 17:10:36 -0700349 File systemDir = new File(dataDir, "system");
350 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800351 syncDir.mkdirs();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700352 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
353 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
354 mPendingFile = new AtomicFile(new File(syncDir, "pending.bin"));
355 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700356
Dianne Hackborn231cc602009-04-27 17:10:36 -0700357 readAccountInfoLocked();
358 readStatusLocked();
359 readPendingOperationsLocked();
360 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700361 readAndDeleteLegacyAccountInfoLocked();
362 writeAccountInfoLocked();
363 writeStatusLocked();
364 writePendingOperationsLocked();
365 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 }
367
368 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800369 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 }
371
372 public static void init(Context context) {
373 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800374 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800376 // This call will return the correct directory whether Encrypted File Systems is
377 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600378 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800379 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
381
382 public static SyncStorageEngine getSingleton() {
383 if (sSyncStorageEngine == null) {
384 throw new IllegalStateException("not initialized");
385 }
386 return sSyncStorageEngine;
387 }
388
Amith Yamasani04e0d262012-02-14 11:50:53 -0800389 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
390 if (mSyncRequestListener == null) {
391 mSyncRequestListener = listener;
392 }
393 }
394
Dianne Hackborn231cc602009-04-27 17:10:36 -0700395 @Override public void handleMessage(Message msg) {
396 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700397 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700398 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700399 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700400 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700401 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700402 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 }
404 }
405 }
Costin Manolache360e4542009-09-04 13:36:04 -0700406
Ashish Sharma69d95de2012-04-11 17:27:24 -0700407 public int getSyncRandomOffset() {
408 return mSyncRandomOffset;
409 }
410
Dianne Hackborn231cc602009-04-27 17:10:36 -0700411 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
412 synchronized (mAuthorities) {
413 mChangeListeners.register(callback, mask);
414 }
415 }
Costin Manolache360e4542009-09-04 13:36:04 -0700416
Dianne Hackborn231cc602009-04-27 17:10:36 -0700417 public void removeStatusChangeListener(ISyncStatusObserver callback) {
418 synchronized (mAuthorities) {
419 mChangeListeners.unregister(callback);
420 }
421 }
Costin Manolache360e4542009-09-04 13:36:04 -0700422
Dianne Hackborn231cc602009-04-27 17:10:36 -0700423 private void reportChange(int which) {
424 ArrayList<ISyncStatusObserver> reports = null;
425 synchronized (mAuthorities) {
426 int i = mChangeListeners.beginBroadcast();
427 while (i > 0) {
428 i--;
429 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
430 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 continue;
432 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700433 if (reports == null) {
434 reports = new ArrayList<ISyncStatusObserver>(i);
435 }
436 reports.add(mChangeListeners.getBroadcastItem(i));
437 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700438 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700439 }
Costin Manolache360e4542009-09-04 13:36:04 -0700440
Fred Quintana77c560f2010-03-29 22:20:26 -0700441 if (Log.isLoggable(TAG, Log.VERBOSE)) {
442 Log.v(TAG, "reportChange " + which + " to: " + reports);
443 }
Costin Manolache360e4542009-09-04 13:36:04 -0700444
Dianne Hackborn231cc602009-04-27 17:10:36 -0700445 if (reports != null) {
446 int i = reports.size();
447 while (i > 0) {
448 i--;
449 try {
450 reports.get(i).onStatusChanged(which);
451 } catch (RemoteException e) {
452 // The remote callback list will take care of this for us.
453 }
454 }
455 }
456 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700457
Amith Yamasani04e0d262012-02-14 11:50:53 -0800458 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700459 synchronized (mAuthorities) {
460 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800461 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700462 "getSyncAutomatically");
463 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700464 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700465
Dianne Hackborn231cc602009-04-27 17:10:36 -0700466 int i = mAuthorities.size();
467 while (i > 0) {
468 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700469 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700470 if (authority.authority.equals(providerName)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800471 && authority.userId == userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700472 && authority.enabled) {
473 return true;
474 }
475 }
476 return false;
477 }
478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479
Amith Yamasani04e0d262012-02-14 11:50:53 -0800480 public void setSyncAutomatically(Account account, int userId, String providerName,
481 boolean sync) {
482 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
483 + ", user " + userId + " -> " + sync);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700484 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800485 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
486 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700487 if (authority.enabled == sync) {
488 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
489 return;
490 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700491 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700492 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700494
Fred Quintana77c560f2010-03-29 22:20:26 -0700495 if (sync) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800496 requestSync(account, userId, providerName, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700497 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700498 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 }
500
Amith Yamasani04e0d262012-02-14 11:50:53 -0800501 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700502 synchronized (mAuthorities) {
503 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800504 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintana5e787c42009-08-16 23:13:53 -0700505 "getIsSyncable");
506 if (authority == null) {
507 return -1;
508 }
509 return authority.syncable;
510 }
511
512 int i = mAuthorities.size();
513 while (i > 0) {
514 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700515 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700516 if (authority.authority.equals(providerName)) {
517 return authority.syncable;
518 }
519 }
520 return -1;
521 }
522 }
523
Amith Yamasani04e0d262012-02-14 11:50:53 -0800524 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700525 if (syncable > 1) {
526 syncable = 1;
527 } else if (syncable < -1) {
528 syncable = -1;
529 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800530 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName
531 + ", user " + userId + " -> " + syncable);
Fred Quintana5e787c42009-08-16 23:13:53 -0700532 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800533 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
534 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700535 if (authority.syncable == syncable) {
536 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
537 return;
538 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700539 authority.syncable = syncable;
540 writeAccountInfoLocked();
541 }
542
Fred Quintana77c560f2010-03-29 22:20:26 -0700543 if (syncable > 0) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800544 requestSync(account, userId, providerName, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700545 }
546 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
547 }
548
Amith Yamasani04e0d262012-02-14 11:50:53 -0800549 public Pair<Long, Long> getBackoff(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800550 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800551 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
552 "getBackoff");
Fred Quintana307da1a2010-01-21 14:24:20 -0800553 if (authority == null || authority.backoffTime < 0) {
554 return null;
555 }
556 return Pair.create(authority.backoffTime, authority.backoffDelay);
557 }
558 }
559
Amith Yamasani04e0d262012-02-14 11:50:53 -0800560 public void setBackoff(Account account, int userId, String providerName,
Fred Quintana307da1a2010-01-21 14:24:20 -0800561 long nextSyncTime, long nextDelay) {
562 if (Log.isLoggable(TAG, Log.VERBOSE)) {
563 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800564 + ", user " + userId
Fred Quintana307da1a2010-01-21 14:24:20 -0800565 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
566 }
567 boolean changed = false;
568 synchronized (mAuthorities) {
569 if (account == null || providerName == null) {
570 for (AccountInfo accountInfo : mAccounts.values()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800571 if (account != null && !account.equals(accountInfo.accountAndUser.account)
572 && userId != accountInfo.accountAndUser.userId) {
573 continue;
574 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800575 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
576 if (providerName != null && !providerName.equals(authorityInfo.authority)) {
577 continue;
578 }
579 if (authorityInfo.backoffTime != nextSyncTime
580 || authorityInfo.backoffDelay != nextDelay) {
581 authorityInfo.backoffTime = nextSyncTime;
582 authorityInfo.backoffDelay = nextDelay;
583 changed = true;
584 }
585 }
586 }
587 } else {
588 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800589 getOrCreateAuthorityLocked(account, userId, providerName, -1 /* ident */,
590 true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800591 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
592 return;
593 }
594 authority.backoffTime = nextSyncTime;
595 authority.backoffDelay = nextDelay;
596 changed = true;
597 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800598 }
599
600 if (changed) {
601 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
602 }
603 }
604
Alon Alberted1d2532011-02-15 14:02:14 -0800605 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800606 boolean changed = false;
607 synchronized (mAuthorities) {
608 for (AccountInfo accountInfo : mAccounts.values()) {
609 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
610 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
611 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
612 if (Log.isLoggable(TAG, Log.VERBOSE)) {
613 Log.v(TAG, "clearAllBackoffs:"
614 + " authority:" + authorityInfo.authority
Amith Yamasani04e0d262012-02-14 11:50:53 -0800615 + " account:" + accountInfo.accountAndUser.account.name
616 + " user:" + accountInfo.accountAndUser.userId
Alon Albert744e310f2010-12-14 11:37:20 -0800617 + " backoffTime was: " + authorityInfo.backoffTime
618 + " backoffDelay was: " + authorityInfo.backoffDelay);
619 }
620 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
621 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800622 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
623 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
Alon Albert744e310f2010-12-14 11:37:20 -0800624 changed = true;
625 }
626 }
627 }
628 }
629
630 if (changed) {
631 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
632 }
633 }
634
Amith Yamasani04e0d262012-02-14 11:50:53 -0800635 public void setDelayUntilTime(Account account, int userId, String providerName,
636 long delayUntil) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800637 if (Log.isLoggable(TAG, Log.VERBOSE)) {
638 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800639 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800640 }
641 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800642 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800643 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800644 if (authority.delayUntil == delayUntil) {
645 return;
646 }
647 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800648 }
649
650 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
651 }
652
Amith Yamasani04e0d262012-02-14 11:50:53 -0800653 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800654 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800655 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
656 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800657 if (authority == null) {
658 return 0;
659 }
660 return authority.delayUntil;
661 }
662 }
663
Amith Yamasani04e0d262012-02-14 11:50:53 -0800664 private void updateOrRemovePeriodicSync(Account account, int userId, String providerName,
665 Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800666 long period, boolean add) {
667 if (period <= 0) {
668 period = 0;
669 }
670 if (extras == null) {
671 extras = new Bundle();
672 }
673 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800674 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", user " + userId
675 + ", provider " + providerName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800676 + " -> period " + period + ", extras " + extras);
677 }
678 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700679 try {
680 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800681 getOrCreateAuthorityLocked(account, userId, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700682 if (add) {
683 // add this periodic sync if one with the same extras doesn't already
684 // exist in the periodicSyncs array
685 boolean alreadyPresent = false;
686 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
687 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
688 final Bundle existingExtras = syncInfo.first;
689 if (equals(existingExtras, extras)) {
690 if (syncInfo.second == period) {
691 return;
692 }
693 authority.periodicSyncs.set(i, Pair.create(extras, period));
694 alreadyPresent = true;
695 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800696 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700697 }
698 // if we added an entry to the periodicSyncs array also add an entry to
699 // the periodic syncs status to correspond to it
700 if (!alreadyPresent) {
701 authority.periodicSyncs.add(Pair.create(extras, period));
702 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
703 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
704 }
705 } else {
706 // remove any periodic syncs that match the authority and extras
707 SyncStatusInfo status = mSyncStatus.get(authority.ident);
708 boolean changed = false;
709 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
710 int i = 0;
711 while (iterator.hasNext()) {
712 Pair<Bundle, Long> syncInfo = iterator.next();
713 if (equals(syncInfo.first, extras)) {
714 iterator.remove();
715 changed = true;
716 // if we removed an entry from the periodicSyncs array also
717 // remove the corresponding entry from the status
718 if (status != null) {
719 status.removePeriodicSyncTime(i);
720 }
721 } else {
722 i++;
723 }
724 }
725 if (!changed) {
726 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800727 }
728 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700729 } finally {
730 writeAccountInfoLocked();
731 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800732 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800733 }
734
735 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
736 }
737
Amith Yamasani04e0d262012-02-14 11:50:53 -0800738 public void addPeriodicSync(Account account, int userId, String providerName, Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800739 long pollFrequency) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800740 updateOrRemovePeriodicSync(account, userId, providerName, extras, pollFrequency,
741 true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800742 }
743
Amith Yamasani04e0d262012-02-14 11:50:53 -0800744 public void removePeriodicSync(Account account, int userId, String providerName,
745 Bundle extras) {
746 updateOrRemovePeriodicSync(account, userId, providerName, extras, 0 /* period, ignored */,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800747 false /* remove */);
748 }
749
Amith Yamasani04e0d262012-02-14 11:50:53 -0800750 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800751 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
752 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800753 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
754 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800755 if (authority != null) {
756 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800757 syncs.add(new PeriodicSync(account, providerName, item.first,
758 item.second));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800759 }
760 }
761 }
762 return syncs;
763 }
764
Amith Yamasani04e0d262012-02-14 11:50:53 -0800765 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700766 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800767 Boolean auto = mMasterSyncAutomatically.get(userId);
768 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700769 return;
770 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800771 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700772 writeAccountInfoLocked();
773 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700774 if (flag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800775 requestSync(null, userId, null, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700776 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700777 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
778 mContext.sendBroadcast(SYNC_CONNECTION_SETTING_CHANGED_INTENT);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780
Amith Yamasani04e0d262012-02-14 11:50:53 -0800781 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700782 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800783 Boolean auto = mMasterSyncAutomatically.get(userId);
784 return auto == null ? true : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700785 }
786 }
Costin Manolache360e4542009-09-04 13:36:04 -0700787
Amith Yamasani04e0d262012-02-14 11:50:53 -0800788 public AuthorityInfo getOrCreateAuthority(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700789 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800790 return getOrCreateAuthorityLocked(account, userId, authority,
Fred Quintana1bbcd102010-02-10 10:04:33 -0800791 -1 /* assign a new identifier if creating a new authority */,
792 true /* write to storage if this results in a change */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700793 }
794 }
Costin Manolache360e4542009-09-04 13:36:04 -0700795
Amith Yamasani04e0d262012-02-14 11:50:53 -0800796 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700797 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800798 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700799 }
800 }
801
Dianne Hackborn231cc602009-04-27 17:10:36 -0700802 public AuthorityInfo getAuthority(int authorityId) {
803 synchronized (mAuthorities) {
804 return mAuthorities.get(authorityId);
805 }
806 }
Costin Manolache360e4542009-09-04 13:36:04 -0700807
Dianne Hackborn231cc602009-04-27 17:10:36 -0700808 /**
809 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700810 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700811 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800812 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700813 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800814 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700815 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700816 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800817 && ainfo.authority.equals(authority)
818 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700819 return true;
820 }
821 }
822 }
Costin Manolache360e4542009-09-04 13:36:04 -0700823
Dianne Hackborn231cc602009-04-27 17:10:36 -0700824 return false;
825 }
Costin Manolache360e4542009-09-04 13:36:04 -0700826
Dianne Hackborn231cc602009-04-27 17:10:36 -0700827 public PendingOperation insertIntoPending(PendingOperation op) {
828 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700829 if (Log.isLoggable(TAG, Log.VERBOSE)) {
830 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800831 + " user=" + op.userId
832 + " auth=" + op.authority
833 + " src=" + op.syncSource
834 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700835 }
Costin Manolache360e4542009-09-04 13:36:04 -0700836
Amith Yamasani04e0d262012-02-14 11:50:53 -0800837 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700838 op.authority,
839 -1 /* desired identifier */,
840 true /* write accounts to storage */);
841 if (authority == null) {
842 return null;
843 }
Costin Manolache360e4542009-09-04 13:36:04 -0700844
Dianne Hackborn231cc602009-04-27 17:10:36 -0700845 op = new PendingOperation(op);
846 op.authorityId = authority.ident;
847 mPendingOperations.add(op);
848 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700849
Dianne Hackborn231cc602009-04-27 17:10:36 -0700850 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
851 status.pending = true;
852 }
Costin Manolache360e4542009-09-04 13:36:04 -0700853
Fred Quintanaac9385e2009-06-22 18:00:59 -0700854 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700855 return op;
856 }
857
858 public boolean deleteFromPending(PendingOperation op) {
859 boolean res = false;
860 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700861 if (Log.isLoggable(TAG, Log.VERBOSE)) {
862 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800863 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700864 + " auth=" + op.authority
865 + " src=" + op.syncSource
866 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700867 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700868 if (mPendingOperations.remove(op)) {
869 if (mPendingOperations.size() == 0
870 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
871 writePendingOperationsLocked();
872 mNumPendingFinished = 0;
873 } else {
874 mNumPendingFinished++;
875 }
Costin Manolache360e4542009-09-04 13:36:04 -0700876
Amith Yamasani04e0d262012-02-14 11:50:53 -0800877 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700878 "deleteFromPending");
879 if (authority != null) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700880 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "removing - " + authority);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700881 final int N = mPendingOperations.size();
882 boolean morePending = false;
883 for (int i=0; i<N; i++) {
884 PendingOperation cur = mPendingOperations.get(i);
885 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800886 && cur.authority.equals(op.authority)
887 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700888 morePending = true;
889 break;
890 }
891 }
Costin Manolache360e4542009-09-04 13:36:04 -0700892
Dianne Hackborn231cc602009-04-27 17:10:36 -0700893 if (!morePending) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700894 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700895 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
896 status.pending = false;
897 }
898 }
Costin Manolache360e4542009-09-04 13:36:04 -0700899
Dianne Hackborn231cc602009-04-27 17:10:36 -0700900 res = true;
901 }
902 }
Costin Manolache360e4542009-09-04 13:36:04 -0700903
Fred Quintanaac9385e2009-06-22 18:00:59 -0700904 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700905 return res;
906 }
907
Dianne Hackborn231cc602009-04-27 17:10:36 -0700908 /**
909 * Return a copy of the current array of pending operations. The
910 * PendingOperation objects are the real objects stored inside, so that
911 * they can be used with deleteFromPending().
912 */
913 public ArrayList<PendingOperation> getPendingOperations() {
914 synchronized (mAuthorities) {
915 return new ArrayList<PendingOperation>(mPendingOperations);
916 }
917 }
Costin Manolache360e4542009-09-04 13:36:04 -0700918
Dianne Hackborn231cc602009-04-27 17:10:36 -0700919 /**
920 * Return the number of currently pending operations.
921 */
922 public int getPendingOperationCount() {
923 synchronized (mAuthorities) {
924 return mPendingOperations.size();
925 }
926 }
Costin Manolache360e4542009-09-04 13:36:04 -0700927
Dianne Hackborn231cc602009-04-27 17:10:36 -0700928 /**
929 * Called when the set of account has changed, given the new array of
930 * active accounts.
931 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800932 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700933 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700934 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.w(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700935 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
936 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
937 while (accIt.hasNext()) {
938 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800939 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
940 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700941 // This account no longer exists...
Fred Quintana77c560f2010-03-29 22:20:26 -0700942 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800943 Log.w(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700944 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700945 for (AuthorityInfo auth : acc.authorities.values()) {
946 removing.put(auth.ident, auth);
947 }
948 accIt.remove();
949 }
950 }
Costin Manolache360e4542009-09-04 13:36:04 -0700951
Dianne Hackborn231cc602009-04-27 17:10:36 -0700952 // Clean out all data structures.
953 int i = removing.size();
954 if (i > 0) {
955 while (i > 0) {
956 i--;
957 int ident = removing.keyAt(i);
958 mAuthorities.remove(ident);
959 int j = mSyncStatus.size();
960 while (j > 0) {
961 j--;
962 if (mSyncStatus.keyAt(j) == ident) {
963 mSyncStatus.remove(mSyncStatus.keyAt(j));
964 }
965 }
966 j = mSyncHistory.size();
967 while (j > 0) {
968 j--;
969 if (mSyncHistory.get(j).authorityId == ident) {
970 mSyncHistory.remove(j);
971 }
972 }
973 }
974 writeAccountInfoLocked();
975 writeStatusLocked();
976 writePendingOperationsLocked();
977 writeStatisticsLocked();
978 }
979 }
980 }
981
982 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700983 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
984 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700985 */
Fred Quintana918339a2010-10-05 14:00:39 -0700986 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
987 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700988 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -0700989 if (Log.isLoggable(TAG, Log.VERBOSE)) {
990 Log.v(TAG, "setActiveSync: account="
991 + activeSyncContext.mSyncOperation.account
992 + " auth=" + activeSyncContext.mSyncOperation.authority
993 + " src=" + activeSyncContext.mSyncOperation.syncSource
994 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700995 }
Fred Quintana918339a2010-10-05 14:00:39 -0700996 AuthorityInfo authority = getOrCreateAuthorityLocked(
997 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -0800998 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -0700999 activeSyncContext.mSyncOperation.authority,
1000 -1 /* assign a new identifier if creating a new authority */,
1001 true /* write to storage if this results in a change */);
1002 syncInfo = new SyncInfo(authority.ident,
1003 authority.account, authority.authority,
1004 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001005 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001006 }
Costin Manolache360e4542009-09-04 13:36:04 -07001007
Fred Quintana918339a2010-10-05 14:00:39 -07001008 reportActiveChange();
1009 return syncInfo;
1010 }
1011
1012 /**
1013 * Called to indicate that a previously active sync is no longer active.
1014 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001015 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001016 synchronized (mAuthorities) {
1017 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001018 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1019 + " user=" + userId
1020 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001021 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001022 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001023 }
1024
1025 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001026 }
1027
1028 /**
1029 * To allow others to send active change reports, to poke clients.
1030 */
1031 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001032 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001033 }
Costin Manolache360e4542009-09-04 13:36:04 -07001034
Dianne Hackborn231cc602009-04-27 17:10:36 -07001035 /**
1036 * Note that sync has started for the given account and authority.
1037 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001038 public long insertStartSyncEvent(Account accountName, int userId, String authorityName,
Fred Quintanadc475562012-05-04 15:51:54 -07001039 long now, int source, boolean initialization) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001040 long id;
1041 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001042 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001043 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001045 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001046 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001047 "insertStartSyncEvent");
1048 if (authority == null) {
1049 return -1;
1050 }
1051 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001052 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001053 item.authorityId = authority.ident;
1054 item.historyId = mNextHistoryId++;
1055 if (mNextHistoryId < 0) mNextHistoryId = 0;
1056 item.eventTime = now;
1057 item.source = source;
1058 item.event = EVENT_START;
1059 mSyncHistory.add(0, item);
1060 while (mSyncHistory.size() > MAX_HISTORY) {
1061 mSyncHistory.remove(mSyncHistory.size()-1);
1062 }
1063 id = item.historyId;
Fred Quintana77c560f2010-03-29 22:20:26 -07001064 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001065 }
Costin Manolache360e4542009-09-04 13:36:04 -07001066
Fred Quintanaac9385e2009-06-22 18:00:59 -07001067 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001068 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
1070
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001071 public static boolean equals(Bundle b1, Bundle b2) {
1072 if (b1.size() != b2.size()) {
1073 return false;
1074 }
1075 if (b1.isEmpty()) {
1076 return true;
1077 }
1078 for (String key : b1.keySet()) {
1079 if (!b2.containsKey(key)) {
1080 return false;
1081 }
1082 if (!b1.get(key).equals(b2.get(key))) {
1083 return false;
1084 }
1085 }
1086 return true;
1087 }
1088
Fred Quintana77c560f2010-03-29 22:20:26 -07001089 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001091 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001092 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1093 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1094 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001095 SyncHistoryItem item = null;
1096 int i = mSyncHistory.size();
1097 while (i > 0) {
1098 i--;
1099 item = mSyncHistory.get(i);
1100 if (item.historyId == historyId) {
1101 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001103 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
Costin Manolache360e4542009-09-04 13:36:04 -07001105
Dianne Hackborn231cc602009-04-27 17:10:36 -07001106 if (item == null) {
1107 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1108 return;
1109 }
Costin Manolache360e4542009-09-04 13:36:04 -07001110
Dianne Hackborn231cc602009-04-27 17:10:36 -07001111 item.elapsedTime = elapsedTime;
1112 item.event = EVENT_STOP;
1113 item.mesg = resultMessage;
1114 item.downstreamActivity = downstreamActivity;
1115 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001116
Dianne Hackborn231cc602009-04-27 17:10:36 -07001117 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001118
Dianne Hackborn231cc602009-04-27 17:10:36 -07001119 status.numSyncs++;
1120 status.totalElapsedTime += elapsedTime;
1121 switch (item.source) {
1122 case SOURCE_LOCAL:
1123 status.numSourceLocal++;
1124 break;
1125 case SOURCE_POLL:
1126 status.numSourcePoll++;
1127 break;
1128 case SOURCE_USER:
1129 status.numSourceUser++;
1130 break;
1131 case SOURCE_SERVER:
1132 status.numSourceServer++;
1133 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001134 case SOURCE_PERIODIC:
1135 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001136 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001137 }
Costin Manolache360e4542009-09-04 13:36:04 -07001138
Dianne Hackborn231cc602009-04-27 17:10:36 -07001139 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001140 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001141 if (mDayStats[0] == null) {
1142 mDayStats[0] = new DayStats(day);
1143 } else if (day != mDayStats[0].day) {
1144 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1145 mDayStats[0] = new DayStats(day);
1146 writeStatisticsNow = true;
1147 } else if (mDayStats[0] == null) {
1148 }
1149 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001150
Dianne Hackborn231cc602009-04-27 17:10:36 -07001151 final long lastSyncTime = (item.eventTime + elapsedTime);
1152 boolean writeStatusNow = false;
1153 if (MESG_SUCCESS.equals(resultMessage)) {
1154 // - if successful, update the successful columns
1155 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1156 writeStatusNow = true;
1157 }
1158 status.lastSuccessTime = lastSyncTime;
1159 status.lastSuccessSource = item.source;
1160 status.lastFailureTime = 0;
1161 status.lastFailureSource = -1;
1162 status.lastFailureMesg = null;
1163 status.initialFailureTime = 0;
1164 ds.successCount++;
1165 ds.successTime += elapsedTime;
1166 } else if (!MESG_CANCELED.equals(resultMessage)) {
1167 if (status.lastFailureTime == 0) {
1168 writeStatusNow = true;
1169 }
1170 status.lastFailureTime = lastSyncTime;
1171 status.lastFailureSource = item.source;
1172 status.lastFailureMesg = resultMessage;
1173 if (status.initialFailureTime == 0) {
1174 status.initialFailureTime = lastSyncTime;
1175 }
1176 ds.failureCount++;
1177 ds.failureTime += elapsedTime;
1178 }
Costin Manolache360e4542009-09-04 13:36:04 -07001179
Dianne Hackborn231cc602009-04-27 17:10:36 -07001180 if (writeStatusNow) {
1181 writeStatusLocked();
1182 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1183 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1184 WRITE_STATUS_DELAY);
1185 }
1186 if (writeStatisticsNow) {
1187 writeStatisticsLocked();
1188 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1189 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1190 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001191 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001192 }
Costin Manolache360e4542009-09-04 13:36:04 -07001193
Fred Quintanaac9385e2009-06-22 18:00:59 -07001194 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001195 }
1196
1197 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001198 * Return a list of the currently active syncs. Note that the returned items are the
1199 * real, live active sync objects, so be careful what you do with it.
1200 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001201 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001202 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001203 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1204 if (syncs == null) {
1205 syncs = new ArrayList<SyncInfo>();
1206 mCurrentSyncs.put(userId, syncs);
1207 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001208 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001209 }
1210 }
Costin Manolache360e4542009-09-04 13:36:04 -07001211
Dianne Hackborn231cc602009-04-27 17:10:36 -07001212 /**
1213 * Return an array of the current sync status for all authorities. Note
1214 * that the objects inside the array are the real, live status objects,
1215 * so be careful what you do with them.
1216 */
1217 public ArrayList<SyncStatusInfo> getSyncStatus() {
1218 synchronized (mAuthorities) {
1219 final int N = mSyncStatus.size();
1220 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1221 for (int i=0; i<N; i++) {
1222 ops.add(mSyncStatus.valueAt(i));
1223 }
1224 return ops;
1225 }
1226 }
Costin Manolache360e4542009-09-04 13:36:04 -07001227
Dianne Hackborn231cc602009-04-27 17:10:36 -07001228 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001229 * Return an array of the current authorities. Note
1230 * that the objects inside the array are the real, live objects,
1231 * so be careful what you do with them.
1232 */
1233 public ArrayList<AuthorityInfo> getAuthorities() {
1234 synchronized (mAuthorities) {
1235 final int N = mAuthorities.size();
1236 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1237 for (int i=0; i<N; i++) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -07001238 // Make deep copy because AuthorityInfo syncs are liable to change.
1239 infos.add(new AuthorityInfo(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001240 }
1241 return infos;
1242 }
1243 }
1244
1245 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001246 * Returns the status that matches the authority and account.
1247 *
1248 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001249 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001250 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001251 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001252 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1253 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001254 if (account == null || authority == null) {
1255 throw new IllegalArgumentException();
1256 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001257 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001258 final int N = mSyncStatus.size();
1259 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001260 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001261 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001262
Amith Yamasani04e0d262012-02-14 11:50:53 -08001263 if (ainfo != null && ainfo.authority.equals(authority)
1264 && ainfo.userId == userId
1265 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001266 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001267 }
1268 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001269 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001270 }
1271 }
Costin Manolache360e4542009-09-04 13:36:04 -07001272
Dianne Hackborn231cc602009-04-27 17:10:36 -07001273 /**
1274 * Return true if the pending status is true of any matching authorities.
1275 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001276 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001277 synchronized (mAuthorities) {
1278 final int N = mSyncStatus.size();
1279 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001280 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001281 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1282 if (ainfo == null) {
1283 continue;
1284 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001285 if (userId != ainfo.userId) {
1286 continue;
1287 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001288 if (account != null && !ainfo.account.equals(account)) {
1289 continue;
1290 }
1291 if (ainfo.authority.equals(authority) && cur.pending) {
1292 return true;
1293 }
1294 }
1295 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 }
1297 }
1298
1299 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001300 * Return an array of the current sync status for all authorities. Note
1301 * that the objects inside the array are the real, live status objects,
1302 * so be careful what you do with them.
1303 */
1304 public ArrayList<SyncHistoryItem> getSyncHistory() {
1305 synchronized (mAuthorities) {
1306 final int N = mSyncHistory.size();
1307 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1308 for (int i=0; i<N; i++) {
1309 items.add(mSyncHistory.get(i));
1310 }
1311 return items;
1312 }
1313 }
Costin Manolache360e4542009-09-04 13:36:04 -07001314
Dianne Hackborn231cc602009-04-27 17:10:36 -07001315 /**
1316 * Return an array of the current per-day statistics. Note
1317 * that the objects inside the array are the real, live status objects,
1318 * so be careful what you do with them.
1319 */
1320 public DayStats[] getDayStatistics() {
1321 synchronized (mAuthorities) {
1322 DayStats[] ds = new DayStats[mDayStats.length];
1323 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1324 return ds;
1325 }
1326 }
Costin Manolache360e4542009-09-04 13:36:04 -07001327
Dianne Hackborn55280a92009-05-07 15:53:46 -07001328 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001329 mCal.setTimeInMillis(System.currentTimeMillis());
1330 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1331 if (mYear != mCal.get(Calendar.YEAR)) {
1332 mYear = mCal.get(Calendar.YEAR);
1333 mCal.clear();
1334 mCal.set(Calendar.YEAR, mYear);
1335 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1336 }
1337 return dayOfYear + mYearInDays;
1338 }
Costin Manolache360e4542009-09-04 13:36:04 -07001339
Dianne Hackborn231cc602009-04-27 17:10:36 -07001340 /**
1341 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001342 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001343 * @param accountName The name of the account for the authority.
1344 * @param authorityName The name of the authority itself.
1345 * @param tag If non-null, this will be used in a log message if the
1346 * requested authority does not exist.
1347 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001348 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001349 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001350 AccountAndUser au = new AccountAndUser(accountName, userId);
1351 AccountInfo accountInfo = mAccounts.get(au);
1352 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001353 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001354 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001355 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001356 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001357 }
1358 return null;
1359 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001360 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001361 if (authority == null) {
1362 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001363 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1364 Log.v(TAG, tag + ": unknown authority " + authorityName);
1365 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001366 }
1367 return null;
1368 }
Costin Manolache360e4542009-09-04 13:36:04 -07001369
Dianne Hackborn231cc602009-04-27 17:10:36 -07001370 return authority;
1371 }
Costin Manolache360e4542009-09-04 13:36:04 -07001372
Amith Yamasani04e0d262012-02-14 11:50:53 -08001373 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001374 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001375 AccountAndUser au = new AccountAndUser(accountName, userId);
1376 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001377 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001378 account = new AccountInfo(au);
1379 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001380 }
1381 AuthorityInfo authority = account.authorities.get(authorityName);
1382 if (authority == null) {
1383 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001384 ident = mNextAuthorityId;
1385 mNextAuthorityId++;
1386 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001387 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001388 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1389 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001390 + ", user " + userId
1391 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001392 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001393 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001394 account.authorities.put(authorityName, authority);
1395 mAuthorities.put(ident, authority);
1396 if (doWrite) {
1397 writeAccountInfoLocked();
1398 }
1399 }
Costin Manolache360e4542009-09-04 13:36:04 -07001400
Dianne Hackborn231cc602009-04-27 17:10:36 -07001401 return authority;
1402 }
Costin Manolache360e4542009-09-04 13:36:04 -07001403
Amith Yamasani04e0d262012-02-14 11:50:53 -08001404 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1405 boolean doWrite) {
1406 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001407 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001408 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1409 if (authorityInfo != null) {
1410 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001411 if (doWrite) {
1412 writeAccountInfoLocked();
1413 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001414 }
1415 }
1416 }
1417
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001418 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1419 synchronized (mAuthorities) {
1420 return getOrCreateSyncStatusLocked(authority.ident);
1421 }
1422 }
1423
Dianne Hackborn231cc602009-04-27 17:10:36 -07001424 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1425 SyncStatusInfo status = mSyncStatus.get(authorityId);
1426 if (status == null) {
1427 status = new SyncStatusInfo(authorityId);
1428 mSyncStatus.put(authorityId, status);
1429 }
1430 return status;
1431 }
Costin Manolache360e4542009-09-04 13:36:04 -07001432
Dianne Hackborn55280a92009-05-07 15:53:46 -07001433 public void writeAllState() {
1434 synchronized (mAuthorities) {
1435 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001436
Dianne Hackborn55280a92009-05-07 15:53:46 -07001437 if (mNumPendingFinished > 0) {
1438 // Only write these if they are out of date.
1439 writePendingOperationsLocked();
1440 }
Costin Manolache360e4542009-09-04 13:36:04 -07001441
Dianne Hackborn55280a92009-05-07 15:53:46 -07001442 // Just always write these... they are likely out of date.
1443 writeStatusLocked();
1444 writeStatisticsLocked();
1445 }
1446 }
Costin Manolache360e4542009-09-04 13:36:04 -07001447
Dianne Hackborn231cc602009-04-27 17:10:36 -07001448 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001449 * public for testing
1450 */
1451 public void clearAndReadState() {
1452 synchronized (mAuthorities) {
1453 mAuthorities.clear();
1454 mAccounts.clear();
1455 mPendingOperations.clear();
1456 mSyncStatus.clear();
1457 mSyncHistory.clear();
1458
1459 readAccountInfoLocked();
1460 readStatusLocked();
1461 readPendingOperationsLocked();
1462 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001463 readAndDeleteLegacyAccountInfoLocked();
1464 writeAccountInfoLocked();
1465 writeStatusLocked();
1466 writePendingOperationsLocked();
1467 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001468 }
1469 }
1470
1471 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001472 * Read all account information back in to the initial engine state.
1473 */
1474 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001475 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001476 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001478 fis = mAccountInfoFile.openRead();
1479 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1480 XmlPullParser parser = Xml.newPullParser();
1481 parser.setInput(fis, null);
1482 int eventType = parser.getEventType();
1483 while (eventType != XmlPullParser.START_TAG) {
1484 eventType = parser.next();
1485 }
1486 String tagName = parser.getName();
1487 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001488 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001489 String versionString = parser.getAttributeValue(null, "version");
1490 int version;
1491 try {
1492 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1493 } catch (NumberFormatException e) {
1494 version = 0;
1495 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001496 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001497 try {
1498 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1499 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1500 } catch (NumberFormatException e) {
1501 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001502 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001503 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1504 try {
1505 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1506 } catch (NumberFormatException e) {
1507 mSyncRandomOffset = 0;
1508 }
1509 if (mSyncRandomOffset == 0) {
1510 Random random = new Random(System.currentTimeMillis());
1511 mSyncRandomOffset = random.nextInt(86400);
1512 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001513 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001514 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001515 AuthorityInfo authority = null;
1516 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001517 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001518 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001519 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001520 if (parser.getDepth() == 2) {
1521 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001522 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001523 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001524 if (authority.ident > highestAuthorityId) {
1525 highestAuthorityId = authority.ident;
1526 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001527 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1528 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001529 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001530 } else if (parser.getDepth() == 3) {
1531 if ("periodicSync".equals(tagName) && authority != null) {
1532 periodicSync = parsePeriodicSync(parser, authority);
1533 }
1534 } else if (parser.getDepth() == 4 && periodicSync != null) {
1535 if ("extra".equals(tagName)) {
1536 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001537 }
1538 }
1539 }
1540 eventType = parser.next();
1541 } while (eventType != XmlPullParser.END_DOCUMENT);
1542 }
1543 } catch (XmlPullParserException e) {
1544 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001545 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001546 } catch (java.io.IOException e) {
1547 if (fis == null) Log.i(TAG, "No initial accounts");
1548 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001549 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001550 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001551 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001552 if (fis != null) {
1553 try {
1554 fis.close();
1555 } catch (java.io.IOException e1) {
1556 }
1557 }
1558 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001559
Fred Quintana77c560f2010-03-29 22:20:26 -07001560 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001561 }
Costin Manolache360e4542009-09-04 13:36:04 -07001562
Fred Quintanafb084402010-03-23 17:57:03 -07001563 /**
1564 * some authority names have changed. copy over their settings and delete the old ones
1565 * @return true if a change was made
1566 */
1567 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1568 boolean writeNeeded = false;
1569
1570 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1571 final int N = mAuthorities.size();
1572 for (int i=0; i<N; i++) {
1573 AuthorityInfo authority = mAuthorities.valueAt(i);
1574 // skip this authority if it isn't one of the renamed ones
1575 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1576 if (newAuthorityName == null) {
1577 continue;
1578 }
1579
1580 // remember this authority so we can remove it later. we can't remove it
1581 // now without messing up this loop iteration
1582 authoritiesToRemove.add(authority);
1583
1584 // this authority isn't enabled, no need to copy it to the new authority name since
1585 // the default is "disabled"
1586 if (!authority.enabled) {
1587 continue;
1588 }
1589
1590 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001591 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1592 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001593 continue;
1594 }
1595
1596 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001597 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001598 newAuthority.enabled = true;
1599 writeNeeded = true;
1600 }
1601
1602 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001603 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1604 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001605 writeNeeded = true;
1606 }
1607
1608 return writeNeeded;
1609 }
1610
Amith Yamasani04e0d262012-02-14 11:50:53 -08001611 private void parseListenForTickles(XmlPullParser parser) {
1612 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1613 int userId = 0;
1614 try {
1615 userId = Integer.parseInt(user);
1616 } catch (NumberFormatException e) {
1617 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1618 } catch (NullPointerException e) {
1619 Log.e(TAG, "the user in listen-for-tickles is null", e);
1620 }
1621 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1622 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1623 mMasterSyncAutomatically.put(userId, listen);
1624 }
1625
Fred Quintanac2e46912010-03-15 16:10:44 -07001626 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001627 AuthorityInfo authority = null;
1628 int id = -1;
1629 try {
1630 id = Integer.parseInt(parser.getAttributeValue(
1631 null, "id"));
1632 } catch (NumberFormatException e) {
1633 Log.e(TAG, "error parsing the id of the authority", e);
1634 } catch (NullPointerException e) {
1635 Log.e(TAG, "the id of the authority is null", e);
1636 }
1637 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001638 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001639 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001640 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001641 String accountName = parser.getAttributeValue(null, "account");
1642 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001643 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1644 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001645 if (accountType == null) {
1646 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001647 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001648 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001649 authority = mAuthorities.get(id);
1650 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1651 + accountName + " auth=" + authorityName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001652 + " user=" + userId
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001653 + " enabled=" + enabled
1654 + " syncable=" + syncable);
1655 if (authority == null) {
1656 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1657 authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001658 new Account(accountName, accountType), userId, authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001659 // If the version is 0 then we are upgrading from a file format that did not
1660 // know about periodic syncs. In that case don't clear the list since we
1661 // want the default, which is a daily periodioc sync.
1662 // Otherwise clear out this default list since we will populate it later with
1663 // the periodic sync descriptions that are read from the configuration file.
1664 if (version > 0) {
1665 authority.periodicSyncs.clear();
1666 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001667 }
1668 if (authority != null) {
1669 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1670 if ("unknown".equals(syncable)) {
1671 authority.syncable = -1;
1672 } else {
1673 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001674 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001675 }
1676 } else {
1677 Log.w(TAG, "Failure adding authority: account="
1678 + accountName + " auth=" + authorityName
1679 + " enabled=" + enabled
1680 + " syncable=" + syncable);
1681 }
1682 }
1683
1684 return authority;
1685 }
1686
1687 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1688 Bundle extras = new Bundle();
1689 String periodValue = parser.getAttributeValue(null, "period");
1690 final long period;
1691 try {
1692 period = Long.parseLong(periodValue);
1693 } catch (NumberFormatException e) {
1694 Log.e(TAG, "error parsing the period of a periodic sync", e);
1695 return null;
1696 } catch (NullPointerException e) {
1697 Log.e(TAG, "the period of a periodic sync is null", e);
1698 return null;
1699 }
1700 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1701 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001702
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001703 return periodicSync;
1704 }
1705
1706 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1707 final Bundle extras = periodicSync.first;
1708 String name = parser.getAttributeValue(null, "name");
1709 String type = parser.getAttributeValue(null, "type");
1710 String value1 = parser.getAttributeValue(null, "value1");
1711 String value2 = parser.getAttributeValue(null, "value2");
1712
1713 try {
1714 if ("long".equals(type)) {
1715 extras.putLong(name, Long.parseLong(value1));
1716 } else if ("integer".equals(type)) {
1717 extras.putInt(name, Integer.parseInt(value1));
1718 } else if ("double".equals(type)) {
1719 extras.putDouble(name, Double.parseDouble(value1));
1720 } else if ("float".equals(type)) {
1721 extras.putFloat(name, Float.parseFloat(value1));
1722 } else if ("boolean".equals(type)) {
1723 extras.putBoolean(name, Boolean.parseBoolean(value1));
1724 } else if ("string".equals(type)) {
1725 extras.putString(name, value1);
1726 } else if ("account".equals(type)) {
1727 extras.putParcelable(name, new Account(value1, value2));
1728 }
1729 } catch (NumberFormatException e) {
1730 Log.e(TAG, "error parsing bundle value", e);
1731 } catch (NullPointerException e) {
1732 Log.e(TAG, "error parsing bundle value", e);
1733 }
1734 }
1735
Dianne Hackborn231cc602009-04-27 17:10:36 -07001736 /**
1737 * Write all account information to the account file.
1738 */
1739 private void writeAccountInfoLocked() {
1740 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1741 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001742
Dianne Hackborn231cc602009-04-27 17:10:36 -07001743 try {
1744 fos = mAccountInfoFile.startWrite();
1745 XmlSerializer out = new FastXmlSerializer();
1746 out.setOutput(fos, "utf-8");
1747 out.startDocument(null, true);
1748 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001749
Dianne Hackborn231cc602009-04-27 17:10:36 -07001750 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001751 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001752 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001753 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001754
1755 // Write the Sync Automatically flags for each user
1756 final int M = mMasterSyncAutomatically.size();
1757 for (int m = 0; m < M; m++) {
1758 int userId = mMasterSyncAutomatically.keyAt(m);
1759 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1760 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1761 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1762 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1763 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001764 }
Costin Manolache360e4542009-09-04 13:36:04 -07001765
Dianne Hackborn231cc602009-04-27 17:10:36 -07001766 final int N = mAuthorities.size();
1767 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001768 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001769 out.startTag(null, "authority");
1770 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001771 out.attribute(null, "account", authority.account.name);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001772 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001773 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001774 out.attribute(null, "authority", authority.authority);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001775 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Fred Quintana5e787c42009-08-16 23:13:53 -07001776 if (authority.syncable < 0) {
1777 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001778 } else {
1779 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001780 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001781 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1782 out.startTag(null, "periodicSync");
1783 out.attribute(null, "period", Long.toString(periodicSync.second));
1784 final Bundle extras = periodicSync.first;
1785 for (String key : extras.keySet()) {
1786 out.startTag(null, "extra");
1787 out.attribute(null, "name", key);
1788 final Object value = extras.get(key);
1789 if (value instanceof Long) {
1790 out.attribute(null, "type", "long");
1791 out.attribute(null, "value1", value.toString());
1792 } else if (value instanceof Integer) {
1793 out.attribute(null, "type", "integer");
1794 out.attribute(null, "value1", value.toString());
1795 } else if (value instanceof Boolean) {
1796 out.attribute(null, "type", "boolean");
1797 out.attribute(null, "value1", value.toString());
1798 } else if (value instanceof Float) {
1799 out.attribute(null, "type", "float");
1800 out.attribute(null, "value1", value.toString());
1801 } else if (value instanceof Double) {
1802 out.attribute(null, "type", "double");
1803 out.attribute(null, "value1", value.toString());
1804 } else if (value instanceof String) {
1805 out.attribute(null, "type", "string");
1806 out.attribute(null, "value1", value.toString());
1807 } else if (value instanceof Account) {
1808 out.attribute(null, "type", "account");
1809 out.attribute(null, "value1", ((Account)value).name);
1810 out.attribute(null, "value2", ((Account)value).type);
1811 }
1812 out.endTag(null, "extra");
1813 }
1814 out.endTag(null, "periodicSync");
1815 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001816 out.endTag(null, "authority");
1817 }
Costin Manolache360e4542009-09-04 13:36:04 -07001818
Dianne Hackborn231cc602009-04-27 17:10:36 -07001819 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001820
Dianne Hackborn231cc602009-04-27 17:10:36 -07001821 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001822
Dianne Hackborn231cc602009-04-27 17:10:36 -07001823 mAccountInfoFile.finishWrite(fos);
1824 } catch (java.io.IOException e1) {
1825 Log.w(TAG, "Error writing accounts", e1);
1826 if (fos != null) {
1827 mAccountInfoFile.failWrite(fos);
1828 }
1829 }
1830 }
Costin Manolache360e4542009-09-04 13:36:04 -07001831
Dianne Hackborn231cc602009-04-27 17:10:36 -07001832 static int getIntColumn(Cursor c, String name) {
1833 return c.getInt(c.getColumnIndex(name));
1834 }
Costin Manolache360e4542009-09-04 13:36:04 -07001835
Dianne Hackborn231cc602009-04-27 17:10:36 -07001836 static long getLongColumn(Cursor c, String name) {
1837 return c.getLong(c.getColumnIndex(name));
1838 }
Costin Manolache360e4542009-09-04 13:36:04 -07001839
Dianne Hackborn231cc602009-04-27 17:10:36 -07001840 /**
1841 * Load sync engine state from the old syncmanager database, and then
1842 * erase it. Note that we don't deal with pending operations, active
1843 * sync, or history.
1844 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001845 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001846 // Look for old database to initialize from.
1847 File file = mContext.getDatabasePath("syncmanager.db");
1848 if (!file.exists()) {
1849 return;
1850 }
1851 String path = file.getPath();
1852 SQLiteDatabase db = null;
1853 try {
1854 db = SQLiteDatabase.openDatabase(path, null,
1855 SQLiteDatabase.OPEN_READONLY);
1856 } catch (SQLiteException e) {
1857 }
Costin Manolache360e4542009-09-04 13:36:04 -07001858
Dianne Hackborn231cc602009-04-27 17:10:36 -07001859 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001860 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001861
Dianne Hackborn231cc602009-04-27 17:10:36 -07001862 // Copy in all of the status information, as well as accounts.
1863 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1864 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1865 qb.setTables("stats, status");
1866 HashMap<String,String> map = new HashMap<String,String>();
1867 map.put("_id", "status._id as _id");
1868 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001869 if (hasType) {
1870 map.put("account_type", "stats.account_type as account_type");
1871 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001872 map.put("authority", "stats.authority as authority");
1873 map.put("totalElapsedTime", "totalElapsedTime");
1874 map.put("numSyncs", "numSyncs");
1875 map.put("numSourceLocal", "numSourceLocal");
1876 map.put("numSourcePoll", "numSourcePoll");
1877 map.put("numSourceServer", "numSourceServer");
1878 map.put("numSourceUser", "numSourceUser");
1879 map.put("lastSuccessSource", "lastSuccessSource");
1880 map.put("lastSuccessTime", "lastSuccessTime");
1881 map.put("lastFailureSource", "lastFailureSource");
1882 map.put("lastFailureTime", "lastFailureTime");
1883 map.put("lastFailureMesg", "lastFailureMesg");
1884 map.put("pending", "pending");
1885 qb.setProjectionMap(map);
1886 qb.appendWhere("stats._id = status.stats_id");
1887 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001889 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001890 String accountType = hasType
1891 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001892 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001893 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001895 String authorityName = c.getString(c.getColumnIndex("authority"));
1896 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001897 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07001898 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001899 if (authority != null) {
1900 int i = mSyncStatus.size();
1901 boolean found = false;
1902 SyncStatusInfo st = null;
1903 while (i > 0) {
1904 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001905 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001906 if (st.authorityId == authority.ident) {
1907 found = true;
1908 break;
1909 }
1910 }
1911 if (!found) {
1912 st = new SyncStatusInfo(authority.ident);
1913 mSyncStatus.put(authority.ident, st);
1914 }
1915 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1916 st.numSyncs = getIntColumn(c, "numSyncs");
1917 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1918 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1919 st.numSourceServer = getIntColumn(c, "numSourceServer");
1920 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001921 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001922 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1923 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1924 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1925 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1926 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1927 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
Costin Manolache360e4542009-09-04 13:36:04 -07001930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001932
Dianne Hackborn231cc602009-04-27 17:10:36 -07001933 // Retrieve the settings.
1934 qb = new SQLiteQueryBuilder();
1935 qb.setTables("settings");
1936 c = qb.query(db, null, null, null, null, null, null);
1937 while (c.moveToNext()) {
1938 String name = c.getString(c.getColumnIndex("name"));
1939 String value = c.getString(c.getColumnIndex("value"));
1940 if (name == null) continue;
1941 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001942 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001943 } else if (name.startsWith("sync_provider_")) {
1944 String provider = name.substring("sync_provider_".length(),
1945 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001946 int i = mAuthorities.size();
1947 while (i > 0) {
1948 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001949 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001950 if (authority.authority.equals(provider)) {
1951 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001952 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001953 }
1954 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
Costin Manolache360e4542009-09-04 13:36:04 -07001957
Dianne Hackborn231cc602009-04-27 17:10:36 -07001958 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001959
Dianne Hackborn231cc602009-04-27 17:10:36 -07001960 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001961
Dianne Hackborn231cc602009-04-27 17:10:36 -07001962 (new File(path)).delete();
1963 }
1964 }
Costin Manolache360e4542009-09-04 13:36:04 -07001965
Dianne Hackborn231cc602009-04-27 17:10:36 -07001966 public static final int STATUS_FILE_END = 0;
1967 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001968
Dianne Hackborn231cc602009-04-27 17:10:36 -07001969 /**
1970 * Read all sync status back in to the initial engine state.
1971 */
1972 private void readStatusLocked() {
1973 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1974 try {
1975 byte[] data = mStatusFile.readFully();
1976 Parcel in = Parcel.obtain();
1977 in.unmarshall(data, 0, data.length);
1978 in.setDataPosition(0);
1979 int token;
1980 while ((token=in.readInt()) != STATUS_FILE_END) {
1981 if (token == STATUS_FILE_ITEM) {
1982 SyncStatusInfo status = new SyncStatusInfo(in);
1983 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1984 status.pending = false;
1985 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
1986 + status.authorityId);
1987 mSyncStatus.put(status.authorityId, status);
1988 }
1989 } else {
1990 // Ooops.
1991 Log.w(TAG, "Unknown status token: " + token);
1992 break;
1993 }
1994 }
1995 } catch (java.io.IOException e) {
1996 Log.i(TAG, "No initial status");
1997 }
1998 }
Costin Manolache360e4542009-09-04 13:36:04 -07001999
Dianne Hackborn231cc602009-04-27 17:10:36 -07002000 /**
2001 * Write all sync status to the sync status file.
2002 */
2003 private void writeStatusLocked() {
2004 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002005
Dianne Hackborn231cc602009-04-27 17:10:36 -07002006 // The file is being written, so we don't need to have a scheduled
2007 // write until the next change.
2008 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002009
Dianne Hackborn231cc602009-04-27 17:10:36 -07002010 FileOutputStream fos = null;
2011 try {
2012 fos = mStatusFile.startWrite();
2013 Parcel out = Parcel.obtain();
2014 final int N = mSyncStatus.size();
2015 for (int i=0; i<N; i++) {
2016 SyncStatusInfo status = mSyncStatus.valueAt(i);
2017 out.writeInt(STATUS_FILE_ITEM);
2018 status.writeToParcel(out, 0);
2019 }
2020 out.writeInt(STATUS_FILE_END);
2021 fos.write(out.marshall());
2022 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002023
Dianne Hackborn231cc602009-04-27 17:10:36 -07002024 mStatusFile.finishWrite(fos);
2025 } catch (java.io.IOException e1) {
2026 Log.w(TAG, "Error writing status", e1);
2027 if (fos != null) {
2028 mStatusFile.failWrite(fos);
2029 }
2030 }
2031 }
Costin Manolache360e4542009-09-04 13:36:04 -07002032
Fred Quintana307da1a2010-01-21 14:24:20 -08002033 public static final int PENDING_OPERATION_VERSION = 2;
Costin Manolache360e4542009-09-04 13:36:04 -07002034
Dianne Hackborn231cc602009-04-27 17:10:36 -07002035 /**
2036 * Read all pending operations back in to the initial engine state.
2037 */
2038 private void readPendingOperationsLocked() {
2039 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
2040 try {
2041 byte[] data = mPendingFile.readFully();
2042 Parcel in = Parcel.obtain();
2043 in.unmarshall(data, 0, data.length);
2044 in.setDataPosition(0);
2045 final int SIZE = in.dataSize();
2046 while (in.dataPosition() < SIZE) {
2047 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08002048 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002049 Log.w(TAG, "Unknown pending operation version "
2050 + version + "; dropping all ops");
2051 break;
2052 }
2053 int authorityId = in.readInt();
2054 int syncSource = in.readInt();
2055 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08002056 boolean expedited;
2057 if (version == PENDING_OPERATION_VERSION) {
2058 expedited = in.readInt() != 0;
2059 } else {
2060 expedited = false;
2061 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002062 AuthorityInfo authority = mAuthorities.get(authorityId);
2063 if (authority != null) {
Fred Quintana5695c7b2010-12-06 15:07:52 -08002064 Bundle extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002065 if (flatExtras != null) {
2066 extras = unflattenBundle(flatExtras);
Fred Quintana5695c7b2010-12-06 15:07:52 -08002067 } else {
2068 // if we are unable to parse the extras for whatever reason convert this
2069 // to a regular sync by creating an empty extras
2070 extras = new Bundle();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002071 }
2072 PendingOperation op = new PendingOperation(
Amith Yamasani04e0d262012-02-14 11:50:53 -08002073 authority.account, authority.userId, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08002074 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002075 op.authorityId = authorityId;
2076 op.flatExtras = flatExtras;
2077 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
2078 + " auth=" + op.authority
2079 + " src=" + op.syncSource
Fred Quintana307da1a2010-01-21 14:24:20 -08002080 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07002081 + " extras=" + op.extras);
2082 mPendingOperations.add(op);
2083 }
2084 }
2085 } catch (java.io.IOException e) {
2086 Log.i(TAG, "No initial pending operations");
2087 }
2088 }
Costin Manolache360e4542009-09-04 13:36:04 -07002089
Dianne Hackborn231cc602009-04-27 17:10:36 -07002090 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
2091 out.writeInt(PENDING_OPERATION_VERSION);
2092 out.writeInt(op.authorityId);
2093 out.writeInt(op.syncSource);
2094 if (op.flatExtras == null && op.extras != null) {
2095 op.flatExtras = flattenBundle(op.extras);
2096 }
2097 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08002098 out.writeInt(op.expedited ? 1 : 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002099 }
Costin Manolache360e4542009-09-04 13:36:04 -07002100
Dianne Hackborn231cc602009-04-27 17:10:36 -07002101 /**
2102 * Write all currently pending ops to the pending ops file.
2103 */
2104 private void writePendingOperationsLocked() {
2105 final int N = mPendingOperations.size();
2106 FileOutputStream fos = null;
2107 try {
2108 if (N == 0) {
2109 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2110 mPendingFile.truncate();
2111 return;
2112 }
Costin Manolache360e4542009-09-04 13:36:04 -07002113
Dianne Hackborn231cc602009-04-27 17:10:36 -07002114 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2115 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07002116
Dianne Hackborn231cc602009-04-27 17:10:36 -07002117 Parcel out = Parcel.obtain();
2118 for (int i=0; i<N; i++) {
2119 PendingOperation op = mPendingOperations.get(i);
2120 writePendingOperationLocked(op, out);
2121 }
2122 fos.write(out.marshall());
2123 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002124
Dianne Hackborn231cc602009-04-27 17:10:36 -07002125 mPendingFile.finishWrite(fos);
2126 } catch (java.io.IOException e1) {
2127 Log.w(TAG, "Error writing pending operations", e1);
2128 if (fos != null) {
2129 mPendingFile.failWrite(fos);
2130 }
2131 }
2132 }
Costin Manolache360e4542009-09-04 13:36:04 -07002133
Dianne Hackborn231cc602009-04-27 17:10:36 -07002134 /**
2135 * Append the given operation to the pending ops file; if unable to,
2136 * write all pending ops.
2137 */
2138 private void appendPendingOperationLocked(PendingOperation op) {
2139 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2140 FileOutputStream fos = null;
2141 try {
2142 fos = mPendingFile.openAppend();
2143 } catch (java.io.IOException e) {
2144 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2145 writePendingOperationsLocked();
2146 return;
2147 }
Costin Manolache360e4542009-09-04 13:36:04 -07002148
Dianne Hackborn231cc602009-04-27 17:10:36 -07002149 try {
2150 Parcel out = Parcel.obtain();
2151 writePendingOperationLocked(op, out);
2152 fos.write(out.marshall());
2153 out.recycle();
2154 } catch (java.io.IOException e1) {
2155 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002157 try {
2158 fos.close();
2159 } catch (java.io.IOException e2) {
2160 }
2161 }
2162 }
Costin Manolache360e4542009-09-04 13:36:04 -07002163
Dianne Hackborn231cc602009-04-27 17:10:36 -07002164 static private byte[] flattenBundle(Bundle bundle) {
2165 byte[] flatData = null;
2166 Parcel parcel = Parcel.obtain();
2167 try {
2168 bundle.writeToParcel(parcel, 0);
2169 flatData = parcel.marshall();
2170 } finally {
2171 parcel.recycle();
2172 }
2173 return flatData;
2174 }
Costin Manolache360e4542009-09-04 13:36:04 -07002175
Dianne Hackborn231cc602009-04-27 17:10:36 -07002176 static private Bundle unflattenBundle(byte[] flatData) {
2177 Bundle bundle;
2178 Parcel parcel = Parcel.obtain();
2179 try {
2180 parcel.unmarshall(flatData, 0, flatData.length);
2181 parcel.setDataPosition(0);
2182 bundle = parcel.readBundle();
2183 } catch (RuntimeException e) {
2184 // A RuntimeException is thrown if we were unable to parse the parcel.
2185 // Create an empty parcel in this case.
2186 bundle = new Bundle();
2187 } finally {
2188 parcel.recycle();
2189 }
2190 return bundle;
2191 }
Costin Manolache360e4542009-09-04 13:36:04 -07002192
Amith Yamasani04e0d262012-02-14 11:50:53 -08002193 private void requestSync(Account account, int userId, String authority, Bundle extras) {
2194 // If this is happening in the system process, then call the syncrequest listener
2195 // to make a request back to the SyncManager directly.
2196 // If this is probably a test instance, then call back through the ContentResolver
2197 // which will know which userId to apply based on the Binder id.
2198 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2199 && mSyncRequestListener != null) {
2200 mSyncRequestListener.onSyncRequest(account, userId, authority, extras);
2201 } else {
2202 ContentResolver.requestSync(account, authority, extras);
2203 }
2204 }
2205
Dianne Hackborn231cc602009-04-27 17:10:36 -07002206 public static final int STATISTICS_FILE_END = 0;
2207 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2208 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002209
Dianne Hackborn231cc602009-04-27 17:10:36 -07002210 /**
2211 * Read all sync statistics back in to the initial engine state.
2212 */
2213 private void readStatisticsLocked() {
2214 try {
2215 byte[] data = mStatisticsFile.readFully();
2216 Parcel in = Parcel.obtain();
2217 in.unmarshall(data, 0, data.length);
2218 in.setDataPosition(0);
2219 int token;
2220 int index = 0;
2221 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2222 if (token == STATISTICS_FILE_ITEM
2223 || token == STATISTICS_FILE_ITEM_OLD) {
2224 int day = in.readInt();
2225 if (token == STATISTICS_FILE_ITEM_OLD) {
2226 day = day - 2009 + 14245; // Magic!
2227 }
2228 DayStats ds = new DayStats(day);
2229 ds.successCount = in.readInt();
2230 ds.successTime = in.readLong();
2231 ds.failureCount = in.readInt();
2232 ds.failureTime = in.readLong();
2233 if (index < mDayStats.length) {
2234 mDayStats[index] = ds;
2235 index++;
2236 }
2237 } else {
2238 // Ooops.
2239 Log.w(TAG, "Unknown stats token: " + token);
2240 break;
2241 }
2242 }
2243 } catch (java.io.IOException e) {
2244 Log.i(TAG, "No initial statistics");
2245 }
2246 }
Costin Manolache360e4542009-09-04 13:36:04 -07002247
Dianne Hackborn231cc602009-04-27 17:10:36 -07002248 /**
2249 * Write all sync statistics to the sync status file.
2250 */
2251 private void writeStatisticsLocked() {
2252 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002253
Dianne Hackborn231cc602009-04-27 17:10:36 -07002254 // The file is being written, so we don't need to have a scheduled
2255 // write until the next change.
2256 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002257
Dianne Hackborn231cc602009-04-27 17:10:36 -07002258 FileOutputStream fos = null;
2259 try {
2260 fos = mStatisticsFile.startWrite();
2261 Parcel out = Parcel.obtain();
2262 final int N = mDayStats.length;
2263 for (int i=0; i<N; i++) {
2264 DayStats ds = mDayStats[i];
2265 if (ds == null) {
2266 break;
2267 }
2268 out.writeInt(STATISTICS_FILE_ITEM);
2269 out.writeInt(ds.day);
2270 out.writeInt(ds.successCount);
2271 out.writeLong(ds.successTime);
2272 out.writeInt(ds.failureCount);
2273 out.writeLong(ds.failureTime);
2274 }
2275 out.writeInt(STATISTICS_FILE_END);
2276 fos.write(out.marshall());
2277 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002278
Dianne Hackborn231cc602009-04-27 17:10:36 -07002279 mStatisticsFile.finishWrite(fos);
2280 } catch (java.io.IOException e1) {
2281 Log.w(TAG, "Error writing stats", e1);
2282 if (fos != null) {
2283 mStatisticsFile.failWrite(fos);
2284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 }
2286 }
2287}