2 * ownCloud Android client application
4 * Copyright (C) 2012 Bartek Przybylski
5 * Copyright (C) 2012-2015 ownCloud Inc.
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2,
9 * as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 package com
.owncloud
.android
.files
.services
;
24 import java
.util
.AbstractList
;
25 import java
.util
.HashMap
;
26 import java
.util
.Iterator
;
28 import java
.util
.Vector
;
30 import android
.accounts
.Account
;
31 import android
.accounts
.AccountManager
;
32 import android
.accounts
.OnAccountsUpdateListener
;
33 import android
.app
.NotificationManager
;
34 import android
.app
.PendingIntent
;
35 import android
.app
.Service
;
36 import android
.content
.Intent
;
37 import android
.os
.Binder
;
38 import android
.os
.Handler
;
39 import android
.os
.HandlerThread
;
40 import android
.os
.IBinder
;
41 import android
.os
.Looper
;
42 import android
.os
.Message
;
43 import android
.os
.Process
;
44 import android
.support
.v4
.app
.NotificationCompat
;
45 import android
.util
.Pair
;
46 import android
.webkit
.MimeTypeMap
;
48 import com
.owncloud
.android
.R
;
49 import com
.owncloud
.android
.authentication
.AccountUtils
;
50 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
51 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
52 import com
.owncloud
.android
.datamodel
.OCFile
;
53 import com
.owncloud
.android
.db
.DbHandler
;
54 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
55 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
56 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
57 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
58 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
59 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
60 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
61 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
62 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
63 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
64 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
65 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
66 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
67 import com
.owncloud
.android
.notifications
.NotificationBuilderWithProgressBar
;
68 import com
.owncloud
.android
.notifications
.NotificationDelayer
;
69 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
70 import com
.owncloud
.android
.operations
.UploadFileOperation
;
71 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
72 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
73 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
74 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
75 import com
.owncloud
.android
.utils
.UriUtils
;
78 public class FileUploader
extends Service
79 implements OnDatatransferProgressListener
, OnAccountsUpdateListener
{
81 private static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
82 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
83 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
84 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
85 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
86 public static final String EXTRA_LINKED_TO_PATH
= "LINKED_TO";
87 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
89 public static final String KEY_FILE
= "FILE";
90 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
91 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
92 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
94 public static final String KEY_ACCOUNT
= "ACCOUNT";
96 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
97 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
98 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
99 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
101 public static final String KEY_CANCEL_ALL
= "CANCEL_ALL";
103 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
104 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
105 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
106 public static final int LOCAL_BEHAVIOUR_REMOVE
= 3;
108 public static final int UPLOAD_SINGLE_FILE
= 0;
109 public static final int UPLOAD_MULTIPLE_FILES
= 1;
111 private static final String TAG
= FileUploader
.class.getSimpleName();
113 private Looper mServiceLooper
;
114 private ServiceHandler mServiceHandler
;
115 private IBinder mBinder
;
116 private OwnCloudClient mUploadClient
= null
;
117 private Account mCurrentAccount
= null
;
118 private FileDataStorageManager mStorageManager
;
120 private IndexedForest
<UploadFileOperation
> mPendingUploads
= new IndexedForest
<UploadFileOperation
>();
121 private UploadFileOperation mCurrentUpload
= null
;
123 private NotificationManager mNotificationManager
;
124 private NotificationCompat
.Builder mNotificationBuilder
;
125 private int mLastPercent
;
127 private static final String MIME_TYPE_PDF
= "application/pdf";
128 private static final String FILE_EXTENSION_PDF
= ".pdf";
131 public static String
getUploadFinishMessage() {
132 return FileUploader
.class.getName() + UPLOAD_FINISH_MESSAGE
;
136 * Checks if an ownCloud server version should support chunked uploads.
138 * @param version OwnCloud version instance corresponding to an ownCloud
140 * @return 'True' if the ownCloud server with version supports chunked
143 * TODO - move to OCClient
145 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
146 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
150 * Service initialization
153 public void onCreate() {
155 Log_OC
.d(TAG
, "Creating service");
156 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
157 HandlerThread thread
= new HandlerThread("FileUploaderThread",
158 Process
.THREAD_PRIORITY_BACKGROUND
);
160 mServiceLooper
= thread
.getLooper();
161 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
162 mBinder
= new FileUploaderBinder();
164 // add AccountsUpdatedListener
165 AccountManager am
= AccountManager
.get(getApplicationContext());
166 am
.addOnAccountsUpdatedListener(this, null
, false
);
173 public void onDestroy() {
174 Log_OC
.v(TAG
, "Destroying service" );
176 mServiceHandler
= null
;
177 mServiceLooper
.quit();
178 mServiceLooper
= null
;
179 mNotificationManager
= null
;
181 // remove AccountsUpdatedListener
182 AccountManager am
= AccountManager
.get(getApplicationContext());
183 am
.removeOnAccountsUpdatedListener(this);
190 * Entry point to add one or several files to the queue of uploads.
192 * New uploads are added calling to startService(), resulting in a call to
193 * this method. This ensures the service will keep on working although the
194 * caller activity goes away.
197 public int onStartCommand(Intent intent
, int flags
, int startId
) {
198 Log_OC
.d(TAG
, "Starting command with id " + startId
);
200 if (intent
.hasExtra(KEY_CANCEL_ALL
) && intent
.hasExtra(KEY_ACCOUNT
)){
201 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
203 Log_OC
.d(TAG
, "Account= " + account
.name
);
205 if (mCurrentUpload
!= null
) {
206 Log_OC
.d(TAG
, "Current Upload Account= " + mCurrentUpload
.getAccount().name
);
207 if (mCurrentUpload
.getAccount().name
.equals(account
.name
)) {
208 mCurrentUpload
.cancel();
211 // Cancel pending uploads
212 cancelUploadsForAccount(account
);
215 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
216 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
217 Log_OC
.e(TAG
, "Not enough information provided in intent");
218 return Service
.START_NOT_STICKY
;
220 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
221 if (uploadType
== -1) {
222 Log_OC
.e(TAG
, "Incorrect upload type provided");
223 return Service
.START_NOT_STICKY
;
225 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
226 if (!AccountUtils
.exists(account
, getApplicationContext())) {
227 return Service
.START_NOT_STICKY
;
230 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
231 OCFile
[] files
= null
;
232 if (uploadType
== UPLOAD_SINGLE_FILE
) {
234 if (intent
.hasExtra(KEY_FILE
)) {
235 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
238 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
239 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
240 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
243 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
245 if (intent
.hasExtra(KEY_FILE
)) {
246 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
254 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
255 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
256 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
260 FileDataStorageManager storageManager
= new FileDataStorageManager(account
,
261 getContentResolver());
263 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
264 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
265 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
267 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
268 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
269 return Service
.START_NOT_STICKY
;
271 } else if (!intent
.hasExtra(KEY_FILE
)) {
272 if (localPaths
== null
) {
273 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
274 return Service
.START_NOT_STICKY
;
276 if (remotePaths
== null
) {
277 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
278 return Service
.START_NOT_STICKY
;
280 if (localPaths
.length
!= remotePaths
.length
) {
281 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
282 return Service
.START_NOT_STICKY
;
285 files
= new OCFile
[localPaths
.length
];
286 for (int i
= 0; i
< localPaths
.length
; i
++) {
287 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
],
288 ((mimeTypes
!= null
) ? mimeTypes
[i
] : null
));
289 if (files
[i
] == null
) {
290 // TODO @andomaex add failure Notification
291 return Service
.START_NOT_STICKY
;
296 OwnCloudVersion ocv
= AccountUtils
.getServerVersion(account
);
298 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
299 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
300 String uploadKey
= null
;
301 UploadFileOperation newUpload
= null
;
303 for (int i
= 0; i
< files
.length
; i
++) {
304 newUpload
= new UploadFileOperation(
309 forceOverwrite
, localAction
,
310 getApplicationContext()
313 newUpload
.setRemoteFolderToBeCreated();
315 newUpload
.addDatatransferProgressListener(this);
316 newUpload
.addDatatransferProgressListener((FileUploaderBinder
) mBinder
);
317 Pair
<String
, String
> putResult
= mPendingUploads
.putIfAbsent(
318 account
, files
[i
].getRemotePath(), newUpload
320 uploadKey
= putResult
.first
;
321 requestedUploads
.add(uploadKey
);
324 } catch (IllegalArgumentException e
) {
325 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
326 return START_NOT_STICKY
;
328 } catch (IllegalStateException e
) {
329 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
330 return START_NOT_STICKY
;
332 } catch (Exception e
) {
333 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
334 return START_NOT_STICKY
;
338 if (requestedUploads
.size() > 0) {
339 Message msg
= mServiceHandler
.obtainMessage();
341 msg
.obj
= requestedUploads
;
342 mServiceHandler
.sendMessage(msg
);
344 return Service
.START_NOT_STICKY
;
348 * Provides a binder object that clients can use to perform operations on
349 * the queue of uploads, excepting the addition of new files.
351 * Implemented to perform cancellation, pause and resume of existing
355 public IBinder
onBind(Intent arg0
) {
360 * Called when ALL the bound clients were onbound.
363 public boolean onUnbind(Intent intent
) {
364 ((FileUploaderBinder
)mBinder
).clearListeners();
365 return false
; // not accepting rebinding (default behaviour)
369 public void onAccountsUpdated(Account
[] accounts
) {
370 // Review current upload, and cancel it if its account doen't exist
371 if (mCurrentUpload
!= null
&&
372 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
373 mCurrentUpload
.cancel();
375 // The rest of uploads are cancelled when they try to start
379 * Binder to let client components to perform operations on the queue of
382 * It provides by itself the available operations.
384 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
387 * Map of listeners that will be reported about progress of uploads from a
388 * {@link FileUploaderBinder} instance
390 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
=
391 new HashMap
<String
, OnDatatransferProgressListener
>();
394 * Cancels a pending or current upload of a remote file.
396 * @param account ownCloud account where the remote file will be stored.
397 * @param file A file in the queue of pending uploads
399 public void cancel(Account account
, OCFile file
) {
400 Pair
<UploadFileOperation
, String
> removeResult
= mPendingUploads
.remove(account
, file
.getRemotePath());
401 UploadFileOperation upload
= removeResult
.first
;
402 if (upload
!= null
) {
405 if (mCurrentUpload
!= null
&& mCurrentAccount
!= null
&&
406 mCurrentUpload
.getRemotePath().startsWith(file
.getRemotePath()) &&
407 account
.name
.equals(mCurrentAccount
.name
)) {
408 mCurrentUpload
.cancel();
414 * Cancels all the uploads for an account
416 * @param account ownCloud account.
418 public void cancel(Account account
) {
419 Log_OC
.d(TAG
, "Account= " + account
.name
);
421 if (mCurrentUpload
!= null
) {
422 Log_OC
.d(TAG
, "Current Upload Account= " + mCurrentUpload
.getAccount().name
);
423 if (mCurrentUpload
.getAccount().name
.equals(account
.name
)) {
424 mCurrentUpload
.cancel();
427 // Cancel pending uploads
428 cancelUploadsForAccount(account
);
431 public void clearListeners() {
432 mBoundListeners
.clear();
437 * Returns True when the file described by 'file' is being uploaded to
438 * the ownCloud account 'account' or waiting for it
440 * If 'file' is a directory, returns 'true' if some of its descendant files
441 * is uploading or waiting to upload.
443 * @param account ownCloud account where the remote file will be stored.
444 * @param file A file that could be in the queue of pending uploads
446 public boolean isUploading(Account account
, OCFile file
) {
447 if (account
== null
|| file
== null
) return false
;
448 return (mPendingUploads
.contains(account
, file
.getRemotePath()));
453 * Adds a listener interested in the progress of the upload for a concrete file.
455 * @param listener Object to notify about progress of transfer.
456 * @param account ownCloud account holding the file of interest.
457 * @param file {@link OCFile} of interest for listener.
459 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
,
460 Account account
, OCFile file
) {
461 if (account
== null
|| file
== null
|| listener
== null
) return;
462 String targetKey
= buildRemoteName(account
, file
);
463 mBoundListeners
.put(targetKey
, listener
);
469 * Removes a listener interested in the progress of the upload for a concrete file.
471 * @param listener Object to notify about progress of transfer.
472 * @param account ownCloud account holding the file of interest.
473 * @param file {@link OCFile} of interest for listener.
475 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
,
476 Account account
, OCFile file
) {
477 if (account
== null
|| file
== null
|| listener
== null
) return;
478 String targetKey
= buildRemoteName(account
, file
);
479 if (mBoundListeners
.get(targetKey
) == listener
) {
480 mBoundListeners
.remove(targetKey
);
486 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
487 long totalToTransfer
, String fileName
) {
488 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
489 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
490 if (boundListener
!= null
) {
491 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
,
492 totalToTransfer
, fileName
);
497 * Builds a key for the map of listeners.
499 * TODO remove and replace key with file.getFileId() after changing current policy (upload file, then
500 * add to local database) to better policy (add to local database, then upload)
502 * @param account ownCloud account where the file to upload belongs.
503 * @param file File to upload
506 private String
buildRemoteName(Account account
, OCFile file
) {
507 return account
.name
+ file
.getRemotePath();
513 * Upload worker. Performs the pending uploads in the order they were
516 * Created with the Looper of a new thread, started in
517 * {@link FileUploader#onCreate()}.
519 private static class ServiceHandler
extends Handler
{
520 // don't make it a final class, and don't remove the static ; lint will
521 // warn about a possible memory leak
522 FileUploader mService
;
524 public ServiceHandler(Looper looper
, FileUploader service
) {
527 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
532 public void handleMessage(Message msg
) {
533 @SuppressWarnings("unchecked")
534 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
535 if (msg
.obj
!= null
) {
536 Iterator
<String
> it
= requestedUploads
.iterator();
537 while (it
.hasNext()) {
538 mService
.uploadFile(it
.next());
541 Log_OC
.d(TAG
, "Stopping command after id " + msg
.arg1
);
542 mService
.stopSelf(msg
.arg1
);
547 * Core upload method: sends the file(s) to upload
549 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
551 public void uploadFile(String uploadKey
) {
553 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
555 if (mCurrentUpload
!= null
) {
556 // Detect if the account exists
557 if (AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
558 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().name
+ " exists");
560 notifyUploadStart(mCurrentUpload
);
562 RemoteOperationResult uploadResult
= null
, grantResult
;
565 /// prepare client object to send the request to the ownCloud server
566 if (mCurrentAccount
== null
|| !mCurrentAccount
.equals(mCurrentUpload
.getAccount())) {
567 mCurrentAccount
= mCurrentUpload
.getAccount();
568 mStorageManager
= new FileDataStorageManager(
572 } // else, reuse storage manager from previous operation
574 // always get client from client manager, to get fresh credentials in case of update
575 OwnCloudAccount ocAccount
= new OwnCloudAccount(mCurrentAccount
, this);
576 mUploadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
577 getClientFor(ocAccount
, this);
580 /// check the existence of the parent folder for the file to upload
581 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
582 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
583 remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
584 grantResult
= grantFolderExistence(remoteParentPath
);
586 /// perform the upload
587 if (grantResult
.isSuccess()) {
588 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
589 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
590 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
591 if (uploadResult
.isSuccess()) {
594 } else if (uploadResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
595 mStorageManager
.saveConflict(mCurrentUpload
.getFile(),
596 mCurrentUpload
.getFile().getEtagInConflict());
599 uploadResult
= grantResult
;
602 } catch (Exception e
) {
603 Log_OC
.e(TAG
, "Error uploading", e
);
604 uploadResult
= new RemoteOperationResult(e
);
607 Pair
<UploadFileOperation
, String
> removeResult
;
608 if (mCurrentUpload
.wasRenamed()) {
609 removeResult
= mPendingUploads
.removePayload(
611 mCurrentUpload
.getOldFile().getRemotePath()
614 removeResult
= mPendingUploads
.removePayload(
616 mCurrentUpload
.getRemotePath()
621 notifyUploadResult(mCurrentUpload
, uploadResult
);
623 sendBroadcastUploadFinished(mCurrentUpload
, uploadResult
, removeResult
.second
);
627 // Cancel the transfer
628 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().toString() +
630 cancelUploadsForAccount(mCurrentUpload
.getAccount());
638 * Checks the existence of the folder where the current file will be uploaded both
639 * in the remote server and in the local database.
641 * If the upload is set to enforce the creation of the folder, the method tries to
642 * create it both remote and locally.
644 * @param pathToGrant Full remote path whose existence will be granted.
645 * @return An {@link OCFile} instance corresponding to the folder where the file
648 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
649 RemoteOperation operation
= new ExistenceCheckRemoteOperation(pathToGrant
, this, false
);
650 RemoteOperationResult result
= operation
.execute(mUploadClient
);
651 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&&
652 mCurrentUpload
.isRemoteFolderToBeCreated()) {
653 SyncOperation syncOp
= new CreateFolderOperation( pathToGrant
, true
);
654 result
= syncOp
.execute(mUploadClient
, mStorageManager
);
656 if (result
.isSuccess()) {
657 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
658 if (parentDir
== null
) {
659 parentDir
= createLocalFolder(pathToGrant
);
661 if (parentDir
!= null
) {
662 result
= new RemoteOperationResult(ResultCode
.OK
);
664 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
671 private OCFile
createLocalFolder(String remotePath
) {
672 String parentPath
= new File(remotePath
).getParent();
673 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
674 parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
675 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
676 if (parent
== null
) {
677 parent
= createLocalFolder(parentPath
);
679 if (parent
!= null
) {
680 OCFile createdFolder
= new OCFile(remotePath
);
681 createdFolder
.setMimetype("DIR");
682 createdFolder
.setParentId(parent
.getFileId());
683 mStorageManager
.saveFile(createdFolder
);
684 return createdFolder
;
691 * Saves a OC File after a successful upload.
693 * A PROPFIND is necessary to keep the props in the local database
694 * synchronized with the server, specially the modification time and Etag
697 * TODO move into UploadFileOperation
699 private void saveUploadedFile() {
700 OCFile file
= mCurrentUpload
.getFile();
701 if (file
.fileExists()) {
702 file
= mStorageManager
.getFileById(file
.getFileId());
704 long syncDate
= System
.currentTimeMillis();
705 file
.setLastSyncDateForData(syncDate
);
707 // new PROPFIND to keep data consistent with server
708 // in theory, should return the same we already have
709 ReadRemoteFileOperation operation
=
710 new ReadRemoteFileOperation(mCurrentUpload
.getRemotePath());
711 RemoteOperationResult result
= operation
.execute(mUploadClient
);
712 if (result
.isSuccess()) {
713 updateOCFile(file
, (RemoteFile
) result
.getData().get(0));
714 file
.setLastSyncDateForProperties(syncDate
);
716 Log_OC
.e(TAG
, "Error reading properties of file after successful upload; this is gonna hurt...");
719 // / maybe this would be better as part of UploadFileOperation... or
720 // maybe all this method
721 if (mCurrentUpload
.wasRenamed()) {
722 OCFile oldFile
= mCurrentUpload
.getOldFile();
723 if (oldFile
.fileExists()) {
724 oldFile
.setStoragePath(null
);
725 mStorageManager
.saveFile(oldFile
);
726 mStorageManager
.saveConflict(oldFile
, null
);
728 } // else: it was just an automatic renaming due to a name
729 // coincidence; nothing else is needed, the storagePath is right
730 // in the instance returned by mCurrentUpload.getFile()
732 file
.setNeedsUpdateThumbnail(true
);
733 mStorageManager
.saveFile(file
);
734 mStorageManager
.saveConflict(file
, null
);
736 mStorageManager
.triggerMediaScan(file
.getStoragePath());
740 private void updateOCFile(OCFile file
, RemoteFile remoteFile
) {
741 file
.setCreationTimestamp(remoteFile
.getCreationTimestamp());
742 file
.setFileLength(remoteFile
.getLength());
743 file
.setMimetype(remoteFile
.getMimeType());
744 file
.setModificationTimestamp(remoteFile
.getModifiedTimestamp());
745 file
.setModificationTimestampAtLastSyncForData(remoteFile
.getModifiedTimestamp());
746 file
.setEtag(remoteFile
.getEtag());
747 file
.setRemoteId(remoteFile
.getRemoteId());
750 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
) {
753 if (mimeType
== null
|| mimeType
.length() <= 0) {
755 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
756 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
757 } catch (IndexOutOfBoundsException e
) {
758 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " +
762 if (mimeType
== null
) {
763 mimeType
= "application/octet-stream";
766 if (isPdfFileFromContentProviderWithoutExtension(localPath
, mimeType
)){
767 remotePath
+= FILE_EXTENSION_PDF
;
770 OCFile newFile
= new OCFile(remotePath
);
771 newFile
.setStoragePath(localPath
);
772 newFile
.setLastSyncDateForProperties(0);
773 newFile
.setLastSyncDateForData(0);
776 if (localPath
!= null
&& localPath
.length() > 0) {
777 File localFile
= new File(localPath
);
778 newFile
.setFileLength(localFile
.length());
779 newFile
.setLastSyncDateForData(localFile
.lastModified());
780 } // don't worry about not assigning size, the problems with localPath
781 // are checked when the UploadFileOperation instance is created
784 newFile
.setMimetype(mimeType
);
790 * Creates a status notification to show the upload progress
792 * @param upload Upload operation starting.
794 private void notifyUploadStart(UploadFileOperation upload
) {
795 // / create status notification with a progress bar
797 mNotificationBuilder
=
798 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
801 .setSmallIcon(R
.drawable
.notification_icon
)
802 .setTicker(getString(R
.string
.uploader_upload_in_progress_ticker
))
803 .setContentTitle(getString(R
.string
.uploader_upload_in_progress_ticker
))
804 .setProgress(100, 0, false
)
806 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
808 /// includes a pending intent in the notification showing the details view of the file
809 Intent showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
810 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
811 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
812 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
813 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
814 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
817 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
821 * Callback method to update the progress bar in the status notification
824 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
825 long totalToTransfer
, String filePath
) {
826 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
827 if (percent
!= mLastPercent
) {
828 mNotificationBuilder
.setProgress(100, percent
, false
);
829 String fileName
= filePath
.substring(
830 filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
831 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
832 mNotificationBuilder
.setContentText(text
);
833 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
835 mLastPercent
= percent
;
839 * Updates the status notification with the result of an upload operation.
841 * @param uploadResult Result of the upload operation.
842 * @param upload Finished upload operation
844 private void notifyUploadResult(UploadFileOperation upload
,
845 RemoteOperationResult uploadResult
) {
846 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
847 // / cancelled operation or success -> silent removal of progress notification
848 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
850 // Show the result: success or fail notification
851 if (!uploadResult
.isCancelled()) {
852 int tickerId
= (uploadResult
.isSuccess()) ? R
.string
.uploader_upload_succeeded_ticker
:
853 R
.string
.uploader_upload_failed_ticker
;
857 // check credentials error
858 boolean needsToUpdateCredentials
= (
859 uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
860 uploadResult
.isIdPRedirection()
862 tickerId
= (needsToUpdateCredentials
) ?
863 R
.string
.uploader_upload_failed_credentials_error
: tickerId
;
866 .setTicker(getString(tickerId
))
867 .setContentTitle(getString(tickerId
))
870 .setProgress(0, 0, false
);
872 content
= ErrorMessageAdapter
.getErrorCauseMessage(
873 uploadResult
, upload
, getResources()
876 if (needsToUpdateCredentials
) {
877 // let the user update credentials with one click
878 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
879 updateAccountCredentials
.putExtra(
880 AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount()
882 updateAccountCredentials
.putExtra(
883 AuthenticatorActivity
.EXTRA_ACTION
,
884 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
886 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
887 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
888 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
889 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
891 (int) System
.currentTimeMillis(),
892 updateAccountCredentials
,
893 PendingIntent
.FLAG_ONE_SHOT
896 mUploadClient
= null
;
897 // grant that future retries on the same account will get the fresh credentials
899 mNotificationBuilder
.setContentText(content
);
901 if (upload
.isInstant()) {
904 db
= new DbHandler(this.getBaseContext());
905 String message
= uploadResult
.getLogMessage() + " errorCode: " +
906 uploadResult
.getCode();
907 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
908 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
909 //message = getString(R.string.failed_upload_quota_exceeded_text);
910 if (db
.updateFileState(
911 upload
.getOriginalStoragePath(),
912 DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
915 upload
.getOriginalStoragePath(),
916 upload
.getAccount().name
,
929 mNotificationBuilder
.setContentText(content
);
930 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
932 if (uploadResult
.isSuccess()) {
934 DbHandler db
= new DbHandler(this.getBaseContext());
935 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
938 // remove success notification, with a delay of 2 seconds
939 NotificationDelayer
.cancelWithDelay(
940 mNotificationManager
,
941 R
.string
.uploader_upload_succeeded_ticker
,
949 * Sends a broadcast in order to the interested activities can update their
952 * @param upload Finished upload operation
953 * @param uploadResult Result of the upload operation
954 * @param unlinkedFromRemotePath Path in the uploads tree where the upload was unlinked from
956 private void sendBroadcastUploadFinished(
957 UploadFileOperation upload
,
958 RemoteOperationResult uploadResult
,
959 String unlinkedFromRemotePath
) {
961 Intent end
= new Intent(getUploadFinishMessage());
962 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
967 if (upload
.wasRenamed()) {
968 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
970 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
971 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
972 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
973 if (unlinkedFromRemotePath
!= null
) {
974 end
.putExtra(EXTRA_LINKED_TO_PATH
, unlinkedFromRemotePath
);
977 sendStickyBroadcast(end
);
981 * Checks if content provider, using the content:// scheme, returns a file with mime-type
982 * 'application/pdf' but file has not extension
983 * @param localPath Full path to a file in the local file system.
984 * @param mimeType MIME type of the file.
985 * @return true if is needed to add the pdf file extension to the file
987 * TODO - move to OCFile or Utils class
989 private boolean isPdfFileFromContentProviderWithoutExtension(String localPath
,
991 return localPath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
) &&
992 mimeType
.equals(MIME_TYPE_PDF
) &&
993 !localPath
.endsWith(FILE_EXTENSION_PDF
);
997 * Remove uploads of an account
999 * @param account Downloads account to remove
1001 private void cancelUploadsForAccount(Account account
){
1002 // Cancel pending uploads
1003 mPendingUploads
.remove(account
);