ThumbnailsCacheManager.java 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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 Listener mListener;
  363. private boolean gridViewEnabled = false;
  364. public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager, Account account)
  365. throws IllegalArgumentException {
  366. this(imageView, storageManager, account, null);
  367. }
  368. public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager,
  369. Account account, List<ThumbnailGenerationTask> asyncTasks)
  370. throws IllegalArgumentException {
  371. // Use a WeakReference to ensure the ImageView can be garbage collected
  372. mImageViewReference = new WeakReference<>(imageView);
  373. if (storageManager == null) {
  374. throw new IllegalArgumentException("storageManager must not be NULL");
  375. }
  376. mStorageManager = storageManager;
  377. mAccount = account;
  378. mAsyncTasks = asyncTasks;
  379. }
  380. public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager,
  381. Account account, List<ThumbnailGenerationTask> asyncTasks,
  382. boolean gridViewEnabled)
  383. throws IllegalArgumentException {
  384. this(imageView, storageManager, account, asyncTasks);
  385. this.gridViewEnabled = gridViewEnabled;
  386. }
  387. public GetMethod getGetMethod() {
  388. return getMethod;
  389. }
  390. public ThumbnailGenerationTask(FileDataStorageManager storageManager, Account account){
  391. if (storageManager == null) {
  392. throw new IllegalArgumentException("storageManager must not be NULL");
  393. }
  394. mStorageManager = storageManager;
  395. mAccount = account;
  396. mImageViewReference = null;
  397. }
  398. public ThumbnailGenerationTask(ImageView imageView) {
  399. // Use a WeakReference to ensure the ImageView can be garbage collected
  400. mImageViewReference = new WeakReference<>(imageView);
  401. }
  402. @SuppressFBWarnings("Dm")
  403. @Override
  404. protected Bitmap doInBackground(ThumbnailGenerationTaskObject... params) {
  405. Bitmap thumbnail = null;
  406. boolean isError = false;
  407. try {
  408. if (mAccount != null) {
  409. OwnCloudAccount ocAccount = new OwnCloudAccount(
  410. mAccount,
  411. MainApp.getAppContext()
  412. );
  413. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  414. getClientFor(ocAccount, MainApp.getAppContext());
  415. }
  416. ThumbnailGenerationTaskObject object = params[0];
  417. mFile = object.getFile();
  418. mImageKey = object.getImageKey();
  419. if (mFile instanceof ServerFileInterface) {
  420. thumbnail = doThumbnailFromOCFileInBackground();
  421. if (MimeTypeUtil.isVideo((ServerFileInterface) mFile) && thumbnail != null) {
  422. thumbnail = addVideoOverlay(thumbnail);
  423. }
  424. } else if (mFile instanceof File) {
  425. thumbnail = doFileInBackground();
  426. String url = ((File) mFile).getAbsolutePath();
  427. String mMimeType = FileStorageUtils.getMimeTypeFromName(url);
  428. if (MimeTypeUtil.isVideo(mMimeType) && thumbnail != null) {
  429. thumbnail = addVideoOverlay(thumbnail);
  430. }
  431. //} else { do nothing
  432. }
  433. } catch(OutOfMemoryError oome) {
  434. Log_OC.e(TAG, "Out of memory");
  435. isError = true;
  436. } catch (Throwable t) {
  437. // the app should never break due to a problem with thumbnails
  438. Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
  439. isError = true;
  440. } finally {
  441. if (isError && mListener != null){
  442. mListener.onError();
  443. }
  444. }
  445. return thumbnail;
  446. }
  447. protected void onPostExecute(Bitmap bitmap) {
  448. if (bitmap != null && mImageViewReference != null) {
  449. final ImageView imageView = mImageViewReference.get();
  450. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  451. if (this == bitmapWorkerTask) {
  452. String tagId = "";
  453. if (mFile instanceof OCFile) {
  454. tagId = String.valueOf(((OCFile)mFile).getFileId());
  455. } else if (mFile instanceof File) {
  456. tagId = String.valueOf(mFile.hashCode());
  457. } else if (mFile instanceof TrashbinFile) {
  458. tagId = String.valueOf(((TrashbinFile) mFile).getRemoteId());
  459. }
  460. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  461. if (gridViewEnabled){
  462. BitmapUtils.setRoundedBitmapForGridMode(bitmap, imageView);
  463. } else {
  464. BitmapUtils.setRoundedBitmap(bitmap, imageView);
  465. }
  466. }
  467. }
  468. }
  469. if (mListener !=null){
  470. mListener.onSuccess();
  471. }
  472. if (mAsyncTasks != null) {
  473. mAsyncTasks.remove(this);
  474. }
  475. }
  476. public void setListener(Listener listener){
  477. mListener = listener;
  478. }
  479. private Bitmap doThumbnailFromOCFileInBackground() {
  480. Bitmap thumbnail;
  481. ServerFileInterface file = (ServerFileInterface) mFile;
  482. String imageKey = PREFIX_THUMBNAIL + file.getRemoteId();
  483. // Check disk cache in background thread
  484. thumbnail = getBitmapFromDiskCache(imageKey);
  485. // Not found in disk cache
  486. if (thumbnail == null || (file instanceof OCFile && ((OCFile) file).isUpdateThumbnailNeeded())) {
  487. int pxW;
  488. int pxH;
  489. pxW = pxH = getThumbnailDimension();
  490. if (file instanceof OCFile) {
  491. OCFile ocFile = (OCFile) file;
  492. if (ocFile.isDown()) {
  493. Bitmap bitmap;
  494. if (MimeTypeUtil.isVideo(ocFile)) {
  495. bitmap = ThumbnailUtils.createVideoThumbnail(ocFile.getStoragePath(),
  496. MediaStore.Images.Thumbnails.MINI_KIND);
  497. } else {
  498. bitmap = BitmapUtils.decodeSampledBitmapFromFile(ocFile.getStoragePath(), pxW, pxH);
  499. }
  500. if (bitmap != null) {
  501. // Handle PNG
  502. if (PNG_MIMETYPE.equalsIgnoreCase(ocFile.getMimeType())) {
  503. bitmap = handlePNG(bitmap, pxW, pxH);
  504. }
  505. thumbnail = addThumbnailToCache(imageKey, bitmap, ocFile.getStoragePath(), pxW, pxH);
  506. ocFile.setUpdateThumbnailNeeded(false);
  507. mStorageManager.saveFile(ocFile);
  508. }
  509. }
  510. }
  511. if (thumbnail == null) {
  512. // check if resized version is available
  513. String resizedImageKey = PREFIX_RESIZED_IMAGE + file.getRemoteId();
  514. Bitmap resizedImage = getBitmapFromDiskCache(resizedImageKey);
  515. if (resizedImage != null) {
  516. thumbnail = ThumbnailUtils.extractThumbnail(resizedImage, pxW, pxH);
  517. } else {
  518. // Download thumbnail from server
  519. if (mClient != null) {
  520. getMethod = null;
  521. try {
  522. // thumbnail
  523. String uri;
  524. if (file instanceof OCFile) {
  525. uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
  526. pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
  527. } else {
  528. uri = mClient.getBaseUri() + "/index.php/apps/files_trashbin/preview?fileId=" +
  529. file.getLocalId() + "&x=" + pxW + "&y=" + pxH;
  530. }
  531. Log_OC.d(TAG, "generate thumbnail: " + file.getFileName() + " URI: " + uri);
  532. getMethod = new GetMethod(uri);
  533. getMethod.setRequestHeader("Cookie",
  534. "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
  535. getMethod.setRequestHeader(RemoteOperation.OCS_API_HEADER,
  536. RemoteOperation.OCS_API_HEADER_VALUE);
  537. int status = mClient.executeMethod(getMethod);
  538. if (status == HttpStatus.SC_OK) {
  539. InputStream inputStream = getMethod.getResponseBodyAsStream();
  540. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  541. thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
  542. } else {
  543. mClient.exhaustResponse(getMethod.getResponseBodyAsStream());
  544. }
  545. // Handle PNG
  546. if (PNG_MIMETYPE.equalsIgnoreCase(file.getMimeType())) {
  547. thumbnail = handlePNG(thumbnail, pxW, pxH);
  548. }
  549. } catch (Exception e) {
  550. Log_OC.d(TAG, e.getMessage(), e);
  551. } finally {
  552. if (getMethod != null) {
  553. getMethod.releaseConnection();
  554. }
  555. }
  556. }
  557. }
  558. // Add thumbnail to cache
  559. if (thumbnail != null) {
  560. Log_OC.d(TAG, "add thumbnail to cache: " + file.getFileName());
  561. addBitmapToCache(imageKey, thumbnail);
  562. }
  563. }
  564. }
  565. return thumbnail;
  566. }
  567. /**
  568. * Converts size of file icon from dp to pixel
  569. *
  570. * @return int
  571. */
  572. private int getThumbnailDimension() {
  573. // Converts dp to pixel
  574. Resources r = MainApp.getAppContext().getResources();
  575. Double d = Math.pow(2, Math.floor(Math.log(r.getDimension(R.dimen.file_icon_size_grid)) / Math.log(2)));
  576. return d.intValue();
  577. }
  578. private Bitmap doFileInBackground() {
  579. File file = (File)mFile;
  580. final String imageKey;
  581. if (mImageKey != null) {
  582. imageKey = mImageKey;
  583. } else {
  584. imageKey = String.valueOf(file.hashCode());
  585. }
  586. // local file should always generate a thumbnail
  587. mImageKey = PREFIX_THUMBNAIL + mImageKey;
  588. // Check disk cache in background thread
  589. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  590. // Not found in disk cache
  591. if (thumbnail == null) {
  592. int pxW;
  593. int pxH;
  594. pxW = pxH = getThumbnailDimension();
  595. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getAbsolutePath(), pxW, pxH);
  596. if (bitmap != null) {
  597. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), pxW, pxH);
  598. }
  599. }
  600. return thumbnail;
  601. }
  602. public interface Listener{
  603. void onSuccess();
  604. void onError();
  605. }
  606. }
  607. public static class MediaThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
  608. private static final int IMAGE_KEY_PARAMS_LENGTH = 2;
  609. private enum Type {IMAGE, VIDEO}
  610. private final WeakReference<ImageView> mImageViewReference;
  611. private File mFile;
  612. private String mImageKey;
  613. private Context mContext;
  614. public MediaThumbnailGenerationTask(ImageView imageView, Context context) {
  615. // Use a WeakReference to ensure the ImageView can be garbage collected
  616. mImageViewReference = new WeakReference<>(imageView);
  617. mContext = context;
  618. }
  619. @Override
  620. protected Bitmap doInBackground(Object... params) {
  621. Bitmap thumbnail = null;
  622. try {
  623. if (params[0] instanceof File) {
  624. mFile = (File) params[0];
  625. if (params.length == IMAGE_KEY_PARAMS_LENGTH) {
  626. mImageKey = (String) params[1];
  627. }
  628. if (MimeTypeUtil.isImage(mFile)) {
  629. thumbnail = doFileInBackground(mFile, Type.IMAGE);
  630. } else if (MimeTypeUtil.isVideo(mFile)) {
  631. thumbnail = doFileInBackground(mFile, Type.VIDEO);
  632. }
  633. }
  634. } // the app should never break due to a problem with thumbnails
  635. catch (OutOfMemoryError t) {
  636. Log_OC.e(TAG, "Generation of thumbnail for " + mFile.getAbsolutePath() + " failed", t);
  637. Log_OC.e(TAG, "Out of memory");
  638. } catch (Throwable t) {
  639. // the app should never break due to a problem with thumbnails
  640. Log_OC.e(TAG, "Generation of thumbnail for " + mFile.getAbsolutePath() + " failed", t);
  641. }
  642. return thumbnail;
  643. }
  644. protected void onPostExecute(Bitmap bitmap) {
  645. String tagId = "";
  646. final ImageView imageView = mImageViewReference.get();
  647. if (imageView != null) {
  648. if (mFile != null) {
  649. tagId = String.valueOf(mFile.hashCode());
  650. }
  651. if (bitmap != null) {
  652. if (tagId.equals(String.valueOf(imageView.getTag()))) {
  653. imageView.setImageBitmap(bitmap);
  654. }
  655. } else {
  656. if (mFile != null) {
  657. if (mFile.isDirectory()) {
  658. imageView.setImageDrawable(MimeTypeUtil.getDefaultFolderIcon(mContext));
  659. } else {
  660. if (MimeTypeUtil.isVideo(mFile)) {
  661. imageView.setImageBitmap(ThumbnailsCacheManager.mDefaultVideo);
  662. } else {
  663. imageView.setImageDrawable(MimeTypeUtil.getFileTypeIcon(null, mFile.getName(),
  664. mContext));
  665. }
  666. }
  667. }
  668. }
  669. }
  670. }
  671. private Bitmap doFileInBackground(File file, Type type) {
  672. final String imageKey;
  673. if (mImageKey != null) {
  674. imageKey = mImageKey;
  675. } else {
  676. imageKey = String.valueOf(file.hashCode());
  677. }
  678. // Check disk cache in background thread
  679. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  680. // Not found in disk cache
  681. if (thumbnail == null) {
  682. if (Type.IMAGE.equals(type)) {
  683. int px = getThumbnailDimension();
  684. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getAbsolutePath(), px, px);
  685. if (bitmap != null) {
  686. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), px, px);
  687. }
  688. } else if (Type.VIDEO.equals(type)) {
  689. MediaMetadataRetriever retriever = new MediaMetadataRetriever();
  690. try {
  691. retriever.setDataSource(file.getAbsolutePath());
  692. thumbnail = retriever.getFrameAtTime(-1);
  693. } catch (Exception ex) {
  694. // can't create a bitmap
  695. Log_OC.w(TAG, "Failed to create bitmap from video " + file.getAbsolutePath());
  696. } finally {
  697. try {
  698. retriever.release();
  699. } catch (RuntimeException ex) {
  700. // Ignore failure at this point.
  701. Log_OC.w(TAG, "Failed release MediaMetadataRetriever for " + file.getAbsolutePath());
  702. }
  703. }
  704. if (thumbnail != null) {
  705. // Scale down bitmap if too large.
  706. int px = getThumbnailDimension();
  707. int width = thumbnail.getWidth();
  708. int height = thumbnail.getHeight();
  709. int max = Math.max(width, height);
  710. if (max > px) {
  711. thumbnail = BitmapUtils.scaleBitmap(thumbnail, px, width, height, max);
  712. thumbnail = addThumbnailToCache(imageKey, thumbnail, file.getPath(), px, px);
  713. }
  714. }
  715. }
  716. }
  717. return thumbnail;
  718. }
  719. }
  720. public static class AvatarGenerationTask extends AsyncTask<String, Void, Drawable> {
  721. private final WeakReference<AvatarGenerationListener> mAvatarGenerationListener;
  722. private final Object mCallContext;
  723. private final Resources mResources;
  724. private final float mAvatarRadius;
  725. private Account mAccount;
  726. private String mUserId;
  727. private String mServerName;
  728. private Context mContext;
  729. public AvatarGenerationTask(AvatarGenerationListener avatarGenerationListener,
  730. Object callContext,
  731. Account account,
  732. Resources resources,
  733. float avatarRadius,
  734. String userId,
  735. String serverName,
  736. Context context) {
  737. mAvatarGenerationListener = new WeakReference<>(avatarGenerationListener);
  738. mCallContext = callContext;
  739. mAccount = account;
  740. mResources = resources;
  741. mAvatarRadius = avatarRadius;
  742. mUserId = userId;
  743. mServerName = serverName;
  744. mContext = context;
  745. }
  746. @SuppressFBWarnings("Dm")
  747. @Override
  748. protected Drawable doInBackground(String... params) {
  749. Drawable thumbnail = null;
  750. try {
  751. if (mAccount != null) {
  752. OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, mContext);
  753. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, mContext);
  754. }
  755. thumbnail = doAvatarInBackground();
  756. } catch (OutOfMemoryError oome) {
  757. Log_OC.e(TAG, "Out of memory");
  758. } catch (Throwable t) {
  759. // the app should never break due to a problem with avatars
  760. Log_OC.e(TAG, "Generation of avatar for " + mUserId + " failed", t);
  761. }
  762. return thumbnail;
  763. }
  764. protected void onPostExecute(Drawable drawable) {
  765. if (drawable != null) {
  766. AvatarGenerationListener listener = mAvatarGenerationListener.get();
  767. if (listener != null) {
  768. AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(mCallContext);
  769. String accountName = mUserId + "@" + mServerName;
  770. if (this == avatarWorkerTask && listener.shouldCallGeneratedCallback(accountName, mCallContext)) {
  771. listener.avatarGenerated(drawable, mCallContext);
  772. }
  773. }
  774. }
  775. }
  776. /**
  777. * Converts size of file icon from dp to pixel
  778. *
  779. * @return int
  780. */
  781. private int getAvatarDimension() {
  782. // Converts dp to pixel
  783. Resources r = MainApp.getAppContext().getResources();
  784. return Math.round(r.getDimension(R.dimen.file_avatar_size));
  785. }
  786. private @NonNull
  787. Drawable doAvatarInBackground() {
  788. Bitmap avatar;
  789. String accountName = mUserId + "@" + mServerName;
  790. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(mContext.getContentResolver());
  791. String eTag = arbitraryDataProvider.getValue(accountName, ThumbnailsCacheManager.AVATAR);
  792. long timestamp = arbitraryDataProvider.getLongValue(accountName, ThumbnailsCacheManager.AVATAR_TIMESTAMP);
  793. String avatarKey = "a_" + mUserId + "_" + mServerName + "_" + eTag;
  794. avatar = getBitmapFromDiskCache(avatarKey);
  795. // Download avatar from server, only if older than 60 min or avatar does not exist
  796. if ((System.currentTimeMillis() - timestamp >= 60 * 60 * 1000 || avatar == null) && mClient != null) {
  797. GetMethod get = null;
  798. try {
  799. int px = getAvatarDimension();
  800. String uri = mClient.getBaseUri() + "/index.php/avatar/" + Uri.encode(mUserId) + "/" + px;
  801. Log_OC.d("Avatar", "URI: " + uri);
  802. get = new GetMethod(uri);
  803. // only use eTag if available and corresponding avatar is still there
  804. // (might be deleted from cache)
  805. if (!eTag.isEmpty() && avatar != null) {
  806. get.setRequestHeader("If-None-Match", eTag);
  807. }
  808. int status = mClient.executeMethod(get);
  809. // we are using eTag to download a new avatar only if it changed
  810. switch (status) {
  811. case HttpStatus.SC_OK:
  812. case HttpStatus.SC_CREATED:
  813. // new avatar
  814. InputStream inputStream = get.getResponseBodyAsStream();
  815. String newETag = null;
  816. if (get.getResponseHeader(ETAG) != null) {
  817. newETag = get.getResponseHeader(ETAG).getValue().replace("\"", "");
  818. arbitraryDataProvider.storeOrUpdateKeyValue(accountName, AVATAR, newETag);
  819. }
  820. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  821. avatar = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  822. // Add avatar to cache
  823. if (avatar != null && !TextUtils.isEmpty(newETag)) {
  824. avatar = handlePNG(avatar, px, px);
  825. String newImageKey = "a_" + mUserId + "_" + mServerName + "_" + newETag;
  826. addBitmapToCache(newImageKey, avatar);
  827. arbitraryDataProvider.storeOrUpdateKeyValue(accountName,
  828. ThumbnailsCacheManager.AVATAR_TIMESTAMP,
  829. System.currentTimeMillis());
  830. } else {
  831. return TextDrawable.createAvatar(mAccount, mAvatarRadius);
  832. }
  833. break;
  834. case HttpStatus.SC_NOT_MODIFIED:
  835. // old avatar
  836. mClient.exhaustResponse(get.getResponseBodyAsStream());
  837. arbitraryDataProvider.storeOrUpdateKeyValue(accountName,
  838. ThumbnailsCacheManager.AVATAR_TIMESTAMP,
  839. System.currentTimeMillis());
  840. break;
  841. default:
  842. // everything else
  843. mClient.exhaustResponse(get.getResponseBodyAsStream());
  844. break;
  845. }
  846. } catch (Exception e) {
  847. try {
  848. return TextDrawable.createAvatar(mAccount, mAvatarRadius);
  849. } catch (Exception e1) {
  850. Log_OC.e(TAG, "Error generating fallback avatar");
  851. }
  852. } finally {
  853. if (get != null) {
  854. get.releaseConnection();
  855. }
  856. }
  857. }
  858. if (avatar == null) {
  859. try {
  860. return TextDrawable.createAvatar(mAccount, mAvatarRadius);
  861. } catch (Exception e1) {
  862. return mResources.getDrawable(R.drawable.ic_user);
  863. }
  864. } else {
  865. return BitmapUtils.bitmapToCircularBitmapDrawable(mResources, avatar);
  866. }
  867. }
  868. }
  869. public static boolean cancelPotentialThumbnailWork(Object file, ImageView imageView) {
  870. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  871. if (bitmapWorkerTask != null) {
  872. final Object bitmapData = bitmapWorkerTask.mFile;
  873. // If bitmapData is not yet set or it differs from the new data
  874. if (bitmapData == null || !bitmapData.equals(file)) {
  875. // Cancel previous task
  876. bitmapWorkerTask.cancel(true);
  877. Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView");
  878. } else {
  879. // The same work is already in progress
  880. return false;
  881. }
  882. }
  883. // No task associated with the ImageView, or an existing task was cancelled
  884. return true;
  885. }
  886. public static boolean cancelPotentialAvatarWork(Object file, Object callContext) {
  887. if (callContext instanceof ImageView) {
  888. return cancelPotentialAvatarWork(file, (ImageView) callContext);
  889. } else if (callContext instanceof MenuItem) {
  890. return cancelPotentialAvatarWork(file, (MenuItem)callContext);
  891. }
  892. return false;
  893. }
  894. public static boolean cancelPotentialAvatarWork(Object file, ImageView imageView) {
  895. final AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(imageView);
  896. if (avatarWorkerTask != null) {
  897. final Object usernameData = avatarWorkerTask.mUserId;
  898. // If usernameData is not yet set or it differs from the new data
  899. if (usernameData == null || !usernameData.equals(file)) {
  900. // Cancel previous task
  901. avatarWorkerTask.cancel(true);
  902. Log_OC.v(TAG, "Cancelled generation of avatar for a reused imageView");
  903. } else {
  904. // The same work is already in progress
  905. return false;
  906. }
  907. }
  908. // No task associated with the ImageView, or an existing task was cancelled
  909. return true;
  910. }
  911. public static boolean cancelPotentialAvatarWork(Object file, MenuItem menuItem) {
  912. final AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(menuItem);
  913. if (avatarWorkerTask != null) {
  914. final Object usernameData = avatarWorkerTask.mUserId;
  915. // If usernameData is not yet set or it differs from the new data
  916. if (usernameData == null || !usernameData.equals(file)) {
  917. // Cancel previous task
  918. avatarWorkerTask.cancel(true);
  919. Log_OC.v(TAG, "Cancelled generation of avatar for a reused imageView");
  920. } else {
  921. // The same work is already in progress
  922. return false;
  923. }
  924. }
  925. // No task associated with the ImageView, or an existing task was cancelled
  926. return true;
  927. }
  928. public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
  929. if (imageView != null) {
  930. final Drawable drawable = imageView.getDrawable();
  931. if (drawable instanceof AsyncThumbnailDrawable) {
  932. final AsyncThumbnailDrawable asyncDrawable = (AsyncThumbnailDrawable) drawable;
  933. return asyncDrawable.getBitmapWorkerTask();
  934. }
  935. }
  936. return null;
  937. }
  938. private static ResizedImageGenerationTask getResizedImageGenerationWorkerTask(ImageView imageView) {
  939. if (imageView != null) {
  940. final Drawable drawable = imageView.getDrawable();
  941. if (drawable instanceof AsyncResizedImageDrawable) {
  942. final AsyncResizedImageDrawable asyncDrawable = (AsyncResizedImageDrawable) drawable;
  943. return asyncDrawable.getBitmapWorkerTask();
  944. }
  945. }
  946. return null;
  947. }
  948. public static Bitmap addVideoOverlay(Bitmap thumbnail){
  949. Drawable playButtonDrawable = MainApp.getAppContext().getResources().getDrawable(R.drawable.view_play);
  950. Bitmap playButton = BitmapUtils.drawableToBitmap(playButtonDrawable);
  951. Bitmap resizedPlayButton = Bitmap.createScaledBitmap(playButton,
  952. (int) (thumbnail.getWidth() * 0.3),
  953. (int) (thumbnail.getHeight() * 0.3), true);
  954. Bitmap resultBitmap = Bitmap.createBitmap(thumbnail.getWidth(),
  955. thumbnail.getHeight(),
  956. Bitmap.Config.ARGB_8888);
  957. Canvas c = new Canvas(resultBitmap);
  958. // compute visual center of play button, according to resized image
  959. int x1 = resizedPlayButton.getWidth();
  960. int y1 = resizedPlayButton.getHeight() / 2;
  961. int x2 = 0;
  962. int y2 = resizedPlayButton.getWidth();
  963. int x3 = 0;
  964. int y3 = 0;
  965. double ym = ( ((Math.pow(x3,2) - Math.pow(x1,2) + Math.pow(y3,2) - Math.pow(y1,2)) *
  966. (x2 - x1)) - (Math.pow(x2,2) - Math.pow(x1,2) + Math.pow(y2,2) -
  967. Math.pow(y1,2)) * (x3 - x1) ) / (2 * ( ((y3 - y1) * (x2 - x1)) -
  968. ((y2 - y1) * (x3 - x1)) ));
  969. double xm = ( (Math.pow(x2,2) - Math.pow(x1,2)) + (Math.pow(y2,2) - Math.pow(y1,2)) -
  970. (2*ym*(y2 - y1)) ) / (2*(x2 - x1));
  971. // offset to top left
  972. double ox = - xm;
  973. c.drawBitmap(thumbnail, 0, 0, null);
  974. Paint p = new Paint();
  975. p.setAlpha(230);
  976. c.drawBitmap(resizedPlayButton, (float) ((thumbnail.getWidth() / 2) + ox),
  977. (float) ((thumbnail.getHeight() / 2) - ym), p);
  978. return resultBitmap;
  979. }
  980. public static AvatarGenerationTask getAvatarWorkerTask(Object callContext) {
  981. if (callContext instanceof ImageView) {
  982. return getAvatarWorkerTask(((ImageView)callContext).getDrawable());
  983. } else if (callContext instanceof MenuItem) {
  984. return getAvatarWorkerTask(((MenuItem)callContext).getIcon());
  985. }
  986. return null;
  987. }
  988. private static AvatarGenerationTask getAvatarWorkerTask(Drawable drawable) {
  989. if (drawable instanceof AsyncAvatarDrawable) {
  990. final AsyncAvatarDrawable asyncDrawable = (AsyncAvatarDrawable) drawable;
  991. return asyncDrawable.getAvatarWorkerTask();
  992. }
  993. return null;
  994. }
  995. public static class AsyncThumbnailDrawable extends BitmapDrawable {
  996. private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
  997. public AsyncThumbnailDrawable(
  998. Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
  999. ) {
  1000. super(res, bitmap);
  1001. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  1002. }
  1003. public ThumbnailGenerationTask getBitmapWorkerTask() {
  1004. return bitmapWorkerTaskReference.get();
  1005. }
  1006. }
  1007. public static class AsyncResizedImageDrawable extends BitmapDrawable {
  1008. private final WeakReference<ResizedImageGenerationTask> bitmapWorkerTaskReference;
  1009. public AsyncResizedImageDrawable(Resources res, Bitmap bitmap, ResizedImageGenerationTask bitmapWorkerTask) {
  1010. super(res, bitmap);
  1011. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  1012. }
  1013. private ResizedImageGenerationTask getBitmapWorkerTask() {
  1014. return bitmapWorkerTaskReference.get();
  1015. }
  1016. }
  1017. public static class AsyncMediaThumbnailDrawable extends BitmapDrawable {
  1018. private final WeakReference<MediaThumbnailGenerationTask> bitmapWorkerTaskReference;
  1019. public AsyncMediaThumbnailDrawable(Resources res, Bitmap bitmap,
  1020. MediaThumbnailGenerationTask bitmapWorkerTask) {
  1021. super(res, bitmap);
  1022. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  1023. }
  1024. }
  1025. public static class AsyncAvatarDrawable extends BitmapDrawable {
  1026. private final WeakReference<AvatarGenerationTask> avatarWorkerTaskReference;
  1027. public AsyncAvatarDrawable(Resources res, Drawable bitmap, AvatarGenerationTask avatarWorkerTask) {
  1028. super(res, BitmapUtils.drawableToBitmap(bitmap));
  1029. avatarWorkerTaskReference = new WeakReference<>(avatarWorkerTask);
  1030. }
  1031. public AvatarGenerationTask getAvatarWorkerTask() {
  1032. return avatarWorkerTaskReference.get();
  1033. }
  1034. }
  1035. private static Bitmap handlePNG(Bitmap bitmap, int pxW, int pxH) {
  1036. Bitmap resultBitmap = Bitmap.createBitmap(pxW, pxH, Bitmap.Config.ARGB_8888);
  1037. Canvas c = new Canvas(resultBitmap);
  1038. // TODO check based on https://github.com/nextcloud/android/pull/3459#discussion_r339935975
  1039. c.drawColor(MainApp.getAppContext().getResources().getColor(R.color.background_color_png));
  1040. c.drawBitmap(bitmap, 0, 0, null);
  1041. return resultBitmap;
  1042. }
  1043. public static void generateResizedImage(OCFile file) {
  1044. Point p = getScreenDimension();
  1045. int pxW = p.x;
  1046. int pxH = p.y;
  1047. String imageKey = PREFIX_RESIZED_IMAGE + file.getRemoteId();
  1048. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getStoragePath(), pxW, pxH);
  1049. if (bitmap != null) {
  1050. // Handle PNG
  1051. if (PNG_MIMETYPE.equalsIgnoreCase(file.getMimeType())) {
  1052. bitmap = handlePNG(bitmap, pxW, pxH);
  1053. }
  1054. addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
  1055. }
  1056. }
  1057. public static void generateThumbnailFromOCFile(OCFile file) {
  1058. int pxW;
  1059. int pxH;
  1060. pxW = pxH = getThumbnailDimension();
  1061. String imageKey = PREFIX_THUMBNAIL + file.getRemoteId();
  1062. GetMethod getMethod = null;
  1063. try {
  1064. Bitmap thumbnail = null;
  1065. String uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
  1066. pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
  1067. Log_OC.d(TAG, "generate thumbnail: " + file.getFileName() + " URI: " + uri);
  1068. getMethod = new GetMethod(uri);
  1069. getMethod.setRequestHeader("Cookie", "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
  1070. getMethod.setRequestHeader(RemoteOperation.OCS_API_HEADER,
  1071. RemoteOperation.OCS_API_HEADER_VALUE);
  1072. int status = mClient.executeMethod(getMethod);
  1073. if (status == HttpStatus.SC_OK) {
  1074. InputStream inputStream = getMethod.getResponseBodyAsStream();
  1075. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  1076. thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
  1077. } else {
  1078. mClient.exhaustResponse(getMethod.getResponseBodyAsStream());
  1079. }
  1080. // Add thumbnail to cache
  1081. if (thumbnail != null) {
  1082. // Handle PNG
  1083. if (PNG_MIMETYPE.equalsIgnoreCase(file.getMimeType())) {
  1084. thumbnail = handlePNG(thumbnail, pxW, pxH);
  1085. }
  1086. Log_OC.d(TAG, "add thumbnail to cache: " + file.getFileName());
  1087. addBitmapToCache(imageKey, thumbnail);
  1088. }
  1089. } catch (Exception e) {
  1090. Log_OC.d(TAG, e.getMessage(), e);
  1091. } finally {
  1092. if (getMethod != null) {
  1093. getMethod.releaseConnection();
  1094. }
  1095. }
  1096. }
  1097. }