summaryrefslogtreecommitdiff
path: root/android/util/RecurrenceRule.java
blob: 9f115eba442cd17f640e95a4c8410d545c0e88ba (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
/*
 * Copyright (C) 2017 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 android.util;

import android.os.Parcel;
import android.os.Parcelable;

import com.android.internal.annotations.VisibleForTesting;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ProtocolException;
import java.time.Clock;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Iterator;
import java.util.Objects;

/**
 * Description of an event that should recur over time at a specific interval
 * between two anchor points in time.
 *
 * @hide
 */
public class RecurrenceRule implements Parcelable {
    private static final String TAG = "RecurrenceRule";
    private static final boolean LOGD = Log.isLoggable(TAG, Log.DEBUG);

    private static final int VERSION_INIT = 0;

    /** {@hide} */
    @VisibleForTesting
    public static Clock sClock = Clock.systemDefaultZone();

    public final ZonedDateTime start;
    public final ZonedDateTime end;
    public final Period period;

    public RecurrenceRule(ZonedDateTime start, ZonedDateTime end, Period period) {
        this.start = start;
        this.end = end;
        this.period = period;
    }

    @Deprecated
    public static RecurrenceRule buildNever() {
        return new RecurrenceRule(null, null, null);
    }

    @Deprecated
    public static RecurrenceRule buildRecurringMonthly(int dayOfMonth, ZoneId zone) {
        // Assume we started last January, since it has all possible days
        final ZonedDateTime now = ZonedDateTime.now(sClock).withZoneSameInstant(zone);
        final ZonedDateTime start = ZonedDateTime.of(
                now.toLocalDate().minusYears(1).withMonth(1).withDayOfMonth(dayOfMonth),
                LocalTime.MIDNIGHT, zone);
        return new RecurrenceRule(start, null, Period.ofMonths(1));
    }

    private RecurrenceRule(Parcel source) {
        start = convertZonedDateTime(source.readString());
        end = convertZonedDateTime(source.readString());
        period = convertPeriod(source.readString());
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(convertZonedDateTime(start));
        dest.writeString(convertZonedDateTime(end));
        dest.writeString(convertPeriod(period));
    }

    public RecurrenceRule(DataInputStream in) throws IOException {
        final int version = in.readInt();
        switch (version) {
            case VERSION_INIT:
                start = convertZonedDateTime(BackupUtils.readString(in));
                end = convertZonedDateTime(BackupUtils.readString(in));
                period = convertPeriod(BackupUtils.readString(in));
                break;
            default:
                throw new ProtocolException("Unknown version " + version);
        }
    }

    public void writeToStream(DataOutputStream out) throws IOException {
        out.writeInt(VERSION_INIT);
        BackupUtils.writeString(out, convertZonedDateTime(start));
        BackupUtils.writeString(out, convertZonedDateTime(end));
        BackupUtils.writeString(out, convertPeriod(period));
    }

    @Override
    public String toString() {
        return new StringBuilder("RecurrenceRule{")
                .append("start=").append(start)
                .append(" end=").append(end)
                .append(" period=").append(period)
                .append("}").toString();
    }

    @Override
    public int hashCode() {
        return Objects.hash(start, end, period);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof RecurrenceRule) {
            final RecurrenceRule other = (RecurrenceRule) obj;
            return Objects.equals(start, other.start)
                    && Objects.equals(end, other.end)
                    && Objects.equals(period, other.period);
        }
        return false;
    }

    public static final Parcelable.Creator<RecurrenceRule> CREATOR = new Parcelable.Creator<RecurrenceRule>() {
        @Override
        public RecurrenceRule createFromParcel(Parcel source) {
            return new RecurrenceRule(source);
        }

        @Override
        public RecurrenceRule[] newArray(int size) {
            return new RecurrenceRule[size];
        }
    };

    @Deprecated
    public boolean isMonthly() {
        return start != null
                && period != null
                && period.getYears() == 0
                && period.getMonths() == 1
                && period.getDays() == 0;
    }

    public Iterator<Pair<ZonedDateTime, ZonedDateTime>> cycleIterator() {
        if (period != null) {
            return new RecurringIterator();
        } else {
            return new NonrecurringIterator();
        }
    }

    private class NonrecurringIterator implements Iterator<Pair<ZonedDateTime, ZonedDateTime>> {
        boolean hasNext;

        public NonrecurringIterator() {
            hasNext = (start != null) && (end != null);
        }

        @Override
        public boolean hasNext() {
            return hasNext;
        }

        @Override
        public Pair<ZonedDateTime, ZonedDateTime> next() {
            hasNext = false;
            return new Pair<>(start, end);
        }
    }

    private class RecurringIterator implements Iterator<Pair<ZonedDateTime, ZonedDateTime>> {
        int i;
        ZonedDateTime cycleStart;
        ZonedDateTime cycleEnd;

        public RecurringIterator() {
            final ZonedDateTime anchor = (end != null) ? end
                    : ZonedDateTime.now(sClock).withZoneSameInstant(start.getZone());
            if (LOGD) Log.d(TAG, "Resolving using anchor " + anchor);

            updateCycle();

            // Walk forwards until we find first cycle after now
            while (anchor.toEpochSecond() > cycleEnd.toEpochSecond()) {
                i++;
                updateCycle();
            }

            // Walk backwards until we find first cycle before now
            while (anchor.toEpochSecond() <= cycleStart.toEpochSecond()) {
                i--;
                updateCycle();
            }
        }

        private void updateCycle() {
            cycleStart = roundBoundaryTime(start.plus(period.multipliedBy(i)));
            cycleEnd = roundBoundaryTime(start.plus(period.multipliedBy(i + 1)));
        }

        private ZonedDateTime roundBoundaryTime(ZonedDateTime boundary) {
            if (isMonthly() && (boundary.getDayOfMonth() < start.getDayOfMonth())) {
                // When forced to end a monthly cycle early, we want to count
                // that entire day against the boundary.
                return ZonedDateTime.of(boundary.toLocalDate(), LocalTime.MAX, start.getZone());
            } else {
                return boundary;
            }
        }

        @Override
        public boolean hasNext() {
            return cycleStart.toEpochSecond() >= start.toEpochSecond();
        }

        @Override
        public Pair<ZonedDateTime, ZonedDateTime> next() {
            if (LOGD) Log.d(TAG, "Cycle " + i + " from " + cycleStart + " to " + cycleEnd);
            Pair<ZonedDateTime, ZonedDateTime> p = new Pair<>(cycleStart, cycleEnd);
            i--;
            updateCycle();
            return p;
        }
    }

    public static String convertZonedDateTime(ZonedDateTime time) {
        return time != null ? time.toString() : null;
    }

    public static ZonedDateTime convertZonedDateTime(String time) {
        return time != null ? ZonedDateTime.parse(time) : null;
    }

    public static String convertPeriod(Period period) {
        return period != null ? period.toString() : null;
    }

    public static Period convertPeriod(String period) {
        return period != null ? Period.parse(period) : null;
    }
}