Studying lack of upload when a file that was not previously down is set as favourite...
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileUploader.java
index da352ed..c8916ef 100644 (file)
@@ -1,3 +1,21 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012 Bartek Przybylski
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 3 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
 package com.owncloud.android.files.services;
 
 import java.io.File;
@@ -7,6 +25,10 @@ import java.util.Vector;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
+import org.apache.http.HttpStatus;
+import org.apache.jackrabbit.webdav.MultiStatus;
+import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
+
 import com.owncloud.android.authenticator.AccountAuthenticator;
 import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
@@ -19,6 +41,8 @@ import com.owncloud.android.ui.fragment.FileDetailFragment;
 import com.owncloud.android.utils.OwnCloudVersion;
 
 import eu.alefzero.webdav.OnDatatransferProgressListener;
+import eu.alefzero.webdav.WebdavEntry;
+import eu.alefzero.webdav.WebdavUtils;
 
 import com.owncloud.android.network.OwnCloudClientUtils;
 
@@ -69,7 +93,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
     private ServiceHandler mServiceHandler;
     private IBinder mBinder;
     private WebdavClient mUploadClient = null;
-    private Account mLastAccount = null, mLastAccountWhereInstantFolderWasCreated = null;
+    private Account mLastAccount = null;
     private FileDataStorageManager mStorageManager;
 
     private ConcurrentMap<String, UploadFileOperation> mPendingUploads = new ConcurrentHashMap<String, UploadFileOperation>();
@@ -180,15 +204,22 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         UploadFileOperation newUpload = null;
         OCFile file = null;
         FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
+        boolean fixed = false;
+        if (isInstant) {
+            fixed = checkAndFixInstantUploadDirectory(storageManager);
+        }
         try {
             for (int i=0; i < localPaths.length; i++) {
                 uploadKey = buildRemoteName(account, remotePaths[i]);
-                file = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes!=null)?mimeTypes[i]:(String)null), forceOverwrite, storageManager);
+                file = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes!=null)?mimeTypes[i]:(String)null), isInstant, forceOverwrite, storageManager);
                 if (chunked) {
                     newUpload = new ChunkedUploadFileOperation(account, file, isInstant, forceOverwrite);
                 } else {
                     newUpload = new UploadFileOperation(account, file, isInstant, forceOverwrite);
                 }
+                if (fixed && i==0) {
+                    newUpload.setRemoteFolderToBeCreated();
+                }
                 mPendingUploads.putIfAbsent(uploadKey, newUpload);
                 newUpload.addDatatransferProgressListener(this);
                 requestedUploads.add(uploadKey);
@@ -197,6 +228,15 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         } catch (IllegalArgumentException e) {
             Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
             return START_NOT_STICKY;
+            
+        } catch (IllegalStateException e) {
+            Log.e(TAG, "Bad information provided in intent: " + e.getMessage());
+            return START_NOT_STICKY;
+            
+        } catch (Exception e) {
+            Log.e(TAG, "Unexpected exception while processing upload intent", e);
+            return START_NOT_STICKY;
+            
         }
         
         if (requestedUploads.size() > 0) {
@@ -315,18 +355,18 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                 mUploadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
             }
             
-            /// create remote folder for instant uploads, "if necessary" (would be great that HEAD to a folder worked as with files, we should check; but it's not WebDAV standard, anyway
-            if (mCurrentUpload.isInstant() && !mLastAccountWhereInstantFolderWasCreated.equals(mCurrentUpload.getAccount())) {
-                mLastAccountWhereInstantFolderWasCreated = mCurrentUpload.getAccount();
-                createRemoteFolderForInstantUploads(mUploadClient, mStorageManager);
+            /// create remote folder for instant uploads
+            if (mCurrentUpload.isRemoteFolderToBeCreated()) {
+                mUploadClient.createDirectory(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);    // ignoring result; fail could just mean that it already exists, but local database is not synchronized; the upload will be tried anyway
             }
-        
+
+            
             /// perform the upload
             RemoteOperationResult uploadResult = null;
             try {
                 uploadResult = mCurrentUpload.execute(mUploadClient);
                 if (uploadResult.isSuccess()) {
-                    saveUploadedFile(mCurrentUpload.getFile(), mStorageManager);
+                    saveUploadedFile();
                 }
                 
             } finally {
@@ -345,39 +385,94 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
     }
 
     /**
-     * Create remote folder for instant uploads if necessary.
+     * Saves a OC File after a successful upload.
+     * 
+     * A PROPFIND is necessary to keep the props in the local database synchronized with the server, 
+     * specially the modification time and Etag (where available)
      * 
-     * @param client            WebdavClient to the ownCloud server.
-     * @param storageManager    Interface to the local database caching the data in the server.
-     * @return                  'True' if the folder exists when the methods finishes.
+     * TODO refactor this ugly thing
      */
-    private boolean createRemoteFolderForInstantUploads(WebdavClient client, FileDataStorageManager storageManager) {
-        boolean result = true;
+    private void saveUploadedFile() {
+        OCFile file = mCurrentUpload.getFile();
+        
+        PropFindMethod propfind = null;
+        RemoteOperationResult result = null;
+        try {
+          propfind = new PropFindMethod(mUploadClient.getBaseUri() + WebdavUtils.encodePath(mCurrentUpload.getRemotePath()));
+          int status = mUploadClient.executeMethod(propfind);
+          boolean isMultiStatus = status == HttpStatus.SC_MULTI_STATUS;
+          if (isMultiStatus) {
+              MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
+              WebdavEntry we = new WebdavEntry(resp.getResponses()[0],
+                                               mUploadClient.getBaseUri().getPath());
+              OCFile newFile = fillOCFile(we);
+              newFile.setStoragePath(file.getStoragePath());
+              newFile.setKeepInSync(file.keepInSync());
+              file = newFile;
+              
+          } else {
+              // this would be a problem
+              mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
+          }
+          
+          result = new RemoteOperationResult(isMultiStatus, status);
+          Log.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": " + result.getLogMessage());
+          
+        } catch (Exception e) {
+            result = new RemoteOperationResult(e);
+            Log.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": " + result.getLogMessage(), e);
+
+        } finally {
+            if (propfind != null)
+                propfind.releaseConnection();
+        }
+
+        if (!result.isSuccess()) {
+            // file was successfully uploaded, but the new time stamp and Etag in the server could not be read; 
+            // just keeping old values :(
+            if (!mCurrentUpload.getRemotePath().equals(file.getRemotePath())) {
+                // true when the file was automatically renamed to avoid an overwrite 
+                OCFile newFile = new OCFile(mCurrentUpload.getRemotePath());
+                newFile.setCreationTimestamp(file.getCreationTimestamp());
+                newFile.setFileLength(file.getFileLength());
+                newFile.setMimetype(file.getMimetype());
+                newFile.setModificationTimestamp(file.getModificationTimestamp());  // this is specially BAD
+                // newFile.setEtag(file.getEtag()) // TODO and this is still worse 
+                file = newFile;
+            }
+        }
+        
+        file.setLastSyncDate(System.currentTimeMillis());
+        mStorageManager.saveFile(file);
+    }
+
+    
+    private OCFile fillOCFile(WebdavEntry we) {
+        OCFile file = new OCFile(we.decodedPath());
+        file.setCreationTimestamp(we.createTimestamp());
+        file.setFileLength(we.contentLength());
+        file.setMimetype(we.contentType());
+        file.setModificationTimestamp(we.modifiedTimesamp());
+        // file.setEtag(mCurrentDownload.getEtag());    // TODO Etag, where available
+        return file;
+    }
+    
+    
+    private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager) {
         OCFile instantUploadDir = storageManager.getFileByPath(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
         if (instantUploadDir == null) {
-            result = client.createDirectory(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);    // fail could just mean that it already exists, but local database is not synchronized; the upload will be started anyway
+            // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
             OCFile newDir = new OCFile(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
             newDir.setMimetype("DIR");
             newDir.setParentId(storageManager.getFileByPath(OCFile.PATH_SEPARATOR).getFileId());
             storageManager.saveFile(newDir);
+            return true;
         }
-        return result;
+        return false;
     }
 
-    /**
-     * Saves a new OC File after a successful upload.
-     * 
-     * @param file              OCFile describing the uploaded file
-     * @param storageManager    Interface to the database where the new OCFile has to be stored.
-     * @param parentDirId       Id of the parent OCFile.
-     */
-    private void saveUploadedFile(OCFile file, FileDataStorageManager storageManager) {
-        file.setModificationTimestamp(System.currentTimeMillis());
-        storageManager.saveFile(file);
-    }
-    
     
-    private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType, boolean forceOverwrite, FileDataStorageManager storageManager) {
+    private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType, boolean isInstant, boolean forceOverwrite, FileDataStorageManager storageManager) {
         OCFile newFile = new OCFile(remotePath);
         newFile.setStoragePath(localPath);
         newFile.setLastSyncDate(0);
@@ -407,9 +502,12 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         // parent dir
         String parentPath = new File(remotePath).getParent();
         parentPath = parentPath.endsWith("/")?parentPath:parentPath+"/" ;
-        long parentDirId = storageManager.getFileByPath(parentPath).getFileId();
+        OCFile parentDir = storageManager.getFileByPath(parentPath);
+        if (parentDir == null) {
+            throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath);
+        }
+        long parentDirId = parentDir.getFileId();
         newFile.setParentId(parentDirId);
-        
         return newFile;
     }
     
@@ -435,7 +533,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
         showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
         showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-        mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, showDetailsIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+        mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
         
         mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
     }
@@ -488,7 +586,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
             showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
             showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
             showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-            mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, showDetailsIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+            mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
             
             mNotification.setLatestEventInfo(   getApplicationContext(), 
                                                 getString(R.string.uploader_upload_succeeded_ticker), 
@@ -510,7 +608,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
             Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
             finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
             // TODO put something smart in the contentIntent below
-            finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
+            finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
             finalNotification.setLatestEventInfo(   getApplicationContext(), 
                                                     getString(R.string.uploader_upload_failed_ticker), 
                                                     String.format(getString(R.string.uploader_upload_failed_content_single), (new File(upload.getStoragePath())).getName()),