aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/ruesga/android/wallpapers/photophase/MediaPictureDiscoverer.java
blob: 297bb20a657c4177949af6034fa425b2bd3bc582 (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
/*
 * Copyright (C) 2013 Jorge Ruesga
 *
 * 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.ruesga.android.wallpapers.photophase;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.provider.MediaStore;
import android.util.Log;

import com.ruesga.android.wallpapers.photophase.preferences.PreferencesProvider.Preferences;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * A class that load asynchronously the paths of all media stored in the device.
 * This class only seek at the specified paths
 */
public class MediaPictureDiscoverer {

    private static final String TAG = "MediaPictureDiscoverer";

    private static final boolean DEBUG = false;

    /**
     * An interface that is called when new data is ready.
     */
    public interface OnMediaPictureDiscoveredListener  {
        /**
         * Called when the starting to fetch data
         *
         * @param userRequest If the user requested this media discovery
         */
        void onStartMediaDiscovered(boolean userRequest);
        /**
         * Called when the all the data is ready
         *
         * @param images All the images paths found
         * @param userRequest If the user requested this media discovery
         */
        void onEndMediaDiscovered(File[] images, boolean userRequest);
        /**
         * Called when the partial data is ready
         *
         * @param images All the images paths found
         * @param userRequest If the user requested this media discovery
         */
        void onPartialMediaDiscovered(File[] images, boolean userRequest);
    }

    /**
     * The asynchronous task for query the MediaStore
     */
    private class AsyncDiscoverTask extends AsyncTask<Void, File, List<File>> {

        private final ContentResolver mFinalContentResolver;
        private final OnMediaPictureDiscoveredListener mFinalCallback;
        private final Set<String> mFilter;
        private final Set<String> mLastAlbums;
        private final Set<String> mNewAlbums;
        private final boolean mIsAutoSelectNewAlbums;
        private final boolean mUserRequest;

        /**
         * Constructor of <code>AsyncDiscoverTask</code>
         *
         * @param cr The {@link ContentResolver}
         * @param cb The {@link OnMediaPictureDiscoveredListener} listener
         * @param userRequest If the request was generated by the user
         */
        public AsyncDiscoverTask(
                ContentResolver cr, OnMediaPictureDiscoveredListener cb, boolean userRequest) {
            super();
            mFinalContentResolver = cr;
            mFinalCallback = cb;
            mFilter = Preferences.Media.getSelectedMedia();
            mLastAlbums = Preferences.Media.getLastDiscorevedAlbums();
            mIsAutoSelectNewAlbums = Preferences.Media.isAutoSelectNewAlbums();
            mNewAlbums = new HashSet<String>();
            mUserRequest = userRequest;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        protected List<File> doInBackground(Void...params) {
            try {
                // Start progress
                publishProgress(new File[]{});

                // The columns to read
                final String[] projection = {MediaStore.MediaColumns.DATA};

                // Query external content
                List<File> paths =
                        getPictures(
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                projection,
                                null,
                                null);
                if (DEBUG) {
                    int cc = paths.size();
                    Log.v(TAG, "Pictures found (" + cc + "):");
                    for (int i = 0; i < cc; i++) {
                        Log.v(TAG, "\t" + paths.get(i));
                    }
                }
                return paths;

            } catch (Exception e) {
                Log.e(TAG, "AsyncDiscoverTask failed.", e);

                // Return and empty list
                return new ArrayList<File>();
            } finally {
                // Save the filter (could have new albums)
                Preferences.Media.setSelectedMedia(mContext, mFilter);
                Preferences.Media.setLastDiscorevedAlbums(mContext, mNewAlbums);
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        protected void onProgressUpdate(File... values) {
            if (mFinalCallback != null) {
                if (values == null || values.length == 0) {
                    mFinalCallback.onStartMediaDiscovered(mUserRequest);
                } else {
                    mFinalCallback.onPartialMediaDiscovered(values, mUserRequest);
                }
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        protected void onPostExecute(List<File> result) {
            if (mFinalCallback != null) {
                mFinalCallback.onEndMediaDiscovered(result.toArray(new File[result.size()]), mUserRequest);
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        protected void onCancelled(List<File> result) {
            // Nothing found
            if (mFinalCallback != null) {
                // Overwrite the user request setting. If the task is cancelled then
                // there is no notification to send to the user
                mFinalCallback.onEndMediaDiscovered(new File[]{}, false);
            }
        }

        /**
         * Method that return all the media store pictures for the content uri
         *
         * @param uri The content uri where to search
         * @param projection The field data to return
         * @param where A filter
         * @param args The filter arguments
         * @return List<File> The pictures found
         */
        private List<File> getPictures(
                Uri uri, String[] projection, String where, String[] args) {
            List<File> paths = new ArrayList<File>();
            List<File> partial = new ArrayList<File>();
            Cursor c = mFinalContentResolver.query(uri, projection, where, args, null);
            if (c != null) {
                try {
                    int i = 0;
                    while (c.moveToNext()) {
                        // Only valid files (those i can read)
                        String p = c.getString(0);
                        if (p != null) {
                            File f = new File(p);
                            if (f.isFile() && f.canRead()) {
                                // Catalog the file
                                catalog(f);

                                // Check if is a valid filter
                                if (matchFilter(f)) {
                                    paths.add(f);
                                    partial.add(f);
                                }
                            }
                        }

                        // Publish partial data
                        if (i % 5 == 0 && partial.size() > 0) {
                            publishProgress(partial.toArray(new File[partial.size()]));
                            partial.clear();
                        }
                        i++;
                    }
                } finally {
                    try {
                        c.close();
                    } catch (Exception e) {
                        // Ignore: handle exception
                    }
                }
            }
            return paths;
        }

        /**
         * Method that checks if the picture match the preferences filter
         *
         * @param picture The picture to check
         * @return boolean whether the picture match the filter
         */
        private boolean matchFilter(File picture) {
            Iterator<String> it = mFilter.iterator();
            boolean noFilter = true;
            while (it.hasNext()) {
                noFilter = false;
                File filter = new File(it.next());
                if (filter.isDirectory()) {
                    // Album match
                    if (filter.compareTo(picture.getParentFile()) == 0) {
                        return true;
                    }
                } else {
                    // Picture match
                    if (filter.compareTo(picture) == 0) {
                        return true;
                    }
                }
            }
            return noFilter;
        }

        /**
         * Method that catalog the file (set its album and determine if is a new album)
         *
         * @param f The file to catalog
         */
        private void catalog(File f) {
            File parent = f.getParentFile();
            String albumPath = parent.getAbsolutePath();

            // Add to new albums
            mNewAlbums.add(albumPath);

            // Is a new album?
            if (!mLastAlbums.contains(albumPath)) {
                // Is in the filter?
                if (mIsAutoSelectNewAlbums && !mFilter.contains(albumPath)) {
                    // Add the album to the selected filter
                    mFilter.add(parent.getAbsolutePath());
                }
            }
        }
    }

    /*package*/ final Context mContext;
    private final OnMediaPictureDiscoveredListener mCallback;

    private AsyncDiscoverTask mTask;

    /**
     * Constructor of <code>MediaPictureDiscoverer</code>.
     *
     * @param ctx The current context
     * @param callback A callback to returns the data when it gets ready
     */
    public MediaPictureDiscoverer(Context ctx, OnMediaPictureDiscoveredListener callback) {
        super();
        mContext = ctx;
        mCallback = callback;
    }

    /**
     * Method that request a new reload of the media store picture data.
     *
     * @param userRequest If the request was generated by the user
     */
    public synchronized void discover(boolean userRequest) {
        if (mTask != null && mTask.getStatus().compareTo(Status.FINISHED) != 0 &&
                !mTask.isCancelled()) {
            mTask.cancel(true);
        }
        mTask = new AsyncDiscoverTask(mContext.getContentResolver(), mCallback, userRequest);
        mTask.execute();
    }

    /**
     * Method that destroy the references of this class
     */
    public void recycle() {
        if (mTask != null && !mTask.isCancelled()) {
            mTask.cancel(true);
        }
    }

}