ThumbnailsCacheManager.java 53 KB

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