blob: c4dc5751a21dc4fce03544066e19030eefa64580 [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.content.ContentResolver;
22import android.content.Context;
23import android.content.ISyncStatusObserver;
24import android.content.PeriodicSync;
25import android.content.SyncInfo;
26import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070029import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070031import android.os.Bundle;
32import android.os.Environment;
33import android.os.Handler;
34import android.os.Message;
35import android.os.Parcel;
36import android.os.RemoteCallbackList;
37import android.os.RemoteException;
Dianne Hackborn39606a02012-07-31 17:54:35 -070038import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080040import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070041import android.util.SparseArray;
42import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080043
44import com.android.internal.annotations.VisibleForTesting;
45import com.android.internal.util.ArrayUtils;
46import com.android.internal.util.FastXmlSerializer;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -070047import com.android.server.content.SyncStorageEngine.AuthorityInfo;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080048
49import org.xmlpull.v1.XmlPullParser;
50import org.xmlpull.v1.XmlPullParserException;
51import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
Dianne Hackborn231cc602009-04-27 17:10:36 -070053import java.io.File;
54import java.io.FileInputStream;
55import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070057import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070059import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080060import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070061import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060062import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063
64/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070065 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070067 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 * @hide
69 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070070public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private static final String TAG = "SyncManager";
Dianne Hackborn40e9f292012-11-27 19:12:23 -080073 private static final boolean DEBUG = false;
Dianne Hackborn231cc602009-04-27 17:10:36 -070074 private static final boolean DEBUG_FILE = false;
Costin Manolache360e4542009-09-04 13:36:04 -070075
Amith Yamasani04e0d262012-02-14 11:50:53 -080076 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
77 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070078 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080079 private static final String XML_ATTR_ENABLED = "enabled";
80 private static final String XML_ATTR_USER = "user";
81 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
82
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080083 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
84
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080085 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070086 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087
Dianne Hackborn231cc602009-04-27 17:10:36 -070088 /** Enum value for a sync start event. */
89 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
Dianne Hackborn231cc602009-04-27 17:10:36 -070091 /** Enum value for a sync stop event. */
92 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Dianne Hackborn231cc602009-04-27 17:10:36 -070094 // TODO: i18n -- grab these out of resources.
95 /** String names for the sync event types. */
96 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Dianne Hackborn231cc602009-04-27 17:10:36 -070098 /** Enum value for a server-initiated sync. */
99 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Dianne Hackborn231cc602009-04-27 17:10:36 -0700101 /** Enum value for a local-initiated sync. */
102 public static final int SOURCE_LOCAL = 1;
103 /**
104 * Enum value for a poll-based sync (e.g., upon connection to
105 * network)
106 */
107 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Dianne Hackborn231cc602009-04-27 17:10:36 -0700109 /** Enum value for a user-initiated sync. */
110 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800112 /** Enum value for a periodic sync. */
113 public static final int SOURCE_PERIODIC = 4;
114
Fred Quintana307da1a2010-01-21 14:24:20 -0800115 public static final long NOT_IN_BACKOFF_MODE = -1;
116
Dianne Hackborn231cc602009-04-27 17:10:36 -0700117 // TODO: i18n -- grab these out of resources.
118 /** String names for the sync source types. */
119 public static final String[] SOURCES = { "SERVER",
120 "LOCAL",
121 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800122 "USER",
123 "PERIODIC" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
Dianne Hackborn231cc602009-04-27 17:10:36 -0700125 // The MESG column will contain one of these or one of the Error types.
126 public static final String MESG_SUCCESS = "success";
127 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700129 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700130
Dianne Hackborn231cc602009-04-27 17:10:36 -0700131 private static final int MSG_WRITE_STATUS = 1;
132 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700133
Dianne Hackborn231cc602009-04-27 17:10:36 -0700134 private static final int MSG_WRITE_STATISTICS = 2;
135 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700136
137 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700138
Fred Quintanac2e46912010-03-15 16:10:44 -0700139 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700140 private static final int ACCOUNTS_VERSION = 2;
141
142 private static HashMap<String, String> sAuthorityRenames;
143
144 static {
145 sAuthorityRenames = new HashMap<String, String>();
146 sAuthorityRenames.put("contacts", "com.android.contacts");
147 sAuthorityRenames.put("calendar", "com.android.calendar");
148 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700149
Dianne Hackborn231cc602009-04-27 17:10:36 -0700150 public static class PendingOperation {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700151 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800152 final int userId;
Alon Albert57286f92012-10-09 14:21:38 -0700153 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700154 final int syncSource;
155 final String authority;
156 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800157 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700158
Dianne Hackborn231cc602009-04-27 17:10:36 -0700159 int authorityId;
160 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700161
Alon Albert57286f92012-10-09 14:21:38 -0700162 PendingOperation(Account account, int userId, int reason,int source,
Fred Quintana307da1a2010-01-21 14:24:20 -0800163 String authority, Bundle extras, boolean expedited) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700164 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800165 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700166 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700167 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700168 this.authority = authority;
169 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800170 this.expedited = expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700171 this.authorityId = -1;
172 }
173
174 PendingOperation(PendingOperation other) {
175 this.account = other.account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800176 this.userId = other.userId;
Alon Albert57286f92012-10-09 14:21:38 -0700177 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700178 this.syncSource = other.syncSource;
179 this.authority = other.authority;
180 this.extras = other.extras;
181 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800182 this.expedited = other.expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 }
Costin Manolache360e4542009-09-04 13:36:04 -0700185
Dianne Hackborn231cc602009-04-27 17:10:36 -0700186 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800187 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700188 final HashMap<String, AuthorityInfo> authorities =
189 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700190
Amith Yamasani04e0d262012-02-14 11:50:53 -0800191 AccountInfo(AccountAndUser accountAndUser) {
192 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700193 }
194 }
Costin Manolache360e4542009-09-04 13:36:04 -0700195
Dianne Hackborn231cc602009-04-27 17:10:36 -0700196 public static class AuthorityInfo {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700197 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800198 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700199 final String authority;
200 final int ident;
201 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700202 int syncable;
Fred Quintana307da1a2010-01-21 14:24:20 -0800203 long backoffTime;
204 long backoffDelay;
205 long delayUntil;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800206 final ArrayList<Pair<Bundle, Long>> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700207
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700208 /**
209 * Copy constructor for making deep-ish copies. Only the bundles stored
210 * in periodic syncs can make unexpected changes.
211 *
212 * @param toCopy AuthorityInfo to be copied.
213 */
214 AuthorityInfo(AuthorityInfo toCopy) {
215 account = toCopy.account;
216 userId = toCopy.userId;
217 authority = toCopy.authority;
218 ident = toCopy.ident;
219 enabled = toCopy.enabled;
220 syncable = toCopy.syncable;
221 backoffTime = toCopy.backoffTime;
222 backoffDelay = toCopy.backoffDelay;
223 delayUntil = toCopy.delayUntil;
224 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
225 for (Pair<Bundle, Long> sync : toCopy.periodicSyncs) {
226 // Still not a perfect copy, because we are just copying the mappings.
227 periodicSyncs.add(Pair.create(new Bundle(sync.first), sync.second));
228 }
229 }
230
Amith Yamasani04e0d262012-02-14 11:50:53 -0800231 AuthorityInfo(Account account, int userId, String authority, int ident) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700232 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800233 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700234 this.authority = authority;
235 this.ident = ident;
Joe Onorato8294fad2009-07-15 16:08:44 -0700236 enabled = SYNC_ENABLED_DEFAULT;
Fred Quintana4a6679b2009-08-17 13:05:39 -0700237 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800238 backoffTime = -1; // if < 0 then we aren't in backoff mode
239 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800240 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
241 periodicSyncs.add(Pair.create(new Bundle(), DEFAULT_POLL_FREQUENCY_SECONDS));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700242 }
243 }
Costin Manolache360e4542009-09-04 13:36:04 -0700244
Dianne Hackborn231cc602009-04-27 17:10:36 -0700245 public static class SyncHistoryItem {
246 int authorityId;
247 int historyId;
248 long eventTime;
249 long elapsedTime;
250 int source;
251 int event;
252 long upstreamActivity;
253 long downstreamActivity;
254 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700255 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700256 Bundle extras;
257 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700258 }
Costin Manolache360e4542009-09-04 13:36:04 -0700259
Dianne Hackborn231cc602009-04-27 17:10:36 -0700260 public static class DayStats {
261 public final int day;
262 public int successCount;
263 public long successTime;
264 public int failureCount;
265 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700266
Dianne Hackborn231cc602009-04-27 17:10:36 -0700267 public DayStats(int day) {
268 this.day = day;
269 }
270 }
Costin Manolache360e4542009-09-04 13:36:04 -0700271
Amith Yamasani04e0d262012-02-14 11:50:53 -0800272 interface OnSyncRequestListener {
273 /**
274 * Called when a sync is needed on an account(s) due to some change in state.
275 * @param account
276 * @param userId
Alon Albert57286f92012-10-09 14:21:38 -0700277 * @param reason
Amith Yamasani04e0d262012-02-14 11:50:53 -0800278 * @param authority
279 * @param extras
280 */
Alon Albert57286f92012-10-09 14:21:38 -0700281 public void onSyncRequest(Account account, int userId, int reason, String authority,
282 Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800283 }
284
Dianne Hackborn231cc602009-04-27 17:10:36 -0700285 // Primary list of all syncable authorities. Also our global lock.
286 private final SparseArray<AuthorityInfo> mAuthorities =
287 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700288
Amith Yamasani04e0d262012-02-14 11:50:53 -0800289 private final HashMap<AccountAndUser, AccountInfo> mAccounts
290 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291
Dianne Hackborn231cc602009-04-27 17:10:36 -0700292 private final ArrayList<PendingOperation> mPendingOperations =
293 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700294
Amith Yamasani04e0d262012-02-14 11:50:53 -0800295 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
296 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700297
Dianne Hackborn231cc602009-04-27 17:10:36 -0700298 private final SparseArray<SyncStatusInfo> mSyncStatus =
299 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700300
Dianne Hackborn231cc602009-04-27 17:10:36 -0700301 private final ArrayList<SyncHistoryItem> mSyncHistory =
302 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700303
Dianne Hackborn231cc602009-04-27 17:10:36 -0700304 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
305 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700306
Fred Quintana77c560f2010-03-29 22:20:26 -0700307 private int mNextAuthorityId = 0;
308
Dianne Hackborn231cc602009-04-27 17:10:36 -0700309 // We keep 4 weeks of stats.
310 private final DayStats[] mDayStats = new DayStats[7*4];
311 private final Calendar mCal;
312 private int mYear;
313 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700314
Dianne Hackborn231cc602009-04-27 17:10:36 -0700315 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800316
Dianne Hackborn231cc602009-04-27 17:10:36 -0700317 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700318
Ashish Sharma69d95de2012-04-11 17:27:24 -0700319 private int mSyncRandomOffset;
320
Dianne Hackborn231cc602009-04-27 17:10:36 -0700321 /**
322 * This file contains the core engine state: all accounts and the
323 * settings for them. It must never be lost, and should be changed
324 * infrequently, so it is stored as an XML file.
325 */
326 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700327
Dianne Hackborn231cc602009-04-27 17:10:36 -0700328 /**
329 * This file contains the current sync status. We would like to retain
330 * it across boots, but its loss is not the end of the world, so we store
331 * this information as binary data.
332 */
333 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700334
Dianne Hackborn231cc602009-04-27 17:10:36 -0700335 /**
336 * This file contains sync statistics. This is purely debugging information
337 * so is written infrequently and can be thrown away at any time.
338 */
339 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700340
Dianne Hackborn231cc602009-04-27 17:10:36 -0700341 /**
342 * This file contains the pending sync operations. It is a binary file,
343 * which must be updated every time an operation is added or removed,
344 * so we have special handling of it.
345 */
346 private final AtomicFile mPendingFile;
347 private static final int PENDING_FINISH_TO_WRITE = 4;
348 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700349
Dianne Hackborn231cc602009-04-27 17:10:36 -0700350 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800351 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800352 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800353
354 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700355
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800356 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700359
Dianne Hackborn231cc602009-04-27 17:10:36 -0700360 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700361
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800362 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
363 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
364
Dianne Hackborn231cc602009-04-27 17:10:36 -0700365 File systemDir = new File(dataDir, "system");
366 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800367 syncDir.mkdirs();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700368 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
369 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
370 mPendingFile = new AtomicFile(new File(syncDir, "pending.bin"));
371 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700372
Dianne Hackborn231cc602009-04-27 17:10:36 -0700373 readAccountInfoLocked();
374 readStatusLocked();
375 readPendingOperationsLocked();
376 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700377 readAndDeleteLegacyAccountInfoLocked();
378 writeAccountInfoLocked();
379 writeStatusLocked();
380 writePendingOperationsLocked();
381 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 }
383
384 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800385 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 }
387
388 public static void init(Context context) {
389 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800390 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800392 // This call will return the correct directory whether Encrypted File Systems is
393 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600394 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800395 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 }
397
398 public static SyncStorageEngine getSingleton() {
399 if (sSyncStorageEngine == null) {
400 throw new IllegalStateException("not initialized");
401 }
402 return sSyncStorageEngine;
403 }
404
Amith Yamasani04e0d262012-02-14 11:50:53 -0800405 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
406 if (mSyncRequestListener == null) {
407 mSyncRequestListener = listener;
408 }
409 }
410
Dianne Hackborn231cc602009-04-27 17:10:36 -0700411 @Override public void handleMessage(Message msg) {
412 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700413 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700414 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700415 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700416 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700417 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700418 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 }
420 }
421 }
Costin Manolache360e4542009-09-04 13:36:04 -0700422
Ashish Sharma69d95de2012-04-11 17:27:24 -0700423 public int getSyncRandomOffset() {
424 return mSyncRandomOffset;
425 }
426
Dianne Hackborn231cc602009-04-27 17:10:36 -0700427 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
428 synchronized (mAuthorities) {
429 mChangeListeners.register(callback, mask);
430 }
431 }
Costin Manolache360e4542009-09-04 13:36:04 -0700432
Dianne Hackborn231cc602009-04-27 17:10:36 -0700433 public void removeStatusChangeListener(ISyncStatusObserver callback) {
434 synchronized (mAuthorities) {
435 mChangeListeners.unregister(callback);
436 }
437 }
Costin Manolache360e4542009-09-04 13:36:04 -0700438
Dianne Hackborn231cc602009-04-27 17:10:36 -0700439 private void reportChange(int which) {
440 ArrayList<ISyncStatusObserver> reports = null;
441 synchronized (mAuthorities) {
442 int i = mChangeListeners.beginBroadcast();
443 while (i > 0) {
444 i--;
445 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
446 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 continue;
448 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700449 if (reports == null) {
450 reports = new ArrayList<ISyncStatusObserver>(i);
451 }
452 reports.add(mChangeListeners.getBroadcastItem(i));
453 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700454 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700455 }
Costin Manolache360e4542009-09-04 13:36:04 -0700456
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800457 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700458 Log.v(TAG, "reportChange " + which + " to: " + reports);
459 }
Costin Manolache360e4542009-09-04 13:36:04 -0700460
Dianne Hackborn231cc602009-04-27 17:10:36 -0700461 if (reports != null) {
462 int i = reports.size();
463 while (i > 0) {
464 i--;
465 try {
466 reports.get(i).onStatusChanged(which);
467 } catch (RemoteException e) {
468 // The remote callback list will take care of this for us.
469 }
470 }
471 }
472 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700473
Amith Yamasani04e0d262012-02-14 11:50:53 -0800474 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700475 synchronized (mAuthorities) {
476 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800477 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700478 "getSyncAutomatically");
479 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700480 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700481
Dianne Hackborn231cc602009-04-27 17:10:36 -0700482 int i = mAuthorities.size();
483 while (i > 0) {
484 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700485 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700486 if (authority.authority.equals(providerName)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800487 && authority.userId == userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700488 && authority.enabled) {
489 return true;
490 }
491 }
492 return false;
493 }
494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495
Amith Yamasani04e0d262012-02-14 11:50:53 -0800496 public void setSyncAutomatically(Account account, int userId, String providerName,
497 boolean sync) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800498 if (DEBUG) {
499 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
500 + ", user " + userId + " -> " + sync);
501 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700502 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800503 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
504 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700505 if (authority.enabled == sync) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800506 if (DEBUG) {
507 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
508 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700509 return;
510 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700511 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700512 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700514
Fred Quintana77c560f2010-03-29 22:20:26 -0700515 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700516 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
517 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700518 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700519 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 }
521
Amith Yamasani04e0d262012-02-14 11:50:53 -0800522 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700523 synchronized (mAuthorities) {
524 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800525 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintana5e787c42009-08-16 23:13:53 -0700526 "getIsSyncable");
527 if (authority == null) {
528 return -1;
529 }
530 return authority.syncable;
531 }
532
533 int i = mAuthorities.size();
534 while (i > 0) {
535 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700536 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700537 if (authority.authority.equals(providerName)) {
538 return authority.syncable;
539 }
540 }
541 return -1;
542 }
543 }
544
Amith Yamasani04e0d262012-02-14 11:50:53 -0800545 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700546 if (syncable > 1) {
547 syncable = 1;
548 } else if (syncable < -1) {
549 syncable = -1;
550 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800551 if (DEBUG) {
552 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName
553 + ", user " + userId + " -> " + syncable);
554 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700555 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800556 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
557 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700558 if (authority.syncable == syncable) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800559 if (DEBUG) {
560 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
561 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700562 return;
563 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700564 authority.syncable = syncable;
565 writeAccountInfoLocked();
566 }
567
Fred Quintana77c560f2010-03-29 22:20:26 -0700568 if (syncable > 0) {
Alon Albert57286f92012-10-09 14:21:38 -0700569 requestSync(account, userId, SyncOperation.REASON_IS_SYNCABLE, providerName,
570 new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700571 }
572 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
573 }
574
Amith Yamasani04e0d262012-02-14 11:50:53 -0800575 public Pair<Long, Long> getBackoff(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800576 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800577 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
578 "getBackoff");
Fred Quintana307da1a2010-01-21 14:24:20 -0800579 if (authority == null || authority.backoffTime < 0) {
580 return null;
581 }
582 return Pair.create(authority.backoffTime, authority.backoffDelay);
583 }
584 }
585
Amith Yamasani04e0d262012-02-14 11:50:53 -0800586 public void setBackoff(Account account, int userId, String providerName,
Fred Quintana307da1a2010-01-21 14:24:20 -0800587 long nextSyncTime, long nextDelay) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800588 if (DEBUG) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800589 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800590 + ", user " + userId
Fred Quintana307da1a2010-01-21 14:24:20 -0800591 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
592 }
593 boolean changed = false;
594 synchronized (mAuthorities) {
595 if (account == null || providerName == null) {
596 for (AccountInfo accountInfo : mAccounts.values()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800597 if (account != null && !account.equals(accountInfo.accountAndUser.account)
598 && userId != accountInfo.accountAndUser.userId) {
599 continue;
600 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800601 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
602 if (providerName != null && !providerName.equals(authorityInfo.authority)) {
603 continue;
604 }
605 if (authorityInfo.backoffTime != nextSyncTime
606 || authorityInfo.backoffDelay != nextDelay) {
607 authorityInfo.backoffTime = nextSyncTime;
608 authorityInfo.backoffDelay = nextDelay;
609 changed = true;
610 }
611 }
612 }
613 } else {
614 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800615 getOrCreateAuthorityLocked(account, userId, providerName, -1 /* ident */,
616 true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800617 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
618 return;
619 }
620 authority.backoffTime = nextSyncTime;
621 authority.backoffDelay = nextDelay;
622 changed = true;
623 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800624 }
625
626 if (changed) {
627 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
628 }
629 }
630
Alon Alberted1d2532011-02-15 14:02:14 -0800631 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800632 boolean changed = false;
633 synchronized (mAuthorities) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700634 synchronized (syncQueue) {
635 for (AccountInfo accountInfo : mAccounts.values()) {
636 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
637 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
638 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800639 if (DEBUG) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700640 Log.v(TAG, "clearAllBackoffs:"
641 + " authority:" + authorityInfo.authority
642 + " account:" + accountInfo.accountAndUser.account.name
643 + " user:" + accountInfo.accountAndUser.userId
644 + " backoffTime was: " + authorityInfo.backoffTime
645 + " backoffDelay was: " + authorityInfo.backoffDelay);
646 }
647 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
648 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
649 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
650 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
651 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800652 }
Alon Albert744e310f2010-12-14 11:37:20 -0800653 }
654 }
655 }
656 }
657
658 if (changed) {
659 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
660 }
661 }
662
Amith Yamasani04e0d262012-02-14 11:50:53 -0800663 public void setDelayUntilTime(Account account, int userId, String providerName,
664 long delayUntil) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800665 if (DEBUG) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800666 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800667 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800668 }
669 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800670 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800671 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800672 if (authority.delayUntil == delayUntil) {
673 return;
674 }
675 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800676 }
677
678 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
679 }
680
Amith Yamasani04e0d262012-02-14 11:50:53 -0800681 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800682 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800683 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
684 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800685 if (authority == null) {
686 return 0;
687 }
688 return authority.delayUntil;
689 }
690 }
691
Amith Yamasani04e0d262012-02-14 11:50:53 -0800692 private void updateOrRemovePeriodicSync(Account account, int userId, String providerName,
693 Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800694 long period, boolean add) {
695 if (period <= 0) {
696 period = 0;
697 }
698 if (extras == null) {
699 extras = new Bundle();
700 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800701 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800702 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", user " + userId
703 + ", provider " + providerName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800704 + " -> period " + period + ", extras " + extras);
705 }
706 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700707 try {
708 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800709 getOrCreateAuthorityLocked(account, userId, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700710 if (add) {
711 // add this periodic sync if one with the same extras doesn't already
712 // exist in the periodicSyncs array
713 boolean alreadyPresent = false;
714 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
715 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
716 final Bundle existingExtras = syncInfo.first;
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800717 if (PeriodicSync.syncExtrasEquals(existingExtras, extras)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700718 if (syncInfo.second == period) {
719 return;
720 }
721 authority.periodicSyncs.set(i, Pair.create(extras, period));
722 alreadyPresent = true;
723 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800724 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700725 }
726 // if we added an entry to the periodicSyncs array also add an entry to
727 // the periodic syncs status to correspond to it
728 if (!alreadyPresent) {
729 authority.periodicSyncs.add(Pair.create(extras, period));
730 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
731 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
732 }
733 } else {
734 // remove any periodic syncs that match the authority and extras
735 SyncStatusInfo status = mSyncStatus.get(authority.ident);
736 boolean changed = false;
737 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
738 int i = 0;
739 while (iterator.hasNext()) {
740 Pair<Bundle, Long> syncInfo = iterator.next();
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800741 if (PeriodicSync.syncExtrasEquals(syncInfo.first, extras)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700742 iterator.remove();
743 changed = true;
744 // if we removed an entry from the periodicSyncs array also
745 // remove the corresponding entry from the status
746 if (status != null) {
747 status.removePeriodicSyncTime(i);
748 }
749 } else {
750 i++;
751 }
752 }
753 if (!changed) {
754 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800755 }
756 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700757 } finally {
758 writeAccountInfoLocked();
759 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800760 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800761 }
762
763 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
764 }
765
Amith Yamasani04e0d262012-02-14 11:50:53 -0800766 public void addPeriodicSync(Account account, int userId, String providerName, Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800767 long pollFrequency) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800768 updateOrRemovePeriodicSync(account, userId, providerName, extras, pollFrequency,
769 true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800770 }
771
Amith Yamasani04e0d262012-02-14 11:50:53 -0800772 public void removePeriodicSync(Account account, int userId, String providerName,
773 Bundle extras) {
774 updateOrRemovePeriodicSync(account, userId, providerName, extras, 0 /* period, ignored */,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800775 false /* remove */);
776 }
777
Amith Yamasani04e0d262012-02-14 11:50:53 -0800778 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800779 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
780 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800781 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
782 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800783 if (authority != null) {
784 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800785 syncs.add(new PeriodicSync(account, providerName, item.first,
786 item.second));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800787 }
788 }
789 }
790 return syncs;
791 }
792
Amith Yamasani04e0d262012-02-14 11:50:53 -0800793 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700794 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800795 Boolean auto = mMasterSyncAutomatically.get(userId);
796 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700797 return;
798 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800799 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700800 writeAccountInfoLocked();
801 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700802 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700803 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
804 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700805 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700806 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800807 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809
Amith Yamasani04e0d262012-02-14 11:50:53 -0800810 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700811 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800812 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800813 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700814 }
815 }
Costin Manolache360e4542009-09-04 13:36:04 -0700816
Amith Yamasani04e0d262012-02-14 11:50:53 -0800817 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700818 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800819 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700820 }
821 }
822
Dianne Hackborn231cc602009-04-27 17:10:36 -0700823 public AuthorityInfo getAuthority(int authorityId) {
824 synchronized (mAuthorities) {
825 return mAuthorities.get(authorityId);
826 }
827 }
Costin Manolache360e4542009-09-04 13:36:04 -0700828
Dianne Hackborn231cc602009-04-27 17:10:36 -0700829 /**
830 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700831 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700832 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800833 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700834 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800835 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700836 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700837 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800838 && ainfo.authority.equals(authority)
839 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700840 return true;
841 }
842 }
843 }
Costin Manolache360e4542009-09-04 13:36:04 -0700844
Dianne Hackborn231cc602009-04-27 17:10:36 -0700845 return false;
846 }
Costin Manolache360e4542009-09-04 13:36:04 -0700847
Dianne Hackborn231cc602009-04-27 17:10:36 -0700848 public PendingOperation insertIntoPending(PendingOperation op) {
849 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800850 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700851 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800852 + " user=" + op.userId
853 + " auth=" + op.authority
854 + " src=" + op.syncSource
855 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700856 }
Costin Manolache360e4542009-09-04 13:36:04 -0700857
Amith Yamasani04e0d262012-02-14 11:50:53 -0800858 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700859 op.authority,
860 -1 /* desired identifier */,
861 true /* write accounts to storage */);
862 if (authority == null) {
863 return null;
864 }
Costin Manolache360e4542009-09-04 13:36:04 -0700865
Dianne Hackborn231cc602009-04-27 17:10:36 -0700866 op = new PendingOperation(op);
867 op.authorityId = authority.ident;
868 mPendingOperations.add(op);
869 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700870
Dianne Hackborn231cc602009-04-27 17:10:36 -0700871 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
872 status.pending = true;
873 }
Costin Manolache360e4542009-09-04 13:36:04 -0700874
Fred Quintanaac9385e2009-06-22 18:00:59 -0700875 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700876 return op;
877 }
878
879 public boolean deleteFromPending(PendingOperation op) {
880 boolean res = false;
881 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800882 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700883 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800884 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700885 + " auth=" + op.authority
886 + " src=" + op.syncSource
887 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700888 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700889 if (mPendingOperations.remove(op)) {
890 if (mPendingOperations.size() == 0
891 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
892 writePendingOperationsLocked();
893 mNumPendingFinished = 0;
894 } else {
895 mNumPendingFinished++;
896 }
Costin Manolache360e4542009-09-04 13:36:04 -0700897
Amith Yamasani04e0d262012-02-14 11:50:53 -0800898 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700899 "deleteFromPending");
900 if (authority != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800901 if (DEBUG) Log.v(TAG, "removing - " + authority);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700902 final int N = mPendingOperations.size();
903 boolean morePending = false;
904 for (int i=0; i<N; i++) {
905 PendingOperation cur = mPendingOperations.get(i);
906 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800907 && cur.authority.equals(op.authority)
908 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700909 morePending = true;
910 break;
911 }
912 }
Costin Manolache360e4542009-09-04 13:36:04 -0700913
Dianne Hackborn231cc602009-04-27 17:10:36 -0700914 if (!morePending) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800915 if (DEBUG) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700916 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
917 status.pending = false;
918 }
919 }
Costin Manolache360e4542009-09-04 13:36:04 -0700920
Dianne Hackborn231cc602009-04-27 17:10:36 -0700921 res = true;
922 }
923 }
Costin Manolache360e4542009-09-04 13:36:04 -0700924
Fred Quintanaac9385e2009-06-22 18:00:59 -0700925 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700926 return res;
927 }
928
Dianne Hackborn231cc602009-04-27 17:10:36 -0700929 /**
930 * Return a copy of the current array of pending operations. The
931 * PendingOperation objects are the real objects stored inside, so that
932 * they can be used with deleteFromPending().
933 */
934 public ArrayList<PendingOperation> getPendingOperations() {
935 synchronized (mAuthorities) {
936 return new ArrayList<PendingOperation>(mPendingOperations);
937 }
938 }
Costin Manolache360e4542009-09-04 13:36:04 -0700939
Dianne Hackborn231cc602009-04-27 17:10:36 -0700940 /**
941 * Return the number of currently pending operations.
942 */
943 public int getPendingOperationCount() {
944 synchronized (mAuthorities) {
945 return mPendingOperations.size();
946 }
947 }
Costin Manolache360e4542009-09-04 13:36:04 -0700948
Dianne Hackborn231cc602009-04-27 17:10:36 -0700949 /**
950 * Called when the set of account has changed, given the new array of
951 * active accounts.
952 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800953 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700954 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800955 if (DEBUG) Log.v(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700956 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
957 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
958 while (accIt.hasNext()) {
959 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800960 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
961 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700962 // This account no longer exists...
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800963 if (DEBUG) {
964 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700965 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700966 for (AuthorityInfo auth : acc.authorities.values()) {
967 removing.put(auth.ident, auth);
968 }
969 accIt.remove();
970 }
971 }
Costin Manolache360e4542009-09-04 13:36:04 -0700972
Dianne Hackborn231cc602009-04-27 17:10:36 -0700973 // Clean out all data structures.
974 int i = removing.size();
975 if (i > 0) {
976 while (i > 0) {
977 i--;
978 int ident = removing.keyAt(i);
979 mAuthorities.remove(ident);
980 int j = mSyncStatus.size();
981 while (j > 0) {
982 j--;
983 if (mSyncStatus.keyAt(j) == ident) {
984 mSyncStatus.remove(mSyncStatus.keyAt(j));
985 }
986 }
987 j = mSyncHistory.size();
988 while (j > 0) {
989 j--;
990 if (mSyncHistory.get(j).authorityId == ident) {
991 mSyncHistory.remove(j);
992 }
993 }
994 }
995 writeAccountInfoLocked();
996 writeStatusLocked();
997 writePendingOperationsLocked();
998 writeStatisticsLocked();
999 }
1000 }
1001 }
1002
1003 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001004 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1005 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001006 */
Fred Quintana918339a2010-10-05 14:00:39 -07001007 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1008 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001009 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001010 if (DEBUG) {
Fred Quintana918339a2010-10-05 14:00:39 -07001011 Log.v(TAG, "setActiveSync: account="
1012 + activeSyncContext.mSyncOperation.account
1013 + " auth=" + activeSyncContext.mSyncOperation.authority
1014 + " src=" + activeSyncContext.mSyncOperation.syncSource
1015 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001016 }
Fred Quintana918339a2010-10-05 14:00:39 -07001017 AuthorityInfo authority = getOrCreateAuthorityLocked(
1018 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001019 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -07001020 activeSyncContext.mSyncOperation.authority,
1021 -1 /* assign a new identifier if creating a new authority */,
1022 true /* write to storage if this results in a change */);
1023 syncInfo = new SyncInfo(authority.ident,
1024 authority.account, authority.authority,
1025 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001026 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001027 }
Costin Manolache360e4542009-09-04 13:36:04 -07001028
Fred Quintana918339a2010-10-05 14:00:39 -07001029 reportActiveChange();
1030 return syncInfo;
1031 }
1032
1033 /**
1034 * Called to indicate that a previously active sync is no longer active.
1035 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001036 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001037 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001038 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001039 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1040 + " user=" + userId
1041 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001042 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001043 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001044 }
1045
1046 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001047 }
1048
1049 /**
1050 * To allow others to send active change reports, to poke clients.
1051 */
1052 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001053 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001054 }
Costin Manolache360e4542009-09-04 13:36:04 -07001055
Dianne Hackborn231cc602009-04-27 17:10:36 -07001056 /**
1057 * Note that sync has started for the given account and authority.
1058 */
Alon Albert57286f92012-10-09 14:21:38 -07001059 public long insertStartSyncEvent(Account accountName, int userId, int reason,
1060 String authorityName, long now, int source, boolean initialization, Bundle extras) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001061 long id;
1062 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001063 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001064 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001065 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001066 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001067 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001068 "insertStartSyncEvent");
1069 if (authority == null) {
1070 return -1;
1071 }
1072 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001073 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001074 item.authorityId = authority.ident;
1075 item.historyId = mNextHistoryId++;
1076 if (mNextHistoryId < 0) mNextHistoryId = 0;
1077 item.eventTime = now;
1078 item.source = source;
Alon Albert57286f92012-10-09 14:21:38 -07001079 item.reason = reason;
1080 item.extras = extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001081 item.event = EVENT_START;
1082 mSyncHistory.add(0, item);
1083 while (mSyncHistory.size() > MAX_HISTORY) {
1084 mSyncHistory.remove(mSyncHistory.size()-1);
1085 }
1086 id = item.historyId;
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001087 if (DEBUG) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001088 }
Costin Manolache360e4542009-09-04 13:36:04 -07001089
Fred Quintanaac9385e2009-06-22 18:00:59 -07001090 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001091 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
1093
Fred Quintana77c560f2010-03-29 22:20:26 -07001094 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001096 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001097 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001098 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1099 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001100 SyncHistoryItem item = null;
1101 int i = mSyncHistory.size();
1102 while (i > 0) {
1103 i--;
1104 item = mSyncHistory.get(i);
1105 if (item.historyId == historyId) {
1106 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001108 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
Costin Manolache360e4542009-09-04 13:36:04 -07001110
Dianne Hackborn231cc602009-04-27 17:10:36 -07001111 if (item == null) {
1112 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1113 return;
1114 }
Costin Manolache360e4542009-09-04 13:36:04 -07001115
Dianne Hackborn231cc602009-04-27 17:10:36 -07001116 item.elapsedTime = elapsedTime;
1117 item.event = EVENT_STOP;
1118 item.mesg = resultMessage;
1119 item.downstreamActivity = downstreamActivity;
1120 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001121
Dianne Hackborn231cc602009-04-27 17:10:36 -07001122 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001123
Dianne Hackborn231cc602009-04-27 17:10:36 -07001124 status.numSyncs++;
1125 status.totalElapsedTime += elapsedTime;
1126 switch (item.source) {
1127 case SOURCE_LOCAL:
1128 status.numSourceLocal++;
1129 break;
1130 case SOURCE_POLL:
1131 status.numSourcePoll++;
1132 break;
1133 case SOURCE_USER:
1134 status.numSourceUser++;
1135 break;
1136 case SOURCE_SERVER:
1137 status.numSourceServer++;
1138 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001139 case SOURCE_PERIODIC:
1140 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001141 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001142 }
Costin Manolache360e4542009-09-04 13:36:04 -07001143
Dianne Hackborn231cc602009-04-27 17:10:36 -07001144 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001145 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001146 if (mDayStats[0] == null) {
1147 mDayStats[0] = new DayStats(day);
1148 } else if (day != mDayStats[0].day) {
1149 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1150 mDayStats[0] = new DayStats(day);
1151 writeStatisticsNow = true;
1152 } else if (mDayStats[0] == null) {
1153 }
1154 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001155
Dianne Hackborn231cc602009-04-27 17:10:36 -07001156 final long lastSyncTime = (item.eventTime + elapsedTime);
1157 boolean writeStatusNow = false;
1158 if (MESG_SUCCESS.equals(resultMessage)) {
1159 // - if successful, update the successful columns
1160 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1161 writeStatusNow = true;
1162 }
1163 status.lastSuccessTime = lastSyncTime;
1164 status.lastSuccessSource = item.source;
1165 status.lastFailureTime = 0;
1166 status.lastFailureSource = -1;
1167 status.lastFailureMesg = null;
1168 status.initialFailureTime = 0;
1169 ds.successCount++;
1170 ds.successTime += elapsedTime;
1171 } else if (!MESG_CANCELED.equals(resultMessage)) {
1172 if (status.lastFailureTime == 0) {
1173 writeStatusNow = true;
1174 }
1175 status.lastFailureTime = lastSyncTime;
1176 status.lastFailureSource = item.source;
1177 status.lastFailureMesg = resultMessage;
1178 if (status.initialFailureTime == 0) {
1179 status.initialFailureTime = lastSyncTime;
1180 }
1181 ds.failureCount++;
1182 ds.failureTime += elapsedTime;
1183 }
Costin Manolache360e4542009-09-04 13:36:04 -07001184
Dianne Hackborn231cc602009-04-27 17:10:36 -07001185 if (writeStatusNow) {
1186 writeStatusLocked();
1187 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1188 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1189 WRITE_STATUS_DELAY);
1190 }
1191 if (writeStatisticsNow) {
1192 writeStatisticsLocked();
1193 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1194 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1195 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001196 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001197 }
Costin Manolache360e4542009-09-04 13:36:04 -07001198
Fred Quintanaac9385e2009-06-22 18:00:59 -07001199 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001200 }
1201
1202 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001203 * Return a list of the currently active syncs. Note that the returned items are the
1204 * real, live active sync objects, so be careful what you do with it.
1205 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001206 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001207 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001208 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1209 if (syncs == null) {
1210 syncs = new ArrayList<SyncInfo>();
1211 mCurrentSyncs.put(userId, syncs);
1212 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001213 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001214 }
1215 }
Costin Manolache360e4542009-09-04 13:36:04 -07001216
Dianne Hackborn231cc602009-04-27 17:10:36 -07001217 /**
1218 * Return an array of the current sync status for all authorities. Note
1219 * that the objects inside the array are the real, live status objects,
1220 * so be careful what you do with them.
1221 */
1222 public ArrayList<SyncStatusInfo> getSyncStatus() {
1223 synchronized (mAuthorities) {
1224 final int N = mSyncStatus.size();
1225 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1226 for (int i=0; i<N; i++) {
1227 ops.add(mSyncStatus.valueAt(i));
1228 }
1229 return ops;
1230 }
1231 }
Costin Manolache360e4542009-09-04 13:36:04 -07001232
Dianne Hackborn231cc602009-04-27 17:10:36 -07001233 /**
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001234 * Return a copy of the specified authority with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001235 */
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001236 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(
1237 Account account, int userId, String authority) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001238 synchronized (mAuthorities) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001239 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(account, userId, authority,
1240 -1 /* assign a new identifier if creating a new authority */,
1241 true /* write to storage if this results in a change */);
1242 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1243 }
1244 }
1245
1246 /**
1247 * Return a copy of all authorities with their corresponding sync status
1248 */
1249 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1250 synchronized (mAuthorities) {
1251 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1252 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1253 for (int i = 0; i < mAuthorities.size(); i++) {
1254 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001255 }
1256 return infos;
1257 }
1258 }
1259
1260 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001261 * Returns the status that matches the authority and account.
1262 *
1263 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001264 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001265 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001266 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001267 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1268 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001269 if (account == null || authority == null) {
1270 throw new IllegalArgumentException();
1271 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001272 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001273 final int N = mSyncStatus.size();
1274 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001275 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001276 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001277
Amith Yamasani04e0d262012-02-14 11:50:53 -08001278 if (ainfo != null && ainfo.authority.equals(authority)
1279 && ainfo.userId == userId
1280 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001281 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001282 }
1283 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001284 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001285 }
1286 }
Costin Manolache360e4542009-09-04 13:36:04 -07001287
Dianne Hackborn231cc602009-04-27 17:10:36 -07001288 /**
1289 * Return true if the pending status is true of any matching authorities.
1290 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001291 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001292 synchronized (mAuthorities) {
1293 final int N = mSyncStatus.size();
1294 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001295 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001296 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1297 if (ainfo == null) {
1298 continue;
1299 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001300 if (userId != ainfo.userId) {
1301 continue;
1302 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001303 if (account != null && !ainfo.account.equals(account)) {
1304 continue;
1305 }
1306 if (ainfo.authority.equals(authority) && cur.pending) {
1307 return true;
1308 }
1309 }
1310 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 }
1312 }
1313
1314 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001315 * Return an array of the current sync status for all authorities. 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 ArrayList<SyncHistoryItem> getSyncHistory() {
1320 synchronized (mAuthorities) {
1321 final int N = mSyncHistory.size();
1322 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1323 for (int i=0; i<N; i++) {
1324 items.add(mSyncHistory.get(i));
1325 }
1326 return items;
1327 }
1328 }
Costin Manolache360e4542009-09-04 13:36:04 -07001329
Dianne Hackborn231cc602009-04-27 17:10:36 -07001330 /**
1331 * Return an array of the current per-day statistics. Note
1332 * that the objects inside the array are the real, live status objects,
1333 * so be careful what you do with them.
1334 */
1335 public DayStats[] getDayStatistics() {
1336 synchronized (mAuthorities) {
1337 DayStats[] ds = new DayStats[mDayStats.length];
1338 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1339 return ds;
1340 }
1341 }
Costin Manolache360e4542009-09-04 13:36:04 -07001342
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001343 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1344 AuthorityInfo authorityInfo) {
1345 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1346 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1347 }
1348
Dianne Hackborn55280a92009-05-07 15:53:46 -07001349 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001350 mCal.setTimeInMillis(System.currentTimeMillis());
1351 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1352 if (mYear != mCal.get(Calendar.YEAR)) {
1353 mYear = mCal.get(Calendar.YEAR);
1354 mCal.clear();
1355 mCal.set(Calendar.YEAR, mYear);
1356 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1357 }
1358 return dayOfYear + mYearInDays;
1359 }
Costin Manolache360e4542009-09-04 13:36:04 -07001360
Dianne Hackborn231cc602009-04-27 17:10:36 -07001361 /**
1362 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001363 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001364 * @param accountName The name of the account for the authority.
1365 * @param authorityName The name of the authority itself.
1366 * @param tag If non-null, this will be used in a log message if the
1367 * requested authority does not exist.
1368 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001369 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001370 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001371 AccountAndUser au = new AccountAndUser(accountName, userId);
1372 AccountInfo accountInfo = mAccounts.get(au);
1373 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001374 if (tag != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001375 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001376 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001377 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001378 }
1379 return null;
1380 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001381 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001382 if (authority == null) {
1383 if (tag != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001384 if (DEBUG) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001385 Log.v(TAG, tag + ": unknown authority " + authorityName);
1386 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001387 }
1388 return null;
1389 }
Costin Manolache360e4542009-09-04 13:36:04 -07001390
Dianne Hackborn231cc602009-04-27 17:10:36 -07001391 return authority;
1392 }
Costin Manolache360e4542009-09-04 13:36:04 -07001393
Amith Yamasani04e0d262012-02-14 11:50:53 -08001394 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001395 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001396 AccountAndUser au = new AccountAndUser(accountName, userId);
1397 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001398 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001399 account = new AccountInfo(au);
1400 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001401 }
1402 AuthorityInfo authority = account.authorities.get(authorityName);
1403 if (authority == null) {
1404 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001405 ident = mNextAuthorityId;
1406 mNextAuthorityId++;
1407 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001408 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001409 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001410 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001411 + ", user " + userId
1412 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001413 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001414 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001415 account.authorities.put(authorityName, authority);
1416 mAuthorities.put(ident, authority);
1417 if (doWrite) {
1418 writeAccountInfoLocked();
1419 }
1420 }
Costin Manolache360e4542009-09-04 13:36:04 -07001421
Dianne Hackborn231cc602009-04-27 17:10:36 -07001422 return authority;
1423 }
Costin Manolache360e4542009-09-04 13:36:04 -07001424
Amith Yamasani04e0d262012-02-14 11:50:53 -08001425 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1426 boolean doWrite) {
1427 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001428 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001429 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1430 if (authorityInfo != null) {
1431 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001432 if (doWrite) {
1433 writeAccountInfoLocked();
1434 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001435 }
1436 }
1437 }
1438
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001439 /**
1440 * Updates (in a synchronized way) the periodic sync time of the specified
1441 * authority id and target periodic sync
1442 */
1443 public void setPeriodicSyncTime(
1444 int authorityId, Pair<Bundle, Long> targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001445 boolean found = false;
1446 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001447 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001448 authorityInfo = mAuthorities.get(authorityId);
1449 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
1450 Pair<Bundle, Long> periodicSync = authorityInfo.periodicSyncs.get(i);
1451 if (PeriodicSync.syncExtrasEquals(periodicSync.first, targetPeriodicSync.first)
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001452 && periodicSync.second == targetPeriodicSync.second) {
1453 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001454 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001455 break;
1456 }
1457 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001458 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001459
1460 if (!found) {
1461 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
1462 "Authority: " + authorityInfo.authority);
1463 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001464 }
1465
Dianne Hackborn231cc602009-04-27 17:10:36 -07001466 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1467 SyncStatusInfo status = mSyncStatus.get(authorityId);
1468 if (status == null) {
1469 status = new SyncStatusInfo(authorityId);
1470 mSyncStatus.put(authorityId, status);
1471 }
1472 return status;
1473 }
Costin Manolache360e4542009-09-04 13:36:04 -07001474
Dianne Hackborn55280a92009-05-07 15:53:46 -07001475 public void writeAllState() {
1476 synchronized (mAuthorities) {
1477 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001478
Dianne Hackborn55280a92009-05-07 15:53:46 -07001479 if (mNumPendingFinished > 0) {
1480 // Only write these if they are out of date.
1481 writePendingOperationsLocked();
1482 }
Costin Manolache360e4542009-09-04 13:36:04 -07001483
Dianne Hackborn55280a92009-05-07 15:53:46 -07001484 // Just always write these... they are likely out of date.
1485 writeStatusLocked();
1486 writeStatisticsLocked();
1487 }
1488 }
Costin Manolache360e4542009-09-04 13:36:04 -07001489
Dianne Hackborn231cc602009-04-27 17:10:36 -07001490 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001491 * public for testing
1492 */
1493 public void clearAndReadState() {
1494 synchronized (mAuthorities) {
1495 mAuthorities.clear();
1496 mAccounts.clear();
1497 mPendingOperations.clear();
1498 mSyncStatus.clear();
1499 mSyncHistory.clear();
1500
1501 readAccountInfoLocked();
1502 readStatusLocked();
1503 readPendingOperationsLocked();
1504 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001505 readAndDeleteLegacyAccountInfoLocked();
1506 writeAccountInfoLocked();
1507 writeStatusLocked();
1508 writePendingOperationsLocked();
1509 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001510 }
1511 }
1512
1513 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001514 * Read all account information back in to the initial engine state.
1515 */
1516 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001517 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001518 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001520 fis = mAccountInfoFile.openRead();
1521 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1522 XmlPullParser parser = Xml.newPullParser();
1523 parser.setInput(fis, null);
1524 int eventType = parser.getEventType();
1525 while (eventType != XmlPullParser.START_TAG) {
1526 eventType = parser.next();
1527 }
1528 String tagName = parser.getName();
1529 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001530 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001531 String versionString = parser.getAttributeValue(null, "version");
1532 int version;
1533 try {
1534 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1535 } catch (NumberFormatException e) {
1536 version = 0;
1537 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001538 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001539 try {
1540 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1541 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1542 } catch (NumberFormatException e) {
1543 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001544 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001545 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1546 try {
1547 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1548 } catch (NumberFormatException e) {
1549 mSyncRandomOffset = 0;
1550 }
1551 if (mSyncRandomOffset == 0) {
1552 Random random = new Random(System.currentTimeMillis());
1553 mSyncRandomOffset = random.nextInt(86400);
1554 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001555 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001556 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001557 AuthorityInfo authority = null;
1558 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001559 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001560 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001561 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001562 if (parser.getDepth() == 2) {
1563 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001564 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001565 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001566 if (authority.ident > highestAuthorityId) {
1567 highestAuthorityId = authority.ident;
1568 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001569 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1570 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001571 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001572 } else if (parser.getDepth() == 3) {
1573 if ("periodicSync".equals(tagName) && authority != null) {
1574 periodicSync = parsePeriodicSync(parser, authority);
1575 }
1576 } else if (parser.getDepth() == 4 && periodicSync != null) {
1577 if ("extra".equals(tagName)) {
1578 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001579 }
1580 }
1581 }
1582 eventType = parser.next();
1583 } while (eventType != XmlPullParser.END_DOCUMENT);
1584 }
1585 } catch (XmlPullParserException e) {
1586 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001587 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001588 } catch (java.io.IOException e) {
1589 if (fis == null) Log.i(TAG, "No initial accounts");
1590 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001591 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001592 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001593 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001594 if (fis != null) {
1595 try {
1596 fis.close();
1597 } catch (java.io.IOException e1) {
1598 }
1599 }
1600 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001601
Fred Quintana77c560f2010-03-29 22:20:26 -07001602 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001603 }
Costin Manolache360e4542009-09-04 13:36:04 -07001604
Fred Quintanafb084402010-03-23 17:57:03 -07001605 /**
1606 * some authority names have changed. copy over their settings and delete the old ones
1607 * @return true if a change was made
1608 */
1609 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1610 boolean writeNeeded = false;
1611
1612 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1613 final int N = mAuthorities.size();
1614 for (int i=0; i<N; i++) {
1615 AuthorityInfo authority = mAuthorities.valueAt(i);
1616 // skip this authority if it isn't one of the renamed ones
1617 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1618 if (newAuthorityName == null) {
1619 continue;
1620 }
1621
1622 // remember this authority so we can remove it later. we can't remove it
1623 // now without messing up this loop iteration
1624 authoritiesToRemove.add(authority);
1625
1626 // this authority isn't enabled, no need to copy it to the new authority name since
1627 // the default is "disabled"
1628 if (!authority.enabled) {
1629 continue;
1630 }
1631
1632 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001633 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1634 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001635 continue;
1636 }
1637
1638 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001639 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001640 newAuthority.enabled = true;
1641 writeNeeded = true;
1642 }
1643
1644 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001645 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1646 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001647 writeNeeded = true;
1648 }
1649
1650 return writeNeeded;
1651 }
1652
Amith Yamasani04e0d262012-02-14 11:50:53 -08001653 private void parseListenForTickles(XmlPullParser parser) {
1654 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1655 int userId = 0;
1656 try {
1657 userId = Integer.parseInt(user);
1658 } catch (NumberFormatException e) {
1659 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1660 } catch (NullPointerException e) {
1661 Log.e(TAG, "the user in listen-for-tickles is null", e);
1662 }
1663 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1664 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1665 mMasterSyncAutomatically.put(userId, listen);
1666 }
1667
Fred Quintanac2e46912010-03-15 16:10:44 -07001668 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001669 AuthorityInfo authority = null;
1670 int id = -1;
1671 try {
1672 id = Integer.parseInt(parser.getAttributeValue(
1673 null, "id"));
1674 } catch (NumberFormatException e) {
1675 Log.e(TAG, "error parsing the id of the authority", e);
1676 } catch (NullPointerException e) {
1677 Log.e(TAG, "the id of the authority is null", e);
1678 }
1679 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001680 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001681 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001682 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001683 String accountName = parser.getAttributeValue(null, "account");
1684 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001685 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1686 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001687 if (accountType == null) {
1688 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001689 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001690 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001691 authority = mAuthorities.get(id);
1692 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1693 + accountName + " auth=" + authorityName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001694 + " user=" + userId
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001695 + " enabled=" + enabled
1696 + " syncable=" + syncable);
1697 if (authority == null) {
1698 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1699 authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001700 new Account(accountName, accountType), userId, authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001701 // If the version is 0 then we are upgrading from a file format that did not
1702 // know about periodic syncs. In that case don't clear the list since we
1703 // want the default, which is a daily periodioc sync.
1704 // Otherwise clear out this default list since we will populate it later with
1705 // the periodic sync descriptions that are read from the configuration file.
1706 if (version > 0) {
1707 authority.periodicSyncs.clear();
1708 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001709 }
1710 if (authority != null) {
1711 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1712 if ("unknown".equals(syncable)) {
1713 authority.syncable = -1;
1714 } else {
1715 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001716 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001717 }
1718 } else {
1719 Log.w(TAG, "Failure adding authority: account="
1720 + accountName + " auth=" + authorityName
1721 + " enabled=" + enabled
1722 + " syncable=" + syncable);
1723 }
1724 }
1725
1726 return authority;
1727 }
1728
1729 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1730 Bundle extras = new Bundle();
1731 String periodValue = parser.getAttributeValue(null, "period");
1732 final long period;
1733 try {
1734 period = Long.parseLong(periodValue);
1735 } catch (NumberFormatException e) {
1736 Log.e(TAG, "error parsing the period of a periodic sync", e);
1737 return null;
1738 } catch (NullPointerException e) {
1739 Log.e(TAG, "the period of a periodic sync is null", e);
1740 return null;
1741 }
1742 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1743 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001744
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001745 return periodicSync;
1746 }
1747
1748 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1749 final Bundle extras = periodicSync.first;
1750 String name = parser.getAttributeValue(null, "name");
1751 String type = parser.getAttributeValue(null, "type");
1752 String value1 = parser.getAttributeValue(null, "value1");
1753 String value2 = parser.getAttributeValue(null, "value2");
1754
1755 try {
1756 if ("long".equals(type)) {
1757 extras.putLong(name, Long.parseLong(value1));
1758 } else if ("integer".equals(type)) {
1759 extras.putInt(name, Integer.parseInt(value1));
1760 } else if ("double".equals(type)) {
1761 extras.putDouble(name, Double.parseDouble(value1));
1762 } else if ("float".equals(type)) {
1763 extras.putFloat(name, Float.parseFloat(value1));
1764 } else if ("boolean".equals(type)) {
1765 extras.putBoolean(name, Boolean.parseBoolean(value1));
1766 } else if ("string".equals(type)) {
1767 extras.putString(name, value1);
1768 } else if ("account".equals(type)) {
1769 extras.putParcelable(name, new Account(value1, value2));
1770 }
1771 } catch (NumberFormatException e) {
1772 Log.e(TAG, "error parsing bundle value", e);
1773 } catch (NullPointerException e) {
1774 Log.e(TAG, "error parsing bundle value", e);
1775 }
1776 }
1777
Dianne Hackborn231cc602009-04-27 17:10:36 -07001778 /**
1779 * Write all account information to the account file.
1780 */
1781 private void writeAccountInfoLocked() {
1782 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1783 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001784
Dianne Hackborn231cc602009-04-27 17:10:36 -07001785 try {
1786 fos = mAccountInfoFile.startWrite();
1787 XmlSerializer out = new FastXmlSerializer();
1788 out.setOutput(fos, "utf-8");
1789 out.startDocument(null, true);
1790 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001791
Dianne Hackborn231cc602009-04-27 17:10:36 -07001792 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001793 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001794 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001795 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001796
1797 // Write the Sync Automatically flags for each user
1798 final int M = mMasterSyncAutomatically.size();
1799 for (int m = 0; m < M; m++) {
1800 int userId = mMasterSyncAutomatically.keyAt(m);
1801 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1802 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1803 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1804 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1805 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001806 }
Costin Manolache360e4542009-09-04 13:36:04 -07001807
Dianne Hackborn231cc602009-04-27 17:10:36 -07001808 final int N = mAuthorities.size();
1809 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001810 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001811 out.startTag(null, "authority");
1812 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001813 out.attribute(null, "account", authority.account.name);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001814 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001815 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001816 out.attribute(null, "authority", authority.authority);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001817 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Fred Quintana5e787c42009-08-16 23:13:53 -07001818 if (authority.syncable < 0) {
1819 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001820 } else {
1821 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001822 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001823 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1824 out.startTag(null, "periodicSync");
1825 out.attribute(null, "period", Long.toString(periodicSync.second));
1826 final Bundle extras = periodicSync.first;
1827 for (String key : extras.keySet()) {
1828 out.startTag(null, "extra");
1829 out.attribute(null, "name", key);
1830 final Object value = extras.get(key);
1831 if (value instanceof Long) {
1832 out.attribute(null, "type", "long");
1833 out.attribute(null, "value1", value.toString());
1834 } else if (value instanceof Integer) {
1835 out.attribute(null, "type", "integer");
1836 out.attribute(null, "value1", value.toString());
1837 } else if (value instanceof Boolean) {
1838 out.attribute(null, "type", "boolean");
1839 out.attribute(null, "value1", value.toString());
1840 } else if (value instanceof Float) {
1841 out.attribute(null, "type", "float");
1842 out.attribute(null, "value1", value.toString());
1843 } else if (value instanceof Double) {
1844 out.attribute(null, "type", "double");
1845 out.attribute(null, "value1", value.toString());
1846 } else if (value instanceof String) {
1847 out.attribute(null, "type", "string");
1848 out.attribute(null, "value1", value.toString());
1849 } else if (value instanceof Account) {
1850 out.attribute(null, "type", "account");
1851 out.attribute(null, "value1", ((Account)value).name);
1852 out.attribute(null, "value2", ((Account)value).type);
1853 }
1854 out.endTag(null, "extra");
1855 }
1856 out.endTag(null, "periodicSync");
1857 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001858 out.endTag(null, "authority");
1859 }
Costin Manolache360e4542009-09-04 13:36:04 -07001860
Dianne Hackborn231cc602009-04-27 17:10:36 -07001861 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001862
Dianne Hackborn231cc602009-04-27 17:10:36 -07001863 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001864
Dianne Hackborn231cc602009-04-27 17:10:36 -07001865 mAccountInfoFile.finishWrite(fos);
1866 } catch (java.io.IOException e1) {
1867 Log.w(TAG, "Error writing accounts", e1);
1868 if (fos != null) {
1869 mAccountInfoFile.failWrite(fos);
1870 }
1871 }
1872 }
Costin Manolache360e4542009-09-04 13:36:04 -07001873
Dianne Hackborn231cc602009-04-27 17:10:36 -07001874 static int getIntColumn(Cursor c, String name) {
1875 return c.getInt(c.getColumnIndex(name));
1876 }
Costin Manolache360e4542009-09-04 13:36:04 -07001877
Dianne Hackborn231cc602009-04-27 17:10:36 -07001878 static long getLongColumn(Cursor c, String name) {
1879 return c.getLong(c.getColumnIndex(name));
1880 }
Costin Manolache360e4542009-09-04 13:36:04 -07001881
Dianne Hackborn231cc602009-04-27 17:10:36 -07001882 /**
1883 * Load sync engine state from the old syncmanager database, and then
1884 * erase it. Note that we don't deal with pending operations, active
1885 * sync, or history.
1886 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001887 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001888 // Look for old database to initialize from.
1889 File file = mContext.getDatabasePath("syncmanager.db");
1890 if (!file.exists()) {
1891 return;
1892 }
1893 String path = file.getPath();
1894 SQLiteDatabase db = null;
1895 try {
1896 db = SQLiteDatabase.openDatabase(path, null,
1897 SQLiteDatabase.OPEN_READONLY);
1898 } catch (SQLiteException e) {
1899 }
Costin Manolache360e4542009-09-04 13:36:04 -07001900
Dianne Hackborn231cc602009-04-27 17:10:36 -07001901 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001902 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001903
Dianne Hackborn231cc602009-04-27 17:10:36 -07001904 // Copy in all of the status information, as well as accounts.
1905 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1906 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1907 qb.setTables("stats, status");
1908 HashMap<String,String> map = new HashMap<String,String>();
1909 map.put("_id", "status._id as _id");
1910 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001911 if (hasType) {
1912 map.put("account_type", "stats.account_type as account_type");
1913 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001914 map.put("authority", "stats.authority as authority");
1915 map.put("totalElapsedTime", "totalElapsedTime");
1916 map.put("numSyncs", "numSyncs");
1917 map.put("numSourceLocal", "numSourceLocal");
1918 map.put("numSourcePoll", "numSourcePoll");
1919 map.put("numSourceServer", "numSourceServer");
1920 map.put("numSourceUser", "numSourceUser");
1921 map.put("lastSuccessSource", "lastSuccessSource");
1922 map.put("lastSuccessTime", "lastSuccessTime");
1923 map.put("lastFailureSource", "lastFailureSource");
1924 map.put("lastFailureTime", "lastFailureTime");
1925 map.put("lastFailureMesg", "lastFailureMesg");
1926 map.put("pending", "pending");
1927 qb.setProjectionMap(map);
1928 qb.appendWhere("stats._id = status.stats_id");
1929 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001931 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001932 String accountType = hasType
1933 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001934 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001935 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001937 String authorityName = c.getString(c.getColumnIndex("authority"));
1938 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001939 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07001940 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001941 if (authority != null) {
1942 int i = mSyncStatus.size();
1943 boolean found = false;
1944 SyncStatusInfo st = null;
1945 while (i > 0) {
1946 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001947 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001948 if (st.authorityId == authority.ident) {
1949 found = true;
1950 break;
1951 }
1952 }
1953 if (!found) {
1954 st = new SyncStatusInfo(authority.ident);
1955 mSyncStatus.put(authority.ident, st);
1956 }
1957 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1958 st.numSyncs = getIntColumn(c, "numSyncs");
1959 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1960 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1961 st.numSourceServer = getIntColumn(c, "numSourceServer");
1962 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001963 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001964 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1965 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1966 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1967 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1968 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1969 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 }
Costin Manolache360e4542009-09-04 13:36:04 -07001972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001974
Dianne Hackborn231cc602009-04-27 17:10:36 -07001975 // Retrieve the settings.
1976 qb = new SQLiteQueryBuilder();
1977 qb.setTables("settings");
1978 c = qb.query(db, null, null, null, null, null, null);
1979 while (c.moveToNext()) {
1980 String name = c.getString(c.getColumnIndex("name"));
1981 String value = c.getString(c.getColumnIndex("value"));
1982 if (name == null) continue;
1983 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001984 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001985 } else if (name.startsWith("sync_provider_")) {
1986 String provider = name.substring("sync_provider_".length(),
1987 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001988 int i = mAuthorities.size();
1989 while (i > 0) {
1990 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001991 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001992 if (authority.authority.equals(provider)) {
1993 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001994 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001995 }
1996 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 }
Costin Manolache360e4542009-09-04 13:36:04 -07001999
Dianne Hackborn231cc602009-04-27 17:10:36 -07002000 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002001
Dianne Hackborn231cc602009-04-27 17:10:36 -07002002 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002003
Dianne Hackborn231cc602009-04-27 17:10:36 -07002004 (new File(path)).delete();
2005 }
2006 }
Costin Manolache360e4542009-09-04 13:36:04 -07002007
Dianne Hackborn231cc602009-04-27 17:10:36 -07002008 public static final int STATUS_FILE_END = 0;
2009 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002010
Dianne Hackborn231cc602009-04-27 17:10:36 -07002011 /**
2012 * Read all sync status back in to the initial engine state.
2013 */
2014 private void readStatusLocked() {
2015 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
2016 try {
2017 byte[] data = mStatusFile.readFully();
2018 Parcel in = Parcel.obtain();
2019 in.unmarshall(data, 0, data.length);
2020 in.setDataPosition(0);
2021 int token;
2022 while ((token=in.readInt()) != STATUS_FILE_END) {
2023 if (token == STATUS_FILE_ITEM) {
2024 SyncStatusInfo status = new SyncStatusInfo(in);
2025 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2026 status.pending = false;
2027 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
2028 + status.authorityId);
2029 mSyncStatus.put(status.authorityId, status);
2030 }
2031 } else {
2032 // Ooops.
2033 Log.w(TAG, "Unknown status token: " + token);
2034 break;
2035 }
2036 }
2037 } catch (java.io.IOException e) {
2038 Log.i(TAG, "No initial status");
2039 }
2040 }
Costin Manolache360e4542009-09-04 13:36:04 -07002041
Dianne Hackborn231cc602009-04-27 17:10:36 -07002042 /**
2043 * Write all sync status to the sync status file.
2044 */
2045 private void writeStatusLocked() {
2046 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002047
Dianne Hackborn231cc602009-04-27 17:10:36 -07002048 // The file is being written, so we don't need to have a scheduled
2049 // write until the next change.
2050 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002051
Dianne Hackborn231cc602009-04-27 17:10:36 -07002052 FileOutputStream fos = null;
2053 try {
2054 fos = mStatusFile.startWrite();
2055 Parcel out = Parcel.obtain();
2056 final int N = mSyncStatus.size();
2057 for (int i=0; i<N; i++) {
2058 SyncStatusInfo status = mSyncStatus.valueAt(i);
2059 out.writeInt(STATUS_FILE_ITEM);
2060 status.writeToParcel(out, 0);
2061 }
2062 out.writeInt(STATUS_FILE_END);
2063 fos.write(out.marshall());
2064 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002065
Dianne Hackborn231cc602009-04-27 17:10:36 -07002066 mStatusFile.finishWrite(fos);
2067 } catch (java.io.IOException e1) {
2068 Log.w(TAG, "Error writing status", e1);
2069 if (fos != null) {
2070 mStatusFile.failWrite(fos);
2071 }
2072 }
2073 }
Costin Manolache360e4542009-09-04 13:36:04 -07002074
Alon Albert57286f92012-10-09 14:21:38 -07002075 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002076
Dianne Hackborn231cc602009-04-27 17:10:36 -07002077 /**
2078 * Read all pending operations back in to the initial engine state.
2079 */
2080 private void readPendingOperationsLocked() {
2081 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
2082 try {
2083 byte[] data = mPendingFile.readFully();
2084 Parcel in = Parcel.obtain();
2085 in.unmarshall(data, 0, data.length);
2086 in.setDataPosition(0);
2087 final int SIZE = in.dataSize();
2088 while (in.dataPosition() < SIZE) {
2089 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08002090 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002091 Log.w(TAG, "Unknown pending operation version "
2092 + version + "; dropping all ops");
2093 break;
2094 }
2095 int authorityId = in.readInt();
2096 int syncSource = in.readInt();
2097 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08002098 boolean expedited;
2099 if (version == PENDING_OPERATION_VERSION) {
2100 expedited = in.readInt() != 0;
2101 } else {
2102 expedited = false;
2103 }
Alon Albert57286f92012-10-09 14:21:38 -07002104 int reason = in.readInt();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002105 AuthorityInfo authority = mAuthorities.get(authorityId);
2106 if (authority != null) {
Fred Quintana5695c7b2010-12-06 15:07:52 -08002107 Bundle extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002108 if (flatExtras != null) {
2109 extras = unflattenBundle(flatExtras);
Fred Quintana5695c7b2010-12-06 15:07:52 -08002110 } else {
2111 // if we are unable to parse the extras for whatever reason convert this
2112 // to a regular sync by creating an empty extras
2113 extras = new Bundle();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002114 }
2115 PendingOperation op = new PendingOperation(
Alon Albert57286f92012-10-09 14:21:38 -07002116 authority.account, authority.userId, reason, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08002117 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002118 op.authorityId = authorityId;
2119 op.flatExtras = flatExtras;
2120 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
2121 + " auth=" + op.authority
2122 + " src=" + op.syncSource
Alon Albert57286f92012-10-09 14:21:38 -07002123 + " reason=" + op.reason
Fred Quintana307da1a2010-01-21 14:24:20 -08002124 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07002125 + " extras=" + op.extras);
2126 mPendingOperations.add(op);
2127 }
2128 }
2129 } catch (java.io.IOException e) {
2130 Log.i(TAG, "No initial pending operations");
2131 }
2132 }
Costin Manolache360e4542009-09-04 13:36:04 -07002133
Dianne Hackborn231cc602009-04-27 17:10:36 -07002134 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
2135 out.writeInt(PENDING_OPERATION_VERSION);
2136 out.writeInt(op.authorityId);
2137 out.writeInt(op.syncSource);
2138 if (op.flatExtras == null && op.extras != null) {
2139 op.flatExtras = flattenBundle(op.extras);
2140 }
2141 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08002142 out.writeInt(op.expedited ? 1 : 0);
Alon Albert57286f92012-10-09 14:21:38 -07002143 out.writeInt(op.reason);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002144 }
Costin Manolache360e4542009-09-04 13:36:04 -07002145
Dianne Hackborn231cc602009-04-27 17:10:36 -07002146 /**
2147 * Write all currently pending ops to the pending ops file.
2148 */
2149 private void writePendingOperationsLocked() {
2150 final int N = mPendingOperations.size();
2151 FileOutputStream fos = null;
2152 try {
2153 if (N == 0) {
2154 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2155 mPendingFile.truncate();
2156 return;
2157 }
Costin Manolache360e4542009-09-04 13:36:04 -07002158
Dianne Hackborn231cc602009-04-27 17:10:36 -07002159 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2160 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07002161
Dianne Hackborn231cc602009-04-27 17:10:36 -07002162 Parcel out = Parcel.obtain();
2163 for (int i=0; i<N; i++) {
2164 PendingOperation op = mPendingOperations.get(i);
2165 writePendingOperationLocked(op, out);
2166 }
2167 fos.write(out.marshall());
2168 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002169
Dianne Hackborn231cc602009-04-27 17:10:36 -07002170 mPendingFile.finishWrite(fos);
2171 } catch (java.io.IOException e1) {
2172 Log.w(TAG, "Error writing pending operations", e1);
2173 if (fos != null) {
2174 mPendingFile.failWrite(fos);
2175 }
2176 }
2177 }
Costin Manolache360e4542009-09-04 13:36:04 -07002178
Dianne Hackborn231cc602009-04-27 17:10:36 -07002179 /**
2180 * Append the given operation to the pending ops file; if unable to,
2181 * write all pending ops.
2182 */
2183 private void appendPendingOperationLocked(PendingOperation op) {
2184 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2185 FileOutputStream fos = null;
2186 try {
2187 fos = mPendingFile.openAppend();
2188 } catch (java.io.IOException e) {
2189 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2190 writePendingOperationsLocked();
2191 return;
2192 }
Costin Manolache360e4542009-09-04 13:36:04 -07002193
Dianne Hackborn231cc602009-04-27 17:10:36 -07002194 try {
2195 Parcel out = Parcel.obtain();
2196 writePendingOperationLocked(op, out);
2197 fos.write(out.marshall());
2198 out.recycle();
2199 } catch (java.io.IOException e1) {
2200 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002202 try {
2203 fos.close();
2204 } catch (java.io.IOException e2) {
2205 }
2206 }
2207 }
Costin Manolache360e4542009-09-04 13:36:04 -07002208
Dianne Hackborn231cc602009-04-27 17:10:36 -07002209 static private byte[] flattenBundle(Bundle bundle) {
2210 byte[] flatData = null;
2211 Parcel parcel = Parcel.obtain();
2212 try {
2213 bundle.writeToParcel(parcel, 0);
2214 flatData = parcel.marshall();
2215 } finally {
2216 parcel.recycle();
2217 }
2218 return flatData;
2219 }
Costin Manolache360e4542009-09-04 13:36:04 -07002220
Dianne Hackborn231cc602009-04-27 17:10:36 -07002221 static private Bundle unflattenBundle(byte[] flatData) {
2222 Bundle bundle;
2223 Parcel parcel = Parcel.obtain();
2224 try {
2225 parcel.unmarshall(flatData, 0, flatData.length);
2226 parcel.setDataPosition(0);
2227 bundle = parcel.readBundle();
2228 } catch (RuntimeException e) {
2229 // A RuntimeException is thrown if we were unable to parse the parcel.
2230 // Create an empty parcel in this case.
2231 bundle = new Bundle();
2232 } finally {
2233 parcel.recycle();
2234 }
2235 return bundle;
2236 }
Costin Manolache360e4542009-09-04 13:36:04 -07002237
Alon Albert57286f92012-10-09 14:21:38 -07002238 private void requestSync(Account account, int userId, int reason, String authority,
2239 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002240 // If this is happening in the system process, then call the syncrequest listener
2241 // to make a request back to the SyncManager directly.
2242 // If this is probably a test instance, then call back through the ContentResolver
2243 // which will know which userId to apply based on the Binder id.
2244 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2245 && mSyncRequestListener != null) {
Alon Albert57286f92012-10-09 14:21:38 -07002246 mSyncRequestListener.onSyncRequest(account, userId, reason, authority, extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002247 } else {
2248 ContentResolver.requestSync(account, authority, extras);
2249 }
2250 }
2251
Dianne Hackborn231cc602009-04-27 17:10:36 -07002252 public static final int STATISTICS_FILE_END = 0;
2253 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2254 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002255
Dianne Hackborn231cc602009-04-27 17:10:36 -07002256 /**
2257 * Read all sync statistics back in to the initial engine state.
2258 */
2259 private void readStatisticsLocked() {
2260 try {
2261 byte[] data = mStatisticsFile.readFully();
2262 Parcel in = Parcel.obtain();
2263 in.unmarshall(data, 0, data.length);
2264 in.setDataPosition(0);
2265 int token;
2266 int index = 0;
2267 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2268 if (token == STATISTICS_FILE_ITEM
2269 || token == STATISTICS_FILE_ITEM_OLD) {
2270 int day = in.readInt();
2271 if (token == STATISTICS_FILE_ITEM_OLD) {
2272 day = day - 2009 + 14245; // Magic!
2273 }
2274 DayStats ds = new DayStats(day);
2275 ds.successCount = in.readInt();
2276 ds.successTime = in.readLong();
2277 ds.failureCount = in.readInt();
2278 ds.failureTime = in.readLong();
2279 if (index < mDayStats.length) {
2280 mDayStats[index] = ds;
2281 index++;
2282 }
2283 } else {
2284 // Ooops.
2285 Log.w(TAG, "Unknown stats token: " + token);
2286 break;
2287 }
2288 }
2289 } catch (java.io.IOException e) {
2290 Log.i(TAG, "No initial statistics");
2291 }
2292 }
Costin Manolache360e4542009-09-04 13:36:04 -07002293
Dianne Hackborn231cc602009-04-27 17:10:36 -07002294 /**
2295 * Write all sync statistics to the sync status file.
2296 */
2297 private void writeStatisticsLocked() {
2298 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002299
Dianne Hackborn231cc602009-04-27 17:10:36 -07002300 // The file is being written, so we don't need to have a scheduled
2301 // write until the next change.
2302 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002303
Dianne Hackborn231cc602009-04-27 17:10:36 -07002304 FileOutputStream fos = null;
2305 try {
2306 fos = mStatisticsFile.startWrite();
2307 Parcel out = Parcel.obtain();
2308 final int N = mDayStats.length;
2309 for (int i=0; i<N; i++) {
2310 DayStats ds = mDayStats[i];
2311 if (ds == null) {
2312 break;
2313 }
2314 out.writeInt(STATISTICS_FILE_ITEM);
2315 out.writeInt(ds.day);
2316 out.writeInt(ds.successCount);
2317 out.writeLong(ds.successTime);
2318 out.writeInt(ds.failureCount);
2319 out.writeLong(ds.failureTime);
2320 }
2321 out.writeInt(STATISTICS_FILE_END);
2322 fos.write(out.marshall());
2323 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002324
Dianne Hackborn231cc602009-04-27 17:10:36 -07002325 mStatisticsFile.finishWrite(fos);
2326 } catch (java.io.IOException e1) {
2327 Log.w(TAG, "Error writing stats", e1);
2328 if (fos != null) {
2329 mStatisticsFile.failWrite(fos);
2330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 }
2332 }
2333}