ThumbnailsCacheManager.java 50 KB

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