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
.io
.IOException
;
25 import java
.util
.AbstractList
;
26 import java
.util
.HashMap
;
27 import java
.util
.Iterator
;
29 import java
.util
.Vector
;
30 import java
.util
.concurrent
.ConcurrentHashMap
;
31 import java
.util
.concurrent
.ConcurrentMap
;
33 import android
.accounts
.Account
;
34 import android
.accounts
.AccountManager
;
35 import android
.accounts
.AccountsException
;
36 import android
.accounts
.OnAccountsUpdateListener
;
37 import android
.app
.NotificationManager
;
38 import android
.app
.PendingIntent
;
39 import android
.app
.Service
;
40 import android
.content
.Intent
;
41 import android
.os
.Binder
;
42 import android
.os
.Handler
;
43 import android
.os
.HandlerThread
;
44 import android
.os
.IBinder
;
45 import android
.os
.Looper
;
46 import android
.os
.Message
;
47 import android
.os
.Process
;
48 import android
.support
.v4
.app
.NotificationCompat
;
49 import android
.webkit
.MimeTypeMap
;
51 import com
.owncloud
.android
.R
;
52 import com
.owncloud
.android
.authentication
.AccountUtils
;
53 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
54 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
55 import com
.owncloud
.android
.datamodel
.OCFile
;
56 import com
.owncloud
.android
.db
.DbHandler
;
57 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
58 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
59 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
60 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
61 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
62 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
63 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
64 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
65 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
66 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
67 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
68 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
69 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
70 import com
.owncloud
.android
.notifications
.NotificationBuilderWithProgressBar
;
71 import com
.owncloud
.android
.notifications
.NotificationDelayer
;
72 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
73 import com
.owncloud
.android
.operations
.UploadFileOperation
;
74 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
75 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
76 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
77 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
78 import com
.owncloud
.android
.utils
.UriUtils
;
81 public class FileUploader
extends Service
82 implements OnDatatransferProgressListener
, OnAccountsUpdateListener
{
84 private static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
85 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
86 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
87 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
88 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
89 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
91 public static final String KEY_FILE
= "FILE";
92 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
93 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
94 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
96 public static final String KEY_ACCOUNT
= "ACCOUNT";
98 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
99 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
100 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
101 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
103 public static final String KEY_CANCEL_ALL
= "CANCEL_ALL";
105 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
106 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
107 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
109 public static final int UPLOAD_SINGLE_FILE
= 0;
110 public static final int UPLOAD_MULTIPLE_FILES
= 1;
112 private static final String TAG
= FileUploader
.class.getSimpleName();
114 private Looper mServiceLooper
;
115 private ServiceHandler mServiceHandler
;
116 private IBinder mBinder
;
117 private OwnCloudClient mUploadClient
= null
;
118 private Account mLastAccount
= null
;
119 private FileDataStorageManager mStorageManager
;
121 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
=
122 new ConcurrentHashMap
<String
, UploadFileOperation
>();
123 private UploadFileOperation mCurrentUpload
= null
;
125 private NotificationManager mNotificationManager
;
126 private NotificationCompat
.Builder mNotificationBuilder
;
127 private int mLastPercent
;
129 private static final String MIME_TYPE_PDF
= "application/pdf";
130 private static final String FILE_EXTENSION_PDF
= ".pdf";
133 public static String
getUploadFinishMessage() {
134 return FileUploader
.class.getName() + UPLOAD_FINISH_MESSAGE
;
138 * Builds a key for mPendingUploads from the account and file to upload
140 * @param account Account where the file to upload is stored
141 * @param file File to upload
143 private String
buildRemoteName(Account account
, OCFile file
) {
144 return account
.name
+ file
.getRemotePath();
147 private String
buildRemoteName(Account account
, String remotePath
) {
148 return account
.name
+ remotePath
;
152 * Checks if an ownCloud server version should support chunked uploads.
154 * @param version OwnCloud version instance corresponding to an ownCloud
156 * @return 'True' if the ownCloud server with version supports chunked
159 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
160 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
164 * Service initialization
167 public void onCreate() {
169 Log_OC
.d(TAG
, "Creating service");
170 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
171 HandlerThread thread
= new HandlerThread("FileUploaderThread",
172 Process
.THREAD_PRIORITY_BACKGROUND
);
174 mServiceLooper
= thread
.getLooper();
175 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
176 mBinder
= new FileUploaderBinder();
178 // add AccountsUpdatedListener
179 AccountManager am
= AccountManager
.get(getApplicationContext());
180 am
.addOnAccountsUpdatedListener(this, null
, false
);
187 public void onDestroy() {
188 Log_OC
.v(TAG
, "Destroying service" );
190 mServiceHandler
= null
;
191 mServiceLooper
.quit();
192 mServiceLooper
= null
;
193 mNotificationManager
= null
;
195 // remove AccountsUpdatedListener
196 AccountManager am
= AccountManager
.get(getApplicationContext());
197 am
.removeOnAccountsUpdatedListener(this);
204 * Entry point to add one or several files to the queue of uploads.
206 * New uploads are added calling to startService(), resulting in a call to
207 * this method. This ensures the service will keep on working although the
208 * caller activity goes away.
211 public int onStartCommand(Intent intent
, int flags
, int startId
) {
212 Log_OC
.d(TAG
, "Starting command with id " + startId
);
214 if (intent
.hasExtra(KEY_CANCEL_ALL
) && intent
.hasExtra(KEY_ACCOUNT
)){
215 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
216 cancelUploadForAccount(account
.name
);
219 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
220 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
221 Log_OC
.e(TAG
, "Not enough information provided in intent");
222 return Service
.START_NOT_STICKY
;
224 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
225 if (uploadType
== -1) {
226 Log_OC
.e(TAG
, "Incorrect upload type provided");
227 return Service
.START_NOT_STICKY
;
229 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
230 if (!AccountUtils
.exists(account
, getApplicationContext())) {
231 return Service
.START_NOT_STICKY
;
234 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
235 OCFile
[] files
= null
;
236 if (uploadType
== UPLOAD_SINGLE_FILE
) {
238 if (intent
.hasExtra(KEY_FILE
)) {
239 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
242 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
243 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
244 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
247 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
249 if (intent
.hasExtra(KEY_FILE
)) {
250 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
258 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
259 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
260 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
264 FileDataStorageManager storageManager
= new FileDataStorageManager(account
,
265 getContentResolver());
267 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
268 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
269 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
271 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
272 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
273 return Service
.START_NOT_STICKY
;
275 } else if (!intent
.hasExtra(KEY_FILE
)) {
276 if (localPaths
== null
) {
277 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
278 return Service
.START_NOT_STICKY
;
280 if (remotePaths
== null
) {
281 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
282 return Service
.START_NOT_STICKY
;
284 if (localPaths
.length
!= remotePaths
.length
) {
285 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
286 return Service
.START_NOT_STICKY
;
289 files
= new OCFile
[localPaths
.length
];
290 for (int i
= 0; i
< localPaths
.length
; i
++) {
291 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
],
292 ((mimeTypes
!= null
) ? mimeTypes
[i
] : null
), storageManager
);
293 if (files
[i
] == null
) {
294 // TODO @andomaex add failure Notification
295 return Service
.START_NOT_STICKY
;
300 OwnCloudVersion ocv
= AccountUtils
.getServerVersion(account
);
302 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
303 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
304 String uploadKey
= null
;
305 UploadFileOperation newUpload
= null
;
307 for (int i
= 0; i
< files
.length
; i
++) {
308 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
309 newUpload
= new UploadFileOperation(account
, files
[i
], chunked
, isInstant
,
310 forceOverwrite
, localAction
,
311 getApplicationContext());
313 newUpload
.setRemoteFolderToBeCreated();
315 // Grants that the file only upload once time
316 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
318 newUpload
.addDatatransferProgressListener(this);
319 newUpload
.addDatatransferProgressListener((FileUploaderBinder
)mBinder
);
320 requestedUploads
.add(uploadKey
);
323 } catch (IllegalArgumentException e
) {
324 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
325 return START_NOT_STICKY
;
327 } catch (IllegalStateException e
) {
328 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
329 return START_NOT_STICKY
;
331 } catch (Exception e
) {
332 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
333 return START_NOT_STICKY
;
337 if (requestedUploads
.size() > 0) {
338 Message msg
= mServiceHandler
.obtainMessage();
340 msg
.obj
= requestedUploads
;
341 mServiceHandler
.sendMessage(msg
);
343 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
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 UploadFileOperation upload
;
401 synchronized (mPendingUploads
) {
402 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
404 if (upload
!= null
) {
410 * Cancels a pending or current upload for an account
412 * @param account Owncloud accountName where the remote file will be stored.
414 public void cancel(Account account
) {
415 Log_OC
.d(TAG
, "Account= " + account
.name
);
417 if (mCurrentUpload
!= null
) {
418 Log_OC
.d(TAG
, "Current Upload Account= " + mCurrentUpload
.getAccount().name
);
419 if (mCurrentUpload
.getAccount().name
.equals(account
.name
)) {
420 mCurrentUpload
.cancel();
423 // Cancel pending uploads
424 cancelUploadForAccount(account
.name
);
427 public void clearListeners() {
428 mBoundListeners
.clear();
432 * Returns True when the file described by 'file' is being uploaded to
433 * the ownCloud account 'account' or waiting for it
435 * If 'file' is a directory, returns 'true' if some of its descendant files
436 * is uploading or waiting to upload.
438 * @param account ownCloud account where the remote file will be stored.
439 * @param file A file that could be in the queue of pending uploads
441 public boolean isUploading(Account account
, OCFile file
) {
442 if (account
== null
|| file
== null
)
444 String targetKey
= buildRemoteName(account
, file
);
445 synchronized (mPendingUploads
) {
446 if (file
.isFolder()) {
447 // this can be slow if there are many uploads :(
448 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
449 boolean found
= false
;
450 while (it
.hasNext() && !found
) {
451 found
= it
.next().startsWith(targetKey
);
455 return (mPendingUploads
.containsKey(targetKey
));
462 * Adds a listener interested in the progress of the upload for a concrete file.
464 * @param listener Object to notify about progress of transfer.
465 * @param account ownCloud account holding the file of interest.
466 * @param file {@link OCFile} of interest for listener.
468 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
,
469 Account account
, OCFile file
) {
470 if (account
== null
|| file
== null
|| listener
== null
) return;
471 String targetKey
= buildRemoteName(account
, file
);
472 mBoundListeners
.put(targetKey
, listener
);
478 * Removes a listener interested in the progress of the upload for a concrete file.
480 * @param listener Object to notify about progress of transfer.
481 * @param account ownCloud account holding the file of interest.
482 * @param file {@link OCFile} of interest for listener.
484 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
,
485 Account account
, OCFile file
) {
486 if (account
== null
|| file
== null
|| listener
== null
) return;
487 String targetKey
= buildRemoteName(account
, file
);
488 if (mBoundListeners
.get(targetKey
) == listener
) {
489 mBoundListeners
.remove(targetKey
);
495 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
496 long totalToTransfer
, String fileName
) {
497 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
498 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
499 if (boundListener
!= null
) {
500 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
,
501 totalToTransfer
, fileName
);
506 * Review uploads and cancel it if its account doesn't exist
508 public void checkAccountOfCurrentUpload() {
509 if (mCurrentUpload
!= null
&&
510 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
511 mCurrentUpload
.cancel();
513 // The rest of uploads are cancelled when they try to start
518 * Upload worker. Performs the pending uploads in the order they were
521 * Created with the Looper of a new thread, started in
522 * {@link FileUploader#onCreate()}.
524 private static class ServiceHandler
extends Handler
{
525 // don't make it a final class, and don't remove the static ; lint will
526 // warn about a possible memory leak
527 FileUploader mService
;
529 public ServiceHandler(Looper looper
, FileUploader service
) {
532 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
537 public void handleMessage(Message msg
) {
538 @SuppressWarnings("unchecked")
539 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
540 if (msg
.obj
!= null
) {
541 Iterator
<String
> it
= requestedUploads
.iterator();
542 while (it
.hasNext()) {
543 mService
.uploadFile(it
.next());
546 Log_OC
.d(TAG
, "Stopping command after id " + msg
.arg1
);
547 mService
.stopSelf(msg
.arg1
);
552 * Core upload method: sends the file(s) to upload
554 * @param uploadKey Key to access the upload to perform, contained in
557 public void uploadFile(String uploadKey
) {
559 synchronized (mPendingUploads
) {
560 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
563 if (mCurrentUpload
!= null
) {
565 // Detect if the account exists
566 if (AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
567 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().name
+ " exists");
569 notifyUploadStart(mCurrentUpload
);
571 RemoteOperationResult uploadResult
= null
, grantResult
;
574 /// prepare client object to send requests to the ownCloud server
575 if (mUploadClient
== null
||
576 !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
577 mLastAccount
= mCurrentUpload
.getAccount();
579 new FileDataStorageManager(mLastAccount
, getContentResolver());
580 OwnCloudAccount ocAccount
= new OwnCloudAccount(mLastAccount
, this);
581 mUploadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
582 getClientFor(ocAccount
, this);
585 /// check the existence of the parent folder for the file to upload
586 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
587 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
588 remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
589 grantResult
= grantFolderExistence(remoteParentPath
);
591 /// perform the upload
592 if (grantResult
.isSuccess()) {
593 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
594 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
595 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
596 if (uploadResult
.isSuccess()) {
600 uploadResult
= grantResult
;
603 } catch (AccountsException e
) {
604 Log_OC
.e(TAG
, "Error while trying to get autorization for " +
605 mLastAccount
.name
, e
);
606 uploadResult
= new RemoteOperationResult(e
);
608 } catch (IOException e
) {
609 Log_OC
.e(TAG
, "Error while trying to get autorization for " +
610 mLastAccount
.name
, e
);
611 uploadResult
= new RemoteOperationResult(e
);
614 synchronized (mPendingUploads
) {
615 mPendingUploads
.remove(uploadKey
);
616 Log_OC
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
618 if (uploadResult
!= null
&& uploadResult
.isException()) {
619 // enforce the creation of a new client object for next uploads;
620 // this grant that a new socket will be created in the future if
621 // the current exception is due to an abrupt lose of network connection
622 mUploadClient
= null
;
627 notifyUploadResult(uploadResult
, mCurrentUpload
);
628 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
631 // Cancel the transfer
632 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().toString() +
634 cancelUploadForAccount(mCurrentUpload
.getAccount().name
);
642 * Checks the existence of the folder where the current file will be uploaded both
643 * in the remote server and in the local database.
645 * If the upload is set to enforce the creation of the folder, the method tries to
646 * create it both remote and locally.
648 * @param pathToGrant Full remote path whose existence will be granted.
649 * @return An {@link OCFile} instance corresponding to the folder where the file
652 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
653 RemoteOperation operation
= new ExistenceCheckRemoteOperation(pathToGrant
, this, false
);
654 RemoteOperationResult result
= operation
.execute(mUploadClient
);
655 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&&
656 mCurrentUpload
.isRemoteFolderToBeCreated()) {
657 SyncOperation syncOp
= new CreateFolderOperation( pathToGrant
, true
);
658 result
= syncOp
.execute(mUploadClient
, mStorageManager
);
660 if (result
.isSuccess()) {
661 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
662 if (parentDir
== null
) {
663 parentDir
= createLocalFolder(pathToGrant
);
665 if (parentDir
!= null
) {
666 result
= new RemoteOperationResult(ResultCode
.OK
);
668 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
675 private OCFile
createLocalFolder(String remotePath
) {
676 String parentPath
= new File(remotePath
).getParent();
677 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
678 parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
679 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
680 if (parent
== null
) {
681 parent
= createLocalFolder(parentPath
);
683 if (parent
!= null
) {
684 OCFile createdFolder
= new OCFile(remotePath
);
685 createdFolder
.setMimetype("DIR");
686 createdFolder
.setParentId(parent
.getFileId());
687 mStorageManager
.saveFile(createdFolder
);
688 return createdFolder
;
695 * Saves a OC File after a successful upload.
697 * A PROPFIND is necessary to keep the props in the local database
698 * synchronized with the server, specially the modification time and Etag
701 * TODO refactor this ugly thing
703 private void saveUploadedFile() {
704 OCFile file
= mCurrentUpload
.getFile();
705 if (file
.fileExists()) {
706 file
= mStorageManager
.getFileById(file
.getFileId());
708 long syncDate
= System
.currentTimeMillis();
709 file
.setLastSyncDateForData(syncDate
);
711 // new PROPFIND to keep data consistent with server
712 // in theory, should return the same we already have
713 ReadRemoteFileOperation operation
=
714 new ReadRemoteFileOperation(mCurrentUpload
.getRemotePath());
715 RemoteOperationResult result
= operation
.execute(mUploadClient
);
716 if (result
.isSuccess()) {
717 updateOCFile(file
, (RemoteFile
) result
.getData().get(0));
718 file
.setLastSyncDateForProperties(syncDate
);
721 // / maybe this would be better as part of UploadFileOperation... or
722 // maybe all this method
723 if (mCurrentUpload
.wasRenamed()) {
724 OCFile oldFile
= mCurrentUpload
.getOldFile();
725 if (oldFile
.fileExists()) {
726 oldFile
.setStoragePath(null
);
727 mStorageManager
.saveFile(oldFile
);
729 } // else: it was just an automatic renaming due to a name
730 // coincidence; nothing else is needed, the storagePath is right
731 // in the instance returned by mCurrentUpload.getFile()
733 file
.setNeedsUpdateThumbnail(true
);
734 mStorageManager
.saveFile(file
);
735 mStorageManager
.triggerMediaScan(file
.getStoragePath());
738 private void updateOCFile(OCFile file
, RemoteFile remoteFile
) {
739 file
.setCreationTimestamp(remoteFile
.getCreationTimestamp());
740 file
.setFileLength(remoteFile
.getLength());
741 file
.setMimetype(remoteFile
.getMimeType());
742 file
.setModificationTimestamp(remoteFile
.getModifiedTimestamp());
743 file
.setModificationTimestampAtLastSyncForData(remoteFile
.getModifiedTimestamp());
744 // file.setEtag(remoteFile.getEtag()); // TODO Etag, where available
745 file
.setRemoteId(remoteFile
.getRemoteId());
748 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
749 FileDataStorageManager storageManager
) {
752 if (mimeType
== null
|| mimeType
.length() <= 0) {
754 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
755 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
756 } catch (IndexOutOfBoundsException e
) {
757 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " +
761 if (mimeType
== null
) {
762 mimeType
= "application/octet-stream";
765 if (isPdfFileFromContentProviderWithoutExtension(localPath
, mimeType
)){
766 remotePath
+= FILE_EXTENSION_PDF
;
769 OCFile newFile
= new OCFile(remotePath
);
770 newFile
.setStoragePath(localPath
);
771 newFile
.setLastSyncDateForProperties(0);
772 newFile
.setLastSyncDateForData(0);
775 if (localPath
!= null
&& localPath
.length() > 0) {
776 File localFile
= new File(localPath
);
777 newFile
.setFileLength(localFile
.length());
778 newFile
.setLastSyncDateForData(localFile
.lastModified());
779 } // don't worry about not assigning size, the problems with localPath
780 // are checked when the UploadFileOperation instance is created
783 newFile
.setMimetype(mimeType
);
789 * Creates a status notification to show the upload progress
791 * @param upload Upload operation starting.
793 private void notifyUploadStart(UploadFileOperation upload
) {
794 // / create status notification with a progress bar
796 mNotificationBuilder
=
797 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
800 .setSmallIcon(R
.drawable
.notification_icon
)
801 .setTicker(getString(R
.string
.uploader_upload_in_progress_ticker
))
802 .setContentTitle(getString(R
.string
.uploader_upload_in_progress_ticker
))
803 .setProgress(100, 0, false
)
805 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
807 /// includes a pending intent in the notification showing the details view of the file
808 Intent showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
809 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
810 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
811 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
812 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
813 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
816 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
820 * Callback method to update the progress bar in the status notification
823 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
824 long totalToTransfer
, String filePath
) {
825 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
826 if (percent
!= mLastPercent
) {
827 mNotificationBuilder
.setProgress(100, percent
, false
);
828 String fileName
= filePath
.substring(
829 filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
830 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
831 mNotificationBuilder
.setContentText(text
);
832 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
834 mLastPercent
= percent
;
838 * Updates the status notification with the result of an upload operation.
840 * @param uploadResult Result of the upload operation.
841 * @param upload Finished upload operation
843 private void notifyUploadResult(
844 RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
845 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
846 // / cancelled operation or success -> silent removal of progress notification
847 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
849 // Show the result: success or fail notification
850 if (!uploadResult
.isCancelled()) {
851 int tickerId
= (uploadResult
.isSuccess()) ? R
.string
.uploader_upload_succeeded_ticker
:
852 R
.string
.uploader_upload_failed_ticker
;
856 // check credentials error
857 boolean needsToUpdateCredentials
= (
858 uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
859 uploadResult
.isIdPRedirection()
861 tickerId
= (needsToUpdateCredentials
) ?
862 R
.string
.uploader_upload_failed_credentials_error
: tickerId
;
865 .setTicker(getString(tickerId
))
866 .setContentTitle(getString(tickerId
))
869 .setProgress(0, 0, false
);
871 content
= ErrorMessageAdapter
.getErrorCauseMessage(
872 uploadResult
, upload
, getResources()
875 if (needsToUpdateCredentials
) {
876 // let the user update credentials with one click
877 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
878 updateAccountCredentials
.putExtra(
879 AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount()
881 updateAccountCredentials
.putExtra(
882 AuthenticatorActivity
.EXTRA_ACTION
,
883 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
885 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
886 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
887 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
888 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
890 (int) System
.currentTimeMillis(),
891 updateAccountCredentials
,
892 PendingIntent
.FLAG_ONE_SHOT
895 mUploadClient
= null
;
896 // grant that future retries on the same account will get the fresh credentials
898 mNotificationBuilder
.setContentText(content
);
900 if (upload
.isInstant()) {
903 db
= new DbHandler(this.getBaseContext());
904 String message
= uploadResult
.getLogMessage() + " errorCode: " +
905 uploadResult
.getCode();
906 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
907 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
908 //message = getString(R.string.failed_upload_quota_exceeded_text);
909 if (db
.updateFileState(
910 upload
.getOriginalStoragePath(),
911 DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
914 upload
.getOriginalStoragePath(),
915 upload
.getAccount().name
,
928 mNotificationBuilder
.setContentText(content
);
929 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
931 if (uploadResult
.isSuccess()) {
933 DbHandler db
= new DbHandler(this.getBaseContext());
934 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
937 // remove success notification, with a delay of 2 seconds
938 NotificationDelayer
.cancelWithDelay(
939 mNotificationManager
,
940 R
.string
.uploader_upload_succeeded_ticker
,
948 * Sends a broadcast in order to the interested activities can update their
951 * @param upload Finished upload operation
952 * @param uploadResult Result of the upload operation
954 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
955 Intent end
= new Intent(getUploadFinishMessage());
956 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
961 if (upload
.wasRenamed()) {
962 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
964 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
965 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
966 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
967 sendStickyBroadcast(end
);
971 * Checks if content provider, using the content:// scheme, returns a file with mime-type
972 * 'application/pdf' but file has not extension
973 * @param localPath Full path to a file in the local file system.
974 * @param mimeType MIME type of the file.
975 * @return true if is needed to add the pdf file extension to the file
977 private boolean isPdfFileFromContentProviderWithoutExtension(String localPath
,
979 return localPath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
) &&
980 mimeType
.equals(MIME_TYPE_PDF
) &&
981 !localPath
.endsWith(FILE_EXTENSION_PDF
);
985 * Remove uploads of an account
986 * @param accountName Name of an OC account
988 private void cancelUploadForAccount(String accountName
){
989 // this can be slow if there are many uploads :(
990 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
991 Log_OC
.d(TAG
, "Number of pending updloads= " + mPendingUploads
.size());
992 while (it
.hasNext()) {
993 String key
= it
.next();
994 Log_OC
.d(TAG
, "mPendingUploads CANCELLED " + key
);
995 if (key
.startsWith(accountName
)) {
996 synchronized (mPendingUploads
) {
997 mPendingUploads
.remove(key
);