1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.files
.services
;
22 import java
.io
.IOException
;
23 import java
.util
.AbstractList
;
24 import java
.util
.HashMap
;
25 import java
.util
.Iterator
;
27 import java
.util
.Vector
;
28 import java
.util
.concurrent
.ConcurrentHashMap
;
29 import java
.util
.concurrent
.ConcurrentMap
;
31 import org
.apache
.http
.HttpStatus
;
32 import org
.apache
.jackrabbit
.webdav
.DavConstants
;
33 import org
.apache
.jackrabbit
.webdav
.MultiStatus
;
34 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
36 import com
.owncloud
.android
.R
;
37 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
38 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
39 import com
.owncloud
.android
.datamodel
.OCFile
;
40 import com
.owncloud
.android
.db
.DbHandler
;
41 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
42 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
43 import com
.owncloud
.android
.operations
.ExistenceCheckOperation
;
44 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperation
;
45 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperationResult
;
46 import com
.owncloud
.android
.operations
.UploadFileOperation
;
47 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperationResult
.ResultCode
;
48 import com
.owncloud
.android
.oc_framework
.utils
.OwnCloudVersion
;
49 import com
.owncloud
.android
.oc_framework
.network
.webdav
.OnDatatransferProgressListener
;
50 import com
.owncloud
.android
.oc_framework
.accounts
.OwnCloudAccount
;
51 import com
.owncloud
.android
.oc_framework
.network
.webdav
.ChunkFromFileChannelRequestEntity
;
52 import com
.owncloud
.android
.oc_framework
.network
.webdav
.OwnCloudClientFactory
;
53 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavClient
;
54 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavEntry
;
55 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavUtils
;
56 import com
.owncloud
.android
.ui
.activity
.FailedUploadActivity
;
57 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
58 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
59 import com
.owncloud
.android
.ui
.activity
.InstantUploadActivity
;
60 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
61 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
62 import com
.owncloud
.android
.utils
.DisplayUtils
;
63 import com
.owncloud
.android
.utils
.Log_OC
;
65 import android
.accounts
.Account
;
66 import android
.accounts
.AccountManager
;
67 import android
.accounts
.AccountsException
;
68 import android
.app
.Notification
;
69 import android
.app
.NotificationManager
;
70 import android
.app
.PendingIntent
;
71 import android
.app
.Service
;
72 import android
.content
.Intent
;
73 import android
.os
.Binder
;
74 import android
.os
.Handler
;
75 import android
.os
.HandlerThread
;
76 import android
.os
.IBinder
;
77 import android
.os
.Looper
;
78 import android
.os
.Message
;
79 import android
.os
.Process
;
80 import android
.webkit
.MimeTypeMap
;
81 import android
.widget
.RemoteViews
;
85 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
87 private static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
88 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
89 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
90 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
91 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
92 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
94 public static final String KEY_FILE
= "FILE";
95 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
96 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
97 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
99 public static final String KEY_ACCOUNT
= "ACCOUNT";
101 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
102 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
103 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
104 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
106 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
107 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
108 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
110 public static final int UPLOAD_SINGLE_FILE
= 0;
111 public static final int UPLOAD_MULTIPLE_FILES
= 1;
113 private static final String TAG
= FileUploader
.class.getSimpleName();
115 private Looper mServiceLooper
;
116 private ServiceHandler mServiceHandler
;
117 private IBinder mBinder
;
118 private WebdavClient mUploadClient
= null
;
119 private Account mLastAccount
= null
;
120 private FileDataStorageManager mStorageManager
;
122 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
123 private UploadFileOperation mCurrentUpload
= null
;
125 private NotificationManager mNotificationManager
;
126 private Notification mNotification
;
127 private int mLastPercent
;
128 private RemoteViews mDefaultNotificationContentView
;
131 public static String
getUploadFinishMessage() {
132 return FileUploader
.class.getName().toString() + UPLOAD_FINISH_MESSAGE
;
136 * Builds a key for mPendingUploads from the account and file to upload
138 * @param account Account where the file to upload is stored
139 * @param file File to upload
141 private String
buildRemoteName(Account account
, OCFile file
) {
142 return account
.name
+ file
.getRemotePath();
145 private String
buildRemoteName(Account account
, String remotePath
) {
146 return account
.name
+ remotePath
;
150 * Checks if an ownCloud server version should support chunked uploads.
152 * @param version OwnCloud version instance corresponding to an ownCloud
154 * @return 'True' if the ownCloud server with version supports chunked
157 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
158 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
162 * Service initialization
165 public void onCreate() {
167 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
168 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
169 HandlerThread thread
= new HandlerThread("FileUploaderThread", Process
.THREAD_PRIORITY_BACKGROUND
);
171 mServiceLooper
= thread
.getLooper();
172 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
173 mBinder
= new FileUploaderBinder();
177 * Entry point to add one or several files to the queue of uploads.
179 * New uploads are added calling to startService(), resulting in a call to
180 * this method. This ensures the service will keep on working although the
181 * caller activity goes away.
184 public int onStartCommand(Intent intent
, int flags
, int startId
) {
185 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
186 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
187 Log_OC
.e(TAG
, "Not enough information provided in intent");
188 return Service
.START_NOT_STICKY
;
190 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
191 if (uploadType
== -1) {
192 Log_OC
.e(TAG
, "Incorrect upload type provided");
193 return Service
.START_NOT_STICKY
;
195 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
197 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
198 OCFile
[] files
= null
;
199 if (uploadType
== UPLOAD_SINGLE_FILE
) {
201 if (intent
.hasExtra(KEY_FILE
)) {
202 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
205 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
206 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
207 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
210 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
212 if (intent
.hasExtra(KEY_FILE
)) {
213 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
221 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
222 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
223 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
227 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
229 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
230 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
231 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
233 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
234 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
235 return Service
.START_NOT_STICKY
;
237 } else if (!intent
.hasExtra(KEY_FILE
)) {
238 if (localPaths
== null
) {
239 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
240 return Service
.START_NOT_STICKY
;
242 if (remotePaths
== null
) {
243 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
244 return Service
.START_NOT_STICKY
;
246 if (localPaths
.length
!= remotePaths
.length
) {
247 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
248 return Service
.START_NOT_STICKY
;
251 files
= new OCFile
[localPaths
.length
];
252 for (int i
= 0; i
< localPaths
.length
; i
++) {
253 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!= null
) ? mimeTypes
[i
]
254 : (String
) null
), storageManager
);
255 if (files
[i
] == null
) {
256 // TODO @andomaex add failure Notiification
257 return Service
.START_NOT_STICKY
;
262 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
, OwnCloudAccount
.Constants
.KEY_OC_VERSION
));
263 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
264 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
265 String uploadKey
= null
;
266 UploadFileOperation newUpload
= null
;
268 for (int i
= 0; i
< files
.length
; i
++) {
269 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
271 && (new File(files
[i
].getStoragePath())).length() > ChunkedUploadFileOperation
.CHUNK_SIZE
) // added to work around bug in servers 5.x
273 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
,
276 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
279 newUpload
.setRemoteFolderToBeCreated();
281 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
); // Grants that the file only upload once time
283 newUpload
.addDatatransferProgressListener(this);
284 newUpload
.addDatatransferProgressListener((FileUploaderBinder
)mBinder
);
285 requestedUploads
.add(uploadKey
);
288 } catch (IllegalArgumentException e
) {
289 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
290 return START_NOT_STICKY
;
292 } catch (IllegalStateException e
) {
293 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
294 return START_NOT_STICKY
;
296 } catch (Exception e
) {
297 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
298 return START_NOT_STICKY
;
302 if (requestedUploads
.size() > 0) {
303 Message msg
= mServiceHandler
.obtainMessage();
305 msg
.obj
= requestedUploads
;
306 mServiceHandler
.sendMessage(msg
);
308 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
309 return Service
.START_NOT_STICKY
;
313 * Provides a binder object that clients can use to perform operations on
314 * the queue of uploads, excepting the addition of new files.
316 * Implemented to perform cancellation, pause and resume of existing
320 public IBinder
onBind(Intent arg0
) {
325 * Called when ALL the bound clients were onbound.
328 public boolean onUnbind(Intent intent
) {
329 ((FileUploaderBinder
)mBinder
).clearListeners();
330 return false
; // not accepting rebinding (default behaviour)
335 * Binder to let client components to perform operations on the queue of
338 * It provides by itself the available operations.
340 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
343 * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
345 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
348 * Cancels a pending or current upload of a remote file.
350 * @param account Owncloud account where the remote file will be stored.
351 * @param file A file in the queue of pending uploads
353 public void cancel(Account account
, OCFile file
) {
354 UploadFileOperation upload
= null
;
355 synchronized (mPendingUploads
) {
356 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
358 if (upload
!= null
) {
365 public void clearListeners() {
366 mBoundListeners
.clear();
373 * Returns True when the file described by 'file' is being uploaded to
374 * the ownCloud account 'account' or waiting for it
376 * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
378 * @param account Owncloud account where the remote file will be stored.
379 * @param file A file that could be in the queue of pending uploads
381 public boolean isUploading(Account account
, OCFile file
) {
382 if (account
== null
|| file
== null
)
384 String targetKey
= buildRemoteName(account
, file
);
385 synchronized (mPendingUploads
) {
386 if (file
.isFolder()) {
387 // this can be slow if there are many uploads :(
388 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
389 boolean found
= false
;
390 while (it
.hasNext() && !found
) {
391 found
= it
.next().startsWith(targetKey
);
395 return (mPendingUploads
.containsKey(targetKey
));
402 * Adds a listener interested in the progress of the upload for a concrete file.
404 * @param listener Object to notify about progress of transfer.
405 * @param account ownCloud account holding the file of interest.
406 * @param file {@link OCfile} of interest for listener.
408 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
409 if (account
== null
|| file
== null
|| listener
== null
) return;
410 String targetKey
= buildRemoteName(account
, file
);
411 mBoundListeners
.put(targetKey
, listener
);
417 * Removes a listener interested in the progress of the upload for a concrete file.
419 * @param listener Object to notify about progress of transfer.
420 * @param account ownCloud account holding the file of interest.
421 * @param file {@link OCfile} of interest for listener.
423 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
424 if (account
== null
|| file
== null
|| listener
== null
) return;
425 String targetKey
= buildRemoteName(account
, file
);
426 if (mBoundListeners
.get(targetKey
) == listener
) {
427 mBoundListeners
.remove(targetKey
);
433 public void onTransferProgress(long progressRate
) {
434 // old way, should not be in use any more
439 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
441 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
442 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
443 if (boundListener
!= null
) {
444 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
451 * Upload worker. Performs the pending uploads in the order they were
454 * Created with the Looper of a new thread, started in
455 * {@link FileUploader#onCreate()}.
457 private static class ServiceHandler
extends Handler
{
458 // don't make it a final class, and don't remove the static ; lint will
459 // warn about a possible memory leak
460 FileUploader mService
;
462 public ServiceHandler(Looper looper
, FileUploader service
) {
465 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
470 public void handleMessage(Message msg
) {
471 @SuppressWarnings("unchecked")
472 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
473 if (msg
.obj
!= null
) {
474 Iterator
<String
> it
= requestedUploads
.iterator();
475 while (it
.hasNext()) {
476 mService
.uploadFile(it
.next());
479 mService
.stopSelf(msg
.arg1
);
484 * Core upload method: sends the file(s) to upload
486 * @param uploadKey Key to access the upload to perform, contained in
489 public void uploadFile(String uploadKey
) {
491 synchronized (mPendingUploads
) {
492 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
495 if (mCurrentUpload
!= null
) {
497 notifyUploadStart(mCurrentUpload
);
499 RemoteOperationResult uploadResult
= null
, grantResult
= null
;
502 /// prepare client object to send requests to the ownCloud server
503 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
504 mLastAccount
= mCurrentUpload
.getAccount();
505 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
506 mUploadClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastAccount
, getApplicationContext());
509 /// check the existence of the parent folder for the file to upload
510 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
511 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
512 grantResult
= grantFolderExistence(remoteParentPath
);
514 /// perform the upload
515 if (grantResult
.isSuccess()) {
516 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
517 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
518 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
519 if (uploadResult
.isSuccess()) {
523 uploadResult
= grantResult
;
526 } catch (AccountsException e
) {
527 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
528 uploadResult
= new RemoteOperationResult(e
);
530 } catch (IOException e
) {
531 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
532 uploadResult
= new RemoteOperationResult(e
);
535 synchronized (mPendingUploads
) {
536 mPendingUploads
.remove(uploadKey
);
537 Log_OC
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
539 if (uploadResult
.isException()) {
540 // enforce the creation of a new client object for next uploads; this grant that a new socket will
541 // be created in the future if the current exception is due to an abrupt lose of network connection
542 mUploadClient
= null
;
548 notifyUploadResult(uploadResult
, mCurrentUpload
);
549 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
556 * Checks the existence of the folder where the current file will be uploaded both in the remote server
557 * and in the local database.
559 * If the upload is set to enforce the creation of the folder, the method tries to create it both remote
562 * @param pathToGrant Full remote path whose existence will be granted.
563 * @return An {@link OCFile} instance corresponding to the folder where the file will be uploaded.
565 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
566 RemoteOperation operation
= new ExistenceCheckOperation(pathToGrant
, this, false
);
567 RemoteOperationResult result
= operation
.execute(mUploadClient
);
568 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&& mCurrentUpload
.isRemoteFolderToBeCreated()) {
569 operation
= new CreateFolderOperation( pathToGrant
,
572 result
= operation
.execute(mUploadClient
);
574 if (result
.isSuccess()) {
575 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
576 if (parentDir
== null
) {
577 parentDir
= createLocalFolder(pathToGrant
);
579 if (parentDir
!= null
) {
580 result
= new RemoteOperationResult(ResultCode
.OK
);
582 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
589 private OCFile
createLocalFolder(String remotePath
) {
590 String parentPath
= new File(remotePath
).getParent();
591 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
592 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
593 if (parent
== null
) {
594 parent
= createLocalFolder(parentPath
);
596 if (parent
!= null
) {
597 OCFile createdFolder
= new OCFile(remotePath
);
598 createdFolder
.setMimetype("DIR");
599 createdFolder
.setParentId(parent
.getFileId());
600 mStorageManager
.saveFile(createdFolder
);
601 return createdFolder
;
608 * Saves a OC File after a successful upload.
610 * A PROPFIND is necessary to keep the props in the local database
611 * synchronized with the server, specially the modification time and Etag
614 * TODO refactor this ugly thing
616 private void saveUploadedFile() {
617 OCFile file
= mCurrentUpload
.getFile();
618 long syncDate
= System
.currentTimeMillis();
619 file
.setLastSyncDateForData(syncDate
);
621 // / new PROPFIND to keep data consistent with server in theory, should
622 // return the same we already have
623 PropFindMethod propfind
= null
;
624 RemoteOperationResult result
= null
;
626 propfind
= new PropFindMethod(mUploadClient
.getBaseUri() + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()),
627 DavConstants
.PROPFIND_ALL_PROP
,
628 DavConstants
.DEPTH_0
);
629 int status
= mUploadClient
.executeMethod(propfind
);
630 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
632 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
633 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], mUploadClient
.getBaseUri().getPath());
634 updateOCFile(file
, we
);
635 file
.setLastSyncDateForProperties(syncDate
);
638 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
641 result
= new RemoteOperationResult(isMultiStatus
, status
, propfind
.getResponseHeaders());
642 Log_OC
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
643 + result
.getLogMessage());
645 } catch (Exception e
) {
646 result
= new RemoteOperationResult(e
);
647 Log_OC
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
648 + result
.getLogMessage(), e
);
651 if (propfind
!= null
)
652 propfind
.releaseConnection();
655 // / maybe this would be better as part of UploadFileOperation... or
656 // maybe all this method
657 if (mCurrentUpload
.wasRenamed()) {
658 OCFile oldFile
= mCurrentUpload
.getOldFile();
659 if (oldFile
.fileExists()) {
660 oldFile
.setStoragePath(null
);
661 mStorageManager
.saveFile(oldFile
);
663 } // else: it was just an automatic renaming due to a name
664 // coincidence; nothing else is needed, the storagePath is right
665 // in the instance returned by mCurrentUpload.getFile()
668 mStorageManager
.saveFile(file
);
671 private void updateOCFile(OCFile file
, WebdavEntry we
) {
672 file
.setCreationTimestamp(we
.createTimestamp());
673 file
.setFileLength(we
.contentLength());
674 file
.setMimetype(we
.contentType());
675 file
.setModificationTimestamp(we
.modifiedTimestamp());
676 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
677 // file.setEtag(mCurrentUpload.getEtag()); // TODO Etag, where available
680 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
681 FileDataStorageManager storageManager
) {
682 OCFile newFile
= new OCFile(remotePath
);
683 newFile
.setStoragePath(localPath
);
684 newFile
.setLastSyncDateForProperties(0);
685 newFile
.setLastSyncDateForData(0);
688 if (localPath
!= null
&& localPath
.length() > 0) {
689 File localFile
= new File(localPath
);
690 newFile
.setFileLength(localFile
.length());
691 newFile
.setLastSyncDateForData(localFile
.lastModified());
692 } // don't worry about not assigning size, the problems with localPath
693 // are checked when the UploadFileOperation instance is created
696 if (mimeType
== null
|| mimeType
.length() <= 0) {
698 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
699 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
700 } catch (IndexOutOfBoundsException e
) {
701 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
704 if (mimeType
== null
) {
705 mimeType
= "application/octet-stream";
707 newFile
.setMimetype(mimeType
);
713 * Creates a status notification to show the upload progress
715 * @param upload Upload operation starting.
717 @SuppressWarnings("deprecation")
718 private void notifyUploadStart(UploadFileOperation upload
) {
719 // / create status notification with a progress bar
721 mNotification
= new Notification(DisplayUtils
.getSeasonalIconId(), getString(R
.string
.uploader_upload_in_progress_ticker
),
722 System
.currentTimeMillis());
723 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
724 mDefaultNotificationContentView
= mNotification
.contentView
;
725 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(),
726 R
.layout
.progressbar_layout
);
727 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
728 mNotification
.contentView
.setTextViewText(R
.id
.status_text
,
729 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
730 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, DisplayUtils
.getSeasonalIconId());
732 /// includes a pending intent in the notification showing the details view of the file
733 Intent showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
734 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
735 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
736 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
737 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
738 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
740 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
744 * Callback method to update the progress bar in the status notification
747 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
748 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
749 if (percent
!= mLastPercent
) {
750 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
751 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
752 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
753 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
755 mLastPercent
= percent
;
759 * Callback method to update the progress bar in the status notification
763 public void onTransferProgress(long progressRate
) {
764 // NOTHING TO DO HERE ANYMORE
768 * Updates the status notification with the result of an upload operation.
770 * @param uploadResult Result of the upload operation.
771 * @param upload Finished upload operation
773 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
774 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
775 if (uploadResult
.isCancelled()) {
776 // / cancelled operation -> silent removal of progress notification
777 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
779 } else if (uploadResult
.isSuccess()) {
780 // / success -> silent update of progress notification to success
782 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove
786 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
787 mNotification
.contentView
= mDefaultNotificationContentView
;
789 /// includes a pending intent in the notification showing the details view of the file
790 Intent showDetailsIntent
= null
;
791 if (PreviewImageFragment
.canBePreviewed(upload
.getFile())) {
792 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
794 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
796 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
797 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
798 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
799 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
800 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
802 mNotification
.setLatestEventInfo(getApplicationContext(),
803 getString(R
.string
.uploader_upload_succeeded_ticker
),
804 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
805 mNotification
.contentIntent
);
807 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
); // NOT
809 DbHandler db
= new DbHandler(this.getBaseContext());
810 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
815 // / fail -> explicit failure notification
816 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
817 Notification finalNotification
= new Notification(DisplayUtils
.getSeasonalIconId(),
818 getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
819 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
820 String content
= null
;
822 boolean needsToUpdateCredentials
= (uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
823 //(uploadResult.isTemporalRedirection() && uploadResult.isIdPRedirection() &&
824 (uploadResult
.isIdPRedirection() &&
825 mUploadClient
.getCredentials() == null
));
826 //MainApp.getAuthTokenTypeSamlSessionCookie().equals(mUploadClient.getAuthTokenType())));
827 if (needsToUpdateCredentials
) {
828 // let the user update credentials with one click
829 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
830 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
831 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
832 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
833 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
834 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
835 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
836 finalNotification
.contentIntent
= PendingIntent
.getActivity(this, (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
837 content
= String
.format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
838 finalNotification
.setLatestEventInfo(getApplicationContext(),
839 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
840 mUploadClient
= null
; // grant that future retries on the same account will get the fresh credentials
842 // TODO put something smart in the contentIntent below
843 // finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
846 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
847 || uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
848 // TODO we need a class to provide error messages for the users
849 // from a RemoteOperationResult and a RemoteOperation
850 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(),
851 getString(R
.string
.app_name
));
852 } else if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
853 content
= getString(R
.string
.failed_upload_quota_exceeded_text
);
856 .format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
859 // we add only for instant-uploads the InstantUploadActivity and the
861 Intent detailUploadIntent
= null
;
862 if (upload
.isInstant() && InstantUploadActivity
.IS_ENABLED
) {
863 detailUploadIntent
= new Intent(this, InstantUploadActivity
.class);
864 detailUploadIntent
.putExtra(FileUploader
.KEY_ACCOUNT
, upload
.getAccount());
866 detailUploadIntent
= new Intent(this, FailedUploadActivity
.class);
867 detailUploadIntent
.putExtra(FailedUploadActivity
.MESSAGE
, content
);
869 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
870 (int) System
.currentTimeMillis(), detailUploadIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
871 | PendingIntent
.FLAG_ONE_SHOT
);
873 if (upload
.isInstant()) {
876 db
= new DbHandler(this.getBaseContext());
877 String message
= uploadResult
.getLogMessage() + " errorCode: " + uploadResult
.getCode();
878 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
879 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
880 message
= getString(R
.string
.failed_upload_quota_exceeded_text
);
881 if (db
.updateFileState(upload
.getOriginalStoragePath(), DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
883 db
.putFileForLater(upload
.getOriginalStoragePath(), upload
.getAccount().name
, message
);
893 finalNotification
.setLatestEventInfo(getApplicationContext(),
894 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
896 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
902 * Sends a broadcast in order to the interested activities can update their
905 * @param upload Finished upload operation
906 * @param uploadResult Result of the upload operation
908 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
909 Intent end
= new Intent(getUploadFinishMessage());
910 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
915 if (upload
.wasRenamed()) {
916 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
918 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
919 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
920 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
921 sendStickyBroadcast(end
);