Quick patch to fix operations not ready for HTTPS
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / files / services / FileUploader.java
index 9f2e3e7..db2461c 100644 (file)
@@ -1,16 +1,10 @@
 package eu.alefzero.owncloud.files.services;
 
 import java.io.File;
-import java.util.List;
 
-import eu.alefzero.owncloud.AccountUtils;
-import eu.alefzero.owncloud.R;
-import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
-import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
-import eu.alefzero.owncloud.datamodel.OCFile;
-import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;
-import eu.alefzero.owncloud.utils.OwnCloudVersion;
-import eu.alefzero.webdav.WebdavClient;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.HeadMethod;
+
 import android.accounts.Account;
 import android.accounts.AccountManager;
 import android.app.Notification;
@@ -18,7 +12,6 @@ import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Service;
 import android.content.Intent;
-import android.net.Uri;
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.IBinder;
@@ -29,6 +22,11 @@ import android.util.Log;
 import android.webkit.MimeTypeMap;
 import android.widget.RemoteViews;
 import android.widget.Toast;
+import eu.alefzero.owncloud.R;
+import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
+import eu.alefzero.owncloud.datamodel.OCFile;
+import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;
+import eu.alefzero.webdav.WebdavClient;
 
 public class FileUploader extends Service implements OnDatatransferProgressListener {
 
@@ -39,6 +37,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
     public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
     public static final String KEY_ACCOUNT = "ACCOUNT";
     public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
+    public static final String ACCOUNT_NAME = "ACCOUNT_NAME";    
 
     public static final int UPLOAD_SINGLE_FILE = 0;
     public static final int UPLOAD_MULTIPLE_FILES = 1;
@@ -47,14 +46,13 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
     private NotificationManager mNotificationManager;
     private Looper mServiceLooper;
     private ServiceHandler mServiceHandler;
-    private AccountManager mAccountManager;
     private Account mAccount;
     private String[] mLocalPaths, mRemotePaths;
-    private boolean mResult;
     private int mUploadType;
     private Notification mNotification;
     private int mTotalDataToSend, mSendData;
     private int mCurrentIndexUpload, mPreviousPercent;
+    private int mSuccessCounter;
 
     @Override
     public IBinder onBind(Intent arg0) {
@@ -82,7 +80,6 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         thread.start();
         mServiceLooper = thread.getLooper();
         mServiceHandler = new ServiceHandler(mServiceLooper);
-        mAccountManager = AccountManager.get(this);
     }
 
     @Override
@@ -106,9 +103,6 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
             mRemotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
         }
 
-        for (int i = 0; i < mRemotePaths.length; ++i)
-            mRemotePaths[i] = mRemotePaths[i].replace(' ', '+');
-
         if (mLocalPaths.length != mRemotePaths.length) {
             Log.e(TAG, "Remote paths and local paths are not equal!");
             return Service.START_NOT_STICKY;
@@ -122,24 +116,16 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
     }
 
     public void run() {
-        if (mResult) {
-            Toast.makeText(this, "Upload successfull", Toast.LENGTH_SHORT)
-                    .show();
+        String message;
+        if (mSuccessCounter == mLocalPaths.length) {
+            message = getString(R.string.uploader_upload_succeed); 
         } else {
-            Toast.makeText(this, "Upload could not be completed", Toast.LENGTH_SHORT).show();
+            message = String.format(getString(R.string.uploader_upload_failed), mSuccessCounter, mLocalPaths.length); 
         }
+        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
     }
 
     public void uploadFile() {
-        String baseUrl = mAccountManager.getUserData(mAccount,
-                AccountAuthenticator.KEY_OC_BASE_URL), ocVerStr = mAccountManager
-                .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
-        OwnCloudVersion ocVer = new OwnCloudVersion(ocVerStr);
-        String webdav_path = AccountUtils.getWebdavPath(ocVer);
-        Uri ocUri = Uri.parse(baseUrl + webdav_path);
-        String username = mAccount.name.substring(0,
-                mAccount.name.lastIndexOf('@'));
-        String password = mAccountManager.getPassword(mAccount);
         FileDataStorageManager storageManager = new FileDataStorageManager(mAccount, getContentResolver());
         
         mTotalDataToSend = mSendData = mPreviousPercent = 0;
@@ -157,10 +143,9 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         
         mNotificationManager.notify(42, mNotification);
 
-        WebdavClient wc = new WebdavClient(ocUri);
+        WebdavClient wc = new WebdavClient(mAccount, getApplicationContext());
         wc.allowSelfsignedCertificates();
         wc.setDataTransferProgressListener(this);
-        wc.setCredentials(username, password);
 
         for (int i = 0; i < mLocalPaths.length; ++i) {
             File f = new File(mLocalPaths[i]);
@@ -169,9 +154,11 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         
         Log.d(TAG, "Will upload " + mTotalDataToSend + " bytes, with " + mLocalPaths.length + " files");
         
+        mSuccessCounter = 0;
+        
         for (int i = 0; i < mLocalPaths.length; ++i) {
             
-            String mimeType;
+            String mimeType = null;
             try {
                 mimeType = MimeTypeMap.getSingleton()
                         .getMimeTypeFromExtension(
@@ -179,13 +166,14 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                                     .lastIndexOf('.') + 1));
             } catch (IndexOutOfBoundsException e) {
                 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + mLocalPaths[i]);
-                mimeType = "application/octet-stream";
             }
+            if (mimeType == null)
+                mimeType = "application/octet-stream";
             
-            mResult = false;
             mCurrentIndexUpload = i;
-            if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
-                mResult |= true;
+            mRemotePaths[i] = getAvailableRemotePath(wc, mRemotePaths[i]);
+            if (mRemotePaths[i] != null && wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
+                mSuccessCounter++;
                 OCFile new_file = new OCFile(mRemotePaths[i]);
                 new_file.setMimetype(mimeType);
                 new_file.setFileLength(new File(mLocalPaths[i]).length());
@@ -199,6 +187,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                 
                 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
                 end.putExtra(EXTRA_PARENT_DIR_ID, parentDirId);
+                end.putExtra(ACCOUNT_NAME, mAccount.name);
                 sendBroadcast(end);
             }
             
@@ -207,6 +196,46 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         run();
     }
 
+    /**
+     * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
+     * file is overwritten.
+     * 
+     * @param string
+     * @return
+     */
+    private String getAvailableRemotePath(WebdavClient wc, String remotePath) {
+        Boolean check = wc.existsFile(remotePath);
+        if (check == null) {    // null means fail
+            return null;
+        } else if (!check) {
+            return remotePath;
+        }
+    
+        int pos = remotePath.lastIndexOf(".");
+        String suffix = "";
+        String extension = "";
+        if (pos >= 0) {
+            extension = remotePath.substring(pos+1);
+            remotePath = remotePath.substring(0, pos);
+        }
+        int count = 2;
+        while (check != null && check) {
+            suffix = " (" + count + ")";
+            if (pos >= 0)
+                check = wc.existsFile(remotePath + suffix + "." + extension);
+            else
+                check = wc.existsFile(remotePath + suffix);
+            count++;
+        }
+        if (check == null) {
+            return null;
+        } else if (pos >=0) {
+            return remotePath + suffix + "." + extension;
+        } else {
+            return remotePath + suffix;
+        }
+    }
+
     @Override
     public void transferProgress(long progressRate) {
         mSendData += progressRate;