ThumbnailsCacheManager.java 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  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 android.accounts.Account;
  23. import android.accounts.AccountManager;
  24. import android.content.Context;
  25. import android.content.res.Resources;
  26. import android.graphics.Bitmap;
  27. import android.graphics.Bitmap.CompressFormat;
  28. import android.graphics.BitmapFactory;
  29. import android.graphics.Canvas;
  30. import android.graphics.Paint;
  31. import android.graphics.Point;
  32. import android.graphics.drawable.BitmapDrawable;
  33. import android.graphics.drawable.Drawable;
  34. import android.media.MediaMetadataRetriever;
  35. import android.media.ThumbnailUtils;
  36. import android.net.Uri;
  37. import android.os.AsyncTask;
  38. import android.provider.MediaStore;
  39. import android.support.annotation.Nullable;
  40. import android.text.TextUtils;
  41. import android.view.Display;
  42. import android.view.MenuItem;
  43. import android.view.WindowManager;
  44. import android.widget.ImageView;
  45. import com.owncloud.android.MainApp;
  46. import com.owncloud.android.R;
  47. import com.owncloud.android.authentication.AccountUtils;
  48. import com.owncloud.android.lib.common.OwnCloudAccount;
  49. import com.owncloud.android.lib.common.OwnCloudClient;
  50. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  51. import com.owncloud.android.lib.common.operations.RemoteOperation;
  52. import com.owncloud.android.lib.common.utils.Log_OC;
  53. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  54. import com.owncloud.android.ui.TextDrawable;
  55. import com.owncloud.android.ui.adapter.DiskLruImageCache;
  56. import com.owncloud.android.ui.preview.PreviewImageFragment;
  57. import com.owncloud.android.utils.BitmapUtils;
  58. import com.owncloud.android.utils.ConnectivityUtils;
  59. import com.owncloud.android.utils.DisplayUtils.AvatarGenerationListener;
  60. import com.owncloud.android.utils.FileStorageUtils;
  61. import com.owncloud.android.utils.MimeTypeUtil;
  62. import org.apache.commons.httpclient.HttpStatus;
  63. import org.apache.commons.httpclient.methods.GetMethod;
  64. import java.io.File;
  65. import java.io.FileNotFoundException;
  66. import java.io.InputStream;
  67. import java.lang.ref.WeakReference;
  68. import java.net.URLEncoder;
  69. import java.util.ArrayList;
  70. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  71. /**
  72. * Manager for concurrent access to thumbnails cache.
  73. */
  74. public class ThumbnailsCacheManager {
  75. public static final String PREFIX_RESIZED_IMAGE = "r";
  76. public static final String PREFIX_THUMBNAIL = "t";
  77. private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
  78. private static final String PNG_MIMETYPE = "image/png";
  79. private static final String CACHE_FOLDER = "thumbnailCache";
  80. public static final String AVATAR = "avatar";
  81. private static final String ETAG = "ETag";
  82. private static final Object mThumbnailsDiskCacheLock = new Object();
  83. private static DiskLruImageCache mThumbnailCache = null;
  84. private static boolean mThumbnailCacheStarting = true;
  85. private static final int DISK_CACHE_SIZE = 1024 * 1024 * 200; // 200MB
  86. private static final CompressFormat mCompressFormat = CompressFormat.JPEG;
  87. private static final int mCompressQuality = 70;
  88. private static OwnCloudClient mClient = null;
  89. public static final Bitmap mDefaultImg = BitmapFactory.decodeResource(MainApp.getAppContext().getResources(),
  90. R.drawable.file_image);
  91. public static final Bitmap mDefaultVideo = BitmapFactory.decodeResource(MainApp.getAppContext().getResources(),
  92. R.drawable.file_movie);
  93. public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
  94. @Override
  95. protected Void doInBackground(File... params) {
  96. synchronized (mThumbnailsDiskCacheLock) {
  97. mThumbnailCacheStarting = true;
  98. if (mThumbnailCache == null) {
  99. try {
  100. // Check if media is mounted or storage is built-in, if so,
  101. // try and use external cache dir; otherwise use internal cache dir
  102. File cacheDir = MainApp.getAppContext().getExternalCacheDir();
  103. if (cacheDir != null) {
  104. String cachePath = cacheDir.getPath() + File.separator + CACHE_FOLDER;
  105. Log_OC.d(TAG, "create dir: " + cachePath);
  106. File diskCacheDir = new File(cachePath);
  107. mThumbnailCache = new DiskLruImageCache(diskCacheDir, DISK_CACHE_SIZE, mCompressFormat,
  108. mCompressQuality);
  109. } else {
  110. throw new FileNotFoundException("Thumbnail cache could not be opened");
  111. }
  112. } catch (java.io.IOException e) {
  113. Log_OC.d(TAG, e.getMessage());
  114. mThumbnailCache = null;
  115. }
  116. }
  117. mThumbnailCacheStarting = false; // Finished initialization
  118. mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
  119. }
  120. return null;
  121. }
  122. }
  123. /**
  124. * Converts size of file icon from dp to pixel
  125. * @return int
  126. */
  127. private static int getThumbnailDimension(){
  128. // Converts dp to pixel
  129. Resources r = MainApp.getAppContext().getResources();
  130. return Math.round(r.getDimension(R.dimen.file_icon_size_grid));
  131. }
  132. /**
  133. * Converts dimension of screen as point
  134. *
  135. * @return Point
  136. */
  137. private static Point getScreenDimension() {
  138. WindowManager wm = (WindowManager) MainApp.getAppContext().getSystemService(Context.WINDOW_SERVICE);
  139. Display display = wm.getDefaultDisplay();
  140. Point point = new Point();
  141. display.getSize(point);
  142. return point;
  143. }
  144. /**
  145. * Add thumbnail to cache
  146. * @param imageKey: thumb key
  147. * @param bitmap: image for extracting thumbnail
  148. * @param path: image path
  149. * @param pxW: thumbnail width in pixel
  150. * @param pxH: thumbnail height in pixel
  151. * @return Bitmap
  152. */
  153. private static Bitmap addThumbnailToCache(String imageKey, Bitmap bitmap, String path, int pxW, int pxH){
  154. Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
  155. // Rotate image, obeying exif tag
  156. thumbnail = BitmapUtils.rotateImage(thumbnail,path);
  157. // Add thumbnail to cache
  158. addBitmapToCache(imageKey, thumbnail);
  159. return thumbnail;
  160. }
  161. public static void addBitmapToCache(String key, Bitmap bitmap) {
  162. synchronized (mThumbnailsDiskCacheLock) {
  163. if (mThumbnailCache != null) {
  164. mThumbnailCache.put(key, bitmap);
  165. }
  166. }
  167. }
  168. public static Bitmap getBitmapFromDiskCache(String key) {
  169. synchronized (mThumbnailsDiskCacheLock) {
  170. // Wait while disk cache is started from background thread
  171. while (mThumbnailCacheStarting) {
  172. try {
  173. mThumbnailsDiskCacheLock.wait();
  174. } catch (InterruptedException e) {
  175. Log_OC.e(TAG, "Wait in mThumbnailsDiskCacheLock was interrupted", e);
  176. }
  177. }
  178. if (mThumbnailCache != null) {
  179. return mThumbnailCache.getBitmap(key);
  180. }
  181. }
  182. return null;
  183. }
  184. public static class ResizedImageGenerationTask extends AsyncTask<Object, Void, Bitmap> {
  185. private PreviewImageFragment previewImageFragment;
  186. private FileDataStorageManager storageManager;
  187. private Account account;
  188. private WeakReference<ImageView> imageViewReference;
  189. private OCFile file;
  190. public ResizedImageGenerationTask(PreviewImageFragment previewImageFragment, ImageView imageView,
  191. FileDataStorageManager storageManager, Account account)
  192. throws IllegalArgumentException {
  193. this.previewImageFragment = previewImageFragment;
  194. imageViewReference = new WeakReference<>(imageView);
  195. this.storageManager = storageManager;
  196. this.account = account;
  197. }
  198. @Override
  199. protected Bitmap doInBackground(Object... params) {
  200. Bitmap thumbnail = null;
  201. file = (OCFile) params[0];
  202. try {
  203. if (account != null) {
  204. OwnCloudAccount ocAccount = new OwnCloudAccount(account, MainApp.getAppContext());
  205. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount,
  206. MainApp.getAppContext());
  207. }
  208. thumbnail = doResizedImageInBackground();
  209. if (MimeTypeUtil.isVideo(file) && thumbnail != null) {
  210. thumbnail = addVideoOverlay(thumbnail);
  211. }
  212. } catch (OutOfMemoryError oome) {
  213. System.gc();
  214. Log_OC.e(TAG, "Out of memory -> garbage collector called");
  215. } catch (Throwable t) {
  216. // the app should never break due to a problem with thumbnails
  217. Log_OC.e(TAG, "Generation of thumbnail for " + file + " failed", t);
  218. }
  219. return thumbnail;
  220. }
  221. private Bitmap doResizedImageInBackground() {
  222. Bitmap thumbnail;
  223. String imageKey = PREFIX_RESIZED_IMAGE + String.valueOf(file.getRemoteId());
  224. // Check disk cache in background thread
  225. thumbnail = getBitmapFromDiskCache(imageKey);
  226. // Not found in disk cache
  227. if (thumbnail == null || file.needsUpdateThumbnail()) {
  228. Point p = getScreenDimension();
  229. int pxW = p.x;
  230. int pxH = p.y;
  231. if (file.isDown()) {
  232. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getStoragePath(), pxW, pxH);
  233. if (bitmap != null) {
  234. // Handle PNG
  235. if (file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  236. bitmap = handlePNG(bitmap, pxW, pxH);
  237. }
  238. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
  239. file.setNeedsUpdateThumbnail(false);
  240. storageManager.saveFile(file);
  241. }
  242. } else {
  243. // Download thumbnail from server
  244. OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(account);
  245. if (mClient != null) {
  246. if (serverOCVersion.supportsRemoteThumbnails()) {
  247. GetMethod getMethod = null;
  248. try {
  249. String uri = mClient.getBaseUri() + "/index.php/core/preview.png?file="
  250. + URLEncoder.encode(file.getRemotePath())
  251. + "&x=" + pxW + "&y=" + pxH + "&a=1&mode=cover&forceIcon=0";
  252. getMethod = new GetMethod(uri);
  253. int status = mClient.executeMethod(getMethod);
  254. if (status == HttpStatus.SC_OK) {
  255. InputStream inputStream = getMethod.getResponseBodyAsStream();
  256. thumbnail = BitmapFactory.decodeStream(inputStream);
  257. } else {
  258. mClient.exhaustResponse(getMethod.getResponseBodyAsStream());
  259. }
  260. // Handle PNG
  261. if (thumbnail != null && file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  262. thumbnail = handlePNG(thumbnail, thumbnail.getWidth(), thumbnail.getHeight());
  263. }
  264. // Add thumbnail to cache
  265. if (thumbnail != null) {
  266. Log_OC.d(TAG, "add thumbnail to cache: " + file.getFileName());
  267. addBitmapToCache(imageKey, thumbnail);
  268. }
  269. } catch (Exception e) {
  270. Log_OC.d(TAG, e.getMessage(), e);
  271. } finally {
  272. if (getMethod != null) {
  273. getMethod.releaseConnection();
  274. }
  275. }
  276. } else {
  277. Log_OC.d(TAG, "Server too old");
  278. }
  279. }
  280. }
  281. }
  282. return thumbnail;
  283. }
  284. protected void onPostExecute(Bitmap bitmap) {
  285. if (imageViewReference != null) {
  286. final ImageView imageView = imageViewReference.get();
  287. if (bitmap != null) {
  288. final ResizedImageGenerationTask bitmapWorkerTask = getResizedImageGenerationWorkerTask(imageView);
  289. if (this == bitmapWorkerTask) {
  290. String tagId = String.valueOf(file.getFileId());
  291. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  292. imageView.setImageBitmap(bitmap);
  293. }
  294. }
  295. } else {
  296. new Thread(() -> {
  297. if (ConnectivityUtils.isInternetWalled(MainApp.getAppContext())) {
  298. previewImageFragment.setNoConnectionErrorMessage();
  299. } else {
  300. previewImageFragment.setErrorPreviewMessage();
  301. }
  302. }).start();
  303. }
  304. }
  305. }
  306. }
  307. public static class ThumbnailGenerationTaskObject {
  308. private Object file;
  309. private String imageKey;
  310. public ThumbnailGenerationTaskObject(Object file, String imageKey) {
  311. this.file = file;
  312. this.imageKey = imageKey;
  313. }
  314. private Object getFile() {
  315. return file;
  316. }
  317. private String getImageKey() {
  318. return imageKey;
  319. }
  320. }
  321. public static class ThumbnailGenerationTask extends AsyncTask<ThumbnailGenerationTaskObject, Void, Bitmap> {
  322. private final WeakReference<ImageView> mImageViewReference;
  323. private static Account mAccount;
  324. private ArrayList<ThumbnailGenerationTask> mAsyncTasks = null;
  325. private Object mFile;
  326. private String mImageKey = null;
  327. private FileDataStorageManager mStorageManager;
  328. private GetMethod getMethod;
  329. public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager, Account account)
  330. throws IllegalArgumentException {
  331. this(imageView, storageManager, account, null);
  332. }
  333. public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager,
  334. Account account, ArrayList<ThumbnailGenerationTask> asyncTasks)
  335. throws IllegalArgumentException {
  336. // Use a WeakReference to ensure the ImageView can be garbage collected
  337. mImageViewReference = new WeakReference<ImageView>(imageView);
  338. if (storageManager == null) {
  339. throw new IllegalArgumentException("storageManager must not be NULL");
  340. }
  341. mStorageManager = storageManager;
  342. mAccount = account;
  343. mAsyncTasks = asyncTasks;
  344. }
  345. public GetMethod getGetMethod() {
  346. return getMethod;
  347. }
  348. public ThumbnailGenerationTask(FileDataStorageManager storageManager, Account account){
  349. if (storageManager == null) {
  350. throw new IllegalArgumentException("storageManager must not be NULL");
  351. }
  352. mStorageManager = storageManager;
  353. mAccount = account;
  354. mImageViewReference = null;
  355. }
  356. public ThumbnailGenerationTask(ImageView imageView) {
  357. // Use a WeakReference to ensure the ImageView can be garbage collected
  358. mImageViewReference = new WeakReference<ImageView>(imageView);
  359. }
  360. @SuppressFBWarnings("Dm")
  361. @Override
  362. protected Bitmap doInBackground(ThumbnailGenerationTaskObject... params) {
  363. Bitmap thumbnail = null;
  364. try {
  365. if (mAccount != null) {
  366. OwnCloudAccount ocAccount = new OwnCloudAccount(
  367. mAccount,
  368. MainApp.getAppContext()
  369. );
  370. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  371. getClientFor(ocAccount, MainApp.getAppContext());
  372. }
  373. ThumbnailGenerationTaskObject object = params[0];
  374. mFile = object.getFile();
  375. mImageKey = object.getImageKey();
  376. if (mFile instanceof OCFile) {
  377. thumbnail = doThumbnailFromOCFileInBackground();
  378. if (MimeTypeUtil.isVideo((OCFile) mFile) && thumbnail != null) {
  379. thumbnail = addVideoOverlay(thumbnail);
  380. }
  381. } else if (mFile instanceof File) {
  382. thumbnail = doFileInBackground();
  383. String url = ((File) mFile).getAbsolutePath();
  384. String mMimeType = FileStorageUtils.getMimeTypeFromName(url);
  385. if (MimeTypeUtil.isVideo(mMimeType) && thumbnail != null) {
  386. thumbnail = addVideoOverlay(thumbnail);
  387. }
  388. //} else { do nothing
  389. }
  390. } catch(OutOfMemoryError oome) {
  391. System.gc();
  392. } catch (Throwable t) {
  393. // the app should never break due to a problem with thumbnails
  394. Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
  395. }
  396. return thumbnail;
  397. }
  398. protected void onPostExecute(Bitmap bitmap) {
  399. if (bitmap != null && mImageViewReference != null) {
  400. final ImageView imageView = mImageViewReference.get();
  401. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  402. if (this == bitmapWorkerTask) {
  403. String tagId = "";
  404. if (mFile instanceof OCFile) {
  405. tagId = String.valueOf(((OCFile)mFile).getFileId());
  406. } else if (mFile instanceof File) {
  407. tagId = String.valueOf(mFile.hashCode());
  408. }
  409. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  410. imageView.setImageBitmap(bitmap);
  411. }
  412. }
  413. }
  414. if (mAsyncTasks != null) {
  415. mAsyncTasks.remove(this);
  416. }
  417. }
  418. private Bitmap doThumbnailFromOCFileInBackground() {
  419. Bitmap thumbnail;
  420. OCFile file = (OCFile) mFile;
  421. String imageKey = PREFIX_THUMBNAIL + String.valueOf(file.getRemoteId());
  422. // Check disk cache in background thread
  423. thumbnail = getBitmapFromDiskCache(imageKey);
  424. // Not found in disk cache
  425. if (thumbnail == null || file.needsUpdateThumbnail()) {
  426. int pxW;
  427. int pxH;
  428. pxW = pxH = getThumbnailDimension();
  429. if (file.isDown()) {
  430. Bitmap bitmap;
  431. if (MimeTypeUtil.isVideo(file)) {
  432. bitmap = ThumbnailUtils.createVideoThumbnail(file.getStoragePath(),
  433. MediaStore.Images.Thumbnails.MINI_KIND);
  434. } else {
  435. bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getStoragePath(), pxW, pxH);
  436. }
  437. if (bitmap != null) {
  438. // Handle PNG
  439. if (file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  440. bitmap = handlePNG(bitmap, pxW, pxH);
  441. }
  442. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
  443. file.setNeedsUpdateThumbnail(false);
  444. mStorageManager.saveFile(file);
  445. }
  446. } else {
  447. // check if resized version is available
  448. String resizedImageKey = PREFIX_RESIZED_IMAGE + String.valueOf(file.getRemoteId());
  449. Bitmap resizedImage = getBitmapFromDiskCache(resizedImageKey);
  450. if (resizedImage != null) {
  451. thumbnail = ThumbnailUtils.extractThumbnail(resizedImage, pxW, pxH);
  452. } else {
  453. // Download thumbnail from server
  454. if (mClient != null && AccountUtils.getServerVersion(mAccount).supportsRemoteThumbnails()) {
  455. getMethod = null;
  456. try {
  457. // thumbnail
  458. String uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
  459. pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
  460. Log_OC.d(TAG, "generate thumbnail: " + file.getFileName() +
  461. " URI: " + uri);
  462. getMethod = new GetMethod(uri);
  463. getMethod.setRequestHeader("Cookie",
  464. "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
  465. getMethod.setRequestHeader(RemoteOperation.OCS_API_HEADER,
  466. RemoteOperation.OCS_API_HEADER_VALUE);
  467. int status = mClient.executeMethod(getMethod);
  468. if (status == HttpStatus.SC_OK) {
  469. InputStream inputStream = getMethod.getResponseBodyAsStream();
  470. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  471. thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
  472. } else {
  473. mClient.exhaustResponse(getMethod.getResponseBodyAsStream());
  474. }
  475. // Handle PNG
  476. if (file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  477. thumbnail = handlePNG(thumbnail, pxW, pxH);
  478. }
  479. } catch (Exception e) {
  480. Log_OC.d(TAG, e.getMessage(), e);
  481. } finally {
  482. if (getMethod != null) {
  483. getMethod.releaseConnection();
  484. }
  485. }
  486. } else {
  487. Log_OC.d(TAG, "Server too old");
  488. }
  489. }
  490. // Add thumbnail to cache
  491. if (thumbnail != null) {
  492. Log_OC.d(TAG, "add thumbnail to cache: " + file.getFileName());
  493. addBitmapToCache(imageKey, thumbnail);
  494. }
  495. }
  496. }
  497. return thumbnail;
  498. }
  499. /**
  500. * Converts size of file icon from dp to pixel
  501. *
  502. * @return int
  503. */
  504. private int getThumbnailDimension() {
  505. // Converts dp to pixel
  506. Resources r = MainApp.getAppContext().getResources();
  507. Double d = Math.pow(2, Math.floor(Math.log(r.getDimension(R.dimen.file_icon_size_grid)) / Math.log(2)));
  508. return d.intValue();
  509. }
  510. private Bitmap doFileInBackground() {
  511. File file = (File)mFile;
  512. final String imageKey;
  513. if (mImageKey != null) {
  514. imageKey = mImageKey;
  515. } else {
  516. imageKey = String.valueOf(file.hashCode());
  517. }
  518. // local file should always generate a thumbnail
  519. mImageKey = PREFIX_THUMBNAIL + mImageKey;
  520. // Check disk cache in background thread
  521. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  522. // Not found in disk cache
  523. if (thumbnail == null) {
  524. int pxW;
  525. int pxH;
  526. pxW = pxH = getThumbnailDimension();
  527. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getAbsolutePath(), pxW, pxH);
  528. if (bitmap != null) {
  529. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), pxW, pxH);
  530. }
  531. }
  532. return thumbnail;
  533. }
  534. }
  535. public static class MediaThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
  536. private enum Type {IMAGE, VIDEO}
  537. private final WeakReference<ImageView> mImageViewReference;
  538. private File mFile;
  539. private String mImageKey = null;
  540. public MediaThumbnailGenerationTask(ImageView imageView) {
  541. // Use a WeakReference to ensure the ImageView can be garbage collected
  542. mImageViewReference = new WeakReference<>(imageView);
  543. }
  544. @Override
  545. protected Bitmap doInBackground(Object... params) {
  546. Bitmap thumbnail = null;
  547. try {
  548. if (params[0] instanceof File) {
  549. mFile = (File) params[0];
  550. if (params.length == 2) {
  551. mImageKey = (String) params[1];
  552. }
  553. if (MimeTypeUtil.isImage(mFile)) {
  554. thumbnail = doFileInBackground(mFile, Type.IMAGE);
  555. } else if (MimeTypeUtil.isVideo(mFile)) {
  556. thumbnail = doFileInBackground(mFile, Type.VIDEO);
  557. }
  558. }
  559. } // the app should never break due to a problem with thumbnails
  560. catch (OutOfMemoryError t) {
  561. Log_OC.e(TAG, "Generation of thumbnail for " + mFile.getAbsolutePath() + " failed", t);
  562. System.gc();
  563. } catch (Throwable t) {
  564. // the app should never break due to a problem with thumbnails
  565. Log_OC.e(TAG, "Generation of thumbnail for " + mFile.getAbsolutePath() + " failed", t);
  566. }
  567. return thumbnail;
  568. }
  569. protected void onPostExecute(Bitmap bitmap) {
  570. String tagId = "";
  571. final ImageView imageView = mImageViewReference.get();
  572. if (imageView != null) {
  573. if (mFile != null) {
  574. tagId = String.valueOf(mFile.hashCode());
  575. }
  576. if (bitmap != null) {
  577. if (tagId.equals(String.valueOf(imageView.getTag()))) {
  578. imageView.setImageBitmap(bitmap);
  579. }
  580. } else {
  581. if (mFile != null) {
  582. if (mFile.isDirectory()) {
  583. imageView.setImageDrawable(MimeTypeUtil.getDefaultFolderIcon());
  584. } else {
  585. if (MimeTypeUtil.isVideo(mFile)) {
  586. imageView.setImageBitmap(ThumbnailsCacheManager.mDefaultVideo);
  587. } else {
  588. imageView.setImageDrawable(MimeTypeUtil.getFileTypeIcon(null, mFile.getName(), null));
  589. }
  590. }
  591. }
  592. }
  593. }
  594. }
  595. private Bitmap doFileInBackground(File file, Type type) {
  596. final String imageKey;
  597. if (mImageKey != null) {
  598. imageKey = mImageKey;
  599. } else {
  600. imageKey = String.valueOf(file.hashCode());
  601. }
  602. // Check disk cache in background thread
  603. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  604. // Not found in disk cache
  605. if (thumbnail == null) {
  606. if (Type.IMAGE.equals(type)) {
  607. int px = getThumbnailDimension();
  608. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getAbsolutePath(), px, px);
  609. if (bitmap != null) {
  610. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), px, px);
  611. }
  612. } else if (Type.VIDEO.equals(type)) {
  613. MediaMetadataRetriever retriever = new MediaMetadataRetriever();
  614. try {
  615. retriever.setDataSource(file.getAbsolutePath());
  616. thumbnail = retriever.getFrameAtTime(-1);
  617. } catch (Exception ex) {
  618. // can't create a bitmap
  619. Log_OC.w(TAG, "Failed to create bitmap from video " + file.getAbsolutePath());
  620. } finally {
  621. try {
  622. retriever.release();
  623. } catch (RuntimeException ex) {
  624. // Ignore failure at this point.
  625. Log_OC.w(TAG, "Failed release MediaMetadataRetriever for " + file.getAbsolutePath());
  626. }
  627. }
  628. if (thumbnail != null) {
  629. // Scale down bitmap if too large.
  630. int px = getThumbnailDimension();
  631. int width = thumbnail.getWidth();
  632. int height = thumbnail.getHeight();
  633. int max = Math.max(width, height);
  634. if (max > px) {
  635. thumbnail = BitmapUtils.scaleBitmap(thumbnail, px, width, height, max);
  636. thumbnail = addThumbnailToCache(imageKey, thumbnail, file.getPath(), px, px);
  637. }
  638. }
  639. }
  640. }
  641. return thumbnail;
  642. }
  643. }
  644. public static class AvatarGenerationTask extends AsyncTask<String, Void, Drawable> {
  645. private final WeakReference<AvatarGenerationListener> mAvatarGenerationListener;
  646. private final Object mCallContext;
  647. private final Resources mResources;
  648. private final float mAvatarRadius;
  649. private Account mAccount;
  650. private String mUsername;
  651. public AvatarGenerationTask(AvatarGenerationListener avatarGenerationListener, Object callContext,
  652. FileDataStorageManager storageManager, Account account, Resources resources,
  653. float avatarRadius) {
  654. mAvatarGenerationListener = new WeakReference<>(avatarGenerationListener);
  655. mCallContext = callContext;
  656. if (storageManager == null) {
  657. throw new IllegalArgumentException("storageManager must not be NULL");
  658. }
  659. mAccount = account;
  660. mResources = resources;
  661. mAvatarRadius = avatarRadius;
  662. }
  663. @SuppressFBWarnings("Dm")
  664. @Override
  665. protected Drawable doInBackground(String... params) {
  666. Drawable thumbnail = null;
  667. try {
  668. if (mAccount != null) {
  669. OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount,
  670. MainApp.getAppContext());
  671. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  672. getClientFor(ocAccount, MainApp.getAppContext());
  673. }
  674. mUsername = params[0];
  675. thumbnail = doAvatarInBackground();
  676. } catch(OutOfMemoryError oome) {
  677. System.gc(); // todo, does this really make sense?
  678. } catch(Throwable t){
  679. // the app should never break due to a problem with avatars
  680. Log_OC.e(TAG, "Generation of avatar for " + mUsername + " failed", t);
  681. }
  682. return thumbnail;
  683. }
  684. protected void onPostExecute(Drawable drawable) {
  685. if (drawable != null) {
  686. AvatarGenerationListener listener = mAvatarGenerationListener.get();
  687. AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(mCallContext);
  688. if (this == avatarWorkerTask && listener.shouldCallGeneratedCallback(mUsername, mCallContext)) {
  689. listener.avatarGenerated(drawable, mCallContext);
  690. }
  691. }
  692. }
  693. /**
  694. * Converts size of file icon from dp to pixel
  695. * @return int
  696. */
  697. private int getAvatarDimension(){
  698. // Converts dp to pixel
  699. Resources r = MainApp.getAppContext().getResources();
  700. return Math.round(r.getDimension(R.dimen.file_avatar_size));
  701. }
  702. private @Nullable
  703. Drawable doAvatarInBackground() {
  704. Bitmap avatar = null;
  705. String username = mUsername;
  706. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(
  707. MainApp.getAppContext().getContentResolver());
  708. String eTag = arbitraryDataProvider.getValue(mAccount, AVATAR);
  709. final String imageKey = "a_" + username + "_" + eTag;
  710. int px = getAvatarDimension();
  711. // Download avatar from server
  712. OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
  713. if (mClient != null) {
  714. if (serverOCVersion.supportsRemoteThumbnails()) {
  715. GetMethod get = null;
  716. try {
  717. String userId = AccountManager.get(MainApp.getAppContext()).getUserData(mAccount,
  718. com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
  719. if (TextUtils.isEmpty(userId)) {
  720. userId = AccountUtils.getAccountUsername(username);
  721. }
  722. String uri = mClient.getBaseUri() + "/index.php/avatar/" + Uri.encode(userId) + "/" + px;
  723. Log_OC.d("Avatar", "URI: " + uri);
  724. get = new GetMethod(uri);
  725. if (!eTag.isEmpty()) {
  726. get.setRequestHeader("If-None-Match", eTag);
  727. }
  728. int status = mClient.executeMethod(get);
  729. // we are using eTag to download a new avatar only if it changed
  730. switch (status) {
  731. case HttpStatus.SC_OK:
  732. // new avatar
  733. InputStream inputStream = get.getResponseBodyAsStream();
  734. if (get.getResponseHeader(ETAG) != null) {
  735. eTag = get.getResponseHeader(ETAG).getValue().replace("\"", "");
  736. arbitraryDataProvider.storeOrUpdateKeyValue(mAccount.name, AVATAR, eTag);
  737. }
  738. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  739. avatar = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  740. // Add avatar to cache
  741. if (avatar != null) {
  742. avatar = handlePNG(avatar, px, px);
  743. String newImageKey = "a_" + username + "_" + eTag;
  744. addBitmapToCache(newImageKey, avatar);
  745. } else {
  746. return TextDrawable.createAvatar(mAccount.name, mAvatarRadius);
  747. }
  748. break;
  749. case HttpStatus.SC_NOT_MODIFIED:
  750. // old avatar
  751. avatar = getBitmapFromDiskCache(imageKey);
  752. mClient.exhaustResponse(get.getResponseBodyAsStream());
  753. break;
  754. default:
  755. // everything else
  756. mClient.exhaustResponse(get.getResponseBodyAsStream());
  757. break;
  758. }
  759. } catch (Exception e) {
  760. try {
  761. return TextDrawable.createAvatar(mAccount.name, mAvatarRadius);
  762. } catch (Exception e1) {
  763. Log_OC.e(TAG, "Error generating fallback avatar");
  764. }
  765. } finally {
  766. if (get != null) {
  767. get.releaseConnection();
  768. }
  769. }
  770. } else {
  771. Log_OC.d(TAG, "Server too old");
  772. try {
  773. return TextDrawable.createAvatar(mAccount.name, mAvatarRadius);
  774. } catch (Exception e) {
  775. Log_OC.e(TAG, "Error generating fallback avatar");
  776. }
  777. }
  778. }
  779. return BitmapUtils.bitmapToCircularBitmapDrawable(mResources, avatar);
  780. }
  781. }
  782. public static boolean cancelPotentialThumbnailWork(Object file, ImageView imageView) {
  783. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  784. if (bitmapWorkerTask != null) {
  785. final Object bitmapData = bitmapWorkerTask.mFile;
  786. // If bitmapData is not yet set or it differs from the new data
  787. if (bitmapData == null || !bitmapData.equals(file)) {
  788. // Cancel previous task
  789. bitmapWorkerTask.cancel(true);
  790. Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView");
  791. } else {
  792. // The same work is already in progress
  793. return false;
  794. }
  795. }
  796. // No task associated with the ImageView, or an existing task was cancelled
  797. return true;
  798. }
  799. public static boolean cancelPotentialAvatarWork(Object file, Object callContext) {
  800. if (callContext instanceof ImageView) {
  801. return cancelPotentialAvatarWork(file, (ImageView) callContext);
  802. } else if (callContext instanceof MenuItem) {
  803. return cancelPotentialAvatarWork(file, (MenuItem)callContext);
  804. }
  805. return false;
  806. }
  807. public static boolean cancelPotentialAvatarWork(Object file, ImageView imageView) {
  808. final AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(imageView);
  809. if (avatarWorkerTask != null) {
  810. final Object usernameData = avatarWorkerTask.mUsername;
  811. // If usernameData is not yet set or it differs from the new data
  812. if (usernameData == null || !usernameData.equals(file)) {
  813. // Cancel previous task
  814. avatarWorkerTask.cancel(true);
  815. Log_OC.v(TAG, "Cancelled generation of avatar for a reused imageView");
  816. } else {
  817. // The same work is already in progress
  818. return false;
  819. }
  820. }
  821. // No task associated with the ImageView, or an existing task was cancelled
  822. return true;
  823. }
  824. public static boolean cancelPotentialAvatarWork(Object file, MenuItem menuItem) {
  825. final AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(menuItem);
  826. if (avatarWorkerTask != null) {
  827. final Object usernameData = avatarWorkerTask.mUsername;
  828. // If usernameData is not yet set or it differs from the new data
  829. if (usernameData == null || !usernameData.equals(file)) {
  830. // Cancel previous task
  831. avatarWorkerTask.cancel(true);
  832. Log_OC.v(TAG, "Cancelled generation of avatar for a reused imageView");
  833. } else {
  834. // The same work is already in progress
  835. return false;
  836. }
  837. }
  838. // No task associated with the ImageView, or an existing task was cancelled
  839. return true;
  840. }
  841. public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
  842. if (imageView != null) {
  843. final Drawable drawable = imageView.getDrawable();
  844. if (drawable instanceof AsyncThumbnailDrawable) {
  845. final AsyncThumbnailDrawable asyncDrawable = (AsyncThumbnailDrawable) drawable;
  846. return asyncDrawable.getBitmapWorkerTask();
  847. }
  848. }
  849. return null;
  850. }
  851. private static ResizedImageGenerationTask getResizedImageGenerationWorkerTask(ImageView imageView) {
  852. if (imageView != null) {
  853. final Drawable drawable = imageView.getDrawable();
  854. if (drawable instanceof AsyncResizedImageDrawable) {
  855. final AsyncResizedImageDrawable asyncDrawable = (AsyncResizedImageDrawable) drawable;
  856. return asyncDrawable.getBitmapWorkerTask();
  857. }
  858. }
  859. return null;
  860. }
  861. public static Bitmap addVideoOverlay(Bitmap thumbnail){
  862. Bitmap playButton = BitmapFactory.decodeResource(MainApp.getAppContext().getResources(),
  863. R.drawable.view_play);
  864. Bitmap resizedPlayButton = Bitmap.createScaledBitmap(playButton,
  865. (int) (thumbnail.getWidth() * 0.3),
  866. (int) (thumbnail.getHeight() * 0.3), true);
  867. Bitmap resultBitmap = Bitmap.createBitmap(thumbnail.getWidth(),
  868. thumbnail.getHeight(),
  869. Bitmap.Config.ARGB_8888);
  870. Canvas c = new Canvas(resultBitmap);
  871. // compute visual center of play button, according to resized image
  872. int x1 = resizedPlayButton.getWidth();
  873. int y1 = resizedPlayButton.getHeight() / 2;
  874. int x2 = 0;
  875. int y2 = resizedPlayButton.getWidth();
  876. int x3 = 0;
  877. int y3 = 0;
  878. double ym = ( ((Math.pow(x3,2) - Math.pow(x1,2) + Math.pow(y3,2) - Math.pow(y1,2)) *
  879. (x2 - x1)) - (Math.pow(x2,2) - Math.pow(x1,2) + Math.pow(y2,2) -
  880. Math.pow(y1,2)) * (x3 - x1) ) / (2 * ( ((y3 - y1) * (x2 - x1)) -
  881. ((y2 - y1) * (x3 - x1)) ));
  882. double xm = ( (Math.pow(x2,2) - Math.pow(x1,2)) + (Math.pow(y2,2) - Math.pow(y1,2)) -
  883. (2*ym*(y2 - y1)) ) / (2*(x2 - x1));
  884. // offset to top left
  885. double ox = - xm;
  886. c.drawBitmap(thumbnail, 0, 0, null);
  887. Paint p = new Paint();
  888. p.setAlpha(230);
  889. c.drawBitmap(resizedPlayButton, (float) ((thumbnail.getWidth() / 2) + ox),
  890. (float) ((thumbnail.getHeight() / 2) - ym), p);
  891. return resultBitmap;
  892. }
  893. public static AvatarGenerationTask getAvatarWorkerTask(Object callContext) {
  894. if (callContext instanceof ImageView) {
  895. return getAvatarWorkerTask(((ImageView)callContext).getDrawable());
  896. } else if (callContext instanceof MenuItem) {
  897. return getAvatarWorkerTask(((MenuItem)callContext).getIcon());
  898. }
  899. return null;
  900. }
  901. private static AvatarGenerationTask getAvatarWorkerTask(Drawable drawable) {
  902. if (drawable instanceof AsyncAvatarDrawable) {
  903. final AsyncAvatarDrawable asyncDrawable = (AsyncAvatarDrawable) drawable;
  904. return asyncDrawable.getAvatarWorkerTask();
  905. }
  906. return null;
  907. }
  908. public static class AsyncThumbnailDrawable extends BitmapDrawable {
  909. private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
  910. public AsyncThumbnailDrawable(
  911. Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
  912. ) {
  913. super(res, bitmap);
  914. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  915. }
  916. public ThumbnailGenerationTask getBitmapWorkerTask() {
  917. return bitmapWorkerTaskReference.get();
  918. }
  919. }
  920. public static class AsyncResizedImageDrawable extends BitmapDrawable {
  921. private final WeakReference<ResizedImageGenerationTask> bitmapWorkerTaskReference;
  922. public AsyncResizedImageDrawable(Resources res, Bitmap bitmap, ResizedImageGenerationTask bitmapWorkerTask) {
  923. super(res, bitmap);
  924. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  925. }
  926. private ResizedImageGenerationTask getBitmapWorkerTask() {
  927. return bitmapWorkerTaskReference.get();
  928. }
  929. }
  930. public static class AsyncMediaThumbnailDrawable extends BitmapDrawable {
  931. private final WeakReference<MediaThumbnailGenerationTask> bitmapWorkerTaskReference;
  932. public AsyncMediaThumbnailDrawable(Resources res, Bitmap bitmap,
  933. MediaThumbnailGenerationTask bitmapWorkerTask) {
  934. super(res, bitmap);
  935. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  936. }
  937. }
  938. public static class AsyncAvatarDrawable extends BitmapDrawable {
  939. private final WeakReference<AvatarGenerationTask> avatarWorkerTaskReference;
  940. public AsyncAvatarDrawable(Resources res, Drawable bitmap, AvatarGenerationTask avatarWorkerTask) {
  941. super(res, BitmapUtils.drawableToBitmap(bitmap));
  942. avatarWorkerTaskReference = new WeakReference<>(avatarWorkerTask);
  943. }
  944. public AvatarGenerationTask getAvatarWorkerTask() {
  945. return avatarWorkerTaskReference.get();
  946. }
  947. }
  948. private static Bitmap handlePNG(Bitmap bitmap, int pxW, int pxH) {
  949. Bitmap resultBitmap = Bitmap.createBitmap(pxW, pxH, Bitmap.Config.ARGB_8888);
  950. Canvas c = new Canvas(resultBitmap);
  951. c.drawColor(MainApp.getAppContext().getResources().getColor(R.color.background_color));
  952. c.drawBitmap(bitmap, 0, 0, null);
  953. return resultBitmap;
  954. }
  955. public static void generateResizedImage(OCFile file) {
  956. Point p = getScreenDimension();
  957. int pxW = p.x;
  958. int pxH = p.y;
  959. String imageKey = PREFIX_RESIZED_IMAGE + String.valueOf(file.getRemoteId());
  960. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getStoragePath(), pxW, pxH);
  961. if (bitmap != null) {
  962. // Handle PNG
  963. if (file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  964. bitmap = handlePNG(bitmap, pxW, pxH);
  965. }
  966. addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
  967. }
  968. }
  969. }