ThumbnailsCacheManager.java 52 KB

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