ThumbnailsCacheManager.java 47 KB

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