2 * ownCloud Android client application
4 * @author Tobias Kaminsky
5 * @author David A. Velasco
6 * Copyright (C) 2015 ownCloud Inc.
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 package com
.owncloud
.android
.datamodel
;
25 import java
.io
.InputStream
;
26 import java
.lang
.ref
.WeakReference
;
27 import java
.net
.FileNameMap
;
28 import java
.net
.URLConnection
;
30 import org
.apache
.commons
.httpclient
.HttpStatus
;
31 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
33 import android
.accounts
.Account
;
34 import android
.content
.res
.Resources
;
35 import android
.graphics
.Bitmap
;
36 import android
.graphics
.Bitmap
.CompressFormat
;
37 import android
.graphics
.BitmapFactory
;
38 import android
.graphics
.Canvas
;
39 import android
.graphics
.Paint
;
40 import android
.graphics
.drawable
.BitmapDrawable
;
41 import android
.graphics
.drawable
.Drawable
;
42 import android
.media
.ThumbnailUtils
;
43 import android
.net
.Uri
;
44 import android
.os
.AsyncTask
;
45 import android
.widget
.ImageView
;
47 import com
.owncloud
.android
.MainApp
;
48 import com
.owncloud
.android
.R
;
49 import com
.owncloud
.android
.authentication
.AccountUtils
;
50 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
51 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
52 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
53 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
54 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
55 import com
.owncloud
.android
.ui
.adapter
.DiskLruImageCache
;
56 import com
.owncloud
.android
.utils
.BitmapUtils
;
57 import com
.owncloud
.android
.utils
.DisplayUtils
;
60 * Manager for concurrent access to thumbnails cache.
62 public class ThumbnailsCacheManager
{
64 private static final String TAG
= ThumbnailsCacheManager
.class.getSimpleName();
66 private static final String CACHE_FOLDER
= "thumbnailCache";
68 private static final Object mThumbnailsDiskCacheLock
= new Object();
69 private static DiskLruImageCache mThumbnailCache
= null
;
70 private static boolean mThumbnailCacheStarting
= true
;
72 private static final int DISK_CACHE_SIZE
= 1024 * 1024 * 10; // 10MB
73 private static final CompressFormat mCompressFormat
= CompressFormat
.JPEG
;
74 private static final int mCompressQuality
= 70;
75 private static OwnCloudClient mClient
= null
;
77 public static Bitmap mDefaultImg
=
78 BitmapFactory
.decodeResource(
79 MainApp
.getAppContext().getResources(),
80 DisplayUtils
.getFileTypeIconId("image/png", "default.png")
84 public static class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
87 protected Void
doInBackground(File
... params
) {
88 synchronized (mThumbnailsDiskCacheLock
) {
89 mThumbnailCacheStarting
= true
;
91 if (mThumbnailCache
== null
) {
93 // Check if media is mounted or storage is built-in, if so,
94 // try and use external cache dir; otherwise use internal cache dir
95 final String cachePath
=
96 MainApp
.getAppContext().getExternalCacheDir().getPath() +
97 File
.separator
+ CACHE_FOLDER
;
98 Log_OC
.d(TAG
, "create dir: " + cachePath
);
99 final File diskCacheDir
= new File(cachePath
);
100 mThumbnailCache
= new DiskLruImageCache(
106 } catch (Exception e
) {
107 Log_OC
.d(TAG
, "Thumbnail cache could not be opened ", e
);
108 mThumbnailCache
= null
;
111 mThumbnailCacheStarting
= false
; // Finished initialization
112 mThumbnailsDiskCacheLock
.notifyAll(); // Wake any waiting threads
119 public static void addBitmapToCache(String key
, Bitmap bitmap
) {
120 synchronized (mThumbnailsDiskCacheLock
) {
121 if (mThumbnailCache
!= null
) {
122 mThumbnailCache
.put(key
, bitmap
);
128 public static Bitmap
getBitmapFromDiskCache(String key
) {
129 synchronized (mThumbnailsDiskCacheLock
) {
130 // Wait while disk cache is started from background thread
131 while (mThumbnailCacheStarting
) {
133 mThumbnailsDiskCacheLock
.wait();
134 } catch (InterruptedException e
) {
135 Log_OC
.e(TAG
, "Wait in mThumbnailsDiskCacheLock was interrupted", e
);
138 if (mThumbnailCache
!= null
) {
139 return mThumbnailCache
.getBitmap(key
);
145 public static class ThumbnailGenerationTask
extends AsyncTask
<Object
, Void
, Bitmap
> {
146 private final WeakReference
<ImageView
> mImageViewReference
;
147 private static Account mAccount
;
148 private Object mFile
;
149 private FileDataStorageManager mStorageManager
;
152 public ThumbnailGenerationTask(ImageView imageView
, FileDataStorageManager storageManager
,
154 // Use a WeakReference to ensure the ImageView can be garbage collected
155 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
156 if (storageManager
== null
)
157 throw new IllegalArgumentException("storageManager must not be NULL");
158 mStorageManager
= storageManager
;
162 public ThumbnailGenerationTask(ImageView imageView
) {
163 // Use a WeakReference to ensure the ImageView can be garbage collected
164 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
168 protected Bitmap
doInBackground(Object
... params
) {
169 Bitmap thumbnail
= null
;
172 if (mAccount
!= null
) {
173 OwnCloudAccount ocAccount
= new OwnCloudAccount(mAccount
,
174 MainApp
.getAppContext());
175 mClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
176 getClientFor(ocAccount
, MainApp
.getAppContext());
181 if (mFile
instanceof OCFile
) {
182 thumbnail
= doOCFileInBackground();
184 if (((OCFile
) mFile
).isVideo()){
185 thumbnail
= addVideoOverlay(thumbnail
);
187 } else if (mFile
instanceof File
) {
188 thumbnail
= doFileInBackground();
190 String url
= ((File
) mFile
).getAbsolutePath();
191 FileNameMap fileNameMap
= URLConnection
.getFileNameMap();
192 String mMimeType
= fileNameMap
.getContentTypeFor("file://" + url
);
194 if (mMimeType
!= null
&& mMimeType
.startsWith("video/")){
195 thumbnail
= addVideoOverlay(thumbnail
);
197 //} else { do nothing
201 // the app should never break due to a problem with thumbnails
202 Log_OC
.e(TAG
, "Generation of thumbnail for " + mFile
+ " failed", t
);
203 if (t
instanceof OutOfMemoryError
) {
211 protected void onPostExecute(Bitmap bitmap
){
216 if (bitmap
!= null
) {
217 final ImageView imageView
= mImageViewReference
.get();
218 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
219 if (this == bitmapWorkerTask
) {
221 if (mFile
instanceof OCFile
){
222 tagId
= String
.valueOf(((OCFile
)mFile
).getFileId());
223 } else if (mFile
instanceof File
){
224 tagId
= String
.valueOf(mFile
.hashCode());
226 if (String
.valueOf(imageView
.getTag()).equals(tagId
)) {
227 imageView
.setImageBitmap(bitmap
);
234 * Add thumbnail to cache
235 * @param imageKey: thumb key
236 * @param bitmap: image for extracting thumbnail
237 * @param path: image path
238 * @param px: thumbnail dp
241 private Bitmap
addThumbnailToCache(String imageKey
, Bitmap bitmap
, String path
, int px
){
243 Bitmap thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
245 // Rotate image, obeying exif tag
246 thumbnail
= BitmapUtils
.rotateImage(thumbnail
,path
);
248 // Add thumbnail to cache
249 addBitmapToCache(imageKey
, thumbnail
);
255 * Converts size of file icon from dp to pixel
258 private int getThumbnailDimension(){
259 // Converts dp to pixel
260 Resources r
= MainApp
.getAppContext().getResources();
261 return Math
.round(r
.getDimension(R
.dimen
.file_icon_size_grid
));
264 private Bitmap
doOCFileInBackground() {
265 OCFile file
= (OCFile
)mFile
;
267 final String imageKey
= String
.valueOf(file
.getRemoteId());
269 // Check disk cache in background thread
270 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
272 // Not found in disk cache
273 if (thumbnail
== null
|| file
.needsUpdateThumbnail()) {
275 int px
= getThumbnailDimension();
278 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
279 file
.getStoragePath(), px
, px
);
281 if (bitmap
!= null
) {
282 thumbnail
= addThumbnailToCache(imageKey
, bitmap
, file
.getStoragePath(), px
);
284 file
.setNeedsUpdateThumbnail(false
);
285 mStorageManager
.saveFile(file
);
289 // Download thumbnail from server
290 OwnCloudVersion serverOCVersion
= AccountUtils
.getServerVersion(mAccount
);
291 if (mClient
!= null
&& serverOCVersion
!= null
) {
292 if (serverOCVersion
.supportsRemoteThumbnails()) {
294 String uri
= mClient
.getBaseUri() + "" +
295 "/index.php/apps/files/api/v1/thumbnail/" +
296 px
+ "/" + px
+ Uri
.encode(file
.getRemotePath(), "/");
297 Log_OC
.d("Thumbnail", "URI: " + uri
);
298 GetMethod get
= new GetMethod(uri
);
299 int status
= mClient
.executeMethod(get
);
300 if (status
== HttpStatus
.SC_OK
) {
301 // byte[] bytes = get.getResponseBody();
302 // Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
304 InputStream inputStream
= get
.getResponseBodyAsStream();
305 Bitmap bitmap
= BitmapFactory
.decodeStream(inputStream
);
306 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
308 // Add thumbnail to cache
309 if (thumbnail
!= null
) {
310 addBitmapToCache(imageKey
, thumbnail
);
313 } catch (Exception e
) {
317 Log_OC
.d(TAG
, "Server too old");
327 private Bitmap
doFileInBackground() {
328 File file
= (File
)mFile
;
330 final String imageKey
= String
.valueOf(file
.hashCode());
332 // Check disk cache in background thread
333 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
335 // Not found in disk cache
336 if (thumbnail
== null
) {
338 int px
= getThumbnailDimension();
340 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
341 file
.getAbsolutePath(), px
, px
);
343 if (bitmap
!= null
) {
344 thumbnail
= addThumbnailToCache(imageKey
, bitmap
, file
.getPath(), px
);
352 public static boolean cancelPotentialWork(Object file
, ImageView imageView
) {
353 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
355 if (bitmapWorkerTask
!= null
) {
356 final Object bitmapData
= bitmapWorkerTask
.mFile
;
357 // If bitmapData is not yet set or it differs from the new data
358 if (bitmapData
== null
|| bitmapData
!= file
) {
359 // Cancel previous task
360 bitmapWorkerTask
.cancel(true
);
362 // The same work is already in progress
366 // No task associated with the ImageView, or an existing task was cancelled
370 public static ThumbnailGenerationTask
getBitmapWorkerTask(ImageView imageView
) {
371 if (imageView
!= null
) {
372 final Drawable drawable
= imageView
.getDrawable();
373 if (drawable
instanceof AsyncDrawable
) {
374 final AsyncDrawable asyncDrawable
= (AsyncDrawable
) drawable
;
375 return asyncDrawable
.getBitmapWorkerTask();
381 public static Bitmap
addVideoOverlay(Bitmap thumbnail
){
382 Bitmap bitmap2
= BitmapFactory
.decodeResource(MainApp
.getAppContext().getResources(),
383 R
.drawable
.view_play
);
385 Bitmap resized
= Bitmap
.createScaledBitmap(bitmap2
,
386 (int) (thumbnail
.getWidth() * 0.6),
387 (int) (thumbnail
.getHeight() * 0.6), true
);
389 Bitmap resultBitmap
= Bitmap
.createBitmap(thumbnail
.getWidth(),
390 thumbnail
.getHeight(),
391 Bitmap
.Config
.ARGB_8888
);
393 Canvas c
= new Canvas(resultBitmap
);
395 c
.drawBitmap(thumbnail
, 0, 0, null
);
397 Paint p
= new Paint();
400 c
.drawBitmap(resized
, (thumbnail
.getWidth() - resized
.getWidth()) / 2,
401 (thumbnail
.getHeight() - resized
.getHeight()) / 2, p
);
406 public static class AsyncDrawable
extends BitmapDrawable
{
407 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
409 public AsyncDrawable(
410 Resources res
, Bitmap bitmap
, ThumbnailGenerationTask bitmapWorkerTask
414 bitmapWorkerTaskReference
=
415 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
418 public ThumbnailGenerationTask
getBitmapWorkerTask() {
419 return bitmapWorkerTaskReference
.get();