Merge pull request #784 from ekeitho/develop
[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.Matrix;
33 import android.graphics.drawable.BitmapDrawable;
34 import android.graphics.drawable.Drawable;
35 import android.media.ExifInterface;
36 import android.media.ThumbnailUtils;
37 import android.net.Uri;
38 import android.os.AsyncTask;
39 import android.widget.ImageView;
40
41 import com.owncloud.android.MainApp;
42 import com.owncloud.android.R;
43 import com.owncloud.android.lib.common.OwnCloudAccount;
44 import com.owncloud.android.lib.common.OwnCloudClient;
45 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
46 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
47 import com.owncloud.android.lib.common.utils.Log_OC;
48 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
49 import com.owncloud.android.ui.adapter.DiskLruImageCache;
50 import com.owncloud.android.utils.BitmapUtils;
51 import com.owncloud.android.utils.DisplayUtils;
52
53 /**
54 * Manager for concurrent access to thumbnails cache.
55 *
56 * @author Tobias Kaminsky
57 * @author David A. Velasco
58 */
59 public class ThumbnailsCacheManager {
60
61 private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
62
63 private static final String CACHE_FOLDER = "thumbnailCache";
64 private static final String MINOR_SERVER_VERSION_FOR_THUMBS = "7.8.0";
65
66 private static final Object mThumbnailsDiskCacheLock = new Object();
67 private static DiskLruImageCache mThumbnailCache = null;
68 private static boolean mThumbnailCacheStarting = true;
69
70 private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
71 private static final CompressFormat mCompressFormat = CompressFormat.JPEG;
72 private static final int mCompressQuality = 70;
73 private static OwnCloudClient mClient = null;
74 private static String mServerVersion = null;
75
76 public static Bitmap mDefaultImg =
77 BitmapFactory.decodeResource(
78 MainApp.getAppContext().getResources(),
79 DisplayUtils.getResourceId("image/png", "default.png")
80 );
81
82
83 public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
84
85 @Override
86 protected Void doInBackground(File... params) {
87 synchronized (mThumbnailsDiskCacheLock) {
88 mThumbnailCacheStarting = true;
89
90 if (mThumbnailCache == null) {
91 try {
92 // Check if media is mounted or storage is built-in, if so,
93 // try and use external cache dir; otherwise use internal cache dir
94 final String cachePath =
95 MainApp.getAppContext().getExternalCacheDir().getPath() +
96 File.separator + CACHE_FOLDER;
97 Log_OC.d(TAG, "create dir: " + cachePath);
98 final File diskCacheDir = new File(cachePath);
99 mThumbnailCache = new DiskLruImageCache(
100 diskCacheDir,
101 DISK_CACHE_SIZE,
102 mCompressFormat,
103 mCompressQuality
104 );
105 } catch (Exception e) {
106 Log_OC.d(TAG, "Thumbnail cache could not be opened ", e);
107 mThumbnailCache = null;
108 }
109 }
110 mThumbnailCacheStarting = false; // Finished initialization
111 mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
112 }
113 return null;
114 }
115 }
116
117
118 public static void addBitmapToCache(String key, Bitmap bitmap) {
119 synchronized (mThumbnailsDiskCacheLock) {
120 if (mThumbnailCache != null) {
121 mThumbnailCache.put(key, bitmap);
122 }
123 }
124 }
125
126
127 public static Bitmap getBitmapFromDiskCache(String key) {
128 synchronized (mThumbnailsDiskCacheLock) {
129 // Wait while disk cache is started from background thread
130 while (mThumbnailCacheStarting) {
131 try {
132 mThumbnailsDiskCacheLock.wait();
133 } catch (InterruptedException e) {}
134 }
135 if (mThumbnailCache != null) {
136 return (Bitmap) mThumbnailCache.getBitmap(key);
137 }
138 }
139 return null;
140 }
141
142
143 public static boolean cancelPotentialWork(OCFile file, ImageView imageView) {
144 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
145
146 if (bitmapWorkerTask != null) {
147 final OCFile bitmapData = bitmapWorkerTask.mFile;
148 // If bitmapData is not yet set or it differs from the new data
149 if (bitmapData == null || bitmapData != file) {
150 // Cancel previous task
151 bitmapWorkerTask.cancel(true);
152 } else {
153 // The same work is already in progress
154 return false;
155 }
156 }
157 // No task associated with the ImageView, or an existing task was cancelled
158 return true;
159 }
160
161 public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
162 if (imageView != null) {
163 final Drawable drawable = imageView.getDrawable();
164 if (drawable instanceof AsyncDrawable) {
165 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
166 return asyncDrawable.getBitmapWorkerTask();
167 }
168 }
169 return null;
170 }
171
172 public static class ThumbnailGenerationTask extends AsyncTask<OCFile, Void, Bitmap> {
173 private final WeakReference<ImageView> mImageViewReference;
174 private static Account mAccount;
175 private OCFile mFile;
176 private FileDataStorageManager mStorageManager;
177
178 public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager, Account account) {
179 // Use a WeakReference to ensure the ImageView can be garbage collected
180 mImageViewReference = new WeakReference<ImageView>(imageView);
181 if (storageManager == null)
182 throw new IllegalArgumentException("storageManager must not be NULL");
183 mStorageManager = storageManager;
184 mAccount = account;
185 }
186
187 // Decode image in background.
188 @Override
189 protected Bitmap doInBackground(OCFile... params) {
190 Bitmap thumbnail = null;
191
192 try {
193 if (mAccount != null) {
194 AccountManager accountMgr = AccountManager.get(MainApp.getAppContext());
195
196 mServerVersion = accountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION);
197 OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, MainApp.getAppContext());
198 mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
199 getClientFor(ocAccount, MainApp.getAppContext());
200 }
201
202 mFile = params[0];
203 final String imageKey = String.valueOf(mFile.getRemoteId());
204
205 // Check disk cache in background thread
206 thumbnail = getBitmapFromDiskCache(imageKey);
207
208 // Not found in disk cache
209 if (thumbnail == null || mFile.needsUpdateThumbnail()) {
210 // Converts dp to pixel
211 Resources r = MainApp.getAppContext().getResources();
212
213 int px = (int) Math.round(r.getDimension(R.dimen.file_icon_size));
214
215 if (mFile.isDown()){
216 Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
217 mFile.getStoragePath(), px, px);
218
219 if (bitmap != null) {
220 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
221
222 // Rotate image, obeying exif tag
223 thumbnail = BitmapUtils.rotateImage(thumbnail, mFile.getStoragePath());
224
225 // Add thumbnail to cache
226 addBitmapToCache(imageKey, thumbnail);
227
228 mFile.setNeedsUpdateThumbnail(false);
229 mStorageManager.saveFile(mFile);
230 }
231
232 } else {
233 // Download thumbnail from server
234 if (mClient != null && mServerVersion != null) {
235 OwnCloudVersion serverOCVersion = new OwnCloudVersion(mServerVersion);
236 if (serverOCVersion.compareTo(new OwnCloudVersion(MINOR_SERVER_VERSION_FOR_THUMBS)) >= 0) {
237 try {
238 int status = -1;
239
240 String uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
241 px + "/" + px + Uri.encode(mFile.getRemotePath(), "/");
242 Log_OC.d("Thumbnail", "URI: " + uri);
243 GetMethod get = new GetMethod(uri);
244 status = mClient.executeMethod(get);
245 if (status == HttpStatus.SC_OK) {
246 byte[] bytes = get.getResponseBody();
247 Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
248 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
249
250 // Add thumbnail to cache
251 if (thumbnail != null) {
252 addBitmapToCache(imageKey, thumbnail);
253 }
254 }
255 } catch (Exception e) {
256 e.printStackTrace();
257 }
258 } else {
259 Log_OC.d(TAG, "Server too old");
260 }
261 }
262 }
263 }
264
265 } catch (Throwable t) {
266 // the app should never break due to a problem with thumbnails
267 Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
268 if (t instanceof OutOfMemoryError) {
269 System.gc();
270 }
271 }
272
273 return thumbnail;
274 }
275
276 protected void onPostExecute(Bitmap bitmap){
277 if (isCancelled()) {
278 bitmap = null;
279 }
280
281 if (mImageViewReference != null && bitmap != null) {
282 final ImageView imageView = mImageViewReference.get();
283 final ThumbnailGenerationTask bitmapWorkerTask =
284 getBitmapWorkerTask(imageView);
285 if (this == bitmapWorkerTask && imageView != null) {
286 if (imageView.getTag().equals(mFile.getFileId())) {
287 imageView.setImageBitmap(bitmap);
288 }
289 }
290 }
291 }
292 }
293
294
295 public static class AsyncDrawable extends BitmapDrawable {
296 private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
297
298 public AsyncDrawable(
299 Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
300 ) {
301
302 super(res, bitmap);
303 bitmapWorkerTaskReference =
304 new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
305 }
306
307 public ThumbnailGenerationTask getBitmapWorkerTask() {
308 return bitmapWorkerTaskReference.get();
309 }
310 }
311
312
313 /**
314 * Remove from cache the remoteId passed
315 * @param fileRemoteId: remote id of mFile passed
316 */
317 public static void removeFileFromCache(String fileRemoteId){
318 synchronized (mThumbnailsDiskCacheLock) {
319 if (mThumbnailCache != null) {
320 mThumbnailCache.removeKey(fileRemoteId);
321 }
322 mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
323 }
324 }
325
326 }