1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 ownCloud Inc.
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.
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.
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/>.
18 package com
.owncloud
.android
.datamodel
;
21 import java
.lang
.ref
.WeakReference
;
23 import org
.apache
.commons
.httpclient
.HttpStatus
;
24 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
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
;
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
;
54 * Manager for concurrent access to thumbnails cache.
56 * @author Tobias Kaminsky
57 * @author David A. Velasco
59 public class ThumbnailsCacheManager
{
61 private static final String TAG
= ThumbnailsCacheManager
.class.getSimpleName();
63 private static final String CACHE_FOLDER
= "thumbnailCache";
64 private static final String MINOR_SERVER_VERSION_FOR_THUMBS
= "7.8.0";
66 private static final Object mThumbnailsDiskCacheLock
= new Object();
67 private static DiskLruImageCache mThumbnailCache
= null
;
68 private static boolean mThumbnailCacheStarting
= true
;
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
;
76 public static Bitmap mDefaultImg
=
77 BitmapFactory
.decodeResource(
78 MainApp
.getAppContext().getResources(),
79 DisplayUtils
.getResourceId("image/png", "default.png")
83 public static class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
86 protected Void
doInBackground(File
... params
) {
87 synchronized (mThumbnailsDiskCacheLock
) {
88 mThumbnailCacheStarting
= true
;
90 if (mThumbnailCache
== null
) {
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(
105 } catch (Exception e
) {
106 Log_OC
.d(TAG
, "Thumbnail cache could not be opened ", e
);
107 mThumbnailCache
= null
;
110 mThumbnailCacheStarting
= false
; // Finished initialization
111 mThumbnailsDiskCacheLock
.notifyAll(); // Wake any waiting threads
118 public static void addBitmapToCache(String key
, Bitmap bitmap
) {
119 synchronized (mThumbnailsDiskCacheLock
) {
120 if (mThumbnailCache
!= null
) {
121 mThumbnailCache
.put(key
, bitmap
);
127 public static Bitmap
getBitmapFromDiskCache(String key
) {
128 synchronized (mThumbnailsDiskCacheLock
) {
129 // Wait while disk cache is started from background thread
130 while (mThumbnailCacheStarting
) {
132 mThumbnailsDiskCacheLock
.wait();
133 } catch (InterruptedException e
) {}
135 if (mThumbnailCache
!= null
) {
136 return (Bitmap
) mThumbnailCache
.getBitmap(key
);
143 public static boolean cancelPotentialWork(OCFile file
, ImageView imageView
) {
144 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
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
);
153 // The same work is already in progress
157 // No task associated with the ImageView, or an existing task was cancelled
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();
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
;
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
;
187 // Decode image in background.
189 protected Bitmap
doInBackground(OCFile
... params
) {
190 Bitmap thumbnail
= null
;
193 if (mAccount
!= null
) {
194 AccountManager accountMgr
= AccountManager
.get(MainApp
.getAppContext());
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());
203 final String imageKey
= String
.valueOf(mFile
.getRemoteId());
205 // Check disk cache in background thread
206 thumbnail
= getBitmapFromDiskCache(imageKey
);
208 // Not found in disk cache
209 if (thumbnail
== null
|| mFile
.needsUpdateThumbnail()) {
210 // Converts dp to pixel
211 Resources r
= MainApp
.getAppContext().getResources();
213 int px
= (int) Math
.round(r
.getDimension(R
.dimen
.file_icon_size
));
216 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
217 mFile
.getStoragePath(), px
, px
);
219 if (bitmap
!= null
) {
220 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
222 // Rotate image, obeying exif tag
223 thumbnail
= BitmapUtils
.rotateImage(thumbnail
, mFile
.getStoragePath());
225 // Add thumbnail to cache
226 addBitmapToCache(imageKey
, thumbnail
);
228 mFile
.setNeedsUpdateThumbnail(false
);
229 mStorageManager
.saveFile(mFile
);
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) {
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
);
250 // Add thumbnail to cache
251 if (thumbnail
!= null
) {
252 addBitmapToCache(imageKey
, thumbnail
);
255 } catch (Exception e
) {
259 Log_OC
.d(TAG
, "Server too old");
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
) {
276 protected void onPostExecute(Bitmap bitmap
){
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
);
295 public static class AsyncDrawable
extends BitmapDrawable
{
296 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
298 public AsyncDrawable(
299 Resources res
, Bitmap bitmap
, ThumbnailGenerationTask bitmapWorkerTask
303 bitmapWorkerTaskReference
=
304 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
307 public ThumbnailGenerationTask
getBitmapWorkerTask() {
308 return bitmapWorkerTaskReference
.get();
314 * Remove from cache the remoteId passed
315 * @param fileRemoteId: remote id of mFile passed
317 public static void removeFileFromCache(String fileRemoteId
){
318 synchronized (mThumbnailsDiskCacheLock
) {
319 if (mThumbnailCache
!= null
) {
320 mThumbnailCache
.removeKey(fileRemoteId
);
322 mThumbnailsDiskCacheLock
.notifyAll(); // Wake any waiting threads