aboutsummaryrefslogtreecommitdiff
path: root/src/com/android/tv/data/WatchedHistoryManager.java
blob: 3edd7b1a0dbf02569f8343bce13e38ba7d5a6274 (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
package com.android.tv.data;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.support.annotation.WorkerThread;
import android.util.Log;

import com.android.tv.common.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * A class to manage watched history.
 *
 * <p>When there is no access to watched table of TvProvider,
 * this class is used to build up watched history and to compute recent channels.
 * <p>Note that this class is not thread safe. Please use this on one thread.
 */
public class WatchedHistoryManager {
    private final static String TAG = "WatchedHistoryManager";
    private final static boolean DEBUG = false;

    private static final int MAX_HISTORY_SIZE = 10000;
    private static final String PREF_KEY_LAST_INDEX = "last_index";
    private static final long MIN_DURATION_MS = TimeUnit.SECONDS.toMillis(10);

    private final List<WatchedRecord> mWatchedHistory = new ArrayList<>();
    private final List<WatchedRecord> mPendingRecords = new ArrayList<>();
    private long mLastIndex;
    private boolean mStarted;
    private boolean mLoaded;
    private SharedPreferences mSharedPreferences;
    private final OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener =
            new OnSharedPreferenceChangeListener() {
                @Override
                @MainThread
                public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                        String key) {
                    if (key.equals(PREF_KEY_LAST_INDEX)) {
                        final long lastIndex = mSharedPreferences.getLong(PREF_KEY_LAST_INDEX, -1);
                        if (lastIndex <= mLastIndex) {
                            return;
                        }
                        // onSharedPreferenceChanged is always called in a main thread.
                        // onNewRecordAdded will be called in the same thread as the thread
                        // which created this instance.
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                for (long i = mLastIndex + 1; i <= lastIndex; ++i) {
                                    WatchedRecord record = decode(
                                            mSharedPreferences.getString(getSharedPreferencesKey(i),
                                                    null));
                                    if (record != null) {
                                        mWatchedHistory.add(record);
                                        if (mListener != null) {
                                            mListener.onNewRecordAdded(record);
                                        }
                                    }
                                }
                                mLastIndex = lastIndex;
                            }
                        });
                    }
                }
            };

    private final Context mContext;
    private Listener mListener;
    private final int mMaxHistorySize;
    private final Handler mHandler;

    public WatchedHistoryManager(Context context) {
        this(context, MAX_HISTORY_SIZE);
    }

    @VisibleForTesting
    WatchedHistoryManager(Context context, int maxHistorySize) {
        mContext = context.getApplicationContext();
        mMaxHistorySize = maxHistorySize;
        mHandler = new Handler();
    }

    /**
     * Starts the manager. It loads history data from {@link SharedPreferences}.
     */
    public void start() {
        if (mStarted) {
            return;
        }
        mStarted = true;
        if (Looper.myLooper() == Looper.getMainLooper()) {
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    loadWatchedHistory();
                    return null;
                }

                @Override
                protected void onPostExecute(Void params) {
                    onLoadFinished();
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        } else {
            loadWatchedHistory();
            onLoadFinished();
        }
    }

    @WorkerThread
    private void loadWatchedHistory() {
        mSharedPreferences = mContext.getSharedPreferences(
                SharedPreferencesUtils.SHARED_PREF_WATCHED_HISTORY, Context.MODE_PRIVATE);
        mLastIndex = mSharedPreferences.getLong(PREF_KEY_LAST_INDEX, -1);
        if (mLastIndex >= 0 && mLastIndex < mMaxHistorySize) {
            for (int i = 0; i <= mLastIndex; ++i) {
                WatchedRecord record =
                        decode(mSharedPreferences.getString(getSharedPreferencesKey(i),
                                null));
                if (record != null) {
                    mWatchedHistory.add(record);
                }
            }
        } else if (mLastIndex >= mMaxHistorySize) {
            for (long i = mLastIndex - mMaxHistorySize + 1; i <= mLastIndex; ++i) {
                WatchedRecord record = decode(mSharedPreferences.getString(
                        getSharedPreferencesKey(i), null));
                if (record != null) {
                    mWatchedHistory.add(record);
                }
            }
        }
    }

    private void onLoadFinished() {
        mLoaded = true;
        if (DEBUG) {
            Log.d(TAG, "Loaded: size=" + mWatchedHistory.size() + " index=" + mLastIndex);
        }
        if (!mPendingRecords.isEmpty()) {
            Editor editor = mSharedPreferences.edit();
            for (WatchedRecord record : mPendingRecords) {
                mWatchedHistory.add(record);
                ++mLastIndex;
                editor.putString(getSharedPreferencesKey(mLastIndex), encode(record));
            }
            editor.putLong(PREF_KEY_LAST_INDEX, mLastIndex).apply();
            mPendingRecords.clear();
        }
        if (mListener != null) {
            mListener.onLoadFinished();
        }
        mSharedPreferences.registerOnSharedPreferenceChangeListener(
                mOnSharedPreferenceChangeListener);
    }

    @VisibleForTesting
    public boolean isLoaded() {
        return mLoaded;
    }

    /**
     * Logs the record of the watched channel.
     */
    public void logChannelViewStop(Channel channel, long endTime, long duration) {
        if (duration < MIN_DURATION_MS) {
            return;
        }
        WatchedRecord record = new WatchedRecord(channel.getId(), endTime - duration, duration);
        if (mLoaded) {
            if (DEBUG) Log.d(TAG, "Log a watched record. " + record);
            mWatchedHistory.add(record);
            ++mLastIndex;
            mSharedPreferences.edit()
                    .putString(getSharedPreferencesKey(mLastIndex), encode(record))
                    .putLong(PREF_KEY_LAST_INDEX, mLastIndex)
                    .apply();
            if (mListener != null) {
                mListener.onNewRecordAdded(record);
            }
        } else {
            mPendingRecords.add(record);
        }
    }

    /**
     * Sets {@link Listener}.
     */
    public void setListener(Listener listener) {
        mListener = listener;
    }

    /**
     * Returns watched history in the ascending order of time. In other words, the first element
     * is the oldest and the last element is the latest record.
     */
    @NonNull
    public List<WatchedRecord> getWatchedHistory() {
        return Collections.unmodifiableList(mWatchedHistory);
    }

    @VisibleForTesting
    WatchedRecord getRecord(int reverseIndex) {
        return mWatchedHistory.get(mWatchedHistory.size() - 1 - reverseIndex);
    }

    @VisibleForTesting
    WatchedRecord getRecordFromSharedPreferences(int reverseIndex) {
        long lastIndex = mSharedPreferences.getLong(PREF_KEY_LAST_INDEX, -1);
        long index = lastIndex - reverseIndex;
        return decode(mSharedPreferences.getString(getSharedPreferencesKey(index), null));
    }

    private String getSharedPreferencesKey(long index) {
        return Long.toString(index % mMaxHistorySize);
    }

    public static class WatchedRecord {
        public final long channelId;
        public final long watchedStartTime;
        public final long duration;

        WatchedRecord(long channelId, long watchedStartTime, long duration) {
            this.channelId = channelId;
            this.watchedStartTime = watchedStartTime;
            this.duration = duration;
        }

        @Override
        public String toString() {
            return "WatchedRecord: id=" + channelId + ",watchedStartTime=" + watchedStartTime
                    + ",duration=" + duration;
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof WatchedRecord) {
                WatchedRecord that = (WatchedRecord) o;
                return Objects.equals(channelId, that.channelId)
                        && Objects.equals(watchedStartTime, that.watchedStartTime)
                        && Objects.equals(duration, that.duration);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return Objects.hash(channelId, watchedStartTime, duration);
        }
    }

    @VisibleForTesting
    String encode(WatchedRecord record) {
        return record.channelId + " " + record.watchedStartTime + " " + record.duration;
    }

    @VisibleForTesting
    WatchedRecord decode(String encodedString) {
        try (Scanner scanner = new Scanner(encodedString)) {
            long channelId = scanner.nextLong();
            long watchedStartTime = scanner.nextLong();
            long duration = scanner.nextLong();
            return new WatchedRecord(channelId, watchedStartTime, duration);
        } catch (Exception e) {
            return null;
        }
    }

    public interface Listener {
        /**
         * Called when history is loaded.
         */
        void onLoadFinished();
        void onNewRecordAdded(WatchedRecord watchedRecord);
    }
}