summaryrefslogtreecommitdiff
path: root/java/com/android/pump/db/VideoStore.java
blob: 657c0c112d8f7e332774ba0e5edb6ee5bade0a8e (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
/*
 * Copyright 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.pump.db;

import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;

import com.android.pump.provider.Query;
import com.android.pump.util.Clog;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

@WorkerThread
class VideoStore extends ContentObserver {
    private static final String TAG = Clog.tag(VideoStore.class);

    // TODO Replace the following with MediaStore.Video.Media.RELATIVE_PATH throughout the code.
    private static final String RELATIVE_PATH = "relative_path";

    // TODO Replace with Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q throughout the code.
    private static boolean isRunningQ() {
        return Build.VERSION.SDK_INT > Build.VERSION_CODES.P
                || (Build.VERSION.SDK_INT == Build.VERSION_CODES.P
                && Build.VERSION.PREVIEW_SDK_INT > 0);
    }

    private final ContentResolver mContentResolver;
    private final ChangeListener mChangeListener;
    private final MediaProvider mMediaProvider;

    interface ChangeListener {
        void onMoviesAdded(@NonNull Collection<Movie> movies);
        void onSeriesAdded(@NonNull Collection<Series> series);
        void onEpisodesAdded(@NonNull Collection<Episode> episodes);
        void onOthersAdded(@NonNull Collection<Other> others);
    }

    @AnyThread
    VideoStore(@NonNull ContentResolver contentResolver, @NonNull ChangeListener changeListener,
            @NonNull MediaProvider mediaProvider) {
        super(null);

        Clog.i(TAG, "VideoStore(" + contentResolver + ", " + changeListener
                + ", " + mediaProvider + ")");
        mContentResolver = contentResolver;
        mChangeListener = changeListener;
        mMediaProvider = mediaProvider;

        // TODO(b/123706961) Do we need content observer for other content uris? (E.g. thumbnail)
        mContentResolver.registerContentObserver(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                true, this);

        // TODO(b/123706961) When to call unregisterContentObserver?
        // mContentResolver.unregisterContentObserver(this);
    }

    void load() {
        Clog.i(TAG, "load()");
        Collection<Movie> movies = new ArrayList<>();
        Collection<Series> series = new ArrayList<>();
        Collection<Episode> episodes = new ArrayList<>();
        Collection<Other> others = new ArrayList<>();

        /* TODO get via count instead?
                Cursor countCursor = mContentResolver.query(CONTENT_URI,
                new String[] { "count(*) AS count" },
                null,
                null,
                null);
        countCursor.moveToFirst();
        int count = countCursor.getInt(0);
        Clog.i(TAG, "count = " + count);
        countCursor.close();
        */

        {
            Uri contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            String[] projection;
            if (isRunningQ()) {
                projection = new String[] {
                    MediaStore.Video.Media._ID,
                    MediaStore.Video.Media.MIME_TYPE,
                    RELATIVE_PATH,
                    MediaStore.Video.Media.DISPLAY_NAME
                };
            } else {
                projection = new String[] {
                    MediaStore.Video.Media._ID,
                    MediaStore.Video.Media.MIME_TYPE,
                    MediaStore.Video.Media.DATA
                };
            }
            String sortOrder = MediaStore.Video.Media._ID;
            Cursor cursor = mContentResolver.query(contentUri, projection, null, null, sortOrder);
            if (cursor != null) {
                try {
                    int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
                    int dataColumn;
                    int relativePathColumn;
                    int displayNameColumn;
                    int mimeTypeColumn = cursor.getColumnIndexOrThrow(
                            MediaStore.Video.Media.MIME_TYPE);

                    if (isRunningQ()) {
                        dataColumn = -1;
                        relativePathColumn = cursor.getColumnIndexOrThrow(RELATIVE_PATH);
                        displayNameColumn = cursor.getColumnIndexOrThrow(
                                MediaStore.Video.Media.DISPLAY_NAME);
                    } else {
                        dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                        relativePathColumn = -1;
                        displayNameColumn = -1;
                    }

                    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                        long id = cursor.getLong(idColumn);
                        String mimeType = cursor.getString(mimeTypeColumn);

                        File file;
                        if (isRunningQ()) {
                            String relativePath = cursor.getString(relativePathColumn);
                            String displayName = cursor.getString(displayNameColumn);
                            file = new File(relativePath, displayName);
                        } else {
                            String data = cursor.getString(dataColumn);
                            file = new File(data);
                        }
                        Query query = Query.parse(Uri.fromFile(file));
                        if (query.isMovie()) {
                            Movie movie;
                            if (query.hasYear()) {
                                movie = new Movie(id, mimeType, query.getName(), query.getYear());
                            } else {
                                movie = new Movie(id, mimeType, query.getName());
                            }
                            movies.add(movie);
                        } else if (query.isEpisode()) {
                            Series serie = null;
                            for (Series s : series) {
                                if (s.getTitle().equals(query.getName())
                                        && s.hasYear() == query.hasYear()
                                        && (!s.hasYear() || s.getYear() == query.getYear())) {
                                    serie = s;
                                    break;
                                }
                            }
                            if (serie == null) {
                                if (query.hasYear()) {
                                    serie = new Series(query.getName(), query.getYear());
                                } else {
                                    serie = new Series(query.getName());
                                }
                                series.add(serie);
                            }

                            Episode episode = new Episode(id, mimeType, serie,
                                    query.getSeason(), query.getEpisode());
                            episodes.add(episode);

                            serie.addEpisode(episode);
                        } else {
                            Other other = new Other(id, mimeType, query.getName());
                            others.add(other);
                        }
                    }
                } finally {
                    cursor.close();
                }
            }
        }

        mChangeListener.onMoviesAdded(movies);
        mChangeListener.onSeriesAdded(series);
        mChangeListener.onEpisodesAdded(episodes);
        mChangeListener.onOthersAdded(others);
    }

    boolean loadData(@NonNull Movie movie) {
        Uri thumbnailUri = getThumbnailUri(movie.getId());
        if (thumbnailUri != null) {
            return movie.setThumbnailUri(thumbnailUri);
        }
        return false;
    }

    boolean loadData(@NonNull Series series) {
        return false;
    }

    boolean loadData(@NonNull Episode episode) {
        Uri thumbnailUri = getThumbnailUri(episode.getId());
        if (thumbnailUri != null) {
            return episode.setThumbnailUri(thumbnailUri);
        }
        return false;
    }

    boolean loadData(@NonNull Other other) {
        boolean updated = false;

        Uri contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {
            MediaStore.Video.Media.TITLE,
            MediaStore.Video.Media.DURATION,
            MediaStore.Video.Media.DATE_TAKEN,
            MediaStore.Video.Media.LATITUDE,
            MediaStore.Video.Media.LONGITUDE
        };
        String selection = MediaStore.Video.Media._ID + " = ?";
        String[] selectionArgs = { Long.toString(other.getId()) };
        Cursor cursor = mContentResolver.query(
                contentUri, projection, selection, selectionArgs, null);
        if (cursor != null) {
            try {
                int titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE);
                int durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
                int dateTakenColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_TAKEN);
                int latitudeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.LATITUDE);
                int longitudeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.LONGITUDE);

                if (cursor.moveToFirst()) {
                    if (!cursor.isNull(titleColumn)) {
                        String title = cursor.getString(titleColumn);
                        updated |= other.setTitle(title);
                    }
                    if (!cursor.isNull(durationColumn)) {
                        long duration = cursor.getLong(durationColumn);
                        updated |= other.setDuration(duration);
                    }
                    if (!cursor.isNull(dateTakenColumn)) {
                        long dateTaken = cursor.getLong(dateTakenColumn);
                        updated |= other.setDateTaken(dateTaken);
                    }
                    if (!cursor.isNull(latitudeColumn) && !cursor.isNull(longitudeColumn)) {
                        double latitude = cursor.getDouble(latitudeColumn);
                        double longitude = cursor.getDouble(longitudeColumn);
                        updated |= other.setLatLong(latitude, longitude);
                    }
                }
            } finally {
                cursor.close();
            }
        }

        Uri thumbnailUri = getThumbnailUri(other.getId());
        if (thumbnailUri != null) {
            updated |= other.setThumbnailUri(thumbnailUri);
        }

        return updated;
    }

    private @Nullable Uri getThumbnailUri(long id) {
        int thumbKind = MediaStore.Video.Thumbnails.MINI_KIND;

        // TODO(b/123707512) The following line is required to generate thumbnails -- is there a better way?
        MediaStore.Video.Thumbnails.getThumbnail(mContentResolver, id, thumbKind, null);

        Uri thumbnailUri = null;
        Uri contentUri = MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI;
        String[] projection = {
            MediaStore.Video.Thumbnails.DATA
        };
        String selection = MediaStore.Video.Thumbnails.KIND + " = " + thumbKind + " AND " +
                MediaStore.Video.Thumbnails.VIDEO_ID + " = ?";
        String[] selectionArgs = { Long.toString(id) };
        Cursor cursor = mContentResolver.query(
                contentUri, projection, selection, selectionArgs, null);
        if (cursor != null) {
            try {
                int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);

                if (cursor.moveToFirst()) {
                    String data = cursor.getString(dataColumn);

                    thumbnailUri = Uri.fromFile(new File(data));
                }
            } finally {
                cursor.close();
            }
        }
        return thumbnailUri;
    }

    @Override
    public void onChange(boolean selfChange) {
        Clog.i(TAG, "onChange(" + selfChange + ")");
        onChange(selfChange, null);
    }

    @Override
    public void onChange(boolean selfChange, @Nullable Uri uri) {
        Clog.i(TAG, "onChange(" + selfChange + ", " + uri + ")");
        // TODO(b/123706961) Figure out what changed
        // onChange(false, content://media)
        // onChange(false, content://media/external)
        // onChange(false, content://media/external/audio/media/444)
        // onChange(false, content://media/external/video/media/328?blocking=1&orig_id=328&group_id=0)

        // TODO(b/123706961) Notify listener about changes
        // mChangeListener.xxx();
    }
}