check available beta version
[pub/Android/ownCloud.git] / src / com / owncloud / android / datamodel / ThumbnailsCacheManager.java
index a5ea595..10dfbd7 100644 (file)
 package com.owncloud.android.datamodel;
 
 import java.io.File;
+import java.io.InputStream;
 import java.lang.ref.WeakReference;
+import java.net.FileNameMap;
+import java.net.URLConnection;
 
 import org.apache.commons.httpclient.HttpStatus;
 import org.apache.commons.httpclient.methods.GetMethod;
@@ -34,8 +37,12 @@ import android.content.res.Resources;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.CompressFormat;
 import android.graphics.BitmapFactory;
+import android.graphics.Canvas;
 import android.graphics.Point;
+import android.graphics.Canvas;
+import android.graphics.Paint;
 import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.ColorDrawable;
 import android.graphics.drawable.Drawable;
 import android.media.ThumbnailUtils;
 import android.net.Uri;
@@ -48,15 +55,16 @@ import android.widget.ProgressBar;
 
 import com.owncloud.android.MainApp;
 import com.owncloud.android.R;
+import com.owncloud.android.authentication.AccountUtils;
 import com.owncloud.android.lib.common.OwnCloudAccount;
 import com.owncloud.android.lib.common.OwnCloudClient;
 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
-import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
 import com.owncloud.android.lib.common.utils.Log_OC;
 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
 import com.owncloud.android.ui.adapter.DiskLruImageCache;
 import com.owncloud.android.utils.BitmapUtils;
 import com.owncloud.android.utils.DisplayUtils;
+import com.owncloud.android.utils.FileStorageUtils;
 
 /**
  * Manager for concurrent access to thumbnails cache.
@@ -66,8 +74,7 @@ public class ThumbnailsCacheManager {
     private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
     
     private static final String CACHE_FOLDER = "thumbnailCache";
-    private static final String MINOR_SERVER_VERSION_FOR_THUMBS = "7.8.0";
-    
+
     private static final Object mThumbnailsDiskCacheLock = new Object();
     private static DiskLruImageCache mThumbnailCache = null;
     private static boolean mThumbnailCacheStarting = true;
@@ -76,12 +83,11 @@ public class ThumbnailsCacheManager {
     private static final CompressFormat mCompressFormat = CompressFormat.JPEG;
     private static final int mCompressQuality = 70;
     private static OwnCloudClient mClient = null;
-    private static String mServerVersion = null;
 
     public static Bitmap mDefaultImg = 
             BitmapFactory.decodeResource(
-                    MainApp.getAppContext().getResources(), 
-                    DisplayUtils.getFileTypeIconId("image/png", "default.png")
+                    MainApp.getAppContext().getResources(),
+                    R.drawable.file_image
             );
 
     
@@ -135,15 +141,39 @@ public class ThumbnailsCacheManager {
             while (mThumbnailCacheStarting) {
                 try {
                     mThumbnailsDiskCacheLock.wait();
-                } catch (InterruptedException e) {}
+                } catch (InterruptedException e) {
+                    Log_OC.e(TAG, "Wait in mThumbnailsDiskCacheLock was interrupted", e);
+                }
             }
             if (mThumbnailCache != null) {
-                return (Bitmap) mThumbnailCache.getBitmap(key);
+                return mThumbnailCache.getBitmap(key);
             }
         }
         return null;
     }
 
+    /**
+     * Sets max size of cache
+     * @param maxSize in MB
+     * @return
+     */
+    public static boolean setMaxSize(long maxSize){
+        if (mThumbnailCache != null){
+            mThumbnailCache.setMaxSize(maxSize * 1024 * 1024);
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    public static long getMaxSize(){
+        if (mThumbnailCache != null) {
+            return mThumbnailCache.getMaxSize();
+        } else {
+            return -1l;
+        }
+    }
+
     public static class ThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
         private final WeakReference<ImageView> mImageViewReference;
         private WeakReference<ProgressBar> mProgressWheelRef;
@@ -179,9 +209,6 @@ public class ThumbnailsCacheManager {
 
             try {
                 if (mAccount != null) {
-                    AccountManager accountMgr = AccountManager.get(MainApp.getAppContext());
-
-                    mServerVersion = accountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION);
                     OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount,
                             MainApp.getAppContext());
                     mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
@@ -194,10 +221,20 @@ public class ThumbnailsCacheManager {
                 
                 if (mFile instanceof OCFile) {
                     thumbnail = doOCFileInBackground(mIsThumbnail);
+
+                    if (((OCFile) mFile).isVideo()){
+                        thumbnail = addVideoOverlay(thumbnail);
+                    }
                 }  else if (mFile instanceof File) {
                     thumbnail = doFileInBackground(mIsThumbnail);
-                } else {
-                    // do nothing
+
+                    String url = ((File) mFile).getAbsolutePath();
+                    String mMimeType = FileStorageUtils.getMimeTypeFromName(url);
+
+                    if (mMimeType != null && mMimeType.startsWith("video/")){
+                        thumbnail = addVideoOverlay(thumbnail);
+                    }
+                //} else {  do nothing
                 }
 
                 }catch(Throwable t){
@@ -212,19 +249,15 @@ public class ThumbnailsCacheManager {
         }
 
         protected void onPostExecute(Bitmap bitmap){
-            if (isCancelled()) {
-                bitmap = null;
-            }
-
-            if (mImageViewReference != null && bitmap != null) {
+            if (bitmap != null) {
                 final ImageView imageView = mImageViewReference.get();
                 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
-                if (this == bitmapWorkerTask && imageView != null) {
+                if (this == bitmapWorkerTask) {
                     String tagId = "";
                     if (mFile instanceof OCFile){
                         tagId = String.valueOf(((OCFile)mFile).getFileId());
                     } else if (mFile instanceof File){
-                        tagId = String.valueOf(((File)mFile).hashCode());
+                        tagId = String.valueOf(mFile.hashCode());
                     }
                     if (String.valueOf(imageView.getTag()).equals(tagId)) {
                         if (mProgressWheelRef != null) {
@@ -269,7 +302,7 @@ public class ThumbnailsCacheManager {
         private int getThumbnailDimension(){
             // Converts dp to pixel
             Resources r = MainApp.getAppContext().getResources();
-            return (int) Math.round(r.getDimension(R.dimen.file_icon_size_grid));
+            return Math.round(r.getDimension(R.dimen.file_icon_size_grid));
         }
 
         private Point getScreenDimension(){
@@ -310,11 +343,18 @@ public class ThumbnailsCacheManager {
                 }
 
                 if (file.isDown()) {
-                    Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
+                    Bitmap tempBitmap = BitmapUtils.decodeSampledBitmapFromFile(
                             file.getStoragePath(), pxW, pxH);
+                    Bitmap bitmap = ThumbnailUtils.extractThumbnail(tempBitmap, pxW, pxH);
 
                     if (bitmap != null) {
-                        thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
+                        // Handle PNG
+                        if (file.getMimetype().equalsIgnoreCase("image/png")) {
+                            bitmap = handlePNG(bitmap, pxW);
+                        }
+
+                        thumbnail = addThumbnailToCache(imageKey, bitmap,
+                                                        file.getStoragePath(), pxW, pxH);
 
                         file.setNeedsUpdateThumbnail(false);
                         mStorageManager.saveFile(file);
@@ -322,44 +362,55 @@ public class ThumbnailsCacheManager {
 
                 } else {
                     // Download thumbnail from server
-                    if (mClient != null && mServerVersion != null) {
-                        OwnCloudVersion serverOCVersion = new OwnCloudVersion(mServerVersion);
-                        if (serverOCVersion.compareTo(
-                                new OwnCloudVersion(MINOR_SERVER_VERSION_FOR_THUMBS)) >= 0) {
+                    OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
+                    if (mClient != null && serverOCVersion != null) {
+                        if (serverOCVersion.supportsRemoteThumbnails()) {
                             try {
-                                int status = -1;
-
-                                String uri = mClient.getBaseUri() + "" +
-                                        "/index.php/apps/files/api/v1/thumbnail/" +
-                                        pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
-                                Log_OC.d("Thumbnail", "URI: " + uri);
-                                GetMethod get = new GetMethod(uri);
-                                status = mClient.executeMethod(get);
-                                if (status == HttpStatus.SC_OK) {
-                                    byte[] bytes = get.getResponseBody();
-
-                                    String type = "";
-                                    if (mIsThumbnail){
-                                        type = "Thumbnail";
+                                if (mIsThumbnail) {
+                                    String uri = mClient.getBaseUri() + "" +
+                                            "/index.php/apps/files/api/v1/thumbnail/" +
+                                            pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
+                                    Log_OC.d("Thumbnail", "Download URI: " + uri);
+                                    GetMethod get = new GetMethod(uri);
+                                    int status = mClient.executeMethod(get);
+                                    if (status == HttpStatus.SC_OK) {
+                                        InputStream inputStream = get.getResponseBodyAsStream();
+                                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
+                                        thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
                                     } else {
-                                        type = "Resized image";
+                                        Log_OC.d(TAG, "Status: " + status);
                                     }
-                                    Log_OC.d("Thumbnail", type + " size of " + file.getRemotePath() + ": " + bytes.length);
-
-                                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
-                                            bytes.length);
-
-                                    if (mIsThumbnail) {
-                                        thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
+                                } else {
+                                    String gallery = "";
+                                    if (serverOCVersion.supportsNativeGallery()){
+                                        gallery = "gallery";
                                     } else {
-                                        thumbnail = bitmap;
+                                        gallery = "galleryplus";
                                     }
 
-                                    // Add thumbnail to cache
-                                    if (thumbnail != null) {
-                                        addBitmapToCache(imageKey, thumbnail);
+                                    String uri = mClient.getBaseUri() +
+                                            "/index.php/apps/" + gallery + "/api/preview/" + Integer.parseInt(file.getRemoteId().substring(0,8)) +
+                                            "/" + pxW + "/" + pxH;
+                                    Log_OC.d("Thumbnail", "FileName: " + file.getFileName() + " Download URI: " + uri);
+                                    GetMethod get = new GetMethod(uri);
+                                    int status = mClient.executeMethod(get);
+                                    if (status == HttpStatus.SC_OK) {
+                                        InputStream inputStream = get.getResponseBodyAsStream();
+                                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
+                                        // Download via gallery app
+                                        thumbnail = bitmap;
                                     }
                                 }
+
+                                // Handle PNG
+                                if (thumbnail != null && file.getMimetype().equalsIgnoreCase("image/png")) {
+                                    thumbnail = handlePNG(thumbnail, pxW);
+                                }
+
+                                // Add thumbnail to cache
+                                if (thumbnail != null) {
+                                    addBitmapToCache(imageKey, thumbnail);
+                                }
                             } catch (Exception e) {
                                 e.printStackTrace();
                             }
@@ -374,14 +425,34 @@ public class ThumbnailsCacheManager {
 
         }
 
+        private Bitmap handlePNG(Bitmap bitmap, int px){
+            Bitmap resultBitmap = Bitmap.createBitmap(px,
+                    px,
+                    Bitmap.Config.ARGB_8888);
+            Canvas c = new Canvas(resultBitmap);
+
+            c.drawColor(MainApp.getAppContext().getResources().
+                    getColor(R.color.background_color));
+            c.drawBitmap(bitmap, 0, 0, null);
+
+            return resultBitmap;
+        }
+
         private Bitmap doFileInBackground(Boolean mIsThumbnail) {
-            Bitmap thumbnail = null;
             File file = (File)mFile;
 
-            final String imageKey = String.valueOf(file.hashCode());
+            // distinguish between thumbnail and resized image
+            String temp = String.valueOf(file.hashCode());
+            if (mIsThumbnail){
+                temp = "t" + temp;
+            } else {
+                temp = "r" + temp;
+            }
+
+            final String imageKey = temp;
 
             // Check disk cache in background thread
-            thumbnail = getBitmapFromDiskCache(imageKey);
+            Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
 
             // Not found in disk cache
             if (thumbnail == null) {
@@ -416,6 +487,7 @@ public class ThumbnailsCacheManager {
             if (bitmapData == null || bitmapData != file) {
                 // Cancel previous task
                 bitmapWorkerTask.cancel(true);
+                Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView");
             } else {
                 // The same work is already in progress
                 return false;
@@ -436,6 +508,51 @@ public class ThumbnailsCacheManager {
         return null;
     }
 
+    public static Bitmap addVideoOverlay(Bitmap thumbnail){
+        Bitmap playButton = BitmapFactory.decodeResource(MainApp.getAppContext().getResources(),
+                R.drawable.view_play);
+
+        Bitmap resizedPlayButton = Bitmap.createScaledBitmap(playButton,
+                (int) (thumbnail.getWidth() * 0.3),
+                (int) (thumbnail.getHeight() * 0.3), true);
+
+        Bitmap resultBitmap = Bitmap.createBitmap(thumbnail.getWidth(),
+                thumbnail.getHeight(),
+                Bitmap.Config.ARGB_8888);
+
+        Canvas c = new Canvas(resultBitmap);
+
+        // compute visual center of play button, according to resized image
+        int x1 = resizedPlayButton.getWidth();
+        int y1 = resizedPlayButton.getHeight() / 2;
+        int x2 = 0;
+        int y2 = resizedPlayButton.getWidth();
+        int x3 = 0;
+        int y3 = 0;
+
+        double ym = ( ((Math.pow(x3,2) - Math.pow(x1,2) + Math.pow(y3,2) - Math.pow(y1,2)) *
+                    (x2 - x1)) - (Math.pow(x2,2) - Math.pow(x1,2) + Math.pow(y2,2) -
+                    Math.pow(y1,2)) * (x3 - x1) )  /  (2 * ( ((y3 - y1) * (x2 - x1)) -
+                    ((y2 - y1) * (x3 - x1)) ));
+        double xm = ( (Math.pow(x2,2) - Math.pow(x1,2)) + (Math.pow(y2,2) - Math.pow(y1,2)) -
+                    (2*ym*(y2 - y1)) ) / (2*(x2 - x1));
+
+        // offset to top left
+        double ox = - xm;
+        double oy = thumbnail.getHeight() - ym;
+
+
+        c.drawBitmap(thumbnail, 0, 0, null);
+
+        Paint p = new Paint();
+        p.setAlpha(230);
+
+        c.drawBitmap(resizedPlayButton, (float) ((thumbnail.getWidth() / 2) + ox),
+                                        (float) ((thumbnail.getHeight() / 2) - ym), p);
+
+        return resultBitmap;
+    }
+
     public static class AsyncDrawable extends BitmapDrawable {
         private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;