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
);
142 public interface AsyncTaskFile
{
143 public String
getId();
144 public String
getTagId();
145 public String
getPath();
146 public String
getRemotePath();
147 public boolean getNeedsUpdateThumbnail();
148 public void setNeedsUpdateThumbnail(boolean needsUpdate
);
149 public boolean getIsDown();
150 public Object
getFile();
154 public static class AsyncTaskFileLocal
implements AsyncTaskFile
{
157 private boolean mNeedsUpdate
;
159 public AsyncTaskFileLocal(File file
){
161 mNeedsUpdate
= false
;
165 public String
getId() {
166 return String
.valueOf(mFile
.hashCode());
170 public String
getTagId() {
171 return String
.valueOf(mFile
.hashCode());
175 public String
getPath() {
176 return mFile
.getAbsolutePath();
180 public String
getRemotePath() {
185 public boolean getNeedsUpdateThumbnail() {
190 public void setNeedsUpdateThumbnail(boolean needsUpdate
) {
191 mNeedsUpdate
= needsUpdate
;
195 public boolean getIsDown() {
200 public Object
getFile() {
205 public static class AsyncTaskOCFile
implements AsyncTaskFile
{
207 private OCFile mFile
;
209 public AsyncTaskOCFile(OCFile file
){
214 public String
getId() {
215 return mFile
.getRemoteId();
219 public String
getTagId() {
220 return String
.valueOf(mFile
.getFileId());
224 public String
getPath() {
225 return mFile
.getStoragePath();
229 public String
getRemotePath() {
230 return mFile
.getRemotePath();
234 public boolean getNeedsUpdateThumbnail() {
235 return mFile
.needsUpdateThumbnail();
239 public void setNeedsUpdateThumbnail(boolean needsUpdate
) {
240 mFile
.setNeedsUpdateThumbnail(needsUpdate
);
244 public boolean getIsDown() {
245 return mFile
.isDown();
249 public Object
getFile() {
254 public static class ThumbnailGenerationGlobalTask
extends AsyncTask
<AsyncTaskFile
, Void
, Bitmap
> {
255 private final WeakReference
<ImageView
> mImageViewReference
;
256 private static Account mAccount
;
257 private AsyncTaskFile mFile
;
258 private FileDataStorageManager mStorageManager
;
261 public ThumbnailGenerationGlobalTask(ImageView imageView
, FileDataStorageManager storageManager
, Account account
) {
262 // Use a WeakReference to ensure the ImageView can be garbage collected
263 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
264 if (storageManager
== null
)
265 throw new IllegalArgumentException("storageManager must not be NULL");
266 mStorageManager
= storageManager
;
270 public ThumbnailGenerationGlobalTask(ImageView imageView
) {
271 // Use a WeakReference to ensure the ImageView can be garbage collected
272 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
276 protected Bitmap
doInBackground(AsyncTaskFile
... params
) {
277 Bitmap thumbnail
= null
;
280 if (mAccount
!= null
) {
281 AccountManager accountMgr
= AccountManager
.get(MainApp
.getAppContext());
283 mServerVersion
= accountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
284 OwnCloudAccount ocAccount
= new OwnCloudAccount(mAccount
, MainApp
.getAppContext());
285 mClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
286 getClientFor(ocAccount
, MainApp
.getAppContext());
291 final String imageKey
= String
.valueOf(mFile
.getId());
293 // Check disk cache in background thread
294 thumbnail
= getBitmapFromDiskCache(imageKey
);
296 if (mFile
instanceof AsyncTaskOCFile
) {
298 // Not found in disk cache
299 if (thumbnail
== null
|| mFile
.getNeedsUpdateThumbnail()) {
300 // Converts dp to pixel
301 Resources r
= MainApp
.getAppContext().getResources();
303 int px
= (int) Math
.round(r
.getDimension(R
.dimen
.file_icon_size
));
305 if (mFile
.getIsDown()) {
306 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
307 mFile
.getPath(), px
, px
);
309 if (bitmap
!= null
) {
310 thumbnail
= addThumbnailToCache(imageKey
, bitmap
, mFile
.getPath(), px
);
312 mFile
.setNeedsUpdateThumbnail(false
);
313 mStorageManager
.saveFile((OCFile
) mFile
.getFile());
317 // Download thumbnail from server
318 if (mClient
!= null
&& mServerVersion
!= null
) {
319 OwnCloudVersion serverOCVersion
= new OwnCloudVersion(mServerVersion
);
320 if (serverOCVersion
.compareTo(new OwnCloudVersion(MINOR_SERVER_VERSION_FOR_THUMBS
)) >= 0) {
324 String uri
= mClient
.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
325 px
+ "/" + px
+ Uri
.encode(mFile
.getRemotePath(), "/");
326 Log_OC
.d("Thumbnail", "URI: " + uri
);
327 GetMethod get
= new GetMethod(uri
);
328 status
= mClient
.executeMethod(get
);
329 if (status
== HttpStatus
.SC_OK
) {
330 byte[] bytes
= get
.getResponseBody();
331 Bitmap bitmap
= BitmapFactory
.decodeByteArray(bytes
, 0, bytes
.length
);
332 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
334 // Add thumbnail to cache
335 if (thumbnail
!= null
) {
336 addBitmapToCache(imageKey
, thumbnail
);
339 } catch (Exception e
) {
343 Log_OC
.d(TAG
, "Server too old");
348 } else if (mFile
instanceof AsyncTaskFileLocal
) {
350 // Not found in disk cache
351 if (thumbnail
== null
) {
352 // Converts dp to pixel
353 Resources r
= MainApp
.getAppContext().getResources();
355 int px
= (int) Math
.round(r
.getDimension(R
.dimen
.file_icon_size
));
357 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
358 mFile
.getPath(), px
, px
);
360 if (bitmap
!= null
) {
361 thumbnail
= addThumbnailToCache(imageKey
, bitmap
, mFile
.getPath(), px
);
368 // the app should never break due to a problem with thumbnails
369 Log_OC
.e(TAG
, "Generation of thumbnail for " + mFile
+ " failed", t
);
370 if (t
instanceof OutOfMemoryError
) {
379 protected void onPostExecute(Bitmap bitmap
){
384 if (mImageViewReference
!= null
&& bitmap
!= null
) {
385 final ImageView imageView
= mImageViewReference
.get();
386 final ThumbnailGenerationGlobalTask bitmapWorkerTask
= getBitmapGlobalWorkerTask(imageView
);
387 if (this == bitmapWorkerTask
&& imageView
!= null
) {
388 if (String
.valueOf(imageView
.getTag()).equals(mFile
.getTagId())) {
389 imageView
.setImageBitmap(bitmap
);
395 private Bitmap
addThumbnailToCache(String imageKey
, Bitmap bitmap
, String path
, int px
){
397 Bitmap thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
399 // Rotate image, obeying exif tag
400 thumbnail
= BitmapUtils
.rotateImage(thumbnail
,path
);
402 // Add thumbnail to cache
403 addBitmapToCache(imageKey
, thumbnail
);
410 public static boolean cancelPotentialGlobalWork(AsyncTaskFile file
, ImageView imageView
) {
411 final ThumbnailGenerationGlobalTask bitmapWorkerTask
= getBitmapGlobalWorkerTask(imageView
);
413 if (bitmapWorkerTask
!= null
) {
414 final AsyncTaskFile bitmapData
= bitmapWorkerTask
.mFile
;
415 // If bitmapData is not yet set or it differs from the new data
416 if (bitmapData
== null
|| bitmapData
!= file
) {
417 // Cancel previous task
418 bitmapWorkerTask
.cancel(true
);
420 // The same work is already in progress
424 // No task associated with the ImageView, or an existing task was cancelled
428 public static ThumbnailGenerationGlobalTask
getBitmapGlobalWorkerTask(ImageView imageView
) {
429 if (imageView
!= null
) {
430 final Drawable drawable
= imageView
.getDrawable();
431 if (drawable
instanceof AsyncGlobalDrawable
) {
432 final AsyncGlobalDrawable asyncDrawable
= (AsyncGlobalDrawable
) drawable
;
433 return asyncDrawable
.getBitmapWorkerTask();
439 public static class AsyncGlobalDrawable
extends BitmapDrawable
{
440 private final WeakReference
<ThumbnailGenerationGlobalTask
> bitmapWorkerTaskReference
;
442 public AsyncGlobalDrawable(
443 Resources res
, Bitmap bitmap
, ThumbnailGenerationGlobalTask bitmapWorkerTask
447 bitmapWorkerTaskReference
=
448 new WeakReference
<ThumbnailGenerationGlobalTask
>(bitmapWorkerTask
);
451 public ThumbnailGenerationGlobalTask
getBitmapWorkerTask() {
452 return bitmapWorkerTaskReference
.get();