summaryrefslogtreecommitdiff
path: root/java/com/android/dialer/speeddial/loader/SpeedDialUiItem.java
blob: 365b88f8ca9256dce4b875f203f06ccf47ca790d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.dialer.speeddial.loader;

import android.content.res.Resources;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.android.dialer.common.Assert;
import com.android.dialer.glidephotomanager.PhotoInfo;
import com.android.dialer.speeddial.database.SpeedDialEntry;
import com.android.dialer.speeddial.database.SpeedDialEntry.Channel;
import com.google.auto.value.AutoValue;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * POJO representation of each speed dial list element.
 *
 * <p>Contains all data needed for the UI so that the UI never needs do additional contact queries.
 *
 * <p>Differs from {@link SpeedDialEntry} in that entries are specific to favorited/starred contacts
 * and {@link SpeedDialUiItem}s can be both favorites and suggested contacts.
 */
@AutoValue
public abstract class SpeedDialUiItem {

  public static final int LOOKUP_KEY = 0;
  public static final int CONTACT_ID = 1;
  public static final int DISPLAY_NAME = 2;
  public static final int STARRED = 3;
  public static final int NUMBER = 4;
  public static final int TYPE = 5;
  public static final int LABEL = 6;
  public static final int PHOTO_ID = 7;
  public static final int PHOTO_URI = 8;
  public static final int CARRIER_PRESENCE = 9;

  private static final String[] PHONE_PROJECTION = {
    Phone.LOOKUP_KEY,
    Phone.CONTACT_ID,
    Phone.DISPLAY_NAME,
    Phone.STARRED,
    Phone.NUMBER,
    Phone.TYPE,
    Phone.LABEL,
    Phone.PHOTO_ID,
    Phone.PHOTO_URI,
    Phone.CARRIER_PRESENCE
  };

  private static final String[] PHONE_PROJECTION_ALTERNATIVE = {
    Phone.LOOKUP_KEY,
    Phone.CONTACT_ID,
    Phone.DISPLAY_NAME_ALTERNATIVE,
    Phone.STARRED,
    Phone.NUMBER,
    Phone.TYPE,
    Phone.LABEL,
    Phone.PHOTO_ID,
    Phone.PHOTO_URI,
    Phone.CARRIER_PRESENCE
  };

  public static String[] getPhoneProjection(boolean primaryDisplayOrder) {
    return primaryDisplayOrder ? PHONE_PROJECTION : PHONE_PROJECTION_ALTERNATIVE;
  }

  public static Builder builder() {
    return new AutoValue_SpeedDialUiItem.Builder()
        .setChannels(ImmutableList.of())
        .setPinnedPosition(Optional.absent());
  }

  /**
   * Convert a cursor with projection {@link #getPhoneProjection(boolean)} into a {@link
   * SpeedDialUiItem}.
   *
   * <p>This cursor is structured such that contacts are grouped by contact id and lookup key and
   * each row that shares the same contact id and lookup key represents a phone number that belongs
   * to a single contact.
   *
   * <p>If the cursor started at row X, this method will advance to row Y s.t. rows X, X + 1, ... Y
   * - 1 all belong to the same contact (that is, share the same contact id and lookup key).
   */
  public static SpeedDialUiItem fromCursor(Resources resources, Cursor cursor) {
    Assert.checkArgument(cursor != null);
    Assert.checkArgument(cursor.getCount() != 0);
    String lookupKey = cursor.getString(LOOKUP_KEY);
    SpeedDialUiItem.Builder builder =
        SpeedDialUiItem.builder()
            .setLookupKey(lookupKey)
            .setContactId(cursor.getLong(CONTACT_ID))
            // TODO(a bug): handle last name first preference
            .setName(cursor.getString(DISPLAY_NAME))
            .setIsStarred(cursor.getInt(STARRED) == 1)
            .setPhotoId(cursor.getLong(PHOTO_ID))
            .setPhotoUri(
                TextUtils.isEmpty(cursor.getString(PHOTO_URI)) ? "" : cursor.getString(PHOTO_URI));

    // While there are more rows and the lookup keys are the same, add a channel for each of the
    // contact's phone numbers.
    List<Channel> channels = new ArrayList<>();
    do {
      Channel channel =
          Channel.builder()
              .setNumber(cursor.getString(NUMBER))
              .setPhoneType(cursor.getInt(TYPE))
              .setLabel(getLabel(resources, cursor))
              .setTechnology(Channel.VOICE)
              .build();
      channels.add(channel);

      if ((cursor.getInt(CARRIER_PRESENCE) & Data.CARRIER_PRESENCE_VT_CAPABLE) == 1) {
        // Add another channel if the number is ViLTE reachable
        channels.add(channel.toBuilder().setTechnology(Channel.IMS_VIDEO).build());
      }
      // TODO(a bug): add another channel for Duo (needs to happen on main thread)
    } while (cursor.moveToNext() && Objects.equals(lookupKey, cursor.getString(LOOKUP_KEY)));

    builder.setChannels(ImmutableList.copyOf(channels));
    return builder.build();
  }

  private static String getLabel(Resources resources, Cursor cursor) {
    int numberType = cursor.getInt(TYPE);
    String numberLabel = cursor.getString(LABEL);

    // Returns empty label instead of "custom" if the custom label is empty.
    if (numberType == Phone.TYPE_CUSTOM && TextUtils.isEmpty(numberLabel)) {
      return "";
    }
    return (String) Phone.getTypeLabel(resources, numberType, numberLabel);
  }

  public PhotoInfo getPhotoInfo() {
    return PhotoInfo.newBuilder()
        .setPhotoId(photoId())
        .setPhotoUri(photoUri())
        .setName(name())
        .setIsVideo(defaultChannel() != null && defaultChannel().isVideoTechnology())
        .setLookupUri(Contacts.getLookupUri(contactId(), lookupKey()).toString())
        .build();
  }

  public SpeedDialEntry buildSpeedDialEntry() {
    return SpeedDialEntry.builder()
        .setId(speedDialEntryId())
        .setPinnedPosition(pinnedPosition())
        .setLookupKey(lookupKey())
        .setContactId(contactId())
        .setDefaultChannel(defaultChannel())
        .build();
  }

  /**
   * Returns one of the following:
   *
   * <ul>
   *   <li>The default channel if it's a video channel.
   *   <li>A video channel if it has the same attributes as the default channel, OR
   *   <li>null. (This is a deliberate product decision, even if there is only a single video
   *       reachable channel, we should still return null if it has different attributes from those
   *       in the default channel).
   * </ul>
   */
  @Nullable
  public Channel getDefaultVideoChannel() {
    if (defaultChannel() == null) {
      return null;
    }

    if (defaultChannel().isVideoTechnology()) {
      return defaultChannel();
    }

    if (channels().size() == 1) {
      // If there is only a single channel, it can't be a video channel
      return null;
    }

    // At this point, the default channel is a *voice* channel and there are more than
    // one channel in total.
    //
    // Our defined assumptions about the channel list include that if a video channel
    // follows a voice channel, it has the same attributes as that voice channel
    // (see comments on method channels() for details).
    //
    // Therefore, if the default video channel exists, it must be the immediate successor
    // of the default channel in the list.
    //
    // Note that we don't have to check if the last channel in the list is the default
    // channel because even if it is, there will be no video channel under the assumption
    // above.
    for (int i = 0; i < channels().size() - 1; i++) {
      // Find the default channel
      if (Objects.equals(defaultChannel(), channels().get(i))) {
        // Our defined assumptions about the list of channels is that if a video channel follows a
        // voice channel, it has the same attributes as that voice channel.
        Channel channel = channels().get(i + 1);
        if (channel.isVideoTechnology()) {
          return channel;
        }
        // Since the default voice channel isn't video reachable, we can't video call this number
        return null;
      }
    }
    throw Assert.createIllegalStateFailException("channels() doesn't contain defaultChannel().");
  }

  /**
   * Returns a voice channel if there is exactly one channel or the default channel is a voice
   * channel.
   */
  @Nullable
  public Channel getDefaultVoiceChannel() {
    if (channels().size() == 1) {
      // If there is only a single channel, it must be a voice channel as per our defined
      // assumptions (detailed in comments on method channels()).
      return channels().get(0);
    }

    if (defaultChannel() == null) {
      return null;
    }

    if (!defaultChannel().isVideoTechnology()) {
      return defaultChannel();
    }

    // Default channel is a video channel, so find it's corresponding voice channel
    Channel prevChannel = channels().get(0);
    for (int i = 1; i < channels().size(); i++) {
      Channel currentChannel = channels().get(i);
      if (currentChannel.equals(defaultChannel())) {
        return prevChannel;
      }
      prevChannel = currentChannel;
    }
    return null;
  }

  /**
   * The id of the corresponding SpeedDialEntry. Null if the UI item does not have an entry, for
   * example suggested contacts (isStarred() will also be false)
   *
   * @see SpeedDialEntry#id()
   */
  @Nullable
  public abstract Long speedDialEntryId();

  /** @see SpeedDialEntry#pinnedPosition() */
  public abstract Optional<Integer> pinnedPosition();

  /** @see android.provider.ContactsContract.Contacts#DISPLAY_NAME */
  public abstract String name();

  /** @see android.provider.ContactsContract.Contacts#_ID */
  public abstract long contactId();

  /** @see android.provider.ContactsContract.Contacts#LOOKUP_KEY */
  public abstract String lookupKey();

  /** @see android.provider.ContactsContract.Contacts#STARRED */
  public abstract boolean isStarred();

  /** @see Phone#PHOTO_ID */
  public abstract long photoId();

  /** @see Phone#PHOTO_URI */
  public abstract String photoUri();

  /**
   * Since a contact can have multiple phone numbers and each number can have multiple technologies,
   * enumerate each one here so that the user can choose the correct one. Each channel here
   * represents a row in the {@link com.android.dialer.speeddial.DisambigDialog}.
   *
   * <p>These channels have a few very strictly enforced assumption that are used heavily throughout
   * the codebase. Those assumption are that:
   *
   * <ol>
   *   <li>Each of the contact's numbers are voice reachable. So if a channel has it's technology
   *       set to anything other than {@link Channel#VOICE}, there is gaurenteed to be another
   *       channel with the exact same attributes, but technology will be {@link Channel#VOICE}.
   *   <li>For each of the contact's phone numbers, there will be a voice channel, then the next
   *       channel will either be the same phone number but a video channel, or a new number.
   * </ol>
   *
   * For example: Say a contact has two phone numbers (A & B) and A is duo reachable. Then you can
   * assume the list of channels will be ordered as either {A_voice, A_duo, B_voice} or {B_voice,
   * A_voice, A_duo}.
   *
   * @see com.android.dialer.speeddial.database.SpeedDialEntry.Channel
   */
  public abstract ImmutableList<Channel> channels();

  /**
   * Will be null when the user hasn't chosen a default yet.
   *
   * @see com.android.dialer.speeddial.database.SpeedDialEntry#defaultChannel()
   */
  public abstract @Nullable Channel defaultChannel();

  public abstract Builder toBuilder();

  /** Builder class for speed dial contact. */
  @AutoValue.Builder
  public abstract static class Builder {

    /** Set to null if {@link #isStarred()} is false. */
    public abstract Builder setSpeedDialEntryId(@Nullable Long id);

    public abstract Builder setPinnedPosition(Optional<Integer> pinnedPosition);

    public abstract Builder setName(String name);

    public abstract Builder setContactId(long contactId);

    public abstract Builder setLookupKey(String lookupKey);

    public abstract Builder setIsStarred(boolean isStarred);

    public abstract Builder setPhotoId(long photoId);

    public abstract Builder setPhotoUri(String photoUri);

    public abstract Builder setChannels(ImmutableList<Channel> channels);

    /** Set to null if the user hasn't chosen a default or the channel no longer exists. */
    public abstract Builder setDefaultChannel(@Nullable Channel defaultChannel);

    public abstract SpeedDialUiItem build();
  }
}