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
.MultiStatus
;
33 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
35 import com
.owncloud
.android
.authentication
.AccountAuthenticator
;
36 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
37 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
38 import com
.owncloud
.android
.datamodel
.OCFile
;
39 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
40 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
41 import com
.owncloud
.android
.operations
.ExistenceCheckOperation
;
42 import com
.owncloud
.android
.operations
.RemoteOperation
;
43 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
44 import com
.owncloud
.android
.operations
.UploadFileOperation
;
45 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
46 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
48 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
49 import eu
.alefzero
.webdav
.WebdavEntry
;
50 import eu
.alefzero
.webdav
.WebdavUtils
;
52 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
54 import android
.accounts
.Account
;
55 import android
.accounts
.AccountManager
;
56 import android
.accounts
.AccountsException
;
57 import android
.app
.Notification
;
58 import android
.app
.NotificationManager
;
59 import android
.app
.PendingIntent
;
60 import android
.app
.Service
;
61 import android
.content
.Intent
;
62 import android
.os
.Binder
;
63 import android
.os
.Handler
;
64 import android
.os
.HandlerThread
;
65 import android
.os
.IBinder
;
66 import android
.os
.Looper
;
67 import android
.os
.Message
;
68 import android
.os
.Process
;
69 import android
.webkit
.MimeTypeMap
;
70 import android
.widget
.RemoteViews
;
72 import com
.owncloud
.android
.Log_OC
;
73 import com
.owncloud
.android
.MainApp
;
74 import com
.owncloud
.android
.R
;
75 import com
.owncloud
.android
.db
.DbHandler
;
76 import com
.owncloud
.android
.ui
.activity
.FailedUploadActivity
;
77 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
78 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
79 import com
.owncloud
.android
.ui
.activity
.InstantUploadActivity
;
80 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
81 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
83 import eu
.alefzero
.webdav
.WebdavClient
;
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 String
getUploadFinishMessage() {
132 return getClass().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
,
263 AccountAuthenticator
.KEY_OC_VERSION
));
264 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
265 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
266 String uploadKey
= null
;
267 UploadFileOperation newUpload
= null
;
269 for (int i
= 0; i
< files
.length
; i
++) {
270 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
272 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
,
275 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
278 newUpload
.setRemoteFolderToBeCreated();
280 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
); // Grants that the file only upload once time
282 newUpload
.addDatatransferProgressListener(this);
283 newUpload
.addDatatransferProgressListener((FileUploaderBinder
)mBinder
);
284 requestedUploads
.add(uploadKey
);
287 } catch (IllegalArgumentException e
) {
288 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
289 return START_NOT_STICKY
;
291 } catch (IllegalStateException e
) {
292 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
293 return START_NOT_STICKY
;
295 } catch (Exception e
) {
296 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
297 return START_NOT_STICKY
;
301 if (requestedUploads
.size() > 0) {
302 Message msg
= mServiceHandler
.obtainMessage();
304 msg
.obj
= requestedUploads
;
305 mServiceHandler
.sendMessage(msg
);
307 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
308 return Service
.START_NOT_STICKY
;
312 * Provides a binder object that clients can use to perform operations on
313 * the queue of uploads, excepting the addition of new files.
315 * Implemented to perform cancellation, pause and resume of existing
319 public IBinder
onBind(Intent arg0
) {
324 * Called when ALL the bound clients were onbound.
327 public boolean onUnbind(Intent intent
) {
328 ((FileUploaderBinder
)mBinder
).clearListeners();
329 return false
; // not accepting rebinding (default behaviour)
334 * Binder to let client components to perform operations on the queue of
337 * It provides by itself the available operations.
339 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
342 * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
344 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
347 * Cancels a pending or current upload of a remote file.
349 * @param account Owncloud account where the remote file will be stored.
350 * @param file A file in the queue of pending uploads
352 public void cancel(Account account
, OCFile file
) {
353 UploadFileOperation upload
= null
;
354 synchronized (mPendingUploads
) {
355 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
357 if (upload
!= null
) {
364 public void clearListeners() {
365 mBoundListeners
.clear();
372 * Returns True when the file described by 'file' is being uploaded to
373 * the ownCloud account 'account' or waiting for it
375 * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
377 * @param account Owncloud account where the remote file will be stored.
378 * @param file A file that could be in the queue of pending uploads
380 public boolean isUploading(Account account
, OCFile file
) {
381 if (account
== null
|| file
== null
)
383 String targetKey
= buildRemoteName(account
, file
);
384 synchronized (mPendingUploads
) {
385 if (file
.isDirectory()) {
386 // this can be slow if there are many uploads :(
387 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
388 boolean found
= false
;
389 while (it
.hasNext() && !found
) {
390 found
= it
.next().startsWith(targetKey
);
394 return (mPendingUploads
.containsKey(targetKey
));
401 * Adds a listener interested in the progress of the upload for a concrete file.
403 * @param listener Object to notify about progress of transfer.
404 * @param account ownCloud account holding the file of interest.
405 * @param file {@link OCfile} of interest for listener.
407 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
408 if (account
== null
|| file
== null
|| listener
== null
) return;
409 String targetKey
= buildRemoteName(account
, file
);
410 mBoundListeners
.put(targetKey
, listener
);
416 * Removes a listener interested in the progress of the upload for a concrete file.
418 * @param listener Object to notify about progress of transfer.
419 * @param account ownCloud account holding the file of interest.
420 * @param file {@link OCfile} of interest for listener.
422 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
423 if (account
== null
|| file
== null
|| listener
== null
) return;
424 String targetKey
= buildRemoteName(account
, file
);
425 if (mBoundListeners
.get(targetKey
) == listener
) {
426 mBoundListeners
.remove(targetKey
);
432 public void onTransferProgress(long progressRate
) {
433 // old way, should not be in use any more
438 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
440 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
441 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
442 if (boundListener
!= null
) {
443 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
450 * Upload worker. Performs the pending uploads in the order they were
453 * Created with the Looper of a new thread, started in
454 * {@link FileUploader#onCreate()}.
456 private static class ServiceHandler
extends Handler
{
457 // don't make it a final class, and don't remove the static ; lint will
458 // warn about a possible memory leak
459 FileUploader mService
;
461 public ServiceHandler(Looper looper
, FileUploader service
) {
464 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
469 public void handleMessage(Message msg
) {
470 @SuppressWarnings("unchecked")
471 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
472 if (msg
.obj
!= null
) {
473 Iterator
<String
> it
= requestedUploads
.iterator();
474 while (it
.hasNext()) {
475 mService
.uploadFile(it
.next());
478 mService
.stopSelf(msg
.arg1
);
483 * Core upload method: sends the file(s) to upload
485 * @param uploadKey Key to access the upload to perform, contained in
488 public void uploadFile(String uploadKey
) {
490 synchronized (mPendingUploads
) {
491 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
494 if (mCurrentUpload
!= null
) {
496 notifyUploadStart(mCurrentUpload
);
498 RemoteOperationResult uploadResult
= null
, grantResult
= null
;
501 /// prepare client object to send requests to the ownCloud server
502 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
503 mLastAccount
= mCurrentUpload
.getAccount();
504 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
505 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
508 /// check the existence of the parent folder for the file to upload
509 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
510 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
511 grantResult
= grantFolderExistence(remoteParentPath
);
513 /// perform the upload
514 if (grantResult
.isSuccess()) {
515 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
516 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
517 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
518 if (uploadResult
.isSuccess()) {
522 uploadResult
= grantResult
;
525 } catch (AccountsException e
) {
526 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
527 uploadResult
= new RemoteOperationResult(e
);
529 } catch (IOException e
) {
530 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
531 uploadResult
= new RemoteOperationResult(e
);
534 synchronized (mPendingUploads
) {
535 mPendingUploads
.remove(uploadKey
);
536 Log_OC
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
542 notifyUploadResult(uploadResult
, mCurrentUpload
);
543 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
550 * Checks the existence of the folder where the current file will be uploaded both in the remote server
551 * and in the local database.
553 * If the upload is set to enforce the creation of the folder, the method tries to create it both remote
556 * @param pathToGrant Full remote path whose existence will be granted.
557 * @return An {@link OCFile} instance corresponding to the folder where the file will be uploaded.
559 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
560 RemoteOperation operation
= new ExistenceCheckOperation(pathToGrant
, this, false
);
561 RemoteOperationResult result
= operation
.execute(mUploadClient
);
562 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&& mCurrentUpload
.isRemoteFolderToBeCreated()) {
563 operation
= new CreateFolderOperation( pathToGrant
,
566 result
= operation
.execute(mUploadClient
);
568 if (result
.isSuccess()) {
569 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
570 if (parentDir
== null
) {
571 parentDir
= createLocalFolder(pathToGrant
);
573 if (parentDir
!= null
) {
574 result
= new RemoteOperationResult(ResultCode
.OK
);
576 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
583 private OCFile
createLocalFolder(String remotePath
) {
584 String parentPath
= new File(remotePath
).getParent();
585 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
586 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
587 if (parent
== null
) {
588 parent
= createLocalFolder(parentPath
);
590 if (parent
!= null
) {
591 OCFile createdFolder
= new OCFile(remotePath
);
592 createdFolder
.setMimetype("DIR");
593 createdFolder
.setParentId(parent
.getFileId());
594 mStorageManager
.saveFile(createdFolder
);
595 return createdFolder
;
602 * Saves a OC File after a successful upload.
604 * A PROPFIND is necessary to keep the props in the local database
605 * synchronized with the server, specially the modification time and Etag
608 * TODO refactor this ugly thing
610 private void saveUploadedFile() {
611 OCFile file
= mCurrentUpload
.getFile();
612 long syncDate
= System
.currentTimeMillis();
613 file
.setLastSyncDateForData(syncDate
);
615 // / new PROPFIND to keep data consistent with server in theory, should
616 // return the same we already have
617 PropFindMethod propfind
= null
;
618 RemoteOperationResult result
= null
;
620 propfind
= new PropFindMethod(mUploadClient
.getBaseUri()
621 + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
622 int status
= mUploadClient
.executeMethod(propfind
);
623 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
625 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
626 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], mUploadClient
.getBaseUri().getPath());
627 updateOCFile(file
, we
);
628 file
.setLastSyncDateForProperties(syncDate
);
631 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
634 result
= new RemoteOperationResult(isMultiStatus
, status
, propfind
.getResponseHeaders());
635 Log_OC
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
636 + result
.getLogMessage());
638 } catch (Exception e
) {
639 result
= new RemoteOperationResult(e
);
640 Log_OC
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
641 + result
.getLogMessage(), e
);
644 if (propfind
!= null
)
645 propfind
.releaseConnection();
648 // / maybe this would be better as part of UploadFileOperation... or
649 // maybe all this method
650 if (mCurrentUpload
.wasRenamed()) {
651 OCFile oldFile
= mCurrentUpload
.getOldFile();
652 if (oldFile
.fileExists()) {
653 oldFile
.setStoragePath(null
);
654 mStorageManager
.saveFile(oldFile
);
656 } // else: it was just an automatic renaming due to a name
657 // coincidence; nothing else is needed, the storagePath is right
658 // in the instance returned by mCurrentUpload.getFile()
661 mStorageManager
.saveFile(file
);
664 private void updateOCFile(OCFile file
, WebdavEntry we
) {
665 file
.setCreationTimestamp(we
.createTimestamp());
666 file
.setFileLength(we
.contentLength());
667 file
.setMimetype(we
.contentType());
668 file
.setModificationTimestamp(we
.modifiedTimestamp());
669 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
670 // file.setEtag(mCurrentUpload.getEtag()); // TODO Etag, where available
673 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
674 FileDataStorageManager storageManager
) {
675 OCFile newFile
= new OCFile(remotePath
);
676 newFile
.setStoragePath(localPath
);
677 newFile
.setLastSyncDateForProperties(0);
678 newFile
.setLastSyncDateForData(0);
681 if (localPath
!= null
&& localPath
.length() > 0) {
682 File localFile
= new File(localPath
);
683 newFile
.setFileLength(localFile
.length());
684 newFile
.setLastSyncDateForData(localFile
.lastModified());
685 } // don't worry about not assigning size, the problems with localPath
686 // are checked when the UploadFileOperation instance is created
689 if (mimeType
== null
|| mimeType
.length() <= 0) {
691 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
692 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
693 } catch (IndexOutOfBoundsException e
) {
694 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
697 if (mimeType
== null
) {
698 mimeType
= "application/octet-stream";
700 newFile
.setMimetype(mimeType
);
706 * Creates a status notification to show the upload progress
708 * @param upload Upload operation starting.
710 @SuppressWarnings("deprecation")
711 private void notifyUploadStart(UploadFileOperation upload
) {
712 // / create status notification with a progress bar
714 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
),
715 System
.currentTimeMillis());
716 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
717 mDefaultNotificationContentView
= mNotification
.contentView
;
718 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(),
719 R
.layout
.progressbar_layout
);
720 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
721 mNotification
.contentView
.setTextViewText(R
.id
.status_text
,
722 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
723 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
725 /// includes a pending intent in the notification showing the details view of the file
726 Intent showDetailsIntent
= null
;
727 if (PreviewImageFragment
.canBePreviewed(upload
.getFile())) {
728 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
730 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
732 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
733 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
734 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
735 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
736 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
738 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
742 * Callback method to update the progress bar in the status notification
745 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
746 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
747 if (percent
!= mLastPercent
) {
748 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
749 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
750 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
751 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
753 mLastPercent
= percent
;
757 * Callback method to update the progress bar in the status notification
761 public void onTransferProgress(long progressRate
) {
762 // NOTHING TO DO HERE ANYMORE
766 * Updates the status notification with the result of an upload operation.
768 * @param uploadResult Result of the upload operation.
769 * @param upload Finished upload operation
771 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
772 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
773 if (uploadResult
.isCancelled()) {
774 // / cancelled operation -> silent removal of progress notification
775 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
777 } else if (uploadResult
.isSuccess()) {
778 // / success -> silent update of progress notification to success
780 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove
784 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
785 mNotification
.contentView
= mDefaultNotificationContentView
;
787 /// includes a pending intent in the notification showing the details view of the file
788 Intent showDetailsIntent
= null
;
789 if (PreviewImageFragment
.canBePreviewed(upload
.getFile())) {
790 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
792 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
794 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
795 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
796 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
797 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
798 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
800 mNotification
.setLatestEventInfo(getApplicationContext(),
801 getString(R
.string
.uploader_upload_succeeded_ticker
),
802 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
803 mNotification
.contentIntent
);
805 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
); // NOT
807 DbHandler db
= new DbHandler(this.getBaseContext());
808 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
813 // / fail -> explicit failure notification
814 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
815 Notification finalNotification
= new Notification(R
.drawable
.icon
,
816 getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
817 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
818 String content
= null
;
820 boolean needsToUpdateCredentials
= (uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
821 //(uploadResult.isTemporalRedirection() && uploadResult.isIdPRedirection() &&
822 (uploadResult
.isIdPRedirection() &&
823 MainApp
.getAuthTokenTypeSamlSessionCookie().equals(mUploadClient
.getAuthTokenType())));
824 if (needsToUpdateCredentials
) {
825 // let the user update credentials with one click
826 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
827 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
828 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
829 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
830 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
831 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
832 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
833 finalNotification
.contentIntent
= PendingIntent
.getActivity(this, (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
834 content
= String
.format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
835 finalNotification
.setLatestEventInfo(getApplicationContext(),
836 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
837 mUploadClient
= null
; // grant that future retries on the same account will get the fresh credentials
839 // TODO put something smart in the contentIntent below
840 // finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
843 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
844 || uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
845 // TODO we need a class to provide error messages for the users
846 // from a RemoteOperationResult and a RemoteOperation
847 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(),
848 getString(R
.string
.app_name
));
849 } else if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
850 content
= getString(R
.string
.failed_upload_quota_exceeded_text
);
853 .format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
856 // we add only for instant-uploads the InstantUploadActivity and the
858 Intent detailUploadIntent
= null
;
859 if (upload
.isInstant() && InstantUploadActivity
.IS_ENABLED
) {
860 detailUploadIntent
= new Intent(this, InstantUploadActivity
.class);
861 detailUploadIntent
.putExtra(FileUploader
.KEY_ACCOUNT
, upload
.getAccount());
863 detailUploadIntent
= new Intent(this, FailedUploadActivity
.class);
864 detailUploadIntent
.putExtra(FailedUploadActivity
.MESSAGE
, content
);
866 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
867 (int) System
.currentTimeMillis(), detailUploadIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
868 | PendingIntent
.FLAG_ONE_SHOT
);
870 if (upload
.isInstant()) {
873 db
= new DbHandler(this.getBaseContext());
874 String message
= uploadResult
.getLogMessage() + " errorCode: " + uploadResult
.getCode();
875 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
876 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
877 message
= getString(R
.string
.failed_upload_quota_exceeded_text
);
878 if (db
.updateFileState(upload
.getOriginalStoragePath(), DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
880 db
.putFileForLater(upload
.getOriginalStoragePath(), upload
.getAccount().name
, message
);
890 finalNotification
.setLatestEventInfo(getApplicationContext(),
891 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
893 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
899 * Sends a broadcast in order to the interested activities can update their
902 * @param upload Finished upload operation
903 * @param uploadResult Result of the upload operation
905 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
906 Intent end
= new Intent(getUploadFinishMessage());
907 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
912 if (upload
.wasRenamed()) {
913 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
915 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
916 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
917 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
918 sendStickyBroadcast(end
);