1 /*
2  * Copyright (C) 2016 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 package com.android.contacts.model;
17 
18 import android.content.ContentProviderOperation;
19 import android.database.MatrixCursor;
20 import android.net.Uri;
21 import android.os.Parcel;
22 import android.os.Parcelable;
23 import android.provider.ContactsContract;
24 import android.provider.ContactsContract.CommonDataKinds.Email;
25 import android.provider.ContactsContract.CommonDataKinds.Phone;
26 import android.provider.ContactsContract.CommonDataKinds.StructuredName;
27 import android.text.TextUtils;
28 
29 import com.android.contacts.ContactPhotoManager;
30 import com.android.contacts.model.account.AccountWithDataSet;
31 
32 import com.google.common.collect.ComparisonChain;
33 import com.google.common.collect.Ordering;
34 
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.Comparator;
39 import java.util.List;
40 import java.util.Objects;
41 
42 /**
43  * Holds data for contacts loaded from the SIM card.
44  */
45 public class SimContact implements Parcelable {
46     private final long mId;
47     private final String mName;
48     private final String mPhone;
49     private final String[] mEmails;
50 
SimContact(long id, String name, String phone)51     public SimContact(long id, String name, String phone) {
52         this(id, name, phone, null);
53     }
54 
SimContact(long id, String name, String phone, String[] emails)55     public SimContact(long id, String name, String phone, String[] emails) {
56         mId = id;
57         mName = name;
58         mPhone = phone == null ? "" : phone.trim();
59         mEmails = emails;
60     }
61 
SimContact(SimContact other)62     public SimContact(SimContact other) {
63         this(other.mId, other.mName, other.mPhone, other.mEmails);
64     }
65 
getId()66     public long getId() {
67         return mId;
68     }
69 
getName()70     public String getName() {
71         return mName;
72     }
73 
getPhone()74     public String getPhone() {
75         return mPhone;
76     }
77 
getEmails()78     public String[] getEmails() {
79         return mEmails;
80     }
81 
appendCreateContactOperations(List<ContentProviderOperation> ops, AccountWithDataSet targetAccount)82     public void appendCreateContactOperations(List<ContentProviderOperation> ops,
83             AccountWithDataSet targetAccount) {
84         // There is nothing to save so skip it.
85         if (!hasName() && !hasPhone() && !hasEmails()) return;
86 
87         final int rawContactOpIndex = ops.size();
88         ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
89                 .withYieldAllowed(true)
90                 .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, targetAccount.name)
91                 .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, targetAccount.type)
92                 .withValue(ContactsContract.RawContacts.DATA_SET, targetAccount.dataSet)
93                 .build());
94         if (mName != null) {
95             ops.add(createInsertOp(rawContactOpIndex, StructuredName.CONTENT_ITEM_TYPE,
96                     StructuredName.DISPLAY_NAME, mName));
97         }
98         if (!mPhone.isEmpty()) {
99             ops.add(createInsertOp(rawContactOpIndex, Phone.CONTENT_ITEM_TYPE,
100                     Phone.NUMBER, mPhone));
101         }
102         if (mEmails != null) {
103             for (String email : mEmails) {
104                 ops.add(createInsertOp(rawContactOpIndex, Email.CONTENT_ITEM_TYPE,
105                         Email.ADDRESS, email));
106             }
107         }
108     }
109 
createInsertOp(int rawContactOpIndex, String mimeType, String column, String value)110     private ContentProviderOperation createInsertOp(int rawContactOpIndex, String mimeType,
111             String column, String value) {
112         return ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
113                 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactOpIndex)
114                 .withValue(ContactsContract.Data.MIMETYPE, mimeType)
115                 .withValue(column, value)
116                 .build();
117     }
118 
appendAsContactRow(MatrixCursor cursor)119     public void appendAsContactRow(MatrixCursor cursor) {
120         cursor.newRow().add(ContactsContract.Contacts._ID, mId)
121                 .add(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, mName)
122                 .add(ContactsContract.Contacts.LOOKUP_KEY, getLookupKey());
123     }
124 
hasName()125     public boolean hasName() {
126         return !TextUtils.isEmpty(mName);
127     }
128 
hasPhone()129     public boolean hasPhone() {
130         return !mPhone.isEmpty();
131     }
132 
hasEmails()133     public boolean hasEmails() {
134         return mEmails != null && mEmails.length > 0;
135     }
136 
137     /**
138      * Generate a "fake" lookup key. This is needed because
139      * {@link ContactPhotoManager} will only generate a letter avatar
140      * if the contact has a lookup key.
141      */
getLookupKey()142     private String getLookupKey() {
143         if (mName != null) {
144             return "sim-n-" + Uri.encode(mName);
145         } else if (mPhone != null) {
146             return "sim-p-" + Uri.encode(mPhone);
147         } else {
148             return null;
149         }
150     }
151 
152     @Override
toString()153     public String toString() {
154         return "SimContact{" +
155                 "mId=" + mId +
156                 ", mName='" + mName + '\'' +
157                 ", mPhone='" + mPhone + '\'' +
158                 ", mEmails=" + Arrays.toString(mEmails) +
159                 '}';
160     }
161 
162     @Override
equals(Object o)163     public boolean equals(Object o) {
164         if (this == o) return true;
165         if (o == null || getClass() != o.getClass()) return false;
166 
167         final SimContact that = (SimContact) o;
168 
169         return mId == that.mId && Objects.equals(mName, that.mName) &&
170                 Objects.equals(mPhone, that.mPhone) && Arrays.equals(mEmails, that.mEmails);
171     }
172 
173     @Override
hashCode()174     public int hashCode() {
175         int result = (int) (mId ^ (mId >>> 32));
176         result = 31 * result + (mName != null ? mName.hashCode() : 0);
177         result = 31 * result + (mPhone != null ? mPhone.hashCode() : 0);
178         result = 31 * result + Arrays.hashCode(mEmails);
179         return result;
180     }
181 
182     @Override
describeContents()183     public int describeContents() {
184         return 0;
185     }
186 
187     @Override
writeToParcel(Parcel dest, int flags)188     public void writeToParcel(Parcel dest, int flags) {
189         dest.writeLong(mId);
190         dest.writeString(mName);
191         dest.writeString(mPhone);
192         dest.writeStringArray(mEmails);
193     }
194 
195     public static final Creator<SimContact> CREATOR = new Creator<SimContact>() {
196         @Override
197         public SimContact createFromParcel(Parcel source) {
198             final long id = source.readLong();
199             final String name = source.readString();
200             final String phone = source.readString();
201             final String[] emails = source.createStringArray();
202             return new SimContact(id, name, phone, emails);
203         }
204 
205         @Override
206         public SimContact[] newArray(int size) {
207             return new SimContact[size];
208         }
209     };
210 
211     /**
212      * Convert a collection of SIM contacts to a Cursor matching a query from
213      * {@link android.provider.ContactsContract.Contacts#CONTENT_URI} with the provided projection.
214      *
215      * This allows a collection of SIM contacts to be displayed using the existing adapters for
216      * contacts.
217      */
convertToContactsCursor(Collection<SimContact> contacts, String[] projection)218     public static final MatrixCursor convertToContactsCursor(Collection<SimContact> contacts,
219             String[] projection) {
220         final MatrixCursor result = new MatrixCursor(projection);
221         for (SimContact contact : contacts) {
222             contact.appendAsContactRow(result);
223         }
224         return result;
225     }
226 
227     /**
228      * Returns the index of a contact with a matching name and phone
229      * @param contacts list to search. Should be sorted using
230      * {@link SimContact#compareByPhoneThenName()}
231      * @param phone the phone to search for
232      * @param name the name to search for
233      */
findByPhoneAndName(List<SimContact> contacts, String phone, String name)234     public static int findByPhoneAndName(List<SimContact> contacts, String phone, String name) {
235         return Collections.binarySearch(contacts, new SimContact(-1, name, phone, null),
236                 compareByPhoneThenName());
237     }
238 
compareByPhoneThenName()239     public static final Comparator<SimContact> compareByPhoneThenName() {
240         return new Comparator<SimContact>() {
241             @Override
242             public int compare(SimContact lhs, SimContact rhs) {
243                 return ComparisonChain.start()
244                         .compare(lhs.mPhone, rhs.mPhone)
245                         .compare(lhs.mName, rhs.mName, Ordering.<String>natural().nullsFirst())
246                         .result();
247             }
248         };
249     }
250 
251     public static final Comparator<SimContact> compareById() {
252         return new Comparator<SimContact>() {
253             @Override
254             public int compare(SimContact lhs, SimContact rhs) {
255                 // We assume ids are unique.
256                 return Long.compare(lhs.mId, rhs.mId);
257             }
258         };
259     }
260 }
261