ThumbnailsCacheManager.java 51 KB

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