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