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 int LOCAL_BEHAVIOUR_COPY
= 0;
104 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
105 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
106 public static final int LOCAL_BEHAVIOUR_REMOVE
= 3;
108 public static final int UPLOAD_SINGLE_FILE
= 0;
109 public static final int UPLOAD_MULTIPLE_FILES
= 1;
111 private static final String TAG
= FileUploader
.class.getSimpleName();
113 private Looper mServiceLooper
;
114 private ServiceHandler mServiceHandler
;
115 private IBinder mBinder
;
116 private OwnCloudClient mUploadClient
= null
;
117 private Account mLastAccount
= null
;
118 private FileDataStorageManager mStorageManager
;
120 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
=
121 new ConcurrentHashMap
<String
, UploadFileOperation
>();
122 private UploadFileOperation mCurrentUpload
= null
;
124 private NotificationManager mNotificationManager
;
125 private NotificationCompat
.Builder mNotificationBuilder
;
126 private int mLastPercent
;
128 private static final String MIME_TYPE_PDF
= "application/pdf";
129 private static final String FILE_EXTENSION_PDF
= ".pdf";
132 public static String
getUploadFinishMessage() {
133 return FileUploader
.class.getName() + UPLOAD_FINISH_MESSAGE
;
137 * Builds a key for mPendingUploads from the account and file to upload
139 * @param account Account where the file to upload is stored
140 * @param file File to upload
142 private String
buildRemoteName(Account account
, OCFile file
) {
143 return account
.name
+ file
.getRemotePath();
146 private String
buildRemoteName(Account account
, String remotePath
) {
147 return account
.name
+ remotePath
;
151 * Checks if an ownCloud server version should support chunked uploads.
153 * @param version OwnCloud version instance corresponding to an ownCloud
155 * @return 'True' if the ownCloud server with version supports chunked
158 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
159 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
163 * Service initialization
166 public void onCreate() {
168 Log_OC
.d(TAG
, "Creating service");
169 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
170 HandlerThread thread
= new HandlerThread("FileUploaderThread",
171 Process
.THREAD_PRIORITY_BACKGROUND
);
173 mServiceLooper
= thread
.getLooper();
174 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
175 mBinder
= new FileUploaderBinder();
177 // add AccountsUpdatedListener
178 AccountManager am
= AccountManager
.get(getApplicationContext());
179 am
.addOnAccountsUpdatedListener(this, null
, false
);
186 public void onDestroy() {
187 Log_OC
.v(TAG
, "Destroying service" );
189 mServiceHandler
= null
;
190 mServiceLooper
.quit();
191 mServiceLooper
= null
;
192 mNotificationManager
= null
;
194 // remove AccountsUpdatedListener
195 AccountManager am
= AccountManager
.get(getApplicationContext());
196 am
.removeOnAccountsUpdatedListener(this);
203 * Entry point to add one or several files to the queue of uploads.
205 * New uploads are added calling to startService(), resulting in a call to
206 * this method. This ensures the service will keep on working although the
207 * caller activity goes away.
210 public int onStartCommand(Intent intent
, int flags
, int startId
) {
211 Log_OC
.d(TAG
, "Starting command with id " + startId
);
213 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
214 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
215 Log_OC
.e(TAG
, "Not enough information provided in intent");
216 return Service
.START_NOT_STICKY
;
218 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
219 if (uploadType
== -1) {
220 Log_OC
.e(TAG
, "Incorrect upload type provided");
221 return Service
.START_NOT_STICKY
;
223 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
224 if (!AccountUtils
.exists(account
, getApplicationContext())) {
225 return Service
.START_NOT_STICKY
;
228 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
229 OCFile
[] files
= null
;
230 if (uploadType
== UPLOAD_SINGLE_FILE
) {
232 if (intent
.hasExtra(KEY_FILE
)) {
233 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
236 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
237 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
238 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
241 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
243 if (intent
.hasExtra(KEY_FILE
)) {
244 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
252 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
253 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
254 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
258 FileDataStorageManager storageManager
= new FileDataStorageManager(account
,
259 getContentResolver());
261 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
262 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
263 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
265 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
266 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
267 return Service
.START_NOT_STICKY
;
269 } else if (!intent
.hasExtra(KEY_FILE
)) {
270 if (localPaths
== null
) {
271 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
272 return Service
.START_NOT_STICKY
;
274 if (remotePaths
== null
) {
275 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
276 return Service
.START_NOT_STICKY
;
278 if (localPaths
.length
!= remotePaths
.length
) {
279 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
280 return Service
.START_NOT_STICKY
;
283 files
= new OCFile
[localPaths
.length
];
284 for (int i
= 0; i
< localPaths
.length
; i
++) {
285 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
],
286 ((mimeTypes
!= null
) ? mimeTypes
[i
] : null
), storageManager
);
287 if (files
[i
] == null
) {
288 // TODO @andomaex add failure Notification
289 return Service
.START_NOT_STICKY
;
294 OwnCloudVersion ocv
= AccountUtils
.getServerVersion(account
);
296 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
297 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
298 String uploadKey
= null
;
299 UploadFileOperation newUpload
= null
;
301 for (int i
= 0; i
< files
.length
; i
++) {
302 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
303 newUpload
= new UploadFileOperation(account
, files
[i
], chunked
, isInstant
,
304 forceOverwrite
, localAction
,
305 getApplicationContext());
307 newUpload
.setRemoteFolderToBeCreated();
309 // Grants that the file only upload once time
310 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
312 newUpload
.addDatatransferProgressListener(this);
313 newUpload
.addDatatransferProgressListener((FileUploaderBinder
)mBinder
);
314 requestedUploads
.add(uploadKey
);
317 } catch (IllegalArgumentException e
) {
318 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
319 return START_NOT_STICKY
;
321 } catch (IllegalStateException e
) {
322 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
323 return START_NOT_STICKY
;
325 } catch (Exception e
) {
326 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
327 return START_NOT_STICKY
;
331 if (requestedUploads
.size() > 0) {
332 Message msg
= mServiceHandler
.obtainMessage();
334 msg
.obj
= requestedUploads
;
335 mServiceHandler
.sendMessage(msg
);
337 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
338 return Service
.START_NOT_STICKY
;
342 * Provides a binder object that clients can use to perform operations on
343 * the queue of uploads, excepting the addition of new files.
345 * Implemented to perform cancellation, pause and resume of existing
349 public IBinder
onBind(Intent arg0
) {
354 * Called when ALL the bound clients were onbound.
357 public boolean onUnbind(Intent intent
) {
358 ((FileUploaderBinder
)mBinder
).clearListeners();
359 return false
; // not accepting rebinding (default behaviour)
363 public void onAccountsUpdated(Account
[] accounts
) {
364 // Review current upload, and cancel it if its account doen't exist
365 if (mCurrentUpload
!= null
&&
366 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
367 mCurrentUpload
.cancel();
369 // The rest of uploads are cancelled when they try to start
373 * Binder to let client components to perform operations on the queue of
376 * It provides by itself the available operations.
378 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
381 * Map of listeners that will be reported about progress of uploads from a
382 * {@link FileUploaderBinder} instance
384 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
=
385 new HashMap
<String
, OnDatatransferProgressListener
>();
388 * Cancels a pending or current upload of a remote file.
390 * @param account Owncloud account where the remote file will be stored.
391 * @param file A file in the queue of pending uploads
393 public void cancel(Account account
, OCFile file
) {
394 UploadFileOperation upload
;
395 synchronized (mPendingUploads
) {
396 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
398 if (upload
!= null
) {
404 * Cancels a pending or current upload for an account
406 * @param account Owncloud accountName where the remote file will be stored.
408 public void cancel(Account account
) {
409 Log_OC
.d(TAG
, "Account= " + account
.name
);
411 if (mCurrentUpload
!= null
) {
412 Log_OC
.d(TAG
, "Current Upload Account= " + mCurrentUpload
.getAccount().name
);
413 if (mCurrentUpload
.getAccount().name
.equals(account
.name
)) {
414 mCurrentUpload
.cancel();
417 // Cancel pending uploads
418 cancelUploadForAccount(account
.name
);
421 public void clearListeners() {
422 mBoundListeners
.clear();
426 * Returns True when the file described by 'file' is being uploaded to
427 * the ownCloud account 'account' or waiting for it
429 * If 'file' is a directory, returns 'true' if some of its descendant files
430 * is uploading or waiting to upload.
432 * @param account ownCloud account where the remote file will be stored.
433 * @param file A file that could be in the queue of pending uploads
435 public boolean isUploading(Account account
, OCFile file
) {
436 if (account
== null
|| file
== null
)
438 String targetKey
= buildRemoteName(account
, file
);
439 synchronized (mPendingUploads
) {
440 if (file
.isFolder()) {
441 // this can be slow if there are many uploads :(
442 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
443 boolean found
= false
;
444 while (it
.hasNext() && !found
) {
445 found
= it
.next().startsWith(targetKey
);
449 return (mPendingUploads
.containsKey(targetKey
));
456 * Adds a listener interested in the progress of the upload for a concrete file.
458 * @param listener Object to notify about progress of transfer.
459 * @param account ownCloud account holding the file of interest.
460 * @param file {@link OCFile} of interest for listener.
462 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
,
463 Account account
, OCFile file
) {
464 if (account
== null
|| file
== null
|| listener
== null
) return;
465 String targetKey
= buildRemoteName(account
, file
);
466 mBoundListeners
.put(targetKey
, listener
);
472 * Removes a listener interested in the progress of the upload for a concrete file.
474 * @param listener Object to notify about progress of transfer.
475 * @param account ownCloud account holding the file of interest.
476 * @param file {@link OCFile} of interest for listener.
478 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
,
479 Account account
, OCFile file
) {
480 if (account
== null
|| file
== null
|| listener
== null
) return;
481 String targetKey
= buildRemoteName(account
, file
);
482 if (mBoundListeners
.get(targetKey
) == listener
) {
483 mBoundListeners
.remove(targetKey
);
489 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
490 long totalToTransfer
, String fileName
) {
491 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
492 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
493 if (boundListener
!= null
) {
494 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
,
495 totalToTransfer
, fileName
);
500 * Review uploads and cancel it if its account doesn't exist
502 public void checkAccountOfCurrentUpload() {
503 if (mCurrentUpload
!= null
&&
504 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
505 mCurrentUpload
.cancel();
507 // The rest of uploads are cancelled when they try to start
512 * Upload worker. Performs the pending uploads in the order they were
515 * Created with the Looper of a new thread, started in
516 * {@link FileUploader#onCreate()}.
518 private static class ServiceHandler
extends Handler
{
519 // don't make it a final class, and don't remove the static ; lint will
520 // warn about a possible memory leak
521 FileUploader mService
;
523 public ServiceHandler(Looper looper
, FileUploader service
) {
526 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
531 public void handleMessage(Message msg
) {
532 @SuppressWarnings("unchecked")
533 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
534 if (msg
.obj
!= null
) {
535 Iterator
<String
> it
= requestedUploads
.iterator();
536 while (it
.hasNext()) {
537 mService
.uploadFile(it
.next());
540 Log_OC
.d(TAG
, "Stopping command after id " + msg
.arg1
);
541 mService
.stopSelf(msg
.arg1
);
546 * Core upload method: sends the file(s) to upload
548 * @param uploadKey Key to access the upload to perform, contained in
551 public void uploadFile(String uploadKey
) {
553 synchronized (mPendingUploads
) {
554 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
557 if (mCurrentUpload
!= null
) {
559 // Detect if the account exists
560 if (AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
561 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().name
+ " exists");
563 notifyUploadStart(mCurrentUpload
);
565 RemoteOperationResult uploadResult
= null
, grantResult
;
568 /// prepare client object to send requests to the ownCloud server
569 if (mUploadClient
== null
||
570 !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
571 mLastAccount
= mCurrentUpload
.getAccount();
573 new FileDataStorageManager(mLastAccount
, getContentResolver());
574 OwnCloudAccount ocAccount
= new OwnCloudAccount(mLastAccount
, this);
575 mUploadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
576 getClientFor(ocAccount
, this);
579 /// check the existence of the parent folder for the file to upload
580 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
581 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
582 remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
583 grantResult
= grantFolderExistence(remoteParentPath
);
585 /// perform the upload
586 if (grantResult
.isSuccess()) {
587 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
588 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
589 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
590 if (uploadResult
.isSuccess()) {
594 uploadResult
= grantResult
;
597 } catch (AccountsException e
) {
598 Log_OC
.e(TAG
, "Error while trying to get autorization for " +
599 mLastAccount
.name
, e
);
600 uploadResult
= new RemoteOperationResult(e
);
602 } catch (IOException e
) {
603 Log_OC
.e(TAG
, "Error while trying to get autorization for " +
604 mLastAccount
.name
, e
);
605 uploadResult
= new RemoteOperationResult(e
);
608 synchronized (mPendingUploads
) {
609 mPendingUploads
.remove(uploadKey
);
610 Log_OC
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
612 if (uploadResult
!= null
&& uploadResult
.isException()) {
613 // enforce the creation of a new client object for next uploads;
614 // this grant that a new socket will be created in the future if
615 // the current exception is due to an abrupt lose of network connection
616 mUploadClient
= null
;
621 notifyUploadResult(uploadResult
, mCurrentUpload
);
622 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
625 // Cancel the transfer
626 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().toString() +
628 cancelUploadForAccount(mCurrentUpload
.getAccount().name
);
636 * Checks the existence of the folder where the current file will be uploaded both
637 * in the remote server and in the local database.
639 * If the upload is set to enforce the creation of the folder, the method tries to
640 * create it both remote and locally.
642 * @param pathToGrant Full remote path whose existence will be granted.
643 * @return An {@link OCFile} instance corresponding to the folder where the file
646 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
647 RemoteOperation operation
= new ExistenceCheckRemoteOperation(pathToGrant
, this, false
);
648 RemoteOperationResult result
= operation
.execute(mUploadClient
);
649 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&&
650 mCurrentUpload
.isRemoteFolderToBeCreated()) {
651 SyncOperation syncOp
= new CreateFolderOperation( pathToGrant
, true
);
652 result
= syncOp
.execute(mUploadClient
, mStorageManager
);
654 if (result
.isSuccess()) {
655 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
656 if (parentDir
== null
) {
657 parentDir
= createLocalFolder(pathToGrant
);
659 if (parentDir
!= null
) {
660 result
= new RemoteOperationResult(ResultCode
.OK
);
662 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
669 private OCFile
createLocalFolder(String remotePath
) {
670 String parentPath
= new File(remotePath
).getParent();
671 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
672 parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
673 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
674 if (parent
== null
) {
675 parent
= createLocalFolder(parentPath
);
677 if (parent
!= null
) {
678 OCFile createdFolder
= new OCFile(remotePath
);
679 createdFolder
.setMimetype("DIR");
680 createdFolder
.setParentId(parent
.getFileId());
681 mStorageManager
.saveFile(createdFolder
);
682 return createdFolder
;
689 * Saves a OC File after a successful upload.
691 * A PROPFIND is necessary to keep the props in the local database
692 * synchronized with the server, specially the modification time and Etag
695 * TODO refactor this ugly thing
697 private void saveUploadedFile() {
698 OCFile file
= mCurrentUpload
.getFile();
699 if (file
.fileExists()) {
700 file
= mStorageManager
.getFileById(file
.getFileId());
702 long syncDate
= System
.currentTimeMillis();
703 file
.setLastSyncDateForData(syncDate
);
705 // new PROPFIND to keep data consistent with server
706 // in theory, should return the same we already have
707 ReadRemoteFileOperation operation
=
708 new ReadRemoteFileOperation(mCurrentUpload
.getRemotePath());
709 RemoteOperationResult result
= operation
.execute(mUploadClient
);
710 if (result
.isSuccess()) {
711 updateOCFile(file
, (RemoteFile
) result
.getData().get(0));
712 file
.setLastSyncDateForProperties(syncDate
);
715 // / maybe this would be better as part of UploadFileOperation... or
716 // maybe all this method
717 if (mCurrentUpload
.wasRenamed()) {
718 OCFile oldFile
= mCurrentUpload
.getOldFile();
719 if (oldFile
.fileExists()) {
720 oldFile
.setStoragePath(null
);
721 mStorageManager
.saveFile(oldFile
);
723 } // else: it was just an automatic renaming due to a name
724 // coincidence; nothing else is needed, the storagePath is right
725 // in the instance returned by mCurrentUpload.getFile()
727 file
.setNeedsUpdateThumbnail(true
);
728 mStorageManager
.saveFile(file
);
731 private void updateOCFile(OCFile file
, RemoteFile remoteFile
) {
732 file
.setCreationTimestamp(remoteFile
.getCreationTimestamp());
733 file
.setFileLength(remoteFile
.getLength());
734 file
.setMimetype(remoteFile
.getMimeType());
735 file
.setModificationTimestamp(remoteFile
.getModifiedTimestamp());
736 file
.setModificationTimestampAtLastSyncForData(remoteFile
.getModifiedTimestamp());
737 // file.setEtag(remoteFile.getEtag()); // TODO Etag, where available
738 file
.setRemoteId(remoteFile
.getRemoteId());
741 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
742 FileDataStorageManager storageManager
) {
745 if (mimeType
== null
|| mimeType
.length() <= 0) {
747 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
748 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
749 } catch (IndexOutOfBoundsException e
) {
750 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " +
754 if (mimeType
== null
) {
755 mimeType
= "application/octet-stream";
758 if (isPdfFileFromContentProviderWithoutExtension(localPath
, mimeType
)){
759 remotePath
+= FILE_EXTENSION_PDF
;
762 OCFile newFile
= new OCFile(remotePath
);
763 newFile
.setStoragePath(localPath
);
764 newFile
.setLastSyncDateForProperties(0);
765 newFile
.setLastSyncDateForData(0);
768 if (localPath
!= null
&& localPath
.length() > 0) {
769 File localFile
= new File(localPath
);
770 newFile
.setFileLength(localFile
.length());
771 newFile
.setLastSyncDateForData(localFile
.lastModified());
772 } // don't worry about not assigning size, the problems with localPath
773 // are checked when the UploadFileOperation instance is created
776 newFile
.setMimetype(mimeType
);
782 * Creates a status notification to show the upload progress
784 * @param upload Upload operation starting.
786 private void notifyUploadStart(UploadFileOperation upload
) {
787 // / create status notification with a progress bar
789 mNotificationBuilder
=
790 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
793 .setSmallIcon(R
.drawable
.notification_icon
)
794 .setTicker(getString(R
.string
.uploader_upload_in_progress_ticker
))
795 .setContentTitle(getString(R
.string
.uploader_upload_in_progress_ticker
))
796 .setProgress(100, 0, false
)
798 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
800 /// includes a pending intent in the notification showing the details view of the file
801 Intent showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
802 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
803 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
804 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
805 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
806 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
809 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
813 * Callback method to update the progress bar in the status notification
816 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
817 long totalToTransfer
, String filePath
) {
818 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
819 if (percent
!= mLastPercent
) {
820 mNotificationBuilder
.setProgress(100, percent
, false
);
821 String fileName
= filePath
.substring(
822 filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
823 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
824 mNotificationBuilder
.setContentText(text
);
825 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
827 mLastPercent
= percent
;
831 * Updates the status notification with the result of an upload operation.
833 * @param uploadResult Result of the upload operation.
834 * @param upload Finished upload operation
836 private void notifyUploadResult(
837 RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
838 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
839 // / cancelled operation or success -> silent removal of progress notification
840 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
842 // Show the result: success or fail notification
843 if (!uploadResult
.isCancelled()) {
844 int tickerId
= (uploadResult
.isSuccess()) ? R
.string
.uploader_upload_succeeded_ticker
:
845 R
.string
.uploader_upload_failed_ticker
;
849 // check credentials error
850 boolean needsToUpdateCredentials
= (
851 uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
852 uploadResult
.isIdPRedirection()
854 tickerId
= (needsToUpdateCredentials
) ?
855 R
.string
.uploader_upload_failed_credentials_error
: tickerId
;
858 .setTicker(getString(tickerId
))
859 .setContentTitle(getString(tickerId
))
862 .setProgress(0, 0, false
);
864 content
= ErrorMessageAdapter
.getErrorCauseMessage(
865 uploadResult
, upload
, getResources()
868 if (needsToUpdateCredentials
) {
869 // let the user update credentials with one click
870 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
871 updateAccountCredentials
.putExtra(
872 AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount()
874 updateAccountCredentials
.putExtra(
875 AuthenticatorActivity
.EXTRA_ACTION
,
876 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
878 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
879 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
880 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
881 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
883 (int) System
.currentTimeMillis(),
884 updateAccountCredentials
,
885 PendingIntent
.FLAG_ONE_SHOT
888 mUploadClient
= null
;
889 // grant that future retries on the same account will get the fresh credentials
891 mNotificationBuilder
.setContentText(content
);
893 if (upload
.isInstant()) {
896 db
= new DbHandler(this.getBaseContext());
897 String message
= uploadResult
.getLogMessage() + " errorCode: " +
898 uploadResult
.getCode();
899 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
900 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
901 //message = getString(R.string.failed_upload_quota_exceeded_text);
902 if (db
.updateFileState(
903 upload
.getOriginalStoragePath(),
904 DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
907 upload
.getOriginalStoragePath(),
908 upload
.getAccount().name
,
921 mNotificationBuilder
.setContentText(content
);
922 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
924 if (uploadResult
.isSuccess()) {
926 DbHandler db
= new DbHandler(this.getBaseContext());
927 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
930 // remove success notification, with a delay of 2 seconds
931 NotificationDelayer
.cancelWithDelay(
932 mNotificationManager
,
933 R
.string
.uploader_upload_succeeded_ticker
,
941 * Sends a broadcast in order to the interested activities can update their
944 * @param upload Finished upload operation
945 * @param uploadResult Result of the upload operation
947 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
948 Intent end
= new Intent(getUploadFinishMessage());
949 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
954 if (upload
.wasRenamed()) {
955 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
957 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
958 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
959 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
960 sendStickyBroadcast(end
);
964 * Checks if content provider, using the content:// scheme, returns a file with mime-type
965 * 'application/pdf' but file has not extension
966 * @param localPath Full path to a file in the local file system.
967 * @param mimeType MIME type of the file.
968 * @return true if is needed to add the pdf file extension to the file
970 private boolean isPdfFileFromContentProviderWithoutExtension(String localPath
,
972 return localPath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
) &&
973 mimeType
.equals(MIME_TYPE_PDF
) &&
974 !localPath
.endsWith(FILE_EXTENSION_PDF
);
978 * Remove uploads of an account
979 * @param accountName Name of an OC account
981 private void cancelUploadForAccount(String accountName
){
982 // this can be slow if there are many uploads :(
983 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
984 Log_OC
.d(TAG
, "Number of pending updloads= " + mPendingUploads
.size());
985 while (it
.hasNext()) {
986 String key
= it
.next();
987 Log_OC
.d(TAG
, "mPendingUploads CANCELLED " + key
);
988 if (key
.startsWith(accountName
)) {
989 synchronized (mPendingUploads
) {
990 mPendingUploads
.remove(key
);