ThumbnailsCacheManager.java 52 KB

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