ThumbnailsCacheManager.java 53 KB

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