1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2015 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.files
.services
;
22 import java
.io
.IOException
;
23 import java
.util
.AbstractList
;
24 import java
.util
.HashMap
;
25 import java
.util
.Iterator
;
27 import java
.util
.Vector
;
28 import java
.util
.concurrent
.ConcurrentHashMap
;
29 import java
.util
.concurrent
.ConcurrentMap
;
31 import android
.accounts
.Account
;
32 import android
.accounts
.AccountManager
;
33 import android
.accounts
.AccountsException
;
34 import android
.accounts
.OnAccountsUpdateListener
;
35 import android
.app
.NotificationManager
;
36 import android
.app
.PendingIntent
;
37 import android
.app
.Service
;
38 import android
.content
.Intent
;
39 import android
.os
.Binder
;
40 import android
.os
.Handler
;
41 import android
.os
.HandlerThread
;
42 import android
.os
.IBinder
;
43 import android
.os
.Looper
;
44 import android
.os
.Message
;
45 import android
.os
.Process
;
46 import android
.support
.v4
.app
.NotificationCompat
;
47 import android
.webkit
.MimeTypeMap
;
49 import com
.owncloud
.android
.R
;
50 import com
.owncloud
.android
.authentication
.AccountUtils
;
51 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
52 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
53 import com
.owncloud
.android
.datamodel
.OCFile
;
54 import com
.owncloud
.android
.db
.DbHandler
;
55 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
56 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
57 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
58 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
59 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
60 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
61 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
62 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
63 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
64 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
65 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
66 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
67 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
68 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
69 import com
.owncloud
.android
.notifications
.NotificationBuilderWithProgressBar
;
70 import com
.owncloud
.android
.notifications
.NotificationDelayer
;
71 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
72 import com
.owncloud
.android
.operations
.UploadFileOperation
;
73 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
74 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
75 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
76 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
77 import com
.owncloud
.android
.utils
.UriUtils
;
80 public class FileUploader
extends Service
81 implements OnDatatransferProgressListener
, OnAccountsUpdateListener
{
83 private static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
84 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
85 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
86 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
87 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
88 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
90 public static final String KEY_FILE
= "FILE";
91 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
92 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
93 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
95 public static final String KEY_ACCOUNT
= "ACCOUNT";
97 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
98 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
99 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
100 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
102 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
103 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
104 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
106 public static final int UPLOAD_SINGLE_FILE
= 0;
107 public static final int UPLOAD_MULTIPLE_FILES
= 1;
109 private static final String TAG
= FileUploader
.class.getSimpleName();
111 private Looper mServiceLooper
;
112 private ServiceHandler mServiceHandler
;
113 private IBinder mBinder
;
114 private OwnCloudClient mUploadClient
= null
;
115 private Account mLastAccount
= null
;
116 private FileDataStorageManager mStorageManager
;
118 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
119 private UploadFileOperation mCurrentUpload
= null
;
121 private NotificationManager mNotificationManager
;
122 private NotificationCompat
.Builder mNotificationBuilder
;
123 private int mLastPercent
;
125 private static final String MIME_TYPE_PDF
= "application/pdf";
126 private static final String FILE_EXTENSION_PDF
= ".pdf";
129 public static String
getUploadFinishMessage() {
130 return FileUploader
.class.getName().toString() + UPLOAD_FINISH_MESSAGE
;
134 * Builds a key for mPendingUploads from the account and file to upload
136 * @param account Account where the file to upload is stored
137 * @param file File to upload
139 private String
buildRemoteName(Account account
, OCFile file
) {
140 return account
.name
+ file
.getRemotePath();
143 private String
buildRemoteName(Account account
, String remotePath
) {
144 return account
.name
+ remotePath
;
148 * Checks if an ownCloud server version should support chunked uploads.
150 * @param version OwnCloud version instance corresponding to an ownCloud
152 * @return 'True' if the ownCloud server with version supports chunked
155 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
156 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
160 * Service initialization
163 public void onCreate() {
165 Log_OC
.d(TAG
, "Creating service");
166 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
167 HandlerThread thread
= new HandlerThread("FileUploaderThread", Process
.THREAD_PRIORITY_BACKGROUND
);
169 mServiceLooper
= thread
.getLooper();
170 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
171 mBinder
= new FileUploaderBinder();
173 // add AccountsUpdatedListener
174 AccountManager am
= AccountManager
.get(getApplicationContext());
175 am
.addOnAccountsUpdatedListener(this, null
, false
);
182 public void onDestroy() {
183 Log_OC
.v(TAG
, "Destroying service" );
185 mServiceHandler
= null
;
186 mServiceLooper
.quit();
187 mServiceLooper
= null
;
188 mNotificationManager
= null
;
190 // remove AccountsUpdatedListener
191 AccountManager am
= AccountManager
.get(getApplicationContext());
192 am
.removeOnAccountsUpdatedListener(this);
199 * Entry point to add one or several files to the queue of uploads.
201 * New uploads are added calling to startService(), resulting in a call to
202 * this method. This ensures the service will keep on working although the
203 * caller activity goes away.
206 public int onStartCommand(Intent intent
, int flags
, int startId
) {
207 Log_OC
.d(TAG
, "Starting command with id " + startId
);
209 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
210 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
211 Log_OC
.e(TAG
, "Not enough information provided in intent");
212 return Service
.START_NOT_STICKY
;
214 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
215 if (uploadType
== -1) {
216 Log_OC
.e(TAG
, "Incorrect upload type provided");
217 return Service
.START_NOT_STICKY
;
219 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
220 if (!AccountUtils
.exists(account
, getApplicationContext())) {
221 return Service
.START_NOT_STICKY
;
224 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
225 OCFile
[] files
= null
;
226 if (uploadType
== UPLOAD_SINGLE_FILE
) {
228 if (intent
.hasExtra(KEY_FILE
)) {
229 files
= new OCFile
[] { (OCFile
) intent
.getParcelableExtra(KEY_FILE
) };
232 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
233 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
234 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
237 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
239 if (intent
.hasExtra(KEY_FILE
)) {
240 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
248 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
249 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
250 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
254 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
256 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
257 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
258 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
260 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
261 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
262 return Service
.START_NOT_STICKY
;
264 } else if (!intent
.hasExtra(KEY_FILE
)) {
265 if (localPaths
== null
) {
266 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
267 return Service
.START_NOT_STICKY
;
269 if (remotePaths
== null
) {
270 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
271 return Service
.START_NOT_STICKY
;
273 if (localPaths
.length
!= remotePaths
.length
) {
274 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
275 return Service
.START_NOT_STICKY
;
278 files
= new OCFile
[localPaths
.length
];
279 for (int i
= 0; i
< localPaths
.length
; i
++) {
280 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!= null
) ? mimeTypes
[i
]
281 : (String
) null
), storageManager
);
282 if (files
[i
] == null
) {
283 // TODO @andomaex add failure Notification
284 return Service
.START_NOT_STICKY
;
289 AccountManager aMgr
= AccountManager
.get(this);
290 String version
= aMgr
.getUserData(account
, Constants
.KEY_OC_VERSION
);
291 OwnCloudVersion ocv
= new OwnCloudVersion(version
);
293 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
294 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
295 String uploadKey
= null
;
296 UploadFileOperation newUpload
= null
;
298 for (int i
= 0; i
< files
.length
; i
++) {
299 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
300 newUpload
= new UploadFileOperation(account
, files
[i
], chunked
, isInstant
, forceOverwrite
, localAction
,
301 getApplicationContext());
303 newUpload
.setRemoteFolderToBeCreated();
305 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
); // Grants that the file only upload once time
307 newUpload
.addDatatransferProgressListener(this);
308 newUpload
.addDatatransferProgressListener((FileUploaderBinder
)mBinder
);
309 requestedUploads
.add(uploadKey
);
312 } catch (IllegalArgumentException e
) {
313 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
314 return START_NOT_STICKY
;
316 } catch (IllegalStateException e
) {
317 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
318 return START_NOT_STICKY
;
320 } catch (Exception e
) {
321 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
322 return START_NOT_STICKY
;
326 if (requestedUploads
.size() > 0) {
327 Message msg
= mServiceHandler
.obtainMessage();
329 msg
.obj
= requestedUploads
;
330 mServiceHandler
.sendMessage(msg
);
332 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
333 return Service
.START_NOT_STICKY
;
337 * Provides a binder object that clients can use to perform operations on
338 * the queue of uploads, excepting the addition of new files.
340 * Implemented to perform cancellation, pause and resume of existing
344 public IBinder
onBind(Intent arg0
) {
349 * Called when ALL the bound clients were onbound.
352 public boolean onUnbind(Intent intent
) {
353 ((FileUploaderBinder
)mBinder
).clearListeners();
354 return false
; // not accepting rebinding (default behaviour)
358 public void onAccountsUpdated(Account
[] accounts
) {
359 // Review current upload, and cancel it if its account doen't exist
360 if (mCurrentUpload
!= null
&&
361 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
362 mCurrentUpload
.cancel();
364 // The rest of uploads are cancelled when they try to start
368 * Binder to let client components to perform operations on the queue of
371 * It provides by itself the available operations.
373 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
376 * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
378 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
381 * Cancels a pending or current upload of a remote file.
383 * @param account Owncloud account where the remote file will be stored.
384 * @param file A file in the queue of pending uploads
386 public void cancel(Account account
, OCFile file
) {
387 UploadFileOperation upload
= null
;
388 synchronized (mPendingUploads
) {
389 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
391 if (upload
!= null
) {
397 * Cancels a pending or current upload for an account
399 * @param account Owncloud accountName where the remote file will be stored.
401 public void cancel(Account account
) {
402 Log_OC
.d(TAG
, "Account= " + account
.name
);
404 if (mCurrentUpload
!= null
) {
405 Log_OC
.d(TAG
, "Current Upload Account= " + mCurrentUpload
.getAccount().name
);
406 if (mCurrentUpload
.getAccount().name
.equals(account
.name
)) {
407 mCurrentUpload
.cancel();
410 // Cancel pending uploads
411 cancelUploadForAccount(account
.name
);
414 public void clearListeners() {
415 mBoundListeners
.clear();
419 * Returns True when the file described by 'file' is being uploaded to
420 * the ownCloud account 'account' or waiting for it
422 * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
424 * @param account ownCloud account where the remote file will be stored.
425 * @param file A file that could be in the queue of pending uploads
427 public boolean isUploading(Account account
, OCFile file
) {
428 if (account
== null
|| file
== null
)
430 String targetKey
= buildRemoteName(account
, file
);
431 synchronized (mPendingUploads
) {
432 if (file
.isFolder()) {
433 // this can be slow if there are many uploads :(
434 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
435 boolean found
= false
;
436 while (it
.hasNext() && !found
) {
437 found
= it
.next().startsWith(targetKey
);
441 return (mPendingUploads
.containsKey(targetKey
));
448 * Adds a listener interested in the progress of the upload for a concrete file.
450 * @param listener Object to notify about progress of transfer.
451 * @param account ownCloud account holding the file of interest.
452 * @param file {@link OCFile} of interest for listener.
454 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
455 if (account
== null
|| file
== null
|| listener
== null
) return;
456 String targetKey
= buildRemoteName(account
, file
);
457 mBoundListeners
.put(targetKey
, listener
);
463 * Removes a listener interested in the progress of the upload for a concrete file.
465 * @param listener Object to notify about progress of transfer.
466 * @param account ownCloud account holding the file of interest.
467 * @param file {@link OCFile} of interest for listener.
469 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
470 if (account
== null
|| file
== null
|| listener
== null
) return;
471 String targetKey
= buildRemoteName(account
, file
);
472 if (mBoundListeners
.get(targetKey
) == listener
) {
473 mBoundListeners
.remove(targetKey
);
479 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
481 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
482 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
483 if (boundListener
!= null
) {
484 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
489 * Review uploads and cancel it if its account doesn't exist
491 public void checkAccountOfCurrentUpload() {
492 if (mCurrentUpload
!= null
&&
493 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
494 mCurrentUpload
.cancel();
496 // The rest of uploads are cancelled when they try to start
501 * Upload worker. Performs the pending uploads in the order they were
504 * Created with the Looper of a new thread, started in
505 * {@link FileUploader#onCreate()}.
507 private static class ServiceHandler
extends Handler
{
508 // don't make it a final class, and don't remove the static ; lint will
509 // warn about a possible memory leak
510 FileUploader mService
;
512 public ServiceHandler(Looper looper
, FileUploader service
) {
515 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
520 public void handleMessage(Message msg
) {
521 @SuppressWarnings("unchecked")
522 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
523 if (msg
.obj
!= null
) {
524 Iterator
<String
> it
= requestedUploads
.iterator();
525 while (it
.hasNext()) {
526 mService
.uploadFile(it
.next());
529 Log_OC
.d(TAG
, "Stopping command after id " + msg
.arg1
);
530 mService
.stopSelf(msg
.arg1
);
535 * Core upload method: sends the file(s) to upload
537 * @param uploadKey Key to access the upload to perform, contained in
540 public void uploadFile(String uploadKey
) {
542 synchronized (mPendingUploads
) {
543 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
546 if (mCurrentUpload
!= null
) {
548 // Detect if the account exists
549 if (AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
550 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().name
+ " exists");
552 notifyUploadStart(mCurrentUpload
);
554 RemoteOperationResult uploadResult
= null
, grantResult
= null
;
557 /// prepare client object to send requests to the ownCloud server
558 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
559 mLastAccount
= mCurrentUpload
.getAccount();
561 new FileDataStorageManager(mLastAccount
, getContentResolver());
562 OwnCloudAccount ocAccount
= new OwnCloudAccount(mLastAccount
, this);
563 mUploadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
564 getClientFor(ocAccount
, this);
567 /// check the existence of the parent folder for the file to upload
568 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
569 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
570 remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
571 grantResult
= grantFolderExistence(remoteParentPath
);
573 /// perform the upload
574 if (grantResult
.isSuccess()) {
575 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
576 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
577 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
578 if (uploadResult
.isSuccess()) {
582 uploadResult
= grantResult
;
585 } catch (AccountsException e
) {
586 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
587 uploadResult
= new RemoteOperationResult(e
);
589 } catch (IOException e
) {
590 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
591 uploadResult
= new RemoteOperationResult(e
);
594 synchronized (mPendingUploads
) {
595 mPendingUploads
.remove(uploadKey
);
596 Log_OC
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
598 if (uploadResult
.isException()) {
599 // enforce the creation of a new client object for next uploads; this grant that a new socket will
600 // be created in the future if the current exception is due to an abrupt lose of network connection
601 mUploadClient
= null
;
606 notifyUploadResult(uploadResult
, mCurrentUpload
);
607 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
610 // Cancel the transfer
611 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().toString() + " doesn't exist");
612 cancelUploadForAccount(mCurrentUpload
.getAccount().name
);
620 * Checks the existence of the folder where the current file will be uploaded both in the remote server
621 * and in the local database.
623 * If the upload is set to enforce the creation of the folder, the method tries to create it both remote
626 * @param pathToGrant Full remote path whose existence will be granted.
627 * @return An {@link OCFile} instance corresponding to the folder where the file will be uploaded.
629 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
630 RemoteOperation operation
= new ExistenceCheckRemoteOperation(pathToGrant
, this, false
);
631 RemoteOperationResult result
= operation
.execute(mUploadClient
);
632 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&&
633 mCurrentUpload
.isRemoteFolderToBeCreated()) {
634 SyncOperation syncOp
= new CreateFolderOperation( pathToGrant
, true
);
635 result
= syncOp
.execute(mUploadClient
, mStorageManager
);
637 if (result
.isSuccess()) {
638 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
639 if (parentDir
== null
) {
640 parentDir
= createLocalFolder(pathToGrant
);
642 if (parentDir
!= null
) {
643 result
= new RemoteOperationResult(ResultCode
.OK
);
645 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
652 private OCFile
createLocalFolder(String remotePath
) {
653 String parentPath
= new File(remotePath
).getParent();
654 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
655 parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
656 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
657 if (parent
== null
) {
658 parent
= createLocalFolder(parentPath
);
660 if (parent
!= null
) {
661 OCFile createdFolder
= new OCFile(remotePath
);
662 createdFolder
.setMimetype("DIR");
663 createdFolder
.setParentId(parent
.getFileId());
664 mStorageManager
.saveFile(createdFolder
);
665 return createdFolder
;
672 * Saves a OC File after a successful upload.
674 * A PROPFIND is necessary to keep the props in the local database
675 * synchronized with the server, specially the modification time and Etag
678 * TODO refactor this ugly thing
680 private void saveUploadedFile() {
681 OCFile file
= mCurrentUpload
.getFile();
682 if (file
.fileExists()) {
683 file
= mStorageManager
.getFileById(file
.getFileId());
685 long syncDate
= System
.currentTimeMillis();
686 file
.setLastSyncDateForData(syncDate
);
688 // new PROPFIND to keep data consistent with server
689 // in theory, should return the same we already have
690 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(mCurrentUpload
.getRemotePath());
691 RemoteOperationResult result
= operation
.execute(mUploadClient
);
692 if (result
.isSuccess()) {
693 updateOCFile(file
, (RemoteFile
) result
.getData().get(0));
694 file
.setLastSyncDateForProperties(syncDate
);
697 // / maybe this would be better as part of UploadFileOperation... or
698 // maybe all this method
699 if (mCurrentUpload
.wasRenamed()) {
700 OCFile oldFile
= mCurrentUpload
.getOldFile();
701 if (oldFile
.fileExists()) {
702 oldFile
.setStoragePath(null
);
703 mStorageManager
.saveFile(oldFile
);
705 } // else: it was just an automatic renaming due to a name
706 // coincidence; nothing else is needed, the storagePath is right
707 // in the instance returned by mCurrentUpload.getFile()
709 file
.setNeedsUpdateThumbnail(true
);
710 mStorageManager
.saveFile(file
);
713 private void updateOCFile(OCFile file
, RemoteFile remoteFile
) {
714 file
.setCreationTimestamp(remoteFile
.getCreationTimestamp());
715 file
.setFileLength(remoteFile
.getLength());
716 file
.setMimetype(remoteFile
.getMimeType());
717 file
.setModificationTimestamp(remoteFile
.getModifiedTimestamp());
718 file
.setModificationTimestampAtLastSyncForData(remoteFile
.getModifiedTimestamp());
719 // file.setEtag(remoteFile.getEtag()); // TODO Etag, where available
720 file
.setRemoteId(remoteFile
.getRemoteId());
723 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
724 FileDataStorageManager storageManager
) {
727 if (mimeType
== null
|| mimeType
.length() <= 0) {
729 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
730 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
731 } catch (IndexOutOfBoundsException e
) {
732 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
735 if (mimeType
== null
) {
736 mimeType
= "application/octet-stream";
739 if (isPdfFileFromContentProviderWithoutExtension(localPath
, mimeType
)){
740 remotePath
+= FILE_EXTENSION_PDF
;
743 OCFile newFile
= new OCFile(remotePath
);
744 newFile
.setStoragePath(localPath
);
745 newFile
.setLastSyncDateForProperties(0);
746 newFile
.setLastSyncDateForData(0);
749 if (localPath
!= null
&& localPath
.length() > 0) {
750 File localFile
= new File(localPath
);
751 newFile
.setFileLength(localFile
.length());
752 newFile
.setLastSyncDateForData(localFile
.lastModified());
753 } // don't worry about not assigning size, the problems with localPath
754 // are checked when the UploadFileOperation instance is created
757 newFile
.setMimetype(mimeType
);
763 * Creates a status notification to show the upload progress
765 * @param upload Upload operation starting.
767 private void notifyUploadStart(UploadFileOperation upload
) {
768 // / create status notification with a progress bar
770 mNotificationBuilder
=
771 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
774 .setSmallIcon(R
.drawable
.notification_icon
)
775 .setTicker(getString(R
.string
.uploader_upload_in_progress_ticker
))
776 .setContentTitle(getString(R
.string
.uploader_upload_in_progress_ticker
))
777 .setProgress(100, 0, false
)
779 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
781 /// includes a pending intent in the notification showing the details view of the file
782 Intent showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
783 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
784 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
785 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
786 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
787 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
790 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
794 * Callback method to update the progress bar in the status notification
797 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
) {
798 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
799 if (percent
!= mLastPercent
) {
800 mNotificationBuilder
.setProgress(100, percent
, false
);
801 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
802 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
803 mNotificationBuilder
.setContentText(text
);
804 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
806 mLastPercent
= percent
;
810 * Updates the status notification with the result of an upload operation.
812 * @param uploadResult Result of the upload operation.
813 * @param upload Finished upload operation
815 private void notifyUploadResult(
816 RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
817 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
818 // / cancelled operation or success -> silent removal of progress notification
819 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
821 // Show the result: success or fail notification
822 if (!uploadResult
.isCancelled()) {
823 int tickerId
= (uploadResult
.isSuccess()) ? R
.string
.uploader_upload_succeeded_ticker
:
824 R
.string
.uploader_upload_failed_ticker
;
826 String content
= null
;
828 // check credentials error
829 boolean needsToUpdateCredentials
= (
830 uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
831 uploadResult
.isIdPRedirection()
833 tickerId
= (needsToUpdateCredentials
) ?
834 R
.string
.uploader_upload_failed_credentials_error
: tickerId
;
837 .setTicker(getString(tickerId
))
838 .setContentTitle(getString(tickerId
))
841 .setProgress(0, 0, false
);
843 content
= ErrorMessageAdapter
.getErrorCauseMessage(
844 uploadResult
, upload
, getResources()
847 if (needsToUpdateCredentials
) {
848 // let the user update credentials with one click
849 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
850 updateAccountCredentials
.putExtra(
851 AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount()
853 updateAccountCredentials
.putExtra(
854 AuthenticatorActivity
.EXTRA_ACTION
,
855 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
857 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
858 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
859 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
860 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
862 (int) System
.currentTimeMillis(),
863 updateAccountCredentials
,
864 PendingIntent
.FLAG_ONE_SHOT
867 mUploadClient
= null
;
868 // grant that future retries on the same account will get the fresh credentials
870 mNotificationBuilder
.setContentText(content
);
872 if (upload
.isInstant()) {
875 db
= new DbHandler(this.getBaseContext());
876 String message
= uploadResult
.getLogMessage() + " errorCode: " +
877 uploadResult
.getCode();
878 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
879 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
880 //message = getString(R.string.failed_upload_quota_exceeded_text);
881 if (db
.updateFileState(
882 upload
.getOriginalStoragePath(),
883 DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
886 upload
.getOriginalStoragePath(),
887 upload
.getAccount().name
,
900 mNotificationBuilder
.setContentText(content
);
901 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
903 if (uploadResult
.isSuccess()) {
905 DbHandler db
= new DbHandler(this.getBaseContext());
906 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
909 // remove success notification, with a delay of 2 seconds
910 NotificationDelayer
.cancelWithDelay(
911 mNotificationManager
,
912 R
.string
.uploader_upload_succeeded_ticker
,
920 * Sends a broadcast in order to the interested activities can update their
923 * @param upload Finished upload operation
924 * @param uploadResult Result of the upload operation
926 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
927 Intent end
= new Intent(getUploadFinishMessage());
928 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
933 if (upload
.wasRenamed()) {
934 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
936 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
937 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
938 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
939 sendStickyBroadcast(end
);
943 * Checks if content provider, using the content:// scheme, returns a file with mime-type
944 * 'application/pdf' but file has not extension
947 * @return true if is needed to add the pdf file extension to the file
949 private boolean isPdfFileFromContentProviderWithoutExtension(String localPath
, String mimeType
) {
950 return localPath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
) &&
951 mimeType
.equals(MIME_TYPE_PDF
) &&
952 !localPath
.endsWith(FILE_EXTENSION_PDF
);
956 * Remove uploads of an account
959 private void cancelUploadForAccount(String accountName
){
960 // this can be slow if there are many uploads :(
961 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
962 Log_OC
.d(TAG
, "Number of pending updloads= " + mPendingUploads
.size());
963 while (it
.hasNext()) {
964 String key
= it
.next();
965 Log_OC
.d(TAG
, "mPendingUploads CANCELLED " + key
);
966 if (key
.startsWith(accountName
)) {
967 synchronized (mPendingUploads
) {
968 mPendingUploads
.remove(key
);