ThumbnailsCacheManager.java 53 KB

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