blob: 02a2471d1b287d9f045cb61831393fb39c30295a [file] [log] [blame]
Daniel Lehmann173ffe12010-06-14 18:19:10 -07001/*
2 * Copyright (C) 2010 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
Dmitri Plotnikov18ffaa22010-12-03 14:28:00 -080017package com.android.contacts;
Daniel Lehmann173ffe12010-06-14 18:19:10 -070018
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -080019import android.app.Activity;
Daniel Lehmann173ffe12010-06-14 18:19:10 -070020import android.app.IntentService;
21import android.content.ContentProviderOperation;
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -080022import android.content.ContentProviderOperation.Builder;
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -070023import android.content.ContentProviderResult;
24import android.content.ContentResolver;
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -080025import android.content.ContentUris;
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -070026import android.content.ContentValues;
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -080027import android.content.Context;
Daniel Lehmann173ffe12010-06-14 18:19:10 -070028import android.content.Intent;
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -080029import android.content.OperationApplicationException;
30import android.database.Cursor;
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -070031import android.net.Uri;
Daniel Lehmannc42ea4e2012-02-16 21:22:37 -080032import android.os.Bundle;
Dmitri Plotnikov886d3d62011-01-03 10:08:47 -080033import android.os.Handler;
34import android.os.Looper;
Dmitri Plotnikova0114142011-02-15 13:53:21 -080035import android.os.Parcelable;
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -080036import android.os.RemoteException;
Daniel Lehmann173ffe12010-06-14 18:19:10 -070037import android.provider.ContactsContract;
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -080038import android.provider.ContactsContract.AggregationExceptions;
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -080039import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -080040import android.provider.ContactsContract.Contacts;
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -070041import android.provider.ContactsContract.Data;
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -080042import android.provider.ContactsContract.Groups;
Yorke Leee8e3fb82013-09-12 17:53:31 -070043import android.provider.ContactsContract.PinnedPositions;
Isaac Katzenelsonead19c52011-07-29 18:24:53 -070044import android.provider.ContactsContract.Profile;
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -070045import android.provider.ContactsContract.RawContacts;
Dave Santoroc90f95e2011-09-07 17:47:15 -070046import android.provider.ContactsContract.RawContactsEntity;
Daniel Lehmann173ffe12010-06-14 18:19:10 -070047import android.util.Log;
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -080048import android.widget.Toast;
Daniel Lehmann173ffe12010-06-14 18:19:10 -070049
Chiao Chengd7ca03e2012-10-24 15:14:08 -070050import com.android.contacts.common.database.ContactUpdateUtils;
Chiao Cheng0d5588d2012-11-26 15:34:14 -080051import com.android.contacts.common.model.AccountTypeManager;
Yorke Leecd321f62013-10-28 15:20:15 -070052import com.android.contacts.common.model.RawContactDelta;
53import com.android.contacts.common.model.RawContactDeltaList;
54import com.android.contacts.common.model.RawContactModifier;
Chiao Cheng428f0082012-11-13 18:38:56 -080055import com.android.contacts.common.model.account.AccountWithDataSet;
Yorke Lee637a38e2013-09-14 08:36:33 -070056import com.android.contacts.util.ContactPhotoUtils;
57
Chiao Chenge0b2f1e2012-06-12 13:07:56 -070058import com.google.common.collect.Lists;
59import com.google.common.collect.Sets;
60
Josh Garguse692e012012-01-18 14:53:11 -080061import java.io.File;
62import java.io.FileInputStream;
63import java.io.FileOutputStream;
64import java.io.IOException;
Yorke Lee637a38e2013-09-14 08:36:33 -070065import java.io.InputStream;
Daniel Lehmannc42ea4e2012-02-16 21:22:37 -080066import java.util.ArrayList;
67import java.util.HashSet;
68import java.util.List;
69import java.util.concurrent.CopyOnWriteArrayList;
Daniel Lehmann173ffe12010-06-14 18:19:10 -070070
Dmitri Plotnikov18ffaa22010-12-03 14:28:00 -080071/**
72 * A service responsible for saving changes to the content provider.
73 */
Daniel Lehmann173ffe12010-06-14 18:19:10 -070074public class ContactSaveService extends IntentService {
75 private static final String TAG = "ContactSaveService";
76
Katherine Kuana007e442011-07-07 09:25:34 -070077 /** Set to true in order to view logs on content provider operations */
78 private static final boolean DEBUG = false;
79
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -070080 public static final String ACTION_NEW_RAW_CONTACT = "newRawContact";
81
82 public static final String EXTRA_ACCOUNT_NAME = "accountName";
83 public static final String EXTRA_ACCOUNT_TYPE = "accountType";
Dave Santoro2b3f3c52011-07-26 17:35:42 -070084 public static final String EXTRA_DATA_SET = "dataSet";
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -070085 public static final String EXTRA_CONTENT_VALUES = "contentValues";
86 public static final String EXTRA_CALLBACK_INTENT = "callbackIntent";
87
Dmitri Plotnikova0114142011-02-15 13:53:21 -080088 public static final String ACTION_SAVE_CONTACT = "saveContact";
89 public static final String EXTRA_CONTACT_STATE = "state";
90 public static final String EXTRA_SAVE_MODE = "saveMode";
Isaac Katzenelsonead19c52011-07-29 18:24:53 -070091 public static final String EXTRA_SAVE_IS_PROFILE = "saveIsProfile";
Dave Santoro36d24d72011-09-25 17:08:10 -070092 public static final String EXTRA_SAVE_SUCCEEDED = "saveSucceeded";
Josh Garguse692e012012-01-18 14:53:11 -080093 public static final String EXTRA_UPDATED_PHOTOS = "updatedPhotos";
Daniel Lehmann173ffe12010-06-14 18:19:10 -070094
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -080095 public static final String ACTION_CREATE_GROUP = "createGroup";
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -080096 public static final String ACTION_RENAME_GROUP = "renameGroup";
97 public static final String ACTION_DELETE_GROUP = "deleteGroup";
Katherine Kuan2d851cc2011-07-05 16:23:27 -070098 public static final String ACTION_UPDATE_GROUP = "updateGroup";
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -080099 public static final String EXTRA_GROUP_ID = "groupId";
100 public static final String EXTRA_GROUP_LABEL = "groupLabel";
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700101 public static final String EXTRA_RAW_CONTACTS_TO_ADD = "rawContactsToAdd";
102 public static final String EXTRA_RAW_CONTACTS_TO_REMOVE = "rawContactsToRemove";
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -0800103
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800104 public static final String ACTION_SET_STARRED = "setStarred";
Dmitri Plotnikov7d8cabb2010-11-24 17:40:01 -0800105 public static final String ACTION_DELETE_CONTACT = "delete";
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800106 public static final String EXTRA_CONTACT_URI = "contactUri";
107 public static final String EXTRA_STARRED_FLAG = "starred";
108
Daniel Lehmann0f78e8b2010-11-24 17:32:03 -0800109 public static final String ACTION_SET_SUPER_PRIMARY = "setSuperPrimary";
110 public static final String ACTION_CLEAR_PRIMARY = "clearPrimary";
111 public static final String EXTRA_DATA_ID = "dataId";
112
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -0800113 public static final String ACTION_JOIN_CONTACTS = "joinContacts";
114 public static final String EXTRA_CONTACT_ID1 = "contactId1";
115 public static final String EXTRA_CONTACT_ID2 = "contactId2";
116 public static final String EXTRA_CONTACT_WRITABLE = "contactWritable";
117
Isaac Katzenelson683b57e2011-07-20 17:06:11 -0700118 public static final String ACTION_SET_SEND_TO_VOICEMAIL = "sendToVoicemail";
119 public static final String EXTRA_SEND_TO_VOICEMAIL_FLAG = "sendToVoicemailFlag";
120
121 public static final String ACTION_SET_RINGTONE = "setRingtone";
122 public static final String EXTRA_CUSTOM_RINGTONE = "customRingtone";
123
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700124 private static final HashSet<String> ALLOWED_DATA_COLUMNS = Sets.newHashSet(
125 Data.MIMETYPE,
126 Data.IS_PRIMARY,
127 Data.DATA1,
128 Data.DATA2,
129 Data.DATA3,
130 Data.DATA4,
131 Data.DATA5,
132 Data.DATA6,
133 Data.DATA7,
134 Data.DATA8,
135 Data.DATA9,
136 Data.DATA10,
137 Data.DATA11,
138 Data.DATA12,
139 Data.DATA13,
140 Data.DATA14,
141 Data.DATA15
142 );
143
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800144 private static final int PERSIST_TRIES = 3;
145
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -0800146 public interface Listener {
147 public void onServiceCompleted(Intent callbackIntent);
148 }
149
Hugo Hudsona831c0b2011-08-13 11:50:15 +0100150 private static final CopyOnWriteArrayList<Listener> sListeners =
151 new CopyOnWriteArrayList<Listener>();
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -0800152
153 private Handler mMainHandler;
154
Daniel Lehmann173ffe12010-06-14 18:19:10 -0700155 public ContactSaveService() {
156 super(TAG);
157 setIntentRedelivery(true);
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -0800158 mMainHandler = new Handler(Looper.getMainLooper());
159 }
160
161 public static void registerListener(Listener listener) {
162 if (!(listener instanceof Activity)) {
163 throw new ClassCastException("Only activities can be registered to"
164 + " receive callback from " + ContactSaveService.class.getName());
165 }
Hugo Hudsona831c0b2011-08-13 11:50:15 +0100166 sListeners.add(0, listener);
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -0800167 }
168
169 public static void unregisterListener(Listener listener) {
Hugo Hudsona831c0b2011-08-13 11:50:15 +0100170 sListeners.remove(listener);
Daniel Lehmann173ffe12010-06-14 18:19:10 -0700171 }
172
173 @Override
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800174 public Object getSystemService(String name) {
175 Object service = super.getSystemService(name);
176 if (service != null) {
177 return service;
178 }
179
180 return getApplicationContext().getSystemService(name);
181 }
182
183 @Override
Daniel Lehmann173ffe12010-06-14 18:19:10 -0700184 protected void onHandleIntent(Intent intent) {
Daisuke Miyakawa2f21c442012-03-22 19:12:31 -0700185 // Call an appropriate method. If we're sure it affects how incoming phone calls are
186 // handled, then notify the fact to in-call screen.
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700187 String action = intent.getAction();
188 if (ACTION_NEW_RAW_CONTACT.equals(action)) {
189 createRawContact(intent);
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800190 } else if (ACTION_SAVE_CONTACT.equals(action)) {
191 saveContact(intent);
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800192 } else if (ACTION_CREATE_GROUP.equals(action)) {
193 createGroup(intent);
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -0800194 } else if (ACTION_RENAME_GROUP.equals(action)) {
195 renameGroup(intent);
196 } else if (ACTION_DELETE_GROUP.equals(action)) {
197 deleteGroup(intent);
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700198 } else if (ACTION_UPDATE_GROUP.equals(action)) {
199 updateGroup(intent);
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800200 } else if (ACTION_SET_STARRED.equals(action)) {
201 setStarred(intent);
Daniel Lehmann0f78e8b2010-11-24 17:32:03 -0800202 } else if (ACTION_SET_SUPER_PRIMARY.equals(action)) {
203 setSuperPrimary(intent);
204 } else if (ACTION_CLEAR_PRIMARY.equals(action)) {
205 clearPrimary(intent);
Dmitri Plotnikov7d8cabb2010-11-24 17:40:01 -0800206 } else if (ACTION_DELETE_CONTACT.equals(action)) {
207 deleteContact(intent);
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -0800208 } else if (ACTION_JOIN_CONTACTS.equals(action)) {
209 joinContacts(intent);
Isaac Katzenelson683b57e2011-07-20 17:06:11 -0700210 } else if (ACTION_SET_SEND_TO_VOICEMAIL.equals(action)) {
211 setSendToVoicemail(intent);
212 } else if (ACTION_SET_RINGTONE.equals(action)) {
213 setRingtone(intent);
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700214 }
215 }
216
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800217 /**
218 * Creates an intent that can be sent to this service to create a new raw contact
219 * using data presented as a set of ContentValues.
220 */
221 public static Intent createNewRawContactIntent(Context context,
Dave Santoro2b3f3c52011-07-26 17:35:42 -0700222 ArrayList<ContentValues> values, AccountWithDataSet account,
Josh Garguse5d3f892012-04-11 11:56:15 -0700223 Class<? extends Activity> callbackActivity, String callbackAction) {
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800224 Intent serviceIntent = new Intent(
225 context, ContactSaveService.class);
226 serviceIntent.setAction(ContactSaveService.ACTION_NEW_RAW_CONTACT);
227 if (account != null) {
228 serviceIntent.putExtra(ContactSaveService.EXTRA_ACCOUNT_NAME, account.name);
229 serviceIntent.putExtra(ContactSaveService.EXTRA_ACCOUNT_TYPE, account.type);
Dave Santoro2b3f3c52011-07-26 17:35:42 -0700230 serviceIntent.putExtra(ContactSaveService.EXTRA_DATA_SET, account.dataSet);
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800231 }
232 serviceIntent.putParcelableArrayListExtra(
233 ContactSaveService.EXTRA_CONTENT_VALUES, values);
234
235 // Callback intent will be invoked by the service once the new contact is
236 // created. The service will put the URI of the new contact as "data" on
237 // the callback intent.
238 Intent callbackIntent = new Intent(context, callbackActivity);
239 callbackIntent.setAction(callbackAction);
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800240 serviceIntent.putExtra(ContactSaveService.EXTRA_CALLBACK_INTENT, callbackIntent);
241 return serviceIntent;
242 }
243
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700244 private void createRawContact(Intent intent) {
245 String accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME);
246 String accountType = intent.getStringExtra(EXTRA_ACCOUNT_TYPE);
Dave Santoro2b3f3c52011-07-26 17:35:42 -0700247 String dataSet = intent.getStringExtra(EXTRA_DATA_SET);
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700248 List<ContentValues> valueList = intent.getParcelableArrayListExtra(EXTRA_CONTENT_VALUES);
249 Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);
250
251 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
252 operations.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
253 .withValue(RawContacts.ACCOUNT_NAME, accountName)
254 .withValue(RawContacts.ACCOUNT_TYPE, accountType)
Dave Santoro2b3f3c52011-07-26 17:35:42 -0700255 .withValue(RawContacts.DATA_SET, dataSet)
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700256 .build());
257
258 int size = valueList.size();
259 for (int i = 0; i < size; i++) {
260 ContentValues values = valueList.get(i);
261 values.keySet().retainAll(ALLOWED_DATA_COLUMNS);
262 operations.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
263 .withValueBackReference(Data.RAW_CONTACT_ID, 0)
264 .withValues(values)
265 .build());
266 }
267
268 ContentResolver resolver = getContentResolver();
269 ContentProviderResult[] results;
270 try {
271 results = resolver.applyBatch(ContactsContract.AUTHORITY, operations);
272 } catch (Exception e) {
273 throw new RuntimeException("Failed to store new contact", e);
274 }
275
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700276 Uri rawContactUri = results[0].uri;
277 callbackIntent.setData(RawContacts.getContactLookupUri(resolver, rawContactUri));
278
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -0800279 deliverCallback(callbackIntent);
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700280 }
281
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700282 /**
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800283 * Creates an intent that can be sent to this service to create a new raw contact
284 * using data presented as a set of ContentValues.
Josh Garguse692e012012-01-18 14:53:11 -0800285 * This variant is more convenient to use when there is only one photo that can
286 * possibly be updated, as in the Contact Details screen.
287 * @param rawContactId identifies a writable raw-contact whose photo is to be updated.
288 * @param updatedPhotoPath denotes a temporary file containing the contact's new photo.
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800289 */
Maurice Chu851222a2012-06-21 11:43:08 -0700290 public static Intent createSaveContactIntent(Context context, RawContactDeltaList state,
Josh Garguse5d3f892012-04-11 11:56:15 -0700291 String saveModeExtraKey, int saveMode, boolean isProfile,
292 Class<? extends Activity> callbackActivity, String callbackAction, long rawContactId,
Yorke Lee637a38e2013-09-14 08:36:33 -0700293 Uri updatedPhotoPath) {
Josh Garguse692e012012-01-18 14:53:11 -0800294 Bundle bundle = new Bundle();
Yorke Lee637a38e2013-09-14 08:36:33 -0700295 bundle.putParcelable(String.valueOf(rawContactId), updatedPhotoPath);
Josh Garguse692e012012-01-18 14:53:11 -0800296 return createSaveContactIntent(context, state, saveModeExtraKey, saveMode, isProfile,
297 callbackActivity, callbackAction, bundle);
298 }
299
300 /**
301 * Creates an intent that can be sent to this service to create a new raw contact
302 * using data presented as a set of ContentValues.
303 * This variant is used when multiple contacts' photos may be updated, as in the
304 * Contact Editor.
305 * @param updatedPhotos maps each raw-contact's ID to the file-path of the new photo.
306 */
Maurice Chu851222a2012-06-21 11:43:08 -0700307 public static Intent createSaveContactIntent(Context context, RawContactDeltaList state,
Josh Garguse5d3f892012-04-11 11:56:15 -0700308 String saveModeExtraKey, int saveMode, boolean isProfile,
309 Class<? extends Activity> callbackActivity, String callbackAction,
310 Bundle updatedPhotos) {
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800311 Intent serviceIntent = new Intent(
312 context, ContactSaveService.class);
313 serviceIntent.setAction(ContactSaveService.ACTION_SAVE_CONTACT);
314 serviceIntent.putExtra(EXTRA_CONTACT_STATE, (Parcelable) state);
Isaac Katzenelsonead19c52011-07-29 18:24:53 -0700315 serviceIntent.putExtra(EXTRA_SAVE_IS_PROFILE, isProfile);
Josh Garguse692e012012-01-18 14:53:11 -0800316 if (updatedPhotos != null) {
317 serviceIntent.putExtra(EXTRA_UPDATED_PHOTOS, (Parcelable) updatedPhotos);
318 }
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800319
Josh Garguse5d3f892012-04-11 11:56:15 -0700320 if (callbackActivity != null) {
321 // Callback intent will be invoked by the service once the contact is
322 // saved. The service will put the URI of the new contact as "data" on
323 // the callback intent.
324 Intent callbackIntent = new Intent(context, callbackActivity);
325 callbackIntent.putExtra(saveModeExtraKey, saveMode);
326 callbackIntent.setAction(callbackAction);
327 serviceIntent.putExtra(ContactSaveService.EXTRA_CALLBACK_INTENT, callbackIntent);
328 }
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800329 return serviceIntent;
330 }
331
332 private void saveContact(Intent intent) {
Maurice Chu851222a2012-06-21 11:43:08 -0700333 RawContactDeltaList state = intent.getParcelableExtra(EXTRA_CONTACT_STATE);
Isaac Katzenelsonead19c52011-07-29 18:24:53 -0700334 boolean isProfile = intent.getBooleanExtra(EXTRA_SAVE_IS_PROFILE, false);
Josh Garguse692e012012-01-18 14:53:11 -0800335 Bundle updatedPhotos = intent.getParcelableExtra(EXTRA_UPDATED_PHOTOS);
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800336
337 // Trim any empty fields, and RawContacts, before persisting
338 final AccountTypeManager accountTypes = AccountTypeManager.getInstance(this);
Maurice Chu851222a2012-06-21 11:43:08 -0700339 RawContactModifier.trimEmpty(state, accountTypes);
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800340
341 Uri lookupUri = null;
342
343 final ContentResolver resolver = getContentResolver();
Josh Garguse692e012012-01-18 14:53:11 -0800344 boolean succeeded = false;
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800345
Josh Gargusef15c8e2012-01-30 16:42:02 -0800346 // Keep track of the id of a newly raw-contact (if any... there can be at most one).
347 long insertedRawContactId = -1;
348
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800349 // Attempt to persist changes
350 int tries = 0;
351 while (tries++ < PERSIST_TRIES) {
352 try {
353 // Build operations and try applying
354 final ArrayList<ContentProviderOperation> diff = state.buildDiff();
Katherine Kuana007e442011-07-07 09:25:34 -0700355 if (DEBUG) {
356 Log.v(TAG, "Content Provider Operations:");
357 for (ContentProviderOperation operation : diff) {
358 Log.v(TAG, operation.toString());
359 }
360 }
361
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800362 ContentProviderResult[] results = null;
363 if (!diff.isEmpty()) {
364 results = resolver.applyBatch(ContactsContract.AUTHORITY, diff);
365 }
366
367 final long rawContactId = getRawContactId(state, diff, results);
368 if (rawContactId == -1) {
369 throw new IllegalStateException("Could not determine RawContact ID after save");
370 }
Josh Gargusef15c8e2012-01-30 16:42:02 -0800371 // We don't have to check to see if the value is still -1. If we reach here,
372 // the previous loop iteration didn't succeed, so any ID that we obtained is bogus.
373 insertedRawContactId = getInsertedRawContactId(diff, results);
Dave Santoro7c34c0a2011-09-12 14:58:20 -0700374 if (isProfile) {
375 // Since the profile supports local raw contacts, which may have been completely
376 // removed if all information was removed, we need to do a special query to
377 // get the lookup URI for the profile contact (if it still exists).
378 Cursor c = resolver.query(Profile.CONTENT_URI,
379 new String[] {Contacts._ID, Contacts.LOOKUP_KEY},
380 null, null, null);
381 try {
Erik162b7e32011-09-20 15:23:55 -0700382 if (c.moveToFirst()) {
383 final long contactId = c.getLong(0);
384 final String lookupKey = c.getString(1);
385 lookupUri = Contacts.getLookupUri(contactId, lookupKey);
386 }
Dave Santoro7c34c0a2011-09-12 14:58:20 -0700387 } finally {
388 c.close();
389 }
390 } else {
391 final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI,
392 rawContactId);
393 lookupUri = RawContacts.getContactLookupUri(resolver, rawContactUri);
394 }
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800395 Log.v(TAG, "Saved contact. New URI: " + lookupUri);
Josh Garguse692e012012-01-18 14:53:11 -0800396
397 // We can change this back to false later, if we fail to save the contact photo.
398 succeeded = true;
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800399 break;
400
401 } catch (RemoteException e) {
402 // Something went wrong, bail without success
403 Log.e(TAG, "Problem persisting user edits", e);
404 break;
405
Jay Shrauner57fca182014-01-17 14:20:50 -0800406 } catch (IllegalArgumentException e) {
407 // This is thrown by applyBatch on malformed requests
408 Log.e(TAG, "Problem persisting user edits", e);
409 showToast(R.string.contactSavedErrorToast);
410 break;
411
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800412 } catch (OperationApplicationException e) {
413 // Version consistency failed, re-parent change and try again
414 Log.w(TAG, "Version consistency failed, re-parenting: " + e.toString());
415 final StringBuilder sb = new StringBuilder(RawContacts._ID + " IN(");
416 boolean first = true;
417 final int count = state.size();
418 for (int i = 0; i < count; i++) {
419 Long rawContactId = state.getRawContactId(i);
420 if (rawContactId != null && rawContactId != -1) {
421 if (!first) {
422 sb.append(',');
423 }
424 sb.append(rawContactId);
425 first = false;
426 }
427 }
428 sb.append(")");
429
430 if (first) {
Brian Attwell3b6c6282014-02-12 17:53:31 -0800431 throw new IllegalStateException(
432 "Version consistency failed for a new contact", e);
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800433 }
434
Maurice Chu851222a2012-06-21 11:43:08 -0700435 final RawContactDeltaList newState = RawContactDeltaList.fromQuery(
Dave Santoroc90f95e2011-09-07 17:47:15 -0700436 isProfile
437 ? RawContactsEntity.PROFILE_CONTENT_URI
438 : RawContactsEntity.CONTENT_URI,
439 resolver, sb.toString(), null, null);
Maurice Chu851222a2012-06-21 11:43:08 -0700440 state = RawContactDeltaList.mergeAfter(newState, state);
Dave Santoroc90f95e2011-09-07 17:47:15 -0700441
442 // Update the new state to use profile URIs if appropriate.
443 if (isProfile) {
Maurice Chu851222a2012-06-21 11:43:08 -0700444 for (RawContactDelta delta : state) {
Dave Santoroc90f95e2011-09-07 17:47:15 -0700445 delta.setProfileQueryUri();
446 }
447 }
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800448 }
449 }
450
Josh Garguse692e012012-01-18 14:53:11 -0800451 // Now save any updated photos. We do this at the end to ensure that
452 // the ContactProvider already knows about newly-created contacts.
453 if (updatedPhotos != null) {
454 for (String key : updatedPhotos.keySet()) {
Yorke Lee637a38e2013-09-14 08:36:33 -0700455 Uri photoUri = updatedPhotos.getParcelable(key);
Josh Garguse692e012012-01-18 14:53:11 -0800456 long rawContactId = Long.parseLong(key);
Josh Gargusef15c8e2012-01-30 16:42:02 -0800457
458 // If the raw-contact ID is negative, we are saving a new raw-contact;
459 // replace the bogus ID with the new one that we actually saved the contact at.
460 if (rawContactId < 0) {
461 rawContactId = insertedRawContactId;
462 if (rawContactId == -1) {
463 throw new IllegalStateException(
464 "Could not determine RawContact ID for image insertion");
465 }
466 }
467
Yorke Lee637a38e2013-09-14 08:36:33 -0700468 if (!saveUpdatedPhoto(rawContactId, photoUri)) succeeded = false;
Josh Garguse692e012012-01-18 14:53:11 -0800469 }
470 }
471
Josh Garguse5d3f892012-04-11 11:56:15 -0700472 Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);
473 if (callbackIntent != null) {
474 if (succeeded) {
475 // Mark the intent to indicate that the save was successful (even if the lookup URI
476 // is now null). For local contacts or the local profile, it's possible that the
477 // save triggered removal of the contact, so no lookup URI would exist..
478 callbackIntent.putExtra(EXTRA_SAVE_SUCCEEDED, true);
479 }
480 callbackIntent.setData(lookupUri);
481 deliverCallback(callbackIntent);
Josh Garguse692e012012-01-18 14:53:11 -0800482 }
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800483 }
484
Josh Garguse692e012012-01-18 14:53:11 -0800485 /**
486 * Save updated photo for the specified raw-contact.
487 * @return true for success, false for failure
488 */
Yorke Lee637a38e2013-09-14 08:36:33 -0700489 private boolean saveUpdatedPhoto(long rawContactId, Uri photoUri) {
Josh Gargusef15c8e2012-01-30 16:42:02 -0800490 final Uri outputUri = Uri.withAppendedPath(
Josh Garguse692e012012-01-18 14:53:11 -0800491 ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId),
492 RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
493
Yorke Lee637a38e2013-09-14 08:36:33 -0700494 return ContactPhotoUtils.savePhotoFromUriToUri(this, photoUri, outputUri, true);
Josh Garguse692e012012-01-18 14:53:11 -0800495 }
496
Josh Gargusef15c8e2012-01-30 16:42:02 -0800497 /**
498 * Find the ID of an existing or newly-inserted raw-contact. If none exists, return -1.
499 */
Maurice Chu851222a2012-06-21 11:43:08 -0700500 private long getRawContactId(RawContactDeltaList state,
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800501 final ArrayList<ContentProviderOperation> diff,
502 final ContentProviderResult[] results) {
Josh Gargusef15c8e2012-01-30 16:42:02 -0800503 long existingRawContactId = state.findRawContactId();
504 if (existingRawContactId != -1) {
505 return existingRawContactId;
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800506 }
507
Josh Gargusef15c8e2012-01-30 16:42:02 -0800508 return getInsertedRawContactId(diff, results);
509 }
510
511 /**
512 * Find the ID of a newly-inserted raw-contact. If none exists, return -1.
513 */
514 private long getInsertedRawContactId(
515 final ArrayList<ContentProviderOperation> diff,
516 final ContentProviderResult[] results) {
Jay Shrauner568f4e72014-11-26 08:16:25 -0800517 if (results == null) {
518 return -1;
519 }
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800520 final int diffSize = diff.size();
Jay Shrauner3d7edc32014-11-10 09:58:23 -0800521 final int numResults = results.length;
522 for (int i = 0; i < diffSize && i < numResults; i++) {
Dmitri Plotnikova0114142011-02-15 13:53:21 -0800523 ContentProviderOperation operation = diff.get(i);
524 if (operation.getType() == ContentProviderOperation.TYPE_INSERT
525 && operation.getUri().getEncodedPath().contains(
526 RawContacts.CONTENT_URI.getEncodedPath())) {
527 return ContentUris.parseId(results[i].uri);
528 }
529 }
530 return -1;
531 }
532
533 /**
Katherine Kuan717e3432011-07-13 17:03:24 -0700534 * Creates an intent that can be sent to this service to create a new group as
535 * well as add new members at the same time.
536 *
537 * @param context of the application
538 * @param account in which the group should be created
539 * @param label is the name of the group (cannot be null)
540 * @param rawContactsToAdd is an array of raw contact IDs for contacts that
541 * should be added to the group
542 * @param callbackActivity is the activity to send the callback intent to
543 * @param callbackAction is the intent action for the callback intent
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700544 */
Dave Santoro2b3f3c52011-07-26 17:35:42 -0700545 public static Intent createNewGroupIntent(Context context, AccountWithDataSet account,
Josh Garguse5d3f892012-04-11 11:56:15 -0700546 String label, long[] rawContactsToAdd, Class<? extends Activity> callbackActivity,
Katherine Kuan717e3432011-07-13 17:03:24 -0700547 String callbackAction) {
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800548 Intent serviceIntent = new Intent(context, ContactSaveService.class);
549 serviceIntent.setAction(ContactSaveService.ACTION_CREATE_GROUP);
550 serviceIntent.putExtra(ContactSaveService.EXTRA_ACCOUNT_TYPE, account.type);
551 serviceIntent.putExtra(ContactSaveService.EXTRA_ACCOUNT_NAME, account.name);
Dave Santoro2b3f3c52011-07-26 17:35:42 -0700552 serviceIntent.putExtra(ContactSaveService.EXTRA_DATA_SET, account.dataSet);
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800553 serviceIntent.putExtra(ContactSaveService.EXTRA_GROUP_LABEL, label);
Katherine Kuan717e3432011-07-13 17:03:24 -0700554 serviceIntent.putExtra(ContactSaveService.EXTRA_RAW_CONTACTS_TO_ADD, rawContactsToAdd);
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700555
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800556 // Callback intent will be invoked by the service once the new group is
Katherine Kuan717e3432011-07-13 17:03:24 -0700557 // created.
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800558 Intent callbackIntent = new Intent(context, callbackActivity);
559 callbackIntent.setAction(callbackAction);
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700560 serviceIntent.putExtra(ContactSaveService.EXTRA_CALLBACK_INTENT, callbackIntent);
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800561
Dmitri Plotnikovcaf0bc72010-09-03 15:16:21 -0700562 return serviceIntent;
563 }
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -0800564
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800565 private void createGroup(Intent intent) {
Dave Santoro2b3f3c52011-07-26 17:35:42 -0700566 String accountType = intent.getStringExtra(EXTRA_ACCOUNT_TYPE);
567 String accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME);
568 String dataSet = intent.getStringExtra(EXTRA_DATA_SET);
569 String label = intent.getStringExtra(EXTRA_GROUP_LABEL);
Katherine Kuan717e3432011-07-13 17:03:24 -0700570 final long[] rawContactsToAdd = intent.getLongArrayExtra(EXTRA_RAW_CONTACTS_TO_ADD);
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800571
572 ContentValues values = new ContentValues();
573 values.put(Groups.ACCOUNT_TYPE, accountType);
574 values.put(Groups.ACCOUNT_NAME, accountName);
Dave Santoro2b3f3c52011-07-26 17:35:42 -0700575 values.put(Groups.DATA_SET, dataSet);
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800576 values.put(Groups.TITLE, label);
577
Katherine Kuan717e3432011-07-13 17:03:24 -0700578 final ContentResolver resolver = getContentResolver();
579
580 // Create the new group
581 final Uri groupUri = resolver.insert(Groups.CONTENT_URI, values);
582
583 // If there's no URI, then the insertion failed. Abort early because group members can't be
584 // added if the group doesn't exist
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800585 if (groupUri == null) {
Katherine Kuan717e3432011-07-13 17:03:24 -0700586 Log.e(TAG, "Couldn't create group with label " + label);
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800587 return;
588 }
589
Katherine Kuan717e3432011-07-13 17:03:24 -0700590 // Add new group members
591 addMembersToGroup(resolver, rawContactsToAdd, ContentUris.parseId(groupUri));
592
593 // TODO: Move this into the contact editor where it belongs. This needs to be integrated
594 // with the way other intent extras that are passed to the {@link ContactEditorActivity}.
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800595 values.clear();
596 values.put(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
597 values.put(GroupMembership.GROUP_ROW_ID, ContentUris.parseId(groupUri));
598
599 Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);
Katherine Kuanc6b8afe2011-06-22 19:03:50 -0700600 callbackIntent.setData(groupUri);
Katherine Kuan717e3432011-07-13 17:03:24 -0700601 // TODO: This can be taken out when the above TODO is addressed
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800602 callbackIntent.putExtra(ContactsContract.Intents.Insert.DATA, Lists.newArrayList(values));
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -0800603 deliverCallback(callbackIntent);
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800604 }
605
606 /**
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800607 * Creates an intent that can be sent to this service to rename a group.
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800608 */
Katherine Kuanc6b8afe2011-06-22 19:03:50 -0700609 public static Intent createGroupRenameIntent(Context context, long groupId, String newLabel,
Josh Garguse5d3f892012-04-11 11:56:15 -0700610 Class<? extends Activity> callbackActivity, String callbackAction) {
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800611 Intent serviceIntent = new Intent(context, ContactSaveService.class);
612 serviceIntent.setAction(ContactSaveService.ACTION_RENAME_GROUP);
613 serviceIntent.putExtra(ContactSaveService.EXTRA_GROUP_ID, groupId);
614 serviceIntent.putExtra(ContactSaveService.EXTRA_GROUP_LABEL, newLabel);
Katherine Kuanc6b8afe2011-06-22 19:03:50 -0700615
616 // Callback intent will be invoked by the service once the group is renamed.
617 Intent callbackIntent = new Intent(context, callbackActivity);
618 callbackIntent.setAction(callbackAction);
619 serviceIntent.putExtra(ContactSaveService.EXTRA_CALLBACK_INTENT, callbackIntent);
620
Dmitri Plotnikov1ac58b62010-11-19 16:12:09 -0800621 return serviceIntent;
622 }
623
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -0800624 private void renameGroup(Intent intent) {
625 long groupId = intent.getLongExtra(EXTRA_GROUP_ID, -1);
626 String label = intent.getStringExtra(EXTRA_GROUP_LABEL);
627
628 if (groupId == -1) {
629 Log.e(TAG, "Invalid arguments for renameGroup request");
630 return;
631 }
632
633 ContentValues values = new ContentValues();
634 values.put(Groups.TITLE, label);
Katherine Kuanc6b8afe2011-06-22 19:03:50 -0700635 final Uri groupUri = ContentUris.withAppendedId(Groups.CONTENT_URI, groupId);
636 getContentResolver().update(groupUri, values, null, null);
637
638 Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);
639 callbackIntent.setData(groupUri);
640 deliverCallback(callbackIntent);
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -0800641 }
642
643 /**
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800644 * Creates an intent that can be sent to this service to delete a group.
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -0800645 */
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800646 public static Intent createGroupDeletionIntent(Context context, long groupId) {
647 Intent serviceIntent = new Intent(context, ContactSaveService.class);
648 serviceIntent.setAction(ContactSaveService.ACTION_DELETE_GROUP);
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -0800649 serviceIntent.putExtra(ContactSaveService.EXTRA_GROUP_ID, groupId);
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -0800650 return serviceIntent;
651 }
652
653 private void deleteGroup(Intent intent) {
654 long groupId = intent.getLongExtra(EXTRA_GROUP_ID, -1);
655 if (groupId == -1) {
656 Log.e(TAG, "Invalid arguments for deleteGroup request");
657 return;
658 }
659
660 getContentResolver().delete(
661 ContentUris.withAppendedId(Groups.CONTENT_URI, groupId), null, null);
662 }
663
664 /**
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700665 * Creates an intent that can be sent to this service to rename a group as
666 * well as add and remove members from the group.
667 *
668 * @param context of the application
669 * @param groupId of the group that should be modified
670 * @param newLabel is the updated name of the group (can be null if the name
671 * should not be updated)
672 * @param rawContactsToAdd is an array of raw contact IDs for contacts that
673 * should be added to the group
674 * @param rawContactsToRemove is an array of raw contact IDs for contacts
675 * that should be removed from the group
676 * @param callbackActivity is the activity to send the callback intent to
677 * @param callbackAction is the intent action for the callback intent
678 */
679 public static Intent createGroupUpdateIntent(Context context, long groupId, String newLabel,
680 long[] rawContactsToAdd, long[] rawContactsToRemove,
Josh Garguse5d3f892012-04-11 11:56:15 -0700681 Class<? extends Activity> callbackActivity, String callbackAction) {
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700682 Intent serviceIntent = new Intent(context, ContactSaveService.class);
683 serviceIntent.setAction(ContactSaveService.ACTION_UPDATE_GROUP);
684 serviceIntent.putExtra(ContactSaveService.EXTRA_GROUP_ID, groupId);
685 serviceIntent.putExtra(ContactSaveService.EXTRA_GROUP_LABEL, newLabel);
686 serviceIntent.putExtra(ContactSaveService.EXTRA_RAW_CONTACTS_TO_ADD, rawContactsToAdd);
687 serviceIntent.putExtra(ContactSaveService.EXTRA_RAW_CONTACTS_TO_REMOVE,
688 rawContactsToRemove);
689
690 // Callback intent will be invoked by the service once the group is updated
691 Intent callbackIntent = new Intent(context, callbackActivity);
692 callbackIntent.setAction(callbackAction);
693 serviceIntent.putExtra(ContactSaveService.EXTRA_CALLBACK_INTENT, callbackIntent);
694
695 return serviceIntent;
696 }
697
698 private void updateGroup(Intent intent) {
699 long groupId = intent.getLongExtra(EXTRA_GROUP_ID, -1);
700 String label = intent.getStringExtra(EXTRA_GROUP_LABEL);
701 long[] rawContactsToAdd = intent.getLongArrayExtra(EXTRA_RAW_CONTACTS_TO_ADD);
702 long[] rawContactsToRemove = intent.getLongArrayExtra(EXTRA_RAW_CONTACTS_TO_REMOVE);
703
704 if (groupId == -1) {
705 Log.e(TAG, "Invalid arguments for updateGroup request");
706 return;
707 }
708
709 final ContentResolver resolver = getContentResolver();
710 final Uri groupUri = ContentUris.withAppendedId(Groups.CONTENT_URI, groupId);
711
712 // Update group name if necessary
713 if (label != null) {
714 ContentValues values = new ContentValues();
715 values.put(Groups.TITLE, label);
Katherine Kuan717e3432011-07-13 17:03:24 -0700716 resolver.update(groupUri, values, null, null);
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700717 }
718
Katherine Kuan717e3432011-07-13 17:03:24 -0700719 // Add and remove members if necessary
720 addMembersToGroup(resolver, rawContactsToAdd, groupId);
721 removeMembersFromGroup(resolver, rawContactsToRemove, groupId);
722
723 Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);
724 callbackIntent.setData(groupUri);
725 deliverCallback(callbackIntent);
726 }
727
Daniel Lehmann18958a22012-02-28 17:45:25 -0800728 private static void addMembersToGroup(ContentResolver resolver, long[] rawContactsToAdd,
Katherine Kuan717e3432011-07-13 17:03:24 -0700729 long groupId) {
730 if (rawContactsToAdd == null) {
731 return;
732 }
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700733 for (long rawContactId : rawContactsToAdd) {
734 try {
735 final ArrayList<ContentProviderOperation> rawContactOperations =
736 new ArrayList<ContentProviderOperation>();
737
738 // Build an assert operation to ensure the contact is not already in the group
739 final ContentProviderOperation.Builder assertBuilder = ContentProviderOperation
740 .newAssertQuery(Data.CONTENT_URI);
741 assertBuilder.withSelection(Data.RAW_CONTACT_ID + "=? AND " +
742 Data.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID + "=?",
743 new String[] { String.valueOf(rawContactId),
744 GroupMembership.CONTENT_ITEM_TYPE, String.valueOf(groupId)});
745 assertBuilder.withExpectedCount(0);
746 rawContactOperations.add(assertBuilder.build());
747
748 // Build an insert operation to add the contact to the group
749 final ContentProviderOperation.Builder insertBuilder = ContentProviderOperation
750 .newInsert(Data.CONTENT_URI);
751 insertBuilder.withValue(Data.RAW_CONTACT_ID, rawContactId);
752 insertBuilder.withValue(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
753 insertBuilder.withValue(GroupMembership.GROUP_ROW_ID, groupId);
754 rawContactOperations.add(insertBuilder.build());
755
756 if (DEBUG) {
757 for (ContentProviderOperation operation : rawContactOperations) {
758 Log.v(TAG, operation.toString());
759 }
760 }
761
762 // Apply batch
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700763 if (!rawContactOperations.isEmpty()) {
Daniel Lehmann18958a22012-02-28 17:45:25 -0800764 resolver.applyBatch(ContactsContract.AUTHORITY, rawContactOperations);
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700765 }
766 } catch (RemoteException e) {
767 // Something went wrong, bail without success
768 Log.e(TAG, "Problem persisting user edits for raw contact ID " +
769 String.valueOf(rawContactId), e);
770 } catch (OperationApplicationException e) {
771 // The assert could have failed because the contact is already in the group,
772 // just continue to the next contact
773 Log.w(TAG, "Assert failed in adding raw contact ID " +
774 String.valueOf(rawContactId) + ". Already exists in group " +
775 String.valueOf(groupId), e);
776 }
777 }
Katherine Kuan717e3432011-07-13 17:03:24 -0700778 }
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700779
Daniel Lehmann18958a22012-02-28 17:45:25 -0800780 private static void removeMembersFromGroup(ContentResolver resolver, long[] rawContactsToRemove,
Katherine Kuan717e3432011-07-13 17:03:24 -0700781 long groupId) {
782 if (rawContactsToRemove == null) {
783 return;
784 }
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700785 for (long rawContactId : rawContactsToRemove) {
786 // Apply the delete operation on the data row for the given raw contact's
787 // membership in the given group. If no contact matches the provided selection, then
788 // nothing will be done. Just continue to the next contact.
Daniel Lehmann18958a22012-02-28 17:45:25 -0800789 resolver.delete(Data.CONTENT_URI, Data.RAW_CONTACT_ID + "=? AND " +
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700790 Data.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID + "=?",
791 new String[] { String.valueOf(rawContactId),
792 GroupMembership.CONTENT_ITEM_TYPE, String.valueOf(groupId)});
793 }
Katherine Kuan2d851cc2011-07-05 16:23:27 -0700794 }
795
796 /**
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800797 * Creates an intent that can be sent to this service to star or un-star a contact.
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -0800798 */
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800799 public static Intent createSetStarredIntent(Context context, Uri contactUri, boolean value) {
800 Intent serviceIntent = new Intent(context, ContactSaveService.class);
801 serviceIntent.setAction(ContactSaveService.ACTION_SET_STARRED);
802 serviceIntent.putExtra(ContactSaveService.EXTRA_CONTACT_URI, contactUri);
803 serviceIntent.putExtra(ContactSaveService.EXTRA_STARRED_FLAG, value);
804
Dmitri Plotnikove898a9f2010-11-18 16:58:25 -0800805 return serviceIntent;
806 }
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800807
808 private void setStarred(Intent intent) {
809 Uri contactUri = intent.getParcelableExtra(EXTRA_CONTACT_URI);
810 boolean value = intent.getBooleanExtra(EXTRA_STARRED_FLAG, false);
811 if (contactUri == null) {
812 Log.e(TAG, "Invalid arguments for setStarred request");
813 return;
814 }
815
816 final ContentValues values = new ContentValues(1);
817 values.put(Contacts.STARRED, value);
818 getContentResolver().update(contactUri, values, null, null);
Yorke Leee8e3fb82013-09-12 17:53:31 -0700819
820 // Undemote the contact if necessary
821 final Cursor c = getContentResolver().query(contactUri, new String[] {Contacts._ID},
822 null, null, null);
Jay Shraunerc12a2802014-11-24 10:07:31 -0800823 if (c == null) {
824 return;
825 }
Yorke Leee8e3fb82013-09-12 17:53:31 -0700826 try {
827 if (c.moveToFirst()) {
828 final long id = c.getLong(0);
Yorke Leebbb8c992013-09-23 16:20:53 -0700829
830 // Don't bother undemoting if this contact is the user's profile.
831 if (id < Profile.MIN_ID) {
Yorke Leede1c78c2014-06-19 11:30:55 -0700832 getContentResolver().call(ContactsContract.AUTHORITY_URI,
833 PinnedPositions.UNDEMOTE_METHOD, String.valueOf(id), null);
Yorke Leebbb8c992013-09-23 16:20:53 -0700834 }
Yorke Leee8e3fb82013-09-12 17:53:31 -0700835 }
836 } finally {
837 c.close();
838 }
Dmitri Plotnikov9d730dd2010-11-24 13:22:23 -0800839 }
Daniel Lehmann0f78e8b2010-11-24 17:32:03 -0800840
841 /**
Isaac Katzenelson683b57e2011-07-20 17:06:11 -0700842 * Creates an intent that can be sent to this service to set the redirect to voicemail.
843 */
844 public static Intent createSetSendToVoicemail(Context context, Uri contactUri,
845 boolean value) {
846 Intent serviceIntent = new Intent(context, ContactSaveService.class);
847 serviceIntent.setAction(ContactSaveService.ACTION_SET_SEND_TO_VOICEMAIL);
848 serviceIntent.putExtra(ContactSaveService.EXTRA_CONTACT_URI, contactUri);
849 serviceIntent.putExtra(ContactSaveService.EXTRA_SEND_TO_VOICEMAIL_FLAG, value);
850
851 return serviceIntent;
852 }
853
854 private void setSendToVoicemail(Intent intent) {
855 Uri contactUri = intent.getParcelableExtra(EXTRA_CONTACT_URI);
856 boolean value = intent.getBooleanExtra(EXTRA_SEND_TO_VOICEMAIL_FLAG, false);
857 if (contactUri == null) {
858 Log.e(TAG, "Invalid arguments for setRedirectToVoicemail");
859 return;
860 }
861
862 final ContentValues values = new ContentValues(1);
863 values.put(Contacts.SEND_TO_VOICEMAIL, value);
864 getContentResolver().update(contactUri, values, null, null);
865 }
866
867 /**
868 * Creates an intent that can be sent to this service to save the contact's ringtone.
869 */
870 public static Intent createSetRingtone(Context context, Uri contactUri,
871 String value) {
872 Intent serviceIntent = new Intent(context, ContactSaveService.class);
873 serviceIntent.setAction(ContactSaveService.ACTION_SET_RINGTONE);
874 serviceIntent.putExtra(ContactSaveService.EXTRA_CONTACT_URI, contactUri);
875 serviceIntent.putExtra(ContactSaveService.EXTRA_CUSTOM_RINGTONE, value);
876
877 return serviceIntent;
878 }
879
880 private void setRingtone(Intent intent) {
881 Uri contactUri = intent.getParcelableExtra(EXTRA_CONTACT_URI);
882 String value = intent.getStringExtra(EXTRA_CUSTOM_RINGTONE);
883 if (contactUri == null) {
884 Log.e(TAG, "Invalid arguments for setRingtone");
885 return;
886 }
887 ContentValues values = new ContentValues(1);
888 values.put(Contacts.CUSTOM_RINGTONE, value);
889 getContentResolver().update(contactUri, values, null, null);
890 }
891
892 /**
Daniel Lehmann0f78e8b2010-11-24 17:32:03 -0800893 * Creates an intent that sets the selected data item as super primary (default)
894 */
895 public static Intent createSetSuperPrimaryIntent(Context context, long dataId) {
896 Intent serviceIntent = new Intent(context, ContactSaveService.class);
897 serviceIntent.setAction(ContactSaveService.ACTION_SET_SUPER_PRIMARY);
898 serviceIntent.putExtra(ContactSaveService.EXTRA_DATA_ID, dataId);
899 return serviceIntent;
900 }
901
902 private void setSuperPrimary(Intent intent) {
903 long dataId = intent.getLongExtra(EXTRA_DATA_ID, -1);
904 if (dataId == -1) {
905 Log.e(TAG, "Invalid arguments for setSuperPrimary request");
906 return;
907 }
908
Chiao Chengd7ca03e2012-10-24 15:14:08 -0700909 ContactUpdateUtils.setSuperPrimary(this, dataId);
Daniel Lehmann0f78e8b2010-11-24 17:32:03 -0800910 }
911
912 /**
913 * Creates an intent that clears the primary flag of all data items that belong to the same
914 * raw_contact as the given data item. Will only clear, if the data item was primary before
915 * this call
916 */
917 public static Intent createClearPrimaryIntent(Context context, long dataId) {
918 Intent serviceIntent = new Intent(context, ContactSaveService.class);
919 serviceIntent.setAction(ContactSaveService.ACTION_CLEAR_PRIMARY);
920 serviceIntent.putExtra(ContactSaveService.EXTRA_DATA_ID, dataId);
921 return serviceIntent;
922 }
923
924 private void clearPrimary(Intent intent) {
925 long dataId = intent.getLongExtra(EXTRA_DATA_ID, -1);
926 if (dataId == -1) {
927 Log.e(TAG, "Invalid arguments for clearPrimary request");
928 return;
929 }
930
931 // Update the primary values in the data record.
932 ContentValues values = new ContentValues(1);
933 values.put(Data.IS_SUPER_PRIMARY, 0);
934 values.put(Data.IS_PRIMARY, 0);
935
936 getContentResolver().update(ContentUris.withAppendedId(Data.CONTENT_URI, dataId),
937 values, null, null);
938 }
Dmitri Plotnikov7d8cabb2010-11-24 17:40:01 -0800939
940 /**
941 * Creates an intent that can be sent to this service to delete a contact.
942 */
943 public static Intent createDeleteContactIntent(Context context, Uri contactUri) {
944 Intent serviceIntent = new Intent(context, ContactSaveService.class);
945 serviceIntent.setAction(ContactSaveService.ACTION_DELETE_CONTACT);
946 serviceIntent.putExtra(ContactSaveService.EXTRA_CONTACT_URI, contactUri);
947 return serviceIntent;
948 }
949
950 private void deleteContact(Intent intent) {
951 Uri contactUri = intent.getParcelableExtra(EXTRA_CONTACT_URI);
952 if (contactUri == null) {
953 Log.e(TAG, "Invalid arguments for deleteContact request");
954 return;
955 }
956
957 getContentResolver().delete(contactUri, null, null);
958 }
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -0800959
960 /**
961 * Creates an intent that can be sent to this service to join two contacts.
962 */
963 public static Intent createJoinContactsIntent(Context context, long contactId1,
964 long contactId2, boolean contactWritable,
Josh Garguse5d3f892012-04-11 11:56:15 -0700965 Class<? extends Activity> callbackActivity, String callbackAction) {
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -0800966 Intent serviceIntent = new Intent(context, ContactSaveService.class);
967 serviceIntent.setAction(ContactSaveService.ACTION_JOIN_CONTACTS);
968 serviceIntent.putExtra(ContactSaveService.EXTRA_CONTACT_ID1, contactId1);
969 serviceIntent.putExtra(ContactSaveService.EXTRA_CONTACT_ID2, contactId2);
970 serviceIntent.putExtra(ContactSaveService.EXTRA_CONTACT_WRITABLE, contactWritable);
971
972 // Callback intent will be invoked by the service once the contacts are joined.
973 Intent callbackIntent = new Intent(context, callbackActivity);
974 callbackIntent.setAction(callbackAction);
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -0800975 serviceIntent.putExtra(ContactSaveService.EXTRA_CALLBACK_INTENT, callbackIntent);
976
977 return serviceIntent;
978 }
979
980
981 private interface JoinContactQuery {
982 String[] PROJECTION = {
983 RawContacts._ID,
984 RawContacts.CONTACT_ID,
985 RawContacts.NAME_VERIFIED,
986 RawContacts.DISPLAY_NAME_SOURCE,
987 };
988
989 String SELECTION = RawContacts.CONTACT_ID + "=? OR " + RawContacts.CONTACT_ID + "=?";
990
991 int _ID = 0;
992 int CONTACT_ID = 1;
993 int NAME_VERIFIED = 2;
994 int DISPLAY_NAME_SOURCE = 3;
995 }
996
997 private void joinContacts(Intent intent) {
998 long contactId1 = intent.getLongExtra(EXTRA_CONTACT_ID1, -1);
999 long contactId2 = intent.getLongExtra(EXTRA_CONTACT_ID2, -1);
1000 boolean writable = intent.getBooleanExtra(EXTRA_CONTACT_WRITABLE, false);
1001 if (contactId1 == -1 || contactId2 == -1) {
1002 Log.e(TAG, "Invalid arguments for joinContacts request");
1003 return;
1004 }
1005
1006 final ContentResolver resolver = getContentResolver();
1007
1008 // Load raw contact IDs for all raw contacts involved - currently edited and selected
1009 // in the join UIs
1010 Cursor c = resolver.query(RawContacts.CONTENT_URI,
1011 JoinContactQuery.PROJECTION,
1012 JoinContactQuery.SELECTION,
1013 new String[]{String.valueOf(contactId1), String.valueOf(contactId2)}, null);
Jay Shraunerc12a2802014-11-24 10:07:31 -08001014 if (c == null) {
1015 Log.e(TAG, "Unable to open Contacts DB cursor");
1016 showToast(R.string.contactSavedErrorToast);
1017 return;
1018 }
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -08001019
1020 long rawContactIds[];
1021 long verifiedNameRawContactId = -1;
1022 try {
Jay Shrauner7f42b902013-01-09 14:43:09 -08001023 if (c.getCount() == 0) {
1024 return;
1025 }
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -08001026 int maxDisplayNameSource = -1;
1027 rawContactIds = new long[c.getCount()];
1028 for (int i = 0; i < rawContactIds.length; i++) {
1029 c.moveToPosition(i);
1030 long rawContactId = c.getLong(JoinContactQuery._ID);
1031 rawContactIds[i] = rawContactId;
1032 int nameSource = c.getInt(JoinContactQuery.DISPLAY_NAME_SOURCE);
1033 if (nameSource > maxDisplayNameSource) {
1034 maxDisplayNameSource = nameSource;
1035 }
1036 }
1037
1038 // Find an appropriate display name for the joined contact:
1039 // if should have a higher DisplayNameSource or be the name
1040 // of the original contact that we are joining with another.
1041 if (writable) {
1042 for (int i = 0; i < rawContactIds.length; i++) {
1043 c.moveToPosition(i);
1044 if (c.getLong(JoinContactQuery.CONTACT_ID) == contactId1) {
1045 int nameSource = c.getInt(JoinContactQuery.DISPLAY_NAME_SOURCE);
1046 if (nameSource == maxDisplayNameSource
1047 && (verifiedNameRawContactId == -1
1048 || c.getInt(JoinContactQuery.NAME_VERIFIED) != 0)) {
1049 verifiedNameRawContactId = c.getLong(JoinContactQuery._ID);
1050 }
1051 }
1052 }
1053 }
1054 } finally {
1055 c.close();
1056 }
1057
1058 // For each pair of raw contacts, insert an aggregation exception
1059 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
1060 for (int i = 0; i < rawContactIds.length; i++) {
1061 for (int j = 0; j < rawContactIds.length; j++) {
1062 if (i != j) {
1063 buildJoinContactDiff(operations, rawContactIds[i], rawContactIds[j]);
1064 }
1065 }
1066 }
1067
1068 // Mark the original contact as "name verified" to make sure that the contact
1069 // display name does not change as a result of the join
1070 if (verifiedNameRawContactId != -1) {
1071 Builder builder = ContentProviderOperation.newUpdate(
1072 ContentUris.withAppendedId(RawContacts.CONTENT_URI, verifiedNameRawContactId));
1073 builder.withValue(RawContacts.NAME_VERIFIED, 1);
1074 operations.add(builder.build());
1075 }
1076
1077 boolean success = false;
1078 // Apply all aggregation exceptions as one batch
1079 try {
1080 resolver.applyBatch(ContactsContract.AUTHORITY, operations);
Dmitri Plotnikov886d3d62011-01-03 10:08:47 -08001081 showToast(R.string.contactsJoinedMessage);
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -08001082 success = true;
1083 } catch (RemoteException e) {
1084 Log.e(TAG, "Failed to apply aggregation exception batch", e);
Dmitri Plotnikov886d3d62011-01-03 10:08:47 -08001085 showToast(R.string.contactSavedErrorToast);
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -08001086 } catch (OperationApplicationException e) {
1087 Log.e(TAG, "Failed to apply aggregation exception batch", e);
Dmitri Plotnikov886d3d62011-01-03 10:08:47 -08001088 showToast(R.string.contactSavedErrorToast);
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -08001089 }
1090
1091 Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);
1092 if (success) {
1093 Uri uri = RawContacts.getContactLookupUri(resolver,
1094 ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactIds[0]));
1095 callbackIntent.setData(uri);
1096 }
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -08001097 deliverCallback(callbackIntent);
Dmitri Plotnikov2b46f032010-11-29 16:41:43 -08001098 }
1099
1100 /**
1101 * Construct a {@link AggregationExceptions#TYPE_KEEP_TOGETHER} ContentProviderOperation.
1102 */
1103 private void buildJoinContactDiff(ArrayList<ContentProviderOperation> operations,
1104 long rawContactId1, long rawContactId2) {
1105 Builder builder =
1106 ContentProviderOperation.newUpdate(AggregationExceptions.CONTENT_URI);
1107 builder.withValue(AggregationExceptions.TYPE, AggregationExceptions.TYPE_KEEP_TOGETHER);
1108 builder.withValue(AggregationExceptions.RAW_CONTACT_ID1, rawContactId1);
1109 builder.withValue(AggregationExceptions.RAW_CONTACT_ID2, rawContactId2);
1110 operations.add(builder.build());
1111 }
Dmitri Plotnikov886d3d62011-01-03 10:08:47 -08001112
1113 /**
1114 * Shows a toast on the UI thread.
1115 */
1116 private void showToast(final int message) {
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -08001117 mMainHandler.post(new Runnable() {
Dmitri Plotnikov886d3d62011-01-03 10:08:47 -08001118
1119 @Override
1120 public void run() {
1121 Toast.makeText(ContactSaveService.this, message, Toast.LENGTH_LONG).show();
1122 }
1123 });
1124 }
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -08001125
1126 private void deliverCallback(final Intent callbackIntent) {
1127 mMainHandler.post(new Runnable() {
1128
1129 @Override
1130 public void run() {
1131 deliverCallbackOnUiThread(callbackIntent);
1132 }
1133 });
1134 }
1135
1136 void deliverCallbackOnUiThread(final Intent callbackIntent) {
1137 // TODO: this assumes that if there are multiple instances of the same
1138 // activity registered, the last one registered is the one waiting for
1139 // the callback. Validity of this assumption needs to be verified.
Hugo Hudsona831c0b2011-08-13 11:50:15 +01001140 for (Listener listener : sListeners) {
1141 if (callbackIntent.getComponent().equals(
1142 ((Activity) listener).getIntent().getComponent())) {
1143 listener.onServiceCompleted(callbackIntent);
1144 return;
Dmitri Plotnikov3a6a9052011-03-02 10:14:43 -08001145 }
1146 }
1147 }
Daniel Lehmann173ffe12010-06-14 18:19:10 -07001148}