blob: 5b8d26ff77cd8c628dd78c97c1f04bca2be66889 [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
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.content.ContentResolver;
22import android.content.Context;
23import android.content.ISyncStatusObserver;
24import android.content.PeriodicSync;
25import android.content.SyncInfo;
26import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070029import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070031import android.os.Bundle;
32import android.os.Environment;
33import android.os.Handler;
34import android.os.Message;
35import android.os.Parcel;
36import android.os.RemoteCallbackList;
37import android.os.RemoteException;
Dianne Hackborn39606a02012-07-31 17:54:35 -070038import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080040import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070041import android.util.SparseArray;
42import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080043
44import com.android.internal.annotations.VisibleForTesting;
45import com.android.internal.util.ArrayUtils;
46import com.android.internal.util.FastXmlSerializer;
47
48import org.xmlpull.v1.XmlPullParser;
49import org.xmlpull.v1.XmlPullParserException;
50import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
Dianne Hackborn231cc602009-04-27 17:10:36 -070052import java.io.File;
53import java.io.FileInputStream;
54import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070056import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070058import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080059import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070060import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060061import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062
63/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070064 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070066 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 * @hide
68 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070069public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 private static final String TAG = "SyncManager";
Dianne Hackborn40e9f292012-11-27 19:12:23 -080072 private static final boolean DEBUG = false;
Dianne Hackborn231cc602009-04-27 17:10:36 -070073 private static final boolean DEBUG_FILE = false;
Costin Manolache360e4542009-09-04 13:36:04 -070074
Amith Yamasani04e0d262012-02-14 11:50:53 -080075 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
76 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070077 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080078 private static final String XML_ATTR_ENABLED = "enabled";
79 private static final String XML_ATTR_USER = "user";
80 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
81
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080082 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
83
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080084 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070085 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
Dianne Hackborn231cc602009-04-27 17:10:36 -070087 /** Enum value for a sync start event. */
88 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
Dianne Hackborn231cc602009-04-27 17:10:36 -070090 /** Enum value for a sync stop event. */
91 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Dianne Hackborn231cc602009-04-27 17:10:36 -070093 // TODO: i18n -- grab these out of resources.
94 /** String names for the sync event types. */
95 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
Dianne Hackborn231cc602009-04-27 17:10:36 -070097 /** Enum value for a server-initiated sync. */
98 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 /** Enum value for a local-initiated sync. */
101 public static final int SOURCE_LOCAL = 1;
102 /**
103 * Enum value for a poll-based sync (e.g., upon connection to
104 * network)
105 */
106 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 /** Enum value for a user-initiated sync. */
109 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800111 /** Enum value for a periodic sync. */
112 public static final int SOURCE_PERIODIC = 4;
113
Fred Quintana307da1a2010-01-21 14:24:20 -0800114 public static final long NOT_IN_BACKOFF_MODE = -1;
115
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 // TODO: i18n -- grab these out of resources.
117 /** String names for the sync source types. */
118 public static final String[] SOURCES = { "SERVER",
119 "LOCAL",
120 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800121 "USER",
122 "PERIODIC" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
Dianne Hackborn231cc602009-04-27 17:10:36 -0700124 // The MESG column will contain one of these or one of the Error types.
125 public static final String MESG_SUCCESS = "success";
126 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700128 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700129
Dianne Hackborn231cc602009-04-27 17:10:36 -0700130 private static final int MSG_WRITE_STATUS = 1;
131 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700132
Dianne Hackborn231cc602009-04-27 17:10:36 -0700133 private static final int MSG_WRITE_STATISTICS = 2;
134 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700135
136 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700137
Fred Quintanac2e46912010-03-15 16:10:44 -0700138 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700139 private static final int ACCOUNTS_VERSION = 2;
140
141 private static HashMap<String, String> sAuthorityRenames;
142
143 static {
144 sAuthorityRenames = new HashMap<String, String>();
145 sAuthorityRenames.put("contacts", "com.android.contacts");
146 sAuthorityRenames.put("calendar", "com.android.calendar");
147 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700148
Dianne Hackborn231cc602009-04-27 17:10:36 -0700149 public static class PendingOperation {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700150 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800151 final int userId;
Alon Albert57286f92012-10-09 14:21:38 -0700152 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700153 final int syncSource;
154 final String authority;
155 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800156 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700157
Dianne Hackborn231cc602009-04-27 17:10:36 -0700158 int authorityId;
159 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700160
Alon Albert57286f92012-10-09 14:21:38 -0700161 PendingOperation(Account account, int userId, int reason,int source,
Fred Quintana307da1a2010-01-21 14:24:20 -0800162 String authority, Bundle extras, boolean expedited) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700163 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800164 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700165 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700166 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700167 this.authority = authority;
168 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800169 this.expedited = expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700170 this.authorityId = -1;
171 }
172
173 PendingOperation(PendingOperation other) {
174 this.account = other.account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800175 this.userId = other.userId;
Alon Albert57286f92012-10-09 14:21:38 -0700176 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700177 this.syncSource = other.syncSource;
178 this.authority = other.authority;
179 this.extras = other.extras;
180 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800181 this.expedited = other.expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 }
Costin Manolache360e4542009-09-04 13:36:04 -0700184
Dianne Hackborn231cc602009-04-27 17:10:36 -0700185 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800186 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700187 final HashMap<String, AuthorityInfo> authorities =
188 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700189
Amith Yamasani04e0d262012-02-14 11:50:53 -0800190 AccountInfo(AccountAndUser accountAndUser) {
191 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700192 }
193 }
Costin Manolache360e4542009-09-04 13:36:04 -0700194
Dianne Hackborn231cc602009-04-27 17:10:36 -0700195 public static class AuthorityInfo {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700196 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800197 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700198 final String authority;
199 final int ident;
200 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700201 int syncable;
Fred Quintana307da1a2010-01-21 14:24:20 -0800202 long backoffTime;
203 long backoffDelay;
204 long delayUntil;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800205 final ArrayList<Pair<Bundle, Long>> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700206
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700207 /**
208 * Copy constructor for making deep-ish copies. Only the bundles stored
209 * in periodic syncs can make unexpected changes.
210 *
211 * @param toCopy AuthorityInfo to be copied.
212 */
213 AuthorityInfo(AuthorityInfo toCopy) {
214 account = toCopy.account;
215 userId = toCopy.userId;
216 authority = toCopy.authority;
217 ident = toCopy.ident;
218 enabled = toCopy.enabled;
219 syncable = toCopy.syncable;
220 backoffTime = toCopy.backoffTime;
221 backoffDelay = toCopy.backoffDelay;
222 delayUntil = toCopy.delayUntil;
223 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
224 for (Pair<Bundle, Long> sync : toCopy.periodicSyncs) {
225 // Still not a perfect copy, because we are just copying the mappings.
226 periodicSyncs.add(Pair.create(new Bundle(sync.first), sync.second));
227 }
228 }
229
Amith Yamasani04e0d262012-02-14 11:50:53 -0800230 AuthorityInfo(Account account, int userId, String authority, int ident) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700231 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800232 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700233 this.authority = authority;
234 this.ident = ident;
Joe Onorato8294fad2009-07-15 16:08:44 -0700235 enabled = SYNC_ENABLED_DEFAULT;
Fred Quintana4a6679b2009-08-17 13:05:39 -0700236 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800237 backoffTime = -1; // if < 0 then we aren't in backoff mode
238 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800239 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
240 periodicSyncs.add(Pair.create(new Bundle(), DEFAULT_POLL_FREQUENCY_SECONDS));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700241 }
242 }
Costin Manolache360e4542009-09-04 13:36:04 -0700243
Dianne Hackborn231cc602009-04-27 17:10:36 -0700244 public static class SyncHistoryItem {
245 int authorityId;
246 int historyId;
247 long eventTime;
248 long elapsedTime;
249 int source;
250 int event;
251 long upstreamActivity;
252 long downstreamActivity;
253 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700254 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700255 Bundle extras;
256 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700257 }
Costin Manolache360e4542009-09-04 13:36:04 -0700258
Dianne Hackborn231cc602009-04-27 17:10:36 -0700259 public static class DayStats {
260 public final int day;
261 public int successCount;
262 public long successTime;
263 public int failureCount;
264 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700265
Dianne Hackborn231cc602009-04-27 17:10:36 -0700266 public DayStats(int day) {
267 this.day = day;
268 }
269 }
Costin Manolache360e4542009-09-04 13:36:04 -0700270
Amith Yamasani04e0d262012-02-14 11:50:53 -0800271 interface OnSyncRequestListener {
272 /**
273 * Called when a sync is needed on an account(s) due to some change in state.
274 * @param account
275 * @param userId
Alon Albert57286f92012-10-09 14:21:38 -0700276 * @param reason
Amith Yamasani04e0d262012-02-14 11:50:53 -0800277 * @param authority
278 * @param extras
279 */
Alon Albert57286f92012-10-09 14:21:38 -0700280 public void onSyncRequest(Account account, int userId, int reason, String authority,
281 Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800282 }
283
Dianne Hackborn231cc602009-04-27 17:10:36 -0700284 // Primary list of all syncable authorities. Also our global lock.
285 private final SparseArray<AuthorityInfo> mAuthorities =
286 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700287
Amith Yamasani04e0d262012-02-14 11:50:53 -0800288 private final HashMap<AccountAndUser, AccountInfo> mAccounts
289 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290
Dianne Hackborn231cc602009-04-27 17:10:36 -0700291 private final ArrayList<PendingOperation> mPendingOperations =
292 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700293
Amith Yamasani04e0d262012-02-14 11:50:53 -0800294 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
295 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700296
Dianne Hackborn231cc602009-04-27 17:10:36 -0700297 private final SparseArray<SyncStatusInfo> mSyncStatus =
298 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700299
Dianne Hackborn231cc602009-04-27 17:10:36 -0700300 private final ArrayList<SyncHistoryItem> mSyncHistory =
301 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700302
Dianne Hackborn231cc602009-04-27 17:10:36 -0700303 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
304 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700305
Fred Quintana77c560f2010-03-29 22:20:26 -0700306 private int mNextAuthorityId = 0;
307
Dianne Hackborn231cc602009-04-27 17:10:36 -0700308 // We keep 4 weeks of stats.
309 private final DayStats[] mDayStats = new DayStats[7*4];
310 private final Calendar mCal;
311 private int mYear;
312 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700313
Dianne Hackborn231cc602009-04-27 17:10:36 -0700314 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800315
Dianne Hackborn231cc602009-04-27 17:10:36 -0700316 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700317
Ashish Sharma69d95de2012-04-11 17:27:24 -0700318 private int mSyncRandomOffset;
319
Dianne Hackborn231cc602009-04-27 17:10:36 -0700320 /**
321 * This file contains the core engine state: all accounts and the
322 * settings for them. It must never be lost, and should be changed
323 * infrequently, so it is stored as an XML file.
324 */
325 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700326
Dianne Hackborn231cc602009-04-27 17:10:36 -0700327 /**
328 * This file contains the current sync status. We would like to retain
329 * it across boots, but its loss is not the end of the world, so we store
330 * this information as binary data.
331 */
332 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700333
Dianne Hackborn231cc602009-04-27 17:10:36 -0700334 /**
335 * This file contains sync statistics. This is purely debugging information
336 * so is written infrequently and can be thrown away at any time.
337 */
338 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700339
Dianne Hackborn231cc602009-04-27 17:10:36 -0700340 /**
341 * This file contains the pending sync operations. It is a binary file,
342 * which must be updated every time an operation is added or removed,
343 * so we have special handling of it.
344 */
345 private final AtomicFile mPendingFile;
346 private static final int PENDING_FINISH_TO_WRITE = 4;
347 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700348
Dianne Hackborn231cc602009-04-27 17:10:36 -0700349 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800350 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800351 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800352
353 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700354
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800355 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700358
Dianne Hackborn231cc602009-04-27 17:10:36 -0700359 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700360
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800361 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
362 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
363
Dianne Hackborn231cc602009-04-27 17:10:36 -0700364 File systemDir = new File(dataDir, "system");
365 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800366 syncDir.mkdirs();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700367 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
368 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
369 mPendingFile = new AtomicFile(new File(syncDir, "pending.bin"));
370 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700371
Dianne Hackborn231cc602009-04-27 17:10:36 -0700372 readAccountInfoLocked();
373 readStatusLocked();
374 readPendingOperationsLocked();
375 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700376 readAndDeleteLegacyAccountInfoLocked();
377 writeAccountInfoLocked();
378 writeStatusLocked();
379 writePendingOperationsLocked();
380 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 }
382
383 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800384 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 }
386
387 public static void init(Context context) {
388 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800389 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800391 // This call will return the correct directory whether Encrypted File Systems is
392 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600393 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800394 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 }
396
397 public static SyncStorageEngine getSingleton() {
398 if (sSyncStorageEngine == null) {
399 throw new IllegalStateException("not initialized");
400 }
401 return sSyncStorageEngine;
402 }
403
Amith Yamasani04e0d262012-02-14 11:50:53 -0800404 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
405 if (mSyncRequestListener == null) {
406 mSyncRequestListener = listener;
407 }
408 }
409
Dianne Hackborn231cc602009-04-27 17:10:36 -0700410 @Override public void handleMessage(Message msg) {
411 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700412 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700413 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700414 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700415 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700416 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700417 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 }
419 }
420 }
Costin Manolache360e4542009-09-04 13:36:04 -0700421
Ashish Sharma69d95de2012-04-11 17:27:24 -0700422 public int getSyncRandomOffset() {
423 return mSyncRandomOffset;
424 }
425
Dianne Hackborn231cc602009-04-27 17:10:36 -0700426 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
427 synchronized (mAuthorities) {
428 mChangeListeners.register(callback, mask);
429 }
430 }
Costin Manolache360e4542009-09-04 13:36:04 -0700431
Dianne Hackborn231cc602009-04-27 17:10:36 -0700432 public void removeStatusChangeListener(ISyncStatusObserver callback) {
433 synchronized (mAuthorities) {
434 mChangeListeners.unregister(callback);
435 }
436 }
Costin Manolache360e4542009-09-04 13:36:04 -0700437
Dianne Hackborn231cc602009-04-27 17:10:36 -0700438 private void reportChange(int which) {
439 ArrayList<ISyncStatusObserver> reports = null;
440 synchronized (mAuthorities) {
441 int i = mChangeListeners.beginBroadcast();
442 while (i > 0) {
443 i--;
444 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
445 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 continue;
447 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700448 if (reports == null) {
449 reports = new ArrayList<ISyncStatusObserver>(i);
450 }
451 reports.add(mChangeListeners.getBroadcastItem(i));
452 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700453 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700454 }
Costin Manolache360e4542009-09-04 13:36:04 -0700455
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800456 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700457 Log.v(TAG, "reportChange " + which + " to: " + reports);
458 }
Costin Manolache360e4542009-09-04 13:36:04 -0700459
Dianne Hackborn231cc602009-04-27 17:10:36 -0700460 if (reports != null) {
461 int i = reports.size();
462 while (i > 0) {
463 i--;
464 try {
465 reports.get(i).onStatusChanged(which);
466 } catch (RemoteException e) {
467 // The remote callback list will take care of this for us.
468 }
469 }
470 }
471 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700472
Amith Yamasani04e0d262012-02-14 11:50:53 -0800473 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700474 synchronized (mAuthorities) {
475 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800476 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700477 "getSyncAutomatically");
478 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700479 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700480
Dianne Hackborn231cc602009-04-27 17:10:36 -0700481 int i = mAuthorities.size();
482 while (i > 0) {
483 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700484 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700485 if (authority.authority.equals(providerName)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800486 && authority.userId == userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700487 && authority.enabled) {
488 return true;
489 }
490 }
491 return false;
492 }
493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494
Amith Yamasani04e0d262012-02-14 11:50:53 -0800495 public void setSyncAutomatically(Account account, int userId, String providerName,
496 boolean sync) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800497 if (DEBUG) {
498 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
499 + ", user " + userId + " -> " + sync);
500 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700501 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800502 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
503 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700504 if (authority.enabled == sync) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800505 if (DEBUG) {
506 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
507 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700508 return;
509 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700510 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700511 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700513
Fred Quintana77c560f2010-03-29 22:20:26 -0700514 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700515 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
516 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700517 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700518 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 }
520
Amith Yamasani04e0d262012-02-14 11:50:53 -0800521 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700522 synchronized (mAuthorities) {
523 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800524 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintana5e787c42009-08-16 23:13:53 -0700525 "getIsSyncable");
526 if (authority == null) {
527 return -1;
528 }
529 return authority.syncable;
530 }
531
532 int i = mAuthorities.size();
533 while (i > 0) {
534 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700535 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700536 if (authority.authority.equals(providerName)) {
537 return authority.syncable;
538 }
539 }
540 return -1;
541 }
542 }
543
Amith Yamasani04e0d262012-02-14 11:50:53 -0800544 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700545 if (syncable > 1) {
546 syncable = 1;
547 } else if (syncable < -1) {
548 syncable = -1;
549 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800550 if (DEBUG) {
551 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName
552 + ", user " + userId + " -> " + syncable);
553 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700554 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800555 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
556 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700557 if (authority.syncable == syncable) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800558 if (DEBUG) {
559 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
560 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700561 return;
562 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700563 authority.syncable = syncable;
564 writeAccountInfoLocked();
565 }
566
Fred Quintana77c560f2010-03-29 22:20:26 -0700567 if (syncable > 0) {
Alon Albert57286f92012-10-09 14:21:38 -0700568 requestSync(account, userId, SyncOperation.REASON_IS_SYNCABLE, providerName,
569 new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700570 }
571 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
572 }
573
Amith Yamasani04e0d262012-02-14 11:50:53 -0800574 public Pair<Long, Long> getBackoff(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800575 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800576 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
577 "getBackoff");
Fred Quintana307da1a2010-01-21 14:24:20 -0800578 if (authority == null || authority.backoffTime < 0) {
579 return null;
580 }
581 return Pair.create(authority.backoffTime, authority.backoffDelay);
582 }
583 }
584
Amith Yamasani04e0d262012-02-14 11:50:53 -0800585 public void setBackoff(Account account, int userId, String providerName,
Fred Quintana307da1a2010-01-21 14:24:20 -0800586 long nextSyncTime, long nextDelay) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800587 if (DEBUG) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800588 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800589 + ", user " + userId
Fred Quintana307da1a2010-01-21 14:24:20 -0800590 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
591 }
592 boolean changed = false;
593 synchronized (mAuthorities) {
594 if (account == null || providerName == null) {
595 for (AccountInfo accountInfo : mAccounts.values()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800596 if (account != null && !account.equals(accountInfo.accountAndUser.account)
597 && userId != accountInfo.accountAndUser.userId) {
598 continue;
599 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800600 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
601 if (providerName != null && !providerName.equals(authorityInfo.authority)) {
602 continue;
603 }
604 if (authorityInfo.backoffTime != nextSyncTime
605 || authorityInfo.backoffDelay != nextDelay) {
606 authorityInfo.backoffTime = nextSyncTime;
607 authorityInfo.backoffDelay = nextDelay;
608 changed = true;
609 }
610 }
611 }
612 } else {
613 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800614 getOrCreateAuthorityLocked(account, userId, providerName, -1 /* ident */,
615 true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800616 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
617 return;
618 }
619 authority.backoffTime = nextSyncTime;
620 authority.backoffDelay = nextDelay;
621 changed = true;
622 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800623 }
624
625 if (changed) {
626 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
627 }
628 }
629
Alon Alberted1d2532011-02-15 14:02:14 -0800630 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800631 boolean changed = false;
632 synchronized (mAuthorities) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700633 synchronized (syncQueue) {
634 for (AccountInfo accountInfo : mAccounts.values()) {
635 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
636 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
637 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800638 if (DEBUG) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700639 Log.v(TAG, "clearAllBackoffs:"
640 + " authority:" + authorityInfo.authority
641 + " account:" + accountInfo.accountAndUser.account.name
642 + " user:" + accountInfo.accountAndUser.userId
643 + " backoffTime was: " + authorityInfo.backoffTime
644 + " backoffDelay was: " + authorityInfo.backoffDelay);
645 }
646 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
647 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
648 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
649 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
650 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800651 }
Alon Albert744e310f2010-12-14 11:37:20 -0800652 }
653 }
654 }
655 }
656
657 if (changed) {
658 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
659 }
660 }
661
Amith Yamasani04e0d262012-02-14 11:50:53 -0800662 public void setDelayUntilTime(Account account, int userId, String providerName,
663 long delayUntil) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800664 if (DEBUG) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800665 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800666 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800667 }
668 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800669 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800670 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800671 if (authority.delayUntil == delayUntil) {
672 return;
673 }
674 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800675 }
676
677 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
678 }
679
Amith Yamasani04e0d262012-02-14 11:50:53 -0800680 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800681 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800682 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
683 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800684 if (authority == null) {
685 return 0;
686 }
687 return authority.delayUntil;
688 }
689 }
690
Amith Yamasani04e0d262012-02-14 11:50:53 -0800691 private void updateOrRemovePeriodicSync(Account account, int userId, String providerName,
692 Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800693 long period, boolean add) {
694 if (period <= 0) {
695 period = 0;
696 }
697 if (extras == null) {
698 extras = new Bundle();
699 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800700 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800701 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", user " + userId
702 + ", provider " + providerName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800703 + " -> period " + period + ", extras " + extras);
704 }
705 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700706 try {
707 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800708 getOrCreateAuthorityLocked(account, userId, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700709 if (add) {
710 // add this periodic sync if one with the same extras doesn't already
711 // exist in the periodicSyncs array
712 boolean alreadyPresent = false;
713 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
714 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
715 final Bundle existingExtras = syncInfo.first;
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800716 if (PeriodicSync.syncExtrasEquals(existingExtras, extras)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700717 if (syncInfo.second == period) {
718 return;
719 }
720 authority.periodicSyncs.set(i, Pair.create(extras, period));
721 alreadyPresent = true;
722 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800723 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700724 }
725 // if we added an entry to the periodicSyncs array also add an entry to
726 // the periodic syncs status to correspond to it
727 if (!alreadyPresent) {
728 authority.periodicSyncs.add(Pair.create(extras, period));
729 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
730 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
731 }
732 } else {
733 // remove any periodic syncs that match the authority and extras
734 SyncStatusInfo status = mSyncStatus.get(authority.ident);
735 boolean changed = false;
736 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
737 int i = 0;
738 while (iterator.hasNext()) {
739 Pair<Bundle, Long> syncInfo = iterator.next();
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800740 if (PeriodicSync.syncExtrasEquals(syncInfo.first, extras)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700741 iterator.remove();
742 changed = true;
743 // if we removed an entry from the periodicSyncs array also
744 // remove the corresponding entry from the status
745 if (status != null) {
746 status.removePeriodicSyncTime(i);
747 }
748 } else {
749 i++;
750 }
751 }
752 if (!changed) {
753 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800754 }
755 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700756 } finally {
757 writeAccountInfoLocked();
758 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800759 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800760 }
761
762 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
763 }
764
Amith Yamasani04e0d262012-02-14 11:50:53 -0800765 public void addPeriodicSync(Account account, int userId, String providerName, Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800766 long pollFrequency) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800767 updateOrRemovePeriodicSync(account, userId, providerName, extras, pollFrequency,
768 true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800769 }
770
Amith Yamasani04e0d262012-02-14 11:50:53 -0800771 public void removePeriodicSync(Account account, int userId, String providerName,
772 Bundle extras) {
773 updateOrRemovePeriodicSync(account, userId, providerName, extras, 0 /* period, ignored */,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800774 false /* remove */);
775 }
776
Amith Yamasani04e0d262012-02-14 11:50:53 -0800777 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800778 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
779 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800780 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
781 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800782 if (authority != null) {
783 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800784 syncs.add(new PeriodicSync(account, providerName, item.first,
785 item.second));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800786 }
787 }
788 }
789 return syncs;
790 }
791
Amith Yamasani04e0d262012-02-14 11:50:53 -0800792 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700793 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800794 Boolean auto = mMasterSyncAutomatically.get(userId);
795 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700796 return;
797 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800798 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700799 writeAccountInfoLocked();
800 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700801 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700802 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
803 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700804 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700805 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800806 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808
Amith Yamasani04e0d262012-02-14 11:50:53 -0800809 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700810 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800811 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800812 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700813 }
814 }
Costin Manolache360e4542009-09-04 13:36:04 -0700815
Amith Yamasani04e0d262012-02-14 11:50:53 -0800816 public AuthorityInfo getOrCreateAuthority(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700817 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800818 return getOrCreateAuthorityLocked(account, userId, authority,
Fred Quintana1bbcd102010-02-10 10:04:33 -0800819 -1 /* assign a new identifier if creating a new authority */,
820 true /* write to storage if this results in a change */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700821 }
822 }
Costin Manolache360e4542009-09-04 13:36:04 -0700823
Amith Yamasani04e0d262012-02-14 11:50:53 -0800824 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700825 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800826 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700827 }
828 }
829
Dianne Hackborn231cc602009-04-27 17:10:36 -0700830 public AuthorityInfo getAuthority(int authorityId) {
831 synchronized (mAuthorities) {
832 return mAuthorities.get(authorityId);
833 }
834 }
Costin Manolache360e4542009-09-04 13:36:04 -0700835
Dianne Hackborn231cc602009-04-27 17:10:36 -0700836 /**
837 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700838 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700839 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800840 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700841 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800842 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700843 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700844 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800845 && ainfo.authority.equals(authority)
846 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700847 return true;
848 }
849 }
850 }
Costin Manolache360e4542009-09-04 13:36:04 -0700851
Dianne Hackborn231cc602009-04-27 17:10:36 -0700852 return false;
853 }
Costin Manolache360e4542009-09-04 13:36:04 -0700854
Dianne Hackborn231cc602009-04-27 17:10:36 -0700855 public PendingOperation insertIntoPending(PendingOperation op) {
856 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800857 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700858 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800859 + " user=" + op.userId
860 + " auth=" + op.authority
861 + " src=" + op.syncSource
862 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700863 }
Costin Manolache360e4542009-09-04 13:36:04 -0700864
Amith Yamasani04e0d262012-02-14 11:50:53 -0800865 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700866 op.authority,
867 -1 /* desired identifier */,
868 true /* write accounts to storage */);
869 if (authority == null) {
870 return null;
871 }
Costin Manolache360e4542009-09-04 13:36:04 -0700872
Dianne Hackborn231cc602009-04-27 17:10:36 -0700873 op = new PendingOperation(op);
874 op.authorityId = authority.ident;
875 mPendingOperations.add(op);
876 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700877
Dianne Hackborn231cc602009-04-27 17:10:36 -0700878 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
879 status.pending = true;
880 }
Costin Manolache360e4542009-09-04 13:36:04 -0700881
Fred Quintanaac9385e2009-06-22 18:00:59 -0700882 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700883 return op;
884 }
885
886 public boolean deleteFromPending(PendingOperation op) {
887 boolean res = false;
888 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800889 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700890 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800891 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700892 + " auth=" + op.authority
893 + " src=" + op.syncSource
894 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700895 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700896 if (mPendingOperations.remove(op)) {
897 if (mPendingOperations.size() == 0
898 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
899 writePendingOperationsLocked();
900 mNumPendingFinished = 0;
901 } else {
902 mNumPendingFinished++;
903 }
Costin Manolache360e4542009-09-04 13:36:04 -0700904
Amith Yamasani04e0d262012-02-14 11:50:53 -0800905 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700906 "deleteFromPending");
907 if (authority != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800908 if (DEBUG) Log.v(TAG, "removing - " + authority);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700909 final int N = mPendingOperations.size();
910 boolean morePending = false;
911 for (int i=0; i<N; i++) {
912 PendingOperation cur = mPendingOperations.get(i);
913 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800914 && cur.authority.equals(op.authority)
915 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700916 morePending = true;
917 break;
918 }
919 }
Costin Manolache360e4542009-09-04 13:36:04 -0700920
Dianne Hackborn231cc602009-04-27 17:10:36 -0700921 if (!morePending) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800922 if (DEBUG) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700923 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
924 status.pending = false;
925 }
926 }
Costin Manolache360e4542009-09-04 13:36:04 -0700927
Dianne Hackborn231cc602009-04-27 17:10:36 -0700928 res = true;
929 }
930 }
Costin Manolache360e4542009-09-04 13:36:04 -0700931
Fred Quintanaac9385e2009-06-22 18:00:59 -0700932 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700933 return res;
934 }
935
Dianne Hackborn231cc602009-04-27 17:10:36 -0700936 /**
937 * Return a copy of the current array of pending operations. The
938 * PendingOperation objects are the real objects stored inside, so that
939 * they can be used with deleteFromPending().
940 */
941 public ArrayList<PendingOperation> getPendingOperations() {
942 synchronized (mAuthorities) {
943 return new ArrayList<PendingOperation>(mPendingOperations);
944 }
945 }
Costin Manolache360e4542009-09-04 13:36:04 -0700946
Dianne Hackborn231cc602009-04-27 17:10:36 -0700947 /**
948 * Return the number of currently pending operations.
949 */
950 public int getPendingOperationCount() {
951 synchronized (mAuthorities) {
952 return mPendingOperations.size();
953 }
954 }
Costin Manolache360e4542009-09-04 13:36:04 -0700955
Dianne Hackborn231cc602009-04-27 17:10:36 -0700956 /**
957 * Called when the set of account has changed, given the new array of
958 * active accounts.
959 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800960 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700961 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800962 if (DEBUG) Log.v(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700963 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
964 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
965 while (accIt.hasNext()) {
966 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800967 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
968 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700969 // This account no longer exists...
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800970 if (DEBUG) {
971 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700972 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700973 for (AuthorityInfo auth : acc.authorities.values()) {
974 removing.put(auth.ident, auth);
975 }
976 accIt.remove();
977 }
978 }
Costin Manolache360e4542009-09-04 13:36:04 -0700979
Dianne Hackborn231cc602009-04-27 17:10:36 -0700980 // Clean out all data structures.
981 int i = removing.size();
982 if (i > 0) {
983 while (i > 0) {
984 i--;
985 int ident = removing.keyAt(i);
986 mAuthorities.remove(ident);
987 int j = mSyncStatus.size();
988 while (j > 0) {
989 j--;
990 if (mSyncStatus.keyAt(j) == ident) {
991 mSyncStatus.remove(mSyncStatus.keyAt(j));
992 }
993 }
994 j = mSyncHistory.size();
995 while (j > 0) {
996 j--;
997 if (mSyncHistory.get(j).authorityId == ident) {
998 mSyncHistory.remove(j);
999 }
1000 }
1001 }
1002 writeAccountInfoLocked();
1003 writeStatusLocked();
1004 writePendingOperationsLocked();
1005 writeStatisticsLocked();
1006 }
1007 }
1008 }
1009
1010 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001011 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1012 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001013 */
Fred Quintana918339a2010-10-05 14:00:39 -07001014 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1015 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001016 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001017 if (DEBUG) {
Fred Quintana918339a2010-10-05 14:00:39 -07001018 Log.v(TAG, "setActiveSync: account="
1019 + activeSyncContext.mSyncOperation.account
1020 + " auth=" + activeSyncContext.mSyncOperation.authority
1021 + " src=" + activeSyncContext.mSyncOperation.syncSource
1022 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001023 }
Fred Quintana918339a2010-10-05 14:00:39 -07001024 AuthorityInfo authority = getOrCreateAuthorityLocked(
1025 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001026 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -07001027 activeSyncContext.mSyncOperation.authority,
1028 -1 /* assign a new identifier if creating a new authority */,
1029 true /* write to storage if this results in a change */);
1030 syncInfo = new SyncInfo(authority.ident,
1031 authority.account, authority.authority,
1032 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001033 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001034 }
Costin Manolache360e4542009-09-04 13:36:04 -07001035
Fred Quintana918339a2010-10-05 14:00:39 -07001036 reportActiveChange();
1037 return syncInfo;
1038 }
1039
1040 /**
1041 * Called to indicate that a previously active sync is no longer active.
1042 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001043 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001044 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001045 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001046 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1047 + " user=" + userId
1048 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001049 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001050 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001051 }
1052
1053 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001054 }
1055
1056 /**
1057 * To allow others to send active change reports, to poke clients.
1058 */
1059 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001060 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001061 }
Costin Manolache360e4542009-09-04 13:36:04 -07001062
Dianne Hackborn231cc602009-04-27 17:10:36 -07001063 /**
1064 * Note that sync has started for the given account and authority.
1065 */
Alon Albert57286f92012-10-09 14:21:38 -07001066 public long insertStartSyncEvent(Account accountName, int userId, int reason,
1067 String authorityName, long now, int source, boolean initialization, Bundle extras) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001068 long id;
1069 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001070 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001071 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001072 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001073 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001074 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001075 "insertStartSyncEvent");
1076 if (authority == null) {
1077 return -1;
1078 }
1079 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001080 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001081 item.authorityId = authority.ident;
1082 item.historyId = mNextHistoryId++;
1083 if (mNextHistoryId < 0) mNextHistoryId = 0;
1084 item.eventTime = now;
1085 item.source = source;
Alon Albert57286f92012-10-09 14:21:38 -07001086 item.reason = reason;
1087 item.extras = extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001088 item.event = EVENT_START;
1089 mSyncHistory.add(0, item);
1090 while (mSyncHistory.size() > MAX_HISTORY) {
1091 mSyncHistory.remove(mSyncHistory.size()-1);
1092 }
1093 id = item.historyId;
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001094 if (DEBUG) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001095 }
Costin Manolache360e4542009-09-04 13:36:04 -07001096
Fred Quintanaac9385e2009-06-22 18:00:59 -07001097 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001098 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 }
1100
Fred Quintana77c560f2010-03-29 22:20:26 -07001101 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001103 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001104 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001105 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1106 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001107 SyncHistoryItem item = null;
1108 int i = mSyncHistory.size();
1109 while (i > 0) {
1110 i--;
1111 item = mSyncHistory.get(i);
1112 if (item.historyId == historyId) {
1113 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001115 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
Costin Manolache360e4542009-09-04 13:36:04 -07001117
Dianne Hackborn231cc602009-04-27 17:10:36 -07001118 if (item == null) {
1119 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1120 return;
1121 }
Costin Manolache360e4542009-09-04 13:36:04 -07001122
Dianne Hackborn231cc602009-04-27 17:10:36 -07001123 item.elapsedTime = elapsedTime;
1124 item.event = EVENT_STOP;
1125 item.mesg = resultMessage;
1126 item.downstreamActivity = downstreamActivity;
1127 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001128
Dianne Hackborn231cc602009-04-27 17:10:36 -07001129 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001130
Dianne Hackborn231cc602009-04-27 17:10:36 -07001131 status.numSyncs++;
1132 status.totalElapsedTime += elapsedTime;
1133 switch (item.source) {
1134 case SOURCE_LOCAL:
1135 status.numSourceLocal++;
1136 break;
1137 case SOURCE_POLL:
1138 status.numSourcePoll++;
1139 break;
1140 case SOURCE_USER:
1141 status.numSourceUser++;
1142 break;
1143 case SOURCE_SERVER:
1144 status.numSourceServer++;
1145 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001146 case SOURCE_PERIODIC:
1147 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001148 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001149 }
Costin Manolache360e4542009-09-04 13:36:04 -07001150
Dianne Hackborn231cc602009-04-27 17:10:36 -07001151 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001152 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001153 if (mDayStats[0] == null) {
1154 mDayStats[0] = new DayStats(day);
1155 } else if (day != mDayStats[0].day) {
1156 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1157 mDayStats[0] = new DayStats(day);
1158 writeStatisticsNow = true;
1159 } else if (mDayStats[0] == null) {
1160 }
1161 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001162
Dianne Hackborn231cc602009-04-27 17:10:36 -07001163 final long lastSyncTime = (item.eventTime + elapsedTime);
1164 boolean writeStatusNow = false;
1165 if (MESG_SUCCESS.equals(resultMessage)) {
1166 // - if successful, update the successful columns
1167 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1168 writeStatusNow = true;
1169 }
1170 status.lastSuccessTime = lastSyncTime;
1171 status.lastSuccessSource = item.source;
1172 status.lastFailureTime = 0;
1173 status.lastFailureSource = -1;
1174 status.lastFailureMesg = null;
1175 status.initialFailureTime = 0;
1176 ds.successCount++;
1177 ds.successTime += elapsedTime;
1178 } else if (!MESG_CANCELED.equals(resultMessage)) {
1179 if (status.lastFailureTime == 0) {
1180 writeStatusNow = true;
1181 }
1182 status.lastFailureTime = lastSyncTime;
1183 status.lastFailureSource = item.source;
1184 status.lastFailureMesg = resultMessage;
1185 if (status.initialFailureTime == 0) {
1186 status.initialFailureTime = lastSyncTime;
1187 }
1188 ds.failureCount++;
1189 ds.failureTime += elapsedTime;
1190 }
Costin Manolache360e4542009-09-04 13:36:04 -07001191
Dianne Hackborn231cc602009-04-27 17:10:36 -07001192 if (writeStatusNow) {
1193 writeStatusLocked();
1194 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1195 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1196 WRITE_STATUS_DELAY);
1197 }
1198 if (writeStatisticsNow) {
1199 writeStatisticsLocked();
1200 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1201 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1202 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001203 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001204 }
Costin Manolache360e4542009-09-04 13:36:04 -07001205
Fred Quintanaac9385e2009-06-22 18:00:59 -07001206 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001207 }
1208
1209 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001210 * Return a list of the currently active syncs. Note that the returned items are the
1211 * real, live active sync objects, so be careful what you do with it.
1212 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001213 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001214 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001215 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1216 if (syncs == null) {
1217 syncs = new ArrayList<SyncInfo>();
1218 mCurrentSyncs.put(userId, syncs);
1219 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001220 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001221 }
1222 }
Costin Manolache360e4542009-09-04 13:36:04 -07001223
Dianne Hackborn231cc602009-04-27 17:10:36 -07001224 /**
1225 * Return an array of the current sync status for all authorities. Note
1226 * that the objects inside the array are the real, live status objects,
1227 * so be careful what you do with them.
1228 */
1229 public ArrayList<SyncStatusInfo> getSyncStatus() {
1230 synchronized (mAuthorities) {
1231 final int N = mSyncStatus.size();
1232 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1233 for (int i=0; i<N; i++) {
1234 ops.add(mSyncStatus.valueAt(i));
1235 }
1236 return ops;
1237 }
1238 }
Costin Manolache360e4542009-09-04 13:36:04 -07001239
Dianne Hackborn231cc602009-04-27 17:10:36 -07001240 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001241 * Return an array of the current authorities. Note
1242 * that the objects inside the array are the real, live objects,
1243 * so be careful what you do with them.
1244 */
1245 public ArrayList<AuthorityInfo> getAuthorities() {
1246 synchronized (mAuthorities) {
1247 final int N = mAuthorities.size();
1248 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1249 for (int i=0; i<N; i++) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -07001250 // Make deep copy because AuthorityInfo syncs are liable to change.
1251 infos.add(new AuthorityInfo(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001252 }
1253 return infos;
1254 }
1255 }
1256
1257 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001258 * Returns the status that matches the authority and account.
1259 *
1260 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001261 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001262 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001263 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001264 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1265 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001266 if (account == null || authority == null) {
1267 throw new IllegalArgumentException();
1268 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001269 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001270 final int N = mSyncStatus.size();
1271 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001272 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001273 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001274
Amith Yamasani04e0d262012-02-14 11:50:53 -08001275 if (ainfo != null && ainfo.authority.equals(authority)
1276 && ainfo.userId == userId
1277 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001278 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001279 }
1280 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001281 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001282 }
1283 }
Costin Manolache360e4542009-09-04 13:36:04 -07001284
Dianne Hackborn231cc602009-04-27 17:10:36 -07001285 /**
1286 * Return true if the pending status is true of any matching authorities.
1287 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001288 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001289 synchronized (mAuthorities) {
1290 final int N = mSyncStatus.size();
1291 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001292 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001293 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1294 if (ainfo == null) {
1295 continue;
1296 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001297 if (userId != ainfo.userId) {
1298 continue;
1299 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001300 if (account != null && !ainfo.account.equals(account)) {
1301 continue;
1302 }
1303 if (ainfo.authority.equals(authority) && cur.pending) {
1304 return true;
1305 }
1306 }
1307 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 }
1309 }
1310
1311 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001312 * Return an array of the current sync status for all authorities. Note
1313 * that the objects inside the array are the real, live status objects,
1314 * so be careful what you do with them.
1315 */
1316 public ArrayList<SyncHistoryItem> getSyncHistory() {
1317 synchronized (mAuthorities) {
1318 final int N = mSyncHistory.size();
1319 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1320 for (int i=0; i<N; i++) {
1321 items.add(mSyncHistory.get(i));
1322 }
1323 return items;
1324 }
1325 }
Costin Manolache360e4542009-09-04 13:36:04 -07001326
Dianne Hackborn231cc602009-04-27 17:10:36 -07001327 /**
1328 * Return an array of the current per-day statistics. Note
1329 * that the objects inside the array are the real, live status objects,
1330 * so be careful what you do with them.
1331 */
1332 public DayStats[] getDayStatistics() {
1333 synchronized (mAuthorities) {
1334 DayStats[] ds = new DayStats[mDayStats.length];
1335 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1336 return ds;
1337 }
1338 }
Costin Manolache360e4542009-09-04 13:36:04 -07001339
Dianne Hackborn55280a92009-05-07 15:53:46 -07001340 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001341 mCal.setTimeInMillis(System.currentTimeMillis());
1342 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1343 if (mYear != mCal.get(Calendar.YEAR)) {
1344 mYear = mCal.get(Calendar.YEAR);
1345 mCal.clear();
1346 mCal.set(Calendar.YEAR, mYear);
1347 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1348 }
1349 return dayOfYear + mYearInDays;
1350 }
Costin Manolache360e4542009-09-04 13:36:04 -07001351
Dianne Hackborn231cc602009-04-27 17:10:36 -07001352 /**
1353 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001354 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001355 * @param accountName The name of the account for the authority.
1356 * @param authorityName The name of the authority itself.
1357 * @param tag If non-null, this will be used in a log message if the
1358 * requested authority does not exist.
1359 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001360 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001361 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001362 AccountAndUser au = new AccountAndUser(accountName, userId);
1363 AccountInfo accountInfo = mAccounts.get(au);
1364 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001365 if (tag != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001366 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001367 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001368 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001369 }
1370 return null;
1371 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001372 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001373 if (authority == null) {
1374 if (tag != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001375 if (DEBUG) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001376 Log.v(TAG, tag + ": unknown authority " + authorityName);
1377 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001378 }
1379 return null;
1380 }
Costin Manolache360e4542009-09-04 13:36:04 -07001381
Dianne Hackborn231cc602009-04-27 17:10:36 -07001382 return authority;
1383 }
Costin Manolache360e4542009-09-04 13:36:04 -07001384
Amith Yamasani04e0d262012-02-14 11:50:53 -08001385 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001386 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001387 AccountAndUser au = new AccountAndUser(accountName, userId);
1388 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001389 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001390 account = new AccountInfo(au);
1391 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001392 }
1393 AuthorityInfo authority = account.authorities.get(authorityName);
1394 if (authority == null) {
1395 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001396 ident = mNextAuthorityId;
1397 mNextAuthorityId++;
1398 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001399 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001400 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001401 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001402 + ", user " + userId
1403 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001404 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001405 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001406 account.authorities.put(authorityName, authority);
1407 mAuthorities.put(ident, authority);
1408 if (doWrite) {
1409 writeAccountInfoLocked();
1410 }
1411 }
Costin Manolache360e4542009-09-04 13:36:04 -07001412
Dianne Hackborn231cc602009-04-27 17:10:36 -07001413 return authority;
1414 }
Costin Manolache360e4542009-09-04 13:36:04 -07001415
Amith Yamasani04e0d262012-02-14 11:50:53 -08001416 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1417 boolean doWrite) {
1418 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001419 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001420 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1421 if (authorityInfo != null) {
1422 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001423 if (doWrite) {
1424 writeAccountInfoLocked();
1425 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001426 }
1427 }
1428 }
1429
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001430 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1431 synchronized (mAuthorities) {
1432 return getOrCreateSyncStatusLocked(authority.ident);
1433 }
1434 }
1435
Dianne Hackborn231cc602009-04-27 17:10:36 -07001436 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1437 SyncStatusInfo status = mSyncStatus.get(authorityId);
1438 if (status == null) {
1439 status = new SyncStatusInfo(authorityId);
1440 mSyncStatus.put(authorityId, status);
1441 }
1442 return status;
1443 }
Costin Manolache360e4542009-09-04 13:36:04 -07001444
Dianne Hackborn55280a92009-05-07 15:53:46 -07001445 public void writeAllState() {
1446 synchronized (mAuthorities) {
1447 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001448
Dianne Hackborn55280a92009-05-07 15:53:46 -07001449 if (mNumPendingFinished > 0) {
1450 // Only write these if they are out of date.
1451 writePendingOperationsLocked();
1452 }
Costin Manolache360e4542009-09-04 13:36:04 -07001453
Dianne Hackborn55280a92009-05-07 15:53:46 -07001454 // Just always write these... they are likely out of date.
1455 writeStatusLocked();
1456 writeStatisticsLocked();
1457 }
1458 }
Costin Manolache360e4542009-09-04 13:36:04 -07001459
Dianne Hackborn231cc602009-04-27 17:10:36 -07001460 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001461 * public for testing
1462 */
1463 public void clearAndReadState() {
1464 synchronized (mAuthorities) {
1465 mAuthorities.clear();
1466 mAccounts.clear();
1467 mPendingOperations.clear();
1468 mSyncStatus.clear();
1469 mSyncHistory.clear();
1470
1471 readAccountInfoLocked();
1472 readStatusLocked();
1473 readPendingOperationsLocked();
1474 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001475 readAndDeleteLegacyAccountInfoLocked();
1476 writeAccountInfoLocked();
1477 writeStatusLocked();
1478 writePendingOperationsLocked();
1479 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001480 }
1481 }
1482
1483 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001484 * Read all account information back in to the initial engine state.
1485 */
1486 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001487 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001488 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001490 fis = mAccountInfoFile.openRead();
1491 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1492 XmlPullParser parser = Xml.newPullParser();
1493 parser.setInput(fis, null);
1494 int eventType = parser.getEventType();
1495 while (eventType != XmlPullParser.START_TAG) {
1496 eventType = parser.next();
1497 }
1498 String tagName = parser.getName();
1499 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001500 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001501 String versionString = parser.getAttributeValue(null, "version");
1502 int version;
1503 try {
1504 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1505 } catch (NumberFormatException e) {
1506 version = 0;
1507 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001508 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001509 try {
1510 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1511 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1512 } catch (NumberFormatException e) {
1513 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001514 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001515 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1516 try {
1517 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1518 } catch (NumberFormatException e) {
1519 mSyncRandomOffset = 0;
1520 }
1521 if (mSyncRandomOffset == 0) {
1522 Random random = new Random(System.currentTimeMillis());
1523 mSyncRandomOffset = random.nextInt(86400);
1524 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001525 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001526 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001527 AuthorityInfo authority = null;
1528 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001529 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001530 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001531 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001532 if (parser.getDepth() == 2) {
1533 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001534 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001535 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001536 if (authority.ident > highestAuthorityId) {
1537 highestAuthorityId = authority.ident;
1538 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001539 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1540 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001541 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001542 } else if (parser.getDepth() == 3) {
1543 if ("periodicSync".equals(tagName) && authority != null) {
1544 periodicSync = parsePeriodicSync(parser, authority);
1545 }
1546 } else if (parser.getDepth() == 4 && periodicSync != null) {
1547 if ("extra".equals(tagName)) {
1548 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001549 }
1550 }
1551 }
1552 eventType = parser.next();
1553 } while (eventType != XmlPullParser.END_DOCUMENT);
1554 }
1555 } catch (XmlPullParserException e) {
1556 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001557 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001558 } catch (java.io.IOException e) {
1559 if (fis == null) Log.i(TAG, "No initial accounts");
1560 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001561 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001562 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001563 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001564 if (fis != null) {
1565 try {
1566 fis.close();
1567 } catch (java.io.IOException e1) {
1568 }
1569 }
1570 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001571
Fred Quintana77c560f2010-03-29 22:20:26 -07001572 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001573 }
Costin Manolache360e4542009-09-04 13:36:04 -07001574
Fred Quintanafb084402010-03-23 17:57:03 -07001575 /**
1576 * some authority names have changed. copy over their settings and delete the old ones
1577 * @return true if a change was made
1578 */
1579 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1580 boolean writeNeeded = false;
1581
1582 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1583 final int N = mAuthorities.size();
1584 for (int i=0; i<N; i++) {
1585 AuthorityInfo authority = mAuthorities.valueAt(i);
1586 // skip this authority if it isn't one of the renamed ones
1587 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1588 if (newAuthorityName == null) {
1589 continue;
1590 }
1591
1592 // remember this authority so we can remove it later. we can't remove it
1593 // now without messing up this loop iteration
1594 authoritiesToRemove.add(authority);
1595
1596 // this authority isn't enabled, no need to copy it to the new authority name since
1597 // the default is "disabled"
1598 if (!authority.enabled) {
1599 continue;
1600 }
1601
1602 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001603 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1604 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001605 continue;
1606 }
1607
1608 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001609 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001610 newAuthority.enabled = true;
1611 writeNeeded = true;
1612 }
1613
1614 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001615 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1616 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001617 writeNeeded = true;
1618 }
1619
1620 return writeNeeded;
1621 }
1622
Amith Yamasani04e0d262012-02-14 11:50:53 -08001623 private void parseListenForTickles(XmlPullParser parser) {
1624 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1625 int userId = 0;
1626 try {
1627 userId = Integer.parseInt(user);
1628 } catch (NumberFormatException e) {
1629 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1630 } catch (NullPointerException e) {
1631 Log.e(TAG, "the user in listen-for-tickles is null", e);
1632 }
1633 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1634 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1635 mMasterSyncAutomatically.put(userId, listen);
1636 }
1637
Fred Quintanac2e46912010-03-15 16:10:44 -07001638 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001639 AuthorityInfo authority = null;
1640 int id = -1;
1641 try {
1642 id = Integer.parseInt(parser.getAttributeValue(
1643 null, "id"));
1644 } catch (NumberFormatException e) {
1645 Log.e(TAG, "error parsing the id of the authority", e);
1646 } catch (NullPointerException e) {
1647 Log.e(TAG, "the id of the authority is null", e);
1648 }
1649 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001650 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001651 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001652 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001653 String accountName = parser.getAttributeValue(null, "account");
1654 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001655 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1656 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001657 if (accountType == null) {
1658 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001659 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001660 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001661 authority = mAuthorities.get(id);
1662 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1663 + accountName + " auth=" + authorityName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001664 + " user=" + userId
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001665 + " enabled=" + enabled
1666 + " syncable=" + syncable);
1667 if (authority == null) {
1668 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1669 authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001670 new Account(accountName, accountType), userId, authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001671 // If the version is 0 then we are upgrading from a file format that did not
1672 // know about periodic syncs. In that case don't clear the list since we
1673 // want the default, which is a daily periodioc sync.
1674 // Otherwise clear out this default list since we will populate it later with
1675 // the periodic sync descriptions that are read from the configuration file.
1676 if (version > 0) {
1677 authority.periodicSyncs.clear();
1678 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001679 }
1680 if (authority != null) {
1681 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1682 if ("unknown".equals(syncable)) {
1683 authority.syncable = -1;
1684 } else {
1685 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001686 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001687 }
1688 } else {
1689 Log.w(TAG, "Failure adding authority: account="
1690 + accountName + " auth=" + authorityName
1691 + " enabled=" + enabled
1692 + " syncable=" + syncable);
1693 }
1694 }
1695
1696 return authority;
1697 }
1698
1699 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1700 Bundle extras = new Bundle();
1701 String periodValue = parser.getAttributeValue(null, "period");
1702 final long period;
1703 try {
1704 period = Long.parseLong(periodValue);
1705 } catch (NumberFormatException e) {
1706 Log.e(TAG, "error parsing the period of a periodic sync", e);
1707 return null;
1708 } catch (NullPointerException e) {
1709 Log.e(TAG, "the period of a periodic sync is null", e);
1710 return null;
1711 }
1712 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1713 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001714
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001715 return periodicSync;
1716 }
1717
1718 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1719 final Bundle extras = periodicSync.first;
1720 String name = parser.getAttributeValue(null, "name");
1721 String type = parser.getAttributeValue(null, "type");
1722 String value1 = parser.getAttributeValue(null, "value1");
1723 String value2 = parser.getAttributeValue(null, "value2");
1724
1725 try {
1726 if ("long".equals(type)) {
1727 extras.putLong(name, Long.parseLong(value1));
1728 } else if ("integer".equals(type)) {
1729 extras.putInt(name, Integer.parseInt(value1));
1730 } else if ("double".equals(type)) {
1731 extras.putDouble(name, Double.parseDouble(value1));
1732 } else if ("float".equals(type)) {
1733 extras.putFloat(name, Float.parseFloat(value1));
1734 } else if ("boolean".equals(type)) {
1735 extras.putBoolean(name, Boolean.parseBoolean(value1));
1736 } else if ("string".equals(type)) {
1737 extras.putString(name, value1);
1738 } else if ("account".equals(type)) {
1739 extras.putParcelable(name, new Account(value1, value2));
1740 }
1741 } catch (NumberFormatException e) {
1742 Log.e(TAG, "error parsing bundle value", e);
1743 } catch (NullPointerException e) {
1744 Log.e(TAG, "error parsing bundle value", e);
1745 }
1746 }
1747
Dianne Hackborn231cc602009-04-27 17:10:36 -07001748 /**
1749 * Write all account information to the account file.
1750 */
1751 private void writeAccountInfoLocked() {
1752 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1753 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001754
Dianne Hackborn231cc602009-04-27 17:10:36 -07001755 try {
1756 fos = mAccountInfoFile.startWrite();
1757 XmlSerializer out = new FastXmlSerializer();
1758 out.setOutput(fos, "utf-8");
1759 out.startDocument(null, true);
1760 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001761
Dianne Hackborn231cc602009-04-27 17:10:36 -07001762 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001763 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001764 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001765 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001766
1767 // Write the Sync Automatically flags for each user
1768 final int M = mMasterSyncAutomatically.size();
1769 for (int m = 0; m < M; m++) {
1770 int userId = mMasterSyncAutomatically.keyAt(m);
1771 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1772 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1773 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1774 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1775 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001776 }
Costin Manolache360e4542009-09-04 13:36:04 -07001777
Dianne Hackborn231cc602009-04-27 17:10:36 -07001778 final int N = mAuthorities.size();
1779 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001780 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001781 out.startTag(null, "authority");
1782 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001783 out.attribute(null, "account", authority.account.name);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001784 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001785 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001786 out.attribute(null, "authority", authority.authority);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001787 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Fred Quintana5e787c42009-08-16 23:13:53 -07001788 if (authority.syncable < 0) {
1789 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001790 } else {
1791 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001792 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001793 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1794 out.startTag(null, "periodicSync");
1795 out.attribute(null, "period", Long.toString(periodicSync.second));
1796 final Bundle extras = periodicSync.first;
1797 for (String key : extras.keySet()) {
1798 out.startTag(null, "extra");
1799 out.attribute(null, "name", key);
1800 final Object value = extras.get(key);
1801 if (value instanceof Long) {
1802 out.attribute(null, "type", "long");
1803 out.attribute(null, "value1", value.toString());
1804 } else if (value instanceof Integer) {
1805 out.attribute(null, "type", "integer");
1806 out.attribute(null, "value1", value.toString());
1807 } else if (value instanceof Boolean) {
1808 out.attribute(null, "type", "boolean");
1809 out.attribute(null, "value1", value.toString());
1810 } else if (value instanceof Float) {
1811 out.attribute(null, "type", "float");
1812 out.attribute(null, "value1", value.toString());
1813 } else if (value instanceof Double) {
1814 out.attribute(null, "type", "double");
1815 out.attribute(null, "value1", value.toString());
1816 } else if (value instanceof String) {
1817 out.attribute(null, "type", "string");
1818 out.attribute(null, "value1", value.toString());
1819 } else if (value instanceof Account) {
1820 out.attribute(null, "type", "account");
1821 out.attribute(null, "value1", ((Account)value).name);
1822 out.attribute(null, "value2", ((Account)value).type);
1823 }
1824 out.endTag(null, "extra");
1825 }
1826 out.endTag(null, "periodicSync");
1827 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001828 out.endTag(null, "authority");
1829 }
Costin Manolache360e4542009-09-04 13:36:04 -07001830
Dianne Hackborn231cc602009-04-27 17:10:36 -07001831 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001832
Dianne Hackborn231cc602009-04-27 17:10:36 -07001833 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001834
Dianne Hackborn231cc602009-04-27 17:10:36 -07001835 mAccountInfoFile.finishWrite(fos);
1836 } catch (java.io.IOException e1) {
1837 Log.w(TAG, "Error writing accounts", e1);
1838 if (fos != null) {
1839 mAccountInfoFile.failWrite(fos);
1840 }
1841 }
1842 }
Costin Manolache360e4542009-09-04 13:36:04 -07001843
Dianne Hackborn231cc602009-04-27 17:10:36 -07001844 static int getIntColumn(Cursor c, String name) {
1845 return c.getInt(c.getColumnIndex(name));
1846 }
Costin Manolache360e4542009-09-04 13:36:04 -07001847
Dianne Hackborn231cc602009-04-27 17:10:36 -07001848 static long getLongColumn(Cursor c, String name) {
1849 return c.getLong(c.getColumnIndex(name));
1850 }
Costin Manolache360e4542009-09-04 13:36:04 -07001851
Dianne Hackborn231cc602009-04-27 17:10:36 -07001852 /**
1853 * Load sync engine state from the old syncmanager database, and then
1854 * erase it. Note that we don't deal with pending operations, active
1855 * sync, or history.
1856 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001857 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001858 // Look for old database to initialize from.
1859 File file = mContext.getDatabasePath("syncmanager.db");
1860 if (!file.exists()) {
1861 return;
1862 }
1863 String path = file.getPath();
1864 SQLiteDatabase db = null;
1865 try {
1866 db = SQLiteDatabase.openDatabase(path, null,
1867 SQLiteDatabase.OPEN_READONLY);
1868 } catch (SQLiteException e) {
1869 }
Costin Manolache360e4542009-09-04 13:36:04 -07001870
Dianne Hackborn231cc602009-04-27 17:10:36 -07001871 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001872 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001873
Dianne Hackborn231cc602009-04-27 17:10:36 -07001874 // Copy in all of the status information, as well as accounts.
1875 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1876 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1877 qb.setTables("stats, status");
1878 HashMap<String,String> map = new HashMap<String,String>();
1879 map.put("_id", "status._id as _id");
1880 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001881 if (hasType) {
1882 map.put("account_type", "stats.account_type as account_type");
1883 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001884 map.put("authority", "stats.authority as authority");
1885 map.put("totalElapsedTime", "totalElapsedTime");
1886 map.put("numSyncs", "numSyncs");
1887 map.put("numSourceLocal", "numSourceLocal");
1888 map.put("numSourcePoll", "numSourcePoll");
1889 map.put("numSourceServer", "numSourceServer");
1890 map.put("numSourceUser", "numSourceUser");
1891 map.put("lastSuccessSource", "lastSuccessSource");
1892 map.put("lastSuccessTime", "lastSuccessTime");
1893 map.put("lastFailureSource", "lastFailureSource");
1894 map.put("lastFailureTime", "lastFailureTime");
1895 map.put("lastFailureMesg", "lastFailureMesg");
1896 map.put("pending", "pending");
1897 qb.setProjectionMap(map);
1898 qb.appendWhere("stats._id = status.stats_id");
1899 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001901 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001902 String accountType = hasType
1903 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001904 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001905 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001907 String authorityName = c.getString(c.getColumnIndex("authority"));
1908 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001909 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07001910 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001911 if (authority != null) {
1912 int i = mSyncStatus.size();
1913 boolean found = false;
1914 SyncStatusInfo st = null;
1915 while (i > 0) {
1916 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001917 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001918 if (st.authorityId == authority.ident) {
1919 found = true;
1920 break;
1921 }
1922 }
1923 if (!found) {
1924 st = new SyncStatusInfo(authority.ident);
1925 mSyncStatus.put(authority.ident, st);
1926 }
1927 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1928 st.numSyncs = getIntColumn(c, "numSyncs");
1929 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1930 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1931 st.numSourceServer = getIntColumn(c, "numSourceServer");
1932 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001933 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001934 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1935 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1936 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1937 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1938 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1939 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 }
Costin Manolache360e4542009-09-04 13:36:04 -07001942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001944
Dianne Hackborn231cc602009-04-27 17:10:36 -07001945 // Retrieve the settings.
1946 qb = new SQLiteQueryBuilder();
1947 qb.setTables("settings");
1948 c = qb.query(db, null, null, null, null, null, null);
1949 while (c.moveToNext()) {
1950 String name = c.getString(c.getColumnIndex("name"));
1951 String value = c.getString(c.getColumnIndex("value"));
1952 if (name == null) continue;
1953 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001954 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001955 } else if (name.startsWith("sync_provider_")) {
1956 String provider = name.substring("sync_provider_".length(),
1957 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001958 int i = mAuthorities.size();
1959 while (i > 0) {
1960 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001961 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001962 if (authority.authority.equals(provider)) {
1963 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001964 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001965 }
1966 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 }
Costin Manolache360e4542009-09-04 13:36:04 -07001969
Dianne Hackborn231cc602009-04-27 17:10:36 -07001970 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001971
Dianne Hackborn231cc602009-04-27 17:10:36 -07001972 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001973
Dianne Hackborn231cc602009-04-27 17:10:36 -07001974 (new File(path)).delete();
1975 }
1976 }
Costin Manolache360e4542009-09-04 13:36:04 -07001977
Dianne Hackborn231cc602009-04-27 17:10:36 -07001978 public static final int STATUS_FILE_END = 0;
1979 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001980
Dianne Hackborn231cc602009-04-27 17:10:36 -07001981 /**
1982 * Read all sync status back in to the initial engine state.
1983 */
1984 private void readStatusLocked() {
1985 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1986 try {
1987 byte[] data = mStatusFile.readFully();
1988 Parcel in = Parcel.obtain();
1989 in.unmarshall(data, 0, data.length);
1990 in.setDataPosition(0);
1991 int token;
1992 while ((token=in.readInt()) != STATUS_FILE_END) {
1993 if (token == STATUS_FILE_ITEM) {
1994 SyncStatusInfo status = new SyncStatusInfo(in);
1995 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1996 status.pending = false;
1997 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
1998 + status.authorityId);
1999 mSyncStatus.put(status.authorityId, status);
2000 }
2001 } else {
2002 // Ooops.
2003 Log.w(TAG, "Unknown status token: " + token);
2004 break;
2005 }
2006 }
2007 } catch (java.io.IOException e) {
2008 Log.i(TAG, "No initial status");
2009 }
2010 }
Costin Manolache360e4542009-09-04 13:36:04 -07002011
Dianne Hackborn231cc602009-04-27 17:10:36 -07002012 /**
2013 * Write all sync status to the sync status file.
2014 */
2015 private void writeStatusLocked() {
2016 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002017
Dianne Hackborn231cc602009-04-27 17:10:36 -07002018 // The file is being written, so we don't need to have a scheduled
2019 // write until the next change.
2020 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002021
Dianne Hackborn231cc602009-04-27 17:10:36 -07002022 FileOutputStream fos = null;
2023 try {
2024 fos = mStatusFile.startWrite();
2025 Parcel out = Parcel.obtain();
2026 final int N = mSyncStatus.size();
2027 for (int i=0; i<N; i++) {
2028 SyncStatusInfo status = mSyncStatus.valueAt(i);
2029 out.writeInt(STATUS_FILE_ITEM);
2030 status.writeToParcel(out, 0);
2031 }
2032 out.writeInt(STATUS_FILE_END);
2033 fos.write(out.marshall());
2034 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002035
Dianne Hackborn231cc602009-04-27 17:10:36 -07002036 mStatusFile.finishWrite(fos);
2037 } catch (java.io.IOException e1) {
2038 Log.w(TAG, "Error writing status", e1);
2039 if (fos != null) {
2040 mStatusFile.failWrite(fos);
2041 }
2042 }
2043 }
Costin Manolache360e4542009-09-04 13:36:04 -07002044
Alon Albert57286f92012-10-09 14:21:38 -07002045 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002046
Dianne Hackborn231cc602009-04-27 17:10:36 -07002047 /**
2048 * Read all pending operations back in to the initial engine state.
2049 */
2050 private void readPendingOperationsLocked() {
2051 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
2052 try {
2053 byte[] data = mPendingFile.readFully();
2054 Parcel in = Parcel.obtain();
2055 in.unmarshall(data, 0, data.length);
2056 in.setDataPosition(0);
2057 final int SIZE = in.dataSize();
2058 while (in.dataPosition() < SIZE) {
2059 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08002060 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002061 Log.w(TAG, "Unknown pending operation version "
2062 + version + "; dropping all ops");
2063 break;
2064 }
2065 int authorityId = in.readInt();
2066 int syncSource = in.readInt();
2067 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08002068 boolean expedited;
2069 if (version == PENDING_OPERATION_VERSION) {
2070 expedited = in.readInt() != 0;
2071 } else {
2072 expedited = false;
2073 }
Alon Albert57286f92012-10-09 14:21:38 -07002074 int reason = in.readInt();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002075 AuthorityInfo authority = mAuthorities.get(authorityId);
2076 if (authority != null) {
Fred Quintana5695c7b2010-12-06 15:07:52 -08002077 Bundle extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002078 if (flatExtras != null) {
2079 extras = unflattenBundle(flatExtras);
Fred Quintana5695c7b2010-12-06 15:07:52 -08002080 } else {
2081 // if we are unable to parse the extras for whatever reason convert this
2082 // to a regular sync by creating an empty extras
2083 extras = new Bundle();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002084 }
2085 PendingOperation op = new PendingOperation(
Alon Albert57286f92012-10-09 14:21:38 -07002086 authority.account, authority.userId, reason, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08002087 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002088 op.authorityId = authorityId;
2089 op.flatExtras = flatExtras;
2090 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
2091 + " auth=" + op.authority
2092 + " src=" + op.syncSource
Alon Albert57286f92012-10-09 14:21:38 -07002093 + " reason=" + op.reason
Fred Quintana307da1a2010-01-21 14:24:20 -08002094 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07002095 + " extras=" + op.extras);
2096 mPendingOperations.add(op);
2097 }
2098 }
2099 } catch (java.io.IOException e) {
2100 Log.i(TAG, "No initial pending operations");
2101 }
2102 }
Costin Manolache360e4542009-09-04 13:36:04 -07002103
Dianne Hackborn231cc602009-04-27 17:10:36 -07002104 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
2105 out.writeInt(PENDING_OPERATION_VERSION);
2106 out.writeInt(op.authorityId);
2107 out.writeInt(op.syncSource);
2108 if (op.flatExtras == null && op.extras != null) {
2109 op.flatExtras = flattenBundle(op.extras);
2110 }
2111 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08002112 out.writeInt(op.expedited ? 1 : 0);
Alon Albert57286f92012-10-09 14:21:38 -07002113 out.writeInt(op.reason);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002114 }
Costin Manolache360e4542009-09-04 13:36:04 -07002115
Dianne Hackborn231cc602009-04-27 17:10:36 -07002116 /**
2117 * Write all currently pending ops to the pending ops file.
2118 */
2119 private void writePendingOperationsLocked() {
2120 final int N = mPendingOperations.size();
2121 FileOutputStream fos = null;
2122 try {
2123 if (N == 0) {
2124 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2125 mPendingFile.truncate();
2126 return;
2127 }
Costin Manolache360e4542009-09-04 13:36:04 -07002128
Dianne Hackborn231cc602009-04-27 17:10:36 -07002129 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2130 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07002131
Dianne Hackborn231cc602009-04-27 17:10:36 -07002132 Parcel out = Parcel.obtain();
2133 for (int i=0; i<N; i++) {
2134 PendingOperation op = mPendingOperations.get(i);
2135 writePendingOperationLocked(op, out);
2136 }
2137 fos.write(out.marshall());
2138 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002139
Dianne Hackborn231cc602009-04-27 17:10:36 -07002140 mPendingFile.finishWrite(fos);
2141 } catch (java.io.IOException e1) {
2142 Log.w(TAG, "Error writing pending operations", e1);
2143 if (fos != null) {
2144 mPendingFile.failWrite(fos);
2145 }
2146 }
2147 }
Costin Manolache360e4542009-09-04 13:36:04 -07002148
Dianne Hackborn231cc602009-04-27 17:10:36 -07002149 /**
2150 * Append the given operation to the pending ops file; if unable to,
2151 * write all pending ops.
2152 */
2153 private void appendPendingOperationLocked(PendingOperation op) {
2154 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2155 FileOutputStream fos = null;
2156 try {
2157 fos = mPendingFile.openAppend();
2158 } catch (java.io.IOException e) {
2159 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2160 writePendingOperationsLocked();
2161 return;
2162 }
Costin Manolache360e4542009-09-04 13:36:04 -07002163
Dianne Hackborn231cc602009-04-27 17:10:36 -07002164 try {
2165 Parcel out = Parcel.obtain();
2166 writePendingOperationLocked(op, out);
2167 fos.write(out.marshall());
2168 out.recycle();
2169 } catch (java.io.IOException e1) {
2170 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002172 try {
2173 fos.close();
2174 } catch (java.io.IOException e2) {
2175 }
2176 }
2177 }
Costin Manolache360e4542009-09-04 13:36:04 -07002178
Dianne Hackborn231cc602009-04-27 17:10:36 -07002179 static private byte[] flattenBundle(Bundle bundle) {
2180 byte[] flatData = null;
2181 Parcel parcel = Parcel.obtain();
2182 try {
2183 bundle.writeToParcel(parcel, 0);
2184 flatData = parcel.marshall();
2185 } finally {
2186 parcel.recycle();
2187 }
2188 return flatData;
2189 }
Costin Manolache360e4542009-09-04 13:36:04 -07002190
Dianne Hackborn231cc602009-04-27 17:10:36 -07002191 static private Bundle unflattenBundle(byte[] flatData) {
2192 Bundle bundle;
2193 Parcel parcel = Parcel.obtain();
2194 try {
2195 parcel.unmarshall(flatData, 0, flatData.length);
2196 parcel.setDataPosition(0);
2197 bundle = parcel.readBundle();
2198 } catch (RuntimeException e) {
2199 // A RuntimeException is thrown if we were unable to parse the parcel.
2200 // Create an empty parcel in this case.
2201 bundle = new Bundle();
2202 } finally {
2203 parcel.recycle();
2204 }
2205 return bundle;
2206 }
Costin Manolache360e4542009-09-04 13:36:04 -07002207
Alon Albert57286f92012-10-09 14:21:38 -07002208 private void requestSync(Account account, int userId, int reason, String authority,
2209 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002210 // If this is happening in the system process, then call the syncrequest listener
2211 // to make a request back to the SyncManager directly.
2212 // If this is probably a test instance, then call back through the ContentResolver
2213 // which will know which userId to apply based on the Binder id.
2214 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2215 && mSyncRequestListener != null) {
Alon Albert57286f92012-10-09 14:21:38 -07002216 mSyncRequestListener.onSyncRequest(account, userId, reason, authority, extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002217 } else {
2218 ContentResolver.requestSync(account, authority, extras);
2219 }
2220 }
2221
Dianne Hackborn231cc602009-04-27 17:10:36 -07002222 public static final int STATISTICS_FILE_END = 0;
2223 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2224 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002225
Dianne Hackborn231cc602009-04-27 17:10:36 -07002226 /**
2227 * Read all sync statistics back in to the initial engine state.
2228 */
2229 private void readStatisticsLocked() {
2230 try {
2231 byte[] data = mStatisticsFile.readFully();
2232 Parcel in = Parcel.obtain();
2233 in.unmarshall(data, 0, data.length);
2234 in.setDataPosition(0);
2235 int token;
2236 int index = 0;
2237 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2238 if (token == STATISTICS_FILE_ITEM
2239 || token == STATISTICS_FILE_ITEM_OLD) {
2240 int day = in.readInt();
2241 if (token == STATISTICS_FILE_ITEM_OLD) {
2242 day = day - 2009 + 14245; // Magic!
2243 }
2244 DayStats ds = new DayStats(day);
2245 ds.successCount = in.readInt();
2246 ds.successTime = in.readLong();
2247 ds.failureCount = in.readInt();
2248 ds.failureTime = in.readLong();
2249 if (index < mDayStats.length) {
2250 mDayStats[index] = ds;
2251 index++;
2252 }
2253 } else {
2254 // Ooops.
2255 Log.w(TAG, "Unknown stats token: " + token);
2256 break;
2257 }
2258 }
2259 } catch (java.io.IOException e) {
2260 Log.i(TAG, "No initial statistics");
2261 }
2262 }
Costin Manolache360e4542009-09-04 13:36:04 -07002263
Dianne Hackborn231cc602009-04-27 17:10:36 -07002264 /**
2265 * Write all sync statistics to the sync status file.
2266 */
2267 private void writeStatisticsLocked() {
2268 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002269
Dianne Hackborn231cc602009-04-27 17:10:36 -07002270 // The file is being written, so we don't need to have a scheduled
2271 // write until the next change.
2272 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002273
Dianne Hackborn231cc602009-04-27 17:10:36 -07002274 FileOutputStream fos = null;
2275 try {
2276 fos = mStatisticsFile.startWrite();
2277 Parcel out = Parcel.obtain();
2278 final int N = mDayStats.length;
2279 for (int i=0; i<N; i++) {
2280 DayStats ds = mDayStats[i];
2281 if (ds == null) {
2282 break;
2283 }
2284 out.writeInt(STATISTICS_FILE_ITEM);
2285 out.writeInt(ds.day);
2286 out.writeInt(ds.successCount);
2287 out.writeLong(ds.successTime);
2288 out.writeInt(ds.failureCount);
2289 out.writeLong(ds.failureTime);
2290 }
2291 out.writeInt(STATISTICS_FILE_END);
2292 fos.write(out.marshall());
2293 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002294
Dianne Hackborn231cc602009-04-27 17:10:36 -07002295 mStatisticsFile.finishWrite(fos);
2296 } catch (java.io.IOException e1) {
2297 Log.w(TAG, "Error writing stats", e1);
2298 if (fos != null) {
2299 mStatisticsFile.failWrite(fos);
2300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 }
2302 }
2303}