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
.io
.IOException
;
22 import java
.lang
.ref
.WeakReference
;
24 import org
.apache
.commons
.httpclient
.HttpStatus
;
25 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
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
;
44 import com
.owncloud
.android
.MainApp
;
45 import com
.owncloud
.android
.R
;
46 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
47 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
48 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
49 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
50 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
51 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
52 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
53 import com
.owncloud
.android
.ui
.adapter
.DiskLruImageCache
;
54 import com
.owncloud
.android
.utils
.BitmapUtils
;
55 import com
.owncloud
.android
.utils
.DisplayUtils
;
58 * Manager for concurrent access to thumbnails cache.
60 * @author Tobias Kaminsky
61 * @author David A. Velasco
63 public class ThumbnailsCacheManager
{
65 private static final String TAG
= ThumbnailsCacheManager
.class.getSimpleName();
67 private static final String CACHE_FOLDER
= "thumbnailCache";
68 private static final String MINOR_SERVER_VERSION_FOR_THUMBS
= "7.8.0";
70 private static final Object mThumbnailsDiskCacheLock
= new Object();
71 private static DiskLruImageCache mThumbnailCache
= null
;
72 private static boolean mThumbnailCacheStarting
= true
;
74 private static final int DISK_CACHE_SIZE
= 1024 * 1024 * 10; // 10MB
75 private static final CompressFormat mCompressFormat
= CompressFormat
.JPEG
;
76 private static final int mCompressQuality
= 70;
77 private static OwnCloudClient mClient
= null
;
78 private static String mServerVersion
= null
;
80 public static Bitmap mDefaultImg
=
81 BitmapFactory
.decodeResource(
82 MainApp
.getAppContext().getResources(),
83 DisplayUtils
.getResourceId("image/png", "default.png")
87 public static class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
88 private static Context mContext
;
90 public InitDiskCacheTask(Context context
) {
95 protected Void
doInBackground(File
... params
) {
96 synchronized (mThumbnailsDiskCacheLock
) {
97 mThumbnailCacheStarting
= true
;
99 if (mThumbnailCache
== null
) {
101 // Check if media is mounted or storage is built-in, if so,
102 // try and use external cache dir; otherwise use internal cache dir
103 final String cachePath
=
104 MainApp
.getAppContext().getExternalCacheDir().getPath() +
105 File
.separator
+ CACHE_FOLDER
;
106 Log_OC
.d(TAG
, "create dir: " + cachePath
);
107 final File diskCacheDir
= new File(cachePath
);
108 mThumbnailCache
= new DiskLruImageCache(
114 } catch (Exception e
) {
115 Log_OC
.d(TAG
, "Thumbnail cache could not be opened ", e
);
116 mThumbnailCache
= null
;
119 mThumbnailCacheStarting
= false
; // Finished initialization
120 mThumbnailsDiskCacheLock
.notifyAll(); // Wake any waiting threads
127 public static void addBitmapToCache(String key
, Bitmap bitmap
) {
128 synchronized (mThumbnailsDiskCacheLock
) {
129 if (mThumbnailCache
!= null
) {
130 mThumbnailCache
.put(key
, bitmap
);
136 public static Bitmap
getBitmapFromDiskCache(String key
) {
137 synchronized (mThumbnailsDiskCacheLock
) {
138 // Wait while disk cache is started from background thread
139 while (mThumbnailCacheStarting
) {
141 mThumbnailsDiskCacheLock
.wait();
142 } catch (InterruptedException e
) {}
144 if (mThumbnailCache
!= null
) {
145 return (Bitmap
) mThumbnailCache
.getBitmap(key
);
152 public static boolean cancelPotentialWork(OCFile file
, ImageView imageView
) {
153 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
155 if (bitmapWorkerTask
!= null
) {
156 final OCFile bitmapData
= bitmapWorkerTask
.mFile
;
157 // If bitmapData is not yet set or it differs from the new data
158 if (bitmapData
== null
|| bitmapData
!= file
) {
159 // Cancel previous task
160 bitmapWorkerTask
.cancel(true
);
162 // The same work is already in progress
166 // No task associated with the ImageView, or an existing task was cancelled
170 public static ThumbnailGenerationTask
getBitmapWorkerTask(ImageView imageView
) {
171 if (imageView
!= null
) {
172 final Drawable drawable
= imageView
.getDrawable();
173 if (drawable
instanceof AsyncDrawable
) {
174 final AsyncDrawable asyncDrawable
= (AsyncDrawable
) drawable
;
175 return asyncDrawable
.getBitmapWorkerTask();
181 public static class ThumbnailGenerationTask
extends AsyncTask
<OCFile
, Void
, Bitmap
> {
182 private final WeakReference
<ImageView
> mImageViewReference
;
183 private static Account mAccount
;
184 private OCFile mFile
;
185 private FileDataStorageManager mStorageManager
;
187 public ThumbnailGenerationTask(ImageView imageView
, FileDataStorageManager storageManager
, Account account
) {
188 // Use a WeakReference to ensure the ImageView can be garbage collected
189 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
190 if (storageManager
== null
)
191 throw new IllegalArgumentException("storageManager must not be NULL");
192 mStorageManager
= storageManager
;
196 // Decode image in background.
198 protected Bitmap
doInBackground(OCFile
... params
) {
199 Bitmap thumbnail
= null
;
202 if (mAccount
!= null
) {
203 AccountManager accountMgr
= AccountManager
.get(MainApp
.getAppContext());
205 mServerVersion
= accountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
206 OwnCloudAccount ocAccount
= new OwnCloudAccount(mAccount
, MainApp
.getAppContext());
207 mClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().getClientFor(ocAccount
, MainApp
.getAppContext());
211 final String imageKey
= String
.valueOf(mFile
.getRemoteId());
213 // Check disk cache in background thread
214 thumbnail
= getBitmapFromDiskCache(imageKey
);
216 // Not found in disk cache
217 if (thumbnail
== null
|| mFile
.needsUpdateThumbnail()) {
218 // Converts dp to pixel
219 Resources r
= MainApp
.getAppContext().getResources();
221 int px
= (int) Math
.round(r
.getDimension(R
.dimen
.file_icon_size
));
224 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
225 mFile
.getStoragePath(), px
, px
);
227 if (bitmap
!= null
) {
228 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
230 // Add thumbnail to cache
231 addBitmapToCache(imageKey
, thumbnail
);
233 mFile
.setNeedsUpdateThumbnail(false
);
234 mStorageManager
.saveFile(mFile
);
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) {
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
);
255 // Add thumbnail to cache
256 if (thumbnail
!= null
) {
257 addBitmapToCache(imageKey
, thumbnail
);
260 } catch (Exception e
) {
264 Log_OC
.d(TAG
, "Server too old");
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
) {
281 protected void onPostExecute(Bitmap bitmap
){
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
);
300 public static class AsyncDrawable
extends BitmapDrawable
{
301 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
303 public AsyncDrawable(
304 Resources res
, Bitmap bitmap
, ThumbnailGenerationTask bitmapWorkerTask
308 bitmapWorkerTaskReference
=
309 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
312 public ThumbnailGenerationTask
getBitmapWorkerTask() {
313 return bitmapWorkerTaskReference
.get();
319 * Remove from cache the remoteId passed
320 * @param fileRemoteId: remote id of mFile passed
322 public static void removeFileFromCache(String fileRemoteId
){
323 synchronized (mThumbnailsDiskCacheLock
) {
324 if (mThumbnailCache
!= null
) {
325 mThumbnailCache
.removeKey(fileRemoteId
);
327 mThumbnailsDiskCacheLock
.notifyAll(); // Wake any waiting threads