ThumbnailsCacheManager.java 51 KB

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