ThumbnailsCacheManager.java 52 KB

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