ThumbnailsCacheManager.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Tobias Kaminsky
  5. * @author David A. Velasco
  6. * Copyright (C) 2015 ownCloud Inc.
  7. *
  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.
  11. *
  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.
  16. *
  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/>.
  19. *
  20. */
  21. package com.owncloud.android.datamodel;
  22. import java.io.File;
  23. import java.io.InputStream;
  24. import java.lang.ref.WeakReference;
  25. import java.net.FileNameMap;
  26. import java.net.URLConnection;
  27. import org.apache.commons.httpclient.HttpStatus;
  28. import org.apache.commons.httpclient.methods.GetMethod;
  29. import android.accounts.Account;
  30. import android.content.res.Resources;
  31. import android.graphics.Bitmap;
  32. import android.graphics.Bitmap.CompressFormat;
  33. import android.graphics.BitmapFactory;
  34. import android.graphics.Canvas;
  35. import android.graphics.Paint;
  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.widget.ImageView;
  42. import com.owncloud.android.MainApp;
  43. import com.owncloud.android.R;
  44. import com.owncloud.android.authentication.AccountUtils;
  45. import com.owncloud.android.lib.common.OwnCloudAccount;
  46. import com.owncloud.android.lib.common.OwnCloudClient;
  47. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  48. import com.owncloud.android.lib.common.utils.Log_OC;
  49. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  50. import com.owncloud.android.ui.adapter.DiskLruImageCache;
  51. import com.owncloud.android.utils.BitmapUtils;
  52. import com.owncloud.android.utils.DisplayUtils;
  53. /**
  54. * Manager for concurrent access to thumbnails cache.
  55. */
  56. public class ThumbnailsCacheManager {
  57. private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
  58. private static final String CACHE_FOLDER = "thumbnailCache";
  59. private static final Object mThumbnailsDiskCacheLock = new Object();
  60. private static DiskLruImageCache mThumbnailCache = null;
  61. private static boolean mThumbnailCacheStarting = true;
  62. private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
  63. private static final CompressFormat mCompressFormat = CompressFormat.JPEG;
  64. private static final int mCompressQuality = 70;
  65. private static OwnCloudClient mClient = null;
  66. public static Bitmap mDefaultImg =
  67. BitmapFactory.decodeResource(
  68. MainApp.getAppContext().getResources(),
  69. DisplayUtils.getFileTypeIconId("image/png", "default.png")
  70. );
  71. public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
  72. @Override
  73. protected Void doInBackground(File... params) {
  74. synchronized (mThumbnailsDiskCacheLock) {
  75. mThumbnailCacheStarting = true;
  76. if (mThumbnailCache == null) {
  77. try {
  78. // Check if media is mounted or storage is built-in, if so,
  79. // try and use external cache dir; otherwise use internal cache dir
  80. final String cachePath =
  81. MainApp.getAppContext().getExternalCacheDir().getPath() +
  82. File.separator + CACHE_FOLDER;
  83. Log_OC.d(TAG, "create dir: " + cachePath);
  84. final File diskCacheDir = new File(cachePath);
  85. mThumbnailCache = new DiskLruImageCache(
  86. diskCacheDir,
  87. DISK_CACHE_SIZE,
  88. mCompressFormat,
  89. mCompressQuality
  90. );
  91. } catch (Exception e) {
  92. Log_OC.d(TAG, "Thumbnail cache could not be opened ", e);
  93. mThumbnailCache = null;
  94. }
  95. }
  96. mThumbnailCacheStarting = false; // Finished initialization
  97. mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
  98. }
  99. return null;
  100. }
  101. }
  102. public static void addBitmapToCache(String key, Bitmap bitmap) {
  103. synchronized (mThumbnailsDiskCacheLock) {
  104. if (mThumbnailCache != null) {
  105. mThumbnailCache.put(key, bitmap);
  106. }
  107. }
  108. }
  109. public static Bitmap getBitmapFromDiskCache(String key) {
  110. synchronized (mThumbnailsDiskCacheLock) {
  111. // Wait while disk cache is started from background thread
  112. while (mThumbnailCacheStarting) {
  113. try {
  114. mThumbnailsDiskCacheLock.wait();
  115. } catch (InterruptedException e) {
  116. Log_OC.e(TAG, "Wait in mThumbnailsDiskCacheLock was interrupted", e);
  117. }
  118. }
  119. if (mThumbnailCache != null) {
  120. return mThumbnailCache.getBitmap(key);
  121. }
  122. }
  123. return null;
  124. }
  125. public static class ThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
  126. private final WeakReference<ImageView> mImageViewReference;
  127. private static Account mAccount;
  128. private Object mFile;
  129. private FileDataStorageManager mStorageManager;
  130. public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager,
  131. Account account) {
  132. // Use a WeakReference to ensure the ImageView can be garbage collected
  133. mImageViewReference = new WeakReference<ImageView>(imageView);
  134. if (storageManager == null)
  135. throw new IllegalArgumentException("storageManager must not be NULL");
  136. mStorageManager = storageManager;
  137. mAccount = account;
  138. }
  139. public ThumbnailGenerationTask(ImageView imageView) {
  140. // Use a WeakReference to ensure the ImageView can be garbage collected
  141. mImageViewReference = new WeakReference<ImageView>(imageView);
  142. }
  143. @Override
  144. protected Bitmap doInBackground(Object... params) {
  145. Bitmap thumbnail = null;
  146. try {
  147. if (mAccount != null) {
  148. OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount,
  149. MainApp.getAppContext());
  150. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  151. getClientFor(ocAccount, MainApp.getAppContext());
  152. }
  153. mFile = params[0];
  154. if (mFile instanceof OCFile) {
  155. thumbnail = doOCFileInBackground();
  156. if (((OCFile) mFile).isVideo()){
  157. thumbnail = addVideoOverlay(thumbnail);
  158. }
  159. } else if (mFile instanceof File) {
  160. thumbnail = doFileInBackground();
  161. String url = ((File) mFile).getAbsolutePath();
  162. FileNameMap fileNameMap = URLConnection.getFileNameMap();
  163. String mMimeType = fileNameMap.getContentTypeFor("file://" + url);
  164. if (mMimeType != null && mMimeType.startsWith("video/")){
  165. thumbnail = addVideoOverlay(thumbnail);
  166. }
  167. //} else { do nothing
  168. }
  169. }catch(Throwable t){
  170. // the app should never break due to a problem with thumbnails
  171. Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
  172. if (t instanceof OutOfMemoryError) {
  173. System.gc();
  174. }
  175. }
  176. return thumbnail;
  177. }
  178. protected void onPostExecute(Bitmap bitmap){
  179. if (isCancelled()) {
  180. bitmap = null;
  181. }
  182. if (bitmap != null) {
  183. final ImageView imageView = mImageViewReference.get();
  184. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  185. if (this == bitmapWorkerTask) {
  186. String tagId = "";
  187. if (mFile instanceof OCFile){
  188. tagId = String.valueOf(((OCFile)mFile).getFileId());
  189. } else if (mFile instanceof File){
  190. tagId = String.valueOf(mFile.hashCode());
  191. }
  192. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  193. imageView.setImageBitmap(bitmap);
  194. }
  195. }
  196. }
  197. }
  198. /**
  199. * Add thumbnail to cache
  200. * @param imageKey: thumb key
  201. * @param bitmap: image for extracting thumbnail
  202. * @param path: image path
  203. * @param px: thumbnail dp
  204. * @return Bitmap
  205. */
  206. private Bitmap addThumbnailToCache(String imageKey, Bitmap bitmap, String path, int px){
  207. Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  208. // Rotate image, obeying exif tag
  209. thumbnail = BitmapUtils.rotateImage(thumbnail,path);
  210. // Add thumbnail to cache
  211. addBitmapToCache(imageKey, thumbnail);
  212. return thumbnail;
  213. }
  214. /**
  215. * Converts size of file icon from dp to pixel
  216. * @return int
  217. */
  218. private int getThumbnailDimension(){
  219. // Converts dp to pixel
  220. Resources r = MainApp.getAppContext().getResources();
  221. return Math.round(r.getDimension(R.dimen.file_icon_size_grid));
  222. }
  223. private Bitmap doOCFileInBackground() {
  224. OCFile file = (OCFile)mFile;
  225. final String imageKey = String.valueOf(file.getRemoteId());
  226. // Check disk cache in background thread
  227. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  228. // Not found in disk cache
  229. if (thumbnail == null || file.needsUpdateThumbnail()) {
  230. int px = getThumbnailDimension();
  231. if (file.isDown()) {
  232. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
  233. file.getStoragePath(), px, px);
  234. if (bitmap != null) {
  235. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), px);
  236. file.setNeedsUpdateThumbnail(false);
  237. mStorageManager.saveFile(file);
  238. }
  239. } else {
  240. // Download thumbnail from server
  241. OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
  242. if (mClient != null && serverOCVersion != null) {
  243. if (serverOCVersion.supportsRemoteThumbnails()) {
  244. try {
  245. String uri = mClient.getBaseUri() + "" +
  246. "/index.php/apps/files/api/v1/thumbnail/" +
  247. px + "/" + px + Uri.encode(file.getRemotePath(), "/");
  248. Log_OC.d("Thumbnail", "URI: " + uri);
  249. GetMethod get = new GetMethod(uri);
  250. int status = mClient.executeMethod(get);
  251. if (status == HttpStatus.SC_OK) {
  252. // byte[] bytes = get.getResponseBody();
  253. // Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
  254. // bytes.length);
  255. InputStream inputStream = get.getResponseBodyAsStream();
  256. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  257. thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  258. // Add thumbnail to cache
  259. if (thumbnail != null) {
  260. addBitmapToCache(imageKey, thumbnail);
  261. }
  262. }
  263. } catch (Exception e) {
  264. e.printStackTrace();
  265. }
  266. } else {
  267. Log_OC.d(TAG, "Server too old");
  268. }
  269. }
  270. }
  271. }
  272. return thumbnail;
  273. }
  274. private Bitmap doFileInBackground() {
  275. File file = (File)mFile;
  276. final String imageKey = String.valueOf(file.hashCode());
  277. // Check disk cache in background thread
  278. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  279. // Not found in disk cache
  280. if (thumbnail == null) {
  281. int px = getThumbnailDimension();
  282. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
  283. file.getAbsolutePath(), px, px);
  284. if (bitmap != null) {
  285. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), px);
  286. }
  287. }
  288. return thumbnail;
  289. }
  290. }
  291. public static boolean cancelPotentialWork(Object file, ImageView imageView) {
  292. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  293. if (bitmapWorkerTask != null) {
  294. final Object bitmapData = bitmapWorkerTask.mFile;
  295. // If bitmapData is not yet set or it differs from the new data
  296. if (bitmapData == null || bitmapData != file) {
  297. // Cancel previous task
  298. bitmapWorkerTask.cancel(true);
  299. } else {
  300. // The same work is already in progress
  301. return false;
  302. }
  303. }
  304. // No task associated with the ImageView, or an existing task was cancelled
  305. return true;
  306. }
  307. public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
  308. if (imageView != null) {
  309. final Drawable drawable = imageView.getDrawable();
  310. if (drawable instanceof AsyncDrawable) {
  311. final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
  312. return asyncDrawable.getBitmapWorkerTask();
  313. }
  314. }
  315. return null;
  316. }
  317. public static Bitmap addVideoOverlay(Bitmap thumbnail){
  318. Bitmap playButton = BitmapFactory.decodeResource(MainApp.getAppContext().getResources(),
  319. R.drawable.view_play);
  320. Bitmap resizedPlayButton = Bitmap.createScaledBitmap(playButton,
  321. (int) (thumbnail.getWidth() * 0.3),
  322. (int) (thumbnail.getHeight() * 0.3), true);
  323. Bitmap resultBitmap = Bitmap.createBitmap(thumbnail.getWidth(),
  324. thumbnail.getHeight(),
  325. Bitmap.Config.ARGB_8888);
  326. Canvas c = new Canvas(resultBitmap);
  327. // compute visual center of play button, according to resized image
  328. int x1 = resizedPlayButton.getWidth();
  329. int y1 = resizedPlayButton.getHeight() / 2;
  330. int x2 = 0;
  331. int y2 = resizedPlayButton.getWidth();
  332. int x3 = 0;
  333. int y3 = 0;
  334. double ym = ( ((Math.pow(x3,2) - Math.pow(x1,2) + Math.pow(y3,2) - Math.pow(y1,2)) *
  335. (x2 - x1)) - (Math.pow(x2,2) - Math.pow(x1,2) + Math.pow(y2,2) -
  336. Math.pow(y1,2)) * (x3 - x1) ) / (2 * ( ((y3 - y1) * (x2 - x1)) -
  337. ((y2 - y1) * (x3 - x1)) ));
  338. double xm = ( (Math.pow(x2,2) - Math.pow(x1,2)) + (Math.pow(y2,2) - Math.pow(y1,2)) -
  339. (2*ym*(y2 - y1)) ) / (2*(x2 - x1));
  340. // offset to top left
  341. double ox = - xm;
  342. double oy = thumbnail.getHeight() - ym;
  343. c.drawBitmap(thumbnail, 0, 0, null);
  344. Paint p = new Paint();
  345. p.setAlpha(230);
  346. c.drawBitmap(resizedPlayButton, (float) ((thumbnail.getWidth() / 2) + ox),
  347. (float) ((thumbnail.getHeight() / 2) - ym), p);
  348. return resultBitmap;
  349. }
  350. public static class AsyncDrawable extends BitmapDrawable {
  351. private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
  352. public AsyncDrawable(
  353. Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
  354. ) {
  355. super(res, bitmap);
  356. bitmapWorkerTaskReference =
  357. new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
  358. }
  359. public ThumbnailGenerationTask getBitmapWorkerTask() {
  360. return bitmapWorkerTaskReference.get();
  361. }
  362. }
  363. }