ThumbnailsCacheManager.java 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. /*
  2. * Nextcloud - Android Client
  3. *
  4. * SPDX-FileCopyrightText: 2022-2023 Álvaro Brey <alvaro@alvarobrey.com>
  5. * SPDX-FileCopyrightText: 2017-2020 Tobias Kaminsky <tobias@kaminsky.me>
  6. * SPDX-FileCopyrightText: 2016-2020 Andy Scherzinger <info@andy-scherzinger.de>
  7. * SPDX-FileCopyrightText: 2019 Chris Narkiewicz <hello@ezaquarii.com>
  8. * SPDX-FileCopyrightText: 2015 ownCloud Inc.
  9. * SPDX-FileCopyrightText: 2014 David A. Velasco <dvelasco@solidgear.es>
  10. * SPDX-License-Identifier: GPL-2.0-only AND (AGPL-3.0-or-later OR GPL-2.0-only)
  11. */
  12. package com.owncloud.android.datamodel;
  13. import android.content.Context;
  14. import android.content.res.Resources;
  15. import android.graphics.Bitmap;
  16. import android.graphics.Bitmap.CompressFormat;
  17. import android.graphics.BitmapFactory;
  18. import android.graphics.Canvas;
  19. import android.graphics.Paint;
  20. import android.graphics.Point;
  21. import android.graphics.RectF;
  22. import android.graphics.drawable.BitmapDrawable;
  23. import android.graphics.drawable.Drawable;
  24. import android.media.MediaMetadataRetriever;
  25. import android.media.ThumbnailUtils;
  26. import android.net.Uri;
  27. import android.os.AsyncTask;
  28. import android.provider.MediaStore;
  29. import android.text.TextUtils;
  30. import android.view.Display;
  31. import android.view.View;
  32. import android.view.WindowManager;
  33. import android.widget.FrameLayout;
  34. import android.widget.ImageView;
  35. import com.nextcloud.client.account.User;
  36. import com.nextcloud.client.network.ConnectivityService;
  37. import com.owncloud.android.MainApp;
  38. import com.owncloud.android.R;
  39. import com.owncloud.android.lib.common.OwnCloudAccount;
  40. import com.owncloud.android.lib.common.OwnCloudClient;
  41. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  42. import com.owncloud.android.lib.common.operations.RemoteOperation;
  43. import com.owncloud.android.lib.common.utils.Log_OC;
  44. import com.owncloud.android.lib.resources.files.model.ImageDimension;
  45. import com.owncloud.android.lib.resources.files.model.ServerFileInterface;
  46. import com.owncloud.android.lib.resources.trashbin.model.TrashbinFile;
  47. import com.owncloud.android.ui.TextDrawable;
  48. import com.owncloud.android.ui.adapter.DiskLruImageCache;
  49. import com.owncloud.android.ui.fragment.FileFragment;
  50. import com.owncloud.android.ui.preview.PreviewImageFragment;
  51. import com.owncloud.android.utils.BitmapUtils;
  52. import com.owncloud.android.utils.DisplayUtils;
  53. import com.owncloud.android.utils.DisplayUtils.AvatarGenerationListener;
  54. import com.owncloud.android.utils.FileStorageUtils;
  55. import com.owncloud.android.utils.MimeTypeUtil;
  56. import com.owncloud.android.utils.theme.ViewThemeUtils;
  57. import org.apache.commons.httpclient.HttpStatus;
  58. import org.apache.commons.httpclient.methods.GetMethod;
  59. import java.io.File;
  60. import java.io.FileNotFoundException;
  61. import java.io.IOException;
  62. import java.io.InputStream;
  63. import java.lang.ref.WeakReference;
  64. import java.net.URLEncoder;
  65. import java.util.List;
  66. import androidx.annotation.NonNull;
  67. import androidx.annotation.Nullable;
  68. import androidx.annotation.VisibleForTesting;
  69. import androidx.core.content.res.ResourcesCompat;
  70. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  71. import kotlin.text.Charsets;
  72. /**
  73. * Manager for concurrent access to thumbnails cache.
  74. */
  75. public final class ThumbnailsCacheManager {
  76. private static final int READ_TIMEOUT = 40000;
  77. private static final int CONNECTION_TIMEOUT = 5000;
  78. public static final String PREFIX_RESIZED_IMAGE = "r";
  79. public static final String PREFIX_THUMBNAIL = "t";
  80. private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
  81. private static final String PNG_MIMETYPE = "image/png";
  82. private static final String CACHE_FOLDER = "thumbnailCache";
  83. public static final String AVATAR = "avatar";
  84. private static final String AVATAR_TIMESTAMP = "avatarTimestamp";
  85. private static final String ETAG = "ETag";
  86. private static final Object mThumbnailsDiskCacheLock = new Object();
  87. private static DiskLruImageCache mThumbnailCache;
  88. private static boolean mThumbnailCacheStarting = true;
  89. private static final int DISK_CACHE_SIZE = 1024 * 1024 * 200; // 200MB
  90. private static final CompressFormat mCompressFormat = CompressFormat.JPEG;
  91. private static final int mCompressQuality = 70;
  92. private static OwnCloudClient mClient;
  93. public static final Bitmap mDefaultImg = BitmapFactory.decodeResource(MainApp.getAppContext().getResources(),
  94. R.drawable.file_image);
  95. public static final Bitmap mDefaultVideo = BitmapFactory.decodeResource(MainApp.getAppContext().getResources(),
  96. R.drawable.file_movie);
  97. private ThumbnailsCacheManager() {
  98. }
  99. public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
  100. @Override
  101. protected Void doInBackground(File... params) {
  102. synchronized (mThumbnailsDiskCacheLock) {
  103. mThumbnailCacheStarting = true;
  104. if (mThumbnailCache == null) {
  105. try {
  106. File cacheDir = MainApp.getAppContext().getCacheDir();
  107. if (cacheDir == null) {
  108. throw new FileNotFoundException("Thumbnail cache could not be opened");
  109. }
  110. String cachePath = cacheDir.getPath() + File.separator + CACHE_FOLDER;
  111. Log_OC.d(TAG, "thumbnail cache dir: " + cachePath);
  112. File diskCacheDir = new File(cachePath);
  113. // migrate from external cache to internal cache
  114. File oldCacheDir = MainApp.getAppContext().getExternalCacheDir();
  115. if (oldCacheDir != null && oldCacheDir.exists()) {
  116. String cacheOldPath = oldCacheDir.getPath() + File.separator + CACHE_FOLDER;
  117. File diskOldCacheDir = new File(cacheOldPath);
  118. FileStorageUtils.copyDirs(diskOldCacheDir, diskCacheDir);
  119. FileStorageUtils.deleteRecursive(diskOldCacheDir);
  120. }
  121. mThumbnailCache = new DiskLruImageCache(diskCacheDir, DISK_CACHE_SIZE, mCompressFormat,
  122. mCompressQuality);
  123. } catch (Exception e) {
  124. Log_OC.d(TAG, "Disk cache init failed", e);
  125. mThumbnailCache = null;
  126. }
  127. }
  128. mThumbnailCacheStarting = false; // Finished initialization
  129. mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
  130. }
  131. return null;
  132. }
  133. }
  134. /**
  135. * Converts size of file icon from dp to pixel
  136. * @return int
  137. */
  138. public static int getThumbnailDimension() {
  139. // Converts dp to pixel
  140. Resources r = MainApp.getAppContext().getResources();
  141. return Math.round(r.getDimension(R.dimen.file_icon_size_grid));
  142. }
  143. /**
  144. * Converts dimension of screen as point
  145. *
  146. * @return Point
  147. */
  148. private static Point getScreenDimension() {
  149. WindowManager wm = (WindowManager) MainApp.getAppContext().getSystemService(Context.WINDOW_SERVICE);
  150. Display display = wm.getDefaultDisplay();
  151. Point point = new Point();
  152. display.getSize(point);
  153. return point;
  154. }
  155. /**
  156. * Add thumbnail to cache
  157. * @param imageKey: thumb key
  158. * @param bitmap: image for extracting thumbnail
  159. * @param path: image path
  160. * @param pxW: thumbnail width in pixel
  161. * @param pxH: thumbnail height in pixel
  162. * @return Bitmap
  163. */
  164. private static Bitmap addThumbnailToCache(String imageKey, Bitmap bitmap, String path, int pxW, int pxH){
  165. Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
  166. // Rotate image, obeying exif tag
  167. thumbnail = BitmapUtils.rotateImage(thumbnail,path);
  168. // Add thumbnail to cache
  169. // do not overwrite any pre-existing image
  170. if (!mThumbnailCache.containsKey(imageKey)) {
  171. addBitmapToCache(imageKey, thumbnail);
  172. }
  173. return thumbnail;
  174. }
  175. public static void addBitmapToCache(String key, Bitmap bitmap) {
  176. synchronized (mThumbnailsDiskCacheLock) {
  177. if (mThumbnailCache != null) {
  178. mThumbnailCache.put(key, bitmap);
  179. }
  180. }
  181. }
  182. public static boolean containsBitmap(String key) {
  183. return mThumbnailCache.containsKey(key);
  184. }
  185. public static Bitmap getScaledBitmapFromDiskCache(String key, int width, int height) {
  186. synchronized (mThumbnailsDiskCacheLock) {
  187. // Wait while disk cache is started from background thread
  188. while (mThumbnailCacheStarting) {
  189. try {
  190. mThumbnailsDiskCacheLock.wait();
  191. } catch (InterruptedException e) {
  192. Log_OC.e(TAG, "Wait in mThumbnailsDiskCacheLock was interrupted", e);
  193. }
  194. }
  195. if (mThumbnailCache != null) {
  196. return mThumbnailCache.getScaledBitmap(key, width, height);
  197. }
  198. }
  199. return null;
  200. }
  201. public static Bitmap getBitmapFromDiskCache(String key) {
  202. synchronized (mThumbnailsDiskCacheLock) {
  203. // Wait while disk cache is started from background thread
  204. while (mThumbnailCacheStarting) {
  205. try {
  206. mThumbnailsDiskCacheLock.wait();
  207. } catch (InterruptedException e) {
  208. Log_OC.e(TAG, "Wait in mThumbnailsDiskCacheLock was interrupted", e);
  209. }
  210. }
  211. if (mThumbnailCache != null) {
  212. return mThumbnailCache.getBitmap(key);
  213. }
  214. }
  215. return null;
  216. }
  217. public static class GalleryImageGenerationTask extends AsyncTask<Object, Void, Bitmap> {
  218. private final User user;
  219. private final FileDataStorageManager storageManager;
  220. private final WeakReference<ImageView> imageViewReference;
  221. private OCFile file;
  222. private String imageKey;
  223. private GalleryListener listener;
  224. private List<GalleryImageGenerationTask> asyncTasks;
  225. private int backgroundColor;
  226. private boolean newImage = false;
  227. public GalleryImageGenerationTask(
  228. ImageView imageView,
  229. User user,
  230. FileDataStorageManager storageManager,
  231. List<GalleryImageGenerationTask> asyncTasks,
  232. String imageKey,
  233. int backgroundColor
  234. ) {
  235. this.user = user;
  236. this.storageManager = storageManager;
  237. imageViewReference = new WeakReference<>(imageView);
  238. this.asyncTasks = asyncTasks;
  239. this.imageKey = imageKey;
  240. this.backgroundColor = backgroundColor;
  241. }
  242. public void setListener(GalleryImageGenerationTask.GalleryListener listener) {
  243. this.listener = listener;
  244. }
  245. public String getImageKey() {
  246. return imageKey;
  247. }
  248. @Override
  249. protected Bitmap doInBackground(Object... params) {
  250. Bitmap thumbnail;
  251. file = (OCFile) params[0];
  252. if (file.getRemoteId() != null || file.isPreviewAvailable()) {
  253. // Thumbnail in cache?
  254. thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
  255. ThumbnailsCacheManager.PREFIX_RESIZED_IMAGE + file.getRemoteId()
  256. );
  257. if (thumbnail != null && !file.isUpdateThumbnailNeeded()) {
  258. Float size = (float) ThumbnailsCacheManager.getThumbnailDimension();
  259. // resized dimensions
  260. ImageDimension imageDimension = file.getImageDimension();
  261. if (imageDimension == null ||
  262. imageDimension.getWidth() != size ||
  263. imageDimension.getHeight() != size) {
  264. file.setImageDimension(new ImageDimension(thumbnail.getWidth(), thumbnail.getHeight()));
  265. storageManager.saveFile(file);
  266. }
  267. if (MimeTypeUtil.isVideo(file)) {
  268. return ThumbnailsCacheManager.addVideoOverlay(thumbnail, MainApp.getAppContext());
  269. } else {
  270. return thumbnail;
  271. }
  272. } else {
  273. try {
  274. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(user.toOwnCloudAccount(),
  275. MainApp.getAppContext());
  276. thumbnail = doResizedImageInBackground(file, storageManager);
  277. newImage = true;
  278. if (MimeTypeUtil.isVideo(file) && thumbnail != null) {
  279. thumbnail = addVideoOverlay(thumbnail, MainApp.getAppContext());
  280. }
  281. } catch (OutOfMemoryError oome) {
  282. Log_OC.e(TAG, "Out of memory");
  283. } catch (Throwable t) {
  284. // the app should never break due to a problem with thumbnails
  285. Log_OC.e(TAG, "Generation of gallery image for " + file + " failed", t);
  286. }
  287. return thumbnail;
  288. }
  289. }
  290. return null;
  291. }
  292. protected void onPostExecute(Bitmap bitmap) {
  293. if (bitmap != null && imageViewReference != null) {
  294. final ImageView imageView = imageViewReference.get();
  295. final GalleryImageGenerationTask bitmapWorkerTask = getGalleryImageGenerationTask(imageView);
  296. if (this == bitmapWorkerTask) {
  297. String tagId = String.valueOf(file.getFileId());
  298. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  299. if ("image/png".equalsIgnoreCase(file.getMimeType())) {
  300. imageView.setBackgroundColor(backgroundColor);
  301. }
  302. if (newImage && listener != null) {
  303. listener.onNewGalleryImage();
  304. }
  305. imageView.setImageBitmap(bitmap);
  306. imageView.invalidate();
  307. }
  308. }
  309. if (listener != null) {
  310. listener.onSuccess();
  311. }
  312. } else {
  313. if (listener != null) {
  314. listener.onError();
  315. }
  316. }
  317. if (asyncTasks != null) {
  318. asyncTasks.remove(this);
  319. }
  320. }
  321. public interface GalleryListener {
  322. void onSuccess();
  323. void onNewGalleryImage();
  324. void onError();
  325. }
  326. }
  327. public static class ResizedImageGenerationTask extends AsyncTask<Object, Void, Bitmap> {
  328. private final FileFragment fileFragment;
  329. private final FileDataStorageManager storageManager;
  330. private final User user;
  331. private final WeakReference<ImageView> imageViewReference;
  332. private final WeakReference<FrameLayout> frameLayoutReference;
  333. private OCFile file;
  334. private final ConnectivityService connectivityService;
  335. private final int backgroundColor;
  336. public ResizedImageGenerationTask(FileFragment fileFragment,
  337. ImageView imageView,
  338. FrameLayout emptyListProgress,
  339. FileDataStorageManager storageManager,
  340. ConnectivityService connectivityService,
  341. User user,
  342. int backgroundColor) throws IllegalArgumentException {
  343. this.fileFragment = fileFragment;
  344. imageViewReference = new WeakReference<>(imageView);
  345. frameLayoutReference = new WeakReference<>(emptyListProgress);
  346. this.storageManager = storageManager;
  347. this.connectivityService = connectivityService;
  348. this.user = user;
  349. this.backgroundColor = backgroundColor;
  350. }
  351. @Override
  352. protected Bitmap doInBackground(Object... params) {
  353. Bitmap thumbnail = null;
  354. file = (OCFile) params[0];
  355. try {
  356. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(user.toOwnCloudAccount(),
  357. MainApp.getAppContext());
  358. thumbnail = doResizedImageInBackground(file, storageManager);
  359. if (MimeTypeUtil.isVideo(file) && thumbnail != null) {
  360. thumbnail = addVideoOverlay(thumbnail, MainApp.getAppContext());
  361. }
  362. } catch (OutOfMemoryError oome) {
  363. Log_OC.e(TAG, "Out of memory");
  364. } catch (Throwable t) {
  365. // the app should never break due to a problem with thumbnails
  366. Log_OC.e(TAG, "Generation of thumbnail for " + file + " failed", t);
  367. }
  368. return thumbnail;
  369. }
  370. protected void onPostExecute(Bitmap bitmap) {
  371. if (imageViewReference != null) {
  372. final ImageView imageView = imageViewReference.get();
  373. final FrameLayout frameLayout = frameLayoutReference.get();
  374. if (bitmap != null) {
  375. final ResizedImageGenerationTask bitmapWorkerTask = getResizedImageGenerationWorkerTask(imageView);
  376. if (this == bitmapWorkerTask) {
  377. String tagId = String.valueOf(file.getFileId());
  378. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  379. imageView.setVisibility(View.VISIBLE);
  380. imageView.setImageBitmap(bitmap);
  381. imageView.setBackgroundColor(backgroundColor);
  382. if (frameLayout != null) {
  383. frameLayout.setVisibility(View.GONE);
  384. }
  385. }
  386. }
  387. } else {
  388. new Thread(() -> {
  389. if (connectivityService.isInternetWalled()) {
  390. if (fileFragment instanceof PreviewImageFragment) {
  391. ((PreviewImageFragment) fileFragment).setNoConnectionErrorMessage();
  392. }
  393. } else {
  394. if (fileFragment instanceof PreviewImageFragment) {
  395. ((PreviewImageFragment) fileFragment).setErrorPreviewMessage();
  396. }
  397. }
  398. }).start();
  399. }
  400. }
  401. }
  402. }
  403. public static class ThumbnailGenerationTaskObject {
  404. private final Object file;
  405. private final String imageKey;
  406. public ThumbnailGenerationTaskObject(Object file, @Nullable String imageKey) {
  407. this.file = file;
  408. this.imageKey = imageKey;
  409. }
  410. private Object getFile() {
  411. return file;
  412. }
  413. private String getImageKey() {
  414. return imageKey;
  415. }
  416. }
  417. public static class ThumbnailGenerationTask extends AsyncTask<ThumbnailGenerationTaskObject, Void, Bitmap> {
  418. private final WeakReference<ImageView> mImageViewReference;
  419. private User user;
  420. private List<ThumbnailGenerationTask> mAsyncTasks;
  421. private Object mFile;
  422. private String mImageKey;
  423. private FileDataStorageManager mStorageManager;
  424. private GetMethod getMethod;
  425. private Listener mListener;
  426. private boolean gridViewEnabled = false;
  427. public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager, User user)
  428. throws IllegalArgumentException {
  429. this(imageView, storageManager, user, null);
  430. }
  431. public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager,
  432. User user, List<ThumbnailGenerationTask> asyncTasks)
  433. throws IllegalArgumentException {
  434. // Use a WeakReference to ensure the ImageView can be garbage collected
  435. mImageViewReference = new WeakReference<>(imageView);
  436. if (storageManager == null) {
  437. throw new IllegalArgumentException("storageManager must not be NULL");
  438. }
  439. mStorageManager = storageManager;
  440. this.user = user;
  441. mAsyncTasks = asyncTasks;
  442. }
  443. public ThumbnailGenerationTask(ImageView imageView,
  444. FileDataStorageManager storageManager,
  445. User user,
  446. List<ThumbnailGenerationTask> asyncTasks,
  447. boolean gridViewEnabled,
  448. String imageKey)
  449. throws IllegalArgumentException {
  450. this(imageView, storageManager, user, asyncTasks);
  451. this.gridViewEnabled = gridViewEnabled;
  452. mImageKey = imageKey;
  453. }
  454. public GetMethod getGetMethod() {
  455. return getMethod;
  456. }
  457. public String getImageKey() {
  458. return mImageKey;
  459. }
  460. public ThumbnailGenerationTask(FileDataStorageManager storageManager, User user) {
  461. if (storageManager == null) {
  462. throw new IllegalArgumentException("storageManager must not be NULL");
  463. }
  464. mStorageManager = storageManager;
  465. this.user = user;
  466. mImageViewReference = null;
  467. }
  468. public ThumbnailGenerationTask(ImageView imageView) {
  469. // Use a WeakReference to ensure the ImageView can be garbage collected
  470. mImageViewReference = new WeakReference<>(imageView);
  471. }
  472. @SuppressFBWarnings("Dm")
  473. @Override
  474. protected Bitmap doInBackground(ThumbnailGenerationTaskObject... params) {
  475. Bitmap thumbnail = null;
  476. try {
  477. if (user != null) {
  478. OwnCloudAccount ocAccount = user.toOwnCloudAccount();
  479. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  480. getClientFor(ocAccount, MainApp.getAppContext());
  481. }
  482. ThumbnailGenerationTaskObject object = params[0];
  483. mFile = object.getFile();
  484. mImageKey = object.getImageKey();
  485. if (mFile instanceof ServerFileInterface) {
  486. thumbnail = doThumbnailFromOCFileInBackground();
  487. if (MimeTypeUtil.isVideo((ServerFileInterface) mFile) && thumbnail != null) {
  488. thumbnail = addVideoOverlay(thumbnail, MainApp.getAppContext());
  489. }
  490. } else if (mFile instanceof File) {
  491. thumbnail = doFileInBackground();
  492. String url = ((File) mFile).getAbsolutePath();
  493. String mMimeType = FileStorageUtils.getMimeTypeFromName(url);
  494. if (MimeTypeUtil.isVideo(mMimeType) && thumbnail != null) {
  495. thumbnail = addVideoOverlay(thumbnail, MainApp.getAppContext());
  496. }
  497. //} else { do nothing
  498. }
  499. } catch(OutOfMemoryError oome) {
  500. Log_OC.e(TAG, "Out of memory");
  501. } catch (Throwable t) {
  502. // the app should never break due to a problem with thumbnails
  503. Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
  504. }
  505. return thumbnail;
  506. }
  507. protected void onPostExecute(Bitmap bitmap) {
  508. if (bitmap != null && mImageViewReference != null) {
  509. final ImageView imageView = mImageViewReference.get();
  510. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  511. if (this == bitmapWorkerTask) {
  512. String tagId = "";
  513. if (mFile instanceof OCFile) {
  514. tagId = String.valueOf(((OCFile)mFile).getFileId());
  515. } else if (mFile instanceof File) {
  516. tagId = String.valueOf(mFile.hashCode());
  517. } else if (mFile instanceof TrashbinFile) {
  518. tagId = String.valueOf(((TrashbinFile) mFile).getRemoteId());
  519. }
  520. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  521. if (gridViewEnabled) {
  522. BitmapUtils.setRoundedBitmapForGridMode(bitmap, imageView);
  523. } else {
  524. BitmapUtils.setRoundedBitmap(bitmap, imageView);
  525. }
  526. }
  527. }
  528. if (mListener != null) {
  529. mListener.onSuccess();
  530. }
  531. } else {
  532. if (mListener != null) {
  533. mListener.onError();
  534. }
  535. }
  536. if (mAsyncTasks != null) {
  537. mAsyncTasks.remove(this);
  538. }
  539. }
  540. public void setListener(Listener listener){
  541. mListener = listener;
  542. }
  543. private Bitmap doThumbnailFromOCFileInBackground() {
  544. Bitmap thumbnail;
  545. ServerFileInterface file = (ServerFileInterface) mFile;
  546. String imageKey = PREFIX_THUMBNAIL + file.getRemoteId();
  547. boolean updateEnforced = (file instanceof OCFile && ((OCFile) file).isUpdateThumbnailNeeded());
  548. if (updateEnforced) {
  549. thumbnail = null;
  550. } else {
  551. // Check disk cache in background thread
  552. thumbnail = getBitmapFromDiskCache(imageKey);
  553. }
  554. // Not found in disk cache
  555. if (thumbnail == null) {
  556. int pxW;
  557. int pxH;
  558. pxW = pxH = getThumbnailDimension();
  559. if (file instanceof OCFile) {
  560. OCFile ocFile = (OCFile) file;
  561. if (ocFile.isDown()) {
  562. Bitmap bitmap;
  563. if (MimeTypeUtil.isVideo(ocFile)) {
  564. bitmap = ThumbnailUtils.createVideoThumbnail(ocFile.getStoragePath(),
  565. MediaStore.Images.Thumbnails.MINI_KIND);
  566. } else {
  567. bitmap = BitmapUtils.decodeSampledBitmapFromFile(ocFile.getStoragePath(), pxW, pxH);
  568. }
  569. if (bitmap != null) {
  570. // Handle PNG
  571. if (PNG_MIMETYPE.equalsIgnoreCase(ocFile.getMimeType())) {
  572. bitmap = handlePNG(bitmap, pxW, pxH);
  573. }
  574. thumbnail = addThumbnailToCache(imageKey, bitmap, ocFile.getStoragePath(), pxW, pxH);
  575. ocFile.setUpdateThumbnailNeeded(false);
  576. mStorageManager.saveFile(ocFile);
  577. }
  578. }
  579. }
  580. if (thumbnail == null) {
  581. // check if resized version is available
  582. String resizedImageKey = PREFIX_RESIZED_IMAGE + file.getRemoteId();
  583. Bitmap resizedImage;
  584. if (updateEnforced) {
  585. resizedImage = null;
  586. } else {
  587. resizedImage = getBitmapFromDiskCache(resizedImageKey);
  588. }
  589. if (resizedImage != null) {
  590. thumbnail = ThumbnailUtils.extractThumbnail(resizedImage, pxW, pxH);
  591. } else {
  592. // Download thumbnail from server
  593. if (mClient != null) {
  594. getMethod = null;
  595. try {
  596. // thumbnail
  597. String uri;
  598. if (file instanceof OCFile) {
  599. uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
  600. pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
  601. } else {
  602. uri = mClient.getBaseUri() + "/index.php/apps/files_trashbin/preview?fileId=" +
  603. file.getLocalId() + "&x=" + pxW + "&y=" + pxH;
  604. }
  605. Log_OC.d(TAG, "generate thumbnail: " + file.getFileName() + " URI: " + uri);
  606. getMethod = new GetMethod(uri);
  607. getMethod.setRequestHeader("Cookie",
  608. "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
  609. getMethod.setRequestHeader(RemoteOperation.OCS_API_HEADER,
  610. RemoteOperation.OCS_API_HEADER_VALUE);
  611. int status = mClient.executeMethod(getMethod, READ_TIMEOUT, CONNECTION_TIMEOUT);
  612. if (status == HttpStatus.SC_OK) {
  613. InputStream inputStream = getMethod.getResponseBodyAsStream();
  614. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  615. thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
  616. } else {
  617. mClient.exhaustResponse(getMethod.getResponseBodyAsStream());
  618. }
  619. // Handle PNG
  620. if (PNG_MIMETYPE.equalsIgnoreCase(file.getMimeType())) {
  621. thumbnail = handlePNG(thumbnail, pxW, pxH);
  622. }
  623. } catch (Exception e) {
  624. Log_OC.d(TAG, e.getMessage(), e);
  625. } finally {
  626. if (getMethod != null) {
  627. getMethod.releaseConnection();
  628. }
  629. }
  630. }
  631. }
  632. // Add thumbnail to cache
  633. if (thumbnail != null) {
  634. Log_OC.d(TAG, "add thumbnail to cache: " + file.getFileName());
  635. addBitmapToCache(imageKey, thumbnail);
  636. }
  637. }
  638. }
  639. return thumbnail;
  640. }
  641. /**
  642. * Converts size of file icon from dp to pixel
  643. *
  644. * @return int
  645. */
  646. private int getThumbnailDimension() {
  647. // Converts dp to pixel
  648. Resources r = MainApp.getAppContext().getResources();
  649. Double d = Math.pow(2, Math.floor(Math.log(r.getDimension(R.dimen.file_icon_size_grid)) / Math.log(2)));
  650. return d.intValue();
  651. }
  652. private Bitmap doFileInBackground() {
  653. File file = (File)mFile;
  654. final String imageKey;
  655. if (mImageKey != null) {
  656. imageKey = mImageKey;
  657. } else {
  658. imageKey = String.valueOf(file.hashCode());
  659. }
  660. // local file should always generate a thumbnail
  661. mImageKey = PREFIX_THUMBNAIL + mImageKey;
  662. // Check disk cache in background thread
  663. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  664. // Not found in disk cache
  665. if (thumbnail == null) {
  666. int pxW;
  667. int pxH;
  668. pxW = pxH = getThumbnailDimension();
  669. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getAbsolutePath(), pxW, pxH);
  670. if (bitmap != null) {
  671. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), pxW, pxH);
  672. }
  673. }
  674. return thumbnail;
  675. }
  676. public interface Listener{
  677. void onSuccess();
  678. void onError();
  679. }
  680. }
  681. public static class MediaThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
  682. private static final int IMAGE_KEY_PARAMS_LENGTH = 2;
  683. private enum Type {IMAGE, VIDEO}
  684. private final WeakReference<ImageView> mImageViewReference;
  685. private File mFile;
  686. private String mImageKey;
  687. private final Context mContext;
  688. private final ViewThemeUtils viewThemeUtils;
  689. public MediaThumbnailGenerationTask(ImageView imageView,
  690. Context context,
  691. ViewThemeUtils viewThemeUtils) {
  692. // Use a WeakReference to ensure the ImageView can be garbage collected
  693. mImageViewReference = new WeakReference<>(imageView);
  694. mContext = context;
  695. this.viewThemeUtils = viewThemeUtils;
  696. }
  697. @Override
  698. protected Bitmap doInBackground(Object... params) {
  699. Bitmap thumbnail = null;
  700. try {
  701. if (params[0] instanceof File) {
  702. mFile = (File) params[0];
  703. if (params.length == IMAGE_KEY_PARAMS_LENGTH) {
  704. mImageKey = (String) params[1];
  705. }
  706. if (MimeTypeUtil.isImage(mFile)) {
  707. thumbnail = doFileInBackground(mFile, Type.IMAGE);
  708. } else if (MimeTypeUtil.isVideo(mFile)) {
  709. thumbnail = doFileInBackground(mFile, Type.VIDEO);
  710. }
  711. }
  712. } // the app should never break due to a problem with thumbnails
  713. catch (OutOfMemoryError t) {
  714. Log_OC.e(TAG, "Generation of thumbnail for " + mFile.getAbsolutePath() + " failed", t);
  715. Log_OC.e(TAG, "Out of memory");
  716. } catch (Throwable t) {
  717. // the app should never break due to a problem with thumbnails
  718. Log_OC.e(TAG, "Generation of thumbnail for " + mFile.getAbsolutePath() + " failed", t);
  719. }
  720. return thumbnail;
  721. }
  722. protected void onPostExecute(Bitmap bitmap) {
  723. String tagId = "";
  724. final ImageView imageView = mImageViewReference.get();
  725. if (imageView != null) {
  726. if (mFile != null) {
  727. tagId = String.valueOf(mFile.hashCode());
  728. }
  729. if (bitmap != null) {
  730. if (tagId.equals(String.valueOf(imageView.getTag()))) {
  731. imageView.setImageBitmap(bitmap);
  732. }
  733. } else {
  734. if (mFile != null) {
  735. if (mFile.isDirectory()) {
  736. imageView.setImageDrawable(MimeTypeUtil.getDefaultFolderIcon(mContext, viewThemeUtils));
  737. } else {
  738. if (MimeTypeUtil.isVideo(mFile)) {
  739. imageView.setImageBitmap(ThumbnailsCacheManager.mDefaultVideo);
  740. } else {
  741. imageView.setImageDrawable(MimeTypeUtil.getFileTypeIcon(null,
  742. mFile.getName(),
  743. mContext,
  744. viewThemeUtils));
  745. }
  746. }
  747. }
  748. }
  749. }
  750. }
  751. private Bitmap doFileInBackground(File file, Type type) {
  752. final String imageKey;
  753. if (mImageKey != null) {
  754. imageKey = mImageKey;
  755. } else {
  756. imageKey = String.valueOf(file.hashCode());
  757. }
  758. // Check disk cache in background thread
  759. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  760. // Not found in disk cache
  761. if (thumbnail == null) {
  762. if (Type.IMAGE == type) {
  763. int px = getThumbnailDimension();
  764. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getAbsolutePath(), px, px);
  765. if (bitmap != null) {
  766. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), px, px);
  767. }
  768. } else if (Type.VIDEO == type) {
  769. MediaMetadataRetriever retriever = new MediaMetadataRetriever();
  770. try {
  771. retriever.setDataSource(file.getAbsolutePath());
  772. thumbnail = retriever.getFrameAtTime(-1);
  773. } catch (Exception ex) {
  774. // can't create a bitmap
  775. Log_OC.w(TAG, "Failed to create bitmap from video " + file.getAbsolutePath());
  776. } finally {
  777. try {
  778. retriever.release();
  779. } catch (RuntimeException | IOException ex) {
  780. // Ignore failure at this point.
  781. Log_OC.w(TAG, "Failed release MediaMetadataRetriever for " + file.getAbsolutePath());
  782. }
  783. }
  784. if (thumbnail != null) {
  785. // Scale down bitmap if too large.
  786. int px = getThumbnailDimension();
  787. int width = thumbnail.getWidth();
  788. int height = thumbnail.getHeight();
  789. int max = Math.max(width, height);
  790. if (max > px) {
  791. thumbnail = BitmapUtils.scaleBitmap(thumbnail, px, width, height, max);
  792. thumbnail = addThumbnailToCache(imageKey, thumbnail, file.getPath(), px, px);
  793. }
  794. }
  795. }
  796. }
  797. return thumbnail;
  798. }
  799. }
  800. public static class AvatarGenerationTask extends AsyncTask<String, Void, Drawable> {
  801. private final WeakReference<AvatarGenerationListener> mAvatarGenerationListener;
  802. private final Object mCallContext;
  803. private final Resources mResources;
  804. private final float mAvatarRadius;
  805. private final User user;
  806. private final String mUserId;
  807. private final String displayName;
  808. private final String mServerName;
  809. private final Context mContext;
  810. public AvatarGenerationTask(AvatarGenerationListener avatarGenerationListener,
  811. Object callContext,
  812. User user,
  813. Resources resources,
  814. float avatarRadius,
  815. String userId,
  816. String displayName,
  817. String serverName,
  818. Context context) {
  819. mAvatarGenerationListener = new WeakReference<>(avatarGenerationListener);
  820. mCallContext = callContext;
  821. this.user = user;
  822. mResources = resources;
  823. mAvatarRadius = avatarRadius;
  824. mUserId = userId;
  825. this.displayName = displayName;
  826. mServerName = serverName;
  827. mContext = context;
  828. }
  829. @SuppressFBWarnings("Dm")
  830. @Override
  831. protected Drawable doInBackground(String... params) {
  832. Drawable thumbnail = null;
  833. try {
  834. thumbnail = doAvatarInBackground();
  835. } catch (OutOfMemoryError oome) {
  836. Log_OC.e(TAG, "Out of memory");
  837. } catch (Throwable t) {
  838. // the app should never break due to a problem with avatars
  839. thumbnail = ResourcesCompat.getDrawable(mResources, R.drawable.account_circle_white, null);
  840. Log_OC.e(TAG, "Generation of avatar for " + mUserId + " failed", t);
  841. }
  842. return thumbnail;
  843. }
  844. protected void onPostExecute(Drawable drawable) {
  845. if (drawable != null) {
  846. AvatarGenerationListener listener = mAvatarGenerationListener.get();
  847. if (listener != null) {
  848. String accountName = mUserId + "@" + mServerName;
  849. if (listener.shouldCallGeneratedCallback(accountName, mCallContext)) {
  850. listener.avatarGenerated(drawable, mCallContext);
  851. }
  852. }
  853. }
  854. }
  855. /**
  856. * Converts size of file icon from dp to pixel
  857. *
  858. * @return int
  859. */
  860. private int getAvatarDimension() {
  861. // Converts dp to pixel
  862. Resources r = MainApp.getAppContext().getResources();
  863. return Math.round(r.getDimension(R.dimen.file_avatar_size));
  864. }
  865. private @NonNull
  866. Drawable doAvatarInBackground() {
  867. Bitmap avatar;
  868. String accountName = mUserId + "@" + mServerName;
  869. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProviderImpl(mContext);
  870. String eTag = arbitraryDataProvider.getValue(accountName, ThumbnailsCacheManager.AVATAR);
  871. long timestamp = arbitraryDataProvider.getLongValue(accountName, ThumbnailsCacheManager.AVATAR_TIMESTAMP);
  872. String avatarKey = "a_" + mUserId + "_" + mServerName + "_" + eTag;
  873. avatar = getBitmapFromDiskCache(avatarKey);
  874. // Download avatar from server, only if older than 60 min or avatar does not exist
  875. if (System.currentTimeMillis() - timestamp >= 60 * 60 * 1000 || avatar == null) {
  876. GetMethod get = null;
  877. try {
  878. if (user != null) {
  879. OwnCloudAccount ocAccount = user.toOwnCloudAccount();
  880. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, mContext);
  881. }
  882. int px = mResources.getInteger(R.integer.file_avatar_px);
  883. String uri = mClient.getBaseUri() + "/index.php/avatar/" + Uri.encode(mUserId) + "/" + px;
  884. Log_OC.d("Avatar", "URI: " + uri);
  885. get = new GetMethod(uri);
  886. // only use eTag if available and corresponding avatar is still there
  887. // (might be deleted from cache)
  888. if (!eTag.isEmpty() && avatar != null) {
  889. get.setRequestHeader("If-None-Match", eTag);
  890. }
  891. int status = mClient.executeMethod(get);
  892. // we are using eTag to download a new avatar only if it changed
  893. switch (status) {
  894. case HttpStatus.SC_OK:
  895. case HttpStatus.SC_CREATED:
  896. // new avatar
  897. InputStream inputStream = get.getResponseBodyAsStream();
  898. String newETag = null;
  899. if (get.getResponseHeader(ETAG) != null) {
  900. newETag = get.getResponseHeader(ETAG).getValue().replace("\"", "");
  901. arbitraryDataProvider.storeOrUpdateKeyValue(accountName, AVATAR, newETag);
  902. }
  903. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  904. avatar = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  905. // Add avatar to cache
  906. if (avatar != null && !TextUtils.isEmpty(newETag)) {
  907. avatar = handlePNG(avatar, px, px);
  908. String newImageKey = "a_" + mUserId + "_" + mServerName + "_" + newETag;
  909. addBitmapToCache(newImageKey, avatar);
  910. arbitraryDataProvider.storeOrUpdateKeyValue(accountName,
  911. ThumbnailsCacheManager.AVATAR_TIMESTAMP,
  912. System.currentTimeMillis());
  913. } else {
  914. return TextDrawable.createAvatar(user, mAvatarRadius);
  915. }
  916. break;
  917. case HttpStatus.SC_NOT_MODIFIED:
  918. // old avatar
  919. mClient.exhaustResponse(get.getResponseBodyAsStream());
  920. arbitraryDataProvider.storeOrUpdateKeyValue(accountName,
  921. ThumbnailsCacheManager.AVATAR_TIMESTAMP,
  922. System.currentTimeMillis());
  923. break;
  924. default:
  925. // everything else
  926. mClient.exhaustResponse(get.getResponseBodyAsStream());
  927. break;
  928. }
  929. } catch (Exception e) {
  930. try {
  931. return TextDrawable.createAvatar(user, mAvatarRadius);
  932. } catch (Exception e1) {
  933. Log_OC.e(TAG, "Error generating fallback avatar");
  934. }
  935. } finally {
  936. if (get != null) {
  937. get.releaseConnection();
  938. }
  939. }
  940. }
  941. if (avatar == null) {
  942. try {
  943. return TextDrawable.createAvatarByUserId(displayName, mAvatarRadius);
  944. } catch (Exception e1) {
  945. return ResourcesCompat.getDrawable(mResources, R.drawable.ic_user, null);
  946. }
  947. } else {
  948. return BitmapUtils.bitmapToCircularBitmapDrawable(mResources, avatar);
  949. }
  950. }
  951. }
  952. public static boolean cancelPotentialThumbnailWork(Object file, ImageView imageView) {
  953. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  954. if (bitmapWorkerTask != null) {
  955. final Object bitmapData = bitmapWorkerTask.mFile;
  956. // If bitmapData is not yet set or it differs from the new data
  957. if (bitmapData == null || !bitmapData.equals(file)) {
  958. // Cancel previous task
  959. bitmapWorkerTask.cancel(true);
  960. Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView");
  961. } else {
  962. // The same work is already in progress
  963. return false;
  964. }
  965. }
  966. // No task associated with the ImageView, or an existing task was cancelled
  967. return true;
  968. }
  969. public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
  970. if (imageView != null) {
  971. final Drawable drawable = imageView.getDrawable();
  972. if (drawable instanceof AsyncThumbnailDrawable) {
  973. final AsyncThumbnailDrawable asyncDrawable = (AsyncThumbnailDrawable) drawable;
  974. return asyncDrawable.getBitmapWorkerTask();
  975. }
  976. }
  977. return null;
  978. }
  979. private static ResizedImageGenerationTask getResizedImageGenerationWorkerTask(ImageView imageView) {
  980. if (imageView != null) {
  981. final Drawable drawable = imageView.getDrawable();
  982. if (drawable instanceof AsyncResizedImageDrawable) {
  983. final AsyncResizedImageDrawable asyncDrawable = (AsyncResizedImageDrawable) drawable;
  984. return asyncDrawable.getBitmapWorkerTask();
  985. }
  986. }
  987. return null;
  988. }
  989. private static GalleryImageGenerationTask getGalleryImageGenerationTask(ImageView imageView) {
  990. if (imageView != null) {
  991. final Drawable drawable = imageView.getDrawable();
  992. if (drawable instanceof AsyncGalleryImageDrawable) {
  993. final AsyncGalleryImageDrawable asyncDrawable = (AsyncGalleryImageDrawable) drawable;
  994. return asyncDrawable.getBitmapWorkerTask();
  995. }
  996. }
  997. return null;
  998. }
  999. public static Bitmap addVideoOverlay(Bitmap thumbnail, Context context) {
  1000. Drawable playButtonDrawable = ResourcesCompat.getDrawable(MainApp.getAppContext().getResources(),
  1001. R.drawable.video_white,
  1002. null);
  1003. int px = DisplayUtils.convertDpToPixel(24f, context);
  1004. Bitmap playButton = BitmapUtils.drawableToBitmap(playButtonDrawable, px, px);
  1005. Bitmap resizedPlayButton = Bitmap.createScaledBitmap(playButton, px, px, true);
  1006. Bitmap resultBitmap = Bitmap.createBitmap(thumbnail.getWidth(),
  1007. thumbnail.getHeight(),
  1008. Bitmap.Config.ARGB_8888);
  1009. Canvas c = new Canvas(resultBitmap);
  1010. c.drawBitmap(thumbnail, 0, 0, null);
  1011. Paint p = new Paint();
  1012. p.setAlpha(230);
  1013. c.drawBitmap(resizedPlayButton, px, px, p);
  1014. return resultBitmap;
  1015. }
  1016. public static class AsyncThumbnailDrawable extends BitmapDrawable {
  1017. private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
  1018. public AsyncThumbnailDrawable(
  1019. Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
  1020. ) {
  1021. super(res, bitmap);
  1022. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  1023. }
  1024. public ThumbnailGenerationTask getBitmapWorkerTask() {
  1025. return bitmapWorkerTaskReference.get();
  1026. }
  1027. }
  1028. public static class AsyncResizedImageDrawable extends BitmapDrawable {
  1029. private final WeakReference<ResizedImageGenerationTask> bitmapWorkerTaskReference;
  1030. public AsyncResizedImageDrawable(Resources res, Bitmap bitmap, ResizedImageGenerationTask bitmapWorkerTask) {
  1031. super(res, bitmap);
  1032. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  1033. }
  1034. private ResizedImageGenerationTask getBitmapWorkerTask() {
  1035. return bitmapWorkerTaskReference.get();
  1036. }
  1037. }
  1038. public static class AsyncGalleryImageDrawable extends BitmapDrawable {
  1039. private final WeakReference<GalleryImageGenerationTask> bitmapWorkerTaskReference;
  1040. public AsyncGalleryImageDrawable(Resources res, Bitmap bitmap, GalleryImageGenerationTask bitmapWorkerTask) {
  1041. super(res, bitmap);
  1042. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  1043. }
  1044. private GalleryImageGenerationTask getBitmapWorkerTask() {
  1045. return bitmapWorkerTaskReference.get();
  1046. }
  1047. }
  1048. public static class AsyncMediaThumbnailDrawable extends BitmapDrawable {
  1049. public AsyncMediaThumbnailDrawable(Resources res, Bitmap bitmap) {
  1050. super(res, bitmap);
  1051. }
  1052. }
  1053. /**
  1054. * adapted from https://stackoverflow.com/a/8113368
  1055. */
  1056. private static Bitmap handlePNG(Bitmap source, int newWidth, int newHeight) {
  1057. int sourceWidth = source.getWidth();
  1058. int sourceHeight = source.getHeight();
  1059. float xScale = (float) newWidth / sourceWidth;
  1060. float yScale = (float) newHeight / sourceHeight;
  1061. float scale = Math.max(xScale, yScale);
  1062. float scaledWidth = scale * sourceWidth;
  1063. float scaledHeight = scale * sourceHeight;
  1064. float left = (newWidth - scaledWidth) / 2;
  1065. float top = (newHeight - scaledHeight) / 2;
  1066. RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
  1067. Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
  1068. Canvas canvas = new Canvas(dest);
  1069. canvas.drawColor(MainApp.getAppContext().getResources().getColor(R.color.background_color_png));
  1070. canvas.drawBitmap(source, null, targetRect, null);
  1071. return dest;
  1072. }
  1073. public static void generateResizedImage(OCFile file) {
  1074. Point p = getScreenDimension();
  1075. int pxW = p.x;
  1076. int pxH = p.y;
  1077. String imageKey = PREFIX_RESIZED_IMAGE + file.getRemoteId();
  1078. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getStoragePath(), pxW, pxH);
  1079. if (bitmap != null) {
  1080. // Handle PNG
  1081. if (PNG_MIMETYPE.equalsIgnoreCase(file.getMimeType())) {
  1082. bitmap = handlePNG(bitmap, pxW, pxH);
  1083. }
  1084. addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
  1085. }
  1086. }
  1087. public static void generateThumbnailFromOCFile(OCFile file, User user, Context context) {
  1088. int pxW;
  1089. int pxH;
  1090. pxW = pxH = getThumbnailDimension();
  1091. String imageKey = PREFIX_THUMBNAIL + file.getRemoteId();
  1092. GetMethod getMethod = null;
  1093. try {
  1094. Bitmap thumbnail = null;
  1095. OwnCloudClient client = mClient;
  1096. if (client == null) {
  1097. OwnCloudAccount ocAccount = user.toOwnCloudAccount();
  1098. client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context);
  1099. }
  1100. String uri = client.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
  1101. pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
  1102. Log_OC.d(TAG, "generate thumbnail: " + file.getFileName() + " URI: " + uri);
  1103. getMethod = new GetMethod(uri);
  1104. getMethod.setRequestHeader("Cookie", "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
  1105. getMethod.setRequestHeader(RemoteOperation.OCS_API_HEADER,
  1106. RemoteOperation.OCS_API_HEADER_VALUE);
  1107. int status = client.executeMethod(getMethod);
  1108. if (status == HttpStatus.SC_OK) {
  1109. InputStream inputStream = getMethod.getResponseBodyAsStream();
  1110. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  1111. thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
  1112. } else {
  1113. client.exhaustResponse(getMethod.getResponseBodyAsStream());
  1114. }
  1115. // Add thumbnail to cache
  1116. if (thumbnail != null) {
  1117. // Handle PNG
  1118. if (PNG_MIMETYPE.equalsIgnoreCase(file.getMimeType())) {
  1119. thumbnail = handlePNG(thumbnail, pxW, pxH);
  1120. }
  1121. Log_OC.d(TAG, "add thumbnail to cache: " + file.getFileName());
  1122. addBitmapToCache(imageKey, thumbnail);
  1123. }
  1124. } catch (Exception e) {
  1125. Log_OC.d(TAG, e.getMessage(), e);
  1126. } finally {
  1127. if (getMethod != null) {
  1128. getMethod.releaseConnection();
  1129. }
  1130. }
  1131. }
  1132. @VisibleForTesting
  1133. public static void clearCache() {
  1134. mThumbnailCache.clearCache();
  1135. mThumbnailCache = null;
  1136. }
  1137. private static Bitmap doResizedImageInBackground(OCFile file, FileDataStorageManager storageManager) {
  1138. Bitmap thumbnail;
  1139. String imageKey = PREFIX_RESIZED_IMAGE + file.getRemoteId();
  1140. // Check disk cache in background thread
  1141. thumbnail = getBitmapFromDiskCache(imageKey);
  1142. // Not found in disk cache
  1143. if (thumbnail == null || file.isUpdateThumbnailNeeded()) {
  1144. Point p = getScreenDimension();
  1145. int pxW = p.x;
  1146. int pxH = p.y;
  1147. if (file.isDown()) {
  1148. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getStoragePath(), pxW, pxH);
  1149. if (bitmap != null) {
  1150. // Handle PNG
  1151. if (PNG_MIMETYPE.equalsIgnoreCase(file.getMimeType())) {
  1152. bitmap = handlePNG(bitmap, pxW, pxH);
  1153. }
  1154. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
  1155. file.setUpdateThumbnailNeeded(false);
  1156. }
  1157. } else {
  1158. // Download thumbnail from server
  1159. if (mClient != null) {
  1160. GetMethod getMethod = null;
  1161. try {
  1162. String uri = mClient.getBaseUri() + "/index.php/core/preview.png?file="
  1163. + URLEncoder.encode(file.getRemotePath(), Charsets.UTF_8.name())
  1164. + "&x=" + (pxW / 2) + "&y=" + (pxH / 2) + "&a=1&mode=cover&forceIcon=0";
  1165. Log_OC.d(TAG, "generate resized image: " + file.getFileName() + " URI: " + uri);
  1166. getMethod = new GetMethod(uri);
  1167. int status = mClient.executeMethod(getMethod);
  1168. if (status == HttpStatus.SC_OK) {
  1169. InputStream inputStream = getMethod.getResponseBodyAsStream();
  1170. thumbnail = BitmapFactory.decodeStream(inputStream);
  1171. } else {
  1172. mClient.exhaustResponse(getMethod.getResponseBodyAsStream());
  1173. }
  1174. // Handle PNG
  1175. if (thumbnail != null && PNG_MIMETYPE.equalsIgnoreCase(file.getMimeType())) {
  1176. thumbnail = handlePNG(thumbnail, thumbnail.getWidth(), thumbnail.getHeight());
  1177. }
  1178. // Add thumbnail to cache
  1179. if (thumbnail != null) {
  1180. Log_OC.d(TAG, "add resized image to cache: " + file.getFileName());
  1181. addBitmapToCache(imageKey, thumbnail);
  1182. }
  1183. } catch (Exception e) {
  1184. Log_OC.d(TAG, e.getMessage(), e);
  1185. } finally {
  1186. if (getMethod != null) {
  1187. getMethod.releaseConnection();
  1188. }
  1189. }
  1190. }
  1191. }
  1192. // resized dimensions and set update thumbnail needed to false to prevent rendering loop
  1193. if (thumbnail != null) {
  1194. file.setImageDimension(new ImageDimension(thumbnail.getWidth(), thumbnail.getHeight()));
  1195. storageManager.saveFile(file);
  1196. }
  1197. }
  1198. return thumbnail;
  1199. }
  1200. }