ThumbnailsCacheManager.java 47 KB

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