1package com.android.contacts.interactions;
2
3import com.google.common.base.Preconditions;
4
5import java.util.ArrayList;
6import java.util.Arrays;
7import java.util.Collections;
8import java.util.HashSet;
9import java.util.List;
10import java.util.Set;
11
12import android.content.AsyncTaskLoader;
13import android.content.ContentValues;
14import android.content.Context;
15import android.database.Cursor;
16import android.database.DatabaseUtils;
17import android.provider.CalendarContract;
18import android.provider.CalendarContract.Calendars;
19import android.util.Log;
20
21
22/**
23 * Loads a list of calendar interactions showing shared calendar events with everyone passed in
24 * {@param emailAddresses}.
25 *
26 * Note: the calendar provider treats mailing lists as atomic email addresses.
27 */
28public class CalendarInteractionsLoader extends AsyncTaskLoader<List<ContactInteraction>> {
29    private static final String TAG = CalendarInteractionsLoader.class.getSimpleName();
30
31    private List<String> mEmailAddresses;
32    private int mMaxFutureToRetrieve;
33    private int mMaxPastToRetrieve;
34    private long mNumberFutureMillisecondToSearchLocalCalendar;
35    private long mNumberPastMillisecondToSearchLocalCalendar;
36    private List<ContactInteraction> mData;
37
38
39    /**
40     * @param maxFutureToRetrieve The maximum number of future events to retrieve
41     * @param maxPastToRetrieve The maximum number of past events to retrieve
42     */
43    public CalendarInteractionsLoader(Context context, List<String> emailAddresses,
44            int maxFutureToRetrieve, int maxPastToRetrieve,
45            long numberFutureMillisecondToSearchLocalCalendar,
46            long numberPastMillisecondToSearchLocalCalendar) {
47        super(context);
48        mEmailAddresses = emailAddresses;
49        mMaxFutureToRetrieve = maxFutureToRetrieve;
50        mMaxPastToRetrieve = maxPastToRetrieve;
51        mNumberFutureMillisecondToSearchLocalCalendar =
52                numberFutureMillisecondToSearchLocalCalendar;
53        mNumberPastMillisecondToSearchLocalCalendar = numberPastMillisecondToSearchLocalCalendar;
54    }
55
56    @Override
57    public List<ContactInteraction> loadInBackground() {
58        if (mEmailAddresses == null || mEmailAddresses.size() < 1) {
59            return Collections.emptyList();
60        }
61        // Perform separate calendar queries for events in the past and future.
62        Cursor cursor = getSharedEventsCursor(/* isFuture= */ true, mMaxFutureToRetrieve);
63        List<ContactInteraction> interactions = getInteractionsFromEventsCursor(cursor);
64        cursor = getSharedEventsCursor(/* isFuture= */ false, mMaxPastToRetrieve);
65        List<ContactInteraction> interactions2 = getInteractionsFromEventsCursor(cursor);
66
67        ArrayList<ContactInteraction> allInteractions = new ArrayList<ContactInteraction>(
68                interactions.size() + interactions2.size());
69        allInteractions.addAll(interactions);
70        allInteractions.addAll(interactions2);
71
72        Log.v(TAG, "# ContactInteraction Loaded: " + allInteractions.size());
73        return allInteractions;
74    }
75
76    /**
77     * @return events inside phone owners' calendars, that are shared with people inside mEmails
78     */
79    private Cursor getSharedEventsCursor(boolean isFuture, int limit) {
80        List<String> calendarIds = getOwnedCalendarIds();
81        if (calendarIds == null) {
82            return null;
83        }
84        long timeMillis = System.currentTimeMillis();
85
86        List<String> selectionArgs = new ArrayList<>();
87        selectionArgs.addAll(mEmailAddresses);
88        selectionArgs.addAll(calendarIds);
89
90        // Add time constraints to selectionArgs
91        String timeOperator = isFuture ? " > " : " < ";
92        long pastTimeCutoff = timeMillis - mNumberPastMillisecondToSearchLocalCalendar;
93        long futureTimeCutoff = timeMillis
94                + mNumberFutureMillisecondToSearchLocalCalendar;
95        String[] timeArguments = {String.valueOf(timeMillis), String.valueOf(pastTimeCutoff),
96                String.valueOf(futureTimeCutoff)};
97        selectionArgs.addAll(Arrays.asList(timeArguments));
98
99        String orderBy = CalendarContract.Attendees.DTSTART + (isFuture ? " ASC " : " DESC ");
100        String selection = caseAndDotInsensitiveEmailComparisonClause(mEmailAddresses.size())
101                + " AND " + CalendarContract.Attendees.CALENDAR_ID
102                + " IN " + ContactInteractionUtil.questionMarks(calendarIds.size())
103                + " AND " + CalendarContract.Attendees.DTSTART + timeOperator + " ? "
104                + " AND " + CalendarContract.Attendees.DTSTART + " > ? "
105                + " AND " + CalendarContract.Attendees.DTSTART + " < ? ";
106
107        return getContext().getContentResolver().query(CalendarContract.Attendees.CONTENT_URI,
108                /* projection = */ null, selection,
109                selectionArgs.toArray(new String[selectionArgs.size()]),
110                orderBy + " LIMIT " + limit);
111    }
112
113    /**
114     * Returns a clause that checks whether an attendee's email is equal to one of
115     * {@param count} values. The comparison is insensitive to dots and case.
116     *
117     * NOTE #1: This function is only needed for supporting non google accounts. For calendars
118     * synced by a google account, attendee email values will be be modified by the server to ensure
119     * they match an entry in contacts.google.com.
120     *
121     * NOTE #2: This comparison clause can result in false positives. Ex#1, test@gmail.com will
122     * match test@gmailco.m. Ex#2, a.2@exchange.com will match a2@exchange.com (exchange addresses
123     * should be dot sensitive). This probably isn't a large concern.
124     */
125    private String caseAndDotInsensitiveEmailComparisonClause(int count) {
126        Preconditions.checkArgument(count > 0, "Count needs to be positive");
127        final String COMPARISON
128                = " REPLACE(" + CalendarContract.Attendees.ATTENDEE_EMAIL
129                + ", '.', '') = REPLACE(?, '.', '') COLLATE NOCASE";
130        StringBuilder sb = new StringBuilder("( " + COMPARISON);
131        for (int i = 1; i < count; i++) {
132            sb.append(" OR " + COMPARISON);
133        }
134        return sb.append(")").toString();
135    }
136
137    /**
138     * @return A list with upto one Card. The Card contains events from {@param Cursor}.
139     * Only returns unique events.
140     */
141    private List<ContactInteraction> getInteractionsFromEventsCursor(Cursor cursor) {
142        try {
143            if (cursor == null || cursor.getCount() == 0) {
144                return Collections.emptyList();
145            }
146            Set<String> uniqueUris = new HashSet<String>();
147            ArrayList<ContactInteraction> interactions = new ArrayList<ContactInteraction>();
148            while (cursor.moveToNext()) {
149                ContentValues values = new ContentValues();
150                DatabaseUtils.cursorRowToContentValues(cursor, values);
151                CalendarInteraction calendarInteraction = new CalendarInteraction(values);
152                if (!uniqueUris.contains(calendarInteraction.getIntent().getData().toString())) {
153                    uniqueUris.add(calendarInteraction.getIntent().getData().toString());
154                    interactions.add(calendarInteraction);
155                }
156            }
157
158            return interactions;
159        } finally {
160            if (cursor != null) {
161                cursor.close();
162            }
163        }
164    }
165
166    /**
167     * @return the Ids of calendars that are owned by accounts on the phone.
168     */
169    private List<String> getOwnedCalendarIds() {
170        String[] projection = new String[] {Calendars._ID, Calendars.CALENDAR_ACCESS_LEVEL};
171        Cursor cursor = getContext().getContentResolver().query(Calendars.CONTENT_URI, projection,
172                Calendars.VISIBLE + " = 1 AND " + Calendars.CALENDAR_ACCESS_LEVEL + " = ? ",
173                new String[] {String.valueOf(Calendars.CAL_ACCESS_OWNER)}, null);
174        try {
175            if (cursor == null || cursor.getCount() < 1) {
176                return null;
177            }
178            cursor.moveToPosition(-1);
179            List<String> calendarIds = new ArrayList<>(cursor.getCount());
180            while (cursor.moveToNext()) {
181                calendarIds.add(String.valueOf(cursor.getInt(0)));
182            }
183            return calendarIds;
184        } finally {
185            if (cursor != null) {
186                cursor.close();
187            }
188        }
189    }
190
191    @Override
192    protected void onStartLoading() {
193        super.onStartLoading();
194
195        if (mData != null) {
196            deliverResult(mData);
197        }
198
199        if (takeContentChanged() || mData == null) {
200            forceLoad();
201        }
202    }
203
204    @Override
205    protected void onStopLoading() {
206        // Attempt to cancel the current load task if possible.
207        cancelLoad();
208    }
209
210    @Override
211    protected void onReset() {
212        super.onReset();
213
214        // Ensure the loader is stopped
215        onStopLoading();
216        if (mData != null) {
217            mData.clear();
218        }
219    }
220
221    @Override
222    public void deliverResult(List<ContactInteraction> data) {
223        mData = data;
224        if (isStarted()) {
225            super.deliverResult(data);
226        }
227    }
228}
229