ThumbnailsCacheManager.java 52 KB

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