ThumbnailsCacheManager.java 50 KB

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