blob: 773e0fe206d6383f318cdfdaa57345343d69866e [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080017package android.content;
18
Dianne Hackborn231cc602009-04-27 17:10:36 -070019import com.android.internal.util.ArrayUtils;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080020import com.android.internal.util.FastXmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021
Jason parksa3cdaa52011-01-13 14:15:43 -060022import org.xmlpull.v1.XmlPullParser;
23import org.xmlpull.v1.XmlPullParserException;
24import org.xmlpull.v1.XmlSerializer;
25
Fred Quintanad9d2f112009-04-23 13:36:27 -070026import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070027import android.accounts.AccountAndUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070030import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.os.Bundle;
33import android.os.Environment;
34import android.os.Handler;
35import android.os.Message;
36import android.os.Parcel;
37import android.os.RemoteCallbackList;
38import android.os.RemoteException;
Dianne Hackborn39606a02012-07-31 17:54:35 -070039import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.util.Log;
Dianne Hackborn231cc602009-04-27 17:10:36 -070041import android.util.SparseArray;
42import android.util.Xml;
Jason parksa3cdaa52011-01-13 14:15:43 -060043import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
Dianne Hackborn231cc602009-04-27 17:10:36 -070045import java.io.File;
46import java.io.FileInputStream;
47import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070049import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070051import java.util.Iterator;
Ashish Sharma69d95de2012-04-11 17:27:24 -070052import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060053import java.util.TimeZone;
Jason parksa3cdaa52011-01-13 14:15:43 -060054import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
56/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070057 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070059 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060 * @hide
61 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070062public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064 private static final String TAG = "SyncManager";
Dianne Hackborn231cc602009-04-27 17:10:36 -070065 private static final boolean DEBUG_FILE = false;
Costin Manolache360e4542009-09-04 13:36:04 -070066
Amith Yamasani04e0d262012-02-14 11:50:53 -080067 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
68 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070069 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080070 private static final String XML_ATTR_ENABLED = "enabled";
71 private static final String XML_ATTR_USER = "user";
72 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
73
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080074 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
75
Dianne Hackborn231cc602009-04-27 17:10:36 -070076 // @VisibleForTesting
77 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
Dianne Hackborn231cc602009-04-27 17:10:36 -070079 /** Enum value for a sync start event. */
80 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
Dianne Hackborn231cc602009-04-27 17:10:36 -070082 /** Enum value for a sync stop event. */
83 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084
Dianne Hackborn231cc602009-04-27 17:10:36 -070085 // TODO: i18n -- grab these out of resources.
86 /** String names for the sync event types. */
87 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
Dianne Hackborn231cc602009-04-27 17:10:36 -070089 /** Enum value for a server-initiated sync. */
90 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
Dianne Hackborn231cc602009-04-27 17:10:36 -070092 /** Enum value for a local-initiated sync. */
93 public static final int SOURCE_LOCAL = 1;
94 /**
95 * Enum value for a poll-based sync (e.g., upon connection to
96 * network)
97 */
98 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 /** Enum value for a user-initiated sync. */
101 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800103 /** Enum value for a periodic sync. */
104 public static final int SOURCE_PERIODIC = 4;
105
Fred Quintana307da1a2010-01-21 14:24:20 -0800106 public static final long NOT_IN_BACKOFF_MODE = -1;
107
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700108 public static final Intent SYNC_CONNECTION_SETTING_CHANGED_INTENT =
Fred Quintanaac9385e2009-06-22 18:00:59 -0700109 new Intent("com.android.sync.SYNC_CONN_STATUS_CHANGED");
110
Dianne Hackborn231cc602009-04-27 17:10:36 -0700111 // TODO: i18n -- grab these out of resources.
112 /** String names for the sync source types. */
113 public static final String[] SOURCES = { "SERVER",
114 "LOCAL",
115 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800116 "USER",
117 "PERIODIC" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Dianne Hackborn231cc602009-04-27 17:10:36 -0700119 // The MESG column will contain one of these or one of the Error types.
120 public static final String MESG_SUCCESS = "success";
121 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700123 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700124
Dianne Hackborn231cc602009-04-27 17:10:36 -0700125 private static final int MSG_WRITE_STATUS = 1;
126 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700127
Dianne Hackborn231cc602009-04-27 17:10:36 -0700128 private static final int MSG_WRITE_STATISTICS = 2;
129 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700130
131 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700132
Fred Quintanac2e46912010-03-15 16:10:44 -0700133 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700134 private static final int ACCOUNTS_VERSION = 2;
135
136 private static HashMap<String, String> sAuthorityRenames;
137
138 static {
139 sAuthorityRenames = new HashMap<String, String>();
140 sAuthorityRenames.put("contacts", "com.android.contacts");
141 sAuthorityRenames.put("calendar", "com.android.calendar");
142 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700143
Dianne Hackborn231cc602009-04-27 17:10:36 -0700144 public static class PendingOperation {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700145 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800146 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700147 final int syncSource;
148 final String authority;
149 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800150 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700151
Dianne Hackborn231cc602009-04-27 17:10:36 -0700152 int authorityId;
153 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700154
Amith Yamasani04e0d262012-02-14 11:50:53 -0800155 PendingOperation(Account account, int userId, int source,
Fred Quintana307da1a2010-01-21 14:24:20 -0800156 String authority, Bundle extras, boolean expedited) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700157 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800158 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700159 this.syncSource = source;
160 this.authority = authority;
161 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800162 this.expedited = expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700163 this.authorityId = -1;
164 }
165
166 PendingOperation(PendingOperation other) {
167 this.account = other.account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800168 this.userId = other.userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700169 this.syncSource = other.syncSource;
170 this.authority = other.authority;
171 this.extras = other.extras;
172 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800173 this.expedited = other.expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 }
Costin Manolache360e4542009-09-04 13:36:04 -0700176
Dianne Hackborn231cc602009-04-27 17:10:36 -0700177 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800178 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700179 final HashMap<String, AuthorityInfo> authorities =
180 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700181
Amith Yamasani04e0d262012-02-14 11:50:53 -0800182 AccountInfo(AccountAndUser accountAndUser) {
183 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700184 }
185 }
Costin Manolache360e4542009-09-04 13:36:04 -0700186
Dianne Hackborn231cc602009-04-27 17:10:36 -0700187 public static class AuthorityInfo {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700188 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800189 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700190 final String authority;
191 final int ident;
192 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700193 int syncable;
Fred Quintana307da1a2010-01-21 14:24:20 -0800194 long backoffTime;
195 long backoffDelay;
196 long delayUntil;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800197 final ArrayList<Pair<Bundle, Long>> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700198
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700199 /**
200 * Copy constructor for making deep-ish copies. Only the bundles stored
201 * in periodic syncs can make unexpected changes.
202 *
203 * @param toCopy AuthorityInfo to be copied.
204 */
205 AuthorityInfo(AuthorityInfo toCopy) {
206 account = toCopy.account;
207 userId = toCopy.userId;
208 authority = toCopy.authority;
209 ident = toCopy.ident;
210 enabled = toCopy.enabled;
211 syncable = toCopy.syncable;
212 backoffTime = toCopy.backoffTime;
213 backoffDelay = toCopy.backoffDelay;
214 delayUntil = toCopy.delayUntil;
215 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
216 for (Pair<Bundle, Long> sync : toCopy.periodicSyncs) {
217 // Still not a perfect copy, because we are just copying the mappings.
218 periodicSyncs.add(Pair.create(new Bundle(sync.first), sync.second));
219 }
220 }
221
Amith Yamasani04e0d262012-02-14 11:50:53 -0800222 AuthorityInfo(Account account, int userId, String authority, int ident) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700223 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800224 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700225 this.authority = authority;
226 this.ident = ident;
Joe Onorato8294fad2009-07-15 16:08:44 -0700227 enabled = SYNC_ENABLED_DEFAULT;
Fred Quintana4a6679b2009-08-17 13:05:39 -0700228 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800229 backoffTime = -1; // if < 0 then we aren't in backoff mode
230 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800231 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
232 periodicSyncs.add(Pair.create(new Bundle(), DEFAULT_POLL_FREQUENCY_SECONDS));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700233 }
234 }
Costin Manolache360e4542009-09-04 13:36:04 -0700235
Dianne Hackborn231cc602009-04-27 17:10:36 -0700236 public static class SyncHistoryItem {
237 int authorityId;
238 int historyId;
239 long eventTime;
240 long elapsedTime;
241 int source;
242 int event;
243 long upstreamActivity;
244 long downstreamActivity;
245 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700246 boolean initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700247 }
Costin Manolache360e4542009-09-04 13:36:04 -0700248
Dianne Hackborn231cc602009-04-27 17:10:36 -0700249 public static class DayStats {
250 public final int day;
251 public int successCount;
252 public long successTime;
253 public int failureCount;
254 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700255
Dianne Hackborn231cc602009-04-27 17:10:36 -0700256 public DayStats(int day) {
257 this.day = day;
258 }
259 }
Costin Manolache360e4542009-09-04 13:36:04 -0700260
Amith Yamasani04e0d262012-02-14 11:50:53 -0800261 interface OnSyncRequestListener {
262 /**
263 * Called when a sync is needed on an account(s) due to some change in state.
264 * @param account
265 * @param userId
266 * @param authority
267 * @param extras
268 */
269 public void onSyncRequest(Account account, int userId, String authority, Bundle extras);
270 }
271
Dianne Hackborn231cc602009-04-27 17:10:36 -0700272 // Primary list of all syncable authorities. Also our global lock.
273 private final SparseArray<AuthorityInfo> mAuthorities =
274 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700275
Amith Yamasani04e0d262012-02-14 11:50:53 -0800276 private final HashMap<AccountAndUser, AccountInfo> mAccounts
277 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278
Dianne Hackborn231cc602009-04-27 17:10:36 -0700279 private final ArrayList<PendingOperation> mPendingOperations =
280 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700281
Amith Yamasani04e0d262012-02-14 11:50:53 -0800282 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
283 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700284
Dianne Hackborn231cc602009-04-27 17:10:36 -0700285 private final SparseArray<SyncStatusInfo> mSyncStatus =
286 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700287
Dianne Hackborn231cc602009-04-27 17:10:36 -0700288 private final ArrayList<SyncHistoryItem> mSyncHistory =
289 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700290
Dianne Hackborn231cc602009-04-27 17:10:36 -0700291 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
292 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700293
Fred Quintana77c560f2010-03-29 22:20:26 -0700294 private int mNextAuthorityId = 0;
295
Dianne Hackborn231cc602009-04-27 17:10:36 -0700296 // We keep 4 weeks of stats.
297 private final DayStats[] mDayStats = new DayStats[7*4];
298 private final Calendar mCal;
299 private int mYear;
300 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700301
Dianne Hackborn231cc602009-04-27 17:10:36 -0700302 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800303
Dianne Hackborn231cc602009-04-27 17:10:36 -0700304 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700305
Ashish Sharma69d95de2012-04-11 17:27:24 -0700306 private int mSyncRandomOffset;
307
Dianne Hackborn231cc602009-04-27 17:10:36 -0700308 /**
309 * This file contains the core engine state: all accounts and the
310 * settings for them. It must never be lost, and should be changed
311 * infrequently, so it is stored as an XML file.
312 */
313 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700314
Dianne Hackborn231cc602009-04-27 17:10:36 -0700315 /**
316 * This file contains the current sync status. We would like to retain
317 * it across boots, but its loss is not the end of the world, so we store
318 * this information as binary data.
319 */
320 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700321
Dianne Hackborn231cc602009-04-27 17:10:36 -0700322 /**
323 * This file contains sync statistics. This is purely debugging information
324 * so is written infrequently and can be thrown away at any time.
325 */
326 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700327
Dianne Hackborn231cc602009-04-27 17:10:36 -0700328 /**
329 * This file contains the pending sync operations. It is a binary file,
330 * which must be updated every time an operation is added or removed,
331 * so we have special handling of it.
332 */
333 private final AtomicFile mPendingFile;
334 private static final int PENDING_FINISH_TO_WRITE = 4;
335 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700336
Dianne Hackborn231cc602009-04-27 17:10:36 -0700337 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800338 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
339
340 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700341
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800342 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700345
Dianne Hackborn231cc602009-04-27 17:10:36 -0700346 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700347
Dianne Hackborn231cc602009-04-27 17:10:36 -0700348 File systemDir = new File(dataDir, "system");
349 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800350 syncDir.mkdirs();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700351 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
352 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
353 mPendingFile = new AtomicFile(new File(syncDir, "pending.bin"));
354 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700355
Dianne Hackborn231cc602009-04-27 17:10:36 -0700356 readAccountInfoLocked();
357 readStatusLocked();
358 readPendingOperationsLocked();
359 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700360 readAndDeleteLegacyAccountInfoLocked();
361 writeAccountInfoLocked();
362 writeStatusLocked();
363 writePendingOperationsLocked();
364 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 }
366
367 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800368 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 }
370
371 public static void init(Context context) {
372 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800373 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800375 // This call will return the correct directory whether Encrypted File Systems is
376 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600377 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800378 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 }
380
381 public static SyncStorageEngine getSingleton() {
382 if (sSyncStorageEngine == null) {
383 throw new IllegalStateException("not initialized");
384 }
385 return sSyncStorageEngine;
386 }
387
Amith Yamasani04e0d262012-02-14 11:50:53 -0800388 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
389 if (mSyncRequestListener == null) {
390 mSyncRequestListener = listener;
391 }
392 }
393
Dianne Hackborn231cc602009-04-27 17:10:36 -0700394 @Override public void handleMessage(Message msg) {
395 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700396 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700397 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700398 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700399 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700400 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700401 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 }
403 }
404 }
Costin Manolache360e4542009-09-04 13:36:04 -0700405
Ashish Sharma69d95de2012-04-11 17:27:24 -0700406 public int getSyncRandomOffset() {
407 return mSyncRandomOffset;
408 }
409
Dianne Hackborn231cc602009-04-27 17:10:36 -0700410 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
411 synchronized (mAuthorities) {
412 mChangeListeners.register(callback, mask);
413 }
414 }
Costin Manolache360e4542009-09-04 13:36:04 -0700415
Dianne Hackborn231cc602009-04-27 17:10:36 -0700416 public void removeStatusChangeListener(ISyncStatusObserver callback) {
417 synchronized (mAuthorities) {
418 mChangeListeners.unregister(callback);
419 }
420 }
Costin Manolache360e4542009-09-04 13:36:04 -0700421
Dianne Hackborn231cc602009-04-27 17:10:36 -0700422 private void reportChange(int which) {
423 ArrayList<ISyncStatusObserver> reports = null;
424 synchronized (mAuthorities) {
425 int i = mChangeListeners.beginBroadcast();
426 while (i > 0) {
427 i--;
428 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
429 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 continue;
431 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700432 if (reports == null) {
433 reports = new ArrayList<ISyncStatusObserver>(i);
434 }
435 reports.add(mChangeListeners.getBroadcastItem(i));
436 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700437 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700438 }
Costin Manolache360e4542009-09-04 13:36:04 -0700439
Fred Quintana77c560f2010-03-29 22:20:26 -0700440 if (Log.isLoggable(TAG, Log.VERBOSE)) {
441 Log.v(TAG, "reportChange " + which + " to: " + reports);
442 }
Costin Manolache360e4542009-09-04 13:36:04 -0700443
Dianne Hackborn231cc602009-04-27 17:10:36 -0700444 if (reports != null) {
445 int i = reports.size();
446 while (i > 0) {
447 i--;
448 try {
449 reports.get(i).onStatusChanged(which);
450 } catch (RemoteException e) {
451 // The remote callback list will take care of this for us.
452 }
453 }
454 }
455 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700456
Amith Yamasani04e0d262012-02-14 11:50:53 -0800457 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700458 synchronized (mAuthorities) {
459 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800460 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700461 "getSyncAutomatically");
462 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700463 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700464
Dianne Hackborn231cc602009-04-27 17:10:36 -0700465 int i = mAuthorities.size();
466 while (i > 0) {
467 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700468 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700469 if (authority.authority.equals(providerName)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800470 && authority.userId == userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700471 && authority.enabled) {
472 return true;
473 }
474 }
475 return false;
476 }
477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478
Amith Yamasani04e0d262012-02-14 11:50:53 -0800479 public void setSyncAutomatically(Account account, int userId, String providerName,
480 boolean sync) {
481 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
482 + ", user " + userId + " -> " + sync);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700483 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800484 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
485 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700486 if (authority.enabled == sync) {
487 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
488 return;
489 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700490 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700491 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700493
Fred Quintana77c560f2010-03-29 22:20:26 -0700494 if (sync) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800495 requestSync(account, userId, providerName, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700496 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700497 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 }
499
Amith Yamasani04e0d262012-02-14 11:50:53 -0800500 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700501 synchronized (mAuthorities) {
502 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800503 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintana5e787c42009-08-16 23:13:53 -0700504 "getIsSyncable");
505 if (authority == null) {
506 return -1;
507 }
508 return authority.syncable;
509 }
510
511 int i = mAuthorities.size();
512 while (i > 0) {
513 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700514 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700515 if (authority.authority.equals(providerName)) {
516 return authority.syncable;
517 }
518 }
519 return -1;
520 }
521 }
522
Amith Yamasani04e0d262012-02-14 11:50:53 -0800523 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700524 if (syncable > 1) {
525 syncable = 1;
526 } else if (syncable < -1) {
527 syncable = -1;
528 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800529 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName
530 + ", user " + userId + " -> " + syncable);
Fred Quintana5e787c42009-08-16 23:13:53 -0700531 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800532 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
533 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700534 if (authority.syncable == syncable) {
535 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
536 return;
537 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700538 authority.syncable = syncable;
539 writeAccountInfoLocked();
540 }
541
Fred Quintana77c560f2010-03-29 22:20:26 -0700542 if (syncable > 0) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800543 requestSync(account, userId, providerName, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700544 }
545 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
546 }
547
Amith Yamasani04e0d262012-02-14 11:50:53 -0800548 public Pair<Long, Long> getBackoff(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800549 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800550 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
551 "getBackoff");
Fred Quintana307da1a2010-01-21 14:24:20 -0800552 if (authority == null || authority.backoffTime < 0) {
553 return null;
554 }
555 return Pair.create(authority.backoffTime, authority.backoffDelay);
556 }
557 }
558
Amith Yamasani04e0d262012-02-14 11:50:53 -0800559 public void setBackoff(Account account, int userId, String providerName,
Fred Quintana307da1a2010-01-21 14:24:20 -0800560 long nextSyncTime, long nextDelay) {
561 if (Log.isLoggable(TAG, Log.VERBOSE)) {
562 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800563 + ", user " + userId
Fred Quintana307da1a2010-01-21 14:24:20 -0800564 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
565 }
566 boolean changed = false;
567 synchronized (mAuthorities) {
568 if (account == null || providerName == null) {
569 for (AccountInfo accountInfo : mAccounts.values()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800570 if (account != null && !account.equals(accountInfo.accountAndUser.account)
571 && userId != accountInfo.accountAndUser.userId) {
572 continue;
573 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800574 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
575 if (providerName != null && !providerName.equals(authorityInfo.authority)) {
576 continue;
577 }
578 if (authorityInfo.backoffTime != nextSyncTime
579 || authorityInfo.backoffDelay != nextDelay) {
580 authorityInfo.backoffTime = nextSyncTime;
581 authorityInfo.backoffDelay = nextDelay;
582 changed = true;
583 }
584 }
585 }
586 } else {
587 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800588 getOrCreateAuthorityLocked(account, userId, providerName, -1 /* ident */,
589 true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800590 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
591 return;
592 }
593 authority.backoffTime = nextSyncTime;
594 authority.backoffDelay = nextDelay;
595 changed = true;
596 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800597 }
598
599 if (changed) {
600 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
601 }
602 }
603
Alon Alberted1d2532011-02-15 14:02:14 -0800604 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800605 boolean changed = false;
606 synchronized (mAuthorities) {
607 for (AccountInfo accountInfo : mAccounts.values()) {
608 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
609 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
610 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
611 if (Log.isLoggable(TAG, Log.VERBOSE)) {
612 Log.v(TAG, "clearAllBackoffs:"
613 + " authority:" + authorityInfo.authority
Amith Yamasani04e0d262012-02-14 11:50:53 -0800614 + " account:" + accountInfo.accountAndUser.account.name
615 + " user:" + accountInfo.accountAndUser.userId
Alon Albert744e310f2010-12-14 11:37:20 -0800616 + " backoffTime was: " + authorityInfo.backoffTime
617 + " backoffDelay was: " + authorityInfo.backoffDelay);
618 }
619 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
620 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800621 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
622 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
Alon Albert744e310f2010-12-14 11:37:20 -0800623 changed = true;
624 }
625 }
626 }
627 }
628
629 if (changed) {
630 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
631 }
632 }
633
Amith Yamasani04e0d262012-02-14 11:50:53 -0800634 public void setDelayUntilTime(Account account, int userId, String providerName,
635 long delayUntil) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800636 if (Log.isLoggable(TAG, Log.VERBOSE)) {
637 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800638 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800639 }
640 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800641 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800642 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800643 if (authority.delayUntil == delayUntil) {
644 return;
645 }
646 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800647 }
648
649 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
650 }
651
Amith Yamasani04e0d262012-02-14 11:50:53 -0800652 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800653 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800654 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
655 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800656 if (authority == null) {
657 return 0;
658 }
659 return authority.delayUntil;
660 }
661 }
662
Amith Yamasani04e0d262012-02-14 11:50:53 -0800663 private void updateOrRemovePeriodicSync(Account account, int userId, String providerName,
664 Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800665 long period, boolean add) {
666 if (period <= 0) {
667 period = 0;
668 }
669 if (extras == null) {
670 extras = new Bundle();
671 }
672 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800673 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", user " + userId
674 + ", provider " + providerName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800675 + " -> period " + period + ", extras " + extras);
676 }
677 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700678 try {
679 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800680 getOrCreateAuthorityLocked(account, userId, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700681 if (add) {
682 // add this periodic sync if one with the same extras doesn't already
683 // exist in the periodicSyncs array
684 boolean alreadyPresent = false;
685 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
686 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
687 final Bundle existingExtras = syncInfo.first;
688 if (equals(existingExtras, extras)) {
689 if (syncInfo.second == period) {
690 return;
691 }
692 authority.periodicSyncs.set(i, Pair.create(extras, period));
693 alreadyPresent = true;
694 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800695 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700696 }
697 // if we added an entry to the periodicSyncs array also add an entry to
698 // the periodic syncs status to correspond to it
699 if (!alreadyPresent) {
700 authority.periodicSyncs.add(Pair.create(extras, period));
701 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
702 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
703 }
704 } else {
705 // remove any periodic syncs that match the authority and extras
706 SyncStatusInfo status = mSyncStatus.get(authority.ident);
707 boolean changed = false;
708 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
709 int i = 0;
710 while (iterator.hasNext()) {
711 Pair<Bundle, Long> syncInfo = iterator.next();
712 if (equals(syncInfo.first, extras)) {
713 iterator.remove();
714 changed = true;
715 // if we removed an entry from the periodicSyncs array also
716 // remove the corresponding entry from the status
717 if (status != null) {
718 status.removePeriodicSyncTime(i);
719 }
720 } else {
721 i++;
722 }
723 }
724 if (!changed) {
725 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800726 }
727 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700728 } finally {
729 writeAccountInfoLocked();
730 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800731 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800732 }
733
734 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
735 }
736
Amith Yamasani04e0d262012-02-14 11:50:53 -0800737 public void addPeriodicSync(Account account, int userId, String providerName, Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800738 long pollFrequency) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800739 updateOrRemovePeriodicSync(account, userId, providerName, extras, pollFrequency,
740 true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800741 }
742
Amith Yamasani04e0d262012-02-14 11:50:53 -0800743 public void removePeriodicSync(Account account, int userId, String providerName,
744 Bundle extras) {
745 updateOrRemovePeriodicSync(account, userId, providerName, extras, 0 /* period, ignored */,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800746 false /* remove */);
747 }
748
Amith Yamasani04e0d262012-02-14 11:50:53 -0800749 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800750 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
751 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800752 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
753 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800754 if (authority != null) {
755 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800756 syncs.add(new PeriodicSync(account, providerName, item.first,
757 item.second));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800758 }
759 }
760 }
761 return syncs;
762 }
763
Amith Yamasani04e0d262012-02-14 11:50:53 -0800764 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700765 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800766 Boolean auto = mMasterSyncAutomatically.get(userId);
767 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700768 return;
769 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800770 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700771 writeAccountInfoLocked();
772 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700773 if (flag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800774 requestSync(null, userId, null, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700775 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700776 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
777 mContext.sendBroadcast(SYNC_CONNECTION_SETTING_CHANGED_INTENT);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779
Amith Yamasani04e0d262012-02-14 11:50:53 -0800780 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700781 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800782 Boolean auto = mMasterSyncAutomatically.get(userId);
783 return auto == null ? true : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700784 }
785 }
Costin Manolache360e4542009-09-04 13:36:04 -0700786
Amith Yamasani04e0d262012-02-14 11:50:53 -0800787 public AuthorityInfo getOrCreateAuthority(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700788 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800789 return getOrCreateAuthorityLocked(account, userId, authority,
Fred Quintana1bbcd102010-02-10 10:04:33 -0800790 -1 /* assign a new identifier if creating a new authority */,
791 true /* write to storage if this results in a change */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700792 }
793 }
Costin Manolache360e4542009-09-04 13:36:04 -0700794
Amith Yamasani04e0d262012-02-14 11:50:53 -0800795 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700796 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800797 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700798 }
799 }
800
Dianne Hackborn231cc602009-04-27 17:10:36 -0700801 public AuthorityInfo getAuthority(int authorityId) {
802 synchronized (mAuthorities) {
803 return mAuthorities.get(authorityId);
804 }
805 }
Costin Manolache360e4542009-09-04 13:36:04 -0700806
Dianne Hackborn231cc602009-04-27 17:10:36 -0700807 /**
808 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700809 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700810 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800811 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700812 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800813 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700814 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700815 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800816 && ainfo.authority.equals(authority)
817 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700818 return true;
819 }
820 }
821 }
Costin Manolache360e4542009-09-04 13:36:04 -0700822
Dianne Hackborn231cc602009-04-27 17:10:36 -0700823 return false;
824 }
Costin Manolache360e4542009-09-04 13:36:04 -0700825
Dianne Hackborn231cc602009-04-27 17:10:36 -0700826 public PendingOperation insertIntoPending(PendingOperation op) {
827 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700828 if (Log.isLoggable(TAG, Log.VERBOSE)) {
829 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800830 + " user=" + op.userId
831 + " auth=" + op.authority
832 + " src=" + op.syncSource
833 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700834 }
Costin Manolache360e4542009-09-04 13:36:04 -0700835
Amith Yamasani04e0d262012-02-14 11:50:53 -0800836 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700837 op.authority,
838 -1 /* desired identifier */,
839 true /* write accounts to storage */);
840 if (authority == null) {
841 return null;
842 }
Costin Manolache360e4542009-09-04 13:36:04 -0700843
Dianne Hackborn231cc602009-04-27 17:10:36 -0700844 op = new PendingOperation(op);
845 op.authorityId = authority.ident;
846 mPendingOperations.add(op);
847 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700848
Dianne Hackborn231cc602009-04-27 17:10:36 -0700849 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
850 status.pending = true;
851 }
Costin Manolache360e4542009-09-04 13:36:04 -0700852
Fred Quintanaac9385e2009-06-22 18:00:59 -0700853 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700854 return op;
855 }
856
857 public boolean deleteFromPending(PendingOperation op) {
858 boolean res = false;
859 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700860 if (Log.isLoggable(TAG, Log.VERBOSE)) {
861 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800862 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700863 + " auth=" + op.authority
864 + " src=" + op.syncSource
865 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700866 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700867 if (mPendingOperations.remove(op)) {
868 if (mPendingOperations.size() == 0
869 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
870 writePendingOperationsLocked();
871 mNumPendingFinished = 0;
872 } else {
873 mNumPendingFinished++;
874 }
Costin Manolache360e4542009-09-04 13:36:04 -0700875
Amith Yamasani04e0d262012-02-14 11:50:53 -0800876 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700877 "deleteFromPending");
878 if (authority != null) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700879 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "removing - " + authority);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700880 final int N = mPendingOperations.size();
881 boolean morePending = false;
882 for (int i=0; i<N; i++) {
883 PendingOperation cur = mPendingOperations.get(i);
884 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800885 && cur.authority.equals(op.authority)
886 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700887 morePending = true;
888 break;
889 }
890 }
Costin Manolache360e4542009-09-04 13:36:04 -0700891
Dianne Hackborn231cc602009-04-27 17:10:36 -0700892 if (!morePending) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700893 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700894 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
895 status.pending = false;
896 }
897 }
Costin Manolache360e4542009-09-04 13:36:04 -0700898
Dianne Hackborn231cc602009-04-27 17:10:36 -0700899 res = true;
900 }
901 }
Costin Manolache360e4542009-09-04 13:36:04 -0700902
Fred Quintanaac9385e2009-06-22 18:00:59 -0700903 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700904 return res;
905 }
906
Dianne Hackborn231cc602009-04-27 17:10:36 -0700907 /**
908 * Return a copy of the current array of pending operations. The
909 * PendingOperation objects are the real objects stored inside, so that
910 * they can be used with deleteFromPending().
911 */
912 public ArrayList<PendingOperation> getPendingOperations() {
913 synchronized (mAuthorities) {
914 return new ArrayList<PendingOperation>(mPendingOperations);
915 }
916 }
Costin Manolache360e4542009-09-04 13:36:04 -0700917
Dianne Hackborn231cc602009-04-27 17:10:36 -0700918 /**
919 * Return the number of currently pending operations.
920 */
921 public int getPendingOperationCount() {
922 synchronized (mAuthorities) {
923 return mPendingOperations.size();
924 }
925 }
Costin Manolache360e4542009-09-04 13:36:04 -0700926
Dianne Hackborn231cc602009-04-27 17:10:36 -0700927 /**
928 * Called when the set of account has changed, given the new array of
929 * active accounts.
930 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800931 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700932 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700933 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.w(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700934 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
935 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
936 while (accIt.hasNext()) {
937 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800938 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
939 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700940 // This account no longer exists...
Fred Quintana77c560f2010-03-29 22:20:26 -0700941 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800942 Log.w(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700943 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700944 for (AuthorityInfo auth : acc.authorities.values()) {
945 removing.put(auth.ident, auth);
946 }
947 accIt.remove();
948 }
949 }
Costin Manolache360e4542009-09-04 13:36:04 -0700950
Dianne Hackborn231cc602009-04-27 17:10:36 -0700951 // Clean out all data structures.
952 int i = removing.size();
953 if (i > 0) {
954 while (i > 0) {
955 i--;
956 int ident = removing.keyAt(i);
957 mAuthorities.remove(ident);
958 int j = mSyncStatus.size();
959 while (j > 0) {
960 j--;
961 if (mSyncStatus.keyAt(j) == ident) {
962 mSyncStatus.remove(mSyncStatus.keyAt(j));
963 }
964 }
965 j = mSyncHistory.size();
966 while (j > 0) {
967 j--;
968 if (mSyncHistory.get(j).authorityId == ident) {
969 mSyncHistory.remove(j);
970 }
971 }
972 }
973 writeAccountInfoLocked();
974 writeStatusLocked();
975 writePendingOperationsLocked();
976 writeStatisticsLocked();
977 }
978 }
979 }
980
981 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700982 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
983 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700984 */
Fred Quintana918339a2010-10-05 14:00:39 -0700985 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
986 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700987 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -0700988 if (Log.isLoggable(TAG, Log.VERBOSE)) {
989 Log.v(TAG, "setActiveSync: account="
990 + activeSyncContext.mSyncOperation.account
991 + " auth=" + activeSyncContext.mSyncOperation.authority
992 + " src=" + activeSyncContext.mSyncOperation.syncSource
993 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700994 }
Fred Quintana918339a2010-10-05 14:00:39 -0700995 AuthorityInfo authority = getOrCreateAuthorityLocked(
996 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -0800997 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -0700998 activeSyncContext.mSyncOperation.authority,
999 -1 /* assign a new identifier if creating a new authority */,
1000 true /* write to storage if this results in a change */);
1001 syncInfo = new SyncInfo(authority.ident,
1002 authority.account, authority.authority,
1003 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001004 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001005 }
Costin Manolache360e4542009-09-04 13:36:04 -07001006
Fred Quintana918339a2010-10-05 14:00:39 -07001007 reportActiveChange();
1008 return syncInfo;
1009 }
1010
1011 /**
1012 * Called to indicate that a previously active sync is no longer active.
1013 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001014 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001015 synchronized (mAuthorities) {
1016 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001017 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1018 + " user=" + userId
1019 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001020 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001021 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001022 }
1023
1024 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001025 }
1026
1027 /**
1028 * To allow others to send active change reports, to poke clients.
1029 */
1030 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001031 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001032 }
Costin Manolache360e4542009-09-04 13:36:04 -07001033
Dianne Hackborn231cc602009-04-27 17:10:36 -07001034 /**
1035 * Note that sync has started for the given account and authority.
1036 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001037 public long insertStartSyncEvent(Account accountName, int userId, String authorityName,
Fred Quintanadc475562012-05-04 15:51:54 -07001038 long now, int source, boolean initialization) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001039 long id;
1040 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001041 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001042 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001043 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001044 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001045 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001046 "insertStartSyncEvent");
1047 if (authority == null) {
1048 return -1;
1049 }
1050 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001051 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001052 item.authorityId = authority.ident;
1053 item.historyId = mNextHistoryId++;
1054 if (mNextHistoryId < 0) mNextHistoryId = 0;
1055 item.eventTime = now;
1056 item.source = source;
1057 item.event = EVENT_START;
1058 mSyncHistory.add(0, item);
1059 while (mSyncHistory.size() > MAX_HISTORY) {
1060 mSyncHistory.remove(mSyncHistory.size()-1);
1061 }
1062 id = item.historyId;
Fred Quintana77c560f2010-03-29 22:20:26 -07001063 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001064 }
Costin Manolache360e4542009-09-04 13:36:04 -07001065
Fred Quintanaac9385e2009-06-22 18:00:59 -07001066 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001067 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001070 public static boolean equals(Bundle b1, Bundle b2) {
1071 if (b1.size() != b2.size()) {
1072 return false;
1073 }
1074 if (b1.isEmpty()) {
1075 return true;
1076 }
1077 for (String key : b1.keySet()) {
1078 if (!b2.containsKey(key)) {
1079 return false;
1080 }
1081 if (!b1.get(key).equals(b2.get(key))) {
1082 return false;
1083 }
1084 }
1085 return true;
1086 }
1087
Fred Quintana77c560f2010-03-29 22:20:26 -07001088 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001090 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001091 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1092 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1093 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001094 SyncHistoryItem item = null;
1095 int i = mSyncHistory.size();
1096 while (i > 0) {
1097 i--;
1098 item = mSyncHistory.get(i);
1099 if (item.historyId == historyId) {
1100 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001102 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 }
Costin Manolache360e4542009-09-04 13:36:04 -07001104
Dianne Hackborn231cc602009-04-27 17:10:36 -07001105 if (item == null) {
1106 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1107 return;
1108 }
Costin Manolache360e4542009-09-04 13:36:04 -07001109
Dianne Hackborn231cc602009-04-27 17:10:36 -07001110 item.elapsedTime = elapsedTime;
1111 item.event = EVENT_STOP;
1112 item.mesg = resultMessage;
1113 item.downstreamActivity = downstreamActivity;
1114 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001115
Dianne Hackborn231cc602009-04-27 17:10:36 -07001116 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001117
Dianne Hackborn231cc602009-04-27 17:10:36 -07001118 status.numSyncs++;
1119 status.totalElapsedTime += elapsedTime;
1120 switch (item.source) {
1121 case SOURCE_LOCAL:
1122 status.numSourceLocal++;
1123 break;
1124 case SOURCE_POLL:
1125 status.numSourcePoll++;
1126 break;
1127 case SOURCE_USER:
1128 status.numSourceUser++;
1129 break;
1130 case SOURCE_SERVER:
1131 status.numSourceServer++;
1132 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001133 case SOURCE_PERIODIC:
1134 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001135 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001136 }
Costin Manolache360e4542009-09-04 13:36:04 -07001137
Dianne Hackborn231cc602009-04-27 17:10:36 -07001138 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001139 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001140 if (mDayStats[0] == null) {
1141 mDayStats[0] = new DayStats(day);
1142 } else if (day != mDayStats[0].day) {
1143 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1144 mDayStats[0] = new DayStats(day);
1145 writeStatisticsNow = true;
1146 } else if (mDayStats[0] == null) {
1147 }
1148 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001149
Dianne Hackborn231cc602009-04-27 17:10:36 -07001150 final long lastSyncTime = (item.eventTime + elapsedTime);
1151 boolean writeStatusNow = false;
1152 if (MESG_SUCCESS.equals(resultMessage)) {
1153 // - if successful, update the successful columns
1154 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1155 writeStatusNow = true;
1156 }
1157 status.lastSuccessTime = lastSyncTime;
1158 status.lastSuccessSource = item.source;
1159 status.lastFailureTime = 0;
1160 status.lastFailureSource = -1;
1161 status.lastFailureMesg = null;
1162 status.initialFailureTime = 0;
1163 ds.successCount++;
1164 ds.successTime += elapsedTime;
1165 } else if (!MESG_CANCELED.equals(resultMessage)) {
1166 if (status.lastFailureTime == 0) {
1167 writeStatusNow = true;
1168 }
1169 status.lastFailureTime = lastSyncTime;
1170 status.lastFailureSource = item.source;
1171 status.lastFailureMesg = resultMessage;
1172 if (status.initialFailureTime == 0) {
1173 status.initialFailureTime = lastSyncTime;
1174 }
1175 ds.failureCount++;
1176 ds.failureTime += elapsedTime;
1177 }
Costin Manolache360e4542009-09-04 13:36:04 -07001178
Dianne Hackborn231cc602009-04-27 17:10:36 -07001179 if (writeStatusNow) {
1180 writeStatusLocked();
1181 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1182 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1183 WRITE_STATUS_DELAY);
1184 }
1185 if (writeStatisticsNow) {
1186 writeStatisticsLocked();
1187 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1188 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1189 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001190 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001191 }
Costin Manolache360e4542009-09-04 13:36:04 -07001192
Fred Quintanaac9385e2009-06-22 18:00:59 -07001193 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001194 }
1195
1196 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001197 * Return a list of the currently active syncs. Note that the returned items are the
1198 * real, live active sync objects, so be careful what you do with it.
1199 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001200 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001201 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001202 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1203 if (syncs == null) {
1204 syncs = new ArrayList<SyncInfo>();
1205 mCurrentSyncs.put(userId, syncs);
1206 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001207 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001208 }
1209 }
Costin Manolache360e4542009-09-04 13:36:04 -07001210
Dianne Hackborn231cc602009-04-27 17:10:36 -07001211 /**
1212 * Return an array of the current sync status for all authorities. Note
1213 * that the objects inside the array are the real, live status objects,
1214 * so be careful what you do with them.
1215 */
1216 public ArrayList<SyncStatusInfo> getSyncStatus() {
1217 synchronized (mAuthorities) {
1218 final int N = mSyncStatus.size();
1219 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1220 for (int i=0; i<N; i++) {
1221 ops.add(mSyncStatus.valueAt(i));
1222 }
1223 return ops;
1224 }
1225 }
Costin Manolache360e4542009-09-04 13:36:04 -07001226
Dianne Hackborn231cc602009-04-27 17:10:36 -07001227 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001228 * Return an array of the current authorities. Note
1229 * that the objects inside the array are the real, live objects,
1230 * so be careful what you do with them.
1231 */
1232 public ArrayList<AuthorityInfo> getAuthorities() {
1233 synchronized (mAuthorities) {
1234 final int N = mAuthorities.size();
1235 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1236 for (int i=0; i<N; i++) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -07001237 // Make deep copy because AuthorityInfo syncs are liable to change.
1238 infos.add(new AuthorityInfo(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001239 }
1240 return infos;
1241 }
1242 }
1243
1244 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001245 * Returns the status that matches the authority and account.
1246 *
1247 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001248 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001249 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001250 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001251 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1252 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001253 if (account == null || authority == null) {
1254 throw new IllegalArgumentException();
1255 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001256 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001257 final int N = mSyncStatus.size();
1258 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001259 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001260 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001261
Amith Yamasani04e0d262012-02-14 11:50:53 -08001262 if (ainfo != null && ainfo.authority.equals(authority)
1263 && ainfo.userId == userId
1264 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001265 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001266 }
1267 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001268 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001269 }
1270 }
Costin Manolache360e4542009-09-04 13:36:04 -07001271
Dianne Hackborn231cc602009-04-27 17:10:36 -07001272 /**
1273 * Return true if the pending status is true of any matching authorities.
1274 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001275 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001276 synchronized (mAuthorities) {
1277 final int N = mSyncStatus.size();
1278 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001279 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001280 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1281 if (ainfo == null) {
1282 continue;
1283 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001284 if (userId != ainfo.userId) {
1285 continue;
1286 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001287 if (account != null && !ainfo.account.equals(account)) {
1288 continue;
1289 }
1290 if (ainfo.authority.equals(authority) && cur.pending) {
1291 return true;
1292 }
1293 }
1294 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 }
1296 }
1297
1298 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001299 * Return an array of the current sync status for all authorities. Note
1300 * that the objects inside the array are the real, live status objects,
1301 * so be careful what you do with them.
1302 */
1303 public ArrayList<SyncHistoryItem> getSyncHistory() {
1304 synchronized (mAuthorities) {
1305 final int N = mSyncHistory.size();
1306 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1307 for (int i=0; i<N; i++) {
1308 items.add(mSyncHistory.get(i));
1309 }
1310 return items;
1311 }
1312 }
Costin Manolache360e4542009-09-04 13:36:04 -07001313
Dianne Hackborn231cc602009-04-27 17:10:36 -07001314 /**
1315 * Return an array of the current per-day statistics. Note
1316 * that the objects inside the array are the real, live status objects,
1317 * so be careful what you do with them.
1318 */
1319 public DayStats[] getDayStatistics() {
1320 synchronized (mAuthorities) {
1321 DayStats[] ds = new DayStats[mDayStats.length];
1322 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1323 return ds;
1324 }
1325 }
Costin Manolache360e4542009-09-04 13:36:04 -07001326
Dianne Hackborn55280a92009-05-07 15:53:46 -07001327 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001328 mCal.setTimeInMillis(System.currentTimeMillis());
1329 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1330 if (mYear != mCal.get(Calendar.YEAR)) {
1331 mYear = mCal.get(Calendar.YEAR);
1332 mCal.clear();
1333 mCal.set(Calendar.YEAR, mYear);
1334 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1335 }
1336 return dayOfYear + mYearInDays;
1337 }
Costin Manolache360e4542009-09-04 13:36:04 -07001338
Dianne Hackborn231cc602009-04-27 17:10:36 -07001339 /**
1340 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001341 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001342 * @param accountName The name of the account for the authority.
1343 * @param authorityName The name of the authority itself.
1344 * @param tag If non-null, this will be used in a log message if the
1345 * requested authority does not exist.
1346 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001347 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001348 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001349 AccountAndUser au = new AccountAndUser(accountName, userId);
1350 AccountInfo accountInfo = mAccounts.get(au);
1351 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001352 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001353 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001354 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001355 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001356 }
1357 return null;
1358 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001359 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001360 if (authority == null) {
1361 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001362 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1363 Log.v(TAG, tag + ": unknown authority " + authorityName);
1364 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001365 }
1366 return null;
1367 }
Costin Manolache360e4542009-09-04 13:36:04 -07001368
Dianne Hackborn231cc602009-04-27 17:10:36 -07001369 return authority;
1370 }
Costin Manolache360e4542009-09-04 13:36:04 -07001371
Amith Yamasani04e0d262012-02-14 11:50:53 -08001372 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001373 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001374 AccountAndUser au = new AccountAndUser(accountName, userId);
1375 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001376 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001377 account = new AccountInfo(au);
1378 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001379 }
1380 AuthorityInfo authority = account.authorities.get(authorityName);
1381 if (authority == null) {
1382 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001383 ident = mNextAuthorityId;
1384 mNextAuthorityId++;
1385 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001386 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001387 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1388 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001389 + ", user " + userId
1390 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001391 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001392 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001393 account.authorities.put(authorityName, authority);
1394 mAuthorities.put(ident, authority);
1395 if (doWrite) {
1396 writeAccountInfoLocked();
1397 }
1398 }
Costin Manolache360e4542009-09-04 13:36:04 -07001399
Dianne Hackborn231cc602009-04-27 17:10:36 -07001400 return authority;
1401 }
Costin Manolache360e4542009-09-04 13:36:04 -07001402
Amith Yamasani04e0d262012-02-14 11:50:53 -08001403 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1404 boolean doWrite) {
1405 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001406 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001407 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1408 if (authorityInfo != null) {
1409 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001410 if (doWrite) {
1411 writeAccountInfoLocked();
1412 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001413 }
1414 }
1415 }
1416
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001417 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1418 synchronized (mAuthorities) {
1419 return getOrCreateSyncStatusLocked(authority.ident);
1420 }
1421 }
1422
Dianne Hackborn231cc602009-04-27 17:10:36 -07001423 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1424 SyncStatusInfo status = mSyncStatus.get(authorityId);
1425 if (status == null) {
1426 status = new SyncStatusInfo(authorityId);
1427 mSyncStatus.put(authorityId, status);
1428 }
1429 return status;
1430 }
Costin Manolache360e4542009-09-04 13:36:04 -07001431
Dianne Hackborn55280a92009-05-07 15:53:46 -07001432 public void writeAllState() {
1433 synchronized (mAuthorities) {
1434 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001435
Dianne Hackborn55280a92009-05-07 15:53:46 -07001436 if (mNumPendingFinished > 0) {
1437 // Only write these if they are out of date.
1438 writePendingOperationsLocked();
1439 }
Costin Manolache360e4542009-09-04 13:36:04 -07001440
Dianne Hackborn55280a92009-05-07 15:53:46 -07001441 // Just always write these... they are likely out of date.
1442 writeStatusLocked();
1443 writeStatisticsLocked();
1444 }
1445 }
Costin Manolache360e4542009-09-04 13:36:04 -07001446
Dianne Hackborn231cc602009-04-27 17:10:36 -07001447 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001448 * public for testing
1449 */
1450 public void clearAndReadState() {
1451 synchronized (mAuthorities) {
1452 mAuthorities.clear();
1453 mAccounts.clear();
1454 mPendingOperations.clear();
1455 mSyncStatus.clear();
1456 mSyncHistory.clear();
1457
1458 readAccountInfoLocked();
1459 readStatusLocked();
1460 readPendingOperationsLocked();
1461 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001462 readAndDeleteLegacyAccountInfoLocked();
1463 writeAccountInfoLocked();
1464 writeStatusLocked();
1465 writePendingOperationsLocked();
1466 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001467 }
1468 }
1469
1470 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001471 * Read all account information back in to the initial engine state.
1472 */
1473 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001474 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001475 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001477 fis = mAccountInfoFile.openRead();
1478 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1479 XmlPullParser parser = Xml.newPullParser();
1480 parser.setInput(fis, null);
1481 int eventType = parser.getEventType();
1482 while (eventType != XmlPullParser.START_TAG) {
1483 eventType = parser.next();
1484 }
1485 String tagName = parser.getName();
1486 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001487 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001488 String versionString = parser.getAttributeValue(null, "version");
1489 int version;
1490 try {
1491 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1492 } catch (NumberFormatException e) {
1493 version = 0;
1494 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001495 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001496 try {
1497 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1498 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1499 } catch (NumberFormatException e) {
1500 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001501 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001502 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1503 try {
1504 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1505 } catch (NumberFormatException e) {
1506 mSyncRandomOffset = 0;
1507 }
1508 if (mSyncRandomOffset == 0) {
1509 Random random = new Random(System.currentTimeMillis());
1510 mSyncRandomOffset = random.nextInt(86400);
1511 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001512 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001513 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001514 AuthorityInfo authority = null;
1515 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001516 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001517 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001518 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001519 if (parser.getDepth() == 2) {
1520 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001521 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001522 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001523 if (authority.ident > highestAuthorityId) {
1524 highestAuthorityId = authority.ident;
1525 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001526 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1527 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001528 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001529 } else if (parser.getDepth() == 3) {
1530 if ("periodicSync".equals(tagName) && authority != null) {
1531 periodicSync = parsePeriodicSync(parser, authority);
1532 }
1533 } else if (parser.getDepth() == 4 && periodicSync != null) {
1534 if ("extra".equals(tagName)) {
1535 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001536 }
1537 }
1538 }
1539 eventType = parser.next();
1540 } while (eventType != XmlPullParser.END_DOCUMENT);
1541 }
1542 } catch (XmlPullParserException e) {
1543 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001544 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001545 } catch (java.io.IOException e) {
1546 if (fis == null) Log.i(TAG, "No initial accounts");
1547 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001548 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001549 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001550 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001551 if (fis != null) {
1552 try {
1553 fis.close();
1554 } catch (java.io.IOException e1) {
1555 }
1556 }
1557 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001558
Fred Quintana77c560f2010-03-29 22:20:26 -07001559 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001560 }
Costin Manolache360e4542009-09-04 13:36:04 -07001561
Fred Quintanafb084402010-03-23 17:57:03 -07001562 /**
1563 * some authority names have changed. copy over their settings and delete the old ones
1564 * @return true if a change was made
1565 */
1566 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1567 boolean writeNeeded = false;
1568
1569 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1570 final int N = mAuthorities.size();
1571 for (int i=0; i<N; i++) {
1572 AuthorityInfo authority = mAuthorities.valueAt(i);
1573 // skip this authority if it isn't one of the renamed ones
1574 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1575 if (newAuthorityName == null) {
1576 continue;
1577 }
1578
1579 // remember this authority so we can remove it later. we can't remove it
1580 // now without messing up this loop iteration
1581 authoritiesToRemove.add(authority);
1582
1583 // this authority isn't enabled, no need to copy it to the new authority name since
1584 // the default is "disabled"
1585 if (!authority.enabled) {
1586 continue;
1587 }
1588
1589 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001590 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1591 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001592 continue;
1593 }
1594
1595 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001596 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001597 newAuthority.enabled = true;
1598 writeNeeded = true;
1599 }
1600
1601 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001602 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1603 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001604 writeNeeded = true;
1605 }
1606
1607 return writeNeeded;
1608 }
1609
Amith Yamasani04e0d262012-02-14 11:50:53 -08001610 private void parseListenForTickles(XmlPullParser parser) {
1611 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1612 int userId = 0;
1613 try {
1614 userId = Integer.parseInt(user);
1615 } catch (NumberFormatException e) {
1616 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1617 } catch (NullPointerException e) {
1618 Log.e(TAG, "the user in listen-for-tickles is null", e);
1619 }
1620 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1621 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1622 mMasterSyncAutomatically.put(userId, listen);
1623 }
1624
Fred Quintanac2e46912010-03-15 16:10:44 -07001625 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001626 AuthorityInfo authority = null;
1627 int id = -1;
1628 try {
1629 id = Integer.parseInt(parser.getAttributeValue(
1630 null, "id"));
1631 } catch (NumberFormatException e) {
1632 Log.e(TAG, "error parsing the id of the authority", e);
1633 } catch (NullPointerException e) {
1634 Log.e(TAG, "the id of the authority is null", e);
1635 }
1636 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001637 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001638 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001639 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001640 String accountName = parser.getAttributeValue(null, "account");
1641 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001642 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1643 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001644 if (accountType == null) {
1645 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001646 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001647 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001648 authority = mAuthorities.get(id);
1649 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1650 + accountName + " auth=" + authorityName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001651 + " user=" + userId
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001652 + " enabled=" + enabled
1653 + " syncable=" + syncable);
1654 if (authority == null) {
1655 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1656 authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001657 new Account(accountName, accountType), userId, authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001658 // If the version is 0 then we are upgrading from a file format that did not
1659 // know about periodic syncs. In that case don't clear the list since we
1660 // want the default, which is a daily periodioc sync.
1661 // Otherwise clear out this default list since we will populate it later with
1662 // the periodic sync descriptions that are read from the configuration file.
1663 if (version > 0) {
1664 authority.periodicSyncs.clear();
1665 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001666 }
1667 if (authority != null) {
1668 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1669 if ("unknown".equals(syncable)) {
1670 authority.syncable = -1;
1671 } else {
1672 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001673 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001674 }
1675 } else {
1676 Log.w(TAG, "Failure adding authority: account="
1677 + accountName + " auth=" + authorityName
1678 + " enabled=" + enabled
1679 + " syncable=" + syncable);
1680 }
1681 }
1682
1683 return authority;
1684 }
1685
1686 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1687 Bundle extras = new Bundle();
1688 String periodValue = parser.getAttributeValue(null, "period");
1689 final long period;
1690 try {
1691 period = Long.parseLong(periodValue);
1692 } catch (NumberFormatException e) {
1693 Log.e(TAG, "error parsing the period of a periodic sync", e);
1694 return null;
1695 } catch (NullPointerException e) {
1696 Log.e(TAG, "the period of a periodic sync is null", e);
1697 return null;
1698 }
1699 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1700 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001701
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001702 return periodicSync;
1703 }
1704
1705 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1706 final Bundle extras = periodicSync.first;
1707 String name = parser.getAttributeValue(null, "name");
1708 String type = parser.getAttributeValue(null, "type");
1709 String value1 = parser.getAttributeValue(null, "value1");
1710 String value2 = parser.getAttributeValue(null, "value2");
1711
1712 try {
1713 if ("long".equals(type)) {
1714 extras.putLong(name, Long.parseLong(value1));
1715 } else if ("integer".equals(type)) {
1716 extras.putInt(name, Integer.parseInt(value1));
1717 } else if ("double".equals(type)) {
1718 extras.putDouble(name, Double.parseDouble(value1));
1719 } else if ("float".equals(type)) {
1720 extras.putFloat(name, Float.parseFloat(value1));
1721 } else if ("boolean".equals(type)) {
1722 extras.putBoolean(name, Boolean.parseBoolean(value1));
1723 } else if ("string".equals(type)) {
1724 extras.putString(name, value1);
1725 } else if ("account".equals(type)) {
1726 extras.putParcelable(name, new Account(value1, value2));
1727 }
1728 } catch (NumberFormatException e) {
1729 Log.e(TAG, "error parsing bundle value", e);
1730 } catch (NullPointerException e) {
1731 Log.e(TAG, "error parsing bundle value", e);
1732 }
1733 }
1734
Dianne Hackborn231cc602009-04-27 17:10:36 -07001735 /**
1736 * Write all account information to the account file.
1737 */
1738 private void writeAccountInfoLocked() {
1739 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1740 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001741
Dianne Hackborn231cc602009-04-27 17:10:36 -07001742 try {
1743 fos = mAccountInfoFile.startWrite();
1744 XmlSerializer out = new FastXmlSerializer();
1745 out.setOutput(fos, "utf-8");
1746 out.startDocument(null, true);
1747 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001748
Dianne Hackborn231cc602009-04-27 17:10:36 -07001749 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001750 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001751 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001752 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001753
1754 // Write the Sync Automatically flags for each user
1755 final int M = mMasterSyncAutomatically.size();
1756 for (int m = 0; m < M; m++) {
1757 int userId = mMasterSyncAutomatically.keyAt(m);
1758 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1759 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1760 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1761 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1762 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001763 }
Costin Manolache360e4542009-09-04 13:36:04 -07001764
Dianne Hackborn231cc602009-04-27 17:10:36 -07001765 final int N = mAuthorities.size();
1766 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001767 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001768 out.startTag(null, "authority");
1769 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001770 out.attribute(null, "account", authority.account.name);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001771 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001772 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001773 out.attribute(null, "authority", authority.authority);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001774 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Fred Quintana5e787c42009-08-16 23:13:53 -07001775 if (authority.syncable < 0) {
1776 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001777 } else {
1778 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001779 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001780 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1781 out.startTag(null, "periodicSync");
1782 out.attribute(null, "period", Long.toString(periodicSync.second));
1783 final Bundle extras = periodicSync.first;
1784 for (String key : extras.keySet()) {
1785 out.startTag(null, "extra");
1786 out.attribute(null, "name", key);
1787 final Object value = extras.get(key);
1788 if (value instanceof Long) {
1789 out.attribute(null, "type", "long");
1790 out.attribute(null, "value1", value.toString());
1791 } else if (value instanceof Integer) {
1792 out.attribute(null, "type", "integer");
1793 out.attribute(null, "value1", value.toString());
1794 } else if (value instanceof Boolean) {
1795 out.attribute(null, "type", "boolean");
1796 out.attribute(null, "value1", value.toString());
1797 } else if (value instanceof Float) {
1798 out.attribute(null, "type", "float");
1799 out.attribute(null, "value1", value.toString());
1800 } else if (value instanceof Double) {
1801 out.attribute(null, "type", "double");
1802 out.attribute(null, "value1", value.toString());
1803 } else if (value instanceof String) {
1804 out.attribute(null, "type", "string");
1805 out.attribute(null, "value1", value.toString());
1806 } else if (value instanceof Account) {
1807 out.attribute(null, "type", "account");
1808 out.attribute(null, "value1", ((Account)value).name);
1809 out.attribute(null, "value2", ((Account)value).type);
1810 }
1811 out.endTag(null, "extra");
1812 }
1813 out.endTag(null, "periodicSync");
1814 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001815 out.endTag(null, "authority");
1816 }
Costin Manolache360e4542009-09-04 13:36:04 -07001817
Dianne Hackborn231cc602009-04-27 17:10:36 -07001818 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001819
Dianne Hackborn231cc602009-04-27 17:10:36 -07001820 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001821
Dianne Hackborn231cc602009-04-27 17:10:36 -07001822 mAccountInfoFile.finishWrite(fos);
1823 } catch (java.io.IOException e1) {
1824 Log.w(TAG, "Error writing accounts", e1);
1825 if (fos != null) {
1826 mAccountInfoFile.failWrite(fos);
1827 }
1828 }
1829 }
Costin Manolache360e4542009-09-04 13:36:04 -07001830
Dianne Hackborn231cc602009-04-27 17:10:36 -07001831 static int getIntColumn(Cursor c, String name) {
1832 return c.getInt(c.getColumnIndex(name));
1833 }
Costin Manolache360e4542009-09-04 13:36:04 -07001834
Dianne Hackborn231cc602009-04-27 17:10:36 -07001835 static long getLongColumn(Cursor c, String name) {
1836 return c.getLong(c.getColumnIndex(name));
1837 }
Costin Manolache360e4542009-09-04 13:36:04 -07001838
Dianne Hackborn231cc602009-04-27 17:10:36 -07001839 /**
1840 * Load sync engine state from the old syncmanager database, and then
1841 * erase it. Note that we don't deal with pending operations, active
1842 * sync, or history.
1843 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001844 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001845 // Look for old database to initialize from.
1846 File file = mContext.getDatabasePath("syncmanager.db");
1847 if (!file.exists()) {
1848 return;
1849 }
1850 String path = file.getPath();
1851 SQLiteDatabase db = null;
1852 try {
1853 db = SQLiteDatabase.openDatabase(path, null,
1854 SQLiteDatabase.OPEN_READONLY);
1855 } catch (SQLiteException e) {
1856 }
Costin Manolache360e4542009-09-04 13:36:04 -07001857
Dianne Hackborn231cc602009-04-27 17:10:36 -07001858 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001859 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001860
Dianne Hackborn231cc602009-04-27 17:10:36 -07001861 // Copy in all of the status information, as well as accounts.
1862 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1863 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1864 qb.setTables("stats, status");
1865 HashMap<String,String> map = new HashMap<String,String>();
1866 map.put("_id", "status._id as _id");
1867 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001868 if (hasType) {
1869 map.put("account_type", "stats.account_type as account_type");
1870 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001871 map.put("authority", "stats.authority as authority");
1872 map.put("totalElapsedTime", "totalElapsedTime");
1873 map.put("numSyncs", "numSyncs");
1874 map.put("numSourceLocal", "numSourceLocal");
1875 map.put("numSourcePoll", "numSourcePoll");
1876 map.put("numSourceServer", "numSourceServer");
1877 map.put("numSourceUser", "numSourceUser");
1878 map.put("lastSuccessSource", "lastSuccessSource");
1879 map.put("lastSuccessTime", "lastSuccessTime");
1880 map.put("lastFailureSource", "lastFailureSource");
1881 map.put("lastFailureTime", "lastFailureTime");
1882 map.put("lastFailureMesg", "lastFailureMesg");
1883 map.put("pending", "pending");
1884 qb.setProjectionMap(map);
1885 qb.appendWhere("stats._id = status.stats_id");
1886 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001888 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001889 String accountType = hasType
1890 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001891 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001892 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001894 String authorityName = c.getString(c.getColumnIndex("authority"));
1895 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001896 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07001897 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001898 if (authority != null) {
1899 int i = mSyncStatus.size();
1900 boolean found = false;
1901 SyncStatusInfo st = null;
1902 while (i > 0) {
1903 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001904 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001905 if (st.authorityId == authority.ident) {
1906 found = true;
1907 break;
1908 }
1909 }
1910 if (!found) {
1911 st = new SyncStatusInfo(authority.ident);
1912 mSyncStatus.put(authority.ident, st);
1913 }
1914 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1915 st.numSyncs = getIntColumn(c, "numSyncs");
1916 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1917 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1918 st.numSourceServer = getIntColumn(c, "numSourceServer");
1919 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001920 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001921 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1922 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1923 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1924 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1925 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1926 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
Costin Manolache360e4542009-09-04 13:36:04 -07001929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001931
Dianne Hackborn231cc602009-04-27 17:10:36 -07001932 // Retrieve the settings.
1933 qb = new SQLiteQueryBuilder();
1934 qb.setTables("settings");
1935 c = qb.query(db, null, null, null, null, null, null);
1936 while (c.moveToNext()) {
1937 String name = c.getString(c.getColumnIndex("name"));
1938 String value = c.getString(c.getColumnIndex("value"));
1939 if (name == null) continue;
1940 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001941 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001942 } else if (name.startsWith("sync_provider_")) {
1943 String provider = name.substring("sync_provider_".length(),
1944 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001945 int i = mAuthorities.size();
1946 while (i > 0) {
1947 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001948 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001949 if (authority.authority.equals(provider)) {
1950 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001951 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001952 }
1953 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
Costin Manolache360e4542009-09-04 13:36:04 -07001956
Dianne Hackborn231cc602009-04-27 17:10:36 -07001957 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001958
Dianne Hackborn231cc602009-04-27 17:10:36 -07001959 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001960
Dianne Hackborn231cc602009-04-27 17:10:36 -07001961 (new File(path)).delete();
1962 }
1963 }
Costin Manolache360e4542009-09-04 13:36:04 -07001964
Dianne Hackborn231cc602009-04-27 17:10:36 -07001965 public static final int STATUS_FILE_END = 0;
1966 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001967
Dianne Hackborn231cc602009-04-27 17:10:36 -07001968 /**
1969 * Read all sync status back in to the initial engine state.
1970 */
1971 private void readStatusLocked() {
1972 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1973 try {
1974 byte[] data = mStatusFile.readFully();
1975 Parcel in = Parcel.obtain();
1976 in.unmarshall(data, 0, data.length);
1977 in.setDataPosition(0);
1978 int token;
1979 while ((token=in.readInt()) != STATUS_FILE_END) {
1980 if (token == STATUS_FILE_ITEM) {
1981 SyncStatusInfo status = new SyncStatusInfo(in);
1982 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1983 status.pending = false;
1984 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
1985 + status.authorityId);
1986 mSyncStatus.put(status.authorityId, status);
1987 }
1988 } else {
1989 // Ooops.
1990 Log.w(TAG, "Unknown status token: " + token);
1991 break;
1992 }
1993 }
1994 } catch (java.io.IOException e) {
1995 Log.i(TAG, "No initial status");
1996 }
1997 }
Costin Manolache360e4542009-09-04 13:36:04 -07001998
Dianne Hackborn231cc602009-04-27 17:10:36 -07001999 /**
2000 * Write all sync status to the sync status file.
2001 */
2002 private void writeStatusLocked() {
2003 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002004
Dianne Hackborn231cc602009-04-27 17:10:36 -07002005 // The file is being written, so we don't need to have a scheduled
2006 // write until the next change.
2007 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002008
Dianne Hackborn231cc602009-04-27 17:10:36 -07002009 FileOutputStream fos = null;
2010 try {
2011 fos = mStatusFile.startWrite();
2012 Parcel out = Parcel.obtain();
2013 final int N = mSyncStatus.size();
2014 for (int i=0; i<N; i++) {
2015 SyncStatusInfo status = mSyncStatus.valueAt(i);
2016 out.writeInt(STATUS_FILE_ITEM);
2017 status.writeToParcel(out, 0);
2018 }
2019 out.writeInt(STATUS_FILE_END);
2020 fos.write(out.marshall());
2021 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002022
Dianne Hackborn231cc602009-04-27 17:10:36 -07002023 mStatusFile.finishWrite(fos);
2024 } catch (java.io.IOException e1) {
2025 Log.w(TAG, "Error writing status", e1);
2026 if (fos != null) {
2027 mStatusFile.failWrite(fos);
2028 }
2029 }
2030 }
Costin Manolache360e4542009-09-04 13:36:04 -07002031
Fred Quintana307da1a2010-01-21 14:24:20 -08002032 public static final int PENDING_OPERATION_VERSION = 2;
Costin Manolache360e4542009-09-04 13:36:04 -07002033
Dianne Hackborn231cc602009-04-27 17:10:36 -07002034 /**
2035 * Read all pending operations back in to the initial engine state.
2036 */
2037 private void readPendingOperationsLocked() {
2038 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
2039 try {
2040 byte[] data = mPendingFile.readFully();
2041 Parcel in = Parcel.obtain();
2042 in.unmarshall(data, 0, data.length);
2043 in.setDataPosition(0);
2044 final int SIZE = in.dataSize();
2045 while (in.dataPosition() < SIZE) {
2046 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08002047 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002048 Log.w(TAG, "Unknown pending operation version "
2049 + version + "; dropping all ops");
2050 break;
2051 }
2052 int authorityId = in.readInt();
2053 int syncSource = in.readInt();
2054 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08002055 boolean expedited;
2056 if (version == PENDING_OPERATION_VERSION) {
2057 expedited = in.readInt() != 0;
2058 } else {
2059 expedited = false;
2060 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002061 AuthorityInfo authority = mAuthorities.get(authorityId);
2062 if (authority != null) {
Fred Quintana5695c7b2010-12-06 15:07:52 -08002063 Bundle extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002064 if (flatExtras != null) {
2065 extras = unflattenBundle(flatExtras);
Fred Quintana5695c7b2010-12-06 15:07:52 -08002066 } else {
2067 // if we are unable to parse the extras for whatever reason convert this
2068 // to a regular sync by creating an empty extras
2069 extras = new Bundle();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002070 }
2071 PendingOperation op = new PendingOperation(
Amith Yamasani04e0d262012-02-14 11:50:53 -08002072 authority.account, authority.userId, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08002073 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002074 op.authorityId = authorityId;
2075 op.flatExtras = flatExtras;
2076 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
2077 + " auth=" + op.authority
2078 + " src=" + op.syncSource
Fred Quintana307da1a2010-01-21 14:24:20 -08002079 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07002080 + " extras=" + op.extras);
2081 mPendingOperations.add(op);
2082 }
2083 }
2084 } catch (java.io.IOException e) {
2085 Log.i(TAG, "No initial pending operations");
2086 }
2087 }
Costin Manolache360e4542009-09-04 13:36:04 -07002088
Dianne Hackborn231cc602009-04-27 17:10:36 -07002089 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
2090 out.writeInt(PENDING_OPERATION_VERSION);
2091 out.writeInt(op.authorityId);
2092 out.writeInt(op.syncSource);
2093 if (op.flatExtras == null && op.extras != null) {
2094 op.flatExtras = flattenBundle(op.extras);
2095 }
2096 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08002097 out.writeInt(op.expedited ? 1 : 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002098 }
Costin Manolache360e4542009-09-04 13:36:04 -07002099
Dianne Hackborn231cc602009-04-27 17:10:36 -07002100 /**
2101 * Write all currently pending ops to the pending ops file.
2102 */
2103 private void writePendingOperationsLocked() {
2104 final int N = mPendingOperations.size();
2105 FileOutputStream fos = null;
2106 try {
2107 if (N == 0) {
2108 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2109 mPendingFile.truncate();
2110 return;
2111 }
Costin Manolache360e4542009-09-04 13:36:04 -07002112
Dianne Hackborn231cc602009-04-27 17:10:36 -07002113 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2114 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07002115
Dianne Hackborn231cc602009-04-27 17:10:36 -07002116 Parcel out = Parcel.obtain();
2117 for (int i=0; i<N; i++) {
2118 PendingOperation op = mPendingOperations.get(i);
2119 writePendingOperationLocked(op, out);
2120 }
2121 fos.write(out.marshall());
2122 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002123
Dianne Hackborn231cc602009-04-27 17:10:36 -07002124 mPendingFile.finishWrite(fos);
2125 } catch (java.io.IOException e1) {
2126 Log.w(TAG, "Error writing pending operations", e1);
2127 if (fos != null) {
2128 mPendingFile.failWrite(fos);
2129 }
2130 }
2131 }
Costin Manolache360e4542009-09-04 13:36:04 -07002132
Dianne Hackborn231cc602009-04-27 17:10:36 -07002133 /**
2134 * Append the given operation to the pending ops file; if unable to,
2135 * write all pending ops.
2136 */
2137 private void appendPendingOperationLocked(PendingOperation op) {
2138 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2139 FileOutputStream fos = null;
2140 try {
2141 fos = mPendingFile.openAppend();
2142 } catch (java.io.IOException e) {
2143 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2144 writePendingOperationsLocked();
2145 return;
2146 }
Costin Manolache360e4542009-09-04 13:36:04 -07002147
Dianne Hackborn231cc602009-04-27 17:10:36 -07002148 try {
2149 Parcel out = Parcel.obtain();
2150 writePendingOperationLocked(op, out);
2151 fos.write(out.marshall());
2152 out.recycle();
2153 } catch (java.io.IOException e1) {
2154 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002156 try {
2157 fos.close();
2158 } catch (java.io.IOException e2) {
2159 }
2160 }
2161 }
Costin Manolache360e4542009-09-04 13:36:04 -07002162
Dianne Hackborn231cc602009-04-27 17:10:36 -07002163 static private byte[] flattenBundle(Bundle bundle) {
2164 byte[] flatData = null;
2165 Parcel parcel = Parcel.obtain();
2166 try {
2167 bundle.writeToParcel(parcel, 0);
2168 flatData = parcel.marshall();
2169 } finally {
2170 parcel.recycle();
2171 }
2172 return flatData;
2173 }
Costin Manolache360e4542009-09-04 13:36:04 -07002174
Dianne Hackborn231cc602009-04-27 17:10:36 -07002175 static private Bundle unflattenBundle(byte[] flatData) {
2176 Bundle bundle;
2177 Parcel parcel = Parcel.obtain();
2178 try {
2179 parcel.unmarshall(flatData, 0, flatData.length);
2180 parcel.setDataPosition(0);
2181 bundle = parcel.readBundle();
2182 } catch (RuntimeException e) {
2183 // A RuntimeException is thrown if we were unable to parse the parcel.
2184 // Create an empty parcel in this case.
2185 bundle = new Bundle();
2186 } finally {
2187 parcel.recycle();
2188 }
2189 return bundle;
2190 }
Costin Manolache360e4542009-09-04 13:36:04 -07002191
Amith Yamasani04e0d262012-02-14 11:50:53 -08002192 private void requestSync(Account account, int userId, String authority, Bundle extras) {
2193 // If this is happening in the system process, then call the syncrequest listener
2194 // to make a request back to the SyncManager directly.
2195 // If this is probably a test instance, then call back through the ContentResolver
2196 // which will know which userId to apply based on the Binder id.
2197 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2198 && mSyncRequestListener != null) {
2199 mSyncRequestListener.onSyncRequest(account, userId, authority, extras);
2200 } else {
2201 ContentResolver.requestSync(account, authority, extras);
2202 }
2203 }
2204
Dianne Hackborn231cc602009-04-27 17:10:36 -07002205 public static final int STATISTICS_FILE_END = 0;
2206 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2207 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002208
Dianne Hackborn231cc602009-04-27 17:10:36 -07002209 /**
2210 * Read all sync statistics back in to the initial engine state.
2211 */
2212 private void readStatisticsLocked() {
2213 try {
2214 byte[] data = mStatisticsFile.readFully();
2215 Parcel in = Parcel.obtain();
2216 in.unmarshall(data, 0, data.length);
2217 in.setDataPosition(0);
2218 int token;
2219 int index = 0;
2220 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2221 if (token == STATISTICS_FILE_ITEM
2222 || token == STATISTICS_FILE_ITEM_OLD) {
2223 int day = in.readInt();
2224 if (token == STATISTICS_FILE_ITEM_OLD) {
2225 day = day - 2009 + 14245; // Magic!
2226 }
2227 DayStats ds = new DayStats(day);
2228 ds.successCount = in.readInt();
2229 ds.successTime = in.readLong();
2230 ds.failureCount = in.readInt();
2231 ds.failureTime = in.readLong();
2232 if (index < mDayStats.length) {
2233 mDayStats[index] = ds;
2234 index++;
2235 }
2236 } else {
2237 // Ooops.
2238 Log.w(TAG, "Unknown stats token: " + token);
2239 break;
2240 }
2241 }
2242 } catch (java.io.IOException e) {
2243 Log.i(TAG, "No initial statistics");
2244 }
2245 }
Costin Manolache360e4542009-09-04 13:36:04 -07002246
Dianne Hackborn231cc602009-04-27 17:10:36 -07002247 /**
2248 * Write all sync statistics to the sync status file.
2249 */
2250 private void writeStatisticsLocked() {
2251 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002252
Dianne Hackborn231cc602009-04-27 17:10:36 -07002253 // The file is being written, so we don't need to have a scheduled
2254 // write until the next change.
2255 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002256
Dianne Hackborn231cc602009-04-27 17:10:36 -07002257 FileOutputStream fos = null;
2258 try {
2259 fos = mStatisticsFile.startWrite();
2260 Parcel out = Parcel.obtain();
2261 final int N = mDayStats.length;
2262 for (int i=0; i<N; i++) {
2263 DayStats ds = mDayStats[i];
2264 if (ds == null) {
2265 break;
2266 }
2267 out.writeInt(STATISTICS_FILE_ITEM);
2268 out.writeInt(ds.day);
2269 out.writeInt(ds.successCount);
2270 out.writeLong(ds.successTime);
2271 out.writeInt(ds.failureCount);
2272 out.writeLong(ds.failureTime);
2273 }
2274 out.writeInt(STATISTICS_FILE_END);
2275 fos.write(out.marshall());
2276 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002277
Dianne Hackborn231cc602009-04-27 17:10:36 -07002278 mStatisticsFile.finishWrite(fos);
2279 } catch (java.io.IOException e1) {
2280 Log.w(TAG, "Error writing stats", e1);
2281 if (fos != null) {
2282 mStatisticsFile.failWrite(fos);
2283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 }
2285 }
2286}