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
.authentication
.AccountAuthenticator
;
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
.operations
.ChunkedUploadFileOperation
;
41 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
42 import com
.owncloud
.android
.operations
.ExistenceCheckOperation
;
43 import com
.owncloud
.android
.operations
.RemoteOperation
;
44 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
45 import com
.owncloud
.android
.operations
.UploadFileOperation
;
46 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
47 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
49 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
50 import eu
.alefzero
.webdav
.WebdavEntry
;
51 import eu
.alefzero
.webdav
.WebdavUtils
;
53 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
55 import android
.accounts
.Account
;
56 import android
.accounts
.AccountManager
;
57 import android
.accounts
.AccountsException
;
58 import android
.app
.Notification
;
59 import android
.app
.NotificationManager
;
60 import android
.app
.PendingIntent
;
61 import android
.app
.Service
;
62 import android
.content
.Intent
;
63 import android
.os
.Binder
;
64 import android
.os
.Handler
;
65 import android
.os
.HandlerThread
;
66 import android
.os
.IBinder
;
67 import android
.os
.Looper
;
68 import android
.os
.Message
;
69 import android
.os
.Process
;
70 import android
.webkit
.MimeTypeMap
;
71 import android
.widget
.RemoteViews
;
73 import com
.owncloud
.android
.Log_OC
;
74 import com
.owncloud
.android
.MainApp
;
75 import com
.owncloud
.android
.R
;
76 import com
.owncloud
.android
.db
.DbHandler
;
77 import com
.owncloud
.android
.ui
.activity
.FailedUploadActivity
;
78 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
79 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
80 import com
.owncloud
.android
.ui
.activity
.InstantUploadActivity
;
81 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
82 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
84 import eu
.alefzero
.webdav
.WebdavClient
;
86 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
88 private static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
89 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
90 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
91 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
92 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
93 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
95 public static final String KEY_FILE
= "FILE";
96 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
97 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
98 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
100 public static final String KEY_ACCOUNT
= "ACCOUNT";
102 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
103 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
104 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
105 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
107 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
108 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
109 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
111 public static final int UPLOAD_SINGLE_FILE
= 0;
112 public static final int UPLOAD_MULTIPLE_FILES
= 1;
114 private static final String TAG
= FileUploader
.class.getSimpleName();
116 private Looper mServiceLooper
;
117 private ServiceHandler mServiceHandler
;
118 private IBinder mBinder
;
119 private WebdavClient mUploadClient
= null
;
120 private Account mLastAccount
= null
;
121 private FileDataStorageManager mStorageManager
;
123 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
124 private UploadFileOperation mCurrentUpload
= null
;
126 private NotificationManager mNotificationManager
;
127 private Notification mNotification
;
128 private int mLastPercent
;
129 private RemoteViews mDefaultNotificationContentView
;
132 public String
getUploadFinishMessage() {
133 return getClass().getName().toString() + UPLOAD_FINISH_MESSAGE
;
137 * Builds a key for mPendingUploads from the account and file to upload
139 * @param account Account where the file to upload is stored
140 * @param file File to upload
142 private String
buildRemoteName(Account account
, OCFile file
) {
143 return account
.name
+ file
.getRemotePath();
146 private String
buildRemoteName(Account account
, String remotePath
) {
147 return account
.name
+ remotePath
;
151 * Checks if an ownCloud server version should support chunked uploads.
153 * @param version OwnCloud version instance corresponding to an ownCloud
155 * @return 'True' if the ownCloud server with version supports chunked
158 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
159 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
163 * Service initialization
166 public void onCreate() {
168 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
169 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
170 HandlerThread thread
= new HandlerThread("FileUploaderThread", Process
.THREAD_PRIORITY_BACKGROUND
);
172 mServiceLooper
= thread
.getLooper();
173 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
174 mBinder
= new FileUploaderBinder();
178 * Entry point to add one or several files to the queue of uploads.
180 * New uploads are added calling to startService(), resulting in a call to
181 * this method. This ensures the service will keep on working although the
182 * caller activity goes away.
185 public int onStartCommand(Intent intent
, int flags
, int startId
) {
186 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
187 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
188 Log_OC
.e(TAG
, "Not enough information provided in intent");
189 return Service
.START_NOT_STICKY
;
191 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
192 if (uploadType
== -1) {
193 Log_OC
.e(TAG
, "Incorrect upload type provided");
194 return Service
.START_NOT_STICKY
;
196 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
198 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
199 OCFile
[] files
= null
;
200 if (uploadType
== UPLOAD_SINGLE_FILE
) {
202 if (intent
.hasExtra(KEY_FILE
)) {
203 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
206 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
207 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
208 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
211 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
213 if (intent
.hasExtra(KEY_FILE
)) {
214 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
222 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
223 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
224 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
228 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
230 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
231 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
232 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
234 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
235 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
236 return Service
.START_NOT_STICKY
;
238 } else if (!intent
.hasExtra(KEY_FILE
)) {
239 if (localPaths
== null
) {
240 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
241 return Service
.START_NOT_STICKY
;
243 if (remotePaths
== null
) {
244 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
245 return Service
.START_NOT_STICKY
;
247 if (localPaths
.length
!= remotePaths
.length
) {
248 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
249 return Service
.START_NOT_STICKY
;
252 files
= new OCFile
[localPaths
.length
];
253 for (int i
= 0; i
< localPaths
.length
; i
++) {
254 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!= null
) ? mimeTypes
[i
]
255 : (String
) null
), storageManager
);
256 if (files
[i
] == null
) {
257 // TODO @andomaex add failure Notiification
258 return Service
.START_NOT_STICKY
;
263 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
,
264 AccountAuthenticator
.KEY_OC_VERSION
));
265 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
266 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
267 String uploadKey
= null
;
268 UploadFileOperation newUpload
= null
;
270 for (int i
= 0; i
< files
.length
; i
++) {
271 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
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
= OwnCloudClientUtils
.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(R
.drawable
.icon
, 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
, R
.drawable
.icon
);
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(R
.drawable
.icon
,
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 MainApp
.getAuthTokenTypeSamlSessionCookie().equals(mUploadClient
.getAuthTokenType())));
826 if (needsToUpdateCredentials
) {
827 // let the user update credentials with one click
828 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
829 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
830 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
831 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
832 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
833 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
834 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
835 finalNotification
.contentIntent
= PendingIntent
.getActivity(this, (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
836 content
= String
.format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
837 finalNotification
.setLatestEventInfo(getApplicationContext(),
838 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
839 mUploadClient
= null
; // grant that future retries on the same account will get the fresh credentials
841 // TODO put something smart in the contentIntent below
842 // finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
845 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
846 || uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
847 // TODO we need a class to provide error messages for the users
848 // from a RemoteOperationResult and a RemoteOperation
849 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(),
850 getString(R
.string
.app_name
));
851 } else if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
852 content
= getString(R
.string
.failed_upload_quota_exceeded_text
);
855 .format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
858 // we add only for instant-uploads the InstantUploadActivity and the
860 Intent detailUploadIntent
= null
;
861 if (upload
.isInstant() && InstantUploadActivity
.IS_ENABLED
) {
862 detailUploadIntent
= new Intent(this, InstantUploadActivity
.class);
863 detailUploadIntent
.putExtra(FileUploader
.KEY_ACCOUNT
, upload
.getAccount());
865 detailUploadIntent
= new Intent(this, FailedUploadActivity
.class);
866 detailUploadIntent
.putExtra(FailedUploadActivity
.MESSAGE
, content
);
868 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
869 (int) System
.currentTimeMillis(), detailUploadIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
870 | PendingIntent
.FLAG_ONE_SHOT
);
872 if (upload
.isInstant()) {
875 db
= new DbHandler(this.getBaseContext());
876 String message
= uploadResult
.getLogMessage() + " errorCode: " + uploadResult
.getCode();
877 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
878 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
879 message
= getString(R
.string
.failed_upload_quota_exceeded_text
);
880 if (db
.updateFileState(upload
.getOriginalStoragePath(), DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
882 db
.putFileForLater(upload
.getOriginalStoragePath(), upload
.getAccount().name
, message
);
892 finalNotification
.setLatestEventInfo(getApplicationContext(),
893 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
895 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
901 * Sends a broadcast in order to the interested activities can update their
904 * @param upload Finished upload operation
905 * @param uploadResult Result of the upload operation
907 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
908 Intent end
= new Intent(getUploadFinishMessage());
909 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
914 if (upload
.wasRenamed()) {
915 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
917 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
918 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
919 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
920 sendStickyBroadcast(end
);