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
.accounts
.AccountUtils
.Constants
;
61 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
62 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
63 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
64 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
65 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
66 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
67 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
68 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
69 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
70 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
71 import com
.owncloud
.android
.notifications
.NotificationBuilderWithProgressBar
;
72 import com
.owncloud
.android
.notifications
.NotificationDelayer
;
73 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
74 import com
.owncloud
.android
.operations
.UploadFileOperation
;
75 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
76 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
77 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
78 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
79 import com
.owncloud
.android
.utils
.UriUtils
;
82 public class FileUploader
extends Service
83 implements OnDatatransferProgressListener
, OnAccountsUpdateListener
{
85 private static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
86 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
87 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
88 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
89 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
90 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
92 public static final String KEY_FILE
= "FILE";
93 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
94 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
95 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
97 public static final String KEY_ACCOUNT
= "ACCOUNT";
99 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
100 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
101 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
102 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
104 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
105 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
106 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
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 mLastAccount
= null
;
118 private FileDataStorageManager mStorageManager
;
120 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, 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().toString() + UPLOAD_FINISH_MESSAGE
;
136 * Builds a key for mPendingUploads from the account and file to upload
138 * @param account Account where the file to upload is stored
139 * @param file File to upload
141 private String
buildRemoteName(Account account
, OCFile file
) {
142 return account
.name
+ file
.getRemotePath();
145 private String
buildRemoteName(Account account
, String remotePath
) {
146 return account
.name
+ remotePath
;
150 * Checks if an ownCloud server version should support chunked uploads.
152 * @param version OwnCloud version instance corresponding to an ownCloud
154 * @return 'True' if the ownCloud server with version supports chunked
157 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
158 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
162 * Service initialization
165 public void onCreate() {
167 Log_OC
.d(TAG
, "Creating service");
168 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
169 HandlerThread thread
= new HandlerThread("FileUploaderThread", Process
.THREAD_PRIORITY_BACKGROUND
);
171 mServiceLooper
= thread
.getLooper();
172 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
173 mBinder
= new FileUploaderBinder();
175 // add AccountsUpdatedListener
176 AccountManager am
= AccountManager
.get(getApplicationContext());
177 am
.addOnAccountsUpdatedListener(this, null
, false
);
184 public void onDestroy() {
185 Log_OC
.v(TAG
, "Destroying service" );
187 mServiceHandler
= null
;
188 mServiceLooper
.quit();
189 mServiceLooper
= null
;
190 mNotificationManager
= null
;
192 // remove AccountsUpdatedListener
193 AccountManager am
= AccountManager
.get(getApplicationContext());
194 am
.removeOnAccountsUpdatedListener(this);
201 * Entry point to add one or several files to the queue of uploads.
203 * New uploads are added calling to startService(), resulting in a call to
204 * this method. This ensures the service will keep on working although the
205 * caller activity goes away.
208 public int onStartCommand(Intent intent
, int flags
, int startId
) {
209 Log_OC
.d(TAG
, "Starting command with id " + startId
);
211 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
212 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
213 Log_OC
.e(TAG
, "Not enough information provided in intent");
214 return Service
.START_NOT_STICKY
;
216 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
217 if (uploadType
== -1) {
218 Log_OC
.e(TAG
, "Incorrect upload type provided");
219 return Service
.START_NOT_STICKY
;
221 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
222 if (!AccountUtils
.exists(account
, getApplicationContext())) {
223 return Service
.START_NOT_STICKY
;
226 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
227 OCFile
[] files
= null
;
228 if (uploadType
== UPLOAD_SINGLE_FILE
) {
230 if (intent
.hasExtra(KEY_FILE
)) {
231 files
= new OCFile
[] { (OCFile
) intent
.getParcelableExtra(KEY_FILE
) };
234 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
235 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
236 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
239 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
241 if (intent
.hasExtra(KEY_FILE
)) {
242 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
250 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
251 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
252 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
256 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
258 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
259 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
260 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
262 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
263 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
264 return Service
.START_NOT_STICKY
;
266 } else if (!intent
.hasExtra(KEY_FILE
)) {
267 if (localPaths
== null
) {
268 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
269 return Service
.START_NOT_STICKY
;
271 if (remotePaths
== null
) {
272 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
273 return Service
.START_NOT_STICKY
;
275 if (localPaths
.length
!= remotePaths
.length
) {
276 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
277 return Service
.START_NOT_STICKY
;
280 files
= new OCFile
[localPaths
.length
];
281 for (int i
= 0; i
< localPaths
.length
; i
++) {
282 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!= null
) ? mimeTypes
[i
]
283 : (String
) null
), storageManager
);
284 if (files
[i
] == null
) {
285 // TODO @andomaex add failure Notification
286 return Service
.START_NOT_STICKY
;
291 AccountManager aMgr
= AccountManager
.get(this);
292 String version
= aMgr
.getUserData(account
, Constants
.KEY_OC_VERSION
);
293 OwnCloudVersion ocv
= new OwnCloudVersion(version
);
295 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
296 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
297 String uploadKey
= null
;
298 UploadFileOperation newUpload
= null
;
300 for (int i
= 0; i
< files
.length
; i
++) {
301 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
302 newUpload
= new UploadFileOperation(account
, files
[i
], chunked
, isInstant
, forceOverwrite
, localAction
,
303 getApplicationContext());
305 newUpload
.setRemoteFolderToBeCreated();
307 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
); // Grants that the file only upload once time
309 newUpload
.addDatatransferProgressListener(this);
310 newUpload
.addDatatransferProgressListener((FileUploaderBinder
)mBinder
);
311 requestedUploads
.add(uploadKey
);
314 } catch (IllegalArgumentException e
) {
315 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
316 return START_NOT_STICKY
;
318 } catch (IllegalStateException e
) {
319 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
320 return START_NOT_STICKY
;
322 } catch (Exception e
) {
323 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
324 return START_NOT_STICKY
;
328 if (requestedUploads
.size() > 0) {
329 Message msg
= mServiceHandler
.obtainMessage();
331 msg
.obj
= requestedUploads
;
332 mServiceHandler
.sendMessage(msg
);
334 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
335 return Service
.START_NOT_STICKY
;
339 * Provides a binder object that clients can use to perform operations on
340 * the queue of uploads, excepting the addition of new files.
342 * Implemented to perform cancellation, pause and resume of existing
346 public IBinder
onBind(Intent arg0
) {
351 * Called when ALL the bound clients were onbound.
354 public boolean onUnbind(Intent intent
) {
355 ((FileUploaderBinder
)mBinder
).clearListeners();
356 return false
; // not accepting rebinding (default behaviour)
360 public void onAccountsUpdated(Account
[] accounts
) {
361 // Review current upload, and cancel it if its account doen't exist
362 if (mCurrentUpload
!= null
&&
363 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
364 mCurrentUpload
.cancel();
366 // The rest of uploads are cancelled when they try to start
370 * Binder to let client components to perform operations on the queue of
373 * It provides by itself the available operations.
375 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
378 * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
380 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
383 * Cancels a pending or current upload of a remote file.
385 * @param account Owncloud account where the remote file will be stored.
386 * @param file A file in the queue of pending uploads
388 public void cancel(Account account
, OCFile file
) {
389 UploadFileOperation upload
= null
;
390 synchronized (mPendingUploads
) {
391 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
393 if (upload
!= null
) {
399 * Cancels a pending or current upload for an account
401 * @param account Owncloud accountName where the remote file will be stored.
403 public void cancel(Account account
) {
404 Log_OC
.d(TAG
, "Account= " + account
.name
);
406 if (mCurrentUpload
!= null
) {
407 Log_OC
.d(TAG
, "Current Upload Account= " + mCurrentUpload
.getAccount().name
);
408 if (mCurrentUpload
.getAccount().name
.equals(account
.name
)) {
409 mCurrentUpload
.cancel();
412 // Cancel pending uploads
413 cancelUploadForAccount(account
.name
);
416 public void clearListeners() {
417 mBoundListeners
.clear();
421 * Returns True when the file described by 'file' is being uploaded to
422 * the ownCloud account 'account' or waiting for it
424 * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
426 * @param account ownCloud account where the remote file will be stored.
427 * @param file A file that could be in the queue of pending uploads
429 public boolean isUploading(Account account
, OCFile file
) {
430 if (account
== null
|| file
== null
)
432 String targetKey
= buildRemoteName(account
, file
);
433 synchronized (mPendingUploads
) {
434 if (file
.isFolder()) {
435 // this can be slow if there are many uploads :(
436 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
437 boolean found
= false
;
438 while (it
.hasNext() && !found
) {
439 found
= it
.next().startsWith(targetKey
);
443 return (mPendingUploads
.containsKey(targetKey
));
450 * Adds a listener interested in the progress of the upload for a concrete file.
452 * @param listener Object to notify about progress of transfer.
453 * @param account ownCloud account holding the file of interest.
454 * @param file {@link OCFile} of interest for listener.
456 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
457 if (account
== null
|| file
== null
|| listener
== null
) return;
458 String targetKey
= buildRemoteName(account
, file
);
459 mBoundListeners
.put(targetKey
, listener
);
465 * Removes a listener interested in the progress of the upload for a concrete file.
467 * @param listener Object to notify about progress of transfer.
468 * @param account ownCloud account holding the file of interest.
469 * @param file {@link OCFile} of interest for listener.
471 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
472 if (account
== null
|| file
== null
|| listener
== null
) return;
473 String targetKey
= buildRemoteName(account
, file
);
474 if (mBoundListeners
.get(targetKey
) == listener
) {
475 mBoundListeners
.remove(targetKey
);
481 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
483 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
484 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
485 if (boundListener
!= null
) {
486 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
491 * Review uploads and cancel it if its account doesn't exist
493 public void checkAccountOfCurrentUpload() {
494 if (mCurrentUpload
!= null
&&
495 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
496 mCurrentUpload
.cancel();
498 // The rest of uploads are cancelled when they try to start
503 * Upload worker. Performs the pending uploads in the order they were
506 * Created with the Looper of a new thread, started in
507 * {@link FileUploader#onCreate()}.
509 private static class ServiceHandler
extends Handler
{
510 // don't make it a final class, and don't remove the static ; lint will
511 // warn about a possible memory leak
512 FileUploader mService
;
514 public ServiceHandler(Looper looper
, FileUploader service
) {
517 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
522 public void handleMessage(Message msg
) {
523 @SuppressWarnings("unchecked")
524 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
525 if (msg
.obj
!= null
) {
526 Iterator
<String
> it
= requestedUploads
.iterator();
527 while (it
.hasNext()) {
528 mService
.uploadFile(it
.next());
531 Log_OC
.d(TAG
, "Stopping command after id " + msg
.arg1
);
532 mService
.stopSelf(msg
.arg1
);
537 * Core upload method: sends the file(s) to upload
539 * @param uploadKey Key to access the upload to perform, contained in
542 public void uploadFile(String uploadKey
) {
544 synchronized (mPendingUploads
) {
545 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
548 if (mCurrentUpload
!= null
) {
550 // Detect if the account exists
551 if (AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
552 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().name
+ " exists");
554 notifyUploadStart(mCurrentUpload
);
556 RemoteOperationResult uploadResult
= null
, grantResult
= null
;
559 /// prepare client object to send requests to the ownCloud server
560 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
561 mLastAccount
= mCurrentUpload
.getAccount();
563 new FileDataStorageManager(mLastAccount
, getContentResolver());
564 OwnCloudAccount ocAccount
= new OwnCloudAccount(mLastAccount
, this);
565 mUploadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
566 getClientFor(ocAccount
, this);
569 /// check the existence of the parent folder for the file to upload
570 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
571 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
572 remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
573 grantResult
= grantFolderExistence(remoteParentPath
);
575 /// perform the upload
576 if (grantResult
.isSuccess()) {
577 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
578 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
579 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
580 if (uploadResult
.isSuccess()) {
584 uploadResult
= grantResult
;
587 } catch (AccountsException e
) {
588 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
589 uploadResult
= new RemoteOperationResult(e
);
591 } catch (IOException e
) {
592 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
593 uploadResult
= new RemoteOperationResult(e
);
596 synchronized (mPendingUploads
) {
597 mPendingUploads
.remove(uploadKey
);
598 Log_OC
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
600 if (uploadResult
.isException()) {
601 // enforce the creation of a new client object for next uploads; this grant that a new socket will
602 // be created in the future if the current exception is due to an abrupt lose of network connection
603 mUploadClient
= null
;
608 notifyUploadResult(uploadResult
, mCurrentUpload
);
609 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
612 // Cancel the transfer
613 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().toString() + " doesn't exist");
614 cancelUploadForAccount(mCurrentUpload
.getAccount().name
);
622 * Checks the existence of the folder where the current file will be uploaded both in the remote server
623 * and in the local database.
625 * If the upload is set to enforce the creation of the folder, the method tries to create it both remote
628 * @param pathToGrant Full remote path whose existence will be granted.
629 * @return An {@link OCFile} instance corresponding to the folder where the file will be uploaded.
631 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
632 RemoteOperation operation
= new ExistenceCheckRemoteOperation(pathToGrant
, this, false
);
633 RemoteOperationResult result
= operation
.execute(mUploadClient
);
634 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&&
635 mCurrentUpload
.isRemoteFolderToBeCreated()) {
636 SyncOperation syncOp
= new CreateFolderOperation( pathToGrant
, true
);
637 result
= syncOp
.execute(mUploadClient
, mStorageManager
);
639 if (result
.isSuccess()) {
640 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
641 if (parentDir
== null
) {
642 parentDir
= createLocalFolder(pathToGrant
);
644 if (parentDir
!= null
) {
645 result
= new RemoteOperationResult(ResultCode
.OK
);
647 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
654 private OCFile
createLocalFolder(String remotePath
) {
655 String parentPath
= new File(remotePath
).getParent();
656 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
657 parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
658 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
659 if (parent
== null
) {
660 parent
= createLocalFolder(parentPath
);
662 if (parent
!= null
) {
663 OCFile createdFolder
= new OCFile(remotePath
);
664 createdFolder
.setMimetype("DIR");
665 createdFolder
.setParentId(parent
.getFileId());
666 mStorageManager
.saveFile(createdFolder
);
667 return createdFolder
;
674 * Saves a OC File after a successful upload.
676 * A PROPFIND is necessary to keep the props in the local database
677 * synchronized with the server, specially the modification time and Etag
680 * TODO refactor this ugly thing
682 private void saveUploadedFile() {
683 OCFile file
= mCurrentUpload
.getFile();
684 if (file
.fileExists()) {
685 file
= mStorageManager
.getFileById(file
.getFileId());
687 long syncDate
= System
.currentTimeMillis();
688 file
.setLastSyncDateForData(syncDate
);
690 // new PROPFIND to keep data consistent with server
691 // in theory, should return the same we already have
692 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(mCurrentUpload
.getRemotePath());
693 RemoteOperationResult result
= operation
.execute(mUploadClient
);
694 if (result
.isSuccess()) {
695 updateOCFile(file
, (RemoteFile
) result
.getData().get(0));
696 file
.setLastSyncDateForProperties(syncDate
);
699 // / maybe this would be better as part of UploadFileOperation... or
700 // maybe all this method
701 if (mCurrentUpload
.wasRenamed()) {
702 OCFile oldFile
= mCurrentUpload
.getOldFile();
703 if (oldFile
.fileExists()) {
704 oldFile
.setStoragePath(null
);
705 mStorageManager
.saveFile(oldFile
);
707 } // else: it was just an automatic renaming due to a name
708 // coincidence; nothing else is needed, the storagePath is right
709 // in the instance returned by mCurrentUpload.getFile()
711 file
.setNeedsUpdateThumbnail(true
);
712 mStorageManager
.saveFile(file
);
715 private void updateOCFile(OCFile file
, RemoteFile remoteFile
) {
716 file
.setCreationTimestamp(remoteFile
.getCreationTimestamp());
717 file
.setFileLength(remoteFile
.getLength());
718 file
.setMimetype(remoteFile
.getMimeType());
719 file
.setModificationTimestamp(remoteFile
.getModifiedTimestamp());
720 file
.setModificationTimestampAtLastSyncForData(remoteFile
.getModifiedTimestamp());
721 // file.setEtag(remoteFile.getEtag()); // TODO Etag, where available
722 file
.setRemoteId(remoteFile
.getRemoteId());
725 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
726 FileDataStorageManager storageManager
) {
729 if (mimeType
== null
|| mimeType
.length() <= 0) {
731 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
732 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
733 } catch (IndexOutOfBoundsException e
) {
734 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
737 if (mimeType
== null
) {
738 mimeType
= "application/octet-stream";
741 if (isPdfFileFromContentProviderWithoutExtension(localPath
, mimeType
)){
742 remotePath
+= FILE_EXTENSION_PDF
;
745 OCFile newFile
= new OCFile(remotePath
);
746 newFile
.setStoragePath(localPath
);
747 newFile
.setLastSyncDateForProperties(0);
748 newFile
.setLastSyncDateForData(0);
751 if (localPath
!= null
&& localPath
.length() > 0) {
752 File localFile
= new File(localPath
);
753 newFile
.setFileLength(localFile
.length());
754 newFile
.setLastSyncDateForData(localFile
.lastModified());
755 } // don't worry about not assigning size, the problems with localPath
756 // are checked when the UploadFileOperation instance is created
759 newFile
.setMimetype(mimeType
);
765 * Creates a status notification to show the upload progress
767 * @param upload Upload operation starting.
769 private void notifyUploadStart(UploadFileOperation upload
) {
770 // / create status notification with a progress bar
772 mNotificationBuilder
=
773 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
776 .setSmallIcon(R
.drawable
.notification_icon
)
777 .setTicker(getString(R
.string
.uploader_upload_in_progress_ticker
))
778 .setContentTitle(getString(R
.string
.uploader_upload_in_progress_ticker
))
779 .setProgress(100, 0, false
)
781 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
783 /// includes a pending intent in the notification showing the details view of the file
784 Intent showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
785 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
786 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
787 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
788 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
789 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
792 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
796 * Callback method to update the progress bar in the status notification
799 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
) {
800 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
801 if (percent
!= mLastPercent
) {
802 mNotificationBuilder
.setProgress(100, percent
, false
);
803 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
804 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
805 mNotificationBuilder
.setContentText(text
);
806 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
808 mLastPercent
= percent
;
812 * Updates the status notification with the result of an upload operation.
814 * @param uploadResult Result of the upload operation.
815 * @param upload Finished upload operation
817 private void notifyUploadResult(
818 RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
819 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
820 // / cancelled operation or success -> silent removal of progress notification
821 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
823 // Show the result: success or fail notification
824 if (!uploadResult
.isCancelled()) {
825 int tickerId
= (uploadResult
.isSuccess()) ? R
.string
.uploader_upload_succeeded_ticker
:
826 R
.string
.uploader_upload_failed_ticker
;
828 String content
= null
;
830 // check credentials error
831 boolean needsToUpdateCredentials
= (
832 uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
833 uploadResult
.isIdPRedirection()
835 tickerId
= (needsToUpdateCredentials
) ?
836 R
.string
.uploader_upload_failed_credentials_error
: tickerId
;
839 .setTicker(getString(tickerId
))
840 .setContentTitle(getString(tickerId
))
843 .setProgress(0, 0, false
);
845 content
= ErrorMessageAdapter
.getErrorCauseMessage(
846 uploadResult
, upload
, getResources()
849 if (needsToUpdateCredentials
) {
850 // let the user update credentials with one click
851 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
852 updateAccountCredentials
.putExtra(
853 AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount()
855 updateAccountCredentials
.putExtra(
856 AuthenticatorActivity
.EXTRA_ACTION
,
857 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
859 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
860 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
861 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
862 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
864 (int) System
.currentTimeMillis(),
865 updateAccountCredentials
,
866 PendingIntent
.FLAG_ONE_SHOT
869 mUploadClient
= null
;
870 // grant that future retries on the same account will get the fresh credentials
872 mNotificationBuilder
.setContentText(content
);
874 if (upload
.isInstant()) {
877 db
= new DbHandler(this.getBaseContext());
878 String message
= uploadResult
.getLogMessage() + " errorCode: " +
879 uploadResult
.getCode();
880 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
881 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
882 //message = getString(R.string.failed_upload_quota_exceeded_text);
883 if (db
.updateFileState(
884 upload
.getOriginalStoragePath(),
885 DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
888 upload
.getOriginalStoragePath(),
889 upload
.getAccount().name
,
902 mNotificationBuilder
.setContentText(content
);
903 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
905 if (uploadResult
.isSuccess()) {
907 DbHandler db
= new DbHandler(this.getBaseContext());
908 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
911 // remove success notification, with a delay of 2 seconds
912 NotificationDelayer
.cancelWithDelay(
913 mNotificationManager
,
914 R
.string
.uploader_upload_succeeded_ticker
,
922 * Sends a broadcast in order to the interested activities can update their
925 * @param upload Finished upload operation
926 * @param uploadResult Result of the upload operation
928 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
929 Intent end
= new Intent(getUploadFinishMessage());
930 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
935 if (upload
.wasRenamed()) {
936 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
938 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
939 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
940 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
941 sendStickyBroadcast(end
);
945 * Checks if content provider, using the content:// scheme, returns a file with mime-type
946 * 'application/pdf' but file has not extension
949 * @return true if is needed to add the pdf file extension to the file
951 private boolean isPdfFileFromContentProviderWithoutExtension(String localPath
, String mimeType
) {
952 return localPath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
) &&
953 mimeType
.equals(MIME_TYPE_PDF
) &&
954 !localPath
.endsWith(FILE_EXTENSION_PDF
);
958 * Remove uploads of an account
961 private void cancelUploadForAccount(String accountName
){
962 // this can be slow if there are many uploads :(
963 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
964 Log_OC
.d(TAG
, "Number of pending updloads= " + mPendingUploads
.size());
965 while (it
.hasNext()) {
966 String key
= it
.next();
967 Log_OC
.d(TAG
, "mPendingUploads CANCELLED " + key
);
968 if (key
.startsWith(accountName
)) {
969 synchronized (mPendingUploads
) {
970 mPendingUploads
.remove(key
);