ThumbnailsCacheManager.java 59 KB

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