1package eu.siacs.conversations.android;
2
3import android.Manifest;
4import android.content.Context;
5import android.content.pm.PackageManager;
6import android.database.Cursor;
7import android.os.Build;
8import android.provider.ContactsContract;
9import android.util.Log;
10
11import java.util.Collections;
12import java.util.HashMap;
13
14import eu.siacs.conversations.Config;
15import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
16import io.michaelrocks.libphonenumber.android.NumberParseException;
17
18public class PhoneNumberContact extends AbstractPhoneContact {
19
20 private String phoneNumber;
21
22 public String getPhoneNumber() {
23 return phoneNumber;
24 }
25
26 private PhoneNumberContact(Context context, Cursor cursor) throws IllegalArgumentException {
27 super(cursor);
28 try {
29 this.phoneNumber = PhoneNumberUtilWrapper.normalize(context,cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
30 } catch (NumberParseException | NullPointerException e) {
31 throw new IllegalArgumentException(e);
32 }
33 }
34
35 public static void load(Context context, OnPhoneContactsLoaded<PhoneNumberContact> callback) {
36 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
37 callback.onPhoneContactsLoaded(Collections.emptyList());
38 return;
39 }
40 final String[] PROJECTION = new String[]{ContactsContract.Data._ID,
41 ContactsContract.Data.DISPLAY_NAME,
42 ContactsContract.Data.PHOTO_URI,
43 ContactsContract.Data.LOOKUP_KEY,
44 ContactsContract.CommonDataKinds.Phone.NUMBER};
45 final Cursor cursor;
46 try {
47 cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
48 } catch (Exception e) {
49 callback.onPhoneContactsLoaded(Collections.emptyList());
50 return;
51 }
52 final HashMap<String, PhoneNumberContact> contacts = new HashMap<>();
53 while (cursor != null && cursor.moveToNext()) {
54 try {
55 final PhoneNumberContact contact = new PhoneNumberContact(context, cursor);
56 final PhoneNumberContact preexisting = contacts.get(contact.getPhoneNumber());
57 if (preexisting == null || preexisting.rating() < contact.rating()) {
58 contacts.put(contact.getPhoneNumber(), contact);
59 }
60 } catch (IllegalArgumentException e) {
61 Log.d(Config.LOGTAG, "unable to create phone contact");
62 }
63 }
64 if (cursor != null) {
65 cursor.close();
66 }
67 callback.onPhoneContactsLoaded(contacts.values());
68 }
69}