ThumbnailsCacheManager.java 49 KB

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