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
.drawable
.BitmapDrawable
;
33 import android
.graphics
.drawable
.Drawable
;
34 import android
.media
.ThumbnailUtils
;
35 import android
.net
.Uri
;
36 import android
.os
.AsyncTask
;
37 import android
.widget
.ImageView
;
39 import com
.owncloud
.android
.MainApp
;
40 import com
.owncloud
.android
.R
;
41 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
42 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
43 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
44 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
45 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
46 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
47 import com
.owncloud
.android
.ui
.adapter
.DiskLruImageCache
;
48 import com
.owncloud
.android
.utils
.BitmapUtils
;
49 import com
.owncloud
.android
.utils
.DisplayUtils
;
52 * Manager for concurrent access to thumbnails cache.
54 * @author Tobias Kaminsky
55 * @author David A. Velasco
57 public class ThumbnailsCacheManager
{
59 private static final String TAG
= ThumbnailsCacheManager
.class.getSimpleName();
61 private static final String CACHE_FOLDER
= "thumbnailCache";
62 private static final String MINOR_SERVER_VERSION_FOR_THUMBS
= "7.8.0";
64 private static final Object mThumbnailsDiskCacheLock
= new Object();
65 private static DiskLruImageCache mThumbnailCache
= null
;
66 private static boolean mThumbnailCacheStarting
= true
;
68 private static final int DISK_CACHE_SIZE
= 1024 * 1024 * 10; // 10MB
69 private static final CompressFormat mCompressFormat
= CompressFormat
.JPEG
;
70 private static final int mCompressQuality
= 70;
71 private static OwnCloudClient mClient
= null
;
72 private static String mServerVersion
= null
;
74 public static Bitmap mDefaultImg
=
75 BitmapFactory
.decodeResource(
76 MainApp
.getAppContext().getResources(),
77 DisplayUtils
.getFileTypeIconId("image/png", "default.png")
81 public static class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
84 protected Void
doInBackground(File
... params
) {
85 synchronized (mThumbnailsDiskCacheLock
) {
86 mThumbnailCacheStarting
= true
;
88 if (mThumbnailCache
== null
) {
90 // Check if media is mounted or storage is built-in, if so,
91 // try and use external cache dir; otherwise use internal cache dir
92 final String cachePath
=
93 MainApp
.getAppContext().getExternalCacheDir().getPath() +
94 File
.separator
+ CACHE_FOLDER
;
95 Log_OC
.d(TAG
, "create dir: " + cachePath
);
96 final File diskCacheDir
= new File(cachePath
);
97 mThumbnailCache
= new DiskLruImageCache(
103 } catch (Exception e
) {
104 Log_OC
.d(TAG
, "Thumbnail cache could not be opened ", e
);
105 mThumbnailCache
= null
;
108 mThumbnailCacheStarting
= false
; // Finished initialization
109 mThumbnailsDiskCacheLock
.notifyAll(); // Wake any waiting threads
116 public static void addBitmapToCache(String key
, Bitmap bitmap
) {
117 synchronized (mThumbnailsDiskCacheLock
) {
118 if (mThumbnailCache
!= null
) {
119 mThumbnailCache
.put(key
, bitmap
);
125 public static Bitmap
getBitmapFromDiskCache(String key
) {
126 synchronized (mThumbnailsDiskCacheLock
) {
127 // Wait while disk cache is started from background thread
128 while (mThumbnailCacheStarting
) {
130 mThumbnailsDiskCacheLock
.wait();
131 } catch (InterruptedException e
) {}
133 if (mThumbnailCache
!= null
) {
134 return (Bitmap
) mThumbnailCache
.getBitmap(key
);
140 public static class ThumbnailGenerationTask
extends AsyncTask
<Object
, Void
, Bitmap
> {
141 private final WeakReference
<ImageView
> mImageViewReference
;
142 private static Account mAccount
;
143 private Object mFile
;
144 private FileDataStorageManager mStorageManager
;
147 public ThumbnailGenerationTask(ImageView imageView
, FileDataStorageManager storageManager
, Account account
) {
148 // Use a WeakReference to ensure the ImageView can be garbage collected
149 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
150 if (storageManager
== null
)
151 throw new IllegalArgumentException("storageManager must not be NULL");
152 mStorageManager
= storageManager
;
156 public ThumbnailGenerationTask(ImageView imageView
) {
157 // Use a WeakReference to ensure the ImageView can be garbage collected
158 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
162 protected Bitmap
doInBackground(Object
... params
) {
163 Bitmap thumbnail
= null
;
166 if (mAccount
!= null
) {
167 AccountManager accountMgr
= AccountManager
.get(MainApp
.getAppContext());
169 mServerVersion
= accountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
170 OwnCloudAccount ocAccount
= new OwnCloudAccount(mAccount
, MainApp
.getAppContext());
171 mClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
172 getClientFor(ocAccount
, MainApp
.getAppContext());
177 if (mFile
instanceof OCFile
) {
178 thumbnail
= doOCFileInBackground();
179 } else if (mFile
instanceof File
) {
180 thumbnail
= doFileInBackground();
186 // the app should never break due to a problem with thumbnails
187 Log_OC
.e(TAG
, "Generation of thumbnail for " + mFile
+ " failed", t
);
188 if (t
instanceof OutOfMemoryError
) {
196 protected void onPostExecute(Bitmap bitmap
){
201 if (mImageViewReference
!= null
&& bitmap
!= null
) {
202 final ImageView imageView
= mImageViewReference
.get();
203 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
204 if (this == bitmapWorkerTask
&& imageView
!= null
) {
206 if (mFile
instanceof OCFile
){
207 tagId
= String
.valueOf(((OCFile
)mFile
).getFileId());
208 } else if (mFile
instanceof File
){
209 tagId
= String
.valueOf(((File
)mFile
).hashCode());
211 if (String
.valueOf(imageView
.getTag()).equals(tagId
)) {
212 imageView
.setImageBitmap(bitmap
);
219 * Add thumbnail to cache
220 * @param imageKey: thumb key
221 * @param bitmap: image for extracting thumbnail
222 * @param path: image path
223 * @param px: thumbnail dp
226 private Bitmap
addThumbnailToCache(String imageKey
, Bitmap bitmap
, String path
, int px
){
228 Bitmap thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
230 // Rotate image, obeying exif tag
231 thumbnail
= BitmapUtils
.rotateImage(thumbnail
,path
);
233 // Add thumbnail to cache
234 addBitmapToCache(imageKey
, thumbnail
);
240 * Converts size of file icon from dp to pixel
243 private int getThumbnailDimension(){
244 // Converts dp to pixel
245 Resources r
= MainApp
.getAppContext().getResources();
246 return (int) Math
.round(r
.getDimension(R
.dimen
.file_icon_size_grid
));
249 private Bitmap
doOCFileInBackground() {
250 Bitmap thumbnail
= null
;
251 OCFile file
= (OCFile
)mFile
;
253 final String imageKey
= String
.valueOf(file
.getRemoteId());
255 // Check disk cache in background thread
256 thumbnail
= getBitmapFromDiskCache(imageKey
);
258 // Not found in disk cache
259 if (thumbnail
== null
|| file
.needsUpdateThumbnail()) {
261 int px
= getThumbnailDimension();
264 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
265 file
.getStoragePath(), px
, px
);
267 if (bitmap
!= null
) {
268 thumbnail
= addThumbnailToCache(imageKey
, bitmap
, file
.getStoragePath(), px
);
270 file
.setNeedsUpdateThumbnail(false
);
271 mStorageManager
.saveFile(file
);
275 // Download thumbnail from server
276 if (mClient
!= null
&& mServerVersion
!= null
) {
277 OwnCloudVersion serverOCVersion
= new OwnCloudVersion(mServerVersion
);
278 if (serverOCVersion
.compareTo(new OwnCloudVersion(MINOR_SERVER_VERSION_FOR_THUMBS
)) >= 0) {
282 String uri
= mClient
.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
283 px
+ "/" + px
+ Uri
.encode(file
.getRemotePath(), "/");
284 Log_OC
.d("Thumbnail", "URI: " + uri
);
285 GetMethod get
= new GetMethod(uri
);
286 status
= mClient
.executeMethod(get
);
287 if (status
== HttpStatus
.SC_OK
) {
288 byte[] bytes
= get
.getResponseBody();
289 Bitmap bitmap
= BitmapFactory
.decodeByteArray(bytes
, 0, bytes
.length
);
290 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
292 // Add thumbnail to cache
293 if (thumbnail
!= null
) {
294 addBitmapToCache(imageKey
, thumbnail
);
297 } catch (Exception e
) {
301 Log_OC
.d(TAG
, "Server too old");
311 private Bitmap
doFileInBackground() {
312 Bitmap thumbnail
= null
;
313 File file
= (File
)mFile
;
315 final String imageKey
= String
.valueOf(file
.hashCode());
317 // Check disk cache in background thread
318 thumbnail
= getBitmapFromDiskCache(imageKey
);
320 // Not found in disk cache
321 if (thumbnail
== null
) {
323 int px
= getThumbnailDimension();
325 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
326 file
.getAbsolutePath(), px
, px
);
328 if (bitmap
!= null
) {
329 thumbnail
= addThumbnailToCache(imageKey
, bitmap
, file
.getPath(), px
);
337 public static boolean cancelPotentialWork(Object file
, ImageView imageView
) {
338 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
340 if (bitmapWorkerTask
!= null
) {
341 final Object bitmapData
= bitmapWorkerTask
.mFile
;
342 // If bitmapData is not yet set or it differs from the new data
343 if (bitmapData
== null
|| bitmapData
!= file
) {
344 // Cancel previous task
345 bitmapWorkerTask
.cancel(true
);
347 // The same work is already in progress
351 // No task associated with the ImageView, or an existing task was cancelled
355 public static ThumbnailGenerationTask
getBitmapWorkerTask(ImageView imageView
) {
356 if (imageView
!= null
) {
357 final Drawable drawable
= imageView
.getDrawable();
358 if (drawable
instanceof AsyncDrawable
) {
359 final AsyncDrawable asyncDrawable
= (AsyncDrawable
) drawable
;
360 return asyncDrawable
.getBitmapWorkerTask();
366 public static class AsyncDrawable
extends BitmapDrawable
{
367 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
369 public AsyncDrawable(
370 Resources res
, Bitmap bitmap
, ThumbnailGenerationTask bitmapWorkerTask
374 bitmapWorkerTaskReference
=
375 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
378 public ThumbnailGenerationTask
getBitmapWorkerTask() {
379 return bitmapWorkerTaskReference
.get();