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;
107 public static final int UPLOAD_SINGLE_FILE
= 0;
108 public static final int UPLOAD_MULTIPLE_FILES
= 1;
110 private static final String TAG
= FileUploader
.class.getSimpleName();
112 private Looper mServiceLooper
;
113 private ServiceHandler mServiceHandler
;
114 private IBinder mBinder
;
115 private OwnCloudClient mUploadClient
= null
;
116 private Account mLastAccount
= null
;
117 private FileDataStorageManager mStorageManager
;
119 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
=
120 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() + 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",
170 Process
.THREAD_PRIORITY_BACKGROUND
);
172 mServiceLooper
= thread
.getLooper();
173 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
174 mBinder
= new FileUploaderBinder();
176 // add AccountsUpdatedListener
177 AccountManager am
= AccountManager
.get(getApplicationContext());
178 am
.addOnAccountsUpdatedListener(this, null
, false
);
185 public void onDestroy() {
186 Log_OC
.v(TAG
, "Destroying service" );
188 mServiceHandler
= null
;
189 mServiceLooper
.quit();
190 mServiceLooper
= null
;
191 mNotificationManager
= null
;
193 // remove AccountsUpdatedListener
194 AccountManager am
= AccountManager
.get(getApplicationContext());
195 am
.removeOnAccountsUpdatedListener(this);
202 * Entry point to add one or several files to the queue of uploads.
204 * New uploads are added calling to startService(), resulting in a call to
205 * this method. This ensures the service will keep on working although the
206 * caller activity goes away.
209 public int onStartCommand(Intent intent
, int flags
, int startId
) {
210 Log_OC
.d(TAG
, "Starting command with id " + startId
);
212 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
213 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
214 Log_OC
.e(TAG
, "Not enough information provided in intent");
215 return Service
.START_NOT_STICKY
;
217 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
218 if (uploadType
== -1) {
219 Log_OC
.e(TAG
, "Incorrect upload type provided");
220 return Service
.START_NOT_STICKY
;
222 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
223 if (!AccountUtils
.exists(account
, getApplicationContext())) {
224 return Service
.START_NOT_STICKY
;
227 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
228 OCFile
[] files
= null
;
229 if (uploadType
== UPLOAD_SINGLE_FILE
) {
231 if (intent
.hasExtra(KEY_FILE
)) {
232 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
235 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
236 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
237 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
240 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
242 if (intent
.hasExtra(KEY_FILE
)) {
243 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
251 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
252 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
253 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
257 FileDataStorageManager storageManager
= new FileDataStorageManager(account
,
258 getContentResolver());
260 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
261 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
262 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
264 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
265 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
266 return Service
.START_NOT_STICKY
;
268 } else if (!intent
.hasExtra(KEY_FILE
)) {
269 if (localPaths
== null
) {
270 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
271 return Service
.START_NOT_STICKY
;
273 if (remotePaths
== null
) {
274 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
275 return Service
.START_NOT_STICKY
;
277 if (localPaths
.length
!= remotePaths
.length
) {
278 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
279 return Service
.START_NOT_STICKY
;
282 files
= new OCFile
[localPaths
.length
];
283 for (int i
= 0; i
< localPaths
.length
; i
++) {
284 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
],
285 ((mimeTypes
!= null
) ? mimeTypes
[i
] : null
), storageManager
);
286 if (files
[i
] == null
) {
287 // TODO @andomaex add failure Notification
288 return Service
.START_NOT_STICKY
;
293 OwnCloudVersion ocv
= AccountUtils
.getServerVersion(account
);
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
,
303 forceOverwrite
, localAction
,
304 getApplicationContext());
306 newUpload
.setRemoteFolderToBeCreated();
308 // Grants that the file only upload once time
309 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
311 newUpload
.addDatatransferProgressListener(this);
312 newUpload
.addDatatransferProgressListener((FileUploaderBinder
)mBinder
);
313 requestedUploads
.add(uploadKey
);
316 } catch (IllegalArgumentException e
) {
317 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
318 return START_NOT_STICKY
;
320 } catch (IllegalStateException e
) {
321 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
322 return START_NOT_STICKY
;
324 } catch (Exception e
) {
325 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
326 return START_NOT_STICKY
;
330 if (requestedUploads
.size() > 0) {
331 Message msg
= mServiceHandler
.obtainMessage();
333 msg
.obj
= requestedUploads
;
334 mServiceHandler
.sendMessage(msg
);
336 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
337 return Service
.START_NOT_STICKY
;
341 * Provides a binder object that clients can use to perform operations on
342 * the queue of uploads, excepting the addition of new files.
344 * Implemented to perform cancellation, pause and resume of existing
348 public IBinder
onBind(Intent arg0
) {
353 * Called when ALL the bound clients were onbound.
356 public boolean onUnbind(Intent intent
) {
357 ((FileUploaderBinder
)mBinder
).clearListeners();
358 return false
; // not accepting rebinding (default behaviour)
362 public void onAccountsUpdated(Account
[] accounts
) {
363 // Review current upload, and cancel it if its account doen't exist
364 if (mCurrentUpload
!= null
&&
365 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
366 mCurrentUpload
.cancel();
368 // The rest of uploads are cancelled when they try to start
372 * Binder to let client components to perform operations on the queue of
375 * It provides by itself the available operations.
377 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
380 * Map of listeners that will be reported about progress of uploads from a
381 * {@link FileUploaderBinder} instance
383 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
=
384 new HashMap
<String
, OnDatatransferProgressListener
>();
387 * Cancels a pending or current upload of a remote file.
389 * @param account Owncloud account where the remote file will be stored.
390 * @param file A file in the queue of pending uploads
392 public void cancel(Account account
, OCFile file
) {
393 UploadFileOperation upload
;
394 synchronized (mPendingUploads
) {
395 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
397 if (upload
!= null
) {
403 * Cancels a pending or current upload for an account
405 * @param account Owncloud accountName where the remote file will be stored.
407 public void cancel(Account account
) {
408 Log_OC
.d(TAG
, "Account= " + account
.name
);
410 if (mCurrentUpload
!= null
) {
411 Log_OC
.d(TAG
, "Current Upload Account= " + mCurrentUpload
.getAccount().name
);
412 if (mCurrentUpload
.getAccount().name
.equals(account
.name
)) {
413 mCurrentUpload
.cancel();
416 // Cancel pending uploads
417 cancelUploadForAccount(account
.name
);
420 public void clearListeners() {
421 mBoundListeners
.clear();
425 * Returns True when the file described by 'file' is being uploaded to
426 * the ownCloud account 'account' or waiting for it
428 * If 'file' is a directory, returns 'true' if some of its descendant files
429 * is uploading or waiting to upload.
431 * @param account ownCloud account where the remote file will be stored.
432 * @param file A file that could be in the queue of pending uploads
434 public boolean isUploading(Account account
, OCFile file
) {
435 if (account
== null
|| file
== null
)
437 String targetKey
= buildRemoteName(account
, file
);
438 synchronized (mPendingUploads
) {
439 if (file
.isFolder()) {
440 // this can be slow if there are many uploads :(
441 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
442 boolean found
= false
;
443 while (it
.hasNext() && !found
) {
444 found
= it
.next().startsWith(targetKey
);
448 return (mPendingUploads
.containsKey(targetKey
));
455 * Adds a listener interested in the progress of the upload for a concrete file.
457 * @param listener Object to notify about progress of transfer.
458 * @param account ownCloud account holding the file of interest.
459 * @param file {@link OCFile} of interest for listener.
461 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
,
462 Account account
, OCFile file
) {
463 if (account
== null
|| file
== null
|| listener
== null
) return;
464 String targetKey
= buildRemoteName(account
, file
);
465 mBoundListeners
.put(targetKey
, listener
);
471 * Removes a listener interested in the progress of the upload for a concrete file.
473 * @param listener Object to notify about progress of transfer.
474 * @param account ownCloud account holding the file of interest.
475 * @param file {@link OCFile} of interest for listener.
477 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
,
478 Account account
, OCFile file
) {
479 if (account
== null
|| file
== null
|| listener
== null
) return;
480 String targetKey
= buildRemoteName(account
, file
);
481 if (mBoundListeners
.get(targetKey
) == listener
) {
482 mBoundListeners
.remove(targetKey
);
488 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
489 long totalToTransfer
, String fileName
) {
490 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
491 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
492 if (boundListener
!= null
) {
493 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
,
494 totalToTransfer
, fileName
);
499 * Review uploads and cancel it if its account doesn't exist
501 public void checkAccountOfCurrentUpload() {
502 if (mCurrentUpload
!= null
&&
503 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
504 mCurrentUpload
.cancel();
506 // The rest of uploads are cancelled when they try to start
511 * Upload worker. Performs the pending uploads in the order they were
514 * Created with the Looper of a new thread, started in
515 * {@link FileUploader#onCreate()}.
517 private static class ServiceHandler
extends Handler
{
518 // don't make it a final class, and don't remove the static ; lint will
519 // warn about a possible memory leak
520 FileUploader mService
;
522 public ServiceHandler(Looper looper
, FileUploader service
) {
525 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
530 public void handleMessage(Message msg
) {
531 @SuppressWarnings("unchecked")
532 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
533 if (msg
.obj
!= null
) {
534 Iterator
<String
> it
= requestedUploads
.iterator();
535 while (it
.hasNext()) {
536 mService
.uploadFile(it
.next());
539 Log_OC
.d(TAG
, "Stopping command after id " + msg
.arg1
);
540 mService
.stopSelf(msg
.arg1
);
545 * Core upload method: sends the file(s) to upload
547 * @param uploadKey Key to access the upload to perform, contained in
550 public void uploadFile(String uploadKey
) {
552 synchronized (mPendingUploads
) {
553 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
556 if (mCurrentUpload
!= null
) {
558 // Detect if the account exists
559 if (AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
560 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().name
+ " exists");
562 notifyUploadStart(mCurrentUpload
);
564 RemoteOperationResult uploadResult
= null
, grantResult
;
567 /// prepare client object to send requests to the ownCloud server
568 if (mUploadClient
== null
||
569 !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
570 mLastAccount
= mCurrentUpload
.getAccount();
572 new FileDataStorageManager(mLastAccount
, getContentResolver());
573 OwnCloudAccount ocAccount
= new OwnCloudAccount(mLastAccount
, this);
574 mUploadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
575 getClientFor(ocAccount
, this);
578 /// check the existence of the parent folder for the file to upload
579 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
580 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
581 remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
582 grantResult
= grantFolderExistence(remoteParentPath
);
584 /// perform the upload
585 if (grantResult
.isSuccess()) {
586 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
587 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
588 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
589 if (uploadResult
.isSuccess()) {
593 uploadResult
= grantResult
;
596 } catch (AccountsException e
) {
597 Log_OC
.e(TAG
, "Error while trying to get autorization for " +
598 mLastAccount
.name
, e
);
599 uploadResult
= new RemoteOperationResult(e
);
601 } catch (IOException e
) {
602 Log_OC
.e(TAG
, "Error while trying to get autorization for " +
603 mLastAccount
.name
, e
);
604 uploadResult
= new RemoteOperationResult(e
);
607 synchronized (mPendingUploads
) {
608 mPendingUploads
.remove(uploadKey
);
609 Log_OC
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
611 if (uploadResult
!= null
&& uploadResult
.isException()) {
612 // enforce the creation of a new client object for next uploads;
613 // this grant that a new socket will be created in the future if
614 // the current exception is due to an abrupt lose of network connection
615 mUploadClient
= null
;
620 notifyUploadResult(uploadResult
, mCurrentUpload
);
621 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
624 // Cancel the transfer
625 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().toString() +
627 cancelUploadForAccount(mCurrentUpload
.getAccount().name
);
635 * Checks the existence of the folder where the current file will be uploaded both
636 * in the remote server and in the local database.
638 * If the upload is set to enforce the creation of the folder, the method tries to
639 * create it both remote and locally.
641 * @param pathToGrant Full remote path whose existence will be granted.
642 * @return An {@link OCFile} instance corresponding to the folder where the file
645 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
646 RemoteOperation operation
= new ExistenceCheckRemoteOperation(pathToGrant
, this, false
);
647 RemoteOperationResult result
= operation
.execute(mUploadClient
);
648 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&&
649 mCurrentUpload
.isRemoteFolderToBeCreated()) {
650 SyncOperation syncOp
= new CreateFolderOperation( pathToGrant
, true
);
651 result
= syncOp
.execute(mUploadClient
, mStorageManager
);
653 if (result
.isSuccess()) {
654 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
655 if (parentDir
== null
) {
656 parentDir
= createLocalFolder(pathToGrant
);
658 if (parentDir
!= null
) {
659 result
= new RemoteOperationResult(ResultCode
.OK
);
661 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
668 private OCFile
createLocalFolder(String remotePath
) {
669 String parentPath
= new File(remotePath
).getParent();
670 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
671 parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
672 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
673 if (parent
== null
) {
674 parent
= createLocalFolder(parentPath
);
676 if (parent
!= null
) {
677 OCFile createdFolder
= new OCFile(remotePath
);
678 createdFolder
.setMimetype("DIR");
679 createdFolder
.setParentId(parent
.getFileId());
680 mStorageManager
.saveFile(createdFolder
);
681 return createdFolder
;
688 * Saves a OC File after a successful upload.
690 * A PROPFIND is necessary to keep the props in the local database
691 * synchronized with the server, specially the modification time and Etag
694 * TODO refactor this ugly thing
696 private void saveUploadedFile() {
697 OCFile file
= mCurrentUpload
.getFile();
698 if (file
.fileExists()) {
699 file
= mStorageManager
.getFileById(file
.getFileId());
701 long syncDate
= System
.currentTimeMillis();
702 file
.setLastSyncDateForData(syncDate
);
704 // new PROPFIND to keep data consistent with server
705 // in theory, should return the same we already have
706 ReadRemoteFileOperation operation
=
707 new ReadRemoteFileOperation(mCurrentUpload
.getRemotePath());
708 RemoteOperationResult result
= operation
.execute(mUploadClient
);
709 if (result
.isSuccess()) {
710 updateOCFile(file
, (RemoteFile
) result
.getData().get(0));
711 file
.setLastSyncDateForProperties(syncDate
);
714 // / maybe this would be better as part of UploadFileOperation... or
715 // maybe all this method
716 if (mCurrentUpload
.wasRenamed()) {
717 OCFile oldFile
= mCurrentUpload
.getOldFile();
718 if (oldFile
.fileExists()) {
719 oldFile
.setStoragePath(null
);
720 mStorageManager
.saveFile(oldFile
);
722 } // else: it was just an automatic renaming due to a name
723 // coincidence; nothing else is needed, the storagePath is right
724 // in the instance returned by mCurrentUpload.getFile()
726 file
.setNeedsUpdateThumbnail(true
);
727 mStorageManager
.saveFile(file
);
730 private void updateOCFile(OCFile file
, RemoteFile remoteFile
) {
731 file
.setCreationTimestamp(remoteFile
.getCreationTimestamp());
732 file
.setFileLength(remoteFile
.getLength());
733 file
.setMimetype(remoteFile
.getMimeType());
734 file
.setModificationTimestamp(remoteFile
.getModifiedTimestamp());
735 file
.setModificationTimestampAtLastSyncForData(remoteFile
.getModifiedTimestamp());
736 // file.setEtag(remoteFile.getEtag()); // TODO Etag, where available
737 file
.setRemoteId(remoteFile
.getRemoteId());
740 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
741 FileDataStorageManager storageManager
) {
744 if (mimeType
== null
|| mimeType
.length() <= 0) {
746 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
747 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
748 } catch (IndexOutOfBoundsException e
) {
749 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " +
753 if (mimeType
== null
) {
754 mimeType
= "application/octet-stream";
757 if (isPdfFileFromContentProviderWithoutExtension(localPath
, mimeType
)){
758 remotePath
+= FILE_EXTENSION_PDF
;
761 OCFile newFile
= new OCFile(remotePath
);
762 newFile
.setStoragePath(localPath
);
763 newFile
.setLastSyncDateForProperties(0);
764 newFile
.setLastSyncDateForData(0);
767 if (localPath
!= null
&& localPath
.length() > 0) {
768 File localFile
= new File(localPath
);
769 newFile
.setFileLength(localFile
.length());
770 newFile
.setLastSyncDateForData(localFile
.lastModified());
771 } // don't worry about not assigning size, the problems with localPath
772 // are checked when the UploadFileOperation instance is created
775 newFile
.setMimetype(mimeType
);
781 * Creates a status notification to show the upload progress
783 * @param upload Upload operation starting.
785 private void notifyUploadStart(UploadFileOperation upload
) {
786 // / create status notification with a progress bar
788 mNotificationBuilder
=
789 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
792 .setSmallIcon(R
.drawable
.notification_icon
)
793 .setTicker(getString(R
.string
.uploader_upload_in_progress_ticker
))
794 .setContentTitle(getString(R
.string
.uploader_upload_in_progress_ticker
))
795 .setProgress(100, 0, false
)
797 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
799 /// includes a pending intent in the notification showing the details view of the file
800 Intent showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
801 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
802 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
803 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
804 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
805 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
808 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
812 * Callback method to update the progress bar in the status notification
815 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
816 long totalToTransfer
, String filePath
) {
817 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
818 if (percent
!= mLastPercent
) {
819 mNotificationBuilder
.setProgress(100, percent
, false
);
820 String fileName
= filePath
.substring(
821 filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
822 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
823 mNotificationBuilder
.setContentText(text
);
824 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
826 mLastPercent
= percent
;
830 * Updates the status notification with the result of an upload operation.
832 * @param uploadResult Result of the upload operation.
833 * @param upload Finished upload operation
835 private void notifyUploadResult(
836 RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
837 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
838 // / cancelled operation or success -> silent removal of progress notification
839 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
841 // Show the result: success or fail notification
842 if (!uploadResult
.isCancelled()) {
843 int tickerId
= (uploadResult
.isSuccess()) ? R
.string
.uploader_upload_succeeded_ticker
:
844 R
.string
.uploader_upload_failed_ticker
;
848 // check credentials error
849 boolean needsToUpdateCredentials
= (
850 uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
851 uploadResult
.isIdPRedirection()
853 tickerId
= (needsToUpdateCredentials
) ?
854 R
.string
.uploader_upload_failed_credentials_error
: tickerId
;
857 .setTicker(getString(tickerId
))
858 .setContentTitle(getString(tickerId
))
861 .setProgress(0, 0, false
);
863 content
= ErrorMessageAdapter
.getErrorCauseMessage(
864 uploadResult
, upload
, getResources()
867 if (needsToUpdateCredentials
) {
868 // let the user update credentials with one click
869 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
870 updateAccountCredentials
.putExtra(
871 AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount()
873 updateAccountCredentials
.putExtra(
874 AuthenticatorActivity
.EXTRA_ACTION
,
875 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
877 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
878 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
879 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
880 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
882 (int) System
.currentTimeMillis(),
883 updateAccountCredentials
,
884 PendingIntent
.FLAG_ONE_SHOT
887 mUploadClient
= null
;
888 // grant that future retries on the same account will get the fresh credentials
890 mNotificationBuilder
.setContentText(content
);
892 if (upload
.isInstant()) {
895 db
= new DbHandler(this.getBaseContext());
896 String message
= uploadResult
.getLogMessage() + " errorCode: " +
897 uploadResult
.getCode();
898 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
899 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
900 //message = getString(R.string.failed_upload_quota_exceeded_text);
901 if (db
.updateFileState(
902 upload
.getOriginalStoragePath(),
903 DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
906 upload
.getOriginalStoragePath(),
907 upload
.getAccount().name
,
920 mNotificationBuilder
.setContentText(content
);
921 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
923 if (uploadResult
.isSuccess()) {
925 DbHandler db
= new DbHandler(this.getBaseContext());
926 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
929 // remove success notification, with a delay of 2 seconds
930 NotificationDelayer
.cancelWithDelay(
931 mNotificationManager
,
932 R
.string
.uploader_upload_succeeded_ticker
,
940 * Sends a broadcast in order to the interested activities can update their
943 * @param upload Finished upload operation
944 * @param uploadResult Result of the upload operation
946 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
947 Intent end
= new Intent(getUploadFinishMessage());
948 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
953 if (upload
.wasRenamed()) {
954 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
956 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
957 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
958 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
959 sendStickyBroadcast(end
);
963 * Checks if content provider, using the content:// scheme, returns a file with mime-type
964 * 'application/pdf' but file has not extension
965 * @param localPath Full path to a file in the local file system.
966 * @param mimeType MIME type of the file.
967 * @return true if is needed to add the pdf file extension to the file
969 private boolean isPdfFileFromContentProviderWithoutExtension(String localPath
,
971 return localPath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
) &&
972 mimeType
.equals(MIME_TYPE_PDF
) &&
973 !localPath
.endsWith(FILE_EXTENSION_PDF
);
977 * Remove uploads of an account
978 * @param accountName Name of an OC account
980 private void cancelUploadForAccount(String accountName
){
981 // this can be slow if there are many uploads :(
982 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
983 Log_OC
.d(TAG
, "Number of pending updloads= " + mPendingUploads
.size());
984 while (it
.hasNext()) {
985 String key
= it
.next();
986 Log_OC
.d(TAG
, "mPendingUploads CANCELLED " + key
);
987 if (key
.startsWith(accountName
)) {
988 synchronized (mPendingUploads
) {
989 mPendingUploads
.remove(key
);