ThumbnailsCacheManager.java 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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.accounts.AccountManager;
  24. import android.content.Context;
  25. import android.content.res.Resources;
  26. import android.graphics.Bitmap;
  27. import android.graphics.Bitmap.CompressFormat;
  28. import android.graphics.BitmapFactory;
  29. import android.graphics.Canvas;
  30. import android.graphics.Paint;
  31. import android.graphics.Point;
  32. import android.graphics.drawable.BitmapDrawable;
  33. import android.graphics.drawable.Drawable;
  34. import android.media.MediaMetadataRetriever;
  35. import android.media.ThumbnailUtils;
  36. import android.net.Uri;
  37. import android.os.AsyncTask;
  38. import android.provider.MediaStore;
  39. import android.support.annotation.Nullable;
  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.owncloud.android.MainApp;
  46. import com.owncloud.android.R;
  47. import com.owncloud.android.authentication.AccountUtils;
  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.status.OwnCloudVersion;
  54. import com.owncloud.android.ui.TextDrawable;
  55. import com.owncloud.android.ui.adapter.DiskLruImageCache;
  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.ArrayList;
  70. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  71. /**
  72. * Manager for concurrent access to thumbnails cache.
  73. */
  74. public 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 = null;
  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 = null;
  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. public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
  94. @Override
  95. protected Void doInBackground(File... params) {
  96. synchronized (mThumbnailsDiskCacheLock) {
  97. mThumbnailCacheStarting = true;
  98. if (mThumbnailCache == null) {
  99. try {
  100. // Check if media is mounted or storage is built-in, if so,
  101. // try and use external cache dir; otherwise use internal cache dir
  102. File cacheDir = MainApp.getAppContext().getExternalCacheDir();
  103. if (cacheDir != null) {
  104. String cachePath = cacheDir.getPath() + File.separator + CACHE_FOLDER;
  105. Log_OC.d(TAG, "create dir: " + cachePath);
  106. File diskCacheDir = new File(cachePath);
  107. mThumbnailCache = new DiskLruImageCache(diskCacheDir, DISK_CACHE_SIZE, mCompressFormat,
  108. mCompressQuality);
  109. } else {
  110. throw new FileNotFoundException("Thumbnail cache could not be opened");
  111. }
  112. } catch (java.io.IOException e) {
  113. Log_OC.d(TAG, e.getMessage());
  114. mThumbnailCache = null;
  115. }
  116. }
  117. mThumbnailCacheStarting = false; // Finished initialization
  118. mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
  119. }
  120. return null;
  121. }
  122. }
  123. /**
  124. * Converts size of file icon from dp to pixel
  125. * @return int
  126. */
  127. private static int getThumbnailDimension(){
  128. // Converts dp to pixel
  129. Resources r = MainApp.getAppContext().getResources();
  130. return Math.round(r.getDimension(R.dimen.file_icon_size_grid));
  131. }
  132. /**
  133. * Converts dimension of screen as point
  134. *
  135. * @return Point
  136. */
  137. private static Point getScreenDimension() {
  138. WindowManager wm = (WindowManager) MainApp.getAppContext().getSystemService(Context.WINDOW_SERVICE);
  139. Display display = wm.getDefaultDisplay();
  140. Point point = new Point();
  141. display.getSize(point);
  142. return point;
  143. }
  144. /**
  145. * Add thumbnail to cache
  146. * @param imageKey: thumb key
  147. * @param bitmap: image for extracting thumbnail
  148. * @param path: image path
  149. * @param pxW: thumbnail width in pixel
  150. * @param pxH: thumbnail height in pixel
  151. * @return Bitmap
  152. */
  153. private static Bitmap addThumbnailToCache(String imageKey, Bitmap bitmap, String path, int pxW, int pxH){
  154. Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
  155. // Rotate image, obeying exif tag
  156. thumbnail = BitmapUtils.rotateImage(thumbnail,path);
  157. // Add thumbnail to cache
  158. addBitmapToCache(imageKey, thumbnail);
  159. return thumbnail;
  160. }
  161. public static void addBitmapToCache(String key, Bitmap bitmap) {
  162. synchronized (mThumbnailsDiskCacheLock) {
  163. if (mThumbnailCache != null) {
  164. mThumbnailCache.put(key, bitmap);
  165. }
  166. }
  167. }
  168. public static Bitmap getBitmapFromDiskCache(String key) {
  169. synchronized (mThumbnailsDiskCacheLock) {
  170. // Wait while disk cache is started from background thread
  171. while (mThumbnailCacheStarting) {
  172. try {
  173. mThumbnailsDiskCacheLock.wait();
  174. } catch (InterruptedException e) {
  175. Log_OC.e(TAG, "Wait in mThumbnailsDiskCacheLock was interrupted", e);
  176. }
  177. }
  178. if (mThumbnailCache != null) {
  179. return mThumbnailCache.getBitmap(key);
  180. }
  181. }
  182. return null;
  183. }
  184. public static class ResizedImageGenerationTask extends AsyncTask<Object, Void, Bitmap> {
  185. private PreviewImageFragment previewImageFragment;
  186. private FileDataStorageManager storageManager;
  187. private Account account;
  188. private WeakReference<ImageView> imageViewReference;
  189. private OCFile file;
  190. public ResizedImageGenerationTask(PreviewImageFragment previewImageFragment, ImageView imageView,
  191. FileDataStorageManager storageManager, Account account)
  192. throws IllegalArgumentException {
  193. this.previewImageFragment = previewImageFragment;
  194. imageViewReference = new WeakReference<>(imageView);
  195. this.storageManager = storageManager;
  196. this.account = account;
  197. }
  198. @Override
  199. protected Bitmap doInBackground(Object... params) {
  200. Bitmap thumbnail = null;
  201. file = (OCFile) params[0];
  202. try {
  203. if (account != null) {
  204. OwnCloudAccount ocAccount = new OwnCloudAccount(account, MainApp.getAppContext());
  205. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount,
  206. MainApp.getAppContext());
  207. }
  208. thumbnail = doResizedImageInBackground();
  209. if (MimeTypeUtil.isVideo(file) && thumbnail != null) {
  210. thumbnail = addVideoOverlay(thumbnail);
  211. }
  212. } catch (OutOfMemoryError oome) {
  213. System.gc();
  214. Log_OC.e(TAG, "Out of memory -> garbage collector called");
  215. } catch (Throwable t) {
  216. // the app should never break due to a problem with thumbnails
  217. Log_OC.e(TAG, "Generation of thumbnail for " + file + " failed", t);
  218. }
  219. return thumbnail;
  220. }
  221. private Bitmap doResizedImageInBackground() {
  222. Bitmap thumbnail;
  223. String imageKey = PREFIX_RESIZED_IMAGE + String.valueOf(file.getRemoteId());
  224. // Check disk cache in background thread
  225. thumbnail = getBitmapFromDiskCache(imageKey);
  226. // Not found in disk cache
  227. if (thumbnail == null || file.needsUpdateThumbnail()) {
  228. Point p = getScreenDimension();
  229. int pxW = p.x;
  230. int pxH = p.y;
  231. if (file.isDown()) {
  232. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getStoragePath(), pxW, pxH);
  233. if (bitmap != null) {
  234. // Handle PNG
  235. if (file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  236. bitmap = handlePNG(bitmap, pxW, pxH);
  237. }
  238. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
  239. file.setNeedsUpdateThumbnail(false);
  240. storageManager.saveFile(file);
  241. }
  242. } else {
  243. // Download thumbnail from server
  244. OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(account);
  245. if (mClient != null && serverOCVersion != null) {
  246. if (serverOCVersion.supportsRemoteThumbnails()) {
  247. GetMethod getMethod = null;
  248. try {
  249. String uri = mClient.getBaseUri() + "/index.php/core/preview.png?file="
  250. + URLEncoder.encode(file.getRemotePath())
  251. + "&x=" + pxW + "&y=" + pxH + "&a=1&mode=cover&forceIcon=0";
  252. getMethod = new GetMethod(uri);
  253. int status = mClient.executeMethod(getMethod);
  254. if (status == HttpStatus.SC_OK) {
  255. InputStream inputStream = getMethod.getResponseBodyAsStream();
  256. thumbnail = BitmapFactory.decodeStream(inputStream);
  257. } else {
  258. mClient.exhaustResponse(getMethod.getResponseBodyAsStream());
  259. }
  260. // Handle PNG
  261. if (thumbnail != null && file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  262. thumbnail = handlePNG(thumbnail, thumbnail.getWidth(), thumbnail.getHeight());
  263. }
  264. // Add thumbnail to cache
  265. if (thumbnail != null) {
  266. Log_OC.d(TAG, "add thumbnail to cache: " + file.getFileName());
  267. addBitmapToCache(imageKey, thumbnail);
  268. }
  269. } catch (Exception e) {
  270. Log_OC.d(TAG, e.getMessage(), e);
  271. } finally {
  272. if (getMethod != null) {
  273. getMethod.releaseConnection();
  274. }
  275. }
  276. } else {
  277. Log_OC.d(TAG, "Server too old");
  278. }
  279. }
  280. }
  281. }
  282. return thumbnail;
  283. }
  284. protected void onPostExecute(Bitmap bitmap) {
  285. if (imageViewReference != null) {
  286. final ImageView imageView = imageViewReference.get();
  287. if (bitmap != null) {
  288. final ResizedImageGenerationTask bitmapWorkerTask = getResizedImageGenerationWorkerTask(imageView);
  289. if (this == bitmapWorkerTask) {
  290. String tagId = String.valueOf(file.getFileId());
  291. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  292. imageView.setImageBitmap(bitmap);
  293. }
  294. }
  295. } else {
  296. new Thread(() -> {
  297. if (ConnectivityUtils.isInternetWalled(MainApp.getAppContext())) {
  298. previewImageFragment.setNoConnectionErrorMessage();
  299. } else {
  300. previewImageFragment.setErrorPreviewMessage();
  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 ArrayList<ThumbnailGenerationTask> mAsyncTasks = null;
  325. private Object mFile;
  326. private String mImageKey = null;
  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, ArrayList<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 OCFile) {
  377. thumbnail = doThumbnailFromOCFileInBackground();
  378. if (MimeTypeUtil.isVideo((OCFile) 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. System.gc();
  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. }
  409. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  410. imageView.setImageBitmap(bitmap);
  411. }
  412. }
  413. }
  414. if (mAsyncTasks != null) {
  415. mAsyncTasks.remove(this);
  416. }
  417. }
  418. private Bitmap doThumbnailFromOCFileInBackground() {
  419. Bitmap thumbnail;
  420. OCFile file = (OCFile) mFile;
  421. String imageKey = PREFIX_THUMBNAIL + String.valueOf(file.getRemoteId());
  422. // Check disk cache in background thread
  423. thumbnail = getBitmapFromDiskCache(imageKey);
  424. // Not found in disk cache
  425. if (thumbnail == null || file.needsUpdateThumbnail()) {
  426. int pxW;
  427. int pxH;
  428. pxW = pxH = getThumbnailDimension();
  429. if (file.isDown()) {
  430. Bitmap bitmap;
  431. if (MimeTypeUtil.isVideo(file)) {
  432. bitmap = ThumbnailUtils.createVideoThumbnail(file.getStoragePath(),
  433. MediaStore.Images.Thumbnails.MINI_KIND);
  434. } else {
  435. bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getStoragePath(), pxW, pxH);
  436. }
  437. if (bitmap != null) {
  438. // Handle PNG
  439. if (file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  440. bitmap = handlePNG(bitmap, pxW, pxH);
  441. }
  442. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
  443. file.setNeedsUpdateThumbnail(false);
  444. mStorageManager.saveFile(file);
  445. }
  446. } else {
  447. // Download thumbnail from server
  448. OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
  449. if (mClient != null && serverOCVersion != null) {
  450. if (serverOCVersion.supportsRemoteThumbnails()) {
  451. getMethod = null;
  452. try {
  453. // thumbnail
  454. String uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
  455. pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
  456. Log_OC.d(TAG, "generate thumbnail: " + file.getFileName() +
  457. " URI: " + uri);
  458. getMethod = new GetMethod(uri);
  459. getMethod.setRequestHeader("Cookie",
  460. "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
  461. getMethod.setRequestHeader(RemoteOperation.OCS_API_HEADER,
  462. RemoteOperation.OCS_API_HEADER_VALUE);
  463. int status = mClient.executeMethod(getMethod);
  464. if (status == HttpStatus.SC_OK) {
  465. InputStream inputStream = getMethod.getResponseBodyAsStream();
  466. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  467. thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
  468. } else {
  469. mClient.exhaustResponse(getMethod.getResponseBodyAsStream());
  470. }
  471. // Handle PNG
  472. if (file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  473. thumbnail = handlePNG(thumbnail, pxW, pxH);
  474. }
  475. // Add thumbnail to cache
  476. if (thumbnail != null) {
  477. Log_OC.d(TAG, "add thumbnail to cache: " + file.getFileName());
  478. addBitmapToCache(imageKey, thumbnail);
  479. }
  480. } catch (Exception e) {
  481. Log_OC.d(TAG, e.getMessage(), e);
  482. } finally {
  483. if (getMethod != null) {
  484. getMethod.releaseConnection();
  485. }
  486. }
  487. } else {
  488. Log_OC.d(TAG, "Server too old");
  489. }
  490. }
  491. }
  492. }
  493. return thumbnail;
  494. }
  495. /**
  496. * Converts size of file icon from dp to pixel
  497. *
  498. * @return int
  499. */
  500. private int getThumbnailDimension() {
  501. // Converts dp to pixel
  502. Resources r = MainApp.getAppContext().getResources();
  503. Double d = Math.pow(2, Math.floor(Math.log(r.getDimension(R.dimen.file_icon_size_grid)) / Math.log(2)));
  504. return d.intValue();
  505. }
  506. private Bitmap doFileInBackground() {
  507. File file = (File)mFile;
  508. final String imageKey;
  509. if (mImageKey != null) {
  510. imageKey = mImageKey;
  511. } else {
  512. imageKey = String.valueOf(file.hashCode());
  513. }
  514. // local file should always generate a thumbnail
  515. mImageKey = PREFIX_THUMBNAIL + mImageKey;
  516. // Check disk cache in background thread
  517. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  518. // Not found in disk cache
  519. if (thumbnail == null) {
  520. int pxW;
  521. int pxH;
  522. pxW = pxH = getThumbnailDimension();
  523. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getAbsolutePath(), pxW, pxH);
  524. if (bitmap != null) {
  525. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), pxW, pxH);
  526. }
  527. }
  528. return thumbnail;
  529. }
  530. }
  531. public static class MediaThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
  532. private enum Type {IMAGE, VIDEO}
  533. private final WeakReference<ImageView> mImageViewReference;
  534. private File mFile;
  535. private String mImageKey = null;
  536. public MediaThumbnailGenerationTask(ImageView imageView) {
  537. // Use a WeakReference to ensure the ImageView can be garbage collected
  538. mImageViewReference = new WeakReference<>(imageView);
  539. }
  540. @Override
  541. protected Bitmap doInBackground(Object... params) {
  542. Bitmap thumbnail = null;
  543. try {
  544. if (params[0] instanceof File) {
  545. mFile = (File) params[0];
  546. if (params.length == 2) {
  547. mImageKey = (String) params[1];
  548. }
  549. if (MimeTypeUtil.isImage(mFile)) {
  550. thumbnail = doFileInBackground(mFile, Type.IMAGE);
  551. } else if (MimeTypeUtil.isVideo(mFile)) {
  552. thumbnail = doFileInBackground(mFile, Type.VIDEO);
  553. }
  554. }
  555. } // the app should never break due to a problem with thumbnails
  556. catch (OutOfMemoryError t) {
  557. Log_OC.e(TAG, "Generation of thumbnail for " + mFile.getAbsolutePath() + " failed", t);
  558. System.gc();
  559. } catch (Throwable t) {
  560. // the app should never break due to a problem with thumbnails
  561. Log_OC.e(TAG, "Generation of thumbnail for " + mFile.getAbsolutePath() + " failed", t);
  562. }
  563. return thumbnail;
  564. }
  565. protected void onPostExecute(Bitmap bitmap) {
  566. String tagId = "";
  567. final ImageView imageView = mImageViewReference.get();
  568. if (imageView != null) {
  569. if (mFile != null) {
  570. tagId = String.valueOf(mFile.hashCode());
  571. }
  572. if (bitmap != null) {
  573. if (tagId.equals(String.valueOf(imageView.getTag()))) {
  574. imageView.setImageBitmap(bitmap);
  575. }
  576. } else {
  577. if (mFile != null) {
  578. if (mFile.isDirectory()) {
  579. imageView.setImageDrawable(MimeTypeUtil.getDefaultFolderIcon());
  580. } else {
  581. if (MimeTypeUtil.isVideo(mFile)) {
  582. imageView.setImageBitmap(ThumbnailsCacheManager.mDefaultVideo);
  583. } else {
  584. imageView.setImageDrawable(MimeTypeUtil.getFileTypeIcon(null, mFile.getName(), null));
  585. }
  586. }
  587. }
  588. }
  589. }
  590. }
  591. private Bitmap doFileInBackground(File file, Type type) {
  592. final String imageKey;
  593. if (mImageKey != null) {
  594. imageKey = mImageKey;
  595. } else {
  596. imageKey = String.valueOf(file.hashCode());
  597. }
  598. // Check disk cache in background thread
  599. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  600. // Not found in disk cache
  601. if (thumbnail == null) {
  602. if (Type.IMAGE.equals(type)) {
  603. int px = getThumbnailDimension();
  604. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getAbsolutePath(), px, px);
  605. if (bitmap != null) {
  606. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), px, px);
  607. }
  608. } else if (Type.VIDEO.equals(type)) {
  609. MediaMetadataRetriever retriever = new MediaMetadataRetriever();
  610. try {
  611. retriever.setDataSource(file.getAbsolutePath());
  612. thumbnail = retriever.getFrameAtTime(-1);
  613. } catch (Exception ex) {
  614. // can't create a bitmap
  615. Log_OC.w(TAG, "Failed to create bitmap from video " + file.getAbsolutePath());
  616. } finally {
  617. try {
  618. retriever.release();
  619. } catch (RuntimeException ex) {
  620. // Ignore failure at this point.
  621. Log_OC.w(TAG, "Failed release MediaMetadataRetriever for " + file.getAbsolutePath());
  622. }
  623. }
  624. if (thumbnail != null) {
  625. // Scale down bitmap if too large.
  626. int px = getThumbnailDimension();
  627. int width = thumbnail.getWidth();
  628. int height = thumbnail.getHeight();
  629. int max = Math.max(width, height);
  630. if (max > px) {
  631. thumbnail = BitmapUtils.scaleBitmap(thumbnail, px, width, height, max);
  632. thumbnail = addThumbnailToCache(imageKey, thumbnail, file.getPath(), px, px);
  633. }
  634. }
  635. }
  636. }
  637. return thumbnail;
  638. }
  639. }
  640. public static class AvatarGenerationTask extends AsyncTask<String, Void, Drawable> {
  641. private final WeakReference<AvatarGenerationListener> mAvatarGenerationListener;
  642. private final Object mCallContext;
  643. private final Resources mResources;
  644. private final float mAvatarRadius;
  645. private Account mAccount;
  646. private String mUsername;
  647. public AvatarGenerationTask(AvatarGenerationListener avatarGenerationListener, Object callContext,
  648. FileDataStorageManager storageManager, Account account, Resources resources,
  649. float avatarRadius) {
  650. mAvatarGenerationListener = new WeakReference<>(avatarGenerationListener);
  651. mCallContext = callContext;
  652. if (storageManager == null) {
  653. throw new IllegalArgumentException("storageManager must not be NULL");
  654. }
  655. mAccount = account;
  656. mResources = resources;
  657. mAvatarRadius = avatarRadius;
  658. }
  659. @SuppressFBWarnings("Dm")
  660. @Override
  661. protected Drawable doInBackground(String... params) {
  662. Drawable thumbnail = null;
  663. try {
  664. if (mAccount != null) {
  665. OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount,
  666. MainApp.getAppContext());
  667. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  668. getClientFor(ocAccount, MainApp.getAppContext());
  669. }
  670. mUsername = params[0];
  671. thumbnail = doAvatarInBackground();
  672. } catch(OutOfMemoryError oome) {
  673. System.gc(); // todo, does this really make sense?
  674. } catch(Throwable t){
  675. // the app should never break due to a problem with avatars
  676. Log_OC.e(TAG, "Generation of avatar for " + mUsername + " failed", t);
  677. }
  678. return thumbnail;
  679. }
  680. protected void onPostExecute(Drawable drawable) {
  681. if (drawable != null) {
  682. AvatarGenerationListener listener = mAvatarGenerationListener.get();
  683. AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(mCallContext);
  684. if (this == avatarWorkerTask && listener.shouldCallGeneratedCallback(mUsername, mCallContext)) {
  685. listener.avatarGenerated(drawable, mCallContext);
  686. }
  687. }
  688. }
  689. /**
  690. * Converts size of file icon from dp to pixel
  691. * @return int
  692. */
  693. private int getAvatarDimension(){
  694. // Converts dp to pixel
  695. Resources r = MainApp.getAppContext().getResources();
  696. return Math.round(r.getDimension(R.dimen.file_avatar_size));
  697. }
  698. private @Nullable
  699. Drawable doAvatarInBackground() {
  700. Bitmap avatar = null;
  701. String username = mUsername;
  702. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(
  703. MainApp.getAppContext().getContentResolver());
  704. String eTag = arbitraryDataProvider.getValue(mAccount, AVATAR);
  705. final String imageKey = "a_" + username + "_" + eTag;
  706. int px = getAvatarDimension();
  707. // Download avatar from server
  708. OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
  709. if (mClient != null && serverOCVersion != null) {
  710. if (serverOCVersion.supportsRemoteThumbnails()) {
  711. GetMethod get = null;
  712. try {
  713. String userId = AccountManager.get(MainApp.getAppContext()).getUserData(mAccount,
  714. com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
  715. if (TextUtils.isEmpty(userId)) {
  716. userId = AccountUtils.getAccountUsername(username);
  717. }
  718. String uri = mClient.getBaseUri() + "/index.php/avatar/" + Uri.encode(userId) + "/" + px;
  719. Log_OC.d("Avatar", "URI: " + uri);
  720. get = new GetMethod(uri);
  721. if (!eTag.isEmpty()) {
  722. get.setRequestHeader("If-None-Match", eTag);
  723. }
  724. int status = mClient.executeMethod(get);
  725. // we are using eTag to download a new avatar only if it changed
  726. switch (status) {
  727. case HttpStatus.SC_OK:
  728. // new avatar
  729. InputStream inputStream = get.getResponseBodyAsStream();
  730. if (get.getResponseHeader(ETAG) != null) {
  731. eTag = get.getResponseHeader(ETAG).getValue().replace("\"", "");
  732. arbitraryDataProvider.storeOrUpdateKeyValue(mAccount.name, AVATAR, eTag);
  733. }
  734. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  735. avatar = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  736. // Add avatar to cache
  737. if (avatar != null) {
  738. avatar = handlePNG(avatar, px, px);
  739. String newImageKey = "a_" + username + "_" + eTag;
  740. addBitmapToCache(newImageKey, avatar);
  741. } else {
  742. return TextDrawable.createAvatar(mAccount.name, mAvatarRadius);
  743. }
  744. break;
  745. case HttpStatus.SC_NOT_MODIFIED:
  746. // old avatar
  747. avatar = getBitmapFromDiskCache(imageKey);
  748. mClient.exhaustResponse(get.getResponseBodyAsStream());
  749. break;
  750. default:
  751. // everything else
  752. mClient.exhaustResponse(get.getResponseBodyAsStream());
  753. break;
  754. }
  755. } catch (Exception e) {
  756. try {
  757. return TextDrawable.createAvatar(mAccount.name, mAvatarRadius);
  758. } catch (Exception e1) {
  759. Log_OC.e(TAG, "Error generating fallback avatar");
  760. }
  761. } finally {
  762. if (get != null) {
  763. get.releaseConnection();
  764. }
  765. }
  766. } else {
  767. Log_OC.d(TAG, "Server too old");
  768. try {
  769. return TextDrawable.createAvatar(mAccount.name, mAvatarRadius);
  770. } catch (Exception e) {
  771. Log_OC.e(TAG, "Error generating fallback avatar");
  772. }
  773. }
  774. }
  775. return BitmapUtils.bitmapToCircularBitmapDrawable(mResources, avatar);
  776. }
  777. }
  778. public static boolean cancelPotentialThumbnailWork(Object file, ImageView imageView) {
  779. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  780. if (bitmapWorkerTask != null) {
  781. final Object bitmapData = bitmapWorkerTask.mFile;
  782. // If bitmapData is not yet set or it differs from the new data
  783. if (bitmapData == null || !bitmapData.equals(file)) {
  784. // Cancel previous task
  785. bitmapWorkerTask.cancel(true);
  786. Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView");
  787. } else {
  788. // The same work is already in progress
  789. return false;
  790. }
  791. }
  792. // No task associated with the ImageView, or an existing task was cancelled
  793. return true;
  794. }
  795. public static boolean cancelPotentialAvatarWork(Object file, Object callContext) {
  796. if (callContext instanceof ImageView) {
  797. return cancelPotentialAvatarWork(file, (ImageView) callContext);
  798. } else if (callContext instanceof MenuItem) {
  799. return cancelPotentialAvatarWork(file, (MenuItem)callContext);
  800. }
  801. return false;
  802. }
  803. public static boolean cancelPotentialAvatarWork(Object file, ImageView imageView) {
  804. final AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(imageView);
  805. if (avatarWorkerTask != null) {
  806. final Object usernameData = avatarWorkerTask.mUsername;
  807. // If usernameData is not yet set or it differs from the new data
  808. if (usernameData == null || !usernameData.equals(file)) {
  809. // Cancel previous task
  810. avatarWorkerTask.cancel(true);
  811. Log_OC.v(TAG, "Cancelled generation of avatar for a reused imageView");
  812. } else {
  813. // The same work is already in progress
  814. return false;
  815. }
  816. }
  817. // No task associated with the ImageView, or an existing task was cancelled
  818. return true;
  819. }
  820. public static boolean cancelPotentialAvatarWork(Object file, MenuItem menuItem) {
  821. final AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(menuItem);
  822. if (avatarWorkerTask != null) {
  823. final Object usernameData = avatarWorkerTask.mUsername;
  824. // If usernameData is not yet set or it differs from the new data
  825. if (usernameData == null || !usernameData.equals(file)) {
  826. // Cancel previous task
  827. avatarWorkerTask.cancel(true);
  828. Log_OC.v(TAG, "Cancelled generation of avatar for a reused imageView");
  829. } else {
  830. // The same work is already in progress
  831. return false;
  832. }
  833. }
  834. // No task associated with the ImageView, or an existing task was cancelled
  835. return true;
  836. }
  837. public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
  838. if (imageView != null) {
  839. final Drawable drawable = imageView.getDrawable();
  840. if (drawable instanceof AsyncThumbnailDrawable) {
  841. final AsyncThumbnailDrawable asyncDrawable = (AsyncThumbnailDrawable) drawable;
  842. return asyncDrawable.getBitmapWorkerTask();
  843. }
  844. }
  845. return null;
  846. }
  847. private static ResizedImageGenerationTask getResizedImageGenerationWorkerTask(ImageView imageView) {
  848. if (imageView != null) {
  849. final Drawable drawable = imageView.getDrawable();
  850. if (drawable instanceof AsyncResizedImageDrawable) {
  851. final AsyncResizedImageDrawable asyncDrawable = (AsyncResizedImageDrawable) drawable;
  852. return asyncDrawable.getBitmapWorkerTask();
  853. }
  854. }
  855. return null;
  856. }
  857. public static Bitmap addVideoOverlay(Bitmap thumbnail){
  858. Bitmap playButton = BitmapFactory.decodeResource(MainApp.getAppContext().getResources(),
  859. R.drawable.view_play);
  860. Bitmap resizedPlayButton = Bitmap.createScaledBitmap(playButton,
  861. (int) (thumbnail.getWidth() * 0.3),
  862. (int) (thumbnail.getHeight() * 0.3), true);
  863. Bitmap resultBitmap = Bitmap.createBitmap(thumbnail.getWidth(),
  864. thumbnail.getHeight(),
  865. Bitmap.Config.ARGB_8888);
  866. Canvas c = new Canvas(resultBitmap);
  867. // compute visual center of play button, according to resized image
  868. int x1 = resizedPlayButton.getWidth();
  869. int y1 = resizedPlayButton.getHeight() / 2;
  870. int x2 = 0;
  871. int y2 = resizedPlayButton.getWidth();
  872. int x3 = 0;
  873. int y3 = 0;
  874. double ym = ( ((Math.pow(x3,2) - Math.pow(x1,2) + Math.pow(y3,2) - Math.pow(y1,2)) *
  875. (x2 - x1)) - (Math.pow(x2,2) - Math.pow(x1,2) + Math.pow(y2,2) -
  876. Math.pow(y1,2)) * (x3 - x1) ) / (2 * ( ((y3 - y1) * (x2 - x1)) -
  877. ((y2 - y1) * (x3 - x1)) ));
  878. double xm = ( (Math.pow(x2,2) - Math.pow(x1,2)) + (Math.pow(y2,2) - Math.pow(y1,2)) -
  879. (2*ym*(y2 - y1)) ) / (2*(x2 - x1));
  880. // offset to top left
  881. double ox = - xm;
  882. c.drawBitmap(thumbnail, 0, 0, null);
  883. Paint p = new Paint();
  884. p.setAlpha(230);
  885. c.drawBitmap(resizedPlayButton, (float) ((thumbnail.getWidth() / 2) + ox),
  886. (float) ((thumbnail.getHeight() / 2) - ym), p);
  887. return resultBitmap;
  888. }
  889. public static AvatarGenerationTask getAvatarWorkerTask(Object callContext) {
  890. if (callContext instanceof ImageView) {
  891. return getAvatarWorkerTask(((ImageView)callContext).getDrawable());
  892. } else if (callContext instanceof MenuItem) {
  893. return getAvatarWorkerTask(((MenuItem)callContext).getIcon());
  894. }
  895. return null;
  896. }
  897. private static AvatarGenerationTask getAvatarWorkerTask(Drawable drawable) {
  898. if (drawable instanceof AsyncAvatarDrawable) {
  899. final AsyncAvatarDrawable asyncDrawable = (AsyncAvatarDrawable) drawable;
  900. return asyncDrawable.getAvatarWorkerTask();
  901. }
  902. return null;
  903. }
  904. public static class AsyncThumbnailDrawable extends BitmapDrawable {
  905. private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
  906. public AsyncThumbnailDrawable(
  907. Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
  908. ) {
  909. super(res, bitmap);
  910. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  911. }
  912. public ThumbnailGenerationTask getBitmapWorkerTask() {
  913. return bitmapWorkerTaskReference.get();
  914. }
  915. }
  916. public static class AsyncResizedImageDrawable extends BitmapDrawable {
  917. private final WeakReference<ResizedImageGenerationTask> bitmapWorkerTaskReference;
  918. public AsyncResizedImageDrawable(Resources res, Bitmap bitmap, ResizedImageGenerationTask bitmapWorkerTask) {
  919. super(res, bitmap);
  920. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  921. }
  922. private ResizedImageGenerationTask getBitmapWorkerTask() {
  923. return bitmapWorkerTaskReference.get();
  924. }
  925. }
  926. public static class AsyncMediaThumbnailDrawable extends BitmapDrawable {
  927. private final WeakReference<MediaThumbnailGenerationTask> bitmapWorkerTaskReference;
  928. public AsyncMediaThumbnailDrawable(Resources res, Bitmap bitmap,
  929. MediaThumbnailGenerationTask bitmapWorkerTask) {
  930. super(res, bitmap);
  931. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  932. }
  933. }
  934. public static class AsyncAvatarDrawable extends BitmapDrawable {
  935. private final WeakReference<AvatarGenerationTask> avatarWorkerTaskReference;
  936. public AsyncAvatarDrawable(Resources res, Drawable bitmap, AvatarGenerationTask avatarWorkerTask) {
  937. super(res, BitmapUtils.drawableToBitmap(bitmap));
  938. avatarWorkerTaskReference = new WeakReference<>(avatarWorkerTask);
  939. }
  940. public AvatarGenerationTask getAvatarWorkerTask() {
  941. return avatarWorkerTaskReference.get();
  942. }
  943. }
  944. private static Bitmap handlePNG(Bitmap bitmap, int pxW, int pxH) {
  945. Bitmap resultBitmap = Bitmap.createBitmap(pxW, pxH, Bitmap.Config.ARGB_8888);
  946. Canvas c = new Canvas(resultBitmap);
  947. c.drawColor(MainApp.getAppContext().getResources().getColor(R.color.background_color));
  948. c.drawBitmap(bitmap, 0, 0, null);
  949. return resultBitmap;
  950. }
  951. public static void generateResizedImage(OCFile file) {
  952. Point p = getScreenDimension();
  953. int pxW = p.x;
  954. int pxH = p.y;
  955. String imageKey = PREFIX_RESIZED_IMAGE + String.valueOf(file.getRemoteId());
  956. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getStoragePath(), pxW, pxH);
  957. if (bitmap != null) {
  958. // Handle PNG
  959. if (file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  960. bitmap = handlePNG(bitmap, pxW, pxH);
  961. }
  962. addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
  963. }
  964. }
  965. }