ThumbnailsCacheManager.java 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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);
  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 (file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  262. thumbnail = handlePNG(thumbnail, pxW);
  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);
  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);
  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. try {
  707. Thread.sleep(3000);
  708. } catch (InterruptedException e) {
  709. e.printStackTrace();
  710. }
  711. int px = getAvatarDimension();
  712. // Download avatar from server
  713. OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
  714. if (mClient != null && serverOCVersion != null) {
  715. if (serverOCVersion.supportsRemoteThumbnails()) {
  716. GetMethod get = null;
  717. try {
  718. String userId = AccountManager.get(MainApp.getAppContext()).getUserData(mAccount,
  719. com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
  720. if (TextUtils.isEmpty(userId)) {
  721. userId = AccountUtils.getAccountUsername(username);
  722. }
  723. String uri = mClient.getBaseUri() + "/index.php/avatar/" + Uri.encode(userId) + "/" + px;
  724. Log_OC.d("Avatar", "URI: " + uri);
  725. get = new GetMethod(uri);
  726. if (!eTag.isEmpty()) {
  727. get.setRequestHeader("If-None-Match", eTag);
  728. }
  729. int status = mClient.executeMethod(get);
  730. // we are using eTag to download a new avatar only if it changed
  731. switch (status) {
  732. case HttpStatus.SC_OK:
  733. // new avatar
  734. InputStream inputStream = get.getResponseBodyAsStream();
  735. if (get.getResponseHeader(ETAG) != null) {
  736. eTag = get.getResponseHeader(ETAG).getValue().replace("\"", "");
  737. arbitraryDataProvider.storeOrUpdateKeyValue(mAccount.name, AVATAR, eTag);
  738. }
  739. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  740. avatar = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  741. // Add avatar to cache
  742. if (avatar != null) {
  743. avatar = handlePNG(avatar, px);
  744. String newImageKey = "a_" + username + "_" + eTag;
  745. addBitmapToCache(newImageKey, avatar);
  746. } else {
  747. return TextDrawable.createAvatar(mAccount.name, mAvatarRadius);
  748. }
  749. break;
  750. case HttpStatus.SC_NOT_MODIFIED:
  751. // old avatar
  752. avatar = getBitmapFromDiskCache(imageKey);
  753. mClient.exhaustResponse(get.getResponseBodyAsStream());
  754. break;
  755. default:
  756. // everything else
  757. mClient.exhaustResponse(get.getResponseBodyAsStream());
  758. break;
  759. }
  760. } catch (Exception e) {
  761. Log_OC.e(TAG, "Error downloading avatar", e);
  762. } finally {
  763. if (get != null) {
  764. get.releaseConnection();
  765. }
  766. }
  767. } else {
  768. Log_OC.d(TAG, "Server too old");
  769. }
  770. }
  771. return BitmapUtils.bitmapToCircularBitmapDrawable(mResources, avatar);
  772. }
  773. }
  774. public static boolean cancelPotentialThumbnailWork(Object file, ImageView imageView) {
  775. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  776. if (bitmapWorkerTask != null) {
  777. final Object bitmapData = bitmapWorkerTask.mFile;
  778. // If bitmapData is not yet set or it differs from the new data
  779. if (bitmapData == null || !bitmapData.equals(file)) {
  780. // Cancel previous task
  781. bitmapWorkerTask.cancel(true);
  782. Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView");
  783. } else {
  784. // The same work is already in progress
  785. return false;
  786. }
  787. }
  788. // No task associated with the ImageView, or an existing task was cancelled
  789. return true;
  790. }
  791. public static boolean cancelPotentialAvatarWork(Object file, Object callContext) {
  792. if (callContext instanceof ImageView) {
  793. return cancelPotentialAvatarWork(file, (ImageView) callContext);
  794. } else if (callContext instanceof MenuItem) {
  795. return cancelPotentialAvatarWork(file, (MenuItem)callContext);
  796. }
  797. return false;
  798. }
  799. public static boolean cancelPotentialAvatarWork(Object file, ImageView imageView) {
  800. final AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(imageView);
  801. if (avatarWorkerTask != null) {
  802. final Object usernameData = avatarWorkerTask.mUsername;
  803. // If usernameData is not yet set or it differs from the new data
  804. if (usernameData == null || !usernameData.equals(file)) {
  805. // Cancel previous task
  806. avatarWorkerTask.cancel(true);
  807. Log_OC.v(TAG, "Cancelled generation of avatar for a reused imageView");
  808. } else {
  809. // The same work is already in progress
  810. return false;
  811. }
  812. }
  813. // No task associated with the ImageView, or an existing task was cancelled
  814. return true;
  815. }
  816. public static boolean cancelPotentialAvatarWork(Object file, MenuItem menuItem) {
  817. final AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(menuItem);
  818. if (avatarWorkerTask != null) {
  819. final Object usernameData = avatarWorkerTask.mUsername;
  820. // If usernameData is not yet set or it differs from the new data
  821. if (usernameData == null || !usernameData.equals(file)) {
  822. // Cancel previous task
  823. avatarWorkerTask.cancel(true);
  824. Log_OC.v(TAG, "Cancelled generation of avatar for a reused imageView");
  825. } else {
  826. // The same work is already in progress
  827. return false;
  828. }
  829. }
  830. // No task associated with the ImageView, or an existing task was cancelled
  831. return true;
  832. }
  833. public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
  834. if (imageView != null) {
  835. final Drawable drawable = imageView.getDrawable();
  836. if (drawable instanceof AsyncThumbnailDrawable) {
  837. final AsyncThumbnailDrawable asyncDrawable = (AsyncThumbnailDrawable) drawable;
  838. return asyncDrawable.getBitmapWorkerTask();
  839. }
  840. }
  841. return null;
  842. }
  843. private static ResizedImageGenerationTask getResizedImageGenerationWorkerTask(ImageView imageView) {
  844. if (imageView != null) {
  845. final Drawable drawable = imageView.getDrawable();
  846. if (drawable instanceof AsyncResizedImageDrawable) {
  847. final AsyncResizedImageDrawable asyncDrawable = (AsyncResizedImageDrawable) drawable;
  848. return asyncDrawable.getBitmapWorkerTask();
  849. }
  850. }
  851. return null;
  852. }
  853. public static Bitmap addVideoOverlay(Bitmap thumbnail){
  854. Bitmap playButton = BitmapFactory.decodeResource(MainApp.getAppContext().getResources(),
  855. R.drawable.view_play);
  856. Bitmap resizedPlayButton = Bitmap.createScaledBitmap(playButton,
  857. (int) (thumbnail.getWidth() * 0.3),
  858. (int) (thumbnail.getHeight() * 0.3), true);
  859. Bitmap resultBitmap = Bitmap.createBitmap(thumbnail.getWidth(),
  860. thumbnail.getHeight(),
  861. Bitmap.Config.ARGB_8888);
  862. Canvas c = new Canvas(resultBitmap);
  863. // compute visual center of play button, according to resized image
  864. int x1 = resizedPlayButton.getWidth();
  865. int y1 = resizedPlayButton.getHeight() / 2;
  866. int x2 = 0;
  867. int y2 = resizedPlayButton.getWidth();
  868. int x3 = 0;
  869. int y3 = 0;
  870. double ym = ( ((Math.pow(x3,2) - Math.pow(x1,2) + Math.pow(y3,2) - Math.pow(y1,2)) *
  871. (x2 - x1)) - (Math.pow(x2,2) - Math.pow(x1,2) + Math.pow(y2,2) -
  872. Math.pow(y1,2)) * (x3 - x1) ) / (2 * ( ((y3 - y1) * (x2 - x1)) -
  873. ((y2 - y1) * (x3 - x1)) ));
  874. double xm = ( (Math.pow(x2,2) - Math.pow(x1,2)) + (Math.pow(y2,2) - Math.pow(y1,2)) -
  875. (2*ym*(y2 - y1)) ) / (2*(x2 - x1));
  876. // offset to top left
  877. double ox = - xm;
  878. c.drawBitmap(thumbnail, 0, 0, null);
  879. Paint p = new Paint();
  880. p.setAlpha(230);
  881. c.drawBitmap(resizedPlayButton, (float) ((thumbnail.getWidth() / 2) + ox),
  882. (float) ((thumbnail.getHeight() / 2) - ym), p);
  883. return resultBitmap;
  884. }
  885. public static AvatarGenerationTask getAvatarWorkerTask(Object callContext) {
  886. if (callContext instanceof ImageView) {
  887. return getAvatarWorkerTask(((ImageView)callContext).getDrawable());
  888. } else if (callContext instanceof MenuItem) {
  889. return getAvatarWorkerTask(((MenuItem)callContext).getIcon());
  890. }
  891. return null;
  892. }
  893. private static AvatarGenerationTask getAvatarWorkerTask(Drawable drawable) {
  894. if (drawable instanceof AsyncAvatarDrawable) {
  895. final AsyncAvatarDrawable asyncDrawable = (AsyncAvatarDrawable) drawable;
  896. return asyncDrawable.getAvatarWorkerTask();
  897. }
  898. return null;
  899. }
  900. public static class AsyncThumbnailDrawable extends BitmapDrawable {
  901. private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
  902. public AsyncThumbnailDrawable(
  903. Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
  904. ) {
  905. super(res, bitmap);
  906. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  907. }
  908. public ThumbnailGenerationTask getBitmapWorkerTask() {
  909. return bitmapWorkerTaskReference.get();
  910. }
  911. }
  912. public static class AsyncResizedImageDrawable extends BitmapDrawable {
  913. private final WeakReference<ResizedImageGenerationTask> bitmapWorkerTaskReference;
  914. public AsyncResizedImageDrawable(Resources res, Bitmap bitmap, ResizedImageGenerationTask bitmapWorkerTask) {
  915. super(res, bitmap);
  916. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  917. }
  918. private ResizedImageGenerationTask getBitmapWorkerTask() {
  919. return bitmapWorkerTaskReference.get();
  920. }
  921. }
  922. public static class AsyncMediaThumbnailDrawable extends BitmapDrawable {
  923. private final WeakReference<MediaThumbnailGenerationTask> bitmapWorkerTaskReference;
  924. public AsyncMediaThumbnailDrawable(Resources res, Bitmap bitmap,
  925. MediaThumbnailGenerationTask bitmapWorkerTask) {
  926. super(res, bitmap);
  927. bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
  928. }
  929. }
  930. public static class AsyncAvatarDrawable extends BitmapDrawable {
  931. private final WeakReference<AvatarGenerationTask> avatarWorkerTaskReference;
  932. public AsyncAvatarDrawable(Resources res, Drawable bitmap, AvatarGenerationTask avatarWorkerTask) {
  933. super(res, BitmapUtils.drawableToBitmap(bitmap));
  934. avatarWorkerTaskReference = new WeakReference<>(avatarWorkerTask);
  935. }
  936. public AvatarGenerationTask getAvatarWorkerTask() {
  937. return avatarWorkerTaskReference.get();
  938. }
  939. }
  940. private static Bitmap handlePNG(Bitmap bitmap, int px){
  941. Bitmap resultBitmap = Bitmap.createBitmap(px,
  942. px,
  943. Bitmap.Config.ARGB_8888);
  944. Canvas c = new Canvas(resultBitmap);
  945. c.drawColor(MainApp.getAppContext().getResources().
  946. getColor(R.color.background_color));
  947. c.drawBitmap(bitmap, 0, 0, null);
  948. return resultBitmap;
  949. }
  950. public static void generateResizedImage(OCFile file) {
  951. Point p = getScreenDimension();
  952. int pxW = p.x;
  953. int pxH = p.y;
  954. String imageKey = PREFIX_RESIZED_IMAGE + String.valueOf(file.getRemoteId());
  955. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(file.getStoragePath(), pxW, pxH);
  956. if (bitmap != null) {
  957. // Handle PNG
  958. if (file.getMimetype().equalsIgnoreCase(PNG_MIMETYPE)) {
  959. bitmap = handlePNG(bitmap, pxW);
  960. }
  961. addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
  962. }
  963. }
  964. }