Merge branch 'release-1.7.2'
[pub/Android/ownCloud.git] / src / com / owncloud / android / datamodel / ThumbnailsCacheManager.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author Tobias Kaminsky
5 * @author David A. Velasco
6 * Copyright (C) 2015 ownCloud Inc.
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
21
22 package com.owncloud.android.datamodel;
23
24 import java.io.File;
25 import java.io.InputStream;
26 import java.lang.ref.WeakReference;
27
28 import org.apache.commons.httpclient.HttpStatus;
29 import org.apache.commons.httpclient.methods.GetMethod;
30
31 import android.accounts.Account;
32 import android.content.res.Resources;
33 import android.graphics.Bitmap;
34 import android.graphics.Bitmap.CompressFormat;
35 import android.graphics.BitmapFactory;
36 import android.graphics.drawable.BitmapDrawable;
37 import android.graphics.drawable.Drawable;
38 import android.media.ThumbnailUtils;
39 import android.net.Uri;
40 import android.os.AsyncTask;
41 import android.widget.ImageView;
42
43 import com.owncloud.android.MainApp;
44 import com.owncloud.android.R;
45 import com.owncloud.android.authentication.AccountUtils;
46 import com.owncloud.android.lib.common.OwnCloudAccount;
47 import com.owncloud.android.lib.common.OwnCloudClient;
48 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
49 import com.owncloud.android.lib.common.utils.Log_OC;
50 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
51 import com.owncloud.android.ui.adapter.DiskLruImageCache;
52 import com.owncloud.android.utils.BitmapUtils;
53 import com.owncloud.android.utils.DisplayUtils;
54
55 /**
56 * Manager for concurrent access to thumbnails cache.
57 */
58 public class ThumbnailsCacheManager {
59
60 private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
61
62 private static final String CACHE_FOLDER = "thumbnailCache";
63
64 private static final Object mThumbnailsDiskCacheLock = new Object();
65 private static DiskLruImageCache mThumbnailCache = null;
66 private static boolean mThumbnailCacheStarting = true;
67
68 private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
69 private static final CompressFormat mCompressFormat = CompressFormat.JPEG;
70 private static final int mCompressQuality = 70;
71 private static OwnCloudClient mClient = null;
72
73 public static Bitmap mDefaultImg =
74 BitmapFactory.decodeResource(
75 MainApp.getAppContext().getResources(),
76 DisplayUtils.getFileTypeIconId("image/png", "default.png")
77 );
78
79
80 public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
81
82 @Override
83 protected Void doInBackground(File... params) {
84 synchronized (mThumbnailsDiskCacheLock) {
85 mThumbnailCacheStarting = true;
86
87 if (mThumbnailCache == null) {
88 try {
89 // Check if media is mounted or storage is built-in, if so,
90 // try and use external cache dir; otherwise use internal cache dir
91 final String cachePath =
92 MainApp.getAppContext().getExternalCacheDir().getPath() +
93 File.separator + CACHE_FOLDER;
94 Log_OC.d(TAG, "create dir: " + cachePath);
95 final File diskCacheDir = new File(cachePath);
96 mThumbnailCache = new DiskLruImageCache(
97 diskCacheDir,
98 DISK_CACHE_SIZE,
99 mCompressFormat,
100 mCompressQuality
101 );
102 } catch (Exception e) {
103 Log_OC.d(TAG, "Thumbnail cache could not be opened ", e);
104 mThumbnailCache = null;
105 }
106 }
107 mThumbnailCacheStarting = false; // Finished initialization
108 mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
109 }
110 return null;
111 }
112 }
113
114
115 public static void addBitmapToCache(String key, Bitmap bitmap) {
116 synchronized (mThumbnailsDiskCacheLock) {
117 if (mThumbnailCache != null) {
118 mThumbnailCache.put(key, bitmap);
119 }
120 }
121 }
122
123
124 public static Bitmap getBitmapFromDiskCache(String key) {
125 synchronized (mThumbnailsDiskCacheLock) {
126 // Wait while disk cache is started from background thread
127 while (mThumbnailCacheStarting) {
128 try {
129 mThumbnailsDiskCacheLock.wait();
130 } catch (InterruptedException e) {
131 Log_OC.e(TAG, "Wait in mThumbnailsDiskCacheLock was interrupted", e);
132 }
133 }
134 if (mThumbnailCache != null) {
135 return mThumbnailCache.getBitmap(key);
136 }
137 }
138 return null;
139 }
140
141 public static class ThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
142 private final WeakReference<ImageView> mImageViewReference;
143 private static Account mAccount;
144 private Object mFile;
145 private FileDataStorageManager mStorageManager;
146
147
148 public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager,
149 Account account) {
150 // Use a WeakReference to ensure the ImageView can be garbage collected
151 mImageViewReference = new WeakReference<ImageView>(imageView);
152 if (storageManager == null)
153 throw new IllegalArgumentException("storageManager must not be NULL");
154 mStorageManager = storageManager;
155 mAccount = account;
156 }
157
158 public ThumbnailGenerationTask(ImageView imageView) {
159 // Use a WeakReference to ensure the ImageView can be garbage collected
160 mImageViewReference = new WeakReference<ImageView>(imageView);
161 }
162
163 @Override
164 protected Bitmap doInBackground(Object... params) {
165 Bitmap thumbnail = null;
166
167 try {
168 if (mAccount != null) {
169 OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount,
170 MainApp.getAppContext());
171 mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
172 getClientFor(ocAccount, MainApp.getAppContext());
173 }
174
175 mFile = params[0];
176
177 if (mFile instanceof OCFile) {
178 thumbnail = doOCFileInBackground();
179 } else if (mFile instanceof File) {
180 thumbnail = doFileInBackground();
181 //} else { do nothing
182 }
183
184 }catch(Throwable t){
185 // the app should never break due to a problem with thumbnails
186 Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
187 if (t instanceof OutOfMemoryError) {
188 System.gc();
189 }
190 }
191
192 return thumbnail;
193 }
194
195 protected void onPostExecute(Bitmap bitmap){
196 if (isCancelled()) {
197 bitmap = null;
198 }
199
200 if (bitmap != null) {
201 final ImageView imageView = mImageViewReference.get();
202 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
203 if (this == bitmapWorkerTask) {
204 String tagId = "";
205 if (mFile instanceof OCFile){
206 tagId = String.valueOf(((OCFile)mFile).getFileId());
207 } else if (mFile instanceof File){
208 tagId = String.valueOf(mFile.hashCode());
209 }
210 if (String.valueOf(imageView.getTag()).equals(tagId)) {
211 imageView.setImageBitmap(bitmap);
212 }
213 }
214 }
215 }
216
217 /**
218 * Add thumbnail to cache
219 * @param imageKey: thumb key
220 * @param bitmap: image for extracting thumbnail
221 * @param path: image path
222 * @param px: thumbnail dp
223 * @return Bitmap
224 */
225 private Bitmap addThumbnailToCache(String imageKey, Bitmap bitmap, String path, int px){
226
227 Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
228
229 // Rotate image, obeying exif tag
230 thumbnail = BitmapUtils.rotateImage(thumbnail,path);
231
232 // Add thumbnail to cache
233 addBitmapToCache(imageKey, thumbnail);
234
235 return thumbnail;
236 }
237
238 /**
239 * Converts size of file icon from dp to pixel
240 * @return int
241 */
242 private int getThumbnailDimension(){
243 // Converts dp to pixel
244 Resources r = MainApp.getAppContext().getResources();
245 return Math.round(r.getDimension(R.dimen.file_icon_size_grid));
246 }
247
248 private Bitmap doOCFileInBackground() {
249 OCFile file = (OCFile)mFile;
250
251 final String imageKey = String.valueOf(file.getRemoteId());
252
253 // Check disk cache in background thread
254 Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
255
256 // Not found in disk cache
257 if (thumbnail == null || file.needsUpdateThumbnail()) {
258
259 int px = getThumbnailDimension();
260
261 if (file.isDown()) {
262 Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
263 file.getStoragePath(), px, px);
264
265 if (bitmap != null) {
266 thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), px);
267
268 file.setNeedsUpdateThumbnail(false);
269 mStorageManager.saveFile(file);
270 }
271
272 } else {
273 // Download thumbnail from server
274 OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
275 if (mClient != null && serverOCVersion != null) {
276 if (serverOCVersion.supportsRemoteThumbnails()) {
277 try {
278 String uri = mClient.getBaseUri() + "" +
279 "/index.php/apps/files/api/v1/thumbnail/" +
280 px + "/" + px + Uri.encode(file.getRemotePath(), "/");
281 Log_OC.d("Thumbnail", "URI: " + uri);
282 GetMethod get = new GetMethod(uri);
283 int status = mClient.executeMethod(get);
284 if (status == HttpStatus.SC_OK) {
285 // byte[] bytes = get.getResponseBody();
286 // Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
287 // bytes.length);
288 InputStream inputStream = get.getResponseBodyAsStream();
289 Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
290 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
291
292 // Add thumbnail to cache
293 if (thumbnail != null) {
294 addBitmapToCache(imageKey, thumbnail);
295 }
296 }
297 } catch (Exception e) {
298 e.printStackTrace();
299 }
300 } else {
301 Log_OC.d(TAG, "Server too old");
302 }
303 }
304 }
305 }
306
307 return thumbnail;
308
309 }
310
311 private Bitmap doFileInBackground() {
312 File file = (File)mFile;
313
314 final String imageKey = String.valueOf(file.hashCode());
315
316 // Check disk cache in background thread
317 Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
318
319 // Not found in disk cache
320 if (thumbnail == null) {
321
322 int px = getThumbnailDimension();
323
324 Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
325 file.getAbsolutePath(), px, px);
326
327 if (bitmap != null) {
328 thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), px);
329 }
330 }
331 return thumbnail;
332 }
333
334 }
335
336 public static boolean cancelPotentialWork(Object file, ImageView imageView) {
337 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
338
339 if (bitmapWorkerTask != null) {
340 final Object bitmapData = bitmapWorkerTask.mFile;
341 // If bitmapData is not yet set or it differs from the new data
342 if (bitmapData == null || bitmapData != file) {
343 // Cancel previous task
344 bitmapWorkerTask.cancel(true);
345 } else {
346 // The same work is already in progress
347 return false;
348 }
349 }
350 // No task associated with the ImageView, or an existing task was cancelled
351 return true;
352 }
353
354 public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
355 if (imageView != null) {
356 final Drawable drawable = imageView.getDrawable();
357 if (drawable instanceof AsyncDrawable) {
358 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
359 return asyncDrawable.getBitmapWorkerTask();
360 }
361 }
362 return null;
363 }
364
365 public static class AsyncDrawable extends BitmapDrawable {
366 private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
367
368 public AsyncDrawable(
369 Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
370 ) {
371
372 super(res, bitmap);
373 bitmapWorkerTaskReference =
374 new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
375 }
376
377 public ThumbnailGenerationTask getBitmapWorkerTask() {
378 return bitmapWorkerTaskReference.get();
379 }
380 }
381 }