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